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
.stream
.Collectors
;
161 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
163 public class Manager
implements Closeable
{
165 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
167 private final CertificateValidator certificateValidator
;
169 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
170 private final String userAgent
;
172 private SignalAccount account
;
173 private final SignalServiceAccountManager accountManager
;
174 private final GroupsV2Api groupsV2Api
;
175 private final GroupsV2Operations groupsV2Operations
;
176 private final SignalServiceMessageReceiver messageReceiver
;
177 private final ClientZkProfileOperations clientZkProfileOperations
;
179 private final ExecutorService executor
= Executors
.newCachedThreadPool();
181 private SignalServiceMessagePipe messagePipe
= null;
182 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
184 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
185 private final ProfileHelper profileHelper
;
186 private final GroupHelper groupHelper
;
187 private final PinHelper pinHelper
;
188 private final AvatarStore avatarStore
;
189 private final AttachmentStore attachmentStore
;
192 SignalAccount account
,
193 PathConfig pathConfig
,
194 ServiceEnvironmentConfig serviceEnvironmentConfig
,
197 this.account
= account
;
198 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
199 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
200 this.userAgent
= userAgent
;
201 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
202 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
203 final SleepTimer timer
= new UptimeSleepTimer();
204 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
205 new DynamicCredentialsProvider(account
.getUuid(),
206 account
.getUsername(),
207 account
.getPassword(),
208 account
.getDeviceId()),
211 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
213 this.groupsV2Api
= accountManager
.getGroupsV2Api();
214 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
215 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
216 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
217 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
220 this.pinHelper
= new PinHelper(keyBackupService
);
221 this.clientZkProfileOperations
= capabilities
.isGv2()
222 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
223 .getProfileOperations()
225 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
227 account
.getUsername(),
228 account
.getPassword(),
229 account
.getDeviceId(),
233 clientZkProfileOperations
,
234 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
236 this.account
.setResolver(this::resolveSignalServiceAddress
);
238 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
239 account
.getProfileStore()::getProfileKey
,
240 this::getRecipientProfile
,
241 this::getSenderCertificate
);
242 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
243 unidentifiedAccessHelper
::getAccessFor
,
244 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
245 () -> messageReceiver
);
246 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
247 this::getRecipientProfile
,
248 account
::getSelfAddress
,
251 this::getGroupAuthForToday
);
252 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
253 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
256 public String
getUsername() {
257 return account
.getUsername();
260 public SignalServiceAddress
getSelfAddress() {
261 return account
.getSelfAddress();
264 private IdentityKeyPair
getIdentityKeyPair() {
265 return account
.getSignalProtocolStore().getIdentityKeyPair();
268 public int getDeviceId() {
269 return account
.getDeviceId();
272 public static Manager
init(
273 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
274 ) throws IOException
, NotRegisteredException
{
275 var pathConfig
= PathConfig
.createDefault(settingsPath
);
277 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
278 throw new NotRegisteredException();
281 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
283 if (!account
.isRegistered()) {
284 throw new NotRegisteredException();
287 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
289 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
292 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
293 var pathConfig
= PathConfig
.createDefault(settingsPath
);
294 final var dataPath
= pathConfig
.getDataPath();
295 final var files
= dataPath
.listFiles();
301 return Arrays
.stream(files
)
302 .filter(File
::isFile
)
304 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
305 .collect(Collectors
.toList());
308 public void checkAccountState() throws IOException
{
309 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
313 if (account
.getUuid() == null) {
314 account
.setUuid(accountManager
.getOwnUuid());
317 updateAccountAttributes();
321 * This is used for checking a set of phone numbers for registration on Signal
323 * @param numbers The set of phone number in question
324 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
325 * @throws IOException if its unable to get the contacts to check if they're registered
327 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
328 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
329 var contactDetails
= getRegisteredUsers(numbers
);
331 var registeredUsers
= contactDetails
.keySet();
333 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
336 public void updateAccountAttributes() throws IOException
{
337 accountManager
.setAccountAttributes(null,
338 account
.getSignalProtocolStore().getLocalRegistrationId(),
340 // set legacy pin only if no KBS master key is set
341 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
342 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
343 account
.getSelfUnidentifiedAccessKey(),
344 account
.isUnrestrictedUnidentifiedAccess(),
346 account
.isDiscoverableByPhoneNumber());
350 * @param name if null, the previous name will be kept
351 * @param about if null, the previous about text will be kept
352 * @param aboutEmoji if null, the previous about emoji will be kept
353 * @param avatar if avatar is null the image from the local avatar store is used (if present),
354 * if it's Optional.absent(), the avatar will be removed
356 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
357 var profileEntry
= account
.getProfileStore().getProfileEntry(getSelfAddress());
358 var profile
= profileEntry
== null ?
null : profileEntry
.getProfile();
359 var newProfile
= new SignalProfile(profile
== null ?
null : profile
.getIdentityKey(),
360 name
!= null ? name
: profile
== null || profile
.getName() == null ?
"" : profile
.getName(),
361 about
!= null ? about
: profile
== null || profile
.getAbout() == null ?
"" : profile
.getAbout(),
364 : profile
== null || profile
.getAboutEmoji() == null ?
"" : profile
.getAboutEmoji(),
365 profile
== null ?
null : profile
.getUnidentifiedAccess(),
366 account
.isUnrestrictedUnidentifiedAccess(),
367 profile
== null ?
null : profile
.getCapabilities());
369 try (final var streamDetails
= avatar
== null
370 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
371 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
372 accountManager
.setVersionedProfile(account
.getUuid(),
373 account
.getProfileKey(),
374 newProfile
.getName(),
375 newProfile
.getAbout(),
376 newProfile
.getAboutEmoji(),
380 if (avatar
!= null) {
381 if (avatar
.isPresent()) {
382 avatarStore
.storeProfileAvatar(getSelfAddress(),
383 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
385 avatarStore
.deleteProfileAvatar(getSelfAddress());
388 account
.getProfileStore()
389 .updateProfile(getSelfAddress(),
390 account
.getProfileKey(),
391 System
.currentTimeMillis(),
393 profileEntry
== null ?
null : profileEntry
.getProfileKeyCredential());
396 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
397 } catch (UntrustedIdentityException ignored
) {
401 public void unregister() throws IOException
{
402 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
403 // If this is the master device, other users can't send messages to this number anymore.
404 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
405 accountManager
.setGcmId(Optional
.absent());
406 accountManager
.deleteAccount();
408 account
.setRegistered(false);
412 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
413 var devices
= accountManager
.getDevices();
414 account
.setMultiDevice(devices
.size() > 1);
419 public void removeLinkedDevices(int deviceId
) throws IOException
{
420 accountManager
.removeDevice(deviceId
);
421 var devices
= accountManager
.getDevices();
422 account
.setMultiDevice(devices
.size() > 1);
426 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
427 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
429 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
432 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
433 var identityKeyPair
= getIdentityKeyPair();
434 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
436 accountManager
.addDevice(deviceIdentifier
,
439 Optional
.of(account
.getProfileKey().serialize()),
441 account
.setMultiDevice(true);
445 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
446 if (!account
.isMasterDevice()) {
447 throw new RuntimeException("Only master device can set a PIN");
449 if (pin
.isPresent()) {
450 final var masterKey
= account
.getPinMasterKey() != null
451 ? account
.getPinMasterKey()
452 : KeyUtils
.createMasterKey();
454 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
456 account
.setRegistrationLockPin(pin
.get());
457 account
.setPinMasterKey(masterKey
);
459 // Remove legacy registration lock
460 accountManager
.removeRegistrationLockV1();
463 pinHelper
.removeRegistrationLockPin();
465 account
.setRegistrationLockPin(null);
466 account
.setPinMasterKey(null);
471 void refreshPreKeys() throws IOException
{
472 var oneTimePreKeys
= generatePreKeys();
473 final var identityKeyPair
= getIdentityKeyPair();
474 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
476 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
479 private List
<PreKeyRecord
> generatePreKeys() {
480 final var offset
= account
.getPreKeyIdOffset();
482 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
483 account
.addPreKeys(records
);
489 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
490 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
492 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
493 account
.addSignedPreKey(record);
499 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
500 if (messagePipe
== null) {
501 messagePipe
= messageReceiver
.createMessagePipe();
506 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
507 if (unidentifiedMessagePipe
== null) {
508 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
510 return unidentifiedMessagePipe
;
513 private SignalServiceMessageSender
createMessageSender() {
514 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
516 account
.getUsername(),
517 account
.getPassword(),
518 account
.getDeviceId(),
519 account
.getSignalProtocolStore(),
521 account
.isMultiDevice(),
522 Optional
.fromNullable(messagePipe
),
523 Optional
.fromNullable(unidentifiedMessagePipe
),
525 clientZkProfileOperations
,
527 ServiceConfig
.MAX_ENVELOPE_SIZE
,
528 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
531 private SignalProfile
getRecipientProfile(
532 SignalServiceAddress address
534 return getRecipientProfile(address
, false);
537 private SignalProfile
getRecipientProfile(
538 SignalServiceAddress address
, boolean force
540 var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
541 if (profileEntry
== null) {
544 var now
= new Date().getTime();
545 // Profiles are cached for 24h before retrieving them again
546 if (!profileEntry
.isRequestPending() && (
548 || profileEntry
.getProfile() == null
549 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
551 profileEntry
.setRequestPending(true);
552 final SignalServiceProfile encryptedProfile
;
554 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
556 } catch (IOException e
) {
557 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
560 profileEntry
.setRequestPending(false);
563 final var profileKey
= profileEntry
.getProfileKey();
564 final var profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
565 account
.getProfileStore()
566 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
569 return profileEntry
.getProfile();
572 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
573 var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
574 if (profileEntry
== null) {
577 if (profileEntry
.getProfileKeyCredential() == null) {
578 ProfileAndCredential profileAndCredential
;
580 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
581 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
582 } catch (IOException e
) {
583 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
587 var now
= new Date().getTime();
588 final var profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
589 final var profile
= decryptProfileAndDownloadAvatar(address
,
590 profileEntry
.getProfileKey(),
591 profileAndCredential
.getProfile());
592 account
.getProfileStore()
593 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
594 return profileKeyCredential
;
596 return profileEntry
.getProfileKeyCredential();
599 private SignalProfile
decryptProfileAndDownloadAvatar(
600 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
602 if (encryptedProfile
.getAvatar() != null) {
603 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
606 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
609 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
610 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
611 if (streamDetails
== null) {
612 return Optional
.absent();
615 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
618 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
619 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
620 if (streamDetails
== null) {
621 return Optional
.absent();
624 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
627 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
628 var g
= getGroup(groupId
);
630 throw new GroupNotFoundException(groupId
);
632 if (!g
.isMember(account
.getSelfAddress())) {
633 throw new NotAGroupMemberException(groupId
, g
.getTitle());
638 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
639 var g
= getGroup(groupId
);
641 throw new GroupNotFoundException(groupId
);
643 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
644 throw new NotAGroupMemberException(groupId
, g
.getTitle());
649 public List
<GroupInfo
> getGroups() {
650 return account
.getGroupStore().getGroups();
653 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
654 String messageText
, List
<String
> attachments
, GroupId groupId
655 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
656 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
657 if (attachments
!= null) {
658 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
661 return sendGroupMessage(messageBuilder
, groupId
);
664 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
665 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
666 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
667 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
669 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
670 targetSentTimestamp
);
671 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
673 return sendGroupMessage(messageBuilder
, groupId
);
676 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
677 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
678 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
679 final var g
= getGroupForSending(groupId
);
681 GroupUtils
.setGroupContext(messageBuilder
, g
);
682 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
684 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
687 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
688 SignalServiceDataMessage
.Builder messageBuilder
;
690 final var g
= getGroupForUpdating(groupId
);
691 if (g
instanceof GroupInfoV1
) {
692 var groupInfoV1
= (GroupInfoV1
) g
;
693 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
694 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
695 groupInfoV1
.removeMember(account
.getSelfAddress());
696 account
.getGroupStore().updateGroup(groupInfoV1
);
698 final var groupInfoV2
= (GroupInfoV2
) g
;
699 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
700 groupInfoV2
.setGroup(groupGroupChangePair
.first());
701 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
702 account
.getGroupStore().updateGroup(groupInfoV2
);
705 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
708 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
709 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
710 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
711 return sendUpdateGroupMessage(groupId
,
713 members
== null ?
null : getSignalServiceAddresses(members
),
717 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
718 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
719 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
721 SignalServiceDataMessage
.Builder messageBuilder
;
722 if (groupId
== null) {
724 var gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
725 members
== null ? List
.of() : members
,
728 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
729 gv1
.addMembers(List
.of(account
.getSelfAddress()));
730 updateGroupV1(gv1
, name
, members
, avatarFile
);
731 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
734 if (avatarFile
!= null) {
735 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
736 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
738 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
742 var group
= getGroupForUpdating(groupId
);
743 if (group
instanceof GroupInfoV2
) {
744 final var groupInfoV2
= (GroupInfoV2
) group
;
746 Pair
<Long
, List
<SendMessageResult
>> result
= null;
747 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
748 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
749 result
= sendUpdateGroupMessage(groupInfoV2
,
750 groupGroupChangePair
.first(),
751 groupGroupChangePair
.second());
754 if (members
!= null) {
755 final var newMembers
= new HashSet
<>(members
);
756 newMembers
.removeAll(group
.getMembers()
758 .map(this::resolveSignalServiceAddress
)
759 .collect(Collectors
.toSet()));
760 if (newMembers
.size() > 0) {
761 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
762 result
= sendUpdateGroupMessage(groupInfoV2
,
763 groupGroupChangePair
.first(),
764 groupGroupChangePair
.second());
767 if (result
== null || name
!= null || avatarFile
!= null) {
768 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
769 if (avatarFile
!= null) {
770 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
771 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
773 result
= sendUpdateGroupMessage(groupInfoV2
,
774 groupGroupChangePair
.first(),
775 groupGroupChangePair
.second());
778 return new Pair
<>(group
.getGroupId(), result
.second());
780 var gv1
= (GroupInfoV1
) group
;
781 updateGroupV1(gv1
, name
, members
, avatarFile
);
782 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
787 account
.getGroupStore().updateGroup(g
);
789 final var result
= sendMessage(messageBuilder
, g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
790 return new Pair
<>(g
.getGroupId(), result
.second());
793 private void updateGroupV1(
796 final Collection
<SignalServiceAddress
> members
,
797 final File avatarFile
798 ) throws IOException
{
803 if (members
!= null) {
804 final var newE164Members
= new HashSet
<String
>();
805 for (var member
: members
) {
806 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
809 newE164Members
.add(member
.getNumber().get());
812 final var registeredUsers
= getRegisteredUsers(newE164Members
);
813 if (registeredUsers
.size() != newE164Members
.size()) {
814 // Some of the new members are not registered on Signal
815 newE164Members
.removeAll(registeredUsers
.keySet());
816 throw new IOException("Failed to add members "
817 + String
.join(", ", newE164Members
)
818 + " to group: Not registered on Signal");
821 g
.addMembers(members
);
824 if (avatarFile
!= null) {
825 avatarStore
.storeGroupAvatar(g
.getGroupId(),
826 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
830 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
831 GroupInviteLinkUrl inviteLinkUrl
832 ) throws IOException
, GroupLinkNotActiveException
{
833 return sendJoinGroupMessage(inviteLinkUrl
);
836 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
837 GroupInviteLinkUrl inviteLinkUrl
838 ) throws IOException
, GroupLinkNotActiveException
{
839 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
840 inviteLinkUrl
.getPassword());
841 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
842 inviteLinkUrl
.getPassword(),
844 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
845 groupJoinInfo
.getRevision() + 1,
846 groupChange
.toByteArray());
848 if (group
.getGroup() == null) {
849 // Only requested member, can't send update to group members
850 return new Pair
<>(group
.getGroupId(), List
.of());
853 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
855 return new Pair
<>(group
.getGroupId(), result
.second());
858 private static int currentTimeDays() {
859 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
862 private GroupsV2AuthorizationString
getGroupAuthForToday(
863 final GroupSecretParams groupSecretParams
864 ) throws IOException
{
865 final var today
= currentTimeDays();
866 // Returns credentials for the next 7 days
867 final var credentials
= groupsV2Api
.getCredentials(today
);
868 // TODO cache credentials until they expire
869 var authCredentialResponse
= credentials
.get(today
);
871 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
874 authCredentialResponse
);
875 } catch (VerificationFailedException e
) {
876 throw new IOException(e
);
880 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
881 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
882 ) throws IOException
{
883 group
.setGroup(newDecryptedGroup
);
884 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
885 account
.getGroupStore().updateGroup(group
);
886 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
889 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
890 GroupIdV1 groupId
, SignalServiceAddress recipient
891 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
893 var group
= getGroupForSending(groupId
);
894 if (!(group
instanceof GroupInfoV1
)) {
895 throw new RuntimeException("Received an invalid group request for a v2 group!");
897 g
= (GroupInfoV1
) group
;
899 if (!g
.isMember(recipient
)) {
900 throw new NotAGroupMemberException(groupId
, g
.name
);
903 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
905 // Send group message only to the recipient who requested it
906 return sendMessage(messageBuilder
, List
.of(recipient
));
909 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
910 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
911 .withId(g
.getGroupId().serialize())
913 .withMembers(new ArrayList
<>(g
.getMembers()));
916 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
917 if (attachment
.isPresent()) {
918 group
.withAvatar(attachment
.get());
920 } catch (IOException e
) {
921 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
924 return SignalServiceDataMessage
.newBuilder()
925 .asGroupMessage(group
.build())
926 .withExpiration(g
.getMessageExpirationTime());
929 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
930 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
931 .withRevision(g
.getGroup().getRevision())
932 .withSignedGroupChange(signedGroupChange
);
933 return SignalServiceDataMessage
.newBuilder()
934 .asGroupMessage(group
.build())
935 .withExpiration(g
.getMessageExpirationTime());
938 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
939 GroupIdV1 groupId
, SignalServiceAddress recipient
940 ) throws IOException
{
941 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
943 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
945 // Send group info request message to the recipient who sent us a message with this groupId
946 return sendMessage(messageBuilder
, List
.of(recipient
));
950 SignalServiceAddress remoteAddress
, long messageId
951 ) throws IOException
, UntrustedIdentityException
{
952 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
954 System
.currentTimeMillis());
956 createMessageSender().sendReceipt(remoteAddress
,
957 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
961 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
962 String messageText
, List
<String
> attachments
, List
<String
> recipients
963 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
964 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
965 if (attachments
!= null) {
966 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
968 // Upload attachments here, so we only upload once even for multiple recipients
969 var messageSender
= createMessageSender();
970 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
971 for (var attachment
: attachmentStreams
) {
972 if (attachment
.isStream()) {
973 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
974 } else if (attachment
.isPointer()) {
975 attachmentPointers
.add(attachment
.asPointer());
979 messageBuilder
.withAttachments(attachmentPointers
);
981 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
984 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
985 String messageText
, List
<String
> attachments
986 ) throws IOException
, AttachmentInvalidException
{
987 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
988 if (attachments
!= null) {
989 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
991 return sendSelfMessage(messageBuilder
);
994 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
995 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
996 ) throws IOException
, InvalidNumberException
{
997 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
999 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1000 targetSentTimestamp
);
1001 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1002 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1005 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1006 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1008 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1010 return sendMessage(messageBuilder
, signalServiceAddresses
);
1011 } catch (Exception e
) {
1012 for (var address
: signalServiceAddresses
) {
1013 handleEndSession(address
);
1020 public String
getContactName(String number
) throws InvalidNumberException
{
1021 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1022 if (contact
== null) {
1025 return contact
.name
;
1029 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1030 final var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1031 var contact
= account
.getContactStore().getContact(address
);
1032 if (contact
== null) {
1033 contact
= new ContactInfo(address
);
1035 contact
.name
= name
;
1036 account
.getContactStore().updateContact(contact
);
1040 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1041 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1044 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1045 var contact
= account
.getContactStore().getContact(address
);
1046 if (contact
== null) {
1047 contact
= new ContactInfo(address
);
1049 contact
.blocked
= blocked
;
1050 account
.getContactStore().updateContact(contact
);
1054 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1055 var group
= getGroup(groupId
);
1056 if (group
== null) {
1057 throw new GroupNotFoundException(groupId
);
1060 group
.setBlocked(blocked
);
1061 account
.getGroupStore().updateGroup(group
);
1066 * Change the expiration timer for a contact
1068 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1069 var contact
= account
.getContactStore().getContact(address
);
1070 contact
.messageExpirationTime
= messageExpirationTimer
;
1071 account
.getContactStore().updateContact(contact
);
1072 sendExpirationTimerUpdate(address
);
1076 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1077 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1078 sendMessage(messageBuilder
, List
.of(address
));
1082 * Change the expiration timer for a contact
1084 public void setExpirationTimer(
1085 String number
, int messageExpirationTimer
1086 ) throws IOException
, InvalidNumberException
{
1087 var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1088 setExpirationTimer(address
, messageExpirationTimer
);
1092 * Change the expiration timer for a group
1094 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1095 var g
= getGroup(groupId
);
1096 if (g
instanceof GroupInfoV1
) {
1097 var groupInfoV1
= (GroupInfoV1
) g
;
1098 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1099 account
.getGroupStore().updateGroup(groupInfoV1
);
1101 throw new RuntimeException("TODO Not implemented!");
1106 * Upload the sticker pack from path.
1108 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1109 * @return if successful, returns the URL to install the sticker pack in the signal app
1111 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1112 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1114 var messageSender
= createMessageSender();
1116 var packKey
= KeyUtils
.createStickerUploadKey();
1117 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1119 var sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1120 account
.getStickerStore().updateSticker(sticker
);
1124 return new URI("https",
1127 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1128 Hex
.toStringCondensed(packKey
),
1129 StandardCharsets
.UTF_8
)).toString();
1130 } catch (URISyntaxException e
) {
1131 throw new AssertionError(e
);
1135 void requestSyncGroups() throws IOException
{
1136 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1137 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1139 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1141 sendSyncMessage(message
);
1142 } catch (UntrustedIdentityException e
) {
1143 throw new AssertionError(e
);
1147 void requestSyncContacts() throws IOException
{
1148 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1149 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1151 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1153 sendSyncMessage(message
);
1154 } catch (UntrustedIdentityException e
) {
1155 throw new AssertionError(e
);
1159 void requestSyncBlocked() throws IOException
{
1160 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1161 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1163 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1165 sendSyncMessage(message
);
1166 } catch (UntrustedIdentityException e
) {
1167 throw new AssertionError(e
);
1171 void requestSyncConfiguration() throws IOException
{
1172 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1173 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1175 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1177 sendSyncMessage(message
);
1178 } catch (UntrustedIdentityException e
) {
1179 throw new AssertionError(e
);
1183 void requestSyncKeys() throws IOException
{
1184 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1185 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1187 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1189 sendSyncMessage(message
);
1190 } catch (UntrustedIdentityException e
) {
1191 throw new AssertionError(e
);
1195 private byte[] getSenderCertificate() {
1196 // TODO support UUID capable sender certificates
1197 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1200 certificate
= accountManager
.getSenderCertificate();
1201 } catch (IOException e
) {
1202 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1205 // TODO cache for a day
1209 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1210 var messageSender
= createMessageSender();
1212 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1213 } catch (UntrustedIdentityException e
) {
1214 account
.getSignalProtocolStore()
1215 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1217 TrustLevel
.UNTRUSTED
);
1222 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1223 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1224 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1226 for (var number
: numbers
) {
1227 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1228 if (resolvedAddress
.getUuid().isPresent()) {
1229 signalServiceAddresses
.add(resolvedAddress
);
1231 addressesMissingUuid
.add(resolvedAddress
);
1235 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1236 .map(a
-> a
.getNumber().get())
1237 .collect(Collectors
.toSet());
1238 Map
<String
, UUID
> registeredUsers
;
1240 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1241 } catch (IOException e
) {
1242 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1243 registeredUsers
= Map
.of();
1246 for (var address
: addressesMissingUuid
) {
1247 final var number
= address
.getNumber().get();
1248 if (registeredUsers
.containsKey(number
)) {
1249 final var newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(registeredUsers
.get(number
),
1251 signalServiceAddresses
.add(newAddress
);
1253 signalServiceAddresses
.add(address
);
1257 return signalServiceAddresses
;
1260 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1262 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1264 serviceEnvironmentConfig
.getCdsMrenclave());
1265 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1266 throw new IOException(e
);
1270 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1271 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1272 ) throws IOException
{
1273 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1274 final var timestamp
= System
.currentTimeMillis();
1275 messageBuilder
.withTimestamp(timestamp
);
1276 getOrCreateMessagePipe();
1277 getOrCreateUnidentifiedMessagePipe();
1278 SignalServiceDataMessage message
= null;
1280 message
= messageBuilder
.build();
1281 if (message
.getGroupContext().isPresent()) {
1283 var messageSender
= createMessageSender();
1284 final var isRecipientUpdate
= false;
1285 var result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1286 unidentifiedAccessHelper
.getAccessFor(recipients
),
1289 for (var r
: result
) {
1290 if (r
.getIdentityFailure() != null) {
1291 account
.getSignalProtocolStore()
1292 .saveIdentity(r
.getAddress(),
1293 r
.getIdentityFailure().getIdentityKey(),
1294 TrustLevel
.UNTRUSTED
);
1297 return new Pair
<>(timestamp
, result
);
1298 } catch (UntrustedIdentityException e
) {
1299 account
.getSignalProtocolStore()
1300 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1302 TrustLevel
.UNTRUSTED
);
1303 return new Pair
<>(timestamp
, List
.of());
1306 // Send to all individually, so sync messages are sent correctly
1307 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1308 var results
= new ArrayList
<SendMessageResult
>(recipients
.size());
1309 for (var address
: recipients
) {
1310 final var contact
= account
.getContactStore().getContact(address
);
1311 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1312 messageBuilder
.withExpiration(expirationTime
);
1313 message
= messageBuilder
.build();
1314 results
.add(sendMessage(address
, message
));
1316 return new Pair
<>(timestamp
, results
);
1319 if (message
!= null && message
.isEndSession()) {
1320 for (var recipient
: recipients
) {
1321 handleEndSession(recipient
);
1328 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1329 SignalServiceDataMessage
.Builder messageBuilder
1330 ) throws IOException
{
1331 final var timestamp
= System
.currentTimeMillis();
1332 messageBuilder
.withTimestamp(timestamp
);
1333 getOrCreateMessagePipe();
1334 getOrCreateUnidentifiedMessagePipe();
1336 final var address
= getSelfAddress();
1338 final var contact
= account
.getContactStore().getContact(address
);
1339 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1340 messageBuilder
.withExpiration(expirationTime
);
1342 var message
= messageBuilder
.build();
1343 final var result
= sendSelfMessage(message
);
1344 return new Pair
<>(timestamp
, result
);
1350 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1351 var messageSender
= createMessageSender();
1353 var recipient
= account
.getSelfAddress();
1355 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1356 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1357 message
.getTimestamp(),
1359 message
.getExpiresInSeconds(),
1360 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1362 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1365 var startTime
= System
.currentTimeMillis();
1366 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1367 return SendMessageResult
.success(recipient
,
1368 unidentifiedAccess
.isPresent(),
1370 System
.currentTimeMillis() - startTime
);
1371 } catch (UntrustedIdentityException e
) {
1372 account
.getSignalProtocolStore()
1373 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1375 TrustLevel
.UNTRUSTED
);
1376 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1380 private SendMessageResult
sendMessage(
1381 SignalServiceAddress address
, SignalServiceDataMessage message
1382 ) throws IOException
{
1383 var messageSender
= createMessageSender();
1386 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1387 } catch (UntrustedIdentityException e
) {
1388 account
.getSignalProtocolStore()
1389 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1391 TrustLevel
.UNTRUSTED
);
1392 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1396 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1397 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1398 account
.getSignalProtocolStore(),
1399 certificateValidator
);
1401 return cipher
.decrypt(envelope
);
1402 } catch (ProtocolUntrustedIdentityException e
) {
1403 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1404 var identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1405 final var untrustedIdentity
= identityException
.getUntrustedIdentity();
1406 if (untrustedIdentity
!= null) {
1407 account
.getSignalProtocolStore()
1408 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1410 TrustLevel
.UNTRUSTED
);
1412 throw identityException
;
1414 throw new AssertionError(e
);
1418 private void handleEndSession(SignalServiceAddress source
) {
1419 account
.getSignalProtocolStore().deleteAllSessions(source
);
1422 private List
<HandleAction
> handleSignalServiceDataMessage(
1423 SignalServiceDataMessage message
,
1425 SignalServiceAddress source
,
1426 SignalServiceAddress destination
,
1427 boolean ignoreAttachments
1429 var actions
= new ArrayList
<HandleAction
>();
1430 if (message
.getGroupContext().isPresent()) {
1431 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1432 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1433 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1434 var group
= getGroup(groupId
);
1435 if (group
== null || group
instanceof GroupInfoV1
) {
1436 var groupV1
= (GroupInfoV1
) group
;
1437 switch (groupInfo
.getType()) {
1439 if (groupV1
== null) {
1440 groupV1
= new GroupInfoV1(groupId
);
1443 if (groupInfo
.getAvatar().isPresent()) {
1444 var avatar
= groupInfo
.getAvatar().get();
1445 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1448 if (groupInfo
.getName().isPresent()) {
1449 groupV1
.name
= groupInfo
.getName().get();
1452 if (groupInfo
.getMembers().isPresent()) {
1453 groupV1
.addMembers(groupInfo
.getMembers()
1456 .map(this::resolveSignalServiceAddress
)
1457 .collect(Collectors
.toSet()));
1460 account
.getGroupStore().updateGroup(groupV1
);
1464 if (groupV1
== null && !isSync
) {
1465 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1469 if (groupV1
!= null) {
1470 groupV1
.removeMember(source
);
1471 account
.getGroupStore().updateGroup(groupV1
);
1476 if (groupV1
!= null && !isSync
) {
1477 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1482 // Received a group v1 message for a v2 group
1485 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1486 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1487 final var groupMasterKey
= groupContext
.getMasterKey();
1489 getOrMigrateGroup(groupMasterKey
,
1490 groupContext
.getRevision(),
1491 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1495 final var conversationPartnerAddress
= isSync ? destination
: source
;
1496 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1497 handleEndSession(conversationPartnerAddress
);
1499 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1500 if (message
.getGroupContext().isPresent()) {
1501 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1502 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1503 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1504 if (group
!= null) {
1505 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1506 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1507 account
.getGroupStore().updateGroup(group
);
1510 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1511 // disappearing message timer already stored in the DecryptedGroup
1513 } else if (conversationPartnerAddress
!= null) {
1514 var contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1515 if (contact
== null) {
1516 contact
= new ContactInfo(conversationPartnerAddress
);
1518 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1519 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1520 account
.getContactStore().updateContact(contact
);
1524 if (!ignoreAttachments
) {
1525 if (message
.getAttachments().isPresent()) {
1526 for (var attachment
: message
.getAttachments().get()) {
1527 downloadAttachment(attachment
);
1530 if (message
.getSharedContacts().isPresent()) {
1531 for (var contact
: message
.getSharedContacts().get()) {
1532 if (contact
.getAvatar().isPresent()) {
1533 downloadAttachment(contact
.getAvatar().get().getAttachment());
1538 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1539 final ProfileKey profileKey
;
1541 profileKey
= new ProfileKey(message
.getProfileKey().get());
1542 } catch (InvalidInputException e
) {
1543 throw new AssertionError(e
);
1545 if (source
.matches(account
.getSelfAddress())) {
1546 this.account
.setProfileKey(profileKey
);
1548 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1550 if (message
.getPreviews().isPresent()) {
1551 final var previews
= message
.getPreviews().get();
1552 for (var preview
: previews
) {
1553 if (preview
.getImage().isPresent()) {
1554 downloadAttachment(preview
.getImage().get());
1558 if (message
.getQuote().isPresent()) {
1559 final var quote
= message
.getQuote().get();
1561 for (var quotedAttachment
: quote
.getAttachments()) {
1562 final var thumbnail
= quotedAttachment
.getThumbnail();
1563 if (thumbnail
!= null) {
1564 downloadAttachment(thumbnail
);
1568 if (message
.getSticker().isPresent()) {
1569 final var messageSticker
= message
.getSticker().get();
1570 var sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1571 if (sticker
== null) {
1572 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1573 account
.getStickerStore().updateSticker(sticker
);
1579 private GroupInfoV2
getOrMigrateGroup(
1580 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1582 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1584 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1585 var groupInfo
= getGroup(groupId
);
1586 final GroupInfoV2 groupInfoV2
;
1587 if (groupInfo
instanceof GroupInfoV1
) {
1588 // Received a v2 group message for a v1 group, we need to locally migrate the group
1589 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1590 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1591 logger
.info("Locally migrated group {} to group v2, id: {}",
1592 groupInfo
.getGroupId().toBase64(),
1593 groupInfoV2
.getGroupId().toBase64());
1594 } else if (groupInfo
instanceof GroupInfoV2
) {
1595 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1597 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1600 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1601 DecryptedGroup group
= null;
1602 if (signedGroupChange
!= null
1603 && groupInfoV2
.getGroup() != null
1604 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1605 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1607 if (group
== null) {
1608 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1610 if (group
!= null) {
1611 storeProfileKeysFromMembers(group
);
1612 final var avatar
= group
.getAvatar();
1613 if (avatar
!= null && !avatar
.isEmpty()) {
1614 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1617 groupInfoV2
.setGroup(group
);
1618 account
.getGroupStore().updateGroup(groupInfoV2
);
1624 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1625 for (var member
: group
.getMembersList()) {
1626 final var address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1627 .toByteArray()), null));
1629 account
.getProfileStore()
1630 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1631 } catch (InvalidInputException ignored
) {
1636 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1637 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1638 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1642 private void retryFailedReceivedMessage(
1643 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1645 var envelope
= cachedMessage
.loadEnvelope();
1646 if (envelope
== null) {
1649 SignalServiceContent content
= null;
1650 if (!envelope
.isReceipt()) {
1652 content
= decryptMessage(envelope
);
1653 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1655 } catch (Exception er
) {
1656 // All other errors are not recoverable, so delete the cached message
1657 cachedMessage
.delete();
1660 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1661 for (var action
: actions
) {
1663 action
.execute(this);
1664 } catch (Throwable e
) {
1665 logger
.warn("Message action failed.", e
);
1670 handler
.handleMessage(envelope
, content
, null);
1671 cachedMessage
.delete();
1674 public void receiveMessages(
1677 boolean returnOnTimeout
,
1678 boolean ignoreAttachments
,
1679 ReceiveMessageHandler handler
1680 ) throws IOException
{
1681 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1683 Set
<HandleAction
> queuedActions
= null;
1685 final var messagePipe
= getOrCreateMessagePipe();
1687 var hasCaughtUpWithOldMessages
= false;
1690 SignalServiceEnvelope envelope
;
1691 SignalServiceContent content
= null;
1692 Exception exception
= null;
1693 final CachedMessage
[] cachedMessage
= {null};
1695 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1696 // store message on disk, before acknowledging receipt to the server
1697 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1699 if (result
.isPresent()) {
1700 envelope
= result
.get();
1702 // Received indicator that server queue is empty
1703 hasCaughtUpWithOldMessages
= true;
1705 if (queuedActions
!= null) {
1706 for (var action
: queuedActions
) {
1708 action
.execute(this);
1709 } catch (Throwable e
) {
1710 logger
.warn("Message action failed.", e
);
1714 queuedActions
.clear();
1715 queuedActions
= null;
1718 // Continue to wait another timeout for new messages
1721 } catch (TimeoutException e
) {
1722 if (returnOnTimeout
) return;
1726 if (envelope
.hasSource()) {
1727 // Store uuid if we don't have it already
1728 var source
= envelope
.getSourceAddress();
1729 resolveSignalServiceAddress(source
);
1731 if (!envelope
.isReceipt()) {
1733 content
= decryptMessage(envelope
);
1734 } catch (Exception e
) {
1737 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1738 if (hasCaughtUpWithOldMessages
) {
1739 for (var action
: actions
) {
1741 action
.execute(this);
1742 } catch (Throwable e
) {
1743 logger
.warn("Message action failed.", e
);
1747 if (queuedActions
== null) {
1748 queuedActions
= new HashSet
<>();
1750 queuedActions
.addAll(actions
);
1754 if (isMessageBlocked(envelope
, content
)) {
1755 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1756 } else if (isNotAGroupMember(envelope
, content
)) {
1757 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1759 handler
.handleMessage(envelope
, content
, exception
);
1761 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1762 if (cachedMessage
[0] != null) {
1763 cachedMessage
[0].delete();
1769 private boolean isMessageBlocked(
1770 SignalServiceEnvelope envelope
, SignalServiceContent content
1772 SignalServiceAddress source
;
1773 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1774 source
= envelope
.getSourceAddress();
1775 } else if (content
!= null) {
1776 source
= content
.getSender();
1780 var sourceContact
= account
.getContactStore().getContact(source
);
1781 if (sourceContact
!= null && sourceContact
.blocked
) {
1785 if (content
!= null && content
.getDataMessage().isPresent()) {
1786 var message
= content
.getDataMessage().get();
1787 if (message
.getGroupContext().isPresent()) {
1788 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1789 var group
= getGroup(groupId
);
1790 if (group
!= null && group
.isBlocked()) {
1798 private boolean isNotAGroupMember(
1799 SignalServiceEnvelope envelope
, SignalServiceContent content
1801 SignalServiceAddress source
;
1802 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1803 source
= envelope
.getSourceAddress();
1804 } else if (content
!= null) {
1805 source
= content
.getSender();
1810 if (content
!= null && content
.getDataMessage().isPresent()) {
1811 var message
= content
.getDataMessage().get();
1812 if (message
.getGroupContext().isPresent()) {
1813 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1814 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1815 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1819 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1820 var group
= getGroup(groupId
);
1821 if (group
!= null && !group
.isMember(source
)) {
1829 private List
<HandleAction
> handleMessage(
1830 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1832 var actions
= new ArrayList
<HandleAction
>();
1833 if (content
!= null) {
1834 final SignalServiceAddress sender
;
1835 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1836 sender
= envelope
.getSourceAddress();
1838 sender
= content
.getSender();
1840 // Store uuid if we don't have it already
1841 resolveSignalServiceAddress(sender
);
1843 if (content
.getDataMessage().isPresent()) {
1844 var message
= content
.getDataMessage().get();
1846 if (content
.isNeedsReceipt()) {
1847 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1850 actions
.addAll(handleSignalServiceDataMessage(message
,
1853 account
.getSelfAddress(),
1854 ignoreAttachments
));
1856 if (content
.getSyncMessage().isPresent()) {
1857 account
.setMultiDevice(true);
1858 var syncMessage
= content
.getSyncMessage().get();
1859 if (syncMessage
.getSent().isPresent()) {
1860 var message
= syncMessage
.getSent().get();
1861 final var destination
= message
.getDestination().orNull();
1862 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1866 ignoreAttachments
));
1868 if (syncMessage
.getRequest().isPresent()) {
1869 var rm
= syncMessage
.getRequest().get();
1870 if (rm
.isContactsRequest()) {
1871 actions
.add(SendSyncContactsAction
.create());
1873 if (rm
.isGroupsRequest()) {
1874 actions
.add(SendSyncGroupsAction
.create());
1876 if (rm
.isBlockedListRequest()) {
1877 actions
.add(SendSyncBlockedListAction
.create());
1879 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1881 if (syncMessage
.getGroups().isPresent()) {
1882 File tmpFile
= null;
1884 tmpFile
= IOUtils
.createTempFile();
1885 final var groupsMessage
= syncMessage
.getGroups().get();
1886 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1887 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1889 while ((g
= s
.read()) != null) {
1890 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1891 if (syncGroup
!= null) {
1892 if (g
.getName().isPresent()) {
1893 syncGroup
.name
= g
.getName().get();
1895 syncGroup
.addMembers(g
.getMembers()
1897 .map(this::resolveSignalServiceAddress
)
1898 .collect(Collectors
.toSet()));
1899 if (!g
.isActive()) {
1900 syncGroup
.removeMember(account
.getSelfAddress());
1902 // Add ourself to the member set as it's marked as active
1903 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1905 syncGroup
.blocked
= g
.isBlocked();
1906 if (g
.getColor().isPresent()) {
1907 syncGroup
.color
= g
.getColor().get();
1910 if (g
.getAvatar().isPresent()) {
1911 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1913 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1914 syncGroup
.archived
= g
.isArchived();
1915 account
.getGroupStore().updateGroup(syncGroup
);
1919 } catch (Exception e
) {
1920 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1924 if (tmpFile
!= null) {
1926 Files
.delete(tmpFile
.toPath());
1927 } catch (IOException e
) {
1928 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1935 if (syncMessage
.getBlockedList().isPresent()) {
1936 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1937 for (var address
: blockedListMessage
.getAddresses()) {
1938 setContactBlocked(resolveSignalServiceAddress(address
), true);
1940 for (var groupId
: blockedListMessage
.getGroupIds()
1942 .map(GroupId
::unknownVersion
)
1943 .collect(Collectors
.toSet())) {
1945 setGroupBlocked(groupId
, true);
1946 } catch (GroupNotFoundException e
) {
1947 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1948 groupId
.toBase64());
1952 if (syncMessage
.getContacts().isPresent()) {
1953 File tmpFile
= null;
1955 tmpFile
= IOUtils
.createTempFile();
1956 final var contactsMessage
= syncMessage
.getContacts().get();
1957 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1958 .asPointer(), tmpFile
)) {
1959 var s
= new DeviceContactsInputStream(attachmentAsStream
);
1960 if (contactsMessage
.isComplete()) {
1961 account
.getContactStore().clear();
1964 while ((c
= s
.read()) != null) {
1965 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1966 account
.setProfileKey(c
.getProfileKey().get());
1968 final var address
= resolveSignalServiceAddress(c
.getAddress());
1969 var contact
= account
.getContactStore().getContact(address
);
1970 if (contact
== null) {
1971 contact
= new ContactInfo(address
);
1973 if (c
.getName().isPresent()) {
1974 contact
.name
= c
.getName().get();
1976 if (c
.getColor().isPresent()) {
1977 contact
.color
= c
.getColor().get();
1979 if (c
.getProfileKey().isPresent()) {
1980 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1982 if (c
.getVerified().isPresent()) {
1983 final var verifiedMessage
= c
.getVerified().get();
1984 account
.getSignalProtocolStore()
1985 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1986 verifiedMessage
.getIdentityKey(),
1987 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1989 if (c
.getExpirationTimer().isPresent()) {
1990 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1992 contact
.blocked
= c
.isBlocked();
1993 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1994 contact
.archived
= c
.isArchived();
1995 account
.getContactStore().updateContact(contact
);
1997 if (c
.getAvatar().isPresent()) {
1998 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2002 } catch (Exception e
) {
2003 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2007 if (tmpFile
!= null) {
2009 Files
.delete(tmpFile
.toPath());
2010 } catch (IOException e
) {
2011 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2018 if (syncMessage
.getVerified().isPresent()) {
2019 final var verifiedMessage
= syncMessage
.getVerified().get();
2020 account
.getSignalProtocolStore()
2021 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2022 verifiedMessage
.getIdentityKey(),
2023 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2025 if (syncMessage
.getStickerPackOperations().isPresent()) {
2026 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2027 for (var m
: stickerPackOperationMessages
) {
2028 if (!m
.getPackId().isPresent()) {
2031 var sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2032 if (sticker
== null) {
2033 if (!m
.getPackKey().isPresent()) {
2036 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2038 sticker
.setInstalled(!m
.getType().isPresent()
2039 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2040 account
.getStickerStore().updateSticker(sticker
);
2043 if (syncMessage
.getFetchType().isPresent()) {
2044 switch (syncMessage
.getFetchType().get()) {
2046 getRecipientProfile(getSelfAddress(), true);
2047 case STORAGE_MANIFEST
:
2051 if (syncMessage
.getKeys().isPresent()) {
2052 final var keysMessage
= syncMessage
.getKeys().get();
2053 if (keysMessage
.getStorageService().isPresent()) {
2054 final var storageKey
= keysMessage
.getStorageService().get();
2055 account
.setStorageKey(storageKey
);
2058 if (syncMessage
.getConfiguration().isPresent()) {
2066 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2068 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2069 } catch (IOException e
) {
2070 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2074 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2076 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2077 } catch (IOException e
) {
2078 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2082 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2084 avatarStore
.storeGroupAvatar(groupId
,
2085 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2086 } catch (IOException e
) {
2087 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2091 private void downloadProfileAvatar(
2092 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2095 avatarStore
.storeProfileAvatar(address
,
2096 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2097 } catch (Throwable e
) {
2098 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2102 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2103 return attachmentStore
.getAttachmentFile(attachmentId
);
2106 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2107 if (!attachment
.isPointer()) {
2108 logger
.warn("Invalid state, can't store an attachment stream.");
2111 var pointer
= attachment
.asPointer();
2112 if (pointer
.getPreview().isPresent()) {
2113 final var preview
= pointer
.getPreview().get();
2115 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2116 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2117 } catch (IOException e
) {
2118 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2123 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2124 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2125 } catch (IOException e
) {
2126 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2130 private void retrieveGroupV2Avatar(
2131 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2132 ) throws IOException
{
2133 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2135 var tmpFile
= IOUtils
.createTempFile();
2136 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2138 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2139 var encryptedData
= IOUtils
.readFully(input
);
2141 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2142 outputStream
.write(decryptedData
);
2145 Files
.delete(tmpFile
.toPath());
2146 } catch (IOException e
) {
2147 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2154 private void retrieveProfileAvatar(
2155 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2156 ) throws IOException
{
2157 var tmpFile
= IOUtils
.createTempFile();
2158 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2161 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2162 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2163 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2166 Files
.delete(tmpFile
.toPath());
2167 } catch (IOException e
) {
2168 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2175 private void retrieveAttachment(
2176 final SignalServiceAttachment attachment
, final OutputStream outputStream
2177 ) throws IOException
{
2178 if (attachment
.isPointer()) {
2179 var pointer
= attachment
.asPointer();
2180 retrieveAttachmentPointer(pointer
, outputStream
);
2182 var stream
= attachment
.asStream();
2183 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2187 private void retrieveAttachmentPointer(
2188 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2189 ) throws IOException
{
2190 var tmpFile
= IOUtils
.createTempFile();
2191 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2192 IOUtils
.copyStream(input
, outputStream
);
2193 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2194 throw new IOException(e
);
2197 Files
.delete(tmpFile
.toPath());
2198 } catch (IOException e
) {
2199 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2206 private InputStream
retrieveAttachmentAsStream(
2207 SignalServiceAttachmentPointer pointer
, File tmpFile
2208 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2209 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2212 void sendGroups() throws IOException
, UntrustedIdentityException
{
2213 var groupsFile
= IOUtils
.createTempFile();
2216 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2217 var out
= new DeviceGroupsOutputStream(fos
);
2218 for (var record : getGroups()) {
2219 if (record instanceof GroupInfoV1
) {
2220 var groupInfo
= (GroupInfoV1
) record;
2221 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2222 Optional
.fromNullable(groupInfo
.name
),
2223 new ArrayList
<>(groupInfo
.getMembers()),
2224 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2225 groupInfo
.isMember(account
.getSelfAddress()),
2226 Optional
.of(groupInfo
.messageExpirationTime
),
2227 Optional
.fromNullable(groupInfo
.color
),
2229 Optional
.fromNullable(groupInfo
.inboxPosition
),
2230 groupInfo
.archived
));
2235 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2236 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2237 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2238 .withStream(groupsFileStream
)
2239 .withContentType("application/octet-stream")
2240 .withLength(groupsFile
.length())
2243 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2248 Files
.delete(groupsFile
.toPath());
2249 } catch (IOException e
) {
2250 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2255 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2256 var contactsFile
= IOUtils
.createTempFile();
2259 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2260 var out
= new DeviceContactsOutputStream(fos
);
2261 for (var record : account
.getContactStore().getContacts()) {
2262 VerifiedMessage verifiedMessage
= null;
2263 var currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2264 if (currentIdentity
!= null) {
2265 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2266 currentIdentity
.getIdentityKey(),
2267 currentIdentity
.getTrustLevel().toVerifiedState(),
2268 currentIdentity
.getDateAdded().getTime());
2271 var profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2272 out
.write(new DeviceContact(record.getAddress(),
2273 Optional
.fromNullable(record.name
),
2274 createContactAvatarAttachment(record.getAddress()),
2275 Optional
.fromNullable(record.color
),
2276 Optional
.fromNullable(verifiedMessage
),
2277 Optional
.fromNullable(profileKey
),
2279 Optional
.of(record.messageExpirationTime
),
2280 Optional
.fromNullable(record.inboxPosition
),
2284 if (account
.getProfileKey() != null) {
2285 // Send our own profile key as well
2286 out
.write(new DeviceContact(account
.getSelfAddress(),
2291 Optional
.of(account
.getProfileKey()),
2299 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2300 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2301 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2302 .withStream(contactsFileStream
)
2303 .withContentType("application/octet-stream")
2304 .withLength(contactsFile
.length())
2307 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2312 Files
.delete(contactsFile
.toPath());
2313 } catch (IOException e
) {
2314 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2319 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2320 var addresses
= new ArrayList
<SignalServiceAddress
>();
2321 for (var record : account
.getContactStore().getContacts()) {
2322 if (record.blocked
) {
2323 addresses
.add(record.getAddress());
2326 var groupIds
= new ArrayList
<byte[]>();
2327 for (var record : getGroups()) {
2328 if (record.isBlocked()) {
2329 groupIds
.add(record.getGroupId().serialize());
2332 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2335 private void sendVerifiedMessage(
2336 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2337 ) throws IOException
, UntrustedIdentityException
{
2338 var verifiedMessage
= new VerifiedMessage(destination
,
2340 trustLevel
.toVerifiedState(),
2341 System
.currentTimeMillis());
2342 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2345 public List
<ContactInfo
> getContacts() {
2346 return account
.getContactStore().getContacts();
2349 public String
getContactOrProfileName(String number
) {
2350 final var address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2352 final var contact
= account
.getContactStore().getContact(address
);
2353 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2354 return contact
.name
;
2357 final var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2358 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2359 return profileEntry
.getProfile().getName();
2365 public GroupInfo
getGroup(GroupId groupId
) {
2366 final var group
= account
.getGroupStore().getGroup(groupId
);
2367 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2368 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2369 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2370 account
.getGroupStore().updateGroup(group
);
2375 public List
<IdentityInfo
> getIdentities() {
2376 return account
.getSignalProtocolStore().getIdentities();
2379 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2380 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2384 * Trust this the identity with this fingerprint
2386 * @param name username of the identity
2387 * @param fingerprint Fingerprint
2389 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2390 var address
= canonicalizeAndResolveSignalServiceAddress(name
);
2391 var ids
= account
.getSignalProtocolStore().getIdentities(address
);
2395 for (var id
: ids
) {
2396 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2400 account
.getSignalProtocolStore()
2401 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2403 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2404 } catch (IOException
| UntrustedIdentityException e
) {
2405 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2414 * Trust this the identity with this safety number
2416 * @param name username of the identity
2417 * @param safetyNumber Safety number
2419 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2420 var address
= canonicalizeAndResolveSignalServiceAddress(name
);
2421 var ids
= account
.getSignalProtocolStore().getIdentities(address
);
2425 for (var id
: ids
) {
2426 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2430 account
.getSignalProtocolStore()
2431 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2433 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2434 } catch (IOException
| UntrustedIdentityException e
) {
2435 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2444 * Trust all keys of this identity without verification
2446 * @param name username of the identity
2448 public boolean trustIdentityAllKeys(String name
) {
2449 var address
= resolveSignalServiceAddress(name
);
2450 var ids
= account
.getSignalProtocolStore().getIdentities(address
);
2454 for (var id
: ids
) {
2455 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2456 account
.getSignalProtocolStore()
2457 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2459 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2460 } catch (IOException
| UntrustedIdentityException e
) {
2461 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2469 public String
computeSafetyNumber(
2470 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2472 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2473 account
.getSelfAddress(),
2474 getIdentityKeyPair().getPublicKey(),
2479 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2480 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2482 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2483 return resolveSignalServiceAddress(canonicalizedNumber
);
2486 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2487 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2489 return resolveSignalServiceAddress(address
);
2492 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2493 if (address
.matches(account
.getSelfAddress())) {
2494 return account
.getSelfAddress();
2497 return account
.getRecipientStore().resolveServiceAddress(address
);
2501 public void close() throws IOException
{
2505 void close(boolean closeAccount
) throws IOException
{
2506 executor
.shutdown();
2508 if (messagePipe
!= null) {
2509 messagePipe
.shutdown();
2513 if (unidentifiedMessagePipe
!= null) {
2514 unidentifiedMessagePipe
.shutdown();
2515 unidentifiedMessagePipe
= null;
2518 if (closeAccount
&& account
!= null) {
2524 public interface ReceiveMessageHandler
{
2526 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);