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
) {
321 if (account
.getUuid() == null) {
322 account
.setUuid(accountManager
.getOwnUuid());
325 updateAccountAttributes();
329 * This is used for checking a set of phone numbers for registration on Signal
331 * @param numbers The set of phone number in question
332 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
333 * @throws IOException if its unable to get the contacts to check if they're registered
335 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
336 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
337 var contactDetails
= getRegisteredUsers(numbers
);
339 var registeredUsers
= contactDetails
.keySet();
341 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
344 public void updateAccountAttributes() throws IOException
{
345 accountManager
.setAccountAttributes(null,
346 account
.getLocalRegistrationId(),
348 // set legacy pin only if no KBS master key is set
349 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
350 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
351 account
.getSelfUnidentifiedAccessKey(),
352 account
.isUnrestrictedUnidentifiedAccess(),
354 account
.isDiscoverableByPhoneNumber());
358 * @param name if null, the previous name will be kept
359 * @param about if null, the previous about text will be kept
360 * @param aboutEmoji if null, the previous about emoji will be kept
361 * @param avatar if avatar is null the image from the local avatar store is used (if present),
362 * if it's Optional.absent(), the avatar will be removed
364 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
365 var profile
= getRecipientProfile(account
.getSelfRecipientId());
366 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
368 builder
.withGivenName(name
);
369 builder
.withFamilyName(null);
372 builder
.withAbout(about
);
374 if (aboutEmoji
!= null) {
375 builder
.withAboutEmoji(aboutEmoji
);
377 var newProfile
= builder
.build();
379 try (final var streamDetails
= avatar
== null
380 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
381 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
382 accountManager
.setVersionedProfile(account
.getUuid(),
383 account
.getProfileKey(),
384 newProfile
.getInternalServiceName(),
385 newProfile
.getAbout(),
386 newProfile
.getAboutEmoji(),
390 if (avatar
!= null) {
391 if (avatar
.isPresent()) {
392 avatarStore
.storeProfileAvatar(getSelfAddress(),
393 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
395 avatarStore
.deleteProfileAvatar(getSelfAddress());
398 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
401 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
402 } catch (UntrustedIdentityException ignored
) {
406 public void unregister() throws IOException
{
407 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
408 // If this is the master device, other users can't send messages to this number anymore.
409 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
410 accountManager
.setGcmId(Optional
.absent());
411 accountManager
.deleteAccount();
413 account
.setRegistered(false);
417 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
418 var devices
= accountManager
.getDevices();
419 account
.setMultiDevice(devices
.size() > 1);
424 public void removeLinkedDevices(int deviceId
) throws IOException
{
425 accountManager
.removeDevice(deviceId
);
426 var devices
= accountManager
.getDevices();
427 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);
450 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
451 if (!account
.isMasterDevice()) {
452 throw new RuntimeException("Only master device can set a PIN");
454 if (pin
.isPresent()) {
455 final var masterKey
= account
.getPinMasterKey() != null
456 ? account
.getPinMasterKey()
457 : KeyUtils
.createMasterKey();
459 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
461 account
.setRegistrationLockPin(pin
.get());
462 account
.setPinMasterKey(masterKey
);
464 // Remove legacy registration lock
465 accountManager
.removeRegistrationLockV1();
468 pinHelper
.removeRegistrationLockPin();
470 account
.setRegistrationLockPin(null);
471 account
.setPinMasterKey(null);
476 void refreshPreKeys() throws IOException
{
477 var oneTimePreKeys
= generatePreKeys();
478 final var identityKeyPair
= getIdentityKeyPair();
479 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
481 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
484 private List
<PreKeyRecord
> generatePreKeys() {
485 final var offset
= account
.getPreKeyIdOffset();
487 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
488 account
.addPreKeys(records
);
493 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
494 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
496 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
497 account
.addSignedPreKey(record);
502 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
503 if (messagePipe
== null) {
504 messagePipe
= messageReceiver
.createMessagePipe();
509 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
510 if (unidentifiedMessagePipe
== null) {
511 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
513 return unidentifiedMessagePipe
;
516 private SignalServiceMessageSender
createMessageSender() {
517 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
519 account
.getUsername(),
520 account
.getPassword(),
521 account
.getDeviceId(),
522 account
.getSignalProtocolStore(),
524 account
.isMultiDevice(),
525 Optional
.fromNullable(messagePipe
),
526 Optional
.fromNullable(unidentifiedMessagePipe
),
528 clientZkProfileOperations
,
530 ServiceConfig
.MAX_ENVELOPE_SIZE
,
531 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
534 public Profile
getRecipientProfile(
535 SignalServiceAddress address
537 return getRecipientProfile(resolveRecipient(address
), false);
540 public Profile
getRecipientProfile(
541 RecipientId recipientId
543 return getRecipientProfile(recipientId
, false);
546 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
548 Profile
getRecipientProfile(
549 RecipientId recipientId
, boolean force
551 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
552 if (profileKey
== null) {
554 // retrieve profile to get identity key
555 retrieveEncryptedProfile(recipientId
);
559 var profile
= account
.getProfileStore().getProfile(recipientId
);
561 var now
= new Date().getTime();
562 // Profiles are cached for 24h before retrieving them again, unless forced
563 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
567 synchronized (pendingProfileRequest
) {
568 if (pendingProfileRequest
.contains(recipientId
)) {
571 pendingProfileRequest
.add(recipientId
);
573 final SignalServiceProfile encryptedProfile
;
575 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
577 synchronized (pendingProfileRequest
) {
578 pendingProfileRequest
.remove(recipientId
);
581 if (encryptedProfile
== null) {
585 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
586 account
.getProfileStore().storeProfile(recipientId
, profile
);
591 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
593 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
594 } catch (IOException e
) {
595 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
600 private ProfileAndCredential
retrieveProfileAndCredential(
601 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
602 ) throws IOException
{
603 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
604 final var profile
= profileAndCredential
.getProfile();
607 account
.getIdentityKeyStore()
608 .saveIdentity(recipientId
,
609 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
611 } catch (InvalidKeyException ignored
) {
612 logger
.warn("Got invalid identity key in profile for {}",
613 resolveSignalServiceAddress(recipientId
).getLegacyIdentifier());
615 return profileAndCredential
;
618 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
619 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
620 if (profileKeyCredential
!= null) {
621 return profileKeyCredential
;
624 ProfileAndCredential profileAndCredential
;
626 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
627 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
628 } catch (IOException e
) {
629 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
633 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
634 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
636 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
637 if (profileKey
!= null) {
638 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
640 profileAndCredential
.getProfile());
641 account
.getProfileStore().storeProfile(recipientId
, profile
);
644 return profileKeyCredential
;
647 private Profile
decryptProfileAndDownloadAvatar(
648 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
650 if (encryptedProfile
.getAvatar() != null) {
651 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
654 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
657 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
658 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
659 if (streamDetails
== null) {
660 return Optional
.absent();
663 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
666 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
667 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
668 if (streamDetails
== null) {
669 return Optional
.absent();
672 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
675 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
676 var g
= getGroup(groupId
);
678 throw new GroupNotFoundException(groupId
);
680 if (!g
.isMember(account
.getSelfRecipientId())) {
681 throw new NotAGroupMemberException(groupId
, g
.getTitle());
686 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
687 var g
= getGroup(groupId
);
689 throw new GroupNotFoundException(groupId
);
691 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
692 throw new NotAGroupMemberException(groupId
, g
.getTitle());
697 public List
<GroupInfo
> getGroups() {
698 return account
.getGroupStore().getGroups();
701 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
702 String messageText
, List
<String
> attachments
, GroupId groupId
703 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
704 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
705 if (attachments
!= null) {
706 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
709 return sendGroupMessage(messageBuilder
, groupId
);
712 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
713 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
714 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
715 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
717 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
718 targetSentTimestamp
);
719 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
721 return sendGroupMessage(messageBuilder
, groupId
);
724 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
725 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
726 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
727 final var g
= getGroupForSending(groupId
);
729 GroupUtils
.setGroupContext(messageBuilder
, g
);
730 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
732 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
735 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
736 SignalServiceDataMessage
.Builder messageBuilder
;
738 final var g
= getGroupForUpdating(groupId
);
739 if (g
instanceof GroupInfoV1
) {
740 var groupInfoV1
= (GroupInfoV1
) g
;
741 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
742 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
743 groupInfoV1
.removeMember(account
.getSelfRecipientId());
744 account
.getGroupStore().updateGroup(groupInfoV1
);
746 final var groupInfoV2
= (GroupInfoV2
) g
;
747 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
748 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
749 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
750 account
.getGroupStore().updateGroup(groupInfoV2
);
753 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
756 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
757 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
758 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
759 return sendUpdateGroupMessage(groupId
,
761 members
== null ?
null : getSignalServiceAddresses(members
),
765 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
766 GroupId groupId
, String name
, Set
<RecipientId
> members
, File avatarFile
767 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
769 SignalServiceDataMessage
.Builder messageBuilder
;
770 if (groupId
== null) {
772 var gv2Pair
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
773 members
== null ? Set
.of() : members
,
775 if (gv2Pair
== null) {
776 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
777 gv1
.addMembers(List
.of(account
.getSelfRecipientId()));
778 updateGroupV1(gv1
, name
, members
, avatarFile
);
779 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
782 final var gv2
= gv2Pair
.first();
783 final var decryptedGroup
= gv2Pair
.second();
785 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
786 if (avatarFile
!= null) {
787 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
788 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
790 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
794 var group
= getGroupForUpdating(groupId
);
795 if (group
instanceof GroupInfoV2
) {
796 final var groupInfoV2
= (GroupInfoV2
) group
;
798 Pair
<Long
, List
<SendMessageResult
>> result
= null;
799 if (groupInfoV2
.isPendingMember(account
.getSelfRecipientId())) {
800 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
801 result
= sendUpdateGroupMessage(groupInfoV2
,
802 groupGroupChangePair
.first(),
803 groupGroupChangePair
.second());
806 if (members
!= null) {
807 final var newMembers
= new HashSet
<>(members
);
808 newMembers
.removeAll(group
.getMembers());
809 if (newMembers
.size() > 0) {
810 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
811 result
= sendUpdateGroupMessage(groupInfoV2
,
812 groupGroupChangePair
.first(),
813 groupGroupChangePair
.second());
816 if (result
== null || name
!= null || avatarFile
!= null) {
817 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
818 if (avatarFile
!= null) {
819 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
820 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
822 result
= sendUpdateGroupMessage(groupInfoV2
,
823 groupGroupChangePair
.first(),
824 groupGroupChangePair
.second());
827 return new Pair
<>(group
.getGroupId(), result
.second());
829 var gv1
= (GroupInfoV1
) group
;
830 updateGroupV1(gv1
, name
, members
, avatarFile
);
831 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
836 account
.getGroupStore().updateGroup(g
);
838 final var result
= sendMessage(messageBuilder
,
839 g
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
840 return new Pair
<>(g
.getGroupId(), result
.second());
843 private void updateGroupV1(
844 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
845 ) throws IOException
{
850 if (members
!= null) {
851 final var newMemberAddresses
= members
.stream()
852 .filter(member
-> !g
.isMember(member
))
853 .map(this::resolveSignalServiceAddress
)
854 .collect(Collectors
.toList());
855 final var newE164Members
= new HashSet
<String
>();
856 for (var member
: newMemberAddresses
) {
857 if (!member
.getNumber().isPresent()) {
860 newE164Members
.add(member
.getNumber().get());
863 final var registeredUsers
= getRegisteredUsers(newE164Members
);
864 if (registeredUsers
.size() != newE164Members
.size()) {
865 // Some of the new members are not registered on Signal
866 newE164Members
.removeAll(registeredUsers
.keySet());
867 throw new IOException("Failed to add members "
868 + String
.join(", ", newE164Members
)
869 + " to group: Not registered on Signal");
872 g
.addMembers(members
);
875 if (avatarFile
!= null) {
876 avatarStore
.storeGroupAvatar(g
.getGroupId(),
877 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
881 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
882 GroupInviteLinkUrl inviteLinkUrl
883 ) throws IOException
, GroupLinkNotActiveException
{
884 return sendJoinGroupMessage(inviteLinkUrl
);
887 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
888 GroupInviteLinkUrl inviteLinkUrl
889 ) throws IOException
, GroupLinkNotActiveException
{
890 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
891 inviteLinkUrl
.getPassword());
892 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
893 inviteLinkUrl
.getPassword(),
895 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
896 groupJoinInfo
.getRevision() + 1,
897 groupChange
.toByteArray());
899 if (group
.getGroup() == null) {
900 // Only requested member, can't send update to group members
901 return new Pair
<>(group
.getGroupId(), List
.of());
904 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
906 return new Pair
<>(group
.getGroupId(), result
.second());
909 private static int currentTimeDays() {
910 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
913 private GroupsV2AuthorizationString
getGroupAuthForToday(
914 final GroupSecretParams groupSecretParams
915 ) throws IOException
{
916 final var today
= currentTimeDays();
917 // Returns credentials for the next 7 days
918 final var credentials
= groupsV2Api
.getCredentials(today
);
919 // TODO cache credentials until they expire
920 var authCredentialResponse
= credentials
.get(today
);
922 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
925 authCredentialResponse
);
926 } catch (VerificationFailedException e
) {
927 throw new IOException(e
);
931 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
932 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
933 ) throws IOException
{
934 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
935 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
936 account
.getGroupStore().updateGroup(group
);
937 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
940 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
941 GroupIdV1 groupId
, SignalServiceAddress recipient
942 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
944 var group
= getGroupForSending(groupId
);
945 if (!(group
instanceof GroupInfoV1
)) {
946 throw new RuntimeException("Received an invalid group request for a v2 group!");
948 g
= (GroupInfoV1
) group
;
950 if (!g
.isMember(resolveRecipient(recipient
))) {
951 throw new NotAGroupMemberException(groupId
, g
.name
);
954 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
956 // Send group message only to the recipient who requested it
957 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
960 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
961 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
962 .withId(g
.getGroupId().serialize())
964 .withMembers(g
.getMembers()
966 .map(this::resolveSignalServiceAddress
)
967 .collect(Collectors
.toList()));
970 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
971 if (attachment
.isPresent()) {
972 group
.withAvatar(attachment
.get());
974 } catch (IOException e
) {
975 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
978 return SignalServiceDataMessage
.newBuilder()
979 .asGroupMessage(group
.build())
980 .withExpiration(g
.getMessageExpirationTime());
983 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
984 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
985 .withRevision(g
.getGroup().getRevision())
986 .withSignedGroupChange(signedGroupChange
);
987 return SignalServiceDataMessage
.newBuilder()
988 .asGroupMessage(group
.build())
989 .withExpiration(g
.getMessageExpirationTime());
992 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
993 GroupIdV1 groupId
, SignalServiceAddress recipient
994 ) throws IOException
{
995 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
997 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
999 // Send group info request message to the recipient who sent us a message with this groupId
1000 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1004 SignalServiceAddress remoteAddress
, long messageId
1005 ) throws IOException
, UntrustedIdentityException
{
1006 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1008 System
.currentTimeMillis());
1010 createMessageSender().sendReceipt(remoteAddress
,
1011 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1015 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1016 String messageText
, List
<String
> attachments
, List
<String
> recipients
1017 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1018 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1019 if (attachments
!= null) {
1020 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1022 // Upload attachments here, so we only upload once even for multiple recipients
1023 var messageSender
= createMessageSender();
1024 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1025 for (var attachment
: attachmentStreams
) {
1026 if (attachment
.isStream()) {
1027 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1028 } else if (attachment
.isPointer()) {
1029 attachmentPointers
.add(attachment
.asPointer());
1033 messageBuilder
.withAttachments(attachmentPointers
);
1035 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1038 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1039 String messageText
, List
<String
> attachments
1040 ) throws IOException
, AttachmentInvalidException
{
1041 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1042 if (attachments
!= null) {
1043 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1045 return sendSelfMessage(messageBuilder
);
1048 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1049 long targetSentTimestamp
, List
<String
> recipients
1050 ) throws IOException
, InvalidNumberException
{
1051 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1052 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1053 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1056 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1057 long targetSentTimestamp
, GroupId groupId
1058 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1059 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1060 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1061 return sendGroupMessage(messageBuilder
, groupId
);
1064 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1065 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1066 ) throws IOException
, InvalidNumberException
{
1067 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1069 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1070 targetSentTimestamp
);
1071 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1072 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1075 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1076 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1078 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1080 return sendMessage(messageBuilder
, signalServiceAddresses
);
1081 } catch (Exception e
) {
1082 for (var address
: signalServiceAddresses
) {
1083 handleEndSession(address
);
1090 public String
getContactName(String number
) throws InvalidNumberException
{
1091 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1092 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1095 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1096 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1097 var contact
= account
.getContactStore().getContact(recipientId
);
1098 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1099 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1103 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1104 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1107 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1108 var contact
= account
.getContactStore().getContact(recipientId
);
1109 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1110 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1114 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1115 var group
= getGroup(groupId
);
1116 if (group
== null) {
1117 throw new GroupNotFoundException(groupId
);
1120 group
.setBlocked(blocked
);
1121 account
.getGroupStore().updateGroup(group
);
1125 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1126 var contact
= account
.getContactStore().getContact(recipientId
);
1127 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1130 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1131 account
.getContactStore()
1132 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1135 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1136 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1137 sendMessage(messageBuilder
, Set
.of(recipientId
));
1141 * Change the expiration timer for a contact
1143 public void setExpirationTimer(
1144 String number
, int messageExpirationTimer
1145 ) throws IOException
, InvalidNumberException
{
1146 var recipientId
= canonicalizeAndResolveRecipient(number
);
1147 setExpirationTimer(recipientId
, messageExpirationTimer
);
1148 sendExpirationTimerUpdate(recipientId
);
1153 * Change the expiration timer for a group
1155 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1156 var g
= getGroup(groupId
);
1157 if (g
instanceof GroupInfoV1
) {
1158 var groupInfoV1
= (GroupInfoV1
) g
;
1159 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1160 account
.getGroupStore().updateGroup(groupInfoV1
);
1162 throw new RuntimeException("TODO Not implemented!");
1167 * Upload the sticker pack from path.
1169 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1170 * @return if successful, returns the URL to install the sticker pack in the signal app
1172 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1173 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1175 var messageSender
= createMessageSender();
1177 var packKey
= KeyUtils
.createStickerUploadKey();
1178 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1180 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1181 account
.getStickerStore().updateSticker(sticker
);
1185 return new URI("https",
1188 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1189 Hex
.toStringCondensed(packKey
),
1190 StandardCharsets
.UTF_8
)).toString();
1191 } catch (URISyntaxException e
) {
1192 throw new AssertionError(e
);
1196 void requestSyncGroups() throws IOException
{
1197 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1198 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1200 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1202 sendSyncMessage(message
);
1203 } catch (UntrustedIdentityException e
) {
1204 throw new AssertionError(e
);
1208 void requestSyncContacts() throws IOException
{
1209 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1210 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1212 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1214 sendSyncMessage(message
);
1215 } catch (UntrustedIdentityException e
) {
1216 throw new AssertionError(e
);
1220 void requestSyncBlocked() throws IOException
{
1221 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1222 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1224 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1226 sendSyncMessage(message
);
1227 } catch (UntrustedIdentityException e
) {
1228 throw new AssertionError(e
);
1232 void requestSyncConfiguration() throws IOException
{
1233 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1234 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1236 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1238 sendSyncMessage(message
);
1239 } catch (UntrustedIdentityException e
) {
1240 throw new AssertionError(e
);
1244 void requestSyncKeys() throws IOException
{
1245 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1246 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1248 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1250 sendSyncMessage(message
);
1251 } catch (UntrustedIdentityException e
) {
1252 throw new AssertionError(e
);
1256 private byte[] getSenderCertificate() {
1257 // TODO support UUID capable sender certificates
1258 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1261 certificate
= accountManager
.getSenderCertificate();
1262 } catch (IOException e
) {
1263 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1266 // TODO cache for a day
1270 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1271 var messageSender
= createMessageSender();
1272 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1275 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1276 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1277 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1279 for (var number
: numbers
) {
1280 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1281 if (resolvedAddress
.getUuid().isPresent()) {
1282 signalServiceAddresses
.add(resolvedAddress
);
1284 addressesMissingUuid
.add(resolvedAddress
);
1288 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1289 .map(a
-> a
.getNumber().get())
1290 .collect(Collectors
.toSet());
1291 Map
<String
, UUID
> registeredUsers
;
1293 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1294 } catch (IOException e
) {
1295 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1296 registeredUsers
= Map
.of();
1299 for (var address
: addressesMissingUuid
) {
1300 final var number
= address
.getNumber().get();
1301 if (registeredUsers
.containsKey(number
)) {
1302 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1303 registeredUsers
.get(number
),
1305 signalServiceAddresses
.add(newAddress
);
1307 signalServiceAddresses
.add(address
);
1311 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1314 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1316 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1318 serviceEnvironmentConfig
.getCdsMrenclave());
1319 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1320 throw new IOException(e
);
1324 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1325 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1326 ) throws IOException
{
1327 final var timestamp
= System
.currentTimeMillis();
1328 messageBuilder
.withTimestamp(timestamp
);
1329 getOrCreateMessagePipe();
1330 getOrCreateUnidentifiedMessagePipe();
1331 SignalServiceDataMessage message
= null;
1333 message
= messageBuilder
.build();
1334 if (message
.getGroupContext().isPresent()) {
1336 var messageSender
= createMessageSender();
1337 final var isRecipientUpdate
= false;
1338 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1339 final var addresses
= recipientIdList
.stream()
1340 .map(this::resolveSignalServiceAddress
)
1341 .collect(Collectors
.toList());
1342 var result
= messageSender
.sendMessage(addresses
,
1343 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1347 for (var r
: result
) {
1348 if (r
.getIdentityFailure() != null) {
1349 account
.getIdentityKeyStore().
1350 saveIdentity(resolveRecipient(r
.getAddress()),
1351 r
.getIdentityFailure().getIdentityKey(),
1356 return new Pair
<>(timestamp
, result
);
1357 } catch (UntrustedIdentityException e
) {
1358 return new Pair
<>(timestamp
, List
.of());
1361 // Send to all individually, so sync messages are sent correctly
1362 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1363 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1364 for (var recipientId
: recipientIds
) {
1365 final var contact
= account
.getContactStore().getContact(recipientId
);
1366 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1367 messageBuilder
.withExpiration(expirationTime
);
1368 message
= messageBuilder
.build();
1369 results
.add(sendMessage(resolveSignalServiceAddress(recipientId
), message
));
1371 return new Pair
<>(timestamp
, results
);
1374 if (message
!= null && message
.isEndSession()) {
1375 for (var recipient
: recipientIds
) {
1376 handleEndSession(recipient
);
1383 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1384 SignalServiceDataMessage
.Builder messageBuilder
1385 ) throws IOException
{
1386 final var timestamp
= System
.currentTimeMillis();
1387 messageBuilder
.withTimestamp(timestamp
);
1388 getOrCreateMessagePipe();
1389 getOrCreateUnidentifiedMessagePipe();
1391 final var recipientId
= account
.getSelfRecipientId();
1393 final var contact
= account
.getContactStore().getContact(recipientId
);
1394 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1395 messageBuilder
.withExpiration(expirationTime
);
1397 var message
= messageBuilder
.build();
1398 final var result
= sendSelfMessage(message
);
1399 return new Pair
<>(timestamp
, result
);
1405 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1406 var messageSender
= createMessageSender();
1408 var recipient
= account
.getSelfAddress();
1410 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(resolveRecipient(recipient
));
1411 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1412 message
.getTimestamp(),
1414 message
.getExpiresInSeconds(),
1415 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1417 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1420 var startTime
= System
.currentTimeMillis();
1421 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1422 return SendMessageResult
.success(recipient
,
1423 unidentifiedAccess
.isPresent(),
1425 System
.currentTimeMillis() - startTime
);
1426 } catch (UntrustedIdentityException e
) {
1427 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1431 private SendMessageResult
sendMessage(
1432 SignalServiceAddress address
, SignalServiceDataMessage message
1433 ) throws IOException
{
1434 var messageSender
= createMessageSender();
1437 return messageSender
.sendMessage(address
,
1438 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(address
)),
1440 } catch (UntrustedIdentityException e
) {
1441 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1445 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1446 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1447 account
.getSignalProtocolStore(),
1448 certificateValidator
);
1450 return cipher
.decrypt(envelope
);
1451 } catch (ProtocolUntrustedIdentityException e
) {
1452 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1453 throw (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1455 throw new AssertionError(e
);
1459 private void handleEndSession(RecipientId recipientId
) {
1460 account
.getSessionStore().deleteAllSessions(recipientId
);
1463 private List
<HandleAction
> handleSignalServiceDataMessage(
1464 SignalServiceDataMessage message
,
1466 SignalServiceAddress source
,
1467 SignalServiceAddress destination
,
1468 boolean ignoreAttachments
1470 var actions
= new ArrayList
<HandleAction
>();
1471 if (message
.getGroupContext().isPresent()) {
1472 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1473 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1474 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1475 var group
= getGroup(groupId
);
1476 if (group
== null || group
instanceof GroupInfoV1
) {
1477 var groupV1
= (GroupInfoV1
) group
;
1478 switch (groupInfo
.getType()) {
1480 if (groupV1
== null) {
1481 groupV1
= new GroupInfoV1(groupId
);
1484 if (groupInfo
.getAvatar().isPresent()) {
1485 var avatar
= groupInfo
.getAvatar().get();
1486 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1489 if (groupInfo
.getName().isPresent()) {
1490 groupV1
.name
= groupInfo
.getName().get();
1493 if (groupInfo
.getMembers().isPresent()) {
1494 groupV1
.addMembers(groupInfo
.getMembers()
1497 .map(this::resolveRecipient
)
1498 .collect(Collectors
.toSet()));
1501 account
.getGroupStore().updateGroup(groupV1
);
1505 if (groupV1
== null && !isSync
) {
1506 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1510 if (groupV1
!= null) {
1511 groupV1
.removeMember(resolveRecipient(source
));
1512 account
.getGroupStore().updateGroup(groupV1
);
1517 if (groupV1
!= null && !isSync
) {
1518 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1523 // Received a group v1 message for a v2 group
1526 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1527 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1528 final var groupMasterKey
= groupContext
.getMasterKey();
1530 getOrMigrateGroup(groupMasterKey
,
1531 groupContext
.getRevision(),
1532 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1536 final var conversationPartnerAddress
= isSync ? destination
: source
;
1537 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1538 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1540 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1541 if (message
.getGroupContext().isPresent()) {
1542 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1543 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1544 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1545 if (group
!= null) {
1546 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1547 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1548 account
.getGroupStore().updateGroup(group
);
1551 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1552 // disappearing message timer already stored in the DecryptedGroup
1554 } else if (conversationPartnerAddress
!= null) {
1555 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1558 if (!ignoreAttachments
) {
1559 if (message
.getAttachments().isPresent()) {
1560 for (var attachment
: message
.getAttachments().get()) {
1561 downloadAttachment(attachment
);
1564 if (message
.getSharedContacts().isPresent()) {
1565 for (var contact
: message
.getSharedContacts().get()) {
1566 if (contact
.getAvatar().isPresent()) {
1567 downloadAttachment(contact
.getAvatar().get().getAttachment());
1572 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1573 final ProfileKey profileKey
;
1575 profileKey
= new ProfileKey(message
.getProfileKey().get());
1576 } catch (InvalidInputException e
) {
1577 throw new AssertionError(e
);
1579 if (source
.matches(account
.getSelfAddress())) {
1580 this.account
.setProfileKey(profileKey
);
1582 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1584 if (message
.getPreviews().isPresent()) {
1585 final var previews
= message
.getPreviews().get();
1586 for (var preview
: previews
) {
1587 if (preview
.getImage().isPresent()) {
1588 downloadAttachment(preview
.getImage().get());
1592 if (message
.getQuote().isPresent()) {
1593 final var quote
= message
.getQuote().get();
1595 for (var quotedAttachment
: quote
.getAttachments()) {
1596 final var thumbnail
= quotedAttachment
.getThumbnail();
1597 if (thumbnail
!= null) {
1598 downloadAttachment(thumbnail
);
1602 if (message
.getSticker().isPresent()) {
1603 final var messageSticker
= message
.getSticker().get();
1604 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1605 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1606 if (sticker
== null) {
1607 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1608 account
.getStickerStore().updateSticker(sticker
);
1614 private GroupInfoV2
getOrMigrateGroup(
1615 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1617 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1619 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1620 var groupInfo
= getGroup(groupId
);
1621 final GroupInfoV2 groupInfoV2
;
1622 if (groupInfo
instanceof GroupInfoV1
) {
1623 // Received a v2 group message for a v1 group, we need to locally migrate the group
1624 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1625 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1626 logger
.info("Locally migrated group {} to group v2, id: {}",
1627 groupInfo
.getGroupId().toBase64(),
1628 groupInfoV2
.getGroupId().toBase64());
1629 } else if (groupInfo
instanceof GroupInfoV2
) {
1630 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1632 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1635 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1636 DecryptedGroup group
= null;
1637 if (signedGroupChange
!= null
1638 && groupInfoV2
.getGroup() != null
1639 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1640 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1642 if (group
== null) {
1643 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1645 if (group
!= null) {
1646 storeProfileKeysFromMembers(group
);
1647 final var avatar
= group
.getAvatar();
1648 if (avatar
!= null && !avatar
.isEmpty()) {
1649 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1652 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1653 account
.getGroupStore().updateGroup(groupInfoV2
);
1659 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1660 for (var member
: group
.getMembersList()) {
1661 final var address
= resolveRecipient(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1662 .toByteArray()), null));
1664 account
.getProfileStore()
1665 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1666 } catch (InvalidInputException ignored
) {
1671 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1672 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1673 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1674 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1675 if (actions
!= null) {
1676 queuedActions
.addAll(actions
);
1679 for (var action
: queuedActions
) {
1681 action
.execute(this);
1682 } catch (Throwable e
) {
1683 logger
.warn("Message action failed.", e
);
1688 private List
<HandleAction
> retryFailedReceivedMessage(
1689 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1691 var envelope
= cachedMessage
.loadEnvelope();
1692 if (envelope
== null) {
1695 SignalServiceContent content
= null;
1696 List
<HandleAction
> actions
= null;
1697 if (!envelope
.isReceipt()) {
1699 content
= decryptMessage(envelope
);
1700 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1701 if (!envelope
.hasSource()) {
1702 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
)
1705 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1706 } catch (IOException ioException
) {
1707 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1711 } catch (Exception er
) {
1712 // All other errors are not recoverable, so delete the cached message
1713 cachedMessage
.delete();
1716 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1719 handler
.handleMessage(envelope
, content
, null);
1720 cachedMessage
.delete();
1724 public void receiveMessages(
1727 boolean returnOnTimeout
,
1728 boolean ignoreAttachments
,
1729 ReceiveMessageHandler handler
1730 ) throws IOException
{
1731 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1733 Set
<HandleAction
> queuedActions
= null;
1735 final var messagePipe
= getOrCreateMessagePipe();
1737 var hasCaughtUpWithOldMessages
= false;
1740 SignalServiceEnvelope envelope
;
1741 SignalServiceContent content
= null;
1742 Exception exception
= null;
1743 final CachedMessage
[] cachedMessage
= {null};
1745 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1746 final var recipientId
= envelope1
.hasSource()
1747 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1749 // store message on disk, before acknowledging receipt to the server
1750 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1752 if (result
.isPresent()) {
1753 envelope
= result
.get();
1755 // Received indicator that server queue is empty
1756 hasCaughtUpWithOldMessages
= true;
1758 if (queuedActions
!= null) {
1759 for (var action
: queuedActions
) {
1761 action
.execute(this);
1762 } catch (Throwable e
) {
1763 logger
.warn("Message action failed.", e
);
1767 queuedActions
.clear();
1768 queuedActions
= null;
1771 // Continue to wait another timeout for new messages
1774 } catch (TimeoutException e
) {
1775 if (returnOnTimeout
) return;
1779 if (envelope
.hasSource()) {
1780 // Store uuid if we don't have it already
1781 resolveRecipientTrusted(envelope
.getSourceAddress());
1783 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1784 if (!envelope
.isReceipt()) {
1786 content
= decryptMessage(envelope
);
1787 } catch (Exception e
) {
1790 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1791 if (hasCaughtUpWithOldMessages
) {
1792 for (var action
: actions
) {
1794 action
.execute(this);
1795 } catch (Throwable e
) {
1796 logger
.warn("Message action failed.", e
);
1800 if (queuedActions
== null) {
1801 queuedActions
= new HashSet
<>();
1803 queuedActions
.addAll(actions
);
1807 if (isMessageBlocked(envelope
, content
)) {
1808 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1809 } else if (notAGroupMember
) {
1810 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1812 handler
.handleMessage(envelope
, content
, exception
);
1814 if (cachedMessage
[0] != null) {
1815 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1816 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
)
1818 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1819 if (!envelope
.hasSource()) {
1821 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1822 } catch (IOException ioException
) {
1823 logger
.warn("Failed to move cached message to recipient folder: {}",
1824 ioException
.getMessage());
1828 cachedMessage
[0].delete();
1834 private boolean isMessageBlocked(
1835 SignalServiceEnvelope envelope
, SignalServiceContent content
1837 SignalServiceAddress source
;
1838 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1839 source
= envelope
.getSourceAddress();
1840 } else if (content
!= null) {
1841 source
= content
.getSender();
1845 final var recipientId
= resolveRecipient(source
);
1846 if (isContactBlocked(recipientId
)) {
1850 if (content
!= null && content
.getDataMessage().isPresent()) {
1851 var message
= content
.getDataMessage().get();
1852 if (message
.getGroupContext().isPresent()) {
1853 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1854 var group
= getGroup(groupId
);
1855 if (group
!= null && group
.isBlocked()) {
1863 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
1864 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
1865 return isContactBlocked(recipientId
);
1868 private boolean isContactBlocked(final RecipientId recipientId
) {
1869 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1870 return sourceContact
!= null && sourceContact
.isBlocked();
1873 private boolean isNotAGroupMember(
1874 SignalServiceEnvelope envelope
, SignalServiceContent content
1876 SignalServiceAddress source
;
1877 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1878 source
= envelope
.getSourceAddress();
1879 } else if (content
!= null) {
1880 source
= content
.getSender();
1885 if (content
!= null && content
.getDataMessage().isPresent()) {
1886 var message
= content
.getDataMessage().get();
1887 if (message
.getGroupContext().isPresent()) {
1888 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1889 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1890 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1894 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1895 var group
= getGroup(groupId
);
1896 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
1904 private List
<HandleAction
> handleMessage(
1905 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1907 var actions
= new ArrayList
<HandleAction
>();
1908 if (content
!= null) {
1909 final SignalServiceAddress sender
;
1910 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1911 sender
= envelope
.getSourceAddress();
1913 sender
= content
.getSender();
1916 if (content
.getDataMessage().isPresent()) {
1917 var message
= content
.getDataMessage().get();
1919 if (content
.isNeedsReceipt()) {
1920 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1923 actions
.addAll(handleSignalServiceDataMessage(message
,
1926 account
.getSelfAddress(),
1927 ignoreAttachments
));
1929 if (content
.getSyncMessage().isPresent()) {
1930 account
.setMultiDevice(true);
1931 var syncMessage
= content
.getSyncMessage().get();
1932 if (syncMessage
.getSent().isPresent()) {
1933 var message
= syncMessage
.getSent().get();
1934 final var destination
= message
.getDestination().orNull();
1935 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1939 ignoreAttachments
));
1941 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
1942 var rm
= syncMessage
.getRequest().get();
1943 if (rm
.isContactsRequest()) {
1944 actions
.add(SendSyncContactsAction
.create());
1946 if (rm
.isGroupsRequest()) {
1947 actions
.add(SendSyncGroupsAction
.create());
1949 if (rm
.isBlockedListRequest()) {
1950 actions
.add(SendSyncBlockedListAction
.create());
1952 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1954 if (syncMessage
.getGroups().isPresent()) {
1955 File tmpFile
= null;
1957 tmpFile
= IOUtils
.createTempFile();
1958 final var groupsMessage
= syncMessage
.getGroups().get();
1959 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1960 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1962 while ((g
= s
.read()) != null) {
1963 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1964 if (syncGroup
!= null) {
1965 if (g
.getName().isPresent()) {
1966 syncGroup
.name
= g
.getName().get();
1968 syncGroup
.addMembers(g
.getMembers()
1970 .map(this::resolveRecipient
)
1971 .collect(Collectors
.toSet()));
1972 if (!g
.isActive()) {
1973 syncGroup
.removeMember(account
.getSelfRecipientId());
1975 // Add ourself to the member set as it's marked as active
1976 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
1978 syncGroup
.blocked
= g
.isBlocked();
1979 if (g
.getColor().isPresent()) {
1980 syncGroup
.color
= g
.getColor().get();
1983 if (g
.getAvatar().isPresent()) {
1984 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1986 syncGroup
.archived
= g
.isArchived();
1987 account
.getGroupStore().updateGroup(syncGroup
);
1991 } catch (Exception e
) {
1992 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1996 if (tmpFile
!= null) {
1998 Files
.delete(tmpFile
.toPath());
1999 } catch (IOException e
) {
2000 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2007 if (syncMessage
.getBlockedList().isPresent()) {
2008 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2009 for (var address
: blockedListMessage
.getAddresses()) {
2010 setContactBlocked(resolveRecipient(address
), true);
2012 for (var groupId
: blockedListMessage
.getGroupIds()
2014 .map(GroupId
::unknownVersion
)
2015 .collect(Collectors
.toSet())) {
2017 setGroupBlocked(groupId
, true);
2018 } catch (GroupNotFoundException e
) {
2019 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2020 groupId
.toBase64());
2024 if (syncMessage
.getContacts().isPresent()) {
2025 File tmpFile
= null;
2027 tmpFile
= IOUtils
.createTempFile();
2028 final var contactsMessage
= syncMessage
.getContacts().get();
2029 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2030 .asPointer(), tmpFile
)) {
2031 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2033 while ((c
= s
.read()) != null) {
2034 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2035 account
.setProfileKey(c
.getProfileKey().get());
2037 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2038 var contact
= account
.getContactStore().getContact(recipientId
);
2039 final var builder
= contact
== null
2040 ? Contact
.newBuilder()
2041 : Contact
.newBuilder(contact
);
2042 if (c
.getName().isPresent()) {
2043 builder
.withName(c
.getName().get());
2045 if (c
.getColor().isPresent()) {
2046 builder
.withColor(c
.getColor().get());
2048 if (c
.getProfileKey().isPresent()) {
2049 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2051 if (c
.getVerified().isPresent()) {
2052 final var verifiedMessage
= c
.getVerified().get();
2053 account
.getIdentityKeyStore()
2054 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2055 verifiedMessage
.getIdentityKey(),
2056 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2058 if (c
.getExpirationTimer().isPresent()) {
2059 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2061 builder
.withBlocked(c
.isBlocked());
2062 builder
.withArchived(c
.isArchived());
2063 account
.getContactStore().storeContact(recipientId
, builder
.build());
2065 if (c
.getAvatar().isPresent()) {
2066 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2070 } catch (Exception e
) {
2071 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2075 if (tmpFile
!= null) {
2077 Files
.delete(tmpFile
.toPath());
2078 } catch (IOException e
) {
2079 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2086 if (syncMessage
.getVerified().isPresent()) {
2087 final var verifiedMessage
= syncMessage
.getVerified().get();
2088 account
.getIdentityKeyStore()
2089 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2090 verifiedMessage
.getIdentityKey(),
2091 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2093 if (syncMessage
.getStickerPackOperations().isPresent()) {
2094 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2095 for (var m
: stickerPackOperationMessages
) {
2096 if (!m
.getPackId().isPresent()) {
2099 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2100 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2101 if (sticker
== null) {
2102 if (!m
.getPackKey().isPresent()) {
2105 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2107 sticker
.setInstalled(!m
.getType().isPresent()
2108 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2109 account
.getStickerStore().updateSticker(sticker
);
2112 if (syncMessage
.getFetchType().isPresent()) {
2113 switch (syncMessage
.getFetchType().get()) {
2115 getRecipientProfile(account
.getSelfRecipientId(), true);
2116 case STORAGE_MANIFEST
:
2120 if (syncMessage
.getKeys().isPresent()) {
2121 final var keysMessage
= syncMessage
.getKeys().get();
2122 if (keysMessage
.getStorageService().isPresent()) {
2123 final var storageKey
= keysMessage
.getStorageService().get();
2124 account
.setStorageKey(storageKey
);
2127 if (syncMessage
.getConfiguration().isPresent()) {
2135 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2137 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2138 } catch (IOException e
) {
2139 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2143 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2145 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2146 } catch (IOException e
) {
2147 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2151 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2153 avatarStore
.storeGroupAvatar(groupId
,
2154 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2155 } catch (IOException e
) {
2156 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2160 private void downloadProfileAvatar(
2161 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2164 avatarStore
.storeProfileAvatar(address
,
2165 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2166 } catch (Throwable e
) {
2167 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2171 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2172 return attachmentStore
.getAttachmentFile(attachmentId
);
2175 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2176 if (!attachment
.isPointer()) {
2177 logger
.warn("Invalid state, can't store an attachment stream.");
2180 var pointer
= attachment
.asPointer();
2181 if (pointer
.getPreview().isPresent()) {
2182 final var preview
= pointer
.getPreview().get();
2184 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2185 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2186 } catch (IOException e
) {
2187 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2192 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2193 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2194 } catch (IOException e
) {
2195 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2199 private void retrieveGroupV2Avatar(
2200 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2201 ) throws IOException
{
2202 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2204 var tmpFile
= IOUtils
.createTempFile();
2205 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2207 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2208 var encryptedData
= IOUtils
.readFully(input
);
2210 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2211 outputStream
.write(decryptedData
);
2214 Files
.delete(tmpFile
.toPath());
2215 } catch (IOException e
) {
2216 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2223 private void retrieveProfileAvatar(
2224 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2225 ) throws IOException
{
2226 var tmpFile
= IOUtils
.createTempFile();
2227 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2230 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2231 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2232 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2235 Files
.delete(tmpFile
.toPath());
2236 } catch (IOException e
) {
2237 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2244 private void retrieveAttachment(
2245 final SignalServiceAttachment attachment
, final OutputStream outputStream
2246 ) throws IOException
{
2247 if (attachment
.isPointer()) {
2248 var pointer
= attachment
.asPointer();
2249 retrieveAttachmentPointer(pointer
, outputStream
);
2251 var stream
= attachment
.asStream();
2252 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2256 private void retrieveAttachmentPointer(
2257 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2258 ) throws IOException
{
2259 var tmpFile
= IOUtils
.createTempFile();
2260 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2261 IOUtils
.copyStream(input
, outputStream
);
2262 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2263 throw new IOException(e
);
2266 Files
.delete(tmpFile
.toPath());
2267 } catch (IOException e
) {
2268 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2275 private InputStream
retrieveAttachmentAsStream(
2276 SignalServiceAttachmentPointer pointer
, File tmpFile
2277 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2278 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2281 void sendGroups() throws IOException
, UntrustedIdentityException
{
2282 var groupsFile
= IOUtils
.createTempFile();
2285 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2286 var out
= new DeviceGroupsOutputStream(fos
);
2287 for (var record : getGroups()) {
2288 if (record instanceof GroupInfoV1
) {
2289 var groupInfo
= (GroupInfoV1
) record;
2290 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2291 Optional
.fromNullable(groupInfo
.name
),
2292 groupInfo
.getMembers()
2294 .map(this::resolveSignalServiceAddress
)
2295 .collect(Collectors
.toList()),
2296 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2297 groupInfo
.isMember(account
.getSelfRecipientId()),
2298 Optional
.of(groupInfo
.messageExpirationTime
),
2299 Optional
.fromNullable(groupInfo
.color
),
2302 groupInfo
.archived
));
2307 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2308 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2309 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2310 .withStream(groupsFileStream
)
2311 .withContentType("application/octet-stream")
2312 .withLength(groupsFile
.length())
2315 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2320 Files
.delete(groupsFile
.toPath());
2321 } catch (IOException e
) {
2322 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2327 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2328 var contactsFile
= IOUtils
.createTempFile();
2331 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2332 var out
= new DeviceContactsOutputStream(fos
);
2333 for (var contactPair
: account
.getContactStore().getContacts()) {
2334 final var recipientId
= contactPair
.first();
2335 final var contact
= contactPair
.second();
2336 final var address
= resolveSignalServiceAddress(recipientId
);
2338 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2339 VerifiedMessage verifiedMessage
= null;
2340 if (currentIdentity
!= null) {
2341 verifiedMessage
= new VerifiedMessage(address
,
2342 currentIdentity
.getIdentityKey(),
2343 currentIdentity
.getTrustLevel().toVerifiedState(),
2344 currentIdentity
.getDateAdded().getTime());
2347 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2348 out
.write(new DeviceContact(address
,
2349 Optional
.fromNullable(contact
.getName()),
2350 createContactAvatarAttachment(address
),
2351 Optional
.fromNullable(contact
.getColor()),
2352 Optional
.fromNullable(verifiedMessage
),
2353 Optional
.fromNullable(profileKey
),
2354 contact
.isBlocked(),
2355 Optional
.of(contact
.getMessageExpirationTime()),
2357 contact
.isArchived()));
2360 if (account
.getProfileKey() != null) {
2361 // Send our own profile key as well
2362 out
.write(new DeviceContact(account
.getSelfAddress(),
2367 Optional
.of(account
.getProfileKey()),
2375 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2376 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2377 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2378 .withStream(contactsFileStream
)
2379 .withContentType("application/octet-stream")
2380 .withLength(contactsFile
.length())
2383 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2388 Files
.delete(contactsFile
.toPath());
2389 } catch (IOException e
) {
2390 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2395 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2396 var addresses
= new ArrayList
<SignalServiceAddress
>();
2397 for (var record : account
.getContactStore().getContacts()) {
2398 if (record.second().isBlocked()) {
2399 addresses
.add(resolveSignalServiceAddress(record.first()));
2402 var groupIds
= new ArrayList
<byte[]>();
2403 for (var record : getGroups()) {
2404 if (record.isBlocked()) {
2405 groupIds
.add(record.getGroupId().serialize());
2408 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2411 private void sendVerifiedMessage(
2412 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2413 ) throws IOException
, UntrustedIdentityException
{
2414 var verifiedMessage
= new VerifiedMessage(destination
,
2416 trustLevel
.toVerifiedState(),
2417 System
.currentTimeMillis());
2418 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2421 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2422 return account
.getContactStore().getContacts();
2425 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2426 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2427 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2428 if (recipient
== null) {
2432 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2433 return recipient
.getContact().getName();
2436 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2437 return recipient
.getProfile().getDisplayName();
2443 public GroupInfo
getGroup(GroupId groupId
) {
2444 final var group
= account
.getGroupStore().getGroup(groupId
);
2445 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2446 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2447 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2448 account
.getGroupStore().updateGroup(group
);
2453 public List
<IdentityInfo
> getIdentities() {
2454 return account
.getIdentityKeyStore().getIdentities();
2457 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2458 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2459 return identity
== null ? List
.of() : List
.of(identity
);
2463 * Trust this the identity with this fingerprint
2465 * @param name username of the identity
2466 * @param fingerprint Fingerprint
2468 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2469 var recipientId
= canonicalizeAndResolveRecipient(name
);
2470 return trustIdentity(recipientId
,
2471 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2472 TrustLevel
.TRUSTED_VERIFIED
);
2476 * Trust this the identity with this safety number
2478 * @param name username of the identity
2479 * @param safetyNumber Safety number
2481 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2482 var recipientId
= canonicalizeAndResolveRecipient(name
);
2483 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2484 return trustIdentity(recipientId
,
2485 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2486 TrustLevel
.TRUSTED_VERIFIED
);
2490 * Trust all keys of this identity without verification
2492 * @param name username of the identity
2494 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2495 var recipientId
= canonicalizeAndResolveRecipient(name
);
2496 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2499 private boolean trustIdentity(
2500 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2502 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2503 if (identity
== null) {
2507 if (!verifier
.apply(identity
.getIdentityKey())) {
2511 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2513 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2514 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2515 } catch (IOException
| UntrustedIdentityException e
) {
2516 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2522 public String
computeSafetyNumber(
2523 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2525 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2526 account
.getSelfAddress(),
2527 getIdentityKeyPair().getPublicKey(),
2533 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2534 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2536 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2537 return resolveSignalServiceAddress(canonicalizedNumber
);
2541 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2542 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2544 return resolveSignalServiceAddress(address
);
2548 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2549 if (address
.matches(account
.getSelfAddress())) {
2550 return account
.getSelfAddress();
2553 return account
.getRecipientStore().resolveServiceAddress(address
);
2556 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2557 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2560 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2561 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2563 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2565 return resolveRecipient(canonicalizedNumber
);
2568 private RecipientId
resolveRecipient(final String identifier
) {
2569 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2571 return resolveRecipient(address
);
2574 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2575 return account
.getRecipientStore().resolveRecipient(address
);
2578 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2579 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2583 public void close() throws IOException
{
2587 void close(boolean closeAccount
) throws IOException
{
2588 executor
.shutdown();
2590 if (messagePipe
!= null) {
2591 messagePipe
.shutdown();
2595 if (unidentifiedMessagePipe
!= null) {
2596 unidentifiedMessagePipe
.shutdown();
2597 unidentifiedMessagePipe
= null;
2600 if (closeAccount
&& account
!= null) {
2606 public interface ReceiveMessageHandler
{
2608 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);