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
.groups
.GroupInfo
;
34 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
35 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
36 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
37 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
38 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
39 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
40 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
41 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
42 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
43 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
44 import org
.asamk
.signal
.manager
.util
.IOUtils
;
45 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
46 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
47 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
48 import org
.asamk
.signal
.manager
.util
.Utils
;
49 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
50 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
51 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
52 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
53 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
54 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
56 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
57 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
58 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
59 import org
.signal
.libsignal
.metadata
.SelfSendException
;
60 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
61 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
62 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
63 import org
.signal
.zkgroup
.InvalidInputException
;
64 import org
.signal
.zkgroup
.VerificationFailedException
;
65 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
66 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
67 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
68 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
69 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
70 import org
.slf4j
.Logger
;
71 import org
.slf4j
.LoggerFactory
;
72 import org
.whispersystems
.libsignal
.IdentityKey
;
73 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
74 import org
.whispersystems
.libsignal
.InvalidKeyException
;
75 import org
.whispersystems
.libsignal
.InvalidMessageException
;
76 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
77 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
78 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
79 import org
.whispersystems
.libsignal
.util
.Pair
;
80 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
81 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
82 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
83 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
84 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
85 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
86 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
87 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
88 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
89 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
90 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
91 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
92 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
93 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
94 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
95 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
96 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
103 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
104 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
105 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
106 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
107 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
117 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
118 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
119 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
120 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
121 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
122 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
123 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
124 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
125 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
126 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
127 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
128 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
129 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
130 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
131 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
132 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
133 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
135 import java
.io
.Closeable
;
137 import java
.io
.FileInputStream
;
138 import java
.io
.FileOutputStream
;
139 import java
.io
.IOException
;
140 import java
.io
.InputStream
;
141 import java
.io
.OutputStream
;
143 import java
.net
.URISyntaxException
;
144 import java
.net
.URLEncoder
;
145 import java
.nio
.charset
.StandardCharsets
;
146 import java
.nio
.file
.Files
;
147 import java
.security
.SignatureException
;
148 import java
.util
.ArrayList
;
149 import java
.util
.Arrays
;
150 import java
.util
.Base64
;
151 import java
.util
.Collection
;
152 import java
.util
.Date
;
153 import java
.util
.HashSet
;
154 import java
.util
.List
;
155 import java
.util
.Map
;
156 import java
.util
.Set
;
157 import java
.util
.UUID
;
158 import java
.util
.concurrent
.ExecutorService
;
159 import java
.util
.concurrent
.Executors
;
160 import java
.util
.concurrent
.TimeUnit
;
161 import java
.util
.concurrent
.TimeoutException
;
162 import java
.util
.function
.Function
;
163 import java
.util
.stream
.Collectors
;
165 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
167 public class Manager
implements Closeable
{
169 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
171 private final CertificateValidator certificateValidator
;
173 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
174 private final String userAgent
;
176 private SignalAccount account
;
177 private final SignalServiceAccountManager accountManager
;
178 private final GroupsV2Api groupsV2Api
;
179 private final GroupsV2Operations groupsV2Operations
;
180 private final SignalServiceMessageReceiver messageReceiver
;
181 private final ClientZkProfileOperations clientZkProfileOperations
;
183 private final ExecutorService executor
= Executors
.newCachedThreadPool();
185 private SignalServiceMessagePipe messagePipe
= null;
186 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
188 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
189 private final ProfileHelper profileHelper
;
190 private final GroupHelper groupHelper
;
191 private final PinHelper pinHelper
;
192 private final AvatarStore avatarStore
;
193 private final AttachmentStore attachmentStore
;
196 SignalAccount account
,
197 PathConfig pathConfig
,
198 ServiceEnvironmentConfig serviceEnvironmentConfig
,
201 this.account
= account
;
202 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
203 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
204 this.userAgent
= userAgent
;
205 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
206 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
207 final SleepTimer timer
= new UptimeSleepTimer();
208 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
209 new DynamicCredentialsProvider(account
.getUuid(),
210 account
.getUsername(),
211 account
.getPassword(),
212 account
.getDeviceId()),
215 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
217 this.groupsV2Api
= accountManager
.getGroupsV2Api();
218 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
219 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
220 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
221 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
224 this.pinHelper
= new PinHelper(keyBackupService
);
225 this.clientZkProfileOperations
= capabilities
.isGv2()
226 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
227 .getProfileOperations()
229 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
231 account
.getUsername(),
232 account
.getPassword(),
233 account
.getDeviceId(),
237 clientZkProfileOperations
,
238 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
240 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
241 account
.getProfileStore()::getProfileKey
,
242 this::getRecipientProfile
,
243 this::getSenderCertificate
);
244 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
245 unidentifiedAccessHelper
::getAccessFor
,
246 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
247 () -> messageReceiver
,
248 this::resolveSignalServiceAddress
);
249 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
250 this::getRecipientProfile
,
251 account
::getSelfRecipientId
,
254 this::getGroupAuthForToday
,
255 this::resolveSignalServiceAddress
);
256 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
257 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
260 public String
getUsername() {
261 return account
.getUsername();
264 public SignalServiceAddress
getSelfAddress() {
265 return account
.getSelfAddress();
268 private IdentityKeyPair
getIdentityKeyPair() {
269 return account
.getIdentityKeyPair();
272 public int getDeviceId() {
273 return account
.getDeviceId();
276 public static Manager
init(
277 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
278 ) throws IOException
, NotRegisteredException
{
279 var pathConfig
= PathConfig
.createDefault(settingsPath
);
281 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
282 throw new NotRegisteredException();
285 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
287 if (!account
.isRegistered()) {
288 throw new NotRegisteredException();
291 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
293 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
296 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
297 var pathConfig
= PathConfig
.createDefault(settingsPath
);
298 final var dataPath
= pathConfig
.getDataPath();
299 final var files
= dataPath
.listFiles();
305 return Arrays
.stream(files
)
306 .filter(File
::isFile
)
308 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
309 .collect(Collectors
.toList());
312 public void checkAccountState() throws IOException
{
313 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
317 if (account
.getUuid() == null) {
318 account
.setUuid(accountManager
.getOwnUuid());
321 updateAccountAttributes();
325 * This is used for checking a set of phone numbers for registration on Signal
327 * @param numbers The set of phone number in question
328 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
329 * @throws IOException if its unable to get the contacts to check if they're registered
331 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
332 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
333 var contactDetails
= getRegisteredUsers(numbers
);
335 var registeredUsers
= contactDetails
.keySet();
337 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
340 public void updateAccountAttributes() throws IOException
{
341 accountManager
.setAccountAttributes(null,
342 account
.getLocalRegistrationId(),
344 // set legacy pin only if no KBS master key is set
345 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
346 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
347 account
.getSelfUnidentifiedAccessKey(),
348 account
.isUnrestrictedUnidentifiedAccess(),
350 account
.isDiscoverableByPhoneNumber());
354 * @param name if null, the previous name will be kept
355 * @param about if null, the previous about text will be kept
356 * @param aboutEmoji if null, the previous about emoji will be kept
357 * @param avatar if avatar is null the image from the local avatar store is used (if present),
358 * if it's Optional.absent(), the avatar will be removed
360 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
361 var profile
= getRecipientProfile(account
.getSelfRecipientId());
362 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
364 builder
.withGivenName(name
);
365 builder
.withFamilyName(null);
368 builder
.withAbout(about
);
370 if (aboutEmoji
!= null) {
371 builder
.withAboutEmoji(aboutEmoji
);
373 var newProfile
= builder
.build();
375 try (final var streamDetails
= avatar
== null
376 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
377 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
378 accountManager
.setVersionedProfile(account
.getUuid(),
379 account
.getProfileKey(),
380 newProfile
.getInternalServiceName(),
381 newProfile
.getAbout(),
382 newProfile
.getAboutEmoji(),
386 if (avatar
!= null) {
387 if (avatar
.isPresent()) {
388 avatarStore
.storeProfileAvatar(getSelfAddress(),
389 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
391 avatarStore
.deleteProfileAvatar(getSelfAddress());
394 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
397 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
398 } catch (UntrustedIdentityException ignored
) {
402 public void unregister() throws IOException
{
403 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
404 // If this is the master device, other users can't send messages to this number anymore.
405 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
406 accountManager
.setGcmId(Optional
.absent());
407 accountManager
.deleteAccount();
409 account
.setRegistered(false);
413 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
414 var devices
= accountManager
.getDevices();
415 account
.setMultiDevice(devices
.size() > 1);
420 public void removeLinkedDevices(int deviceId
) throws IOException
{
421 accountManager
.removeDevice(deviceId
);
422 var devices
= accountManager
.getDevices();
423 account
.setMultiDevice(devices
.size() > 1);
427 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
428 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
430 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
433 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
434 var identityKeyPair
= getIdentityKeyPair();
435 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
437 accountManager
.addDevice(deviceIdentifier
,
440 Optional
.of(account
.getProfileKey().serialize()),
442 account
.setMultiDevice(true);
446 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
447 if (!account
.isMasterDevice()) {
448 throw new RuntimeException("Only master device can set a PIN");
450 if (pin
.isPresent()) {
451 final var masterKey
= account
.getPinMasterKey() != null
452 ? account
.getPinMasterKey()
453 : KeyUtils
.createMasterKey();
455 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
457 account
.setRegistrationLockPin(pin
.get());
458 account
.setPinMasterKey(masterKey
);
460 // Remove legacy registration lock
461 accountManager
.removeRegistrationLockV1();
464 pinHelper
.removeRegistrationLockPin();
466 account
.setRegistrationLockPin(null);
467 account
.setPinMasterKey(null);
472 void refreshPreKeys() throws IOException
{
473 var oneTimePreKeys
= generatePreKeys();
474 final var identityKeyPair
= getIdentityKeyPair();
475 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
477 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
480 private List
<PreKeyRecord
> generatePreKeys() {
481 final var offset
= account
.getPreKeyIdOffset();
483 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
484 account
.addPreKeys(records
);
489 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
490 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
492 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
493 account
.addSignedPreKey(record);
498 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
499 if (messagePipe
== null) {
500 messagePipe
= messageReceiver
.createMessagePipe();
505 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
506 if (unidentifiedMessagePipe
== null) {
507 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
509 return unidentifiedMessagePipe
;
512 private SignalServiceMessageSender
createMessageSender() {
513 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
515 account
.getUsername(),
516 account
.getPassword(),
517 account
.getDeviceId(),
518 account
.getSignalProtocolStore(),
520 account
.isMultiDevice(),
521 Optional
.fromNullable(messagePipe
),
522 Optional
.fromNullable(unidentifiedMessagePipe
),
524 clientZkProfileOperations
,
526 ServiceConfig
.MAX_ENVELOPE_SIZE
,
527 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
530 public Profile
getRecipientProfile(
531 SignalServiceAddress address
533 return getRecipientProfile(resolveRecipient(address
), false);
536 public Profile
getRecipientProfile(
537 RecipientId recipientId
539 return getRecipientProfile(recipientId
, false);
542 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
544 Profile
getRecipientProfile(
545 RecipientId recipientId
, boolean force
547 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
548 if (profileKey
== null) {
550 // retrieve profile to get identity key
551 retrieveEncryptedProfile(recipientId
);
555 var profile
= account
.getProfileStore().getProfile(recipientId
);
557 var now
= new Date().getTime();
558 // Profiles are cached for 24h before retrieving them again, unless forced
559 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
563 synchronized (pendingProfileRequest
) {
564 if (pendingProfileRequest
.contains(recipientId
)) {
567 pendingProfileRequest
.add(recipientId
);
569 final SignalServiceProfile encryptedProfile
;
571 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
573 synchronized (pendingProfileRequest
) {
574 pendingProfileRequest
.remove(recipientId
);
577 if (encryptedProfile
== null) {
581 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
582 account
.getProfileStore().storeProfile(recipientId
, profile
);
587 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
589 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
590 } catch (IOException e
) {
591 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
596 private ProfileAndCredential
retrieveProfileAndCredential(
597 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
598 ) throws IOException
{
599 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
600 final var profile
= profileAndCredential
.getProfile();
603 account
.getIdentityKeyStore()
604 .saveIdentity(recipientId
,
605 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
607 } catch (InvalidKeyException ignored
) {
608 logger
.warn("Got invalid identity key in profile for {}",
609 resolveSignalServiceAddress(recipientId
).getLegacyIdentifier());
611 return profileAndCredential
;
614 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
615 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
616 if (profileKeyCredential
!= null) {
617 return profileKeyCredential
;
620 ProfileAndCredential profileAndCredential
;
622 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
623 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
624 } catch (IOException e
) {
625 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
629 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
630 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
632 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
633 if (profileKey
!= null) {
634 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
636 profileAndCredential
.getProfile());
637 account
.getProfileStore().storeProfile(recipientId
, profile
);
640 return profileKeyCredential
;
643 private Profile
decryptProfileAndDownloadAvatar(
644 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
646 if (encryptedProfile
.getAvatar() != null) {
647 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
650 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
653 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
654 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
655 if (streamDetails
== null) {
656 return Optional
.absent();
659 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
662 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
663 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
664 if (streamDetails
== null) {
665 return Optional
.absent();
668 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
671 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
672 var g
= getGroup(groupId
);
674 throw new GroupNotFoundException(groupId
);
676 if (!g
.isMember(account
.getSelfAddress())) {
677 throw new NotAGroupMemberException(groupId
, g
.getTitle());
682 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
683 var g
= getGroup(groupId
);
685 throw new GroupNotFoundException(groupId
);
687 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
688 throw new NotAGroupMemberException(groupId
, g
.getTitle());
693 public List
<GroupInfo
> getGroups() {
694 return account
.getGroupStore().getGroups();
697 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
698 String messageText
, List
<String
> attachments
, GroupId groupId
699 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
700 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
701 if (attachments
!= null) {
702 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
705 return sendGroupMessage(messageBuilder
, groupId
);
708 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
709 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
710 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
711 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
713 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
714 targetSentTimestamp
);
715 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
717 return sendGroupMessage(messageBuilder
, groupId
);
720 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
721 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
722 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
723 final var g
= getGroupForSending(groupId
);
725 GroupUtils
.setGroupContext(messageBuilder
, g
);
726 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
728 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
731 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
732 SignalServiceDataMessage
.Builder messageBuilder
;
734 final var g
= getGroupForUpdating(groupId
);
735 if (g
instanceof GroupInfoV1
) {
736 var groupInfoV1
= (GroupInfoV1
) g
;
737 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
738 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
739 groupInfoV1
.removeMember(account
.getSelfAddress());
740 account
.getGroupStore().updateGroup(groupInfoV1
);
742 final var groupInfoV2
= (GroupInfoV2
) g
;
743 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
744 groupInfoV2
.setGroup(groupGroupChangePair
.first());
745 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
746 account
.getGroupStore().updateGroup(groupInfoV2
);
749 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
752 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
753 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
754 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
755 return sendUpdateGroupMessage(groupId
,
759 : getSignalServiceAddresses(members
).stream()
760 .map(this::resolveRecipient
)
761 .collect(Collectors
.toSet()),
765 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
766 GroupId groupId
, String name
, Set
<RecipientId
> members
, File avatarFile
767 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
769 SignalServiceDataMessage
.Builder messageBuilder
;
770 if (groupId
== null) {
772 var gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
773 members
== null ? Set
.of() : members
,
776 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
777 gv1
.addMembers(List
.of(account
.getSelfAddress()));
778 updateGroupV1(gv1
, name
, members
, avatarFile
);
779 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
782 if (avatarFile
!= null) {
783 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
784 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
786 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
790 var group
= getGroupForUpdating(groupId
);
791 if (group
instanceof GroupInfoV2
) {
792 final var groupInfoV2
= (GroupInfoV2
) group
;
794 Pair
<Long
, List
<SendMessageResult
>> result
= null;
795 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
796 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
797 result
= sendUpdateGroupMessage(groupInfoV2
,
798 groupGroupChangePair
.first(),
799 groupGroupChangePair
.second());
802 if (members
!= null) {
803 final var newMembers
= new HashSet
<>(members
);
804 newMembers
.removeAll(group
.getMembers()
806 .map(this::resolveRecipient
)
807 .collect(Collectors
.toSet()));
808 if (newMembers
.size() > 0) {
809 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
810 result
= sendUpdateGroupMessage(groupInfoV2
,
811 groupGroupChangePair
.first(),
812 groupGroupChangePair
.second());
815 if (result
== null || name
!= null || avatarFile
!= null) {
816 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
817 if (avatarFile
!= null) {
818 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
819 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
821 result
= sendUpdateGroupMessage(groupInfoV2
,
822 groupGroupChangePair
.first(),
823 groupGroupChangePair
.second());
826 return new Pair
<>(group
.getGroupId(), result
.second());
828 var gv1
= (GroupInfoV1
) group
;
829 updateGroupV1(gv1
, name
, members
, avatarFile
);
830 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
835 account
.getGroupStore().updateGroup(g
);
837 final var result
= sendMessage(messageBuilder
, g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
838 return new Pair
<>(g
.getGroupId(), result
.second());
841 private void updateGroupV1(
842 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
843 ) throws IOException
{
848 if (members
!= null) {
849 final var memberAddresses
= members
.stream()
850 .map(this::resolveSignalServiceAddress
)
851 .collect(Collectors
.toList());
852 final var newE164Members
= new HashSet
<String
>();
853 for (var member
: memberAddresses
) {
854 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
857 newE164Members
.add(member
.getNumber().get());
860 final var registeredUsers
= getRegisteredUsers(newE164Members
);
861 if (registeredUsers
.size() != newE164Members
.size()) {
862 // Some of the new members are not registered on Signal
863 newE164Members
.removeAll(registeredUsers
.keySet());
864 throw new IOException("Failed to add members "
865 + String
.join(", ", newE164Members
)
866 + " to group: Not registered on Signal");
869 g
.addMembers(memberAddresses
);
872 if (avatarFile
!= null) {
873 avatarStore
.storeGroupAvatar(g
.getGroupId(),
874 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
878 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
879 GroupInviteLinkUrl inviteLinkUrl
880 ) throws IOException
, GroupLinkNotActiveException
{
881 return sendJoinGroupMessage(inviteLinkUrl
);
884 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
885 GroupInviteLinkUrl inviteLinkUrl
886 ) throws IOException
, GroupLinkNotActiveException
{
887 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
888 inviteLinkUrl
.getPassword());
889 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
890 inviteLinkUrl
.getPassword(),
892 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
893 groupJoinInfo
.getRevision() + 1,
894 groupChange
.toByteArray());
896 if (group
.getGroup() == null) {
897 // Only requested member, can't send update to group members
898 return new Pair
<>(group
.getGroupId(), List
.of());
901 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
903 return new Pair
<>(group
.getGroupId(), result
.second());
906 private static int currentTimeDays() {
907 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
910 private GroupsV2AuthorizationString
getGroupAuthForToday(
911 final GroupSecretParams groupSecretParams
912 ) throws IOException
{
913 final var today
= currentTimeDays();
914 // Returns credentials for the next 7 days
915 final var credentials
= groupsV2Api
.getCredentials(today
);
916 // TODO cache credentials until they expire
917 var authCredentialResponse
= credentials
.get(today
);
919 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
922 authCredentialResponse
);
923 } catch (VerificationFailedException e
) {
924 throw new IOException(e
);
928 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
929 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
930 ) throws IOException
{
931 group
.setGroup(newDecryptedGroup
);
932 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
933 account
.getGroupStore().updateGroup(group
);
934 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
937 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
938 GroupIdV1 groupId
, SignalServiceAddress recipient
939 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
941 var group
= getGroupForSending(groupId
);
942 if (!(group
instanceof GroupInfoV1
)) {
943 throw new RuntimeException("Received an invalid group request for a v2 group!");
945 g
= (GroupInfoV1
) group
;
947 if (!g
.isMember(recipient
)) {
948 throw new NotAGroupMemberException(groupId
, g
.name
);
951 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
953 // Send group message only to the recipient who requested it
954 return sendMessage(messageBuilder
, List
.of(recipient
));
957 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
958 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
959 .withId(g
.getGroupId().serialize())
961 .withMembers(new ArrayList
<>(g
.getMembers()));
964 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
965 if (attachment
.isPresent()) {
966 group
.withAvatar(attachment
.get());
968 } catch (IOException e
) {
969 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
972 return SignalServiceDataMessage
.newBuilder()
973 .asGroupMessage(group
.build())
974 .withExpiration(g
.getMessageExpirationTime());
977 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
978 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
979 .withRevision(g
.getGroup().getRevision())
980 .withSignedGroupChange(signedGroupChange
);
981 return SignalServiceDataMessage
.newBuilder()
982 .asGroupMessage(group
.build())
983 .withExpiration(g
.getMessageExpirationTime());
986 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
987 GroupIdV1 groupId
, SignalServiceAddress recipient
988 ) throws IOException
{
989 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
991 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
993 // Send group info request message to the recipient who sent us a message with this groupId
994 return sendMessage(messageBuilder
, List
.of(recipient
));
998 SignalServiceAddress remoteAddress
, long messageId
999 ) throws IOException
, UntrustedIdentityException
{
1000 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1002 System
.currentTimeMillis());
1004 createMessageSender().sendReceipt(remoteAddress
,
1005 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1009 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1010 String messageText
, List
<String
> attachments
, List
<String
> recipients
1011 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1012 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1013 if (attachments
!= null) {
1014 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1016 // Upload attachments here, so we only upload once even for multiple recipients
1017 var messageSender
= createMessageSender();
1018 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1019 for (var attachment
: attachmentStreams
) {
1020 if (attachment
.isStream()) {
1021 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1022 } else if (attachment
.isPointer()) {
1023 attachmentPointers
.add(attachment
.asPointer());
1027 messageBuilder
.withAttachments(attachmentPointers
);
1029 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1032 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1033 String messageText
, List
<String
> attachments
1034 ) throws IOException
, AttachmentInvalidException
{
1035 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1036 if (attachments
!= null) {
1037 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1039 return sendSelfMessage(messageBuilder
);
1042 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1043 long targetSentTimestamp
, List
<String
> recipients
1044 ) throws IOException
, InvalidNumberException
{
1045 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1046 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1047 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1050 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1051 long targetSentTimestamp
, GroupId groupId
1052 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1053 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1054 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1055 return sendGroupMessage(messageBuilder
, groupId
);
1058 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1059 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1060 ) throws IOException
, InvalidNumberException
{
1061 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1063 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1064 targetSentTimestamp
);
1065 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1066 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1069 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1070 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1072 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1074 return sendMessage(messageBuilder
, signalServiceAddresses
);
1075 } catch (Exception e
) {
1076 for (var address
: signalServiceAddresses
) {
1077 handleEndSession(address
);
1084 public String
getContactName(String number
) throws InvalidNumberException
{
1085 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1086 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1089 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1090 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1091 var contact
= account
.getContactStore().getContact(recipientId
);
1092 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1093 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1097 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1098 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1101 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1102 var contact
= account
.getContactStore().getContact(recipientId
);
1103 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1104 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1108 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1109 var group
= getGroup(groupId
);
1110 if (group
== null) {
1111 throw new GroupNotFoundException(groupId
);
1114 group
.setBlocked(blocked
);
1115 account
.getGroupStore().updateGroup(group
);
1119 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1120 var contact
= account
.getContactStore().getContact(recipientId
);
1121 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1124 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1125 account
.getContactStore()
1126 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1129 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1130 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1131 sendMessage(messageBuilder
, List
.of(address
));
1135 * Change the expiration timer for a contact
1137 public void setExpirationTimer(
1138 String number
, int messageExpirationTimer
1139 ) throws IOException
, InvalidNumberException
{
1140 var recipientId
= canonicalizeAndResolveRecipient(number
);
1141 setExpirationTimer(recipientId
, messageExpirationTimer
);
1142 sendExpirationTimerUpdate(resolveSignalServiceAddress(recipientId
));
1147 * Change the expiration timer for a group
1149 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1150 var g
= getGroup(groupId
);
1151 if (g
instanceof GroupInfoV1
) {
1152 var groupInfoV1
= (GroupInfoV1
) g
;
1153 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1154 account
.getGroupStore().updateGroup(groupInfoV1
);
1156 throw new RuntimeException("TODO Not implemented!");
1161 * Upload the sticker pack from path.
1163 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1164 * @return if successful, returns the URL to install the sticker pack in the signal app
1166 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1167 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1169 var messageSender
= createMessageSender();
1171 var packKey
= KeyUtils
.createStickerUploadKey();
1172 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1174 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1175 account
.getStickerStore().updateSticker(sticker
);
1179 return new URI("https",
1182 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1183 Hex
.toStringCondensed(packKey
),
1184 StandardCharsets
.UTF_8
)).toString();
1185 } catch (URISyntaxException e
) {
1186 throw new AssertionError(e
);
1190 void requestSyncGroups() throws IOException
{
1191 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1192 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1194 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1196 sendSyncMessage(message
);
1197 } catch (UntrustedIdentityException e
) {
1198 throw new AssertionError(e
);
1202 void requestSyncContacts() throws IOException
{
1203 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1204 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1206 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1208 sendSyncMessage(message
);
1209 } catch (UntrustedIdentityException e
) {
1210 throw new AssertionError(e
);
1214 void requestSyncBlocked() throws IOException
{
1215 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1216 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1218 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1220 sendSyncMessage(message
);
1221 } catch (UntrustedIdentityException e
) {
1222 throw new AssertionError(e
);
1226 void requestSyncConfiguration() throws IOException
{
1227 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1228 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1230 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1232 sendSyncMessage(message
);
1233 } catch (UntrustedIdentityException e
) {
1234 throw new AssertionError(e
);
1238 void requestSyncKeys() throws IOException
{
1239 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1240 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1242 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1244 sendSyncMessage(message
);
1245 } catch (UntrustedIdentityException e
) {
1246 throw new AssertionError(e
);
1250 private byte[] getSenderCertificate() {
1251 // TODO support UUID capable sender certificates
1252 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1255 certificate
= accountManager
.getSenderCertificate();
1256 } catch (IOException e
) {
1257 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1260 // TODO cache for a day
1264 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1265 var messageSender
= createMessageSender();
1266 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1269 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1270 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1271 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1273 for (var number
: numbers
) {
1274 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1275 if (resolvedAddress
.getUuid().isPresent()) {
1276 signalServiceAddresses
.add(resolvedAddress
);
1278 addressesMissingUuid
.add(resolvedAddress
);
1282 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1283 .map(a
-> a
.getNumber().get())
1284 .collect(Collectors
.toSet());
1285 Map
<String
, UUID
> registeredUsers
;
1287 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1288 } catch (IOException e
) {
1289 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1290 registeredUsers
= Map
.of();
1293 for (var address
: addressesMissingUuid
) {
1294 final var number
= address
.getNumber().get();
1295 if (registeredUsers
.containsKey(number
)) {
1296 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1297 registeredUsers
.get(number
),
1299 signalServiceAddresses
.add(newAddress
);
1301 signalServiceAddresses
.add(address
);
1305 return signalServiceAddresses
;
1308 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1310 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1312 serviceEnvironmentConfig
.getCdsMrenclave());
1313 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1314 throw new IOException(e
);
1318 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1319 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1320 ) throws IOException
{
1321 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1322 final var recipientIds
= recipients
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1323 final var timestamp
= System
.currentTimeMillis();
1324 messageBuilder
.withTimestamp(timestamp
);
1325 getOrCreateMessagePipe();
1326 getOrCreateUnidentifiedMessagePipe();
1327 SignalServiceDataMessage message
= null;
1329 message
= messageBuilder
.build();
1330 if (message
.getGroupContext().isPresent()) {
1332 var messageSender
= createMessageSender();
1333 final var isRecipientUpdate
= false;
1334 var result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1335 unidentifiedAccessHelper
.getAccessFor(recipientIds
),
1339 for (var r
: result
) {
1340 if (r
.getIdentityFailure() != null) {
1341 account
.getIdentityKeyStore().
1342 saveIdentity(resolveRecipient(r
.getAddress()),
1343 r
.getIdentityFailure().getIdentityKey(),
1348 return new Pair
<>(timestamp
, result
);
1349 } catch (UntrustedIdentityException e
) {
1350 return new Pair
<>(timestamp
, List
.of());
1353 // Send to all individually, so sync messages are sent correctly
1354 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1355 var results
= new ArrayList
<SendMessageResult
>(recipients
.size());
1356 for (var address
: recipients
) {
1357 final var contact
= account
.getContactStore().getContact(resolveRecipient(address
));
1358 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1359 messageBuilder
.withExpiration(expirationTime
);
1360 message
= messageBuilder
.build();
1361 results
.add(sendMessage(address
, message
));
1363 return new Pair
<>(timestamp
, results
);
1366 if (message
!= null && message
.isEndSession()) {
1367 for (var recipient
: recipients
) {
1368 handleEndSession(recipient
);
1375 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1376 SignalServiceDataMessage
.Builder messageBuilder
1377 ) throws IOException
{
1378 final var timestamp
= System
.currentTimeMillis();
1379 messageBuilder
.withTimestamp(timestamp
);
1380 getOrCreateMessagePipe();
1381 getOrCreateUnidentifiedMessagePipe();
1383 final var recipientId
= account
.getSelfRecipientId();
1385 final var contact
= account
.getContactStore().getContact(recipientId
);
1386 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1387 messageBuilder
.withExpiration(expirationTime
);
1389 var message
= messageBuilder
.build();
1390 final var result
= sendSelfMessage(message
);
1391 return new Pair
<>(timestamp
, result
);
1397 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1398 var messageSender
= createMessageSender();
1400 var recipient
= account
.getSelfAddress();
1402 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(resolveRecipient(recipient
));
1403 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1404 message
.getTimestamp(),
1406 message
.getExpiresInSeconds(),
1407 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1409 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1412 var startTime
= System
.currentTimeMillis();
1413 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1414 return SendMessageResult
.success(recipient
,
1415 unidentifiedAccess
.isPresent(),
1417 System
.currentTimeMillis() - startTime
);
1418 } catch (UntrustedIdentityException e
) {
1419 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1423 private SendMessageResult
sendMessage(
1424 SignalServiceAddress address
, SignalServiceDataMessage message
1425 ) throws IOException
{
1426 var messageSender
= createMessageSender();
1429 return messageSender
.sendMessage(address
,
1430 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(address
)),
1432 } catch (UntrustedIdentityException e
) {
1433 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1437 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1438 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1439 account
.getSignalProtocolStore(),
1440 certificateValidator
);
1442 return cipher
.decrypt(envelope
);
1443 } catch (ProtocolUntrustedIdentityException e
) {
1444 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1445 throw (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1447 throw new AssertionError(e
);
1451 private void handleEndSession(SignalServiceAddress source
) {
1452 account
.getSessionStore().deleteAllSessions(source
.getIdentifier());
1455 private List
<HandleAction
> handleSignalServiceDataMessage(
1456 SignalServiceDataMessage message
,
1458 SignalServiceAddress source
,
1459 SignalServiceAddress destination
,
1460 boolean ignoreAttachments
1462 var actions
= new ArrayList
<HandleAction
>();
1463 if (message
.getGroupContext().isPresent()) {
1464 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1465 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1466 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1467 var group
= getGroup(groupId
);
1468 if (group
== null || group
instanceof GroupInfoV1
) {
1469 var groupV1
= (GroupInfoV1
) group
;
1470 switch (groupInfo
.getType()) {
1472 if (groupV1
== null) {
1473 groupV1
= new GroupInfoV1(groupId
);
1476 if (groupInfo
.getAvatar().isPresent()) {
1477 var avatar
= groupInfo
.getAvatar().get();
1478 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1481 if (groupInfo
.getName().isPresent()) {
1482 groupV1
.name
= groupInfo
.getName().get();
1485 if (groupInfo
.getMembers().isPresent()) {
1486 groupV1
.addMembers(groupInfo
.getMembers()
1489 .map(this::resolveSignalServiceAddress
)
1490 .collect(Collectors
.toSet()));
1493 account
.getGroupStore().updateGroup(groupV1
);
1497 if (groupV1
== null && !isSync
) {
1498 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1502 if (groupV1
!= null) {
1503 groupV1
.removeMember(source
);
1504 account
.getGroupStore().updateGroup(groupV1
);
1509 if (groupV1
!= null && !isSync
) {
1510 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1515 // Received a group v1 message for a v2 group
1518 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1519 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1520 final var groupMasterKey
= groupContext
.getMasterKey();
1522 getOrMigrateGroup(groupMasterKey
,
1523 groupContext
.getRevision(),
1524 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1528 final var conversationPartnerAddress
= isSync ? destination
: source
;
1529 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1530 handleEndSession(conversationPartnerAddress
);
1532 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1533 if (message
.getGroupContext().isPresent()) {
1534 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1535 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1536 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1537 if (group
!= null) {
1538 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1539 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1540 account
.getGroupStore().updateGroup(group
);
1543 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1544 // disappearing message timer already stored in the DecryptedGroup
1546 } else if (conversationPartnerAddress
!= null) {
1547 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1550 if (!ignoreAttachments
) {
1551 if (message
.getAttachments().isPresent()) {
1552 for (var attachment
: message
.getAttachments().get()) {
1553 downloadAttachment(attachment
);
1556 if (message
.getSharedContacts().isPresent()) {
1557 for (var contact
: message
.getSharedContacts().get()) {
1558 if (contact
.getAvatar().isPresent()) {
1559 downloadAttachment(contact
.getAvatar().get().getAttachment());
1564 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1565 final ProfileKey profileKey
;
1567 profileKey
= new ProfileKey(message
.getProfileKey().get());
1568 } catch (InvalidInputException e
) {
1569 throw new AssertionError(e
);
1571 if (source
.matches(account
.getSelfAddress())) {
1572 this.account
.setProfileKey(profileKey
);
1574 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1576 if (message
.getPreviews().isPresent()) {
1577 final var previews
= message
.getPreviews().get();
1578 for (var preview
: previews
) {
1579 if (preview
.getImage().isPresent()) {
1580 downloadAttachment(preview
.getImage().get());
1584 if (message
.getQuote().isPresent()) {
1585 final var quote
= message
.getQuote().get();
1587 for (var quotedAttachment
: quote
.getAttachments()) {
1588 final var thumbnail
= quotedAttachment
.getThumbnail();
1589 if (thumbnail
!= null) {
1590 downloadAttachment(thumbnail
);
1594 if (message
.getSticker().isPresent()) {
1595 final var messageSticker
= message
.getSticker().get();
1596 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1597 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1598 if (sticker
== null) {
1599 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1600 account
.getStickerStore().updateSticker(sticker
);
1606 private GroupInfoV2
getOrMigrateGroup(
1607 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1609 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1611 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1612 var groupInfo
= getGroup(groupId
);
1613 final GroupInfoV2 groupInfoV2
;
1614 if (groupInfo
instanceof GroupInfoV1
) {
1615 // Received a v2 group message for a v1 group, we need to locally migrate the group
1616 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1617 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1618 logger
.info("Locally migrated group {} to group v2, id: {}",
1619 groupInfo
.getGroupId().toBase64(),
1620 groupInfoV2
.getGroupId().toBase64());
1621 } else if (groupInfo
instanceof GroupInfoV2
) {
1622 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1624 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1627 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1628 DecryptedGroup group
= null;
1629 if (signedGroupChange
!= null
1630 && groupInfoV2
.getGroup() != null
1631 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1632 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1634 if (group
== null) {
1635 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1637 if (group
!= null) {
1638 storeProfileKeysFromMembers(group
);
1639 final var avatar
= group
.getAvatar();
1640 if (avatar
!= null && !avatar
.isEmpty()) {
1641 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1644 groupInfoV2
.setGroup(group
);
1645 account
.getGroupStore().updateGroup(groupInfoV2
);
1651 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1652 for (var member
: group
.getMembersList()) {
1653 final var address
= resolveRecipient(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1654 .toByteArray()), null));
1656 account
.getProfileStore()
1657 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1658 } catch (InvalidInputException ignored
) {
1663 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1664 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1665 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1666 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1667 if (actions
!= null) {
1668 queuedActions
.addAll(actions
);
1671 for (var action
: queuedActions
) {
1673 action
.execute(this);
1674 } catch (Throwable e
) {
1675 logger
.warn("Message action failed.", e
);
1680 private List
<HandleAction
> retryFailedReceivedMessage(
1681 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1683 var envelope
= cachedMessage
.loadEnvelope();
1684 if (envelope
== null) {
1687 SignalServiceContent content
= null;
1688 List
<HandleAction
> actions
= null;
1689 if (!envelope
.isReceipt()) {
1691 content
= decryptMessage(envelope
);
1692 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1693 if (!envelope
.hasSource()) {
1694 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
)
1697 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1698 } catch (IOException ioException
) {
1699 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1703 } catch (Exception er
) {
1704 // All other errors are not recoverable, so delete the cached message
1705 cachedMessage
.delete();
1708 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1711 handler
.handleMessage(envelope
, content
, null);
1712 cachedMessage
.delete();
1716 public void receiveMessages(
1719 boolean returnOnTimeout
,
1720 boolean ignoreAttachments
,
1721 ReceiveMessageHandler handler
1722 ) throws IOException
{
1723 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1725 Set
<HandleAction
> queuedActions
= null;
1727 final var messagePipe
= getOrCreateMessagePipe();
1729 var hasCaughtUpWithOldMessages
= false;
1732 SignalServiceEnvelope envelope
;
1733 SignalServiceContent content
= null;
1734 Exception exception
= null;
1735 final CachedMessage
[] cachedMessage
= {null};
1737 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1738 final var recipientId
= envelope1
.hasSource()
1739 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1741 // store message on disk, before acknowledging receipt to the server
1742 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1744 if (result
.isPresent()) {
1745 envelope
= result
.get();
1747 // Received indicator that server queue is empty
1748 hasCaughtUpWithOldMessages
= true;
1750 if (queuedActions
!= null) {
1751 for (var action
: queuedActions
) {
1753 action
.execute(this);
1754 } catch (Throwable e
) {
1755 logger
.warn("Message action failed.", e
);
1759 queuedActions
.clear();
1760 queuedActions
= null;
1763 // Continue to wait another timeout for new messages
1766 } catch (TimeoutException e
) {
1767 if (returnOnTimeout
) return;
1771 if (envelope
.hasSource()) {
1772 // Store uuid if we don't have it already
1773 resolveRecipientTrusted(envelope
.getSourceAddress());
1775 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1776 if (!envelope
.isReceipt()) {
1778 content
= decryptMessage(envelope
);
1779 } catch (Exception e
) {
1782 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1783 if (hasCaughtUpWithOldMessages
) {
1784 for (var action
: actions
) {
1786 action
.execute(this);
1787 } catch (Throwable e
) {
1788 logger
.warn("Message action failed.", e
);
1792 if (queuedActions
== null) {
1793 queuedActions
= new HashSet
<>();
1795 queuedActions
.addAll(actions
);
1799 if (isMessageBlocked(envelope
, content
)) {
1800 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1801 } else if (notAGroupMember
) {
1802 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1804 handler
.handleMessage(envelope
, content
, exception
);
1806 if (cachedMessage
[0] != null) {
1807 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1808 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
)
1810 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1811 if (!envelope
.hasSource()) {
1813 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1814 } catch (IOException ioException
) {
1815 logger
.warn("Failed to move cached message to recipient folder: {}",
1816 ioException
.getMessage());
1820 cachedMessage
[0].delete();
1826 private boolean isMessageBlocked(
1827 SignalServiceEnvelope envelope
, SignalServiceContent content
1829 SignalServiceAddress source
;
1830 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1831 source
= envelope
.getSourceAddress();
1832 } else if (content
!= null) {
1833 source
= content
.getSender();
1837 final var recipientId
= resolveRecipient(source
);
1838 if (isContactBlocked(recipientId
)) {
1842 if (content
!= null && content
.getDataMessage().isPresent()) {
1843 var message
= content
.getDataMessage().get();
1844 if (message
.getGroupContext().isPresent()) {
1845 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1846 var group
= getGroup(groupId
);
1847 if (group
!= null && group
.isBlocked()) {
1855 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
1856 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
1857 return isContactBlocked(recipientId
);
1860 private boolean isContactBlocked(final RecipientId recipientId
) {
1861 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1862 return sourceContact
!= null && sourceContact
.isBlocked();
1865 private boolean isNotAGroupMember(
1866 SignalServiceEnvelope envelope
, SignalServiceContent content
1868 SignalServiceAddress source
;
1869 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1870 source
= envelope
.getSourceAddress();
1871 } else if (content
!= null) {
1872 source
= content
.getSender();
1877 if (content
!= null && content
.getDataMessage().isPresent()) {
1878 var message
= content
.getDataMessage().get();
1879 if (message
.getGroupContext().isPresent()) {
1880 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1881 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1882 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1886 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1887 var group
= getGroup(groupId
);
1888 if (group
!= null && !group
.isMember(source
)) {
1896 private List
<HandleAction
> handleMessage(
1897 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1899 var actions
= new ArrayList
<HandleAction
>();
1900 if (content
!= null) {
1901 final SignalServiceAddress sender
;
1902 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1903 sender
= envelope
.getSourceAddress();
1905 sender
= content
.getSender();
1908 if (content
.getDataMessage().isPresent()) {
1909 var message
= content
.getDataMessage().get();
1911 if (content
.isNeedsReceipt()) {
1912 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1915 actions
.addAll(handleSignalServiceDataMessage(message
,
1918 account
.getSelfAddress(),
1919 ignoreAttachments
));
1921 if (content
.getSyncMessage().isPresent()) {
1922 account
.setMultiDevice(true);
1923 var syncMessage
= content
.getSyncMessage().get();
1924 if (syncMessage
.getSent().isPresent()) {
1925 var message
= syncMessage
.getSent().get();
1926 final var destination
= message
.getDestination().orNull();
1927 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1931 ignoreAttachments
));
1933 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
1934 var rm
= syncMessage
.getRequest().get();
1935 if (rm
.isContactsRequest()) {
1936 actions
.add(SendSyncContactsAction
.create());
1938 if (rm
.isGroupsRequest()) {
1939 actions
.add(SendSyncGroupsAction
.create());
1941 if (rm
.isBlockedListRequest()) {
1942 actions
.add(SendSyncBlockedListAction
.create());
1944 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1946 if (syncMessage
.getGroups().isPresent()) {
1947 File tmpFile
= null;
1949 tmpFile
= IOUtils
.createTempFile();
1950 final var groupsMessage
= syncMessage
.getGroups().get();
1951 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1952 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1954 while ((g
= s
.read()) != null) {
1955 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1956 if (syncGroup
!= null) {
1957 if (g
.getName().isPresent()) {
1958 syncGroup
.name
= g
.getName().get();
1960 syncGroup
.addMembers(g
.getMembers()
1962 .map(this::resolveSignalServiceAddress
)
1963 .collect(Collectors
.toSet()));
1964 if (!g
.isActive()) {
1965 syncGroup
.removeMember(account
.getSelfAddress());
1967 // Add ourself to the member set as it's marked as active
1968 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1970 syncGroup
.blocked
= g
.isBlocked();
1971 if (g
.getColor().isPresent()) {
1972 syncGroup
.color
= g
.getColor().get();
1975 if (g
.getAvatar().isPresent()) {
1976 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1978 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1979 syncGroup
.archived
= g
.isArchived();
1980 account
.getGroupStore().updateGroup(syncGroup
);
1984 } catch (Exception e
) {
1985 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1989 if (tmpFile
!= null) {
1991 Files
.delete(tmpFile
.toPath());
1992 } catch (IOException e
) {
1993 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2000 if (syncMessage
.getBlockedList().isPresent()) {
2001 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2002 for (var address
: blockedListMessage
.getAddresses()) {
2003 setContactBlocked(resolveRecipient(address
), true);
2005 for (var groupId
: blockedListMessage
.getGroupIds()
2007 .map(GroupId
::unknownVersion
)
2008 .collect(Collectors
.toSet())) {
2010 setGroupBlocked(groupId
, true);
2011 } catch (GroupNotFoundException e
) {
2012 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2013 groupId
.toBase64());
2017 if (syncMessage
.getContacts().isPresent()) {
2018 File tmpFile
= null;
2020 tmpFile
= IOUtils
.createTempFile();
2021 final var contactsMessage
= syncMessage
.getContacts().get();
2022 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2023 .asPointer(), tmpFile
)) {
2024 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2026 while ((c
= s
.read()) != null) {
2027 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2028 account
.setProfileKey(c
.getProfileKey().get());
2030 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2031 var contact
= account
.getContactStore().getContact(recipientId
);
2032 final var builder
= contact
== null
2033 ? Contact
.newBuilder()
2034 : Contact
.newBuilder(contact
);
2035 if (c
.getName().isPresent()) {
2036 builder
.withName(c
.getName().get());
2038 if (c
.getColor().isPresent()) {
2039 builder
.withColor(c
.getColor().get());
2041 if (c
.getProfileKey().isPresent()) {
2042 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2044 if (c
.getVerified().isPresent()) {
2045 final var verifiedMessage
= c
.getVerified().get();
2046 account
.getIdentityKeyStore()
2047 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2048 verifiedMessage
.getIdentityKey(),
2049 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2051 if (c
.getExpirationTimer().isPresent()) {
2052 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2054 builder
.withBlocked(c
.isBlocked());
2055 builder
.withArchived(c
.isArchived());
2056 account
.getContactStore().storeContact(recipientId
, builder
.build());
2058 if (c
.getAvatar().isPresent()) {
2059 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2063 } catch (Exception e
) {
2064 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2068 if (tmpFile
!= null) {
2070 Files
.delete(tmpFile
.toPath());
2071 } catch (IOException e
) {
2072 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2079 if (syncMessage
.getVerified().isPresent()) {
2080 final var verifiedMessage
= syncMessage
.getVerified().get();
2081 account
.getIdentityKeyStore()
2082 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2083 verifiedMessage
.getIdentityKey(),
2084 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2086 if (syncMessage
.getStickerPackOperations().isPresent()) {
2087 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2088 for (var m
: stickerPackOperationMessages
) {
2089 if (!m
.getPackId().isPresent()) {
2092 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2093 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2094 if (sticker
== null) {
2095 if (!m
.getPackKey().isPresent()) {
2098 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2100 sticker
.setInstalled(!m
.getType().isPresent()
2101 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2102 account
.getStickerStore().updateSticker(sticker
);
2105 if (syncMessage
.getFetchType().isPresent()) {
2106 switch (syncMessage
.getFetchType().get()) {
2108 getRecipientProfile(account
.getSelfRecipientId(), true);
2109 case STORAGE_MANIFEST
:
2113 if (syncMessage
.getKeys().isPresent()) {
2114 final var keysMessage
= syncMessage
.getKeys().get();
2115 if (keysMessage
.getStorageService().isPresent()) {
2116 final var storageKey
= keysMessage
.getStorageService().get();
2117 account
.setStorageKey(storageKey
);
2120 if (syncMessage
.getConfiguration().isPresent()) {
2128 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2130 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2131 } catch (IOException e
) {
2132 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2136 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2138 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2139 } catch (IOException e
) {
2140 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2144 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2146 avatarStore
.storeGroupAvatar(groupId
,
2147 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2148 } catch (IOException e
) {
2149 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2153 private void downloadProfileAvatar(
2154 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2157 avatarStore
.storeProfileAvatar(address
,
2158 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2159 } catch (Throwable e
) {
2160 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2164 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2165 return attachmentStore
.getAttachmentFile(attachmentId
);
2168 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2169 if (!attachment
.isPointer()) {
2170 logger
.warn("Invalid state, can't store an attachment stream.");
2173 var pointer
= attachment
.asPointer();
2174 if (pointer
.getPreview().isPresent()) {
2175 final var preview
= pointer
.getPreview().get();
2177 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2178 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2179 } catch (IOException e
) {
2180 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2185 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2186 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2187 } catch (IOException e
) {
2188 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2192 private void retrieveGroupV2Avatar(
2193 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2194 ) throws IOException
{
2195 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2197 var tmpFile
= IOUtils
.createTempFile();
2198 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2200 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2201 var encryptedData
= IOUtils
.readFully(input
);
2203 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2204 outputStream
.write(decryptedData
);
2207 Files
.delete(tmpFile
.toPath());
2208 } catch (IOException e
) {
2209 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2216 private void retrieveProfileAvatar(
2217 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2218 ) throws IOException
{
2219 var tmpFile
= IOUtils
.createTempFile();
2220 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2223 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2224 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2225 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2228 Files
.delete(tmpFile
.toPath());
2229 } catch (IOException e
) {
2230 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2237 private void retrieveAttachment(
2238 final SignalServiceAttachment attachment
, final OutputStream outputStream
2239 ) throws IOException
{
2240 if (attachment
.isPointer()) {
2241 var pointer
= attachment
.asPointer();
2242 retrieveAttachmentPointer(pointer
, outputStream
);
2244 var stream
= attachment
.asStream();
2245 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2249 private void retrieveAttachmentPointer(
2250 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2251 ) throws IOException
{
2252 var tmpFile
= IOUtils
.createTempFile();
2253 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2254 IOUtils
.copyStream(input
, outputStream
);
2255 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2256 throw new IOException(e
);
2259 Files
.delete(tmpFile
.toPath());
2260 } catch (IOException e
) {
2261 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2268 private InputStream
retrieveAttachmentAsStream(
2269 SignalServiceAttachmentPointer pointer
, File tmpFile
2270 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2271 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2274 void sendGroups() throws IOException
, UntrustedIdentityException
{
2275 var groupsFile
= IOUtils
.createTempFile();
2278 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2279 var out
= new DeviceGroupsOutputStream(fos
);
2280 for (var record : getGroups()) {
2281 if (record instanceof GroupInfoV1
) {
2282 var groupInfo
= (GroupInfoV1
) record;
2283 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2284 Optional
.fromNullable(groupInfo
.name
),
2285 new ArrayList
<>(groupInfo
.getMembers()),
2286 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2287 groupInfo
.isMember(account
.getSelfAddress()),
2288 Optional
.of(groupInfo
.messageExpirationTime
),
2289 Optional
.fromNullable(groupInfo
.color
),
2291 Optional
.fromNullable(groupInfo
.inboxPosition
),
2292 groupInfo
.archived
));
2297 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2298 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2299 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2300 .withStream(groupsFileStream
)
2301 .withContentType("application/octet-stream")
2302 .withLength(groupsFile
.length())
2305 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2310 Files
.delete(groupsFile
.toPath());
2311 } catch (IOException e
) {
2312 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2317 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2318 var contactsFile
= IOUtils
.createTempFile();
2321 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2322 var out
= new DeviceContactsOutputStream(fos
);
2323 for (var contactPair
: account
.getContactStore().getContacts()) {
2324 final var recipientId
= contactPair
.first();
2325 final var contact
= contactPair
.second();
2326 final var address
= resolveSignalServiceAddress(recipientId
);
2328 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2329 VerifiedMessage verifiedMessage
= null;
2330 if (currentIdentity
!= null) {
2331 verifiedMessage
= new VerifiedMessage(address
,
2332 currentIdentity
.getIdentityKey(),
2333 currentIdentity
.getTrustLevel().toVerifiedState(),
2334 currentIdentity
.getDateAdded().getTime());
2337 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2338 out
.write(new DeviceContact(address
,
2339 Optional
.fromNullable(contact
.getName()),
2340 createContactAvatarAttachment(address
),
2341 Optional
.fromNullable(contact
.getColor()),
2342 Optional
.fromNullable(verifiedMessage
),
2343 Optional
.fromNullable(profileKey
),
2344 contact
.isBlocked(),
2345 Optional
.of(contact
.getMessageExpirationTime()),
2347 contact
.isArchived()));
2350 if (account
.getProfileKey() != null) {
2351 // Send our own profile key as well
2352 out
.write(new DeviceContact(account
.getSelfAddress(),
2357 Optional
.of(account
.getProfileKey()),
2365 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2366 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2367 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2368 .withStream(contactsFileStream
)
2369 .withContentType("application/octet-stream")
2370 .withLength(contactsFile
.length())
2373 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2378 Files
.delete(contactsFile
.toPath());
2379 } catch (IOException e
) {
2380 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2385 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2386 var addresses
= new ArrayList
<SignalServiceAddress
>();
2387 for (var record : account
.getContactStore().getContacts()) {
2388 if (record.second().isBlocked()) {
2389 addresses
.add(resolveSignalServiceAddress(record.first()));
2392 var groupIds
= new ArrayList
<byte[]>();
2393 for (var record : getGroups()) {
2394 if (record.isBlocked()) {
2395 groupIds
.add(record.getGroupId().serialize());
2398 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2401 private void sendVerifiedMessage(
2402 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2403 ) throws IOException
, UntrustedIdentityException
{
2404 var verifiedMessage
= new VerifiedMessage(destination
,
2406 trustLevel
.toVerifiedState(),
2407 System
.currentTimeMillis());
2408 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2411 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2412 return account
.getContactStore().getContacts();
2415 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2416 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2417 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2418 if (recipient
== null) {
2422 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2423 return recipient
.getContact().getName();
2426 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2427 return recipient
.getProfile().getDisplayName();
2433 public GroupInfo
getGroup(GroupId groupId
) {
2434 final var group
= account
.getGroupStore().getGroup(groupId
);
2435 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2436 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2437 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2438 account
.getGroupStore().updateGroup(group
);
2443 public List
<IdentityInfo
> getIdentities() {
2444 return account
.getIdentityKeyStore().getIdentities();
2447 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2448 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2449 return identity
== null ? List
.of() : List
.of(identity
);
2453 * Trust this the identity with this fingerprint
2455 * @param name username of the identity
2456 * @param fingerprint Fingerprint
2458 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2459 var recipientId
= canonicalizeAndResolveRecipient(name
);
2460 return trustIdentity(recipientId
,
2461 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2462 TrustLevel
.TRUSTED_VERIFIED
);
2466 * Trust this the identity with this safety number
2468 * @param name username of the identity
2469 * @param safetyNumber Safety number
2471 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2472 var recipientId
= canonicalizeAndResolveRecipient(name
);
2473 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2474 return trustIdentity(recipientId
,
2475 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2476 TrustLevel
.TRUSTED_VERIFIED
);
2480 * Trust all keys of this identity without verification
2482 * @param name username of the identity
2484 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2485 var recipientId
= canonicalizeAndResolveRecipient(name
);
2486 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2489 private boolean trustIdentity(
2490 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2492 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2493 if (identity
== null) {
2497 if (!verifier
.apply(identity
.getIdentityKey())) {
2501 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2503 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2504 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2505 } catch (IOException
| UntrustedIdentityException e
) {
2506 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2512 public String
computeSafetyNumber(
2513 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2515 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2516 account
.getSelfAddress(),
2517 getIdentityKeyPair().getPublicKey(),
2523 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2524 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2526 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2527 return resolveSignalServiceAddress(canonicalizedNumber
);
2531 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2532 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2534 return resolveSignalServiceAddress(address
);
2538 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2539 if (address
.matches(account
.getSelfAddress())) {
2540 return account
.getSelfAddress();
2543 return account
.getRecipientStore().resolveServiceAddress(address
);
2546 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2547 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2550 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2551 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2553 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2555 return resolveRecipient(canonicalizedNumber
);
2558 private RecipientId
resolveRecipient(final String identifier
) {
2559 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2561 return resolveRecipient(address
);
2564 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2565 return account
.getRecipientStore().resolveRecipient(address
);
2568 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2569 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2573 public void close() throws IOException
{
2577 void close(boolean closeAccount
) throws IOException
{
2578 executor
.shutdown();
2580 if (messagePipe
!= null) {
2581 messagePipe
.shutdown();
2585 if (unidentifiedMessagePipe
!= null) {
2586 unidentifiedMessagePipe
.shutdown();
2587 unidentifiedMessagePipe
= null;
2590 if (closeAccount
&& account
!= null) {
2596 public interface ReceiveMessageHandler
{
2598 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);