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
.messageCache
.CachedMessage
;
38 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfile
;
39 import org
.asamk
.signal
.manager
.storage
.protocol
.IdentityInfo
;
40 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
41 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
42 import org
.asamk
.signal
.manager
.util
.IOUtils
;
43 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
44 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
45 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
46 import org
.asamk
.signal
.manager
.util
.Utils
;
47 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
48 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
49 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
50 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
51 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
52 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
53 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
54 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
56 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
57 import org
.signal
.libsignal
.metadata
.SelfSendException
;
58 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
59 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
60 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
61 import org
.signal
.zkgroup
.InvalidInputException
;
62 import org
.signal
.zkgroup
.VerificationFailedException
;
63 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
64 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
65 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
66 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
67 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
68 import org
.slf4j
.Logger
;
69 import org
.slf4j
.LoggerFactory
;
70 import org
.whispersystems
.libsignal
.IdentityKey
;
71 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
72 import org
.whispersystems
.libsignal
.InvalidKeyException
;
73 import org
.whispersystems
.libsignal
.InvalidMessageException
;
74 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
75 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
76 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
77 import org
.whispersystems
.libsignal
.util
.Pair
;
78 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
79 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
80 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
81 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
82 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
83 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
84 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
85 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
86 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
87 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
88 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
89 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
90 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
91 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
92 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
93 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
94 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
95 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
96 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
101 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
102 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
103 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
104 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
105 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
106 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
107 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
115 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
116 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
117 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
118 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
119 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
120 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
121 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
122 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
123 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
124 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
125 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
126 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
127 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
128 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
129 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
130 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
131 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
133 import java
.io
.Closeable
;
135 import java
.io
.FileInputStream
;
136 import java
.io
.FileOutputStream
;
137 import java
.io
.IOException
;
138 import java
.io
.InputStream
;
139 import java
.io
.OutputStream
;
141 import java
.net
.URISyntaxException
;
142 import java
.net
.URLEncoder
;
143 import java
.nio
.charset
.StandardCharsets
;
144 import java
.nio
.file
.Files
;
145 import java
.security
.SignatureException
;
146 import java
.util
.ArrayList
;
147 import java
.util
.Arrays
;
148 import java
.util
.Collection
;
149 import java
.util
.Date
;
150 import java
.util
.HashSet
;
151 import java
.util
.List
;
152 import java
.util
.Map
;
153 import java
.util
.Set
;
154 import java
.util
.UUID
;
155 import java
.util
.concurrent
.ExecutorService
;
156 import java
.util
.concurrent
.Executors
;
157 import java
.util
.concurrent
.TimeUnit
;
158 import java
.util
.concurrent
.TimeoutException
;
159 import java
.util
.function
.Function
;
160 import java
.util
.stream
.Collectors
;
162 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
164 public class Manager
implements Closeable
{
166 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
168 private final CertificateValidator certificateValidator
;
170 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
171 private final String userAgent
;
173 private SignalAccount account
;
174 private final SignalServiceAccountManager accountManager
;
175 private final GroupsV2Api groupsV2Api
;
176 private final GroupsV2Operations groupsV2Operations
;
177 private final SignalServiceMessageReceiver messageReceiver
;
178 private final ClientZkProfileOperations clientZkProfileOperations
;
180 private final ExecutorService executor
= Executors
.newCachedThreadPool();
182 private SignalServiceMessagePipe messagePipe
= null;
183 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
185 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
186 private final ProfileHelper profileHelper
;
187 private final GroupHelper groupHelper
;
188 private final PinHelper pinHelper
;
189 private final AvatarStore avatarStore
;
190 private final AttachmentStore attachmentStore
;
193 SignalAccount account
,
194 PathConfig pathConfig
,
195 ServiceEnvironmentConfig serviceEnvironmentConfig
,
198 this.account
= account
;
199 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
200 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
201 this.userAgent
= userAgent
;
202 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
203 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
204 final SleepTimer timer
= new UptimeSleepTimer();
205 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
206 new DynamicCredentialsProvider(account
.getUuid(),
207 account
.getUsername(),
208 account
.getPassword(),
209 account
.getDeviceId()),
212 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
214 this.groupsV2Api
= accountManager
.getGroupsV2Api();
215 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
216 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
217 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
218 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
221 this.pinHelper
= new PinHelper(keyBackupService
);
222 this.clientZkProfileOperations
= capabilities
.isGv2()
223 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
224 .getProfileOperations()
226 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
228 account
.getUsername(),
229 account
.getPassword(),
230 account
.getDeviceId(),
234 clientZkProfileOperations
,
235 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
237 this.account
.setResolver(this::resolveSignalServiceAddress
);
239 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
240 account
.getProfileStore()::getProfileKey
,
241 this::getRecipientProfile
,
242 this::getSenderCertificate
);
243 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
244 unidentifiedAccessHelper
::getAccessFor
,
245 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
246 () -> messageReceiver
);
247 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
248 this::getRecipientProfile
,
249 account
::getSelfAddress
,
252 this::getGroupAuthForToday
);
253 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
254 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
257 public String
getUsername() {
258 return account
.getUsername();
261 public SignalServiceAddress
getSelfAddress() {
262 return account
.getSelfAddress();
265 private IdentityKeyPair
getIdentityKeyPair() {
266 return account
.getIdentityKeyPair();
269 public int getDeviceId() {
270 return account
.getDeviceId();
273 public static Manager
init(
274 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
275 ) throws IOException
, NotRegisteredException
{
276 var pathConfig
= PathConfig
.createDefault(settingsPath
);
278 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
279 throw new NotRegisteredException();
282 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
284 if (!account
.isRegistered()) {
285 throw new NotRegisteredException();
288 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
290 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
293 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
294 var pathConfig
= PathConfig
.createDefault(settingsPath
);
295 final var dataPath
= pathConfig
.getDataPath();
296 final var files
= dataPath
.listFiles();
302 return Arrays
.stream(files
)
303 .filter(File
::isFile
)
305 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
306 .collect(Collectors
.toList());
309 public void checkAccountState() throws IOException
{
310 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
314 if (account
.getUuid() == null) {
315 account
.setUuid(accountManager
.getOwnUuid());
318 updateAccountAttributes();
322 * This is used for checking a set of phone numbers for registration on Signal
324 * @param numbers The set of phone number in question
325 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
326 * @throws IOException if its unable to get the contacts to check if they're registered
328 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
329 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
330 var contactDetails
= getRegisteredUsers(numbers
);
332 var registeredUsers
= contactDetails
.keySet();
334 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
337 public void updateAccountAttributes() throws IOException
{
338 accountManager
.setAccountAttributes(null,
339 account
.getLocalRegistrationId(),
341 // set legacy pin only if no KBS master key is set
342 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
343 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
344 account
.getSelfUnidentifiedAccessKey(),
345 account
.isUnrestrictedUnidentifiedAccess(),
347 account
.isDiscoverableByPhoneNumber());
351 * @param name if null, the previous name will be kept
352 * @param about if null, the previous about text will be kept
353 * @param aboutEmoji if null, the previous about emoji will be kept
354 * @param avatar if avatar is null the image from the local avatar store is used (if present),
355 * if it's Optional.absent(), the avatar will be removed
357 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
358 var profileEntry
= account
.getProfileStore().getProfileEntry(getSelfAddress());
359 var profile
= profileEntry
== null ?
null : profileEntry
.getProfile();
360 var newProfile
= new SignalProfile(profile
== null ?
null : profile
.getIdentityKey(),
361 name
!= null ? name
: profile
== null || profile
.getName() == null ?
"" : profile
.getName(),
362 about
!= null ? about
: profile
== null || profile
.getAbout() == null ?
"" : profile
.getAbout(),
365 : profile
== null || profile
.getAboutEmoji() == null ?
"" : profile
.getAboutEmoji(),
366 profile
== null ?
null : profile
.getUnidentifiedAccess(),
367 account
.isUnrestrictedUnidentifiedAccess(),
368 profile
== null ?
null : profile
.getCapabilities());
370 try (final var streamDetails
= avatar
== null
371 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
372 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
373 accountManager
.setVersionedProfile(account
.getUuid(),
374 account
.getProfileKey(),
375 newProfile
.getName(),
376 newProfile
.getAbout(),
377 newProfile
.getAboutEmoji(),
381 if (avatar
!= null) {
382 if (avatar
.isPresent()) {
383 avatarStore
.storeProfileAvatar(getSelfAddress(),
384 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
386 avatarStore
.deleteProfileAvatar(getSelfAddress());
389 account
.getProfileStore()
390 .updateProfile(getSelfAddress(),
391 account
.getProfileKey(),
392 System
.currentTimeMillis(),
394 profileEntry
== null ?
null : profileEntry
.getProfileKeyCredential());
397 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
398 } catch (UntrustedIdentityException ignored
) {
402 public void unregister() throws IOException
{
403 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
404 // If this is the master device, other users can't send messages to this number anymore.
405 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
406 accountManager
.setGcmId(Optional
.absent());
407 accountManager
.deleteAccount();
409 account
.setRegistered(false);
413 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
414 var devices
= accountManager
.getDevices();
415 account
.setMultiDevice(devices
.size() > 1);
420 public void removeLinkedDevices(int deviceId
) throws IOException
{
421 accountManager
.removeDevice(deviceId
);
422 var devices
= accountManager
.getDevices();
423 account
.setMultiDevice(devices
.size() > 1);
427 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
428 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
430 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
433 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
434 var identityKeyPair
= getIdentityKeyPair();
435 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
437 accountManager
.addDevice(deviceIdentifier
,
440 Optional
.of(account
.getProfileKey().serialize()),
442 account
.setMultiDevice(true);
446 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
447 if (!account
.isMasterDevice()) {
448 throw new RuntimeException("Only master device can set a PIN");
450 if (pin
.isPresent()) {
451 final var masterKey
= account
.getPinMasterKey() != null
452 ? account
.getPinMasterKey()
453 : KeyUtils
.createMasterKey();
455 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
457 account
.setRegistrationLockPin(pin
.get());
458 account
.setPinMasterKey(masterKey
);
460 // Remove legacy registration lock
461 accountManager
.removeRegistrationLockV1();
464 pinHelper
.removeRegistrationLockPin();
466 account
.setRegistrationLockPin(null);
467 account
.setPinMasterKey(null);
472 void refreshPreKeys() throws IOException
{
473 var oneTimePreKeys
= generatePreKeys();
474 final var identityKeyPair
= getIdentityKeyPair();
475 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
477 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
480 private List
<PreKeyRecord
> generatePreKeys() {
481 final var offset
= account
.getPreKeyIdOffset();
483 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
484 account
.addPreKeys(records
);
489 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
490 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
492 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
493 account
.addSignedPreKey(record);
498 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
499 if (messagePipe
== null) {
500 messagePipe
= messageReceiver
.createMessagePipe();
505 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
506 if (unidentifiedMessagePipe
== null) {
507 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
509 return unidentifiedMessagePipe
;
512 private SignalServiceMessageSender
createMessageSender() {
513 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
515 account
.getUsername(),
516 account
.getPassword(),
517 account
.getDeviceId(),
518 account
.getSignalProtocolStore(),
520 account
.isMultiDevice(),
521 Optional
.fromNullable(messagePipe
),
522 Optional
.fromNullable(unidentifiedMessagePipe
),
524 clientZkProfileOperations
,
526 ServiceConfig
.MAX_ENVELOPE_SIZE
,
527 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
530 public SignalProfile
getRecipientProfile(
531 SignalServiceAddress address
533 return getRecipientProfile(address
, false);
536 private SignalProfile
getRecipientProfile(
537 SignalServiceAddress address
, boolean force
539 var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
540 if (profileEntry
== null) {
543 var now
= new Date().getTime();
544 // Profiles are cached for 24h before retrieving them again
545 if (!profileEntry
.isRequestPending() && (
547 || profileEntry
.getProfile() == null
548 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
550 profileEntry
.setRequestPending(true);
551 final SignalServiceProfile encryptedProfile
;
553 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
555 } catch (IOException e
) {
556 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
559 profileEntry
.setRequestPending(false);
562 final var profileKey
= profileEntry
.getProfileKey();
563 final var profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
564 account
.getProfileStore()
565 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
568 return profileEntry
.getProfile();
571 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
572 var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
573 if (profileEntry
== null) {
576 if (profileEntry
.getProfileKeyCredential() == null) {
577 ProfileAndCredential profileAndCredential
;
579 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
580 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
581 } catch (IOException e
) {
582 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
586 var now
= new Date().getTime();
587 final var profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
588 final var profile
= decryptProfileAndDownloadAvatar(address
,
589 profileEntry
.getProfileKey(),
590 profileAndCredential
.getProfile());
591 account
.getProfileStore()
592 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
593 return profileKeyCredential
;
595 return profileEntry
.getProfileKeyCredential();
598 private SignalProfile
decryptProfileAndDownloadAvatar(
599 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
601 if (encryptedProfile
.getAvatar() != null) {
602 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
605 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
608 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
609 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
610 if (streamDetails
== null) {
611 return Optional
.absent();
614 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
617 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
618 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
619 if (streamDetails
== null) {
620 return Optional
.absent();
623 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
626 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
627 var g
= getGroup(groupId
);
629 throw new GroupNotFoundException(groupId
);
631 if (!g
.isMember(account
.getSelfAddress())) {
632 throw new NotAGroupMemberException(groupId
, g
.getTitle());
637 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
638 var g
= getGroup(groupId
);
640 throw new GroupNotFoundException(groupId
);
642 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
643 throw new NotAGroupMemberException(groupId
, g
.getTitle());
648 public List
<GroupInfo
> getGroups() {
649 return account
.getGroupStore().getGroups();
652 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
653 String messageText
, List
<String
> attachments
, GroupId groupId
654 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
655 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
656 if (attachments
!= null) {
657 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
660 return sendGroupMessage(messageBuilder
, groupId
);
663 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
664 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
665 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
666 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
668 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
669 targetSentTimestamp
);
670 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
672 return sendGroupMessage(messageBuilder
, groupId
);
675 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
676 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
677 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
678 final var g
= getGroupForSending(groupId
);
680 GroupUtils
.setGroupContext(messageBuilder
, g
);
681 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
683 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
686 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
687 SignalServiceDataMessage
.Builder messageBuilder
;
689 final var g
= getGroupForUpdating(groupId
);
690 if (g
instanceof GroupInfoV1
) {
691 var groupInfoV1
= (GroupInfoV1
) g
;
692 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
693 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
694 groupInfoV1
.removeMember(account
.getSelfAddress());
695 account
.getGroupStore().updateGroup(groupInfoV1
);
697 final var groupInfoV2
= (GroupInfoV2
) g
;
698 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
699 groupInfoV2
.setGroup(groupGroupChangePair
.first());
700 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
701 account
.getGroupStore().updateGroup(groupInfoV2
);
704 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
707 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
708 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
709 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
710 return sendUpdateGroupMessage(groupId
,
712 members
== null ?
null : getSignalServiceAddresses(members
),
716 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
717 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
718 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
720 SignalServiceDataMessage
.Builder messageBuilder
;
721 if (groupId
== null) {
723 var gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
724 members
== null ? List
.of() : members
,
727 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
728 gv1
.addMembers(List
.of(account
.getSelfAddress()));
729 updateGroupV1(gv1
, name
, members
, avatarFile
);
730 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
733 if (avatarFile
!= null) {
734 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
735 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
737 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
741 var group
= getGroupForUpdating(groupId
);
742 if (group
instanceof GroupInfoV2
) {
743 final var groupInfoV2
= (GroupInfoV2
) group
;
745 Pair
<Long
, List
<SendMessageResult
>> result
= null;
746 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
747 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
748 result
= sendUpdateGroupMessage(groupInfoV2
,
749 groupGroupChangePair
.first(),
750 groupGroupChangePair
.second());
753 if (members
!= null) {
754 final var newMembers
= new HashSet
<>(members
);
755 newMembers
.removeAll(group
.getMembers()
757 .map(this::resolveSignalServiceAddress
)
758 .collect(Collectors
.toSet()));
759 if (newMembers
.size() > 0) {
760 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
761 result
= sendUpdateGroupMessage(groupInfoV2
,
762 groupGroupChangePair
.first(),
763 groupGroupChangePair
.second());
766 if (result
== null || name
!= null || avatarFile
!= null) {
767 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
768 if (avatarFile
!= null) {
769 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
770 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
772 result
= sendUpdateGroupMessage(groupInfoV2
,
773 groupGroupChangePair
.first(),
774 groupGroupChangePair
.second());
777 return new Pair
<>(group
.getGroupId(), result
.second());
779 var gv1
= (GroupInfoV1
) group
;
780 updateGroupV1(gv1
, name
, members
, avatarFile
);
781 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
786 account
.getGroupStore().updateGroup(g
);
788 final var result
= sendMessage(messageBuilder
, g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
789 return new Pair
<>(g
.getGroupId(), result
.second());
792 private void updateGroupV1(
795 final Collection
<SignalServiceAddress
> members
,
796 final File avatarFile
797 ) throws IOException
{
802 if (members
!= null) {
803 final var newE164Members
= new HashSet
<String
>();
804 for (var member
: members
) {
805 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
808 newE164Members
.add(member
.getNumber().get());
811 final var registeredUsers
= getRegisteredUsers(newE164Members
);
812 if (registeredUsers
.size() != newE164Members
.size()) {
813 // Some of the new members are not registered on Signal
814 newE164Members
.removeAll(registeredUsers
.keySet());
815 throw new IOException("Failed to add members "
816 + String
.join(", ", newE164Members
)
817 + " to group: Not registered on Signal");
820 g
.addMembers(members
);
823 if (avatarFile
!= null) {
824 avatarStore
.storeGroupAvatar(g
.getGroupId(),
825 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
829 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
830 GroupInviteLinkUrl inviteLinkUrl
831 ) throws IOException
, GroupLinkNotActiveException
{
832 return sendJoinGroupMessage(inviteLinkUrl
);
835 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
836 GroupInviteLinkUrl inviteLinkUrl
837 ) throws IOException
, GroupLinkNotActiveException
{
838 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
839 inviteLinkUrl
.getPassword());
840 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
841 inviteLinkUrl
.getPassword(),
843 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
844 groupJoinInfo
.getRevision() + 1,
845 groupChange
.toByteArray());
847 if (group
.getGroup() == null) {
848 // Only requested member, can't send update to group members
849 return new Pair
<>(group
.getGroupId(), List
.of());
852 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
854 return new Pair
<>(group
.getGroupId(), result
.second());
857 private static int currentTimeDays() {
858 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
861 private GroupsV2AuthorizationString
getGroupAuthForToday(
862 final GroupSecretParams groupSecretParams
863 ) throws IOException
{
864 final var today
= currentTimeDays();
865 // Returns credentials for the next 7 days
866 final var credentials
= groupsV2Api
.getCredentials(today
);
867 // TODO cache credentials until they expire
868 var authCredentialResponse
= credentials
.get(today
);
870 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
873 authCredentialResponse
);
874 } catch (VerificationFailedException e
) {
875 throw new IOException(e
);
879 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
880 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
881 ) throws IOException
{
882 group
.setGroup(newDecryptedGroup
);
883 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
884 account
.getGroupStore().updateGroup(group
);
885 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
888 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
889 GroupIdV1 groupId
, SignalServiceAddress recipient
890 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
892 var group
= getGroupForSending(groupId
);
893 if (!(group
instanceof GroupInfoV1
)) {
894 throw new RuntimeException("Received an invalid group request for a v2 group!");
896 g
= (GroupInfoV1
) group
;
898 if (!g
.isMember(recipient
)) {
899 throw new NotAGroupMemberException(groupId
, g
.name
);
902 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
904 // Send group message only to the recipient who requested it
905 return sendMessage(messageBuilder
, List
.of(recipient
));
908 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
909 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
910 .withId(g
.getGroupId().serialize())
912 .withMembers(new ArrayList
<>(g
.getMembers()));
915 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
916 if (attachment
.isPresent()) {
917 group
.withAvatar(attachment
.get());
919 } catch (IOException e
) {
920 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
923 return SignalServiceDataMessage
.newBuilder()
924 .asGroupMessage(group
.build())
925 .withExpiration(g
.getMessageExpirationTime());
928 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
929 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
930 .withRevision(g
.getGroup().getRevision())
931 .withSignedGroupChange(signedGroupChange
);
932 return SignalServiceDataMessage
.newBuilder()
933 .asGroupMessage(group
.build())
934 .withExpiration(g
.getMessageExpirationTime());
937 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
938 GroupIdV1 groupId
, SignalServiceAddress recipient
939 ) throws IOException
{
940 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
942 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
944 // Send group info request message to the recipient who sent us a message with this groupId
945 return sendMessage(messageBuilder
, List
.of(recipient
));
949 SignalServiceAddress remoteAddress
, long messageId
950 ) throws IOException
, UntrustedIdentityException
{
951 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
953 System
.currentTimeMillis());
955 createMessageSender().sendReceipt(remoteAddress
,
956 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
960 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
961 String messageText
, List
<String
> attachments
, List
<String
> recipients
962 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
963 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
964 if (attachments
!= null) {
965 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
967 // Upload attachments here, so we only upload once even for multiple recipients
968 var messageSender
= createMessageSender();
969 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
970 for (var attachment
: attachmentStreams
) {
971 if (attachment
.isStream()) {
972 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
973 } else if (attachment
.isPointer()) {
974 attachmentPointers
.add(attachment
.asPointer());
978 messageBuilder
.withAttachments(attachmentPointers
);
980 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
983 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
984 String messageText
, List
<String
> attachments
985 ) throws IOException
, AttachmentInvalidException
{
986 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
987 if (attachments
!= null) {
988 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
990 return sendSelfMessage(messageBuilder
);
993 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
994 long targetSentTimestamp
, List
<String
> recipients
995 ) throws IOException
, InvalidNumberException
{
996 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
997 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
998 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1001 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1002 long targetSentTimestamp
, GroupId groupId
1003 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1004 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1005 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1006 return sendGroupMessage(messageBuilder
, groupId
);
1009 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1010 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1011 ) throws IOException
, InvalidNumberException
{
1012 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1014 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1015 targetSentTimestamp
);
1016 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1017 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1020 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1021 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1023 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1025 return sendMessage(messageBuilder
, signalServiceAddresses
);
1026 } catch (Exception e
) {
1027 for (var address
: signalServiceAddresses
) {
1028 handleEndSession(address
);
1035 public String
getContactName(String number
) throws InvalidNumberException
{
1036 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1037 if (contact
== null) {
1040 return contact
.name
;
1044 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1045 final var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1046 var contact
= account
.getContactStore().getContact(address
);
1047 if (contact
== null) {
1048 contact
= new ContactInfo(address
);
1050 contact
.name
= name
;
1051 account
.getContactStore().updateContact(contact
);
1055 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1056 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1059 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1060 var contact
= account
.getContactStore().getContact(address
);
1061 if (contact
== null) {
1062 contact
= new ContactInfo(address
);
1064 contact
.blocked
= blocked
;
1065 account
.getContactStore().updateContact(contact
);
1069 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1070 var group
= getGroup(groupId
);
1071 if (group
== null) {
1072 throw new GroupNotFoundException(groupId
);
1075 group
.setBlocked(blocked
);
1076 account
.getGroupStore().updateGroup(group
);
1081 * Change the expiration timer for a contact
1083 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1084 var contact
= account
.getContactStore().getContact(address
);
1085 contact
.messageExpirationTime
= messageExpirationTimer
;
1086 account
.getContactStore().updateContact(contact
);
1087 sendExpirationTimerUpdate(address
);
1091 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1092 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1093 sendMessage(messageBuilder
, List
.of(address
));
1097 * Change the expiration timer for a contact
1099 public void setExpirationTimer(
1100 String number
, int messageExpirationTimer
1101 ) throws IOException
, InvalidNumberException
{
1102 var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1103 setExpirationTimer(address
, messageExpirationTimer
);
1107 * Change the expiration timer for a group
1109 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1110 var g
= getGroup(groupId
);
1111 if (g
instanceof GroupInfoV1
) {
1112 var groupInfoV1
= (GroupInfoV1
) g
;
1113 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1114 account
.getGroupStore().updateGroup(groupInfoV1
);
1116 throw new RuntimeException("TODO Not implemented!");
1121 * Upload the sticker pack from path.
1123 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1124 * @return if successful, returns the URL to install the sticker pack in the signal app
1126 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1127 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1129 var messageSender
= createMessageSender();
1131 var packKey
= KeyUtils
.createStickerUploadKey();
1132 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1134 var sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1135 account
.getStickerStore().updateSticker(sticker
);
1139 return new URI("https",
1142 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1143 Hex
.toStringCondensed(packKey
),
1144 StandardCharsets
.UTF_8
)).toString();
1145 } catch (URISyntaxException e
) {
1146 throw new AssertionError(e
);
1150 void requestSyncGroups() throws IOException
{
1151 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1152 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1154 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1156 sendSyncMessage(message
);
1157 } catch (UntrustedIdentityException e
) {
1158 throw new AssertionError(e
);
1162 void requestSyncContacts() throws IOException
{
1163 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1164 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1166 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1168 sendSyncMessage(message
);
1169 } catch (UntrustedIdentityException e
) {
1170 throw new AssertionError(e
);
1174 void requestSyncBlocked() throws IOException
{
1175 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1176 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1178 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1180 sendSyncMessage(message
);
1181 } catch (UntrustedIdentityException e
) {
1182 throw new AssertionError(e
);
1186 void requestSyncConfiguration() throws IOException
{
1187 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1188 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1190 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1192 sendSyncMessage(message
);
1193 } catch (UntrustedIdentityException e
) {
1194 throw new AssertionError(e
);
1198 void requestSyncKeys() throws IOException
{
1199 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1200 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1202 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1204 sendSyncMessage(message
);
1205 } catch (UntrustedIdentityException e
) {
1206 throw new AssertionError(e
);
1210 private byte[] getSenderCertificate() {
1211 // TODO support UUID capable sender certificates
1212 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1215 certificate
= accountManager
.getSenderCertificate();
1216 } catch (IOException e
) {
1217 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1220 // TODO cache for a day
1224 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1225 var messageSender
= createMessageSender();
1227 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1228 } catch (UntrustedIdentityException e
) {
1229 if (e
.getIdentityKey() != null) {
1230 account
.getSignalProtocolStore()
1231 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1233 TrustLevel
.UNTRUSTED
);
1239 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1240 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1241 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1243 for (var number
: numbers
) {
1244 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1245 if (resolvedAddress
.getUuid().isPresent()) {
1246 signalServiceAddresses
.add(resolvedAddress
);
1248 addressesMissingUuid
.add(resolvedAddress
);
1252 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1253 .map(a
-> a
.getNumber().get())
1254 .collect(Collectors
.toSet());
1255 Map
<String
, UUID
> registeredUsers
;
1257 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1258 } catch (IOException e
) {
1259 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1260 registeredUsers
= Map
.of();
1263 for (var address
: addressesMissingUuid
) {
1264 final var number
= address
.getNumber().get();
1265 if (registeredUsers
.containsKey(number
)) {
1266 final var newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(registeredUsers
.get(number
),
1268 signalServiceAddresses
.add(newAddress
);
1270 signalServiceAddresses
.add(address
);
1274 return signalServiceAddresses
;
1277 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1279 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1281 serviceEnvironmentConfig
.getCdsMrenclave());
1282 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1283 throw new IOException(e
);
1287 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1288 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1289 ) throws IOException
{
1290 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1291 final var timestamp
= System
.currentTimeMillis();
1292 messageBuilder
.withTimestamp(timestamp
);
1293 getOrCreateMessagePipe();
1294 getOrCreateUnidentifiedMessagePipe();
1295 SignalServiceDataMessage message
= null;
1297 message
= messageBuilder
.build();
1298 if (message
.getGroupContext().isPresent()) {
1300 var messageSender
= createMessageSender();
1301 final var isRecipientUpdate
= false;
1302 var result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1303 unidentifiedAccessHelper
.getAccessFor(recipients
),
1306 for (var r
: result
) {
1307 if (r
.getIdentityFailure() != null) {
1308 account
.getSignalProtocolStore()
1309 .saveIdentity(r
.getAddress(),
1310 r
.getIdentityFailure().getIdentityKey(),
1311 TrustLevel
.UNTRUSTED
);
1314 return new Pair
<>(timestamp
, result
);
1315 } catch (UntrustedIdentityException e
) {
1316 if (e
.getIdentityKey() != null) {
1317 account
.getSignalProtocolStore()
1318 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1320 TrustLevel
.UNTRUSTED
);
1322 return new Pair
<>(timestamp
, List
.of());
1325 // Send to all individually, so sync messages are sent correctly
1326 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1327 var results
= new ArrayList
<SendMessageResult
>(recipients
.size());
1328 for (var address
: recipients
) {
1329 final var contact
= account
.getContactStore().getContact(address
);
1330 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1331 messageBuilder
.withExpiration(expirationTime
);
1332 message
= messageBuilder
.build();
1333 results
.add(sendMessage(address
, message
));
1335 return new Pair
<>(timestamp
, results
);
1338 if (message
!= null && message
.isEndSession()) {
1339 for (var recipient
: recipients
) {
1340 handleEndSession(recipient
);
1347 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1348 SignalServiceDataMessage
.Builder messageBuilder
1349 ) throws IOException
{
1350 final var timestamp
= System
.currentTimeMillis();
1351 messageBuilder
.withTimestamp(timestamp
);
1352 getOrCreateMessagePipe();
1353 getOrCreateUnidentifiedMessagePipe();
1355 final var address
= getSelfAddress();
1357 final var contact
= account
.getContactStore().getContact(address
);
1358 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1359 messageBuilder
.withExpiration(expirationTime
);
1361 var message
= messageBuilder
.build();
1362 final var result
= sendSelfMessage(message
);
1363 return new Pair
<>(timestamp
, result
);
1369 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1370 var messageSender
= createMessageSender();
1372 var recipient
= account
.getSelfAddress();
1374 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1375 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1376 message
.getTimestamp(),
1378 message
.getExpiresInSeconds(),
1379 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1381 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1384 var startTime
= System
.currentTimeMillis();
1385 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1386 return SendMessageResult
.success(recipient
,
1387 unidentifiedAccess
.isPresent(),
1389 System
.currentTimeMillis() - startTime
);
1390 } catch (UntrustedIdentityException e
) {
1391 if (e
.getIdentityKey() != null) {
1392 account
.getSignalProtocolStore()
1393 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1395 TrustLevel
.UNTRUSTED
);
1397 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1401 private SendMessageResult
sendMessage(
1402 SignalServiceAddress address
, SignalServiceDataMessage message
1403 ) throws IOException
{
1404 var messageSender
= createMessageSender();
1407 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1408 } catch (UntrustedIdentityException e
) {
1409 if (e
.getIdentityKey() != null) {
1410 account
.getSignalProtocolStore()
1411 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1413 TrustLevel
.UNTRUSTED
);
1415 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1419 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1420 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1421 account
.getSignalProtocolStore(),
1422 certificateValidator
);
1424 return cipher
.decrypt(envelope
);
1425 } catch (ProtocolUntrustedIdentityException e
) {
1426 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1427 var identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1428 final var untrustedIdentity
= identityException
.getUntrustedIdentity();
1429 if (untrustedIdentity
!= null) {
1430 account
.getSignalProtocolStore()
1431 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1433 TrustLevel
.UNTRUSTED
);
1435 throw identityException
;
1437 throw new AssertionError(e
);
1441 private void handleEndSession(SignalServiceAddress source
) {
1442 account
.getSessionStore().deleteAllSessions(source
.getIdentifier());
1445 private List
<HandleAction
> handleSignalServiceDataMessage(
1446 SignalServiceDataMessage message
,
1448 SignalServiceAddress source
,
1449 SignalServiceAddress destination
,
1450 boolean ignoreAttachments
1452 var actions
= new ArrayList
<HandleAction
>();
1453 if (message
.getGroupContext().isPresent()) {
1454 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1455 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1456 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1457 var group
= getGroup(groupId
);
1458 if (group
== null || group
instanceof GroupInfoV1
) {
1459 var groupV1
= (GroupInfoV1
) group
;
1460 switch (groupInfo
.getType()) {
1462 if (groupV1
== null) {
1463 groupV1
= new GroupInfoV1(groupId
);
1466 if (groupInfo
.getAvatar().isPresent()) {
1467 var avatar
= groupInfo
.getAvatar().get();
1468 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1471 if (groupInfo
.getName().isPresent()) {
1472 groupV1
.name
= groupInfo
.getName().get();
1475 if (groupInfo
.getMembers().isPresent()) {
1476 groupV1
.addMembers(groupInfo
.getMembers()
1479 .map(this::resolveSignalServiceAddress
)
1480 .collect(Collectors
.toSet()));
1483 account
.getGroupStore().updateGroup(groupV1
);
1487 if (groupV1
== null && !isSync
) {
1488 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1492 if (groupV1
!= null) {
1493 groupV1
.removeMember(source
);
1494 account
.getGroupStore().updateGroup(groupV1
);
1499 if (groupV1
!= null && !isSync
) {
1500 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1505 // Received a group v1 message for a v2 group
1508 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1509 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1510 final var groupMasterKey
= groupContext
.getMasterKey();
1512 getOrMigrateGroup(groupMasterKey
,
1513 groupContext
.getRevision(),
1514 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1518 final var conversationPartnerAddress
= isSync ? destination
: source
;
1519 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1520 handleEndSession(conversationPartnerAddress
);
1522 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1523 if (message
.getGroupContext().isPresent()) {
1524 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1525 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1526 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1527 if (group
!= null) {
1528 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1529 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1530 account
.getGroupStore().updateGroup(group
);
1533 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1534 // disappearing message timer already stored in the DecryptedGroup
1536 } else if (conversationPartnerAddress
!= null) {
1537 var contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1538 if (contact
== null) {
1539 contact
= new ContactInfo(conversationPartnerAddress
);
1541 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1542 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1543 account
.getContactStore().updateContact(contact
);
1547 if (!ignoreAttachments
) {
1548 if (message
.getAttachments().isPresent()) {
1549 for (var attachment
: message
.getAttachments().get()) {
1550 downloadAttachment(attachment
);
1553 if (message
.getSharedContacts().isPresent()) {
1554 for (var contact
: message
.getSharedContacts().get()) {
1555 if (contact
.getAvatar().isPresent()) {
1556 downloadAttachment(contact
.getAvatar().get().getAttachment());
1561 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1562 final ProfileKey profileKey
;
1564 profileKey
= new ProfileKey(message
.getProfileKey().get());
1565 } catch (InvalidInputException e
) {
1566 throw new AssertionError(e
);
1568 if (source
.matches(account
.getSelfAddress())) {
1569 this.account
.setProfileKey(profileKey
);
1571 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1573 if (message
.getPreviews().isPresent()) {
1574 final var previews
= message
.getPreviews().get();
1575 for (var preview
: previews
) {
1576 if (preview
.getImage().isPresent()) {
1577 downloadAttachment(preview
.getImage().get());
1581 if (message
.getQuote().isPresent()) {
1582 final var quote
= message
.getQuote().get();
1584 for (var quotedAttachment
: quote
.getAttachments()) {
1585 final var thumbnail
= quotedAttachment
.getThumbnail();
1586 if (thumbnail
!= null) {
1587 downloadAttachment(thumbnail
);
1591 if (message
.getSticker().isPresent()) {
1592 final var messageSticker
= message
.getSticker().get();
1593 var sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1594 if (sticker
== null) {
1595 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1596 account
.getStickerStore().updateSticker(sticker
);
1602 private GroupInfoV2
getOrMigrateGroup(
1603 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1605 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1607 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1608 var groupInfo
= getGroup(groupId
);
1609 final GroupInfoV2 groupInfoV2
;
1610 if (groupInfo
instanceof GroupInfoV1
) {
1611 // Received a v2 group message for a v1 group, we need to locally migrate the group
1612 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1613 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1614 logger
.info("Locally migrated group {} to group v2, id: {}",
1615 groupInfo
.getGroupId().toBase64(),
1616 groupInfoV2
.getGroupId().toBase64());
1617 } else if (groupInfo
instanceof GroupInfoV2
) {
1618 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1620 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1623 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1624 DecryptedGroup group
= null;
1625 if (signedGroupChange
!= null
1626 && groupInfoV2
.getGroup() != null
1627 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1628 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1630 if (group
== null) {
1631 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1633 if (group
!= null) {
1634 storeProfileKeysFromMembers(group
);
1635 final var avatar
= group
.getAvatar();
1636 if (avatar
!= null && !avatar
.isEmpty()) {
1637 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1640 groupInfoV2
.setGroup(group
);
1641 account
.getGroupStore().updateGroup(groupInfoV2
);
1647 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1648 for (var member
: group
.getMembersList()) {
1649 final var address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1650 .toByteArray()), null));
1652 account
.getProfileStore()
1653 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1654 } catch (InvalidInputException ignored
) {
1659 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1660 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1661 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1665 private void retryFailedReceivedMessage(
1666 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1668 var envelope
= cachedMessage
.loadEnvelope();
1669 if (envelope
== null) {
1672 SignalServiceContent content
= null;
1673 if (!envelope
.isReceipt()) {
1675 content
= decryptMessage(envelope
);
1676 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1678 } catch (Exception er
) {
1679 // All other errors are not recoverable, so delete the cached message
1680 cachedMessage
.delete();
1683 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1684 for (var action
: actions
) {
1686 action
.execute(this);
1687 } catch (Throwable e
) {
1688 logger
.warn("Message action failed.", e
);
1693 handler
.handleMessage(envelope
, content
, null);
1694 cachedMessage
.delete();
1697 public void receiveMessages(
1700 boolean returnOnTimeout
,
1701 boolean ignoreAttachments
,
1702 ReceiveMessageHandler handler
1703 ) throws IOException
{
1704 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1706 Set
<HandleAction
> queuedActions
= null;
1708 final var messagePipe
= getOrCreateMessagePipe();
1710 var hasCaughtUpWithOldMessages
= false;
1713 SignalServiceEnvelope envelope
;
1714 SignalServiceContent content
= null;
1715 Exception exception
= null;
1716 final CachedMessage
[] cachedMessage
= {null};
1718 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1719 // store message on disk, before acknowledging receipt to the server
1720 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1722 if (result
.isPresent()) {
1723 envelope
= result
.get();
1725 // Received indicator that server queue is empty
1726 hasCaughtUpWithOldMessages
= true;
1728 if (queuedActions
!= null) {
1729 for (var action
: queuedActions
) {
1731 action
.execute(this);
1732 } catch (Throwable e
) {
1733 logger
.warn("Message action failed.", e
);
1737 queuedActions
.clear();
1738 queuedActions
= null;
1741 // Continue to wait another timeout for new messages
1744 } catch (TimeoutException e
) {
1745 if (returnOnTimeout
) return;
1749 if (envelope
.hasSource()) {
1750 // Store uuid if we don't have it already
1751 var source
= envelope
.getSourceAddress();
1752 resolveSignalServiceAddress(source
);
1754 if (!envelope
.isReceipt()) {
1756 content
= decryptMessage(envelope
);
1757 } catch (Exception e
) {
1760 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1761 if (hasCaughtUpWithOldMessages
) {
1762 for (var action
: actions
) {
1764 action
.execute(this);
1765 } catch (Throwable e
) {
1766 logger
.warn("Message action failed.", e
);
1770 if (queuedActions
== null) {
1771 queuedActions
= new HashSet
<>();
1773 queuedActions
.addAll(actions
);
1777 if (isMessageBlocked(envelope
, content
)) {
1778 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1779 } else if (isNotAGroupMember(envelope
, content
)) {
1780 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1782 handler
.handleMessage(envelope
, content
, exception
);
1784 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1785 if (cachedMessage
[0] != null) {
1786 cachedMessage
[0].delete();
1792 private boolean isMessageBlocked(
1793 SignalServiceEnvelope envelope
, SignalServiceContent content
1795 SignalServiceAddress source
;
1796 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1797 source
= envelope
.getSourceAddress();
1798 } else if (content
!= null) {
1799 source
= content
.getSender();
1803 var sourceContact
= account
.getContactStore().getContact(source
);
1804 if (sourceContact
!= null && sourceContact
.blocked
) {
1808 if (content
!= null && content
.getDataMessage().isPresent()) {
1809 var message
= content
.getDataMessage().get();
1810 if (message
.getGroupContext().isPresent()) {
1811 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1812 var group
= getGroup(groupId
);
1813 if (group
!= null && group
.isBlocked()) {
1821 private boolean isNotAGroupMember(
1822 SignalServiceEnvelope envelope
, SignalServiceContent content
1824 SignalServiceAddress source
;
1825 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1826 source
= envelope
.getSourceAddress();
1827 } else if (content
!= null) {
1828 source
= content
.getSender();
1833 if (content
!= null && content
.getDataMessage().isPresent()) {
1834 var message
= content
.getDataMessage().get();
1835 if (message
.getGroupContext().isPresent()) {
1836 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1837 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1838 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1842 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1843 var group
= getGroup(groupId
);
1844 if (group
!= null && !group
.isMember(source
)) {
1852 private List
<HandleAction
> handleMessage(
1853 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1855 var actions
= new ArrayList
<HandleAction
>();
1856 if (content
!= null) {
1857 final SignalServiceAddress sender
;
1858 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1859 sender
= envelope
.getSourceAddress();
1861 sender
= content
.getSender();
1863 // Store uuid if we don't have it already
1864 resolveSignalServiceAddress(sender
);
1866 if (content
.getDataMessage().isPresent()) {
1867 var message
= content
.getDataMessage().get();
1869 if (content
.isNeedsReceipt()) {
1870 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1873 actions
.addAll(handleSignalServiceDataMessage(message
,
1876 account
.getSelfAddress(),
1877 ignoreAttachments
));
1879 if (content
.getSyncMessage().isPresent()) {
1880 account
.setMultiDevice(true);
1881 var syncMessage
= content
.getSyncMessage().get();
1882 if (syncMessage
.getSent().isPresent()) {
1883 var message
= syncMessage
.getSent().get();
1884 final var destination
= message
.getDestination().orNull();
1885 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1889 ignoreAttachments
));
1891 if (syncMessage
.getRequest().isPresent()) {
1892 var rm
= syncMessage
.getRequest().get();
1893 if (rm
.isContactsRequest()) {
1894 actions
.add(SendSyncContactsAction
.create());
1896 if (rm
.isGroupsRequest()) {
1897 actions
.add(SendSyncGroupsAction
.create());
1899 if (rm
.isBlockedListRequest()) {
1900 actions
.add(SendSyncBlockedListAction
.create());
1902 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1904 if (syncMessage
.getGroups().isPresent()) {
1905 File tmpFile
= null;
1907 tmpFile
= IOUtils
.createTempFile();
1908 final var groupsMessage
= syncMessage
.getGroups().get();
1909 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1910 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1912 while ((g
= s
.read()) != null) {
1913 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1914 if (syncGroup
!= null) {
1915 if (g
.getName().isPresent()) {
1916 syncGroup
.name
= g
.getName().get();
1918 syncGroup
.addMembers(g
.getMembers()
1920 .map(this::resolveSignalServiceAddress
)
1921 .collect(Collectors
.toSet()));
1922 if (!g
.isActive()) {
1923 syncGroup
.removeMember(account
.getSelfAddress());
1925 // Add ourself to the member set as it's marked as active
1926 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1928 syncGroup
.blocked
= g
.isBlocked();
1929 if (g
.getColor().isPresent()) {
1930 syncGroup
.color
= g
.getColor().get();
1933 if (g
.getAvatar().isPresent()) {
1934 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1936 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1937 syncGroup
.archived
= g
.isArchived();
1938 account
.getGroupStore().updateGroup(syncGroup
);
1942 } catch (Exception e
) {
1943 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1947 if (tmpFile
!= null) {
1949 Files
.delete(tmpFile
.toPath());
1950 } catch (IOException e
) {
1951 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1958 if (syncMessage
.getBlockedList().isPresent()) {
1959 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1960 for (var address
: blockedListMessage
.getAddresses()) {
1961 setContactBlocked(resolveSignalServiceAddress(address
), true);
1963 for (var groupId
: blockedListMessage
.getGroupIds()
1965 .map(GroupId
::unknownVersion
)
1966 .collect(Collectors
.toSet())) {
1968 setGroupBlocked(groupId
, true);
1969 } catch (GroupNotFoundException e
) {
1970 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1971 groupId
.toBase64());
1975 if (syncMessage
.getContacts().isPresent()) {
1976 File tmpFile
= null;
1978 tmpFile
= IOUtils
.createTempFile();
1979 final var contactsMessage
= syncMessage
.getContacts().get();
1980 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1981 .asPointer(), tmpFile
)) {
1982 var s
= new DeviceContactsInputStream(attachmentAsStream
);
1983 if (contactsMessage
.isComplete()) {
1984 account
.getContactStore().clear();
1987 while ((c
= s
.read()) != null) {
1988 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1989 account
.setProfileKey(c
.getProfileKey().get());
1991 final var address
= resolveSignalServiceAddress(c
.getAddress());
1992 var contact
= account
.getContactStore().getContact(address
);
1993 if (contact
== null) {
1994 contact
= new ContactInfo(address
);
1996 if (c
.getName().isPresent()) {
1997 contact
.name
= c
.getName().get();
1999 if (c
.getColor().isPresent()) {
2000 contact
.color
= c
.getColor().get();
2002 if (c
.getProfileKey().isPresent()) {
2003 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
2005 if (c
.getVerified().isPresent()) {
2006 final var verifiedMessage
= c
.getVerified().get();
2007 account
.getSignalProtocolStore()
2008 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
2009 verifiedMessage
.getIdentityKey(),
2010 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2012 if (c
.getExpirationTimer().isPresent()) {
2013 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
2015 contact
.blocked
= c
.isBlocked();
2016 contact
.inboxPosition
= c
.getInboxPosition().orNull();
2017 contact
.archived
= c
.isArchived();
2018 account
.getContactStore().updateContact(contact
);
2020 if (c
.getAvatar().isPresent()) {
2021 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2025 } catch (Exception e
) {
2026 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2030 if (tmpFile
!= null) {
2032 Files
.delete(tmpFile
.toPath());
2033 } catch (IOException e
) {
2034 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2041 if (syncMessage
.getVerified().isPresent()) {
2042 final var verifiedMessage
= syncMessage
.getVerified().get();
2043 account
.getSignalProtocolStore()
2044 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2045 verifiedMessage
.getIdentityKey(),
2046 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2048 if (syncMessage
.getStickerPackOperations().isPresent()) {
2049 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2050 for (var m
: stickerPackOperationMessages
) {
2051 if (!m
.getPackId().isPresent()) {
2054 var sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2055 if (sticker
== null) {
2056 if (!m
.getPackKey().isPresent()) {
2059 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2061 sticker
.setInstalled(!m
.getType().isPresent()
2062 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2063 account
.getStickerStore().updateSticker(sticker
);
2066 if (syncMessage
.getFetchType().isPresent()) {
2067 switch (syncMessage
.getFetchType().get()) {
2069 getRecipientProfile(getSelfAddress(), true);
2070 case STORAGE_MANIFEST
:
2074 if (syncMessage
.getKeys().isPresent()) {
2075 final var keysMessage
= syncMessage
.getKeys().get();
2076 if (keysMessage
.getStorageService().isPresent()) {
2077 final var storageKey
= keysMessage
.getStorageService().get();
2078 account
.setStorageKey(storageKey
);
2081 if (syncMessage
.getConfiguration().isPresent()) {
2089 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2091 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2092 } catch (IOException e
) {
2093 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2097 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2099 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2100 } catch (IOException e
) {
2101 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2105 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2107 avatarStore
.storeGroupAvatar(groupId
,
2108 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2109 } catch (IOException e
) {
2110 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2114 private void downloadProfileAvatar(
2115 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2118 avatarStore
.storeProfileAvatar(address
,
2119 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2120 } catch (Throwable e
) {
2121 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2125 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2126 return attachmentStore
.getAttachmentFile(attachmentId
);
2129 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2130 if (!attachment
.isPointer()) {
2131 logger
.warn("Invalid state, can't store an attachment stream.");
2134 var pointer
= attachment
.asPointer();
2135 if (pointer
.getPreview().isPresent()) {
2136 final var preview
= pointer
.getPreview().get();
2138 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2139 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2140 } catch (IOException e
) {
2141 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2146 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2147 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2148 } catch (IOException e
) {
2149 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2153 private void retrieveGroupV2Avatar(
2154 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2155 ) throws IOException
{
2156 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2158 var tmpFile
= IOUtils
.createTempFile();
2159 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2161 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2162 var encryptedData
= IOUtils
.readFully(input
);
2164 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2165 outputStream
.write(decryptedData
);
2168 Files
.delete(tmpFile
.toPath());
2169 } catch (IOException e
) {
2170 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2177 private void retrieveProfileAvatar(
2178 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2179 ) throws IOException
{
2180 var tmpFile
= IOUtils
.createTempFile();
2181 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2184 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2185 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2186 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2189 Files
.delete(tmpFile
.toPath());
2190 } catch (IOException e
) {
2191 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2198 private void retrieveAttachment(
2199 final SignalServiceAttachment attachment
, final OutputStream outputStream
2200 ) throws IOException
{
2201 if (attachment
.isPointer()) {
2202 var pointer
= attachment
.asPointer();
2203 retrieveAttachmentPointer(pointer
, outputStream
);
2205 var stream
= attachment
.asStream();
2206 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2210 private void retrieveAttachmentPointer(
2211 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2212 ) throws IOException
{
2213 var tmpFile
= IOUtils
.createTempFile();
2214 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2215 IOUtils
.copyStream(input
, outputStream
);
2216 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2217 throw new IOException(e
);
2220 Files
.delete(tmpFile
.toPath());
2221 } catch (IOException e
) {
2222 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2229 private InputStream
retrieveAttachmentAsStream(
2230 SignalServiceAttachmentPointer pointer
, File tmpFile
2231 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2232 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2235 void sendGroups() throws IOException
, UntrustedIdentityException
{
2236 var groupsFile
= IOUtils
.createTempFile();
2239 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2240 var out
= new DeviceGroupsOutputStream(fos
);
2241 for (var record : getGroups()) {
2242 if (record instanceof GroupInfoV1
) {
2243 var groupInfo
= (GroupInfoV1
) record;
2244 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2245 Optional
.fromNullable(groupInfo
.name
),
2246 new ArrayList
<>(groupInfo
.getMembers()),
2247 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2248 groupInfo
.isMember(account
.getSelfAddress()),
2249 Optional
.of(groupInfo
.messageExpirationTime
),
2250 Optional
.fromNullable(groupInfo
.color
),
2252 Optional
.fromNullable(groupInfo
.inboxPosition
),
2253 groupInfo
.archived
));
2258 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2259 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2260 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2261 .withStream(groupsFileStream
)
2262 .withContentType("application/octet-stream")
2263 .withLength(groupsFile
.length())
2266 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2271 Files
.delete(groupsFile
.toPath());
2272 } catch (IOException e
) {
2273 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2278 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2279 var contactsFile
= IOUtils
.createTempFile();
2282 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2283 var out
= new DeviceContactsOutputStream(fos
);
2284 for (var record : account
.getContactStore().getContacts()) {
2285 VerifiedMessage verifiedMessage
= null;
2286 var currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2287 if (currentIdentity
!= null) {
2288 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2289 currentIdentity
.getIdentityKey(),
2290 currentIdentity
.getTrustLevel().toVerifiedState(),
2291 currentIdentity
.getDateAdded().getTime());
2294 var profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2295 out
.write(new DeviceContact(record.getAddress(),
2296 Optional
.fromNullable(record.name
),
2297 createContactAvatarAttachment(record.getAddress()),
2298 Optional
.fromNullable(record.color
),
2299 Optional
.fromNullable(verifiedMessage
),
2300 Optional
.fromNullable(profileKey
),
2302 Optional
.of(record.messageExpirationTime
),
2303 Optional
.fromNullable(record.inboxPosition
),
2307 if (account
.getProfileKey() != null) {
2308 // Send our own profile key as well
2309 out
.write(new DeviceContact(account
.getSelfAddress(),
2314 Optional
.of(account
.getProfileKey()),
2322 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2323 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2324 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2325 .withStream(contactsFileStream
)
2326 .withContentType("application/octet-stream")
2327 .withLength(contactsFile
.length())
2330 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2335 Files
.delete(contactsFile
.toPath());
2336 } catch (IOException e
) {
2337 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2342 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2343 var addresses
= new ArrayList
<SignalServiceAddress
>();
2344 for (var record : account
.getContactStore().getContacts()) {
2345 if (record.blocked
) {
2346 addresses
.add(record.getAddress());
2349 var groupIds
= new ArrayList
<byte[]>();
2350 for (var record : getGroups()) {
2351 if (record.isBlocked()) {
2352 groupIds
.add(record.getGroupId().serialize());
2355 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2358 private void sendVerifiedMessage(
2359 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2360 ) throws IOException
, UntrustedIdentityException
{
2361 var verifiedMessage
= new VerifiedMessage(destination
,
2363 trustLevel
.toVerifiedState(),
2364 System
.currentTimeMillis());
2365 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2368 public List
<ContactInfo
> getContacts() {
2369 return account
.getContactStore().getContacts();
2372 public String
getContactOrProfileName(String number
) {
2373 final var address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2375 final var contact
= account
.getContactStore().getContact(address
);
2376 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2377 return contact
.name
;
2380 final var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2381 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2382 return profileEntry
.getProfile().getDisplayName();
2387 public GroupInfo
getGroup(GroupId groupId
) {
2388 final var group
= account
.getGroupStore().getGroup(groupId
);
2389 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2390 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2391 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2392 account
.getGroupStore().updateGroup(group
);
2397 public List
<IdentityInfo
> getIdentities() {
2398 return account
.getSignalProtocolStore().getIdentities();
2401 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2402 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2406 * Trust this the identity with this fingerprint
2408 * @param name username of the identity
2409 * @param fingerprint Fingerprint
2411 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2412 var address
= canonicalizeAndResolveSignalServiceAddress(name
);
2413 return trustIdentity(address
, (identityKey
) -> Arrays
.equals(identityKey
.serialize(), fingerprint
));
2417 * Trust this the identity with this safety number
2419 * @param name username of the identity
2420 * @param safetyNumber Safety number
2422 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2423 var address
= canonicalizeAndResolveSignalServiceAddress(name
);
2424 return trustIdentity(address
, (identityKey
) -> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)));
2427 private boolean trustIdentity(SignalServiceAddress address
, Function
<IdentityKey
, Boolean
> verifier
) {
2428 var ids
= account
.getSignalProtocolStore().getIdentities(address
);
2433 IdentityInfo foundIdentity
= null;
2435 for (var id
: ids
) {
2436 if (verifier
.apply(id
.getIdentityKey())) {
2442 if (foundIdentity
== null) {
2446 account
.getSignalProtocolStore()
2447 .setIdentityTrustLevel(address
, foundIdentity
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2449 sendVerifiedMessage(address
, foundIdentity
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2450 } catch (IOException
| UntrustedIdentityException e
) {
2451 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2454 // Successfully trusted the new identity, now remove all other identities for that number
2455 for (var id
: ids
) {
2456 if (id
== foundIdentity
) {
2459 account
.getSignalProtocolStore().removeIdentity(address
, id
.getIdentityKey());
2467 * Trust all keys of this identity without verification
2469 * @param name username of the identity
2471 public boolean trustIdentityAllKeys(String name
) {
2472 var address
= resolveSignalServiceAddress(name
);
2473 var ids
= account
.getSignalProtocolStore().getIdentities(address
);
2477 for (var id
: ids
) {
2478 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2479 account
.getSignalProtocolStore()
2480 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2482 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2483 } catch (IOException
| UntrustedIdentityException e
) {
2484 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2492 public String
computeSafetyNumber(
2493 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2495 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2496 account
.getSelfAddress(),
2497 getIdentityKeyPair().getPublicKey(),
2502 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2503 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2505 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2506 return resolveSignalServiceAddress(canonicalizedNumber
);
2509 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2510 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2512 return resolveSignalServiceAddress(address
);
2515 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2516 if (address
.matches(account
.getSelfAddress())) {
2517 return account
.getSelfAddress();
2520 return account
.getRecipientStore().resolveServiceAddress(address
);
2524 public void close() throws IOException
{
2528 void close(boolean closeAccount
) throws IOException
{
2529 executor
.shutdown();
2531 if (messagePipe
!= null) {
2532 messagePipe
.shutdown();
2536 if (unidentifiedMessagePipe
!= null) {
2537 unidentifiedMessagePipe
.shutdown();
2538 unidentifiedMessagePipe
= null;
2541 if (closeAccount
&& account
!= null) {
2547 public interface ReceiveMessageHandler
{
2549 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);