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 public RecipientId
getSelfRecipientId() {
269 return account
.getSelfRecipientId();
272 private IdentityKeyPair
getIdentityKeyPair() {
273 return account
.getIdentityKeyPair();
276 public int getDeviceId() {
277 return account
.getDeviceId();
280 public static Manager
init(
281 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
282 ) throws IOException
, NotRegisteredException
{
283 var pathConfig
= PathConfig
.createDefault(settingsPath
);
285 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
286 throw new NotRegisteredException();
289 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
291 if (!account
.isRegistered()) {
292 throw new NotRegisteredException();
295 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
297 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
300 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
301 var pathConfig
= PathConfig
.createDefault(settingsPath
);
302 final var dataPath
= pathConfig
.getDataPath();
303 final var files
= dataPath
.listFiles();
309 return Arrays
.stream(files
)
310 .filter(File
::isFile
)
312 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
313 .collect(Collectors
.toList());
316 public void checkAccountState() throws IOException
{
317 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
320 if (account
.getUuid() == null) {
321 account
.setUuid(accountManager
.getOwnUuid());
323 updateAccountAttributes();
327 * This is used for checking a set of phone numbers for registration on Signal
329 * @param numbers The set of phone number in question
330 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
331 * @throws IOException if its unable to get the contacts to check if they're registered
333 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
334 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
335 var contactDetails
= getRegisteredUsers(numbers
);
337 var registeredUsers
= contactDetails
.keySet();
339 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
342 public void updateAccountAttributes() throws IOException
{
343 accountManager
.setAccountAttributes(null,
344 account
.getLocalRegistrationId(),
346 // set legacy pin only if no KBS master key is set
347 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
348 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
349 account
.getSelfUnidentifiedAccessKey(),
350 account
.isUnrestrictedUnidentifiedAccess(),
352 account
.isDiscoverableByPhoneNumber());
356 * @param name if null, the previous name will be kept
357 * @param about if null, the previous about text will be kept
358 * @param aboutEmoji if null, the previous about emoji will be kept
359 * @param avatar if avatar is null the image from the local avatar store is used (if present),
360 * if it's Optional.absent(), the avatar will be removed
362 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
363 var profile
= getRecipientProfile(account
.getSelfRecipientId());
364 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
366 builder
.withGivenName(name
);
367 builder
.withFamilyName(null);
370 builder
.withAbout(about
);
372 if (aboutEmoji
!= null) {
373 builder
.withAboutEmoji(aboutEmoji
);
375 var newProfile
= builder
.build();
377 try (final var streamDetails
= avatar
== null
378 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
379 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
380 accountManager
.setVersionedProfile(account
.getUuid(),
381 account
.getProfileKey(),
382 newProfile
.getInternalServiceName(),
383 newProfile
.getAbout(),
384 newProfile
.getAboutEmoji(),
388 if (avatar
!= null) {
389 if (avatar
.isPresent()) {
390 avatarStore
.storeProfileAvatar(getSelfAddress(),
391 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
393 avatarStore
.deleteProfileAvatar(getSelfAddress());
396 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
399 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
400 } catch (UntrustedIdentityException ignored
) {
404 public void unregister() throws IOException
{
405 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
406 // If this is the master device, other users can't send messages to this number anymore.
407 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
408 accountManager
.setGcmId(Optional
.absent());
410 account
.setRegistered(false);
413 public void deleteAccount() throws IOException
{
414 accountManager
.deleteAccount();
416 account
.setRegistered(false);
419 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
420 var devices
= accountManager
.getDevices();
421 account
.setMultiDevice(devices
.size() > 1);
425 public void removeLinkedDevices(int deviceId
) throws IOException
{
426 accountManager
.removeDevice(deviceId
);
427 var devices
= accountManager
.getDevices();
428 account
.setMultiDevice(devices
.size() > 1);
431 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
432 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
434 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
437 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
438 var identityKeyPair
= getIdentityKeyPair();
439 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
441 accountManager
.addDevice(deviceIdentifier
,
444 Optional
.of(account
.getProfileKey().serialize()),
446 account
.setMultiDevice(true);
449 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
450 if (!account
.isMasterDevice()) {
451 throw new RuntimeException("Only master device can set a PIN");
453 if (pin
.isPresent()) {
454 final var masterKey
= account
.getPinMasterKey() != null
455 ? account
.getPinMasterKey()
456 : KeyUtils
.createMasterKey();
458 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
460 account
.setRegistrationLockPin(pin
.get(), masterKey
);
462 // Remove legacy registration lock
463 accountManager
.removeRegistrationLockV1();
466 pinHelper
.removeRegistrationLockPin();
468 account
.setRegistrationLockPin(null, 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
.getSelfRecipientId())) {
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
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
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
.getSelfRecipientId()));
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
.getSelfRecipientId());
740 account
.getGroupStore().updateGroup(groupInfoV1
);
742 final var groupInfoV2
= (GroupInfoV2
) g
;
743 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
744 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
745 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
746 account
.getGroupStore().updateGroup(groupInfoV2
);
749 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
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
,
757 members
== null ?
null : getSignalServiceAddresses(members
),
761 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
762 GroupId groupId
, String name
, Set
<RecipientId
> members
, File avatarFile
763 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
765 SignalServiceDataMessage
.Builder messageBuilder
;
766 if (groupId
== null) {
768 var gv2Pair
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
769 members
== null ? Set
.of() : members
,
771 if (gv2Pair
== null) {
772 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
773 gv1
.addMembers(List
.of(account
.getSelfRecipientId()));
774 updateGroupV1(gv1
, name
, members
, avatarFile
);
775 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
778 final var gv2
= gv2Pair
.first();
779 final var decryptedGroup
= gv2Pair
.second();
781 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
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(account
.getSelfRecipientId())) {
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());
805 if (newMembers
.size() > 0) {
806 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
807 result
= sendUpdateGroupMessage(groupInfoV2
,
808 groupGroupChangePair
.first(),
809 groupGroupChangePair
.second());
812 if (result
== null || name
!= null || avatarFile
!= null) {
813 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
814 if (avatarFile
!= null) {
815 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
816 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
818 result
= sendUpdateGroupMessage(groupInfoV2
,
819 groupGroupChangePair
.first(),
820 groupGroupChangePair
.second());
823 return new Pair
<>(group
.getGroupId(), result
.second());
825 var gv1
= (GroupInfoV1
) group
;
826 updateGroupV1(gv1
, name
, members
, avatarFile
);
827 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
832 account
.getGroupStore().updateGroup(g
);
834 final var result
= sendMessage(messageBuilder
,
835 g
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
836 return new Pair
<>(g
.getGroupId(), result
.second());
839 private void updateGroupV1(
840 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
841 ) throws IOException
{
846 if (members
!= null) {
847 final var newMemberAddresses
= members
.stream()
848 .filter(member
-> !g
.isMember(member
))
849 .map(this::resolveSignalServiceAddress
)
850 .collect(Collectors
.toList());
851 final var newE164Members
= new HashSet
<String
>();
852 for (var member
: newMemberAddresses
) {
853 if (!member
.getNumber().isPresent()) {
856 newE164Members
.add(member
.getNumber().get());
859 final var registeredUsers
= getRegisteredUsers(newE164Members
);
860 if (registeredUsers
.size() != newE164Members
.size()) {
861 // Some of the new members are not registered on Signal
862 newE164Members
.removeAll(registeredUsers
.keySet());
863 throw new IOException("Failed to add members "
864 + String
.join(", ", newE164Members
)
865 + " to group: Not registered on Signal");
868 g
.addMembers(members
);
871 if (avatarFile
!= null) {
872 avatarStore
.storeGroupAvatar(g
.getGroupId(),
873 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
877 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
878 GroupInviteLinkUrl inviteLinkUrl
879 ) throws IOException
, GroupLinkNotActiveException
{
880 return sendJoinGroupMessage(inviteLinkUrl
);
883 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
884 GroupInviteLinkUrl inviteLinkUrl
885 ) throws IOException
, GroupLinkNotActiveException
{
886 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
887 inviteLinkUrl
.getPassword());
888 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
889 inviteLinkUrl
.getPassword(),
891 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
892 groupJoinInfo
.getRevision() + 1,
893 groupChange
.toByteArray());
895 if (group
.getGroup() == null) {
896 // Only requested member, can't send update to group members
897 return new Pair
<>(group
.getGroupId(), List
.of());
900 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
902 return new Pair
<>(group
.getGroupId(), result
.second());
905 private static int currentTimeDays() {
906 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
909 private GroupsV2AuthorizationString
getGroupAuthForToday(
910 final GroupSecretParams groupSecretParams
911 ) throws IOException
{
912 final var today
= currentTimeDays();
913 // Returns credentials for the next 7 days
914 final var credentials
= groupsV2Api
.getCredentials(today
);
915 // TODO cache credentials until they expire
916 var authCredentialResponse
= credentials
.get(today
);
918 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
921 authCredentialResponse
);
922 } catch (VerificationFailedException e
) {
923 throw new IOException(e
);
927 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
928 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
929 ) throws IOException
{
930 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
931 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
932 account
.getGroupStore().updateGroup(group
);
933 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
936 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
937 GroupIdV1 groupId
, SignalServiceAddress recipient
938 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
940 var group
= getGroupForSending(groupId
);
941 if (!(group
instanceof GroupInfoV1
)) {
942 throw new RuntimeException("Received an invalid group request for a v2 group!");
944 g
= (GroupInfoV1
) group
;
946 if (!g
.isMember(resolveRecipient(recipient
))) {
947 throw new NotAGroupMemberException(groupId
, g
.name
);
950 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
952 // Send group message only to the recipient who requested it
953 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
956 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
957 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
958 .withId(g
.getGroupId().serialize())
960 .withMembers(g
.getMembers()
962 .map(this::resolveSignalServiceAddress
)
963 .collect(Collectors
.toList()));
966 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
967 if (attachment
.isPresent()) {
968 group
.withAvatar(attachment
.get());
970 } catch (IOException e
) {
971 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
974 return SignalServiceDataMessage
.newBuilder()
975 .asGroupMessage(group
.build())
976 .withExpiration(g
.getMessageExpirationTime());
979 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
980 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
981 .withRevision(g
.getGroup().getRevision())
982 .withSignedGroupChange(signedGroupChange
);
983 return SignalServiceDataMessage
.newBuilder()
984 .asGroupMessage(group
.build())
985 .withExpiration(g
.getMessageExpirationTime());
988 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
989 GroupIdV1 groupId
, SignalServiceAddress recipient
990 ) throws IOException
{
991 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
993 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
995 // Send group info request message to the recipient who sent us a message with this groupId
996 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1000 SignalServiceAddress remoteAddress
, long messageId
1001 ) throws IOException
, UntrustedIdentityException
{
1002 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1004 System
.currentTimeMillis());
1006 createMessageSender().sendReceipt(remoteAddress
,
1007 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1011 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1012 String messageText
, List
<String
> attachments
, List
<String
> recipients
1013 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1014 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1015 if (attachments
!= null) {
1016 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1018 // Upload attachments here, so we only upload once even for multiple recipients
1019 var messageSender
= createMessageSender();
1020 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1021 for (var attachment
: attachmentStreams
) {
1022 if (attachment
.isStream()) {
1023 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1024 } else if (attachment
.isPointer()) {
1025 attachmentPointers
.add(attachment
.asPointer());
1029 messageBuilder
.withAttachments(attachmentPointers
);
1031 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1034 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1035 String messageText
, List
<String
> attachments
1036 ) throws IOException
, AttachmentInvalidException
{
1037 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1038 if (attachments
!= null) {
1039 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1041 return sendSelfMessage(messageBuilder
);
1044 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1045 long targetSentTimestamp
, List
<String
> recipients
1046 ) throws IOException
, InvalidNumberException
{
1047 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1048 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1049 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1052 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1053 long targetSentTimestamp
, GroupId groupId
1054 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1055 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1056 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1057 return sendGroupMessage(messageBuilder
, groupId
);
1060 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1061 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1062 ) throws IOException
, InvalidNumberException
{
1063 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1065 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1066 targetSentTimestamp
);
1067 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1068 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1071 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1072 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1074 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1076 return sendMessage(messageBuilder
, signalServiceAddresses
);
1077 } catch (Exception e
) {
1078 for (var address
: signalServiceAddresses
) {
1079 handleEndSession(address
);
1085 public String
getContactName(String number
) throws InvalidNumberException
{
1086 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1087 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1090 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1091 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1092 var contact
= account
.getContactStore().getContact(recipientId
);
1093 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1094 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());
1107 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1108 var group
= getGroup(groupId
);
1109 if (group
== null) {
1110 throw new GroupNotFoundException(groupId
);
1113 group
.setBlocked(blocked
);
1114 account
.getGroupStore().updateGroup(group
);
1117 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1118 var contact
= account
.getContactStore().getContact(recipientId
);
1119 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1122 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1123 account
.getContactStore()
1124 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1127 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1128 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1129 sendMessage(messageBuilder
, Set
.of(recipientId
));
1133 * Change the expiration timer for a contact
1135 public void setExpirationTimer(
1136 String number
, int messageExpirationTimer
1137 ) throws IOException
, InvalidNumberException
{
1138 var recipientId
= canonicalizeAndResolveRecipient(number
);
1139 setExpirationTimer(recipientId
, messageExpirationTimer
);
1140 sendExpirationTimerUpdate(recipientId
);
1144 * Change the expiration timer for a group
1146 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1147 var g
= getGroup(groupId
);
1148 if (g
instanceof GroupInfoV1
) {
1149 var groupInfoV1
= (GroupInfoV1
) g
;
1150 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1151 account
.getGroupStore().updateGroup(groupInfoV1
);
1153 throw new RuntimeException("TODO Not implemented!");
1158 * Upload the sticker pack from path.
1160 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1161 * @return if successful, returns the URL to install the sticker pack in the signal app
1163 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1164 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1166 var messageSender
= createMessageSender();
1168 var packKey
= KeyUtils
.createStickerUploadKey();
1169 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1171 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1172 account
.getStickerStore().updateSticker(sticker
);
1175 return new URI("https",
1178 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1179 Hex
.toStringCondensed(packKey
),
1180 StandardCharsets
.UTF_8
)).toString();
1181 } catch (URISyntaxException e
) {
1182 throw new AssertionError(e
);
1186 void requestSyncGroups() throws IOException
{
1187 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1188 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1190 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1192 sendSyncMessage(message
);
1193 } catch (UntrustedIdentityException e
) {
1194 throw new AssertionError(e
);
1198 void requestSyncContacts() throws IOException
{
1199 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1200 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1202 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1204 sendSyncMessage(message
);
1205 } catch (UntrustedIdentityException e
) {
1206 throw new AssertionError(e
);
1210 void requestSyncBlocked() throws IOException
{
1211 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1212 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1214 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1216 sendSyncMessage(message
);
1217 } catch (UntrustedIdentityException e
) {
1218 throw new AssertionError(e
);
1222 void requestSyncConfiguration() throws IOException
{
1223 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1224 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1226 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1228 sendSyncMessage(message
);
1229 } catch (UntrustedIdentityException e
) {
1230 throw new AssertionError(e
);
1234 void requestSyncKeys() throws IOException
{
1235 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1236 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1238 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1240 sendSyncMessage(message
);
1241 } catch (UntrustedIdentityException e
) {
1242 throw new AssertionError(e
);
1246 private byte[] getSenderCertificate() {
1247 // TODO support UUID capable sender certificates
1248 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1251 certificate
= accountManager
.getSenderCertificate();
1252 } catch (IOException e
) {
1253 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1256 // TODO cache for a day
1260 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1261 var messageSender
= createMessageSender();
1262 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1265 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1266 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1267 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1269 for (var number
: numbers
) {
1270 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1271 if (resolvedAddress
.getUuid().isPresent()) {
1272 signalServiceAddresses
.add(resolvedAddress
);
1274 addressesMissingUuid
.add(resolvedAddress
);
1278 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1279 .map(a
-> a
.getNumber().get())
1280 .collect(Collectors
.toSet());
1281 Map
<String
, UUID
> registeredUsers
;
1283 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1284 } catch (IOException e
) {
1285 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1286 registeredUsers
= Map
.of();
1289 for (var address
: addressesMissingUuid
) {
1290 final var number
= address
.getNumber().get();
1291 if (registeredUsers
.containsKey(number
)) {
1292 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1293 registeredUsers
.get(number
),
1295 signalServiceAddresses
.add(newAddress
);
1297 signalServiceAddresses
.add(address
);
1301 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1304 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1306 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1308 serviceEnvironmentConfig
.getCdsMrenclave());
1309 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1310 throw new IOException(e
);
1314 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1315 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1316 ) throws IOException
{
1317 final var timestamp
= System
.currentTimeMillis();
1318 messageBuilder
.withTimestamp(timestamp
);
1319 getOrCreateMessagePipe();
1320 getOrCreateUnidentifiedMessagePipe();
1321 SignalServiceDataMessage message
= null;
1323 message
= messageBuilder
.build();
1324 if (message
.getGroupContext().isPresent()) {
1326 var messageSender
= createMessageSender();
1327 final var isRecipientUpdate
= false;
1328 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1329 final var addresses
= recipientIdList
.stream()
1330 .map(this::resolveSignalServiceAddress
)
1331 .collect(Collectors
.toList());
1332 var result
= messageSender
.sendMessage(addresses
,
1333 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1337 for (var r
: result
) {
1338 if (r
.getIdentityFailure() != null) {
1339 account
.getIdentityKeyStore().
1340 saveIdentity(resolveRecipient(r
.getAddress()),
1341 r
.getIdentityFailure().getIdentityKey(),
1346 return new Pair
<>(timestamp
, result
);
1347 } catch (UntrustedIdentityException e
) {
1348 return new Pair
<>(timestamp
, List
.of());
1351 // Send to all individually, so sync messages are sent correctly
1352 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1353 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1354 for (var recipientId
: recipientIds
) {
1355 final var contact
= account
.getContactStore().getContact(recipientId
);
1356 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1357 messageBuilder
.withExpiration(expirationTime
);
1358 message
= messageBuilder
.build();
1359 results
.add(sendMessage(resolveSignalServiceAddress(recipientId
), message
));
1361 return new Pair
<>(timestamp
, results
);
1364 if (message
!= null && message
.isEndSession()) {
1365 for (var recipient
: recipientIds
) {
1366 handleEndSession(recipient
);
1372 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1373 SignalServiceDataMessage
.Builder messageBuilder
1374 ) throws IOException
{
1375 final var timestamp
= System
.currentTimeMillis();
1376 messageBuilder
.withTimestamp(timestamp
);
1377 getOrCreateMessagePipe();
1378 getOrCreateUnidentifiedMessagePipe();
1379 final var recipientId
= account
.getSelfRecipientId();
1381 final var contact
= account
.getContactStore().getContact(recipientId
);
1382 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1383 messageBuilder
.withExpiration(expirationTime
);
1385 var message
= messageBuilder
.build();
1386 final var result
= sendSelfMessage(message
);
1387 return new Pair
<>(timestamp
, result
);
1390 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1391 var messageSender
= createMessageSender();
1393 var recipient
= account
.getSelfAddress();
1395 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(resolveRecipient(recipient
));
1396 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1397 message
.getTimestamp(),
1399 message
.getExpiresInSeconds(),
1400 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1402 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1405 var startTime
= System
.currentTimeMillis();
1406 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1407 return SendMessageResult
.success(recipient
,
1408 unidentifiedAccess
.isPresent(),
1410 System
.currentTimeMillis() - startTime
);
1411 } catch (UntrustedIdentityException e
) {
1412 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1416 private SendMessageResult
sendMessage(
1417 SignalServiceAddress address
, SignalServiceDataMessage message
1418 ) throws IOException
{
1419 var messageSender
= createMessageSender();
1422 return messageSender
.sendMessage(address
,
1423 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(address
)),
1425 } catch (UntrustedIdentityException e
) {
1426 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1430 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1431 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1432 account
.getSignalProtocolStore(),
1433 certificateValidator
);
1435 return cipher
.decrypt(envelope
);
1436 } catch (ProtocolUntrustedIdentityException e
) {
1437 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1438 throw (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1440 throw new AssertionError(e
);
1444 private void handleEndSession(RecipientId recipientId
) {
1445 account
.getSessionStore().deleteAllSessions(recipientId
);
1448 private List
<HandleAction
> handleSignalServiceDataMessage(
1449 SignalServiceDataMessage message
,
1451 SignalServiceAddress source
,
1452 SignalServiceAddress destination
,
1453 boolean ignoreAttachments
1455 var actions
= new ArrayList
<HandleAction
>();
1456 if (message
.getGroupContext().isPresent()) {
1457 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1458 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1459 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1460 var group
= getGroup(groupId
);
1461 if (group
== null || group
instanceof GroupInfoV1
) {
1462 var groupV1
= (GroupInfoV1
) group
;
1463 switch (groupInfo
.getType()) {
1465 if (groupV1
== null) {
1466 groupV1
= new GroupInfoV1(groupId
);
1469 if (groupInfo
.getAvatar().isPresent()) {
1470 var avatar
= groupInfo
.getAvatar().get();
1471 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1474 if (groupInfo
.getName().isPresent()) {
1475 groupV1
.name
= groupInfo
.getName().get();
1478 if (groupInfo
.getMembers().isPresent()) {
1479 groupV1
.addMembers(groupInfo
.getMembers()
1482 .map(this::resolveRecipient
)
1483 .collect(Collectors
.toSet()));
1486 account
.getGroupStore().updateGroup(groupV1
);
1490 if (groupV1
== null && !isSync
) {
1491 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1495 if (groupV1
!= null) {
1496 groupV1
.removeMember(resolveRecipient(source
));
1497 account
.getGroupStore().updateGroup(groupV1
);
1502 if (groupV1
!= null && !isSync
) {
1503 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1508 // Received a group v1 message for a v2 group
1511 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1512 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1513 final var groupMasterKey
= groupContext
.getMasterKey();
1515 getOrMigrateGroup(groupMasterKey
,
1516 groupContext
.getRevision(),
1517 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1521 final var conversationPartnerAddress
= isSync ? destination
: source
;
1522 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1523 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1525 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1526 if (message
.getGroupContext().isPresent()) {
1527 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1528 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1529 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1530 if (group
!= null) {
1531 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1532 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1533 account
.getGroupStore().updateGroup(group
);
1536 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1537 // disappearing message timer already stored in the DecryptedGroup
1539 } else if (conversationPartnerAddress
!= null) {
1540 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1543 if (!ignoreAttachments
) {
1544 if (message
.getAttachments().isPresent()) {
1545 for (var attachment
: message
.getAttachments().get()) {
1546 downloadAttachment(attachment
);
1549 if (message
.getSharedContacts().isPresent()) {
1550 for (var contact
: message
.getSharedContacts().get()) {
1551 if (contact
.getAvatar().isPresent()) {
1552 downloadAttachment(contact
.getAvatar().get().getAttachment());
1557 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1558 final ProfileKey profileKey
;
1560 profileKey
= new ProfileKey(message
.getProfileKey().get());
1561 } catch (InvalidInputException e
) {
1562 throw new AssertionError(e
);
1564 if (source
.matches(account
.getSelfAddress())) {
1565 this.account
.setProfileKey(profileKey
);
1567 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1569 if (message
.getPreviews().isPresent()) {
1570 final var previews
= message
.getPreviews().get();
1571 for (var preview
: previews
) {
1572 if (preview
.getImage().isPresent()) {
1573 downloadAttachment(preview
.getImage().get());
1577 if (message
.getQuote().isPresent()) {
1578 final var quote
= message
.getQuote().get();
1580 for (var quotedAttachment
: quote
.getAttachments()) {
1581 final var thumbnail
= quotedAttachment
.getThumbnail();
1582 if (thumbnail
!= null) {
1583 downloadAttachment(thumbnail
);
1587 if (message
.getSticker().isPresent()) {
1588 final var messageSticker
= message
.getSticker().get();
1589 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1590 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1591 if (sticker
== null) {
1592 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1593 account
.getStickerStore().updateSticker(sticker
);
1599 private GroupInfoV2
getOrMigrateGroup(
1600 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1602 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1604 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1605 var groupInfo
= getGroup(groupId
);
1606 final GroupInfoV2 groupInfoV2
;
1607 if (groupInfo
instanceof GroupInfoV1
) {
1608 // Received a v2 group message for a v1 group, we need to locally migrate the group
1609 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1610 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1611 logger
.info("Locally migrated group {} to group v2, id: {}",
1612 groupInfo
.getGroupId().toBase64(),
1613 groupInfoV2
.getGroupId().toBase64());
1614 } else if (groupInfo
instanceof GroupInfoV2
) {
1615 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1617 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1620 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1621 DecryptedGroup group
= null;
1622 if (signedGroupChange
!= null
1623 && groupInfoV2
.getGroup() != null
1624 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1625 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1627 if (group
== null) {
1628 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1630 if (group
!= null) {
1631 storeProfileKeysFromMembers(group
);
1632 final var avatar
= group
.getAvatar();
1633 if (avatar
!= null && !avatar
.isEmpty()) {
1634 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1637 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1638 account
.getGroupStore().updateGroup(groupInfoV2
);
1644 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1645 for (var member
: group
.getMembersList()) {
1646 final var address
= resolveRecipient(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1647 .toByteArray()), null));
1649 account
.getProfileStore()
1650 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1651 } catch (InvalidInputException ignored
) {
1656 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1657 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1658 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1659 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1660 if (actions
!= null) {
1661 queuedActions
.addAll(actions
);
1664 for (var action
: queuedActions
) {
1666 action
.execute(this);
1667 } catch (Throwable e
) {
1668 logger
.warn("Message action failed.", e
);
1673 private List
<HandleAction
> retryFailedReceivedMessage(
1674 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1676 var envelope
= cachedMessage
.loadEnvelope();
1677 if (envelope
== null) {
1680 SignalServiceContent content
= null;
1681 List
<HandleAction
> actions
= null;
1682 if (!envelope
.isReceipt()) {
1684 content
= decryptMessage(envelope
);
1685 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1686 if (!envelope
.hasSource()) {
1687 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
)
1690 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1691 } catch (IOException ioException
) {
1692 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1696 } catch (Exception er
) {
1697 // All other errors are not recoverable, so delete the cached message
1698 cachedMessage
.delete();
1701 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1703 handler
.handleMessage(envelope
, content
, null);
1704 cachedMessage
.delete();
1708 public void receiveMessages(
1711 boolean returnOnTimeout
,
1712 boolean ignoreAttachments
,
1713 ReceiveMessageHandler handler
1714 ) throws IOException
{
1715 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1717 Set
<HandleAction
> queuedActions
= null;
1719 final var messagePipe
= getOrCreateMessagePipe();
1721 var hasCaughtUpWithOldMessages
= false;
1724 SignalServiceEnvelope envelope
;
1725 SignalServiceContent content
= null;
1726 Exception exception
= null;
1727 final CachedMessage
[] cachedMessage
= {null};
1729 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1730 final var recipientId
= envelope1
.hasSource()
1731 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1733 // store message on disk, before acknowledging receipt to the server
1734 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1736 if (result
.isPresent()) {
1737 envelope
= result
.get();
1739 // Received indicator that server queue is empty
1740 hasCaughtUpWithOldMessages
= true;
1742 if (queuedActions
!= null) {
1743 for (var action
: queuedActions
) {
1745 action
.execute(this);
1746 } catch (Throwable e
) {
1747 logger
.warn("Message action failed.", e
);
1750 queuedActions
.clear();
1751 queuedActions
= null;
1754 // Continue to wait another timeout for new messages
1757 } catch (TimeoutException e
) {
1758 if (returnOnTimeout
) return;
1762 if (envelope
.hasSource()) {
1763 // Store uuid if we don't have it already
1764 resolveRecipientTrusted(envelope
.getSourceAddress());
1766 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1767 if (!envelope
.isReceipt()) {
1769 content
= decryptMessage(envelope
);
1770 } catch (Exception e
) {
1773 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1774 if (hasCaughtUpWithOldMessages
) {
1775 for (var action
: actions
) {
1777 action
.execute(this);
1778 } catch (Throwable e
) {
1779 logger
.warn("Message action failed.", e
);
1783 if (queuedActions
== null) {
1784 queuedActions
= new HashSet
<>();
1786 queuedActions
.addAll(actions
);
1789 if (isMessageBlocked(envelope
, content
)) {
1790 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1791 } else if (notAGroupMember
) {
1792 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1794 handler
.handleMessage(envelope
, content
, exception
);
1796 if (cachedMessage
[0] != null) {
1797 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1798 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
)
1800 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1801 if (!envelope
.hasSource()) {
1803 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1804 } catch (IOException ioException
) {
1805 logger
.warn("Failed to move cached message to recipient folder: {}",
1806 ioException
.getMessage());
1810 cachedMessage
[0].delete();
1816 private boolean isMessageBlocked(
1817 SignalServiceEnvelope envelope
, SignalServiceContent content
1819 SignalServiceAddress source
;
1820 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1821 source
= envelope
.getSourceAddress();
1822 } else if (content
!= null) {
1823 source
= content
.getSender();
1827 final var recipientId
= resolveRecipient(source
);
1828 if (isContactBlocked(recipientId
)) {
1832 if (content
!= null && content
.getDataMessage().isPresent()) {
1833 var message
= content
.getDataMessage().get();
1834 if (message
.getGroupContext().isPresent()) {
1835 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1836 var group
= getGroup(groupId
);
1837 if (group
!= null && group
.isBlocked()) {
1845 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
1846 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
1847 return isContactBlocked(recipientId
);
1850 private boolean isContactBlocked(final RecipientId recipientId
) {
1851 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1852 return sourceContact
!= null && sourceContact
.isBlocked();
1855 private boolean isNotAGroupMember(
1856 SignalServiceEnvelope envelope
, SignalServiceContent content
1858 SignalServiceAddress source
;
1859 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1860 source
= envelope
.getSourceAddress();
1861 } else if (content
!= null) {
1862 source
= content
.getSender();
1867 if (content
!= null && content
.getDataMessage().isPresent()) {
1868 var message
= content
.getDataMessage().get();
1869 if (message
.getGroupContext().isPresent()) {
1870 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1871 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1872 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1876 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1877 var group
= getGroup(groupId
);
1878 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
1886 private List
<HandleAction
> handleMessage(
1887 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1889 var actions
= new ArrayList
<HandleAction
>();
1890 if (content
!= null) {
1891 final SignalServiceAddress sender
;
1892 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1893 sender
= envelope
.getSourceAddress();
1895 sender
= content
.getSender();
1898 if (content
.getDataMessage().isPresent()) {
1899 var message
= content
.getDataMessage().get();
1901 if (content
.isNeedsReceipt()) {
1902 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1905 actions
.addAll(handleSignalServiceDataMessage(message
,
1908 account
.getSelfAddress(),
1909 ignoreAttachments
));
1911 if (content
.getSyncMessage().isPresent()) {
1912 account
.setMultiDevice(true);
1913 var syncMessage
= content
.getSyncMessage().get();
1914 if (syncMessage
.getSent().isPresent()) {
1915 var message
= syncMessage
.getSent().get();
1916 final var destination
= message
.getDestination().orNull();
1917 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1921 ignoreAttachments
));
1923 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
1924 var rm
= syncMessage
.getRequest().get();
1925 if (rm
.isContactsRequest()) {
1926 actions
.add(SendSyncContactsAction
.create());
1928 if (rm
.isGroupsRequest()) {
1929 actions
.add(SendSyncGroupsAction
.create());
1931 if (rm
.isBlockedListRequest()) {
1932 actions
.add(SendSyncBlockedListAction
.create());
1934 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1936 if (syncMessage
.getGroups().isPresent()) {
1937 File tmpFile
= null;
1939 tmpFile
= IOUtils
.createTempFile();
1940 final var groupsMessage
= syncMessage
.getGroups().get();
1941 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1942 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1944 while ((g
= s
.read()) != null) {
1945 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1946 if (syncGroup
!= null) {
1947 if (g
.getName().isPresent()) {
1948 syncGroup
.name
= g
.getName().get();
1950 syncGroup
.addMembers(g
.getMembers()
1952 .map(this::resolveRecipient
)
1953 .collect(Collectors
.toSet()));
1954 if (!g
.isActive()) {
1955 syncGroup
.removeMember(account
.getSelfRecipientId());
1957 // Add ourself to the member set as it's marked as active
1958 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
1960 syncGroup
.blocked
= g
.isBlocked();
1961 if (g
.getColor().isPresent()) {
1962 syncGroup
.color
= g
.getColor().get();
1965 if (g
.getAvatar().isPresent()) {
1966 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1968 syncGroup
.archived
= g
.isArchived();
1969 account
.getGroupStore().updateGroup(syncGroup
);
1973 } catch (Exception e
) {
1974 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1978 if (tmpFile
!= null) {
1980 Files
.delete(tmpFile
.toPath());
1981 } catch (IOException e
) {
1982 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1989 if (syncMessage
.getBlockedList().isPresent()) {
1990 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1991 for (var address
: blockedListMessage
.getAddresses()) {
1992 setContactBlocked(resolveRecipient(address
), true);
1994 for (var groupId
: blockedListMessage
.getGroupIds()
1996 .map(GroupId
::unknownVersion
)
1997 .collect(Collectors
.toSet())) {
1999 setGroupBlocked(groupId
, true);
2000 } catch (GroupNotFoundException e
) {
2001 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2002 groupId
.toBase64());
2006 if (syncMessage
.getContacts().isPresent()) {
2007 File tmpFile
= null;
2009 tmpFile
= IOUtils
.createTempFile();
2010 final var contactsMessage
= syncMessage
.getContacts().get();
2011 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2012 .asPointer(), tmpFile
)) {
2013 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2015 while ((c
= s
.read()) != null) {
2016 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2017 account
.setProfileKey(c
.getProfileKey().get());
2019 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2020 var contact
= account
.getContactStore().getContact(recipientId
);
2021 final var builder
= contact
== null
2022 ? Contact
.newBuilder()
2023 : Contact
.newBuilder(contact
);
2024 if (c
.getName().isPresent()) {
2025 builder
.withName(c
.getName().get());
2027 if (c
.getColor().isPresent()) {
2028 builder
.withColor(c
.getColor().get());
2030 if (c
.getProfileKey().isPresent()) {
2031 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2033 if (c
.getVerified().isPresent()) {
2034 final var verifiedMessage
= c
.getVerified().get();
2035 account
.getIdentityKeyStore()
2036 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2037 verifiedMessage
.getIdentityKey(),
2038 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2040 if (c
.getExpirationTimer().isPresent()) {
2041 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2043 builder
.withBlocked(c
.isBlocked());
2044 builder
.withArchived(c
.isArchived());
2045 account
.getContactStore().storeContact(recipientId
, builder
.build());
2047 if (c
.getAvatar().isPresent()) {
2048 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2052 } catch (Exception e
) {
2053 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2057 if (tmpFile
!= null) {
2059 Files
.delete(tmpFile
.toPath());
2060 } catch (IOException e
) {
2061 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2068 if (syncMessage
.getVerified().isPresent()) {
2069 final var verifiedMessage
= syncMessage
.getVerified().get();
2070 account
.getIdentityKeyStore()
2071 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2072 verifiedMessage
.getIdentityKey(),
2073 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2075 if (syncMessage
.getStickerPackOperations().isPresent()) {
2076 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2077 for (var m
: stickerPackOperationMessages
) {
2078 if (!m
.getPackId().isPresent()) {
2081 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2082 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2083 if (sticker
== null) {
2084 if (!m
.getPackKey().isPresent()) {
2087 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2089 sticker
.setInstalled(!m
.getType().isPresent()
2090 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2091 account
.getStickerStore().updateSticker(sticker
);
2094 if (syncMessage
.getFetchType().isPresent()) {
2095 switch (syncMessage
.getFetchType().get()) {
2097 getRecipientProfile(account
.getSelfRecipientId(), true);
2098 case STORAGE_MANIFEST
:
2102 if (syncMessage
.getKeys().isPresent()) {
2103 final var keysMessage
= syncMessage
.getKeys().get();
2104 if (keysMessage
.getStorageService().isPresent()) {
2105 final var storageKey
= keysMessage
.getStorageService().get();
2106 account
.setStorageKey(storageKey
);
2109 if (syncMessage
.getConfiguration().isPresent()) {
2117 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2119 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2120 } catch (IOException e
) {
2121 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2125 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2127 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2128 } catch (IOException e
) {
2129 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2133 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2135 avatarStore
.storeGroupAvatar(groupId
,
2136 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2137 } catch (IOException e
) {
2138 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2142 private void downloadProfileAvatar(
2143 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2146 avatarStore
.storeProfileAvatar(address
,
2147 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2148 } catch (Throwable e
) {
2149 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2153 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2154 return attachmentStore
.getAttachmentFile(attachmentId
);
2157 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2158 if (!attachment
.isPointer()) {
2159 logger
.warn("Invalid state, can't store an attachment stream.");
2162 var pointer
= attachment
.asPointer();
2163 if (pointer
.getPreview().isPresent()) {
2164 final var preview
= pointer
.getPreview().get();
2166 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2167 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2168 } catch (IOException e
) {
2169 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2174 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2175 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2176 } catch (IOException e
) {
2177 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2181 private void retrieveGroupV2Avatar(
2182 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2183 ) throws IOException
{
2184 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2186 var tmpFile
= IOUtils
.createTempFile();
2187 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2189 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2190 var encryptedData
= IOUtils
.readFully(input
);
2192 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2193 outputStream
.write(decryptedData
);
2196 Files
.delete(tmpFile
.toPath());
2197 } catch (IOException e
) {
2198 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2205 private void retrieveProfileAvatar(
2206 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2207 ) throws IOException
{
2208 var tmpFile
= IOUtils
.createTempFile();
2209 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2212 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2213 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2214 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2217 Files
.delete(tmpFile
.toPath());
2218 } catch (IOException e
) {
2219 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2226 private void retrieveAttachment(
2227 final SignalServiceAttachment attachment
, final OutputStream outputStream
2228 ) throws IOException
{
2229 if (attachment
.isPointer()) {
2230 var pointer
= attachment
.asPointer();
2231 retrieveAttachmentPointer(pointer
, outputStream
);
2233 var stream
= attachment
.asStream();
2234 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2238 private void retrieveAttachmentPointer(
2239 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2240 ) throws IOException
{
2241 var tmpFile
= IOUtils
.createTempFile();
2242 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2243 IOUtils
.copyStream(input
, outputStream
);
2244 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2245 throw new IOException(e
);
2248 Files
.delete(tmpFile
.toPath());
2249 } catch (IOException e
) {
2250 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2257 private InputStream
retrieveAttachmentAsStream(
2258 SignalServiceAttachmentPointer pointer
, File tmpFile
2259 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2260 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2263 void sendGroups() throws IOException
, UntrustedIdentityException
{
2264 var groupsFile
= IOUtils
.createTempFile();
2267 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2268 var out
= new DeviceGroupsOutputStream(fos
);
2269 for (var record : getGroups()) {
2270 if (record instanceof GroupInfoV1
) {
2271 var groupInfo
= (GroupInfoV1
) record;
2272 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2273 Optional
.fromNullable(groupInfo
.name
),
2274 groupInfo
.getMembers()
2276 .map(this::resolveSignalServiceAddress
)
2277 .collect(Collectors
.toList()),
2278 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2279 groupInfo
.isMember(account
.getSelfRecipientId()),
2280 Optional
.of(groupInfo
.messageExpirationTime
),
2281 Optional
.fromNullable(groupInfo
.color
),
2284 groupInfo
.archived
));
2289 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2290 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2291 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2292 .withStream(groupsFileStream
)
2293 .withContentType("application/octet-stream")
2294 .withLength(groupsFile
.length())
2297 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2302 Files
.delete(groupsFile
.toPath());
2303 } catch (IOException e
) {
2304 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2309 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2310 var contactsFile
= IOUtils
.createTempFile();
2313 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2314 var out
= new DeviceContactsOutputStream(fos
);
2315 for (var contactPair
: account
.getContactStore().getContacts()) {
2316 final var recipientId
= contactPair
.first();
2317 final var contact
= contactPair
.second();
2318 final var address
= resolveSignalServiceAddress(recipientId
);
2320 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2321 VerifiedMessage verifiedMessage
= null;
2322 if (currentIdentity
!= null) {
2323 verifiedMessage
= new VerifiedMessage(address
,
2324 currentIdentity
.getIdentityKey(),
2325 currentIdentity
.getTrustLevel().toVerifiedState(),
2326 currentIdentity
.getDateAdded().getTime());
2329 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2330 out
.write(new DeviceContact(address
,
2331 Optional
.fromNullable(contact
.getName()),
2332 createContactAvatarAttachment(address
),
2333 Optional
.fromNullable(contact
.getColor()),
2334 Optional
.fromNullable(verifiedMessage
),
2335 Optional
.fromNullable(profileKey
),
2336 contact
.isBlocked(),
2337 Optional
.of(contact
.getMessageExpirationTime()),
2339 contact
.isArchived()));
2342 if (account
.getProfileKey() != null) {
2343 // Send our own profile key as well
2344 out
.write(new DeviceContact(account
.getSelfAddress(),
2349 Optional
.of(account
.getProfileKey()),
2357 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2358 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2359 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2360 .withStream(contactsFileStream
)
2361 .withContentType("application/octet-stream")
2362 .withLength(contactsFile
.length())
2365 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2370 Files
.delete(contactsFile
.toPath());
2371 } catch (IOException e
) {
2372 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2377 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2378 var addresses
= new ArrayList
<SignalServiceAddress
>();
2379 for (var record : account
.getContactStore().getContacts()) {
2380 if (record.second().isBlocked()) {
2381 addresses
.add(resolveSignalServiceAddress(record.first()));
2384 var groupIds
= new ArrayList
<byte[]>();
2385 for (var record : getGroups()) {
2386 if (record.isBlocked()) {
2387 groupIds
.add(record.getGroupId().serialize());
2390 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2393 private void sendVerifiedMessage(
2394 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2395 ) throws IOException
, UntrustedIdentityException
{
2396 var verifiedMessage
= new VerifiedMessage(destination
,
2398 trustLevel
.toVerifiedState(),
2399 System
.currentTimeMillis());
2400 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2403 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2404 return account
.getContactStore().getContacts();
2407 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2408 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2409 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2410 if (recipient
== null) {
2414 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2415 return recipient
.getContact().getName();
2418 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2419 return recipient
.getProfile().getDisplayName();
2425 public GroupInfo
getGroup(GroupId groupId
) {
2426 final var group
= account
.getGroupStore().getGroup(groupId
);
2427 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2428 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2429 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2430 account
.getGroupStore().updateGroup(group
);
2435 public List
<IdentityInfo
> getIdentities() {
2436 return account
.getIdentityKeyStore().getIdentities();
2439 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2440 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2441 return identity
== null ? List
.of() : List
.of(identity
);
2445 * Trust this the identity with this fingerprint
2447 * @param name username of the identity
2448 * @param fingerprint Fingerprint
2450 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2451 var recipientId
= canonicalizeAndResolveRecipient(name
);
2452 return trustIdentity(recipientId
,
2453 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2454 TrustLevel
.TRUSTED_VERIFIED
);
2458 * Trust this the identity with this safety number
2460 * @param name username of the identity
2461 * @param safetyNumber Safety number
2463 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2464 var recipientId
= canonicalizeAndResolveRecipient(name
);
2465 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2466 return trustIdentity(recipientId
,
2467 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2468 TrustLevel
.TRUSTED_VERIFIED
);
2472 * Trust all keys of this identity without verification
2474 * @param name username of the identity
2476 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2477 var recipientId
= canonicalizeAndResolveRecipient(name
);
2478 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2481 private boolean trustIdentity(
2482 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2484 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2485 if (identity
== null) {
2489 if (!verifier
.apply(identity
.getIdentityKey())) {
2493 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2495 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2496 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2497 } catch (IOException
| UntrustedIdentityException e
) {
2498 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2504 public String
computeSafetyNumber(
2505 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2507 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2508 account
.getSelfAddress(),
2509 getIdentityKeyPair().getPublicKey(),
2515 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2516 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2518 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2519 return resolveSignalServiceAddress(canonicalizedNumber
);
2523 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2524 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2526 return resolveSignalServiceAddress(address
);
2530 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2531 if (address
.matches(account
.getSelfAddress())) {
2532 return account
.getSelfAddress();
2535 return account
.getRecipientStore().resolveServiceAddress(address
);
2538 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2539 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2542 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2543 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2545 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2547 return resolveRecipient(canonicalizedNumber
);
2550 private RecipientId
resolveRecipient(final String identifier
) {
2551 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2553 return resolveRecipient(address
);
2556 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2557 return account
.getRecipientStore().resolveRecipient(address
);
2560 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2561 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2565 public void close() throws IOException
{
2569 void close(boolean closeAccount
) throws IOException
{
2570 executor
.shutdown();
2572 if (messagePipe
!= null) {
2573 messagePipe
.shutdown();
2577 if (unidentifiedMessagePipe
!= null) {
2578 unidentifiedMessagePipe
.shutdown();
2579 unidentifiedMessagePipe
= null;
2582 if (closeAccount
&& account
!= null) {
2588 public interface ReceiveMessageHandler
{
2590 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);