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
);
490 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
491 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
493 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
494 account
.addSignedPreKey(record);
500 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
501 if (messagePipe
== null) {
502 messagePipe
= messageReceiver
.createMessagePipe();
507 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
508 if (unidentifiedMessagePipe
== null) {
509 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
511 return unidentifiedMessagePipe
;
514 private SignalServiceMessageSender
createMessageSender() {
515 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
517 account
.getUsername(),
518 account
.getPassword(),
519 account
.getDeviceId(),
520 account
.getSignalProtocolStore(),
522 account
.isMultiDevice(),
523 Optional
.fromNullable(messagePipe
),
524 Optional
.fromNullable(unidentifiedMessagePipe
),
526 clientZkProfileOperations
,
528 ServiceConfig
.MAX_ENVELOPE_SIZE
,
529 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
532 public SignalProfile
getRecipientProfile(
533 SignalServiceAddress address
535 return getRecipientProfile(address
, false);
538 private SignalProfile
getRecipientProfile(
539 SignalServiceAddress address
, boolean force
541 var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
542 if (profileEntry
== null) {
545 var now
= new Date().getTime();
546 // Profiles are cached for 24h before retrieving them again
547 if (!profileEntry
.isRequestPending() && (
549 || profileEntry
.getProfile() == null
550 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
552 profileEntry
.setRequestPending(true);
553 final SignalServiceProfile encryptedProfile
;
555 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
557 } catch (IOException e
) {
558 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
561 profileEntry
.setRequestPending(false);
564 final var profileKey
= profileEntry
.getProfileKey();
565 final var profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
566 account
.getProfileStore()
567 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
570 return profileEntry
.getProfile();
573 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
574 var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
575 if (profileEntry
== null) {
578 if (profileEntry
.getProfileKeyCredential() == null) {
579 ProfileAndCredential profileAndCredential
;
581 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
582 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
583 } catch (IOException e
) {
584 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
588 var now
= new Date().getTime();
589 final var profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
590 final var profile
= decryptProfileAndDownloadAvatar(address
,
591 profileEntry
.getProfileKey(),
592 profileAndCredential
.getProfile());
593 account
.getProfileStore()
594 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
595 return profileKeyCredential
;
597 return profileEntry
.getProfileKeyCredential();
600 private SignalProfile
decryptProfileAndDownloadAvatar(
601 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
603 if (encryptedProfile
.getAvatar() != null) {
604 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
607 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
610 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
611 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
612 if (streamDetails
== null) {
613 return Optional
.absent();
616 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
619 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
620 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
621 if (streamDetails
== null) {
622 return Optional
.absent();
625 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
628 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
629 var g
= getGroup(groupId
);
631 throw new GroupNotFoundException(groupId
);
633 if (!g
.isMember(account
.getSelfAddress())) {
634 throw new NotAGroupMemberException(groupId
, g
.getTitle());
639 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
640 var g
= getGroup(groupId
);
642 throw new GroupNotFoundException(groupId
);
644 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
645 throw new NotAGroupMemberException(groupId
, g
.getTitle());
650 public List
<GroupInfo
> getGroups() {
651 return account
.getGroupStore().getGroups();
654 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
655 String messageText
, List
<String
> attachments
, GroupId groupId
656 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
657 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
658 if (attachments
!= null) {
659 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
662 return sendGroupMessage(messageBuilder
, groupId
);
665 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
666 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
667 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
668 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
670 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
671 targetSentTimestamp
);
672 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
674 return sendGroupMessage(messageBuilder
, groupId
);
677 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
678 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
679 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
680 final var g
= getGroupForSending(groupId
);
682 GroupUtils
.setGroupContext(messageBuilder
, g
);
683 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
685 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
688 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
689 SignalServiceDataMessage
.Builder messageBuilder
;
691 final var g
= getGroupForUpdating(groupId
);
692 if (g
instanceof GroupInfoV1
) {
693 var groupInfoV1
= (GroupInfoV1
) g
;
694 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
695 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
696 groupInfoV1
.removeMember(account
.getSelfAddress());
697 account
.getGroupStore().updateGroup(groupInfoV1
);
699 final var groupInfoV2
= (GroupInfoV2
) g
;
700 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
701 groupInfoV2
.setGroup(groupGroupChangePair
.first());
702 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
703 account
.getGroupStore().updateGroup(groupInfoV2
);
706 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
709 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
710 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
711 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
712 return sendUpdateGroupMessage(groupId
,
714 members
== null ?
null : getSignalServiceAddresses(members
),
718 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
719 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
720 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
722 SignalServiceDataMessage
.Builder messageBuilder
;
723 if (groupId
== null) {
725 var gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
726 members
== null ? List
.of() : members
,
729 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
730 gv1
.addMembers(List
.of(account
.getSelfAddress()));
731 updateGroupV1(gv1
, name
, members
, avatarFile
);
732 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
735 if (avatarFile
!= null) {
736 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
737 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
739 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
743 var group
= getGroupForUpdating(groupId
);
744 if (group
instanceof GroupInfoV2
) {
745 final var groupInfoV2
= (GroupInfoV2
) group
;
747 Pair
<Long
, List
<SendMessageResult
>> result
= null;
748 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
749 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
750 result
= sendUpdateGroupMessage(groupInfoV2
,
751 groupGroupChangePair
.first(),
752 groupGroupChangePair
.second());
755 if (members
!= null) {
756 final var newMembers
= new HashSet
<>(members
);
757 newMembers
.removeAll(group
.getMembers()
759 .map(this::resolveSignalServiceAddress
)
760 .collect(Collectors
.toSet()));
761 if (newMembers
.size() > 0) {
762 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
763 result
= sendUpdateGroupMessage(groupInfoV2
,
764 groupGroupChangePair
.first(),
765 groupGroupChangePair
.second());
768 if (result
== null || name
!= null || avatarFile
!= null) {
769 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
770 if (avatarFile
!= null) {
771 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
772 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
774 result
= sendUpdateGroupMessage(groupInfoV2
,
775 groupGroupChangePair
.first(),
776 groupGroupChangePair
.second());
779 return new Pair
<>(group
.getGroupId(), result
.second());
781 var gv1
= (GroupInfoV1
) group
;
782 updateGroupV1(gv1
, name
, members
, avatarFile
);
783 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
788 account
.getGroupStore().updateGroup(g
);
790 final var result
= sendMessage(messageBuilder
, g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
791 return new Pair
<>(g
.getGroupId(), result
.second());
794 private void updateGroupV1(
797 final Collection
<SignalServiceAddress
> members
,
798 final File avatarFile
799 ) throws IOException
{
804 if (members
!= null) {
805 final var newE164Members
= new HashSet
<String
>();
806 for (var member
: members
) {
807 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
810 newE164Members
.add(member
.getNumber().get());
813 final var registeredUsers
= getRegisteredUsers(newE164Members
);
814 if (registeredUsers
.size() != newE164Members
.size()) {
815 // Some of the new members are not registered on Signal
816 newE164Members
.removeAll(registeredUsers
.keySet());
817 throw new IOException("Failed to add members "
818 + String
.join(", ", newE164Members
)
819 + " to group: Not registered on Signal");
822 g
.addMembers(members
);
825 if (avatarFile
!= null) {
826 avatarStore
.storeGroupAvatar(g
.getGroupId(),
827 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
831 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
832 GroupInviteLinkUrl inviteLinkUrl
833 ) throws IOException
, GroupLinkNotActiveException
{
834 return sendJoinGroupMessage(inviteLinkUrl
);
837 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
838 GroupInviteLinkUrl inviteLinkUrl
839 ) throws IOException
, GroupLinkNotActiveException
{
840 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
841 inviteLinkUrl
.getPassword());
842 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
843 inviteLinkUrl
.getPassword(),
845 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
846 groupJoinInfo
.getRevision() + 1,
847 groupChange
.toByteArray());
849 if (group
.getGroup() == null) {
850 // Only requested member, can't send update to group members
851 return new Pair
<>(group
.getGroupId(), List
.of());
854 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
856 return new Pair
<>(group
.getGroupId(), result
.second());
859 private static int currentTimeDays() {
860 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
863 private GroupsV2AuthorizationString
getGroupAuthForToday(
864 final GroupSecretParams groupSecretParams
865 ) throws IOException
{
866 final var today
= currentTimeDays();
867 // Returns credentials for the next 7 days
868 final var credentials
= groupsV2Api
.getCredentials(today
);
869 // TODO cache credentials until they expire
870 var authCredentialResponse
= credentials
.get(today
);
872 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
875 authCredentialResponse
);
876 } catch (VerificationFailedException e
) {
877 throw new IOException(e
);
881 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
882 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
883 ) throws IOException
{
884 group
.setGroup(newDecryptedGroup
);
885 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
886 account
.getGroupStore().updateGroup(group
);
887 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
890 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
891 GroupIdV1 groupId
, SignalServiceAddress recipient
892 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
894 var group
= getGroupForSending(groupId
);
895 if (!(group
instanceof GroupInfoV1
)) {
896 throw new RuntimeException("Received an invalid group request for a v2 group!");
898 g
= (GroupInfoV1
) group
;
900 if (!g
.isMember(recipient
)) {
901 throw new NotAGroupMemberException(groupId
, g
.name
);
904 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
906 // Send group message only to the recipient who requested it
907 return sendMessage(messageBuilder
, List
.of(recipient
));
910 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
911 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
912 .withId(g
.getGroupId().serialize())
914 .withMembers(new ArrayList
<>(g
.getMembers()));
917 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
918 if (attachment
.isPresent()) {
919 group
.withAvatar(attachment
.get());
921 } catch (IOException e
) {
922 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
925 return SignalServiceDataMessage
.newBuilder()
926 .asGroupMessage(group
.build())
927 .withExpiration(g
.getMessageExpirationTime());
930 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
931 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
932 .withRevision(g
.getGroup().getRevision())
933 .withSignedGroupChange(signedGroupChange
);
934 return SignalServiceDataMessage
.newBuilder()
935 .asGroupMessage(group
.build())
936 .withExpiration(g
.getMessageExpirationTime());
939 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
940 GroupIdV1 groupId
, SignalServiceAddress recipient
941 ) throws IOException
{
942 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
944 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
946 // Send group info request message to the recipient who sent us a message with this groupId
947 return sendMessage(messageBuilder
, List
.of(recipient
));
951 SignalServiceAddress remoteAddress
, long messageId
952 ) throws IOException
, UntrustedIdentityException
{
953 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
955 System
.currentTimeMillis());
957 createMessageSender().sendReceipt(remoteAddress
,
958 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
962 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
963 String messageText
, List
<String
> attachments
, List
<String
> recipients
964 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
965 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
966 if (attachments
!= null) {
967 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
969 // Upload attachments here, so we only upload once even for multiple recipients
970 var messageSender
= createMessageSender();
971 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
972 for (var attachment
: attachmentStreams
) {
973 if (attachment
.isStream()) {
974 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
975 } else if (attachment
.isPointer()) {
976 attachmentPointers
.add(attachment
.asPointer());
980 messageBuilder
.withAttachments(attachmentPointers
);
982 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
985 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
986 String messageText
, List
<String
> attachments
987 ) throws IOException
, AttachmentInvalidException
{
988 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
989 if (attachments
!= null) {
990 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
992 return sendSelfMessage(messageBuilder
);
995 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
996 long targetSentTimestamp
, List
<String
> recipients
997 ) throws IOException
, InvalidNumberException
{
998 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
999 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1000 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1003 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1004 long targetSentTimestamp
, GroupId groupId
1005 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1006 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1007 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1008 return sendGroupMessage(messageBuilder
, groupId
);
1011 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1012 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1013 ) throws IOException
, InvalidNumberException
{
1014 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1016 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1017 targetSentTimestamp
);
1018 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1019 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1022 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1023 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1025 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1027 return sendMessage(messageBuilder
, signalServiceAddresses
);
1028 } catch (Exception e
) {
1029 for (var address
: signalServiceAddresses
) {
1030 handleEndSession(address
);
1037 public String
getContactName(String number
) throws InvalidNumberException
{
1038 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1039 if (contact
== null) {
1042 return contact
.name
;
1046 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1047 final var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1048 var contact
= account
.getContactStore().getContact(address
);
1049 if (contact
== null) {
1050 contact
= new ContactInfo(address
);
1052 contact
.name
= name
;
1053 account
.getContactStore().updateContact(contact
);
1057 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1058 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1061 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1062 var contact
= account
.getContactStore().getContact(address
);
1063 if (contact
== null) {
1064 contact
= new ContactInfo(address
);
1066 contact
.blocked
= blocked
;
1067 account
.getContactStore().updateContact(contact
);
1071 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1072 var group
= getGroup(groupId
);
1073 if (group
== null) {
1074 throw new GroupNotFoundException(groupId
);
1077 group
.setBlocked(blocked
);
1078 account
.getGroupStore().updateGroup(group
);
1083 * Change the expiration timer for a contact
1085 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1086 var contact
= account
.getContactStore().getContact(address
);
1087 contact
.messageExpirationTime
= messageExpirationTimer
;
1088 account
.getContactStore().updateContact(contact
);
1089 sendExpirationTimerUpdate(address
);
1093 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1094 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1095 sendMessage(messageBuilder
, List
.of(address
));
1099 * Change the expiration timer for a contact
1101 public void setExpirationTimer(
1102 String number
, int messageExpirationTimer
1103 ) throws IOException
, InvalidNumberException
{
1104 var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1105 setExpirationTimer(address
, messageExpirationTimer
);
1109 * Change the expiration timer for a group
1111 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1112 var g
= getGroup(groupId
);
1113 if (g
instanceof GroupInfoV1
) {
1114 var groupInfoV1
= (GroupInfoV1
) g
;
1115 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1116 account
.getGroupStore().updateGroup(groupInfoV1
);
1118 throw new RuntimeException("TODO Not implemented!");
1123 * Upload the sticker pack from path.
1125 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1126 * @return if successful, returns the URL to install the sticker pack in the signal app
1128 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1129 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1131 var messageSender
= createMessageSender();
1133 var packKey
= KeyUtils
.createStickerUploadKey();
1134 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1136 var sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1137 account
.getStickerStore().updateSticker(sticker
);
1141 return new URI("https",
1144 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1145 Hex
.toStringCondensed(packKey
),
1146 StandardCharsets
.UTF_8
)).toString();
1147 } catch (URISyntaxException e
) {
1148 throw new AssertionError(e
);
1152 void requestSyncGroups() throws IOException
{
1153 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1154 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1156 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1158 sendSyncMessage(message
);
1159 } catch (UntrustedIdentityException e
) {
1160 throw new AssertionError(e
);
1164 void requestSyncContacts() throws IOException
{
1165 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1166 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1168 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1170 sendSyncMessage(message
);
1171 } catch (UntrustedIdentityException e
) {
1172 throw new AssertionError(e
);
1176 void requestSyncBlocked() throws IOException
{
1177 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1178 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1180 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1182 sendSyncMessage(message
);
1183 } catch (UntrustedIdentityException e
) {
1184 throw new AssertionError(e
);
1188 void requestSyncConfiguration() throws IOException
{
1189 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1190 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1192 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1194 sendSyncMessage(message
);
1195 } catch (UntrustedIdentityException e
) {
1196 throw new AssertionError(e
);
1200 void requestSyncKeys() throws IOException
{
1201 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1202 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1204 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1206 sendSyncMessage(message
);
1207 } catch (UntrustedIdentityException e
) {
1208 throw new AssertionError(e
);
1212 private byte[] getSenderCertificate() {
1213 // TODO support UUID capable sender certificates
1214 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1217 certificate
= accountManager
.getSenderCertificate();
1218 } catch (IOException e
) {
1219 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1222 // TODO cache for a day
1226 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1227 var messageSender
= createMessageSender();
1229 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1230 } catch (UntrustedIdentityException e
) {
1231 if (e
.getIdentityKey() != null) {
1232 account
.getSignalProtocolStore()
1233 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1235 TrustLevel
.UNTRUSTED
);
1241 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1242 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1243 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1245 for (var number
: numbers
) {
1246 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1247 if (resolvedAddress
.getUuid().isPresent()) {
1248 signalServiceAddresses
.add(resolvedAddress
);
1250 addressesMissingUuid
.add(resolvedAddress
);
1254 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1255 .map(a
-> a
.getNumber().get())
1256 .collect(Collectors
.toSet());
1257 Map
<String
, UUID
> registeredUsers
;
1259 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1260 } catch (IOException e
) {
1261 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1262 registeredUsers
= Map
.of();
1265 for (var address
: addressesMissingUuid
) {
1266 final var number
= address
.getNumber().get();
1267 if (registeredUsers
.containsKey(number
)) {
1268 final var newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(registeredUsers
.get(number
),
1270 signalServiceAddresses
.add(newAddress
);
1272 signalServiceAddresses
.add(address
);
1276 return signalServiceAddresses
;
1279 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1281 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1283 serviceEnvironmentConfig
.getCdsMrenclave());
1284 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1285 throw new IOException(e
);
1289 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1290 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1291 ) throws IOException
{
1292 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1293 final var timestamp
= System
.currentTimeMillis();
1294 messageBuilder
.withTimestamp(timestamp
);
1295 getOrCreateMessagePipe();
1296 getOrCreateUnidentifiedMessagePipe();
1297 SignalServiceDataMessage message
= null;
1299 message
= messageBuilder
.build();
1300 if (message
.getGroupContext().isPresent()) {
1302 var messageSender
= createMessageSender();
1303 final var isRecipientUpdate
= false;
1304 var result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1305 unidentifiedAccessHelper
.getAccessFor(recipients
),
1308 for (var r
: result
) {
1309 if (r
.getIdentityFailure() != null) {
1310 account
.getSignalProtocolStore()
1311 .saveIdentity(r
.getAddress(),
1312 r
.getIdentityFailure().getIdentityKey(),
1313 TrustLevel
.UNTRUSTED
);
1316 return new Pair
<>(timestamp
, result
);
1317 } catch (UntrustedIdentityException e
) {
1318 if (e
.getIdentityKey() != null) {
1319 account
.getSignalProtocolStore()
1320 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1322 TrustLevel
.UNTRUSTED
);
1324 return new Pair
<>(timestamp
, List
.of());
1327 // Send to all individually, so sync messages are sent correctly
1328 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1329 var results
= new ArrayList
<SendMessageResult
>(recipients
.size());
1330 for (var address
: recipients
) {
1331 final var contact
= account
.getContactStore().getContact(address
);
1332 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1333 messageBuilder
.withExpiration(expirationTime
);
1334 message
= messageBuilder
.build();
1335 results
.add(sendMessage(address
, message
));
1337 return new Pair
<>(timestamp
, results
);
1340 if (message
!= null && message
.isEndSession()) {
1341 for (var recipient
: recipients
) {
1342 handleEndSession(recipient
);
1349 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1350 SignalServiceDataMessage
.Builder messageBuilder
1351 ) throws IOException
{
1352 final var timestamp
= System
.currentTimeMillis();
1353 messageBuilder
.withTimestamp(timestamp
);
1354 getOrCreateMessagePipe();
1355 getOrCreateUnidentifiedMessagePipe();
1357 final var address
= getSelfAddress();
1359 final var contact
= account
.getContactStore().getContact(address
);
1360 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1361 messageBuilder
.withExpiration(expirationTime
);
1363 var message
= messageBuilder
.build();
1364 final var result
= sendSelfMessage(message
);
1365 return new Pair
<>(timestamp
, result
);
1371 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1372 var messageSender
= createMessageSender();
1374 var recipient
= account
.getSelfAddress();
1376 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1377 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1378 message
.getTimestamp(),
1380 message
.getExpiresInSeconds(),
1381 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1383 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1386 var startTime
= System
.currentTimeMillis();
1387 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1388 return SendMessageResult
.success(recipient
,
1389 unidentifiedAccess
.isPresent(),
1391 System
.currentTimeMillis() - startTime
);
1392 } catch (UntrustedIdentityException e
) {
1393 if (e
.getIdentityKey() != null) {
1394 account
.getSignalProtocolStore()
1395 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1397 TrustLevel
.UNTRUSTED
);
1399 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1403 private SendMessageResult
sendMessage(
1404 SignalServiceAddress address
, SignalServiceDataMessage message
1405 ) throws IOException
{
1406 var messageSender
= createMessageSender();
1409 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1410 } catch (UntrustedIdentityException e
) {
1411 if (e
.getIdentityKey() != null) {
1412 account
.getSignalProtocolStore()
1413 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1415 TrustLevel
.UNTRUSTED
);
1417 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1421 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1422 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1423 account
.getSignalProtocolStore(),
1424 certificateValidator
);
1426 return cipher
.decrypt(envelope
);
1427 } catch (ProtocolUntrustedIdentityException e
) {
1428 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1429 var identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1430 final var untrustedIdentity
= identityException
.getUntrustedIdentity();
1431 if (untrustedIdentity
!= null) {
1432 account
.getSignalProtocolStore()
1433 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1435 TrustLevel
.UNTRUSTED
);
1437 throw identityException
;
1439 throw new AssertionError(e
);
1443 private void handleEndSession(SignalServiceAddress source
) {
1444 account
.getSessionStore().deleteAllSessions(source
.getIdentifier());
1447 private List
<HandleAction
> handleSignalServiceDataMessage(
1448 SignalServiceDataMessage message
,
1450 SignalServiceAddress source
,
1451 SignalServiceAddress destination
,
1452 boolean ignoreAttachments
1454 var actions
= new ArrayList
<HandleAction
>();
1455 if (message
.getGroupContext().isPresent()) {
1456 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1457 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1458 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1459 var group
= getGroup(groupId
);
1460 if (group
== null || group
instanceof GroupInfoV1
) {
1461 var groupV1
= (GroupInfoV1
) group
;
1462 switch (groupInfo
.getType()) {
1464 if (groupV1
== null) {
1465 groupV1
= new GroupInfoV1(groupId
);
1468 if (groupInfo
.getAvatar().isPresent()) {
1469 var avatar
= groupInfo
.getAvatar().get();
1470 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1473 if (groupInfo
.getName().isPresent()) {
1474 groupV1
.name
= groupInfo
.getName().get();
1477 if (groupInfo
.getMembers().isPresent()) {
1478 groupV1
.addMembers(groupInfo
.getMembers()
1481 .map(this::resolveSignalServiceAddress
)
1482 .collect(Collectors
.toSet()));
1485 account
.getGroupStore().updateGroup(groupV1
);
1489 if (groupV1
== null && !isSync
) {
1490 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1494 if (groupV1
!= null) {
1495 groupV1
.removeMember(source
);
1496 account
.getGroupStore().updateGroup(groupV1
);
1501 if (groupV1
!= null && !isSync
) {
1502 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1507 // Received a group v1 message for a v2 group
1510 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1511 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1512 final var groupMasterKey
= groupContext
.getMasterKey();
1514 getOrMigrateGroup(groupMasterKey
,
1515 groupContext
.getRevision(),
1516 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1520 final var conversationPartnerAddress
= isSync ? destination
: source
;
1521 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1522 handleEndSession(conversationPartnerAddress
);
1524 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1525 if (message
.getGroupContext().isPresent()) {
1526 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1527 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1528 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1529 if (group
!= null) {
1530 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1531 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1532 account
.getGroupStore().updateGroup(group
);
1535 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1536 // disappearing message timer already stored in the DecryptedGroup
1538 } else if (conversationPartnerAddress
!= null) {
1539 var contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1540 if (contact
== null) {
1541 contact
= new ContactInfo(conversationPartnerAddress
);
1543 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1544 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1545 account
.getContactStore().updateContact(contact
);
1549 if (!ignoreAttachments
) {
1550 if (message
.getAttachments().isPresent()) {
1551 for (var attachment
: message
.getAttachments().get()) {
1552 downloadAttachment(attachment
);
1555 if (message
.getSharedContacts().isPresent()) {
1556 for (var contact
: message
.getSharedContacts().get()) {
1557 if (contact
.getAvatar().isPresent()) {
1558 downloadAttachment(contact
.getAvatar().get().getAttachment());
1563 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1564 final ProfileKey profileKey
;
1566 profileKey
= new ProfileKey(message
.getProfileKey().get());
1567 } catch (InvalidInputException e
) {
1568 throw new AssertionError(e
);
1570 if (source
.matches(account
.getSelfAddress())) {
1571 this.account
.setProfileKey(profileKey
);
1573 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1575 if (message
.getPreviews().isPresent()) {
1576 final var previews
= message
.getPreviews().get();
1577 for (var preview
: previews
) {
1578 if (preview
.getImage().isPresent()) {
1579 downloadAttachment(preview
.getImage().get());
1583 if (message
.getQuote().isPresent()) {
1584 final var quote
= message
.getQuote().get();
1586 for (var quotedAttachment
: quote
.getAttachments()) {
1587 final var thumbnail
= quotedAttachment
.getThumbnail();
1588 if (thumbnail
!= null) {
1589 downloadAttachment(thumbnail
);
1593 if (message
.getSticker().isPresent()) {
1594 final var messageSticker
= message
.getSticker().get();
1595 var sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1596 if (sticker
== null) {
1597 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1598 account
.getStickerStore().updateSticker(sticker
);
1604 private GroupInfoV2
getOrMigrateGroup(
1605 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1607 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1609 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1610 var groupInfo
= getGroup(groupId
);
1611 final GroupInfoV2 groupInfoV2
;
1612 if (groupInfo
instanceof GroupInfoV1
) {
1613 // Received a v2 group message for a v1 group, we need to locally migrate the group
1614 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1615 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1616 logger
.info("Locally migrated group {} to group v2, id: {}",
1617 groupInfo
.getGroupId().toBase64(),
1618 groupInfoV2
.getGroupId().toBase64());
1619 } else if (groupInfo
instanceof GroupInfoV2
) {
1620 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1622 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1625 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1626 DecryptedGroup group
= null;
1627 if (signedGroupChange
!= null
1628 && groupInfoV2
.getGroup() != null
1629 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1630 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1632 if (group
== null) {
1633 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1635 if (group
!= null) {
1636 storeProfileKeysFromMembers(group
);
1637 final var avatar
= group
.getAvatar();
1638 if (avatar
!= null && !avatar
.isEmpty()) {
1639 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1642 groupInfoV2
.setGroup(group
);
1643 account
.getGroupStore().updateGroup(groupInfoV2
);
1649 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1650 for (var member
: group
.getMembersList()) {
1651 final var address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1652 .toByteArray()), null));
1654 account
.getProfileStore()
1655 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1656 } catch (InvalidInputException ignored
) {
1661 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1662 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1663 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1667 private void retryFailedReceivedMessage(
1668 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1670 var envelope
= cachedMessage
.loadEnvelope();
1671 if (envelope
== null) {
1674 SignalServiceContent content
= null;
1675 if (!envelope
.isReceipt()) {
1677 content
= decryptMessage(envelope
);
1678 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1680 } catch (Exception er
) {
1681 // All other errors are not recoverable, so delete the cached message
1682 cachedMessage
.delete();
1685 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1686 for (var action
: actions
) {
1688 action
.execute(this);
1689 } catch (Throwable e
) {
1690 logger
.warn("Message action failed.", e
);
1695 handler
.handleMessage(envelope
, content
, null);
1696 cachedMessage
.delete();
1699 public void receiveMessages(
1702 boolean returnOnTimeout
,
1703 boolean ignoreAttachments
,
1704 ReceiveMessageHandler handler
1705 ) throws IOException
{
1706 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1708 Set
<HandleAction
> queuedActions
= null;
1710 final var messagePipe
= getOrCreateMessagePipe();
1712 var hasCaughtUpWithOldMessages
= false;
1715 SignalServiceEnvelope envelope
;
1716 SignalServiceContent content
= null;
1717 Exception exception
= null;
1718 final CachedMessage
[] cachedMessage
= {null};
1720 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1721 // store message on disk, before acknowledging receipt to the server
1722 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1724 if (result
.isPresent()) {
1725 envelope
= result
.get();
1727 // Received indicator that server queue is empty
1728 hasCaughtUpWithOldMessages
= true;
1730 if (queuedActions
!= null) {
1731 for (var action
: queuedActions
) {
1733 action
.execute(this);
1734 } catch (Throwable e
) {
1735 logger
.warn("Message action failed.", e
);
1739 queuedActions
.clear();
1740 queuedActions
= null;
1743 // Continue to wait another timeout for new messages
1746 } catch (TimeoutException e
) {
1747 if (returnOnTimeout
) return;
1751 if (envelope
.hasSource()) {
1752 // Store uuid if we don't have it already
1753 var source
= envelope
.getSourceAddress();
1754 resolveSignalServiceAddress(source
);
1756 if (!envelope
.isReceipt()) {
1758 content
= decryptMessage(envelope
);
1759 } catch (Exception e
) {
1762 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1763 if (hasCaughtUpWithOldMessages
) {
1764 for (var action
: actions
) {
1766 action
.execute(this);
1767 } catch (Throwable e
) {
1768 logger
.warn("Message action failed.", e
);
1772 if (queuedActions
== null) {
1773 queuedActions
= new HashSet
<>();
1775 queuedActions
.addAll(actions
);
1779 if (isMessageBlocked(envelope
, content
)) {
1780 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1781 } else if (isNotAGroupMember(envelope
, content
)) {
1782 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1784 handler
.handleMessage(envelope
, content
, exception
);
1786 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1787 if (cachedMessage
[0] != null) {
1788 cachedMessage
[0].delete();
1794 private boolean isMessageBlocked(
1795 SignalServiceEnvelope envelope
, SignalServiceContent content
1797 SignalServiceAddress source
;
1798 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1799 source
= envelope
.getSourceAddress();
1800 } else if (content
!= null) {
1801 source
= content
.getSender();
1805 var sourceContact
= account
.getContactStore().getContact(source
);
1806 if (sourceContact
!= null && sourceContact
.blocked
) {
1810 if (content
!= null && content
.getDataMessage().isPresent()) {
1811 var message
= content
.getDataMessage().get();
1812 if (message
.getGroupContext().isPresent()) {
1813 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1814 var group
= getGroup(groupId
);
1815 if (group
!= null && group
.isBlocked()) {
1823 private boolean isNotAGroupMember(
1824 SignalServiceEnvelope envelope
, SignalServiceContent content
1826 SignalServiceAddress source
;
1827 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1828 source
= envelope
.getSourceAddress();
1829 } else if (content
!= null) {
1830 source
= content
.getSender();
1835 if (content
!= null && content
.getDataMessage().isPresent()) {
1836 var message
= content
.getDataMessage().get();
1837 if (message
.getGroupContext().isPresent()) {
1838 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1839 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1840 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1844 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1845 var group
= getGroup(groupId
);
1846 if (group
!= null && !group
.isMember(source
)) {
1854 private List
<HandleAction
> handleMessage(
1855 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1857 var actions
= new ArrayList
<HandleAction
>();
1858 if (content
!= null) {
1859 final SignalServiceAddress sender
;
1860 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1861 sender
= envelope
.getSourceAddress();
1863 sender
= content
.getSender();
1865 // Store uuid if we don't have it already
1866 resolveSignalServiceAddress(sender
);
1868 if (content
.getDataMessage().isPresent()) {
1869 var message
= content
.getDataMessage().get();
1871 if (content
.isNeedsReceipt()) {
1872 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1875 actions
.addAll(handleSignalServiceDataMessage(message
,
1878 account
.getSelfAddress(),
1879 ignoreAttachments
));
1881 if (content
.getSyncMessage().isPresent()) {
1882 account
.setMultiDevice(true);
1883 var syncMessage
= content
.getSyncMessage().get();
1884 if (syncMessage
.getSent().isPresent()) {
1885 var message
= syncMessage
.getSent().get();
1886 final var destination
= message
.getDestination().orNull();
1887 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1891 ignoreAttachments
));
1893 if (syncMessage
.getRequest().isPresent()) {
1894 var rm
= syncMessage
.getRequest().get();
1895 if (rm
.isContactsRequest()) {
1896 actions
.add(SendSyncContactsAction
.create());
1898 if (rm
.isGroupsRequest()) {
1899 actions
.add(SendSyncGroupsAction
.create());
1901 if (rm
.isBlockedListRequest()) {
1902 actions
.add(SendSyncBlockedListAction
.create());
1904 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1906 if (syncMessage
.getGroups().isPresent()) {
1907 File tmpFile
= null;
1909 tmpFile
= IOUtils
.createTempFile();
1910 final var groupsMessage
= syncMessage
.getGroups().get();
1911 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1912 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1914 while ((g
= s
.read()) != null) {
1915 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1916 if (syncGroup
!= null) {
1917 if (g
.getName().isPresent()) {
1918 syncGroup
.name
= g
.getName().get();
1920 syncGroup
.addMembers(g
.getMembers()
1922 .map(this::resolveSignalServiceAddress
)
1923 .collect(Collectors
.toSet()));
1924 if (!g
.isActive()) {
1925 syncGroup
.removeMember(account
.getSelfAddress());
1927 // Add ourself to the member set as it's marked as active
1928 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1930 syncGroup
.blocked
= g
.isBlocked();
1931 if (g
.getColor().isPresent()) {
1932 syncGroup
.color
= g
.getColor().get();
1935 if (g
.getAvatar().isPresent()) {
1936 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1938 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1939 syncGroup
.archived
= g
.isArchived();
1940 account
.getGroupStore().updateGroup(syncGroup
);
1944 } catch (Exception e
) {
1945 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1949 if (tmpFile
!= null) {
1951 Files
.delete(tmpFile
.toPath());
1952 } catch (IOException e
) {
1953 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1960 if (syncMessage
.getBlockedList().isPresent()) {
1961 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1962 for (var address
: blockedListMessage
.getAddresses()) {
1963 setContactBlocked(resolveSignalServiceAddress(address
), true);
1965 for (var groupId
: blockedListMessage
.getGroupIds()
1967 .map(GroupId
::unknownVersion
)
1968 .collect(Collectors
.toSet())) {
1970 setGroupBlocked(groupId
, true);
1971 } catch (GroupNotFoundException e
) {
1972 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1973 groupId
.toBase64());
1977 if (syncMessage
.getContacts().isPresent()) {
1978 File tmpFile
= null;
1980 tmpFile
= IOUtils
.createTempFile();
1981 final var contactsMessage
= syncMessage
.getContacts().get();
1982 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1983 .asPointer(), tmpFile
)) {
1984 var s
= new DeviceContactsInputStream(attachmentAsStream
);
1985 if (contactsMessage
.isComplete()) {
1986 account
.getContactStore().clear();
1989 while ((c
= s
.read()) != null) {
1990 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1991 account
.setProfileKey(c
.getProfileKey().get());
1993 final var address
= resolveSignalServiceAddress(c
.getAddress());
1994 var contact
= account
.getContactStore().getContact(address
);
1995 if (contact
== null) {
1996 contact
= new ContactInfo(address
);
1998 if (c
.getName().isPresent()) {
1999 contact
.name
= c
.getName().get();
2001 if (c
.getColor().isPresent()) {
2002 contact
.color
= c
.getColor().get();
2004 if (c
.getProfileKey().isPresent()) {
2005 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
2007 if (c
.getVerified().isPresent()) {
2008 final var verifiedMessage
= c
.getVerified().get();
2009 account
.getSignalProtocolStore()
2010 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
2011 verifiedMessage
.getIdentityKey(),
2012 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2014 if (c
.getExpirationTimer().isPresent()) {
2015 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
2017 contact
.blocked
= c
.isBlocked();
2018 contact
.inboxPosition
= c
.getInboxPosition().orNull();
2019 contact
.archived
= c
.isArchived();
2020 account
.getContactStore().updateContact(contact
);
2022 if (c
.getAvatar().isPresent()) {
2023 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2027 } catch (Exception e
) {
2028 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2032 if (tmpFile
!= null) {
2034 Files
.delete(tmpFile
.toPath());
2035 } catch (IOException e
) {
2036 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2043 if (syncMessage
.getVerified().isPresent()) {
2044 final var verifiedMessage
= syncMessage
.getVerified().get();
2045 account
.getSignalProtocolStore()
2046 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2047 verifiedMessage
.getIdentityKey(),
2048 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2050 if (syncMessage
.getStickerPackOperations().isPresent()) {
2051 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2052 for (var m
: stickerPackOperationMessages
) {
2053 if (!m
.getPackId().isPresent()) {
2056 var sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2057 if (sticker
== null) {
2058 if (!m
.getPackKey().isPresent()) {
2061 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2063 sticker
.setInstalled(!m
.getType().isPresent()
2064 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2065 account
.getStickerStore().updateSticker(sticker
);
2068 if (syncMessage
.getFetchType().isPresent()) {
2069 switch (syncMessage
.getFetchType().get()) {
2071 getRecipientProfile(getSelfAddress(), true);
2072 case STORAGE_MANIFEST
:
2076 if (syncMessage
.getKeys().isPresent()) {
2077 final var keysMessage
= syncMessage
.getKeys().get();
2078 if (keysMessage
.getStorageService().isPresent()) {
2079 final var storageKey
= keysMessage
.getStorageService().get();
2080 account
.setStorageKey(storageKey
);
2083 if (syncMessage
.getConfiguration().isPresent()) {
2091 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2093 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2094 } catch (IOException e
) {
2095 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2099 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2101 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2102 } catch (IOException e
) {
2103 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2107 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2109 avatarStore
.storeGroupAvatar(groupId
,
2110 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2111 } catch (IOException e
) {
2112 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2116 private void downloadProfileAvatar(
2117 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2120 avatarStore
.storeProfileAvatar(address
,
2121 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2122 } catch (Throwable e
) {
2123 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2127 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2128 return attachmentStore
.getAttachmentFile(attachmentId
);
2131 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2132 if (!attachment
.isPointer()) {
2133 logger
.warn("Invalid state, can't store an attachment stream.");
2136 var pointer
= attachment
.asPointer();
2137 if (pointer
.getPreview().isPresent()) {
2138 final var preview
= pointer
.getPreview().get();
2140 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2141 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2142 } catch (IOException e
) {
2143 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2148 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2149 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2150 } catch (IOException e
) {
2151 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2155 private void retrieveGroupV2Avatar(
2156 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2157 ) throws IOException
{
2158 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2160 var tmpFile
= IOUtils
.createTempFile();
2161 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2163 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2164 var encryptedData
= IOUtils
.readFully(input
);
2166 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2167 outputStream
.write(decryptedData
);
2170 Files
.delete(tmpFile
.toPath());
2171 } catch (IOException e
) {
2172 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2179 private void retrieveProfileAvatar(
2180 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2181 ) throws IOException
{
2182 var tmpFile
= IOUtils
.createTempFile();
2183 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2186 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2187 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2188 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2191 Files
.delete(tmpFile
.toPath());
2192 } catch (IOException e
) {
2193 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2200 private void retrieveAttachment(
2201 final SignalServiceAttachment attachment
, final OutputStream outputStream
2202 ) throws IOException
{
2203 if (attachment
.isPointer()) {
2204 var pointer
= attachment
.asPointer();
2205 retrieveAttachmentPointer(pointer
, outputStream
);
2207 var stream
= attachment
.asStream();
2208 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2212 private void retrieveAttachmentPointer(
2213 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2214 ) throws IOException
{
2215 var tmpFile
= IOUtils
.createTempFile();
2216 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2217 IOUtils
.copyStream(input
, outputStream
);
2218 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2219 throw new IOException(e
);
2222 Files
.delete(tmpFile
.toPath());
2223 } catch (IOException e
) {
2224 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2231 private InputStream
retrieveAttachmentAsStream(
2232 SignalServiceAttachmentPointer pointer
, File tmpFile
2233 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2234 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2237 void sendGroups() throws IOException
, UntrustedIdentityException
{
2238 var groupsFile
= IOUtils
.createTempFile();
2241 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2242 var out
= new DeviceGroupsOutputStream(fos
);
2243 for (var record : getGroups()) {
2244 if (record instanceof GroupInfoV1
) {
2245 var groupInfo
= (GroupInfoV1
) record;
2246 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2247 Optional
.fromNullable(groupInfo
.name
),
2248 new ArrayList
<>(groupInfo
.getMembers()),
2249 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2250 groupInfo
.isMember(account
.getSelfAddress()),
2251 Optional
.of(groupInfo
.messageExpirationTime
),
2252 Optional
.fromNullable(groupInfo
.color
),
2254 Optional
.fromNullable(groupInfo
.inboxPosition
),
2255 groupInfo
.archived
));
2260 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2261 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2262 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2263 .withStream(groupsFileStream
)
2264 .withContentType("application/octet-stream")
2265 .withLength(groupsFile
.length())
2268 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2273 Files
.delete(groupsFile
.toPath());
2274 } catch (IOException e
) {
2275 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2280 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2281 var contactsFile
= IOUtils
.createTempFile();
2284 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2285 var out
= new DeviceContactsOutputStream(fos
);
2286 for (var record : account
.getContactStore().getContacts()) {
2287 VerifiedMessage verifiedMessage
= null;
2288 var currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2289 if (currentIdentity
!= null) {
2290 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2291 currentIdentity
.getIdentityKey(),
2292 currentIdentity
.getTrustLevel().toVerifiedState(),
2293 currentIdentity
.getDateAdded().getTime());
2296 var profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2297 out
.write(new DeviceContact(record.getAddress(),
2298 Optional
.fromNullable(record.name
),
2299 createContactAvatarAttachment(record.getAddress()),
2300 Optional
.fromNullable(record.color
),
2301 Optional
.fromNullable(verifiedMessage
),
2302 Optional
.fromNullable(profileKey
),
2304 Optional
.of(record.messageExpirationTime
),
2305 Optional
.fromNullable(record.inboxPosition
),
2309 if (account
.getProfileKey() != null) {
2310 // Send our own profile key as well
2311 out
.write(new DeviceContact(account
.getSelfAddress(),
2316 Optional
.of(account
.getProfileKey()),
2324 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2325 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2326 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2327 .withStream(contactsFileStream
)
2328 .withContentType("application/octet-stream")
2329 .withLength(contactsFile
.length())
2332 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2337 Files
.delete(contactsFile
.toPath());
2338 } catch (IOException e
) {
2339 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2344 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2345 var addresses
= new ArrayList
<SignalServiceAddress
>();
2346 for (var record : account
.getContactStore().getContacts()) {
2347 if (record.blocked
) {
2348 addresses
.add(record.getAddress());
2351 var groupIds
= new ArrayList
<byte[]>();
2352 for (var record : getGroups()) {
2353 if (record.isBlocked()) {
2354 groupIds
.add(record.getGroupId().serialize());
2357 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2360 private void sendVerifiedMessage(
2361 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2362 ) throws IOException
, UntrustedIdentityException
{
2363 var verifiedMessage
= new VerifiedMessage(destination
,
2365 trustLevel
.toVerifiedState(),
2366 System
.currentTimeMillis());
2367 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2370 public List
<ContactInfo
> getContacts() {
2371 return account
.getContactStore().getContacts();
2374 public String
getContactOrProfileName(String number
) {
2375 final var address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2377 final var contact
= account
.getContactStore().getContact(address
);
2378 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2379 return contact
.name
;
2382 final var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2383 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2384 return profileEntry
.getProfile().getDisplayName();
2389 public GroupInfo
getGroup(GroupId groupId
) {
2390 final var group
= account
.getGroupStore().getGroup(groupId
);
2391 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2392 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2393 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2394 account
.getGroupStore().updateGroup(group
);
2399 public List
<IdentityInfo
> getIdentities() {
2400 return account
.getSignalProtocolStore().getIdentities();
2403 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2404 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2408 * Trust this the identity with this fingerprint
2410 * @param name username of the identity
2411 * @param fingerprint Fingerprint
2413 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2414 var address
= canonicalizeAndResolveSignalServiceAddress(name
);
2415 return trustIdentity(address
, (identityKey
) -> Arrays
.equals(identityKey
.serialize(), fingerprint
));
2419 * Trust this the identity with this safety number
2421 * @param name username of the identity
2422 * @param safetyNumber Safety number
2424 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2425 var address
= canonicalizeAndResolveSignalServiceAddress(name
);
2426 return trustIdentity(address
, (identityKey
) -> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)));
2429 private boolean trustIdentity(SignalServiceAddress address
, Function
<IdentityKey
, Boolean
> verifier
) {
2430 var ids
= account
.getSignalProtocolStore().getIdentities(address
);
2435 IdentityInfo foundIdentity
= null;
2437 for (var id
: ids
) {
2438 if (verifier
.apply(id
.getIdentityKey())) {
2444 if (foundIdentity
== null) {
2448 account
.getSignalProtocolStore()
2449 .setIdentityTrustLevel(address
, foundIdentity
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2451 sendVerifiedMessage(address
, foundIdentity
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2452 } catch (IOException
| UntrustedIdentityException e
) {
2453 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2456 // Successfully trusted the new identity, now remove all other identities for that number
2457 for (var id
: ids
) {
2458 if (id
== foundIdentity
) {
2461 account
.getSignalProtocolStore().removeIdentity(address
, id
.getIdentityKey());
2469 * Trust all keys of this identity without verification
2471 * @param name username of the identity
2473 public boolean trustIdentityAllKeys(String name
) {
2474 var address
= resolveSignalServiceAddress(name
);
2475 var ids
= account
.getSignalProtocolStore().getIdentities(address
);
2479 for (var id
: ids
) {
2480 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2481 account
.getSignalProtocolStore()
2482 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2484 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2485 } catch (IOException
| UntrustedIdentityException e
) {
2486 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2494 public String
computeSafetyNumber(
2495 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2497 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2498 account
.getSelfAddress(),
2499 getIdentityKeyPair().getPublicKey(),
2504 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2505 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2507 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2508 return resolveSignalServiceAddress(canonicalizedNumber
);
2511 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2512 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2514 return resolveSignalServiceAddress(address
);
2517 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2518 if (address
.matches(account
.getSelfAddress())) {
2519 return account
.getSelfAddress();
2522 return account
.getRecipientStore().resolveServiceAddress(address
);
2526 public void close() throws IOException
{
2530 void close(boolean closeAccount
) throws IOException
{
2531 executor
.shutdown();
2533 if (messagePipe
!= null) {
2534 messagePipe
.shutdown();
2538 if (unidentifiedMessagePipe
!= null) {
2539 unidentifiedMessagePipe
.shutdown();
2540 unidentifiedMessagePipe
= null;
2543 if (closeAccount
&& account
!= null) {
2549 public interface ReceiveMessageHandler
{
2551 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);