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
.getSignalProtocolStore().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
.getSignalProtocolStore().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
>> sendMessageReaction(
996 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
997 ) throws IOException
, InvalidNumberException
{
998 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1000 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1001 targetSentTimestamp
);
1002 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1003 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1006 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1007 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1009 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1011 return sendMessage(messageBuilder
, signalServiceAddresses
);
1012 } catch (Exception e
) {
1013 for (var address
: signalServiceAddresses
) {
1014 handleEndSession(address
);
1021 public String
getContactName(String number
) throws InvalidNumberException
{
1022 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1023 if (contact
== null) {
1026 return contact
.name
;
1030 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1031 final var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1032 var contact
= account
.getContactStore().getContact(address
);
1033 if (contact
== null) {
1034 contact
= new ContactInfo(address
);
1036 contact
.name
= name
;
1037 account
.getContactStore().updateContact(contact
);
1041 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1042 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1045 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1046 var contact
= account
.getContactStore().getContact(address
);
1047 if (contact
== null) {
1048 contact
= new ContactInfo(address
);
1050 contact
.blocked
= blocked
;
1051 account
.getContactStore().updateContact(contact
);
1055 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1056 var group
= getGroup(groupId
);
1057 if (group
== null) {
1058 throw new GroupNotFoundException(groupId
);
1061 group
.setBlocked(blocked
);
1062 account
.getGroupStore().updateGroup(group
);
1067 * Change the expiration timer for a contact
1069 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1070 var contact
= account
.getContactStore().getContact(address
);
1071 contact
.messageExpirationTime
= messageExpirationTimer
;
1072 account
.getContactStore().updateContact(contact
);
1073 sendExpirationTimerUpdate(address
);
1077 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1078 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1079 sendMessage(messageBuilder
, List
.of(address
));
1083 * Change the expiration timer for a contact
1085 public void setExpirationTimer(
1086 String number
, int messageExpirationTimer
1087 ) throws IOException
, InvalidNumberException
{
1088 var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1089 setExpirationTimer(address
, messageExpirationTimer
);
1093 * Change the expiration timer for a group
1095 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1096 var g
= getGroup(groupId
);
1097 if (g
instanceof GroupInfoV1
) {
1098 var groupInfoV1
= (GroupInfoV1
) g
;
1099 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1100 account
.getGroupStore().updateGroup(groupInfoV1
);
1102 throw new RuntimeException("TODO Not implemented!");
1107 * Upload the sticker pack from path.
1109 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1110 * @return if successful, returns the URL to install the sticker pack in the signal app
1112 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1113 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1115 var messageSender
= createMessageSender();
1117 var packKey
= KeyUtils
.createStickerUploadKey();
1118 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1120 var sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1121 account
.getStickerStore().updateSticker(sticker
);
1125 return new URI("https",
1128 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1129 Hex
.toStringCondensed(packKey
),
1130 StandardCharsets
.UTF_8
)).toString();
1131 } catch (URISyntaxException e
) {
1132 throw new AssertionError(e
);
1136 void requestSyncGroups() throws IOException
{
1137 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1138 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1140 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1142 sendSyncMessage(message
);
1143 } catch (UntrustedIdentityException e
) {
1144 throw new AssertionError(e
);
1148 void requestSyncContacts() throws IOException
{
1149 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1150 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1152 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1154 sendSyncMessage(message
);
1155 } catch (UntrustedIdentityException e
) {
1156 throw new AssertionError(e
);
1160 void requestSyncBlocked() throws IOException
{
1161 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1162 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1164 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1166 sendSyncMessage(message
);
1167 } catch (UntrustedIdentityException e
) {
1168 throw new AssertionError(e
);
1172 void requestSyncConfiguration() throws IOException
{
1173 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1174 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1176 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1178 sendSyncMessage(message
);
1179 } catch (UntrustedIdentityException e
) {
1180 throw new AssertionError(e
);
1184 void requestSyncKeys() throws IOException
{
1185 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1186 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1188 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1190 sendSyncMessage(message
);
1191 } catch (UntrustedIdentityException e
) {
1192 throw new AssertionError(e
);
1196 private byte[] getSenderCertificate() {
1197 // TODO support UUID capable sender certificates
1198 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1201 certificate
= accountManager
.getSenderCertificate();
1202 } catch (IOException e
) {
1203 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1206 // TODO cache for a day
1210 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1211 var messageSender
= createMessageSender();
1213 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1214 } catch (UntrustedIdentityException e
) {
1215 if (e
.getIdentityKey() != null) {
1216 account
.getSignalProtocolStore()
1217 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1219 TrustLevel
.UNTRUSTED
);
1225 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1226 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1227 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1229 for (var number
: numbers
) {
1230 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1231 if (resolvedAddress
.getUuid().isPresent()) {
1232 signalServiceAddresses
.add(resolvedAddress
);
1234 addressesMissingUuid
.add(resolvedAddress
);
1238 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1239 .map(a
-> a
.getNumber().get())
1240 .collect(Collectors
.toSet());
1241 Map
<String
, UUID
> registeredUsers
;
1243 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1244 } catch (IOException e
) {
1245 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1246 registeredUsers
= Map
.of();
1249 for (var address
: addressesMissingUuid
) {
1250 final var number
= address
.getNumber().get();
1251 if (registeredUsers
.containsKey(number
)) {
1252 final var newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(registeredUsers
.get(number
),
1254 signalServiceAddresses
.add(newAddress
);
1256 signalServiceAddresses
.add(address
);
1260 return signalServiceAddresses
;
1263 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1265 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1267 serviceEnvironmentConfig
.getCdsMrenclave());
1268 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1269 throw new IOException(e
);
1273 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1274 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1275 ) throws IOException
{
1276 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1277 final var timestamp
= System
.currentTimeMillis();
1278 messageBuilder
.withTimestamp(timestamp
);
1279 getOrCreateMessagePipe();
1280 getOrCreateUnidentifiedMessagePipe();
1281 SignalServiceDataMessage message
= null;
1283 message
= messageBuilder
.build();
1284 if (message
.getGroupContext().isPresent()) {
1286 var messageSender
= createMessageSender();
1287 final var isRecipientUpdate
= false;
1288 var result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1289 unidentifiedAccessHelper
.getAccessFor(recipients
),
1292 for (var r
: result
) {
1293 if (r
.getIdentityFailure() != null) {
1294 account
.getSignalProtocolStore()
1295 .saveIdentity(r
.getAddress(),
1296 r
.getIdentityFailure().getIdentityKey(),
1297 TrustLevel
.UNTRUSTED
);
1300 return new Pair
<>(timestamp
, result
);
1301 } catch (UntrustedIdentityException e
) {
1302 if (e
.getIdentityKey() != null) {
1303 account
.getSignalProtocolStore()
1304 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1306 TrustLevel
.UNTRUSTED
);
1308 return new Pair
<>(timestamp
, List
.of());
1311 // Send to all individually, so sync messages are sent correctly
1312 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1313 var results
= new ArrayList
<SendMessageResult
>(recipients
.size());
1314 for (var address
: recipients
) {
1315 final var contact
= account
.getContactStore().getContact(address
);
1316 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1317 messageBuilder
.withExpiration(expirationTime
);
1318 message
= messageBuilder
.build();
1319 results
.add(sendMessage(address
, message
));
1321 return new Pair
<>(timestamp
, results
);
1324 if (message
!= null && message
.isEndSession()) {
1325 for (var recipient
: recipients
) {
1326 handleEndSession(recipient
);
1333 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1334 SignalServiceDataMessage
.Builder messageBuilder
1335 ) throws IOException
{
1336 final var timestamp
= System
.currentTimeMillis();
1337 messageBuilder
.withTimestamp(timestamp
);
1338 getOrCreateMessagePipe();
1339 getOrCreateUnidentifiedMessagePipe();
1341 final var address
= getSelfAddress();
1343 final var contact
= account
.getContactStore().getContact(address
);
1344 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1345 messageBuilder
.withExpiration(expirationTime
);
1347 var message
= messageBuilder
.build();
1348 final var result
= sendSelfMessage(message
);
1349 return new Pair
<>(timestamp
, result
);
1355 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1356 var messageSender
= createMessageSender();
1358 var recipient
= account
.getSelfAddress();
1360 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1361 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1362 message
.getTimestamp(),
1364 message
.getExpiresInSeconds(),
1365 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1367 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1370 var startTime
= System
.currentTimeMillis();
1371 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1372 return SendMessageResult
.success(recipient
,
1373 unidentifiedAccess
.isPresent(),
1375 System
.currentTimeMillis() - startTime
);
1376 } catch (UntrustedIdentityException e
) {
1377 if (e
.getIdentityKey() != null) {
1378 account
.getSignalProtocolStore()
1379 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1381 TrustLevel
.UNTRUSTED
);
1383 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1387 private SendMessageResult
sendMessage(
1388 SignalServiceAddress address
, SignalServiceDataMessage message
1389 ) throws IOException
{
1390 var messageSender
= createMessageSender();
1393 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1394 } catch (UntrustedIdentityException e
) {
1395 if (e
.getIdentityKey() != null) {
1396 account
.getSignalProtocolStore()
1397 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1399 TrustLevel
.UNTRUSTED
);
1401 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1405 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1406 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1407 account
.getSignalProtocolStore(),
1408 certificateValidator
);
1410 return cipher
.decrypt(envelope
);
1411 } catch (ProtocolUntrustedIdentityException e
) {
1412 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1413 var identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1414 final var untrustedIdentity
= identityException
.getUntrustedIdentity();
1415 if (untrustedIdentity
!= null) {
1416 account
.getSignalProtocolStore()
1417 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1419 TrustLevel
.UNTRUSTED
);
1421 throw identityException
;
1423 throw new AssertionError(e
);
1427 private void handleEndSession(SignalServiceAddress source
) {
1428 account
.getSignalProtocolStore().deleteAllSessions(source
);
1431 private List
<HandleAction
> handleSignalServiceDataMessage(
1432 SignalServiceDataMessage message
,
1434 SignalServiceAddress source
,
1435 SignalServiceAddress destination
,
1436 boolean ignoreAttachments
1438 var actions
= new ArrayList
<HandleAction
>();
1439 if (message
.getGroupContext().isPresent()) {
1440 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1441 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1442 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1443 var group
= getGroup(groupId
);
1444 if (group
== null || group
instanceof GroupInfoV1
) {
1445 var groupV1
= (GroupInfoV1
) group
;
1446 switch (groupInfo
.getType()) {
1448 if (groupV1
== null) {
1449 groupV1
= new GroupInfoV1(groupId
);
1452 if (groupInfo
.getAvatar().isPresent()) {
1453 var avatar
= groupInfo
.getAvatar().get();
1454 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1457 if (groupInfo
.getName().isPresent()) {
1458 groupV1
.name
= groupInfo
.getName().get();
1461 if (groupInfo
.getMembers().isPresent()) {
1462 groupV1
.addMembers(groupInfo
.getMembers()
1465 .map(this::resolveSignalServiceAddress
)
1466 .collect(Collectors
.toSet()));
1469 account
.getGroupStore().updateGroup(groupV1
);
1473 if (groupV1
== null && !isSync
) {
1474 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1478 if (groupV1
!= null) {
1479 groupV1
.removeMember(source
);
1480 account
.getGroupStore().updateGroup(groupV1
);
1485 if (groupV1
!= null && !isSync
) {
1486 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1491 // Received a group v1 message for a v2 group
1494 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1495 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1496 final var groupMasterKey
= groupContext
.getMasterKey();
1498 getOrMigrateGroup(groupMasterKey
,
1499 groupContext
.getRevision(),
1500 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1504 final var conversationPartnerAddress
= isSync ? destination
: source
;
1505 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1506 handleEndSession(conversationPartnerAddress
);
1508 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1509 if (message
.getGroupContext().isPresent()) {
1510 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1511 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1512 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1513 if (group
!= null) {
1514 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1515 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1516 account
.getGroupStore().updateGroup(group
);
1519 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1520 // disappearing message timer already stored in the DecryptedGroup
1522 } else if (conversationPartnerAddress
!= null) {
1523 var contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1524 if (contact
== null) {
1525 contact
= new ContactInfo(conversationPartnerAddress
);
1527 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1528 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1529 account
.getContactStore().updateContact(contact
);
1533 if (!ignoreAttachments
) {
1534 if (message
.getAttachments().isPresent()) {
1535 for (var attachment
: message
.getAttachments().get()) {
1536 downloadAttachment(attachment
);
1539 if (message
.getSharedContacts().isPresent()) {
1540 for (var contact
: message
.getSharedContacts().get()) {
1541 if (contact
.getAvatar().isPresent()) {
1542 downloadAttachment(contact
.getAvatar().get().getAttachment());
1547 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1548 final ProfileKey profileKey
;
1550 profileKey
= new ProfileKey(message
.getProfileKey().get());
1551 } catch (InvalidInputException e
) {
1552 throw new AssertionError(e
);
1554 if (source
.matches(account
.getSelfAddress())) {
1555 this.account
.setProfileKey(profileKey
);
1557 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1559 if (message
.getPreviews().isPresent()) {
1560 final var previews
= message
.getPreviews().get();
1561 for (var preview
: previews
) {
1562 if (preview
.getImage().isPresent()) {
1563 downloadAttachment(preview
.getImage().get());
1567 if (message
.getQuote().isPresent()) {
1568 final var quote
= message
.getQuote().get();
1570 for (var quotedAttachment
: quote
.getAttachments()) {
1571 final var thumbnail
= quotedAttachment
.getThumbnail();
1572 if (thumbnail
!= null) {
1573 downloadAttachment(thumbnail
);
1577 if (message
.getSticker().isPresent()) {
1578 final var messageSticker
= message
.getSticker().get();
1579 var sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1580 if (sticker
== null) {
1581 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1582 account
.getStickerStore().updateSticker(sticker
);
1588 private GroupInfoV2
getOrMigrateGroup(
1589 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1591 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1593 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1594 var groupInfo
= getGroup(groupId
);
1595 final GroupInfoV2 groupInfoV2
;
1596 if (groupInfo
instanceof GroupInfoV1
) {
1597 // Received a v2 group message for a v1 group, we need to locally migrate the group
1598 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1599 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1600 logger
.info("Locally migrated group {} to group v2, id: {}",
1601 groupInfo
.getGroupId().toBase64(),
1602 groupInfoV2
.getGroupId().toBase64());
1603 } else if (groupInfo
instanceof GroupInfoV2
) {
1604 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1606 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1609 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1610 DecryptedGroup group
= null;
1611 if (signedGroupChange
!= null
1612 && groupInfoV2
.getGroup() != null
1613 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1614 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1616 if (group
== null) {
1617 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1619 if (group
!= null) {
1620 storeProfileKeysFromMembers(group
);
1621 final var avatar
= group
.getAvatar();
1622 if (avatar
!= null && !avatar
.isEmpty()) {
1623 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1626 groupInfoV2
.setGroup(group
);
1627 account
.getGroupStore().updateGroup(groupInfoV2
);
1633 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1634 for (var member
: group
.getMembersList()) {
1635 final var address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1636 .toByteArray()), null));
1638 account
.getProfileStore()
1639 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1640 } catch (InvalidInputException ignored
) {
1645 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1646 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1647 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1651 private void retryFailedReceivedMessage(
1652 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1654 var envelope
= cachedMessage
.loadEnvelope();
1655 if (envelope
== null) {
1658 SignalServiceContent content
= null;
1659 if (!envelope
.isReceipt()) {
1661 content
= decryptMessage(envelope
);
1662 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1664 } catch (Exception er
) {
1665 // All other errors are not recoverable, so delete the cached message
1666 cachedMessage
.delete();
1669 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1670 for (var action
: actions
) {
1672 action
.execute(this);
1673 } catch (Throwable e
) {
1674 logger
.warn("Message action failed.", e
);
1679 handler
.handleMessage(envelope
, content
, null);
1680 cachedMessage
.delete();
1683 public void receiveMessages(
1686 boolean returnOnTimeout
,
1687 boolean ignoreAttachments
,
1688 ReceiveMessageHandler handler
1689 ) throws IOException
{
1690 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1692 Set
<HandleAction
> queuedActions
= null;
1694 final var messagePipe
= getOrCreateMessagePipe();
1696 var hasCaughtUpWithOldMessages
= false;
1699 SignalServiceEnvelope envelope
;
1700 SignalServiceContent content
= null;
1701 Exception exception
= null;
1702 final CachedMessage
[] cachedMessage
= {null};
1704 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1705 // store message on disk, before acknowledging receipt to the server
1706 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1708 if (result
.isPresent()) {
1709 envelope
= result
.get();
1711 // Received indicator that server queue is empty
1712 hasCaughtUpWithOldMessages
= true;
1714 if (queuedActions
!= null) {
1715 for (var action
: queuedActions
) {
1717 action
.execute(this);
1718 } catch (Throwable e
) {
1719 logger
.warn("Message action failed.", e
);
1723 queuedActions
.clear();
1724 queuedActions
= null;
1727 // Continue to wait another timeout for new messages
1730 } catch (TimeoutException e
) {
1731 if (returnOnTimeout
) return;
1735 if (envelope
.hasSource()) {
1736 // Store uuid if we don't have it already
1737 var source
= envelope
.getSourceAddress();
1738 resolveSignalServiceAddress(source
);
1740 if (!envelope
.isReceipt()) {
1742 content
= decryptMessage(envelope
);
1743 } catch (Exception e
) {
1746 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1747 if (hasCaughtUpWithOldMessages
) {
1748 for (var action
: actions
) {
1750 action
.execute(this);
1751 } catch (Throwable e
) {
1752 logger
.warn("Message action failed.", e
);
1756 if (queuedActions
== null) {
1757 queuedActions
= new HashSet
<>();
1759 queuedActions
.addAll(actions
);
1763 if (isMessageBlocked(envelope
, content
)) {
1764 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1765 } else if (isNotAGroupMember(envelope
, content
)) {
1766 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1768 handler
.handleMessage(envelope
, content
, exception
);
1770 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1771 if (cachedMessage
[0] != null) {
1772 cachedMessage
[0].delete();
1778 private boolean isMessageBlocked(
1779 SignalServiceEnvelope envelope
, SignalServiceContent content
1781 SignalServiceAddress source
;
1782 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1783 source
= envelope
.getSourceAddress();
1784 } else if (content
!= null) {
1785 source
= content
.getSender();
1789 var sourceContact
= account
.getContactStore().getContact(source
);
1790 if (sourceContact
!= null && sourceContact
.blocked
) {
1794 if (content
!= null && content
.getDataMessage().isPresent()) {
1795 var message
= content
.getDataMessage().get();
1796 if (message
.getGroupContext().isPresent()) {
1797 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1798 var group
= getGroup(groupId
);
1799 if (group
!= null && group
.isBlocked()) {
1807 private boolean isNotAGroupMember(
1808 SignalServiceEnvelope envelope
, SignalServiceContent content
1810 SignalServiceAddress source
;
1811 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1812 source
= envelope
.getSourceAddress();
1813 } else if (content
!= null) {
1814 source
= content
.getSender();
1819 if (content
!= null && content
.getDataMessage().isPresent()) {
1820 var message
= content
.getDataMessage().get();
1821 if (message
.getGroupContext().isPresent()) {
1822 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1823 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1824 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1828 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1829 var group
= getGroup(groupId
);
1830 if (group
!= null && !group
.isMember(source
)) {
1838 private List
<HandleAction
> handleMessage(
1839 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1841 var actions
= new ArrayList
<HandleAction
>();
1842 if (content
!= null) {
1843 final SignalServiceAddress sender
;
1844 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1845 sender
= envelope
.getSourceAddress();
1847 sender
= content
.getSender();
1849 // Store uuid if we don't have it already
1850 resolveSignalServiceAddress(sender
);
1852 if (content
.getDataMessage().isPresent()) {
1853 var message
= content
.getDataMessage().get();
1855 if (content
.isNeedsReceipt()) {
1856 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1859 actions
.addAll(handleSignalServiceDataMessage(message
,
1862 account
.getSelfAddress(),
1863 ignoreAttachments
));
1865 if (content
.getSyncMessage().isPresent()) {
1866 account
.setMultiDevice(true);
1867 var syncMessage
= content
.getSyncMessage().get();
1868 if (syncMessage
.getSent().isPresent()) {
1869 var message
= syncMessage
.getSent().get();
1870 final var destination
= message
.getDestination().orNull();
1871 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1875 ignoreAttachments
));
1877 if (syncMessage
.getRequest().isPresent()) {
1878 var rm
= syncMessage
.getRequest().get();
1879 if (rm
.isContactsRequest()) {
1880 actions
.add(SendSyncContactsAction
.create());
1882 if (rm
.isGroupsRequest()) {
1883 actions
.add(SendSyncGroupsAction
.create());
1885 if (rm
.isBlockedListRequest()) {
1886 actions
.add(SendSyncBlockedListAction
.create());
1888 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1890 if (syncMessage
.getGroups().isPresent()) {
1891 File tmpFile
= null;
1893 tmpFile
= IOUtils
.createTempFile();
1894 final var groupsMessage
= syncMessage
.getGroups().get();
1895 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1896 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1898 while ((g
= s
.read()) != null) {
1899 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1900 if (syncGroup
!= null) {
1901 if (g
.getName().isPresent()) {
1902 syncGroup
.name
= g
.getName().get();
1904 syncGroup
.addMembers(g
.getMembers()
1906 .map(this::resolveSignalServiceAddress
)
1907 .collect(Collectors
.toSet()));
1908 if (!g
.isActive()) {
1909 syncGroup
.removeMember(account
.getSelfAddress());
1911 // Add ourself to the member set as it's marked as active
1912 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1914 syncGroup
.blocked
= g
.isBlocked();
1915 if (g
.getColor().isPresent()) {
1916 syncGroup
.color
= g
.getColor().get();
1919 if (g
.getAvatar().isPresent()) {
1920 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1922 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1923 syncGroup
.archived
= g
.isArchived();
1924 account
.getGroupStore().updateGroup(syncGroup
);
1928 } catch (Exception e
) {
1929 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1933 if (tmpFile
!= null) {
1935 Files
.delete(tmpFile
.toPath());
1936 } catch (IOException e
) {
1937 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1944 if (syncMessage
.getBlockedList().isPresent()) {
1945 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1946 for (var address
: blockedListMessage
.getAddresses()) {
1947 setContactBlocked(resolveSignalServiceAddress(address
), true);
1949 for (var groupId
: blockedListMessage
.getGroupIds()
1951 .map(GroupId
::unknownVersion
)
1952 .collect(Collectors
.toSet())) {
1954 setGroupBlocked(groupId
, true);
1955 } catch (GroupNotFoundException e
) {
1956 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1957 groupId
.toBase64());
1961 if (syncMessage
.getContacts().isPresent()) {
1962 File tmpFile
= null;
1964 tmpFile
= IOUtils
.createTempFile();
1965 final var contactsMessage
= syncMessage
.getContacts().get();
1966 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1967 .asPointer(), tmpFile
)) {
1968 var s
= new DeviceContactsInputStream(attachmentAsStream
);
1969 if (contactsMessage
.isComplete()) {
1970 account
.getContactStore().clear();
1973 while ((c
= s
.read()) != null) {
1974 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1975 account
.setProfileKey(c
.getProfileKey().get());
1977 final var address
= resolveSignalServiceAddress(c
.getAddress());
1978 var contact
= account
.getContactStore().getContact(address
);
1979 if (contact
== null) {
1980 contact
= new ContactInfo(address
);
1982 if (c
.getName().isPresent()) {
1983 contact
.name
= c
.getName().get();
1985 if (c
.getColor().isPresent()) {
1986 contact
.color
= c
.getColor().get();
1988 if (c
.getProfileKey().isPresent()) {
1989 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1991 if (c
.getVerified().isPresent()) {
1992 final var verifiedMessage
= c
.getVerified().get();
1993 account
.getSignalProtocolStore()
1994 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1995 verifiedMessage
.getIdentityKey(),
1996 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1998 if (c
.getExpirationTimer().isPresent()) {
1999 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
2001 contact
.blocked
= c
.isBlocked();
2002 contact
.inboxPosition
= c
.getInboxPosition().orNull();
2003 contact
.archived
= c
.isArchived();
2004 account
.getContactStore().updateContact(contact
);
2006 if (c
.getAvatar().isPresent()) {
2007 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2011 } catch (Exception e
) {
2012 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2016 if (tmpFile
!= null) {
2018 Files
.delete(tmpFile
.toPath());
2019 } catch (IOException e
) {
2020 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2027 if (syncMessage
.getVerified().isPresent()) {
2028 final var verifiedMessage
= syncMessage
.getVerified().get();
2029 account
.getSignalProtocolStore()
2030 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2031 verifiedMessage
.getIdentityKey(),
2032 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2034 if (syncMessage
.getStickerPackOperations().isPresent()) {
2035 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2036 for (var m
: stickerPackOperationMessages
) {
2037 if (!m
.getPackId().isPresent()) {
2040 var sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2041 if (sticker
== null) {
2042 if (!m
.getPackKey().isPresent()) {
2045 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2047 sticker
.setInstalled(!m
.getType().isPresent()
2048 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2049 account
.getStickerStore().updateSticker(sticker
);
2052 if (syncMessage
.getFetchType().isPresent()) {
2053 switch (syncMessage
.getFetchType().get()) {
2055 getRecipientProfile(getSelfAddress(), true);
2056 case STORAGE_MANIFEST
:
2060 if (syncMessage
.getKeys().isPresent()) {
2061 final var keysMessage
= syncMessage
.getKeys().get();
2062 if (keysMessage
.getStorageService().isPresent()) {
2063 final var storageKey
= keysMessage
.getStorageService().get();
2064 account
.setStorageKey(storageKey
);
2067 if (syncMessage
.getConfiguration().isPresent()) {
2075 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2077 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2078 } catch (IOException e
) {
2079 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2083 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2085 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2086 } catch (IOException e
) {
2087 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2091 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2093 avatarStore
.storeGroupAvatar(groupId
,
2094 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2095 } catch (IOException e
) {
2096 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2100 private void downloadProfileAvatar(
2101 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2104 avatarStore
.storeProfileAvatar(address
,
2105 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2106 } catch (Throwable e
) {
2107 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2111 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2112 return attachmentStore
.getAttachmentFile(attachmentId
);
2115 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2116 if (!attachment
.isPointer()) {
2117 logger
.warn("Invalid state, can't store an attachment stream.");
2120 var pointer
= attachment
.asPointer();
2121 if (pointer
.getPreview().isPresent()) {
2122 final var preview
= pointer
.getPreview().get();
2124 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2125 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2126 } catch (IOException e
) {
2127 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2132 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2133 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2134 } catch (IOException e
) {
2135 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2139 private void retrieveGroupV2Avatar(
2140 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2141 ) throws IOException
{
2142 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2144 var tmpFile
= IOUtils
.createTempFile();
2145 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2147 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2148 var encryptedData
= IOUtils
.readFully(input
);
2150 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2151 outputStream
.write(decryptedData
);
2154 Files
.delete(tmpFile
.toPath());
2155 } catch (IOException e
) {
2156 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2163 private void retrieveProfileAvatar(
2164 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2165 ) throws IOException
{
2166 var tmpFile
= IOUtils
.createTempFile();
2167 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2170 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2171 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2172 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2175 Files
.delete(tmpFile
.toPath());
2176 } catch (IOException e
) {
2177 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2184 private void retrieveAttachment(
2185 final SignalServiceAttachment attachment
, final OutputStream outputStream
2186 ) throws IOException
{
2187 if (attachment
.isPointer()) {
2188 var pointer
= attachment
.asPointer();
2189 retrieveAttachmentPointer(pointer
, outputStream
);
2191 var stream
= attachment
.asStream();
2192 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2196 private void retrieveAttachmentPointer(
2197 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2198 ) throws IOException
{
2199 var tmpFile
= IOUtils
.createTempFile();
2200 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2201 IOUtils
.copyStream(input
, outputStream
);
2202 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2203 throw new IOException(e
);
2206 Files
.delete(tmpFile
.toPath());
2207 } catch (IOException e
) {
2208 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2215 private InputStream
retrieveAttachmentAsStream(
2216 SignalServiceAttachmentPointer pointer
, File tmpFile
2217 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2218 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2221 void sendGroups() throws IOException
, UntrustedIdentityException
{
2222 var groupsFile
= IOUtils
.createTempFile();
2225 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2226 var out
= new DeviceGroupsOutputStream(fos
);
2227 for (var record : getGroups()) {
2228 if (record instanceof GroupInfoV1
) {
2229 var groupInfo
= (GroupInfoV1
) record;
2230 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2231 Optional
.fromNullable(groupInfo
.name
),
2232 new ArrayList
<>(groupInfo
.getMembers()),
2233 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2234 groupInfo
.isMember(account
.getSelfAddress()),
2235 Optional
.of(groupInfo
.messageExpirationTime
),
2236 Optional
.fromNullable(groupInfo
.color
),
2238 Optional
.fromNullable(groupInfo
.inboxPosition
),
2239 groupInfo
.archived
));
2244 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2245 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2246 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2247 .withStream(groupsFileStream
)
2248 .withContentType("application/octet-stream")
2249 .withLength(groupsFile
.length())
2252 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2257 Files
.delete(groupsFile
.toPath());
2258 } catch (IOException e
) {
2259 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2264 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2265 var contactsFile
= IOUtils
.createTempFile();
2268 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2269 var out
= new DeviceContactsOutputStream(fos
);
2270 for (var record : account
.getContactStore().getContacts()) {
2271 VerifiedMessage verifiedMessage
= null;
2272 var currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2273 if (currentIdentity
!= null) {
2274 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2275 currentIdentity
.getIdentityKey(),
2276 currentIdentity
.getTrustLevel().toVerifiedState(),
2277 currentIdentity
.getDateAdded().getTime());
2280 var profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2281 out
.write(new DeviceContact(record.getAddress(),
2282 Optional
.fromNullable(record.name
),
2283 createContactAvatarAttachment(record.getAddress()),
2284 Optional
.fromNullable(record.color
),
2285 Optional
.fromNullable(verifiedMessage
),
2286 Optional
.fromNullable(profileKey
),
2288 Optional
.of(record.messageExpirationTime
),
2289 Optional
.fromNullable(record.inboxPosition
),
2293 if (account
.getProfileKey() != null) {
2294 // Send our own profile key as well
2295 out
.write(new DeviceContact(account
.getSelfAddress(),
2300 Optional
.of(account
.getProfileKey()),
2308 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2309 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2310 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2311 .withStream(contactsFileStream
)
2312 .withContentType("application/octet-stream")
2313 .withLength(contactsFile
.length())
2316 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2321 Files
.delete(contactsFile
.toPath());
2322 } catch (IOException e
) {
2323 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2328 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2329 var addresses
= new ArrayList
<SignalServiceAddress
>();
2330 for (var record : account
.getContactStore().getContacts()) {
2331 if (record.blocked
) {
2332 addresses
.add(record.getAddress());
2335 var groupIds
= new ArrayList
<byte[]>();
2336 for (var record : getGroups()) {
2337 if (record.isBlocked()) {
2338 groupIds
.add(record.getGroupId().serialize());
2341 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2344 private void sendVerifiedMessage(
2345 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2346 ) throws IOException
, UntrustedIdentityException
{
2347 var verifiedMessage
= new VerifiedMessage(destination
,
2349 trustLevel
.toVerifiedState(),
2350 System
.currentTimeMillis());
2351 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2354 public List
<ContactInfo
> getContacts() {
2355 return account
.getContactStore().getContacts();
2358 public String
getContactOrProfileName(String number
) {
2359 final var address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2361 final var contact
= account
.getContactStore().getContact(address
);
2362 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2363 return contact
.name
;
2366 final var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2367 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2368 return profileEntry
.getProfile().getDisplayName();
2373 public GroupInfo
getGroup(GroupId groupId
) {
2374 final var group
= account
.getGroupStore().getGroup(groupId
);
2375 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2376 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2377 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2378 account
.getGroupStore().updateGroup(group
);
2383 public List
<IdentityInfo
> getIdentities() {
2384 return account
.getSignalProtocolStore().getIdentities();
2387 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2388 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2392 * Trust this the identity with this fingerprint
2394 * @param name username of the identity
2395 * @param fingerprint Fingerprint
2397 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2398 var address
= canonicalizeAndResolveSignalServiceAddress(name
);
2399 return trustIdentity(address
, (identityKey
) -> Arrays
.equals(identityKey
.serialize(), fingerprint
));
2403 * Trust this the identity with this safety number
2405 * @param name username of the identity
2406 * @param safetyNumber Safety number
2408 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2409 var address
= canonicalizeAndResolveSignalServiceAddress(name
);
2410 return trustIdentity(address
, (identityKey
) -> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)));
2413 private boolean trustIdentity(SignalServiceAddress address
, Function
<IdentityKey
, Boolean
> verifier
) {
2414 var ids
= account
.getSignalProtocolStore().getIdentities(address
);
2419 IdentityInfo foundIdentity
= null;
2421 for (var id
: ids
) {
2422 if (verifier
.apply(id
.getIdentityKey())) {
2428 if (foundIdentity
== null) {
2432 account
.getSignalProtocolStore()
2433 .setIdentityTrustLevel(address
, foundIdentity
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2435 sendVerifiedMessage(address
, foundIdentity
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2436 } catch (IOException
| UntrustedIdentityException e
) {
2437 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2440 // Successfully trusted the new identity, now remove all other identities for that number
2441 for (var id
: ids
) {
2442 if (id
== foundIdentity
) {
2445 account
.getSignalProtocolStore().removeIdentity(address
, id
.getIdentityKey());
2453 * Trust all keys of this identity without verification
2455 * @param name username of the identity
2457 public boolean trustIdentityAllKeys(String name
) {
2458 var address
= resolveSignalServiceAddress(name
);
2459 var ids
= account
.getSignalProtocolStore().getIdentities(address
);
2463 for (var id
: ids
) {
2464 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2465 account
.getSignalProtocolStore()
2466 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2468 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2469 } catch (IOException
| UntrustedIdentityException e
) {
2470 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2478 public String
computeSafetyNumber(
2479 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2481 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2482 account
.getSelfAddress(),
2483 getIdentityKeyPair().getPublicKey(),
2488 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2489 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2491 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2492 return resolveSignalServiceAddress(canonicalizedNumber
);
2495 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2496 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2498 return resolveSignalServiceAddress(address
);
2501 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2502 if (address
.matches(account
.getSelfAddress())) {
2503 return account
.getSelfAddress();
2506 return account
.getRecipientStore().resolveServiceAddress(address
);
2510 public void close() throws IOException
{
2514 void close(boolean closeAccount
) throws IOException
{
2515 executor
.shutdown();
2517 if (messagePipe
!= null) {
2518 messagePipe
.shutdown();
2522 if (unidentifiedMessagePipe
!= null) {
2523 unidentifiedMessagePipe
.shutdown();
2524 unidentifiedMessagePipe
= null;
2527 if (closeAccount
&& account
!= null) {
2533 public interface ReceiveMessageHandler
{
2535 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);