2 Copyright (C) 2015-2021 AsamK and contributors
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
20 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
21 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
22 import org
.asamk
.signal
.manager
.groups
.GroupId
;
23 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
24 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
25 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
26 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
27 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
28 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
29 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
30 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
31 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
32 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
33 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
34 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
35 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
36 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
37 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
38 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
39 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
40 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
41 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
42 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
43 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
44 import org
.asamk
.signal
.manager
.util
.IOUtils
;
45 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
46 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
47 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
48 import org
.asamk
.signal
.manager
.util
.Utils
;
49 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
50 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
51 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
52 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
53 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
54 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
56 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
57 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
58 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
59 import org
.signal
.libsignal
.metadata
.SelfSendException
;
60 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
61 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
62 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
63 import org
.signal
.zkgroup
.InvalidInputException
;
64 import org
.signal
.zkgroup
.VerificationFailedException
;
65 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
66 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
67 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
68 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
69 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
70 import org
.slf4j
.Logger
;
71 import org
.slf4j
.LoggerFactory
;
72 import org
.whispersystems
.libsignal
.IdentityKey
;
73 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
74 import org
.whispersystems
.libsignal
.InvalidKeyException
;
75 import org
.whispersystems
.libsignal
.InvalidMessageException
;
76 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
77 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
78 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
79 import org
.whispersystems
.libsignal
.util
.Pair
;
80 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
81 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
82 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
83 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
84 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
85 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
86 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
87 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
88 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
89 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
90 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
91 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
92 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
93 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
94 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
95 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
96 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
103 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
104 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
105 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
106 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
107 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
117 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
118 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
119 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
120 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
121 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
122 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
123 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
124 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
125 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
126 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
127 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
128 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
129 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
130 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
131 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
132 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
133 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
135 import java
.io
.Closeable
;
137 import java
.io
.FileInputStream
;
138 import java
.io
.FileOutputStream
;
139 import java
.io
.IOException
;
140 import java
.io
.InputStream
;
141 import java
.io
.OutputStream
;
143 import java
.net
.URISyntaxException
;
144 import java
.net
.URLEncoder
;
145 import java
.nio
.charset
.StandardCharsets
;
146 import java
.nio
.file
.Files
;
147 import java
.security
.SignatureException
;
148 import java
.util
.ArrayList
;
149 import java
.util
.Arrays
;
150 import java
.util
.Base64
;
151 import java
.util
.Collection
;
152 import java
.util
.Date
;
153 import java
.util
.HashSet
;
154 import java
.util
.List
;
155 import java
.util
.Map
;
156 import java
.util
.Set
;
157 import java
.util
.UUID
;
158 import java
.util
.concurrent
.ExecutorService
;
159 import java
.util
.concurrent
.Executors
;
160 import java
.util
.concurrent
.TimeUnit
;
161 import java
.util
.concurrent
.TimeoutException
;
162 import java
.util
.function
.Function
;
163 import java
.util
.stream
.Collectors
;
165 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
167 public class Manager
implements Closeable
{
169 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
171 private final CertificateValidator certificateValidator
;
173 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
174 private final String userAgent
;
176 private SignalAccount account
;
177 private final SignalServiceAccountManager accountManager
;
178 private final GroupsV2Api groupsV2Api
;
179 private final GroupsV2Operations groupsV2Operations
;
180 private final SignalServiceMessageReceiver messageReceiver
;
181 private final ClientZkProfileOperations clientZkProfileOperations
;
183 private final ExecutorService executor
= Executors
.newCachedThreadPool();
185 private SignalServiceMessagePipe messagePipe
= null;
186 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
188 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
189 private final ProfileHelper profileHelper
;
190 private final GroupHelper groupHelper
;
191 private final PinHelper pinHelper
;
192 private final AvatarStore avatarStore
;
193 private final AttachmentStore attachmentStore
;
196 SignalAccount account
,
197 PathConfig pathConfig
,
198 ServiceEnvironmentConfig serviceEnvironmentConfig
,
201 this.account
= account
;
202 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
203 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
204 this.userAgent
= userAgent
;
205 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
206 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
207 final SleepTimer timer
= new UptimeSleepTimer();
208 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
209 new DynamicCredentialsProvider(account
.getUuid(),
210 account
.getUsername(),
211 account
.getPassword(),
212 account
.getDeviceId()),
215 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
217 this.groupsV2Api
= accountManager
.getGroupsV2Api();
218 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
219 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
220 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
221 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
224 this.pinHelper
= new PinHelper(keyBackupService
);
225 this.clientZkProfileOperations
= capabilities
.isGv2()
226 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
227 .getProfileOperations()
229 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
231 account
.getUsername(),
232 account
.getPassword(),
233 account
.getDeviceId(),
237 clientZkProfileOperations
,
238 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
240 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
241 account
.getProfileStore()::getProfileKey
,
242 this::getRecipientProfile
,
243 this::getSenderCertificate
);
244 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
245 unidentifiedAccessHelper
::getAccessFor
,
246 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
247 () -> messageReceiver
,
248 this::resolveSignalServiceAddress
);
249 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
250 this::getRecipientProfile
,
251 account
::getSelfRecipientId
,
254 this::getGroupAuthForToday
,
255 this::resolveSignalServiceAddress
);
256 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
257 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
260 public String
getUsername() {
261 return account
.getUsername();
264 public SignalServiceAddress
getSelfAddress() {
265 return account
.getSelfAddress();
268 public RecipientId
getSelfRecipientId() {
269 return account
.getSelfRecipientId();
272 private IdentityKeyPair
getIdentityKeyPair() {
273 return account
.getIdentityKeyPair();
276 public int getDeviceId() {
277 return account
.getDeviceId();
280 public static Manager
init(
281 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
282 ) throws IOException
, NotRegisteredException
{
283 var pathConfig
= PathConfig
.createDefault(settingsPath
);
285 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
286 throw new NotRegisteredException();
289 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
291 if (!account
.isRegistered()) {
292 throw new NotRegisteredException();
295 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
297 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
300 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
301 var pathConfig
= PathConfig
.createDefault(settingsPath
);
302 final var dataPath
= pathConfig
.getDataPath();
303 final var files
= dataPath
.listFiles();
309 return Arrays
.stream(files
)
310 .filter(File
::isFile
)
312 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
313 .collect(Collectors
.toList());
316 public void checkAccountState() throws IOException
{
317 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
320 if (account
.getUuid() == null) {
321 account
.setUuid(accountManager
.getOwnUuid());
323 updateAccountAttributes();
327 * This is used for checking a set of phone numbers for registration on Signal
329 * @param numbers The set of phone number in question
330 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
331 * @throws IOException if its unable to get the contacts to check if they're registered
333 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
334 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
335 var contactDetails
= getRegisteredUsers(numbers
);
337 var registeredUsers
= contactDetails
.keySet();
339 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
342 public void updateAccountAttributes() throws IOException
{
343 accountManager
.setAccountAttributes(null,
344 account
.getLocalRegistrationId(),
346 // set legacy pin only if no KBS master key is set
347 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
348 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
349 account
.getSelfUnidentifiedAccessKey(),
350 account
.isUnrestrictedUnidentifiedAccess(),
352 account
.isDiscoverableByPhoneNumber());
356 * @param name if null, the previous name will be kept
357 * @param about if null, the previous about text will be kept
358 * @param aboutEmoji if null, the previous about emoji will be kept
359 * @param avatar if avatar is null the image from the local avatar store is used (if present),
360 * if it's Optional.absent(), the avatar will be removed
362 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
363 var profile
= getRecipientProfile(account
.getSelfRecipientId());
364 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
366 builder
.withGivenName(name
);
367 builder
.withFamilyName(null);
370 builder
.withAbout(about
);
372 if (aboutEmoji
!= null) {
373 builder
.withAboutEmoji(aboutEmoji
);
375 var newProfile
= builder
.build();
377 try (final var streamDetails
= avatar
== null
378 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
379 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
380 accountManager
.setVersionedProfile(account
.getUuid(),
381 account
.getProfileKey(),
382 newProfile
.getInternalServiceName(),
383 newProfile
.getAbout(),
384 newProfile
.getAboutEmoji(),
388 if (avatar
!= null) {
389 if (avatar
.isPresent()) {
390 avatarStore
.storeProfileAvatar(getSelfAddress(),
391 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
393 avatarStore
.deleteProfileAvatar(getSelfAddress());
396 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
399 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
400 } catch (UntrustedIdentityException ignored
) {
404 public void unregister() throws IOException
{
405 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
406 // If this is the master device, other users can't send messages to this number anymore.
407 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
408 accountManager
.setGcmId(Optional
.absent());
409 accountManager
.deleteAccount();
411 account
.setRegistered(false);
414 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
415 var devices
= accountManager
.getDevices();
416 account
.setMultiDevice(devices
.size() > 1);
420 public void removeLinkedDevices(int deviceId
) throws IOException
{
421 accountManager
.removeDevice(deviceId
);
422 var devices
= accountManager
.getDevices();
423 account
.setMultiDevice(devices
.size() > 1);
426 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
427 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
429 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
432 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
433 var identityKeyPair
= getIdentityKeyPair();
434 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
436 accountManager
.addDevice(deviceIdentifier
,
439 Optional
.of(account
.getProfileKey().serialize()),
441 account
.setMultiDevice(true);
444 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
445 if (!account
.isMasterDevice()) {
446 throw new RuntimeException("Only master device can set a PIN");
448 if (pin
.isPresent()) {
449 final var masterKey
= account
.getPinMasterKey() != null
450 ? account
.getPinMasterKey()
451 : KeyUtils
.createMasterKey();
453 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
455 account
.setRegistrationLockPin(pin
.get(), masterKey
);
457 // Remove legacy registration lock
458 accountManager
.removeRegistrationLockV1();
461 pinHelper
.removeRegistrationLockPin();
463 account
.setRegistrationLockPin(null, null);
467 void refreshPreKeys() throws IOException
{
468 var oneTimePreKeys
= generatePreKeys();
469 final var identityKeyPair
= getIdentityKeyPair();
470 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
472 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
475 private List
<PreKeyRecord
> generatePreKeys() {
476 final var offset
= account
.getPreKeyIdOffset();
478 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
479 account
.addPreKeys(records
);
484 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
485 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
487 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
488 account
.addSignedPreKey(record);
493 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
494 if (messagePipe
== null) {
495 messagePipe
= messageReceiver
.createMessagePipe();
500 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
501 if (unidentifiedMessagePipe
== null) {
502 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
504 return unidentifiedMessagePipe
;
507 private SignalServiceMessageSender
createMessageSender() {
508 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
510 account
.getUsername(),
511 account
.getPassword(),
512 account
.getDeviceId(),
513 account
.getSignalProtocolStore(),
515 account
.isMultiDevice(),
516 Optional
.fromNullable(messagePipe
),
517 Optional
.fromNullable(unidentifiedMessagePipe
),
519 clientZkProfileOperations
,
521 ServiceConfig
.MAX_ENVELOPE_SIZE
,
522 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
525 public Profile
getRecipientProfile(
526 SignalServiceAddress address
528 return getRecipientProfile(resolveRecipient(address
), false);
531 public Profile
getRecipientProfile(
532 RecipientId recipientId
534 return getRecipientProfile(recipientId
, false);
537 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
539 Profile
getRecipientProfile(
540 RecipientId recipientId
, boolean force
542 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
543 if (profileKey
== null) {
545 // retrieve profile to get identity key
546 retrieveEncryptedProfile(recipientId
);
550 var profile
= account
.getProfileStore().getProfile(recipientId
);
552 var now
= new Date().getTime();
553 // Profiles are cached for 24h before retrieving them again, unless forced
554 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
558 synchronized (pendingProfileRequest
) {
559 if (pendingProfileRequest
.contains(recipientId
)) {
562 pendingProfileRequest
.add(recipientId
);
564 final SignalServiceProfile encryptedProfile
;
566 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
568 synchronized (pendingProfileRequest
) {
569 pendingProfileRequest
.remove(recipientId
);
572 if (encryptedProfile
== null) {
576 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
577 account
.getProfileStore().storeProfile(recipientId
, profile
);
582 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
584 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
585 } catch (IOException e
) {
586 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
591 private ProfileAndCredential
retrieveProfileAndCredential(
592 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
593 ) throws IOException
{
594 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
595 final var profile
= profileAndCredential
.getProfile();
598 account
.getIdentityKeyStore()
599 .saveIdentity(recipientId
,
600 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
602 } catch (InvalidKeyException ignored
) {
603 logger
.warn("Got invalid identity key in profile for {}",
604 resolveSignalServiceAddress(recipientId
).getLegacyIdentifier());
606 return profileAndCredential
;
609 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
610 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
611 if (profileKeyCredential
!= null) {
612 return profileKeyCredential
;
615 ProfileAndCredential profileAndCredential
;
617 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
618 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
619 } catch (IOException e
) {
620 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
624 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
625 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
627 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
628 if (profileKey
!= null) {
629 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
631 profileAndCredential
.getProfile());
632 account
.getProfileStore().storeProfile(recipientId
, profile
);
635 return profileKeyCredential
;
638 private Profile
decryptProfileAndDownloadAvatar(
639 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
641 if (encryptedProfile
.getAvatar() != null) {
642 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
645 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
648 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
649 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
650 if (streamDetails
== null) {
651 return Optional
.absent();
654 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
657 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
658 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
659 if (streamDetails
== null) {
660 return Optional
.absent();
663 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
666 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
667 var g
= getGroup(groupId
);
669 throw new GroupNotFoundException(groupId
);
671 if (!g
.isMember(account
.getSelfRecipientId())) {
672 throw new NotAGroupMemberException(groupId
, g
.getTitle());
677 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
678 var g
= getGroup(groupId
);
680 throw new GroupNotFoundException(groupId
);
682 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
683 throw new NotAGroupMemberException(groupId
, g
.getTitle());
688 public List
<GroupInfo
> getGroups() {
689 return account
.getGroupStore().getGroups();
692 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
693 String messageText
, List
<String
> attachments
, GroupId groupId
694 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
695 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
696 if (attachments
!= null) {
697 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
700 return sendGroupMessage(messageBuilder
, groupId
);
703 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
704 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
705 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
706 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
708 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
709 targetSentTimestamp
);
710 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
712 return sendGroupMessage(messageBuilder
, groupId
);
715 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
716 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
717 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
718 final var g
= getGroupForSending(groupId
);
720 GroupUtils
.setGroupContext(messageBuilder
, g
);
721 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
723 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
726 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
727 SignalServiceDataMessage
.Builder messageBuilder
;
729 final var g
= getGroupForUpdating(groupId
);
730 if (g
instanceof GroupInfoV1
) {
731 var groupInfoV1
= (GroupInfoV1
) g
;
732 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
733 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
734 groupInfoV1
.removeMember(account
.getSelfRecipientId());
735 account
.getGroupStore().updateGroup(groupInfoV1
);
737 final var groupInfoV2
= (GroupInfoV2
) g
;
738 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
739 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
740 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
741 account
.getGroupStore().updateGroup(groupInfoV2
);
744 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
747 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
748 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
749 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
750 return sendUpdateGroupMessage(groupId
,
752 members
== null ?
null : getSignalServiceAddresses(members
),
756 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
757 GroupId groupId
, String name
, Set
<RecipientId
> members
, File avatarFile
758 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
760 SignalServiceDataMessage
.Builder messageBuilder
;
761 if (groupId
== null) {
763 var gv2Pair
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
764 members
== null ? Set
.of() : members
,
766 if (gv2Pair
== null) {
767 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
768 gv1
.addMembers(List
.of(account
.getSelfRecipientId()));
769 updateGroupV1(gv1
, name
, members
, avatarFile
);
770 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
773 final var gv2
= gv2Pair
.first();
774 final var decryptedGroup
= gv2Pair
.second();
776 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
777 if (avatarFile
!= null) {
778 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
779 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
781 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
785 var group
= getGroupForUpdating(groupId
);
786 if (group
instanceof GroupInfoV2
) {
787 final var groupInfoV2
= (GroupInfoV2
) group
;
789 Pair
<Long
, List
<SendMessageResult
>> result
= null;
790 if (groupInfoV2
.isPendingMember(account
.getSelfRecipientId())) {
791 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
792 result
= sendUpdateGroupMessage(groupInfoV2
,
793 groupGroupChangePair
.first(),
794 groupGroupChangePair
.second());
797 if (members
!= null) {
798 final var newMembers
= new HashSet
<>(members
);
799 newMembers
.removeAll(group
.getMembers());
800 if (newMembers
.size() > 0) {
801 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
802 result
= sendUpdateGroupMessage(groupInfoV2
,
803 groupGroupChangePair
.first(),
804 groupGroupChangePair
.second());
807 if (result
== null || name
!= null || avatarFile
!= null) {
808 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
809 if (avatarFile
!= null) {
810 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
811 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
813 result
= sendUpdateGroupMessage(groupInfoV2
,
814 groupGroupChangePair
.first(),
815 groupGroupChangePair
.second());
818 return new Pair
<>(group
.getGroupId(), result
.second());
820 var gv1
= (GroupInfoV1
) group
;
821 updateGroupV1(gv1
, name
, members
, avatarFile
);
822 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
827 account
.getGroupStore().updateGroup(g
);
829 final var result
= sendMessage(messageBuilder
,
830 g
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
831 return new Pair
<>(g
.getGroupId(), result
.second());
834 private void updateGroupV1(
835 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
836 ) throws IOException
{
841 if (members
!= null) {
842 final var newMemberAddresses
= members
.stream()
843 .filter(member
-> !g
.isMember(member
))
844 .map(this::resolveSignalServiceAddress
)
845 .collect(Collectors
.toList());
846 final var newE164Members
= new HashSet
<String
>();
847 for (var member
: newMemberAddresses
) {
848 if (!member
.getNumber().isPresent()) {
851 newE164Members
.add(member
.getNumber().get());
854 final var registeredUsers
= getRegisteredUsers(newE164Members
);
855 if (registeredUsers
.size() != newE164Members
.size()) {
856 // Some of the new members are not registered on Signal
857 newE164Members
.removeAll(registeredUsers
.keySet());
858 throw new IOException("Failed to add members "
859 + String
.join(", ", newE164Members
)
860 + " to group: Not registered on Signal");
863 g
.addMembers(members
);
866 if (avatarFile
!= null) {
867 avatarStore
.storeGroupAvatar(g
.getGroupId(),
868 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
872 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
873 GroupInviteLinkUrl inviteLinkUrl
874 ) throws IOException
, GroupLinkNotActiveException
{
875 return sendJoinGroupMessage(inviteLinkUrl
);
878 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
879 GroupInviteLinkUrl inviteLinkUrl
880 ) throws IOException
, GroupLinkNotActiveException
{
881 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
882 inviteLinkUrl
.getPassword());
883 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
884 inviteLinkUrl
.getPassword(),
886 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
887 groupJoinInfo
.getRevision() + 1,
888 groupChange
.toByteArray());
890 if (group
.getGroup() == null) {
891 // Only requested member, can't send update to group members
892 return new Pair
<>(group
.getGroupId(), List
.of());
895 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
897 return new Pair
<>(group
.getGroupId(), result
.second());
900 private static int currentTimeDays() {
901 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
904 private GroupsV2AuthorizationString
getGroupAuthForToday(
905 final GroupSecretParams groupSecretParams
906 ) throws IOException
{
907 final var today
= currentTimeDays();
908 // Returns credentials for the next 7 days
909 final var credentials
= groupsV2Api
.getCredentials(today
);
910 // TODO cache credentials until they expire
911 var authCredentialResponse
= credentials
.get(today
);
913 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
916 authCredentialResponse
);
917 } catch (VerificationFailedException e
) {
918 throw new IOException(e
);
922 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
923 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
924 ) throws IOException
{
925 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
926 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
927 account
.getGroupStore().updateGroup(group
);
928 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
931 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
932 GroupIdV1 groupId
, SignalServiceAddress recipient
933 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
935 var group
= getGroupForSending(groupId
);
936 if (!(group
instanceof GroupInfoV1
)) {
937 throw new RuntimeException("Received an invalid group request for a v2 group!");
939 g
= (GroupInfoV1
) group
;
941 if (!g
.isMember(resolveRecipient(recipient
))) {
942 throw new NotAGroupMemberException(groupId
, g
.name
);
945 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
947 // Send group message only to the recipient who requested it
948 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
951 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
952 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
953 .withId(g
.getGroupId().serialize())
955 .withMembers(g
.getMembers()
957 .map(this::resolveSignalServiceAddress
)
958 .collect(Collectors
.toList()));
961 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
962 if (attachment
.isPresent()) {
963 group
.withAvatar(attachment
.get());
965 } catch (IOException e
) {
966 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
969 return SignalServiceDataMessage
.newBuilder()
970 .asGroupMessage(group
.build())
971 .withExpiration(g
.getMessageExpirationTime());
974 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
975 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
976 .withRevision(g
.getGroup().getRevision())
977 .withSignedGroupChange(signedGroupChange
);
978 return SignalServiceDataMessage
.newBuilder()
979 .asGroupMessage(group
.build())
980 .withExpiration(g
.getMessageExpirationTime());
983 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
984 GroupIdV1 groupId
, SignalServiceAddress recipient
985 ) throws IOException
{
986 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
988 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
990 // Send group info request message to the recipient who sent us a message with this groupId
991 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
995 SignalServiceAddress remoteAddress
, long messageId
996 ) throws IOException
, UntrustedIdentityException
{
997 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
999 System
.currentTimeMillis());
1001 createMessageSender().sendReceipt(remoteAddress
,
1002 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1006 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1007 String messageText
, List
<String
> attachments
, List
<String
> recipients
1008 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1009 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1010 if (attachments
!= null) {
1011 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1013 // Upload attachments here, so we only upload once even for multiple recipients
1014 var messageSender
= createMessageSender();
1015 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1016 for (var attachment
: attachmentStreams
) {
1017 if (attachment
.isStream()) {
1018 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1019 } else if (attachment
.isPointer()) {
1020 attachmentPointers
.add(attachment
.asPointer());
1024 messageBuilder
.withAttachments(attachmentPointers
);
1026 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1029 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1030 String messageText
, List
<String
> attachments
1031 ) throws IOException
, AttachmentInvalidException
{
1032 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1033 if (attachments
!= null) {
1034 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1036 return sendSelfMessage(messageBuilder
);
1039 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1040 long targetSentTimestamp
, List
<String
> recipients
1041 ) throws IOException
, InvalidNumberException
{
1042 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1043 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1044 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1047 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1048 long targetSentTimestamp
, GroupId groupId
1049 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1050 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1051 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1052 return sendGroupMessage(messageBuilder
, groupId
);
1055 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1056 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1057 ) throws IOException
, InvalidNumberException
{
1058 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1060 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1061 targetSentTimestamp
);
1062 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1063 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1066 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1067 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1069 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1071 return sendMessage(messageBuilder
, signalServiceAddresses
);
1072 } catch (Exception e
) {
1073 for (var address
: signalServiceAddresses
) {
1074 handleEndSession(address
);
1080 public String
getContactName(String number
) throws InvalidNumberException
{
1081 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1082 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1085 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1086 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1087 var contact
= account
.getContactStore().getContact(recipientId
);
1088 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1089 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1092 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1093 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1096 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1097 var contact
= account
.getContactStore().getContact(recipientId
);
1098 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1099 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1102 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1103 var group
= getGroup(groupId
);
1104 if (group
== null) {
1105 throw new GroupNotFoundException(groupId
);
1108 group
.setBlocked(blocked
);
1109 account
.getGroupStore().updateGroup(group
);
1112 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1113 var contact
= account
.getContactStore().getContact(recipientId
);
1114 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1117 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1118 account
.getContactStore()
1119 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1122 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1123 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1124 sendMessage(messageBuilder
, Set
.of(recipientId
));
1128 * Change the expiration timer for a contact
1130 public void setExpirationTimer(
1131 String number
, int messageExpirationTimer
1132 ) throws IOException
, InvalidNumberException
{
1133 var recipientId
= canonicalizeAndResolveRecipient(number
);
1134 setExpirationTimer(recipientId
, messageExpirationTimer
);
1135 sendExpirationTimerUpdate(recipientId
);
1139 * Change the expiration timer for a group
1141 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1142 var g
= getGroup(groupId
);
1143 if (g
instanceof GroupInfoV1
) {
1144 var groupInfoV1
= (GroupInfoV1
) g
;
1145 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1146 account
.getGroupStore().updateGroup(groupInfoV1
);
1148 throw new RuntimeException("TODO Not implemented!");
1153 * Upload the sticker pack from path.
1155 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1156 * @return if successful, returns the URL to install the sticker pack in the signal app
1158 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1159 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1161 var messageSender
= createMessageSender();
1163 var packKey
= KeyUtils
.createStickerUploadKey();
1164 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1166 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1167 account
.getStickerStore().updateSticker(sticker
);
1170 return new URI("https",
1173 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1174 Hex
.toStringCondensed(packKey
),
1175 StandardCharsets
.UTF_8
)).toString();
1176 } catch (URISyntaxException e
) {
1177 throw new AssertionError(e
);
1181 void requestSyncGroups() throws IOException
{
1182 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1183 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1185 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1187 sendSyncMessage(message
);
1188 } catch (UntrustedIdentityException e
) {
1189 throw new AssertionError(e
);
1193 void requestSyncContacts() throws IOException
{
1194 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1195 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1197 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1199 sendSyncMessage(message
);
1200 } catch (UntrustedIdentityException e
) {
1201 throw new AssertionError(e
);
1205 void requestSyncBlocked() throws IOException
{
1206 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1207 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1209 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1211 sendSyncMessage(message
);
1212 } catch (UntrustedIdentityException e
) {
1213 throw new AssertionError(e
);
1217 void requestSyncConfiguration() throws IOException
{
1218 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1219 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1221 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1223 sendSyncMessage(message
);
1224 } catch (UntrustedIdentityException e
) {
1225 throw new AssertionError(e
);
1229 void requestSyncKeys() throws IOException
{
1230 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1231 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1233 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1235 sendSyncMessage(message
);
1236 } catch (UntrustedIdentityException e
) {
1237 throw new AssertionError(e
);
1241 private byte[] getSenderCertificate() {
1242 // TODO support UUID capable sender certificates
1243 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1246 certificate
= accountManager
.getSenderCertificate();
1247 } catch (IOException e
) {
1248 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1251 // TODO cache for a day
1255 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1256 var messageSender
= createMessageSender();
1257 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1260 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1261 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1262 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1264 for (var number
: numbers
) {
1265 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1266 if (resolvedAddress
.getUuid().isPresent()) {
1267 signalServiceAddresses
.add(resolvedAddress
);
1269 addressesMissingUuid
.add(resolvedAddress
);
1273 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1274 .map(a
-> a
.getNumber().get())
1275 .collect(Collectors
.toSet());
1276 Map
<String
, UUID
> registeredUsers
;
1278 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1279 } catch (IOException e
) {
1280 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1281 registeredUsers
= Map
.of();
1284 for (var address
: addressesMissingUuid
) {
1285 final var number
= address
.getNumber().get();
1286 if (registeredUsers
.containsKey(number
)) {
1287 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1288 registeredUsers
.get(number
),
1290 signalServiceAddresses
.add(newAddress
);
1292 signalServiceAddresses
.add(address
);
1296 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1299 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1301 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1303 serviceEnvironmentConfig
.getCdsMrenclave());
1304 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1305 throw new IOException(e
);
1309 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1310 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1311 ) throws IOException
{
1312 final var timestamp
= System
.currentTimeMillis();
1313 messageBuilder
.withTimestamp(timestamp
);
1314 getOrCreateMessagePipe();
1315 getOrCreateUnidentifiedMessagePipe();
1316 SignalServiceDataMessage message
= null;
1318 message
= messageBuilder
.build();
1319 if (message
.getGroupContext().isPresent()) {
1321 var messageSender
= createMessageSender();
1322 final var isRecipientUpdate
= false;
1323 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1324 final var addresses
= recipientIdList
.stream()
1325 .map(this::resolveSignalServiceAddress
)
1326 .collect(Collectors
.toList());
1327 var result
= messageSender
.sendMessage(addresses
,
1328 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1332 for (var r
: result
) {
1333 if (r
.getIdentityFailure() != null) {
1334 account
.getIdentityKeyStore().
1335 saveIdentity(resolveRecipient(r
.getAddress()),
1336 r
.getIdentityFailure().getIdentityKey(),
1341 return new Pair
<>(timestamp
, result
);
1342 } catch (UntrustedIdentityException e
) {
1343 return new Pair
<>(timestamp
, List
.of());
1346 // Send to all individually, so sync messages are sent correctly
1347 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1348 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1349 for (var recipientId
: recipientIds
) {
1350 final var contact
= account
.getContactStore().getContact(recipientId
);
1351 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1352 messageBuilder
.withExpiration(expirationTime
);
1353 message
= messageBuilder
.build();
1354 results
.add(sendMessage(resolveSignalServiceAddress(recipientId
), message
));
1356 return new Pair
<>(timestamp
, results
);
1359 if (message
!= null && message
.isEndSession()) {
1360 for (var recipient
: recipientIds
) {
1361 handleEndSession(recipient
);
1367 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1368 SignalServiceDataMessage
.Builder messageBuilder
1369 ) throws IOException
{
1370 final var timestamp
= System
.currentTimeMillis();
1371 messageBuilder
.withTimestamp(timestamp
);
1372 getOrCreateMessagePipe();
1373 getOrCreateUnidentifiedMessagePipe();
1374 final var recipientId
= account
.getSelfRecipientId();
1376 final var contact
= account
.getContactStore().getContact(recipientId
);
1377 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1378 messageBuilder
.withExpiration(expirationTime
);
1380 var message
= messageBuilder
.build();
1381 final var result
= sendSelfMessage(message
);
1382 return new Pair
<>(timestamp
, result
);
1385 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1386 var messageSender
= createMessageSender();
1388 var recipient
= account
.getSelfAddress();
1390 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(resolveRecipient(recipient
));
1391 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1392 message
.getTimestamp(),
1394 message
.getExpiresInSeconds(),
1395 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1397 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1400 var startTime
= System
.currentTimeMillis();
1401 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1402 return SendMessageResult
.success(recipient
,
1403 unidentifiedAccess
.isPresent(),
1405 System
.currentTimeMillis() - startTime
);
1406 } catch (UntrustedIdentityException e
) {
1407 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1411 private SendMessageResult
sendMessage(
1412 SignalServiceAddress address
, SignalServiceDataMessage message
1413 ) throws IOException
{
1414 var messageSender
= createMessageSender();
1417 return messageSender
.sendMessage(address
,
1418 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(address
)),
1420 } catch (UntrustedIdentityException e
) {
1421 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1425 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1426 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1427 account
.getSignalProtocolStore(),
1428 certificateValidator
);
1430 return cipher
.decrypt(envelope
);
1431 } catch (ProtocolUntrustedIdentityException e
) {
1432 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1433 throw (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1435 throw new AssertionError(e
);
1439 private void handleEndSession(RecipientId recipientId
) {
1440 account
.getSessionStore().deleteAllSessions(recipientId
);
1443 private List
<HandleAction
> handleSignalServiceDataMessage(
1444 SignalServiceDataMessage message
,
1446 SignalServiceAddress source
,
1447 SignalServiceAddress destination
,
1448 boolean ignoreAttachments
1450 var actions
= new ArrayList
<HandleAction
>();
1451 if (message
.getGroupContext().isPresent()) {
1452 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1453 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1454 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1455 var group
= getGroup(groupId
);
1456 if (group
== null || group
instanceof GroupInfoV1
) {
1457 var groupV1
= (GroupInfoV1
) group
;
1458 switch (groupInfo
.getType()) {
1460 if (groupV1
== null) {
1461 groupV1
= new GroupInfoV1(groupId
);
1464 if (groupInfo
.getAvatar().isPresent()) {
1465 var avatar
= groupInfo
.getAvatar().get();
1466 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1469 if (groupInfo
.getName().isPresent()) {
1470 groupV1
.name
= groupInfo
.getName().get();
1473 if (groupInfo
.getMembers().isPresent()) {
1474 groupV1
.addMembers(groupInfo
.getMembers()
1477 .map(this::resolveRecipient
)
1478 .collect(Collectors
.toSet()));
1481 account
.getGroupStore().updateGroup(groupV1
);
1485 if (groupV1
== null && !isSync
) {
1486 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1490 if (groupV1
!= null) {
1491 groupV1
.removeMember(resolveRecipient(source
));
1492 account
.getGroupStore().updateGroup(groupV1
);
1497 if (groupV1
!= null && !isSync
) {
1498 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1503 // Received a group v1 message for a v2 group
1506 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1507 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1508 final var groupMasterKey
= groupContext
.getMasterKey();
1510 getOrMigrateGroup(groupMasterKey
,
1511 groupContext
.getRevision(),
1512 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1516 final var conversationPartnerAddress
= isSync ? destination
: source
;
1517 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1518 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1520 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1521 if (message
.getGroupContext().isPresent()) {
1522 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1523 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1524 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1525 if (group
!= null) {
1526 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1527 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1528 account
.getGroupStore().updateGroup(group
);
1531 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1532 // disappearing message timer already stored in the DecryptedGroup
1534 } else if (conversationPartnerAddress
!= null) {
1535 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1538 if (!ignoreAttachments
) {
1539 if (message
.getAttachments().isPresent()) {
1540 for (var attachment
: message
.getAttachments().get()) {
1541 downloadAttachment(attachment
);
1544 if (message
.getSharedContacts().isPresent()) {
1545 for (var contact
: message
.getSharedContacts().get()) {
1546 if (contact
.getAvatar().isPresent()) {
1547 downloadAttachment(contact
.getAvatar().get().getAttachment());
1552 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1553 final ProfileKey profileKey
;
1555 profileKey
= new ProfileKey(message
.getProfileKey().get());
1556 } catch (InvalidInputException e
) {
1557 throw new AssertionError(e
);
1559 if (source
.matches(account
.getSelfAddress())) {
1560 this.account
.setProfileKey(profileKey
);
1562 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1564 if (message
.getPreviews().isPresent()) {
1565 final var previews
= message
.getPreviews().get();
1566 for (var preview
: previews
) {
1567 if (preview
.getImage().isPresent()) {
1568 downloadAttachment(preview
.getImage().get());
1572 if (message
.getQuote().isPresent()) {
1573 final var quote
= message
.getQuote().get();
1575 for (var quotedAttachment
: quote
.getAttachments()) {
1576 final var thumbnail
= quotedAttachment
.getThumbnail();
1577 if (thumbnail
!= null) {
1578 downloadAttachment(thumbnail
);
1582 if (message
.getSticker().isPresent()) {
1583 final var messageSticker
= message
.getSticker().get();
1584 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1585 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1586 if (sticker
== null) {
1587 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1588 account
.getStickerStore().updateSticker(sticker
);
1594 private GroupInfoV2
getOrMigrateGroup(
1595 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1597 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1599 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1600 var groupInfo
= getGroup(groupId
);
1601 final GroupInfoV2 groupInfoV2
;
1602 if (groupInfo
instanceof GroupInfoV1
) {
1603 // Received a v2 group message for a v1 group, we need to locally migrate the group
1604 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1605 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1606 logger
.info("Locally migrated group {} to group v2, id: {}",
1607 groupInfo
.getGroupId().toBase64(),
1608 groupInfoV2
.getGroupId().toBase64());
1609 } else if (groupInfo
instanceof GroupInfoV2
) {
1610 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1612 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1615 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1616 DecryptedGroup group
= null;
1617 if (signedGroupChange
!= null
1618 && groupInfoV2
.getGroup() != null
1619 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1620 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1622 if (group
== null) {
1623 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1625 if (group
!= null) {
1626 storeProfileKeysFromMembers(group
);
1627 final var avatar
= group
.getAvatar();
1628 if (avatar
!= null && !avatar
.isEmpty()) {
1629 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1632 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1633 account
.getGroupStore().updateGroup(groupInfoV2
);
1639 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1640 for (var member
: group
.getMembersList()) {
1641 final var address
= resolveRecipient(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1642 .toByteArray()), null));
1644 account
.getProfileStore()
1645 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1646 } catch (InvalidInputException ignored
) {
1651 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1652 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1653 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1654 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1655 if (actions
!= null) {
1656 queuedActions
.addAll(actions
);
1659 for (var action
: queuedActions
) {
1661 action
.execute(this);
1662 } catch (Throwable e
) {
1663 logger
.warn("Message action failed.", e
);
1668 private List
<HandleAction
> retryFailedReceivedMessage(
1669 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1671 var envelope
= cachedMessage
.loadEnvelope();
1672 if (envelope
== null) {
1675 SignalServiceContent content
= null;
1676 List
<HandleAction
> actions
= null;
1677 if (!envelope
.isReceipt()) {
1679 content
= decryptMessage(envelope
);
1680 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1681 if (!envelope
.hasSource()) {
1682 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
)
1685 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1686 } catch (IOException ioException
) {
1687 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1691 } catch (Exception er
) {
1692 // All other errors are not recoverable, so delete the cached message
1693 cachedMessage
.delete();
1696 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1698 handler
.handleMessage(envelope
, content
, null);
1699 cachedMessage
.delete();
1703 public void receiveMessages(
1706 boolean returnOnTimeout
,
1707 boolean ignoreAttachments
,
1708 ReceiveMessageHandler handler
1709 ) throws IOException
{
1710 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1712 Set
<HandleAction
> queuedActions
= null;
1714 final var messagePipe
= getOrCreateMessagePipe();
1716 var hasCaughtUpWithOldMessages
= false;
1719 SignalServiceEnvelope envelope
;
1720 SignalServiceContent content
= null;
1721 Exception exception
= null;
1722 final CachedMessage
[] cachedMessage
= {null};
1724 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1725 final var recipientId
= envelope1
.hasSource()
1726 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1728 // store message on disk, before acknowledging receipt to the server
1729 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1731 if (result
.isPresent()) {
1732 envelope
= result
.get();
1734 // Received indicator that server queue is empty
1735 hasCaughtUpWithOldMessages
= true;
1737 if (queuedActions
!= null) {
1738 for (var action
: queuedActions
) {
1740 action
.execute(this);
1741 } catch (Throwable e
) {
1742 logger
.warn("Message action failed.", e
);
1745 queuedActions
.clear();
1746 queuedActions
= null;
1749 // Continue to wait another timeout for new messages
1752 } catch (TimeoutException e
) {
1753 if (returnOnTimeout
) return;
1757 if (envelope
.hasSource()) {
1758 // Store uuid if we don't have it already
1759 resolveRecipientTrusted(envelope
.getSourceAddress());
1761 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1762 if (!envelope
.isReceipt()) {
1764 content
= decryptMessage(envelope
);
1765 } catch (Exception e
) {
1768 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1769 if (hasCaughtUpWithOldMessages
) {
1770 for (var action
: actions
) {
1772 action
.execute(this);
1773 } catch (Throwable e
) {
1774 logger
.warn("Message action failed.", e
);
1778 if (queuedActions
== null) {
1779 queuedActions
= new HashSet
<>();
1781 queuedActions
.addAll(actions
);
1784 if (isMessageBlocked(envelope
, content
)) {
1785 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1786 } else if (notAGroupMember
) {
1787 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1789 handler
.handleMessage(envelope
, content
, exception
);
1791 if (cachedMessage
[0] != null) {
1792 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1793 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
)
1795 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1796 if (!envelope
.hasSource()) {
1798 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1799 } catch (IOException ioException
) {
1800 logger
.warn("Failed to move cached message to recipient folder: {}",
1801 ioException
.getMessage());
1805 cachedMessage
[0].delete();
1811 private boolean isMessageBlocked(
1812 SignalServiceEnvelope envelope
, SignalServiceContent content
1814 SignalServiceAddress source
;
1815 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1816 source
= envelope
.getSourceAddress();
1817 } else if (content
!= null) {
1818 source
= content
.getSender();
1822 final var recipientId
= resolveRecipient(source
);
1823 if (isContactBlocked(recipientId
)) {
1827 if (content
!= null && content
.getDataMessage().isPresent()) {
1828 var message
= content
.getDataMessage().get();
1829 if (message
.getGroupContext().isPresent()) {
1830 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1831 var group
= getGroup(groupId
);
1832 if (group
!= null && group
.isBlocked()) {
1840 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
1841 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
1842 return isContactBlocked(recipientId
);
1845 private boolean isContactBlocked(final RecipientId recipientId
) {
1846 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1847 return sourceContact
!= null && sourceContact
.isBlocked();
1850 private boolean isNotAGroupMember(
1851 SignalServiceEnvelope envelope
, SignalServiceContent content
1853 SignalServiceAddress source
;
1854 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1855 source
= envelope
.getSourceAddress();
1856 } else if (content
!= null) {
1857 source
= content
.getSender();
1862 if (content
!= null && content
.getDataMessage().isPresent()) {
1863 var message
= content
.getDataMessage().get();
1864 if (message
.getGroupContext().isPresent()) {
1865 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1866 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1867 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1871 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1872 var group
= getGroup(groupId
);
1873 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
1881 private List
<HandleAction
> handleMessage(
1882 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1884 var actions
= new ArrayList
<HandleAction
>();
1885 if (content
!= null) {
1886 final SignalServiceAddress sender
;
1887 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1888 sender
= envelope
.getSourceAddress();
1890 sender
= content
.getSender();
1893 if (content
.getDataMessage().isPresent()) {
1894 var message
= content
.getDataMessage().get();
1896 if (content
.isNeedsReceipt()) {
1897 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1900 actions
.addAll(handleSignalServiceDataMessage(message
,
1903 account
.getSelfAddress(),
1904 ignoreAttachments
));
1906 if (content
.getSyncMessage().isPresent()) {
1907 account
.setMultiDevice(true);
1908 var syncMessage
= content
.getSyncMessage().get();
1909 if (syncMessage
.getSent().isPresent()) {
1910 var message
= syncMessage
.getSent().get();
1911 final var destination
= message
.getDestination().orNull();
1912 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1916 ignoreAttachments
));
1918 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
1919 var rm
= syncMessage
.getRequest().get();
1920 if (rm
.isContactsRequest()) {
1921 actions
.add(SendSyncContactsAction
.create());
1923 if (rm
.isGroupsRequest()) {
1924 actions
.add(SendSyncGroupsAction
.create());
1926 if (rm
.isBlockedListRequest()) {
1927 actions
.add(SendSyncBlockedListAction
.create());
1929 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1931 if (syncMessage
.getGroups().isPresent()) {
1932 File tmpFile
= null;
1934 tmpFile
= IOUtils
.createTempFile();
1935 final var groupsMessage
= syncMessage
.getGroups().get();
1936 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1937 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1939 while ((g
= s
.read()) != null) {
1940 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1941 if (syncGroup
!= null) {
1942 if (g
.getName().isPresent()) {
1943 syncGroup
.name
= g
.getName().get();
1945 syncGroup
.addMembers(g
.getMembers()
1947 .map(this::resolveRecipient
)
1948 .collect(Collectors
.toSet()));
1949 if (!g
.isActive()) {
1950 syncGroup
.removeMember(account
.getSelfRecipientId());
1952 // Add ourself to the member set as it's marked as active
1953 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
1955 syncGroup
.blocked
= g
.isBlocked();
1956 if (g
.getColor().isPresent()) {
1957 syncGroup
.color
= g
.getColor().get();
1960 if (g
.getAvatar().isPresent()) {
1961 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1963 syncGroup
.archived
= g
.isArchived();
1964 account
.getGroupStore().updateGroup(syncGroup
);
1968 } catch (Exception e
) {
1969 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1973 if (tmpFile
!= null) {
1975 Files
.delete(tmpFile
.toPath());
1976 } catch (IOException e
) {
1977 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1984 if (syncMessage
.getBlockedList().isPresent()) {
1985 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1986 for (var address
: blockedListMessage
.getAddresses()) {
1987 setContactBlocked(resolveRecipient(address
), true);
1989 for (var groupId
: blockedListMessage
.getGroupIds()
1991 .map(GroupId
::unknownVersion
)
1992 .collect(Collectors
.toSet())) {
1994 setGroupBlocked(groupId
, true);
1995 } catch (GroupNotFoundException e
) {
1996 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1997 groupId
.toBase64());
2001 if (syncMessage
.getContacts().isPresent()) {
2002 File tmpFile
= null;
2004 tmpFile
= IOUtils
.createTempFile();
2005 final var contactsMessage
= syncMessage
.getContacts().get();
2006 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2007 .asPointer(), tmpFile
)) {
2008 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2010 while ((c
= s
.read()) != null) {
2011 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2012 account
.setProfileKey(c
.getProfileKey().get());
2014 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2015 var contact
= account
.getContactStore().getContact(recipientId
);
2016 final var builder
= contact
== null
2017 ? Contact
.newBuilder()
2018 : Contact
.newBuilder(contact
);
2019 if (c
.getName().isPresent()) {
2020 builder
.withName(c
.getName().get());
2022 if (c
.getColor().isPresent()) {
2023 builder
.withColor(c
.getColor().get());
2025 if (c
.getProfileKey().isPresent()) {
2026 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2028 if (c
.getVerified().isPresent()) {
2029 final var verifiedMessage
= c
.getVerified().get();
2030 account
.getIdentityKeyStore()
2031 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2032 verifiedMessage
.getIdentityKey(),
2033 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2035 if (c
.getExpirationTimer().isPresent()) {
2036 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2038 builder
.withBlocked(c
.isBlocked());
2039 builder
.withArchived(c
.isArchived());
2040 account
.getContactStore().storeContact(recipientId
, builder
.build());
2042 if (c
.getAvatar().isPresent()) {
2043 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2047 } catch (Exception e
) {
2048 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2052 if (tmpFile
!= null) {
2054 Files
.delete(tmpFile
.toPath());
2055 } catch (IOException e
) {
2056 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2063 if (syncMessage
.getVerified().isPresent()) {
2064 final var verifiedMessage
= syncMessage
.getVerified().get();
2065 account
.getIdentityKeyStore()
2066 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2067 verifiedMessage
.getIdentityKey(),
2068 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2070 if (syncMessage
.getStickerPackOperations().isPresent()) {
2071 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2072 for (var m
: stickerPackOperationMessages
) {
2073 if (!m
.getPackId().isPresent()) {
2076 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2077 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2078 if (sticker
== null) {
2079 if (!m
.getPackKey().isPresent()) {
2082 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2084 sticker
.setInstalled(!m
.getType().isPresent()
2085 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2086 account
.getStickerStore().updateSticker(sticker
);
2089 if (syncMessage
.getFetchType().isPresent()) {
2090 switch (syncMessage
.getFetchType().get()) {
2092 getRecipientProfile(account
.getSelfRecipientId(), true);
2093 case STORAGE_MANIFEST
:
2097 if (syncMessage
.getKeys().isPresent()) {
2098 final var keysMessage
= syncMessage
.getKeys().get();
2099 if (keysMessage
.getStorageService().isPresent()) {
2100 final var storageKey
= keysMessage
.getStorageService().get();
2101 account
.setStorageKey(storageKey
);
2104 if (syncMessage
.getConfiguration().isPresent()) {
2112 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2114 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2115 } catch (IOException e
) {
2116 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2120 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2122 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2123 } catch (IOException e
) {
2124 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2128 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2130 avatarStore
.storeGroupAvatar(groupId
,
2131 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2132 } catch (IOException e
) {
2133 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2137 private void downloadProfileAvatar(
2138 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2141 avatarStore
.storeProfileAvatar(address
,
2142 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2143 } catch (Throwable e
) {
2144 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2148 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2149 return attachmentStore
.getAttachmentFile(attachmentId
);
2152 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2153 if (!attachment
.isPointer()) {
2154 logger
.warn("Invalid state, can't store an attachment stream.");
2157 var pointer
= attachment
.asPointer();
2158 if (pointer
.getPreview().isPresent()) {
2159 final var preview
= pointer
.getPreview().get();
2161 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2162 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2163 } catch (IOException e
) {
2164 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2169 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2170 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2171 } catch (IOException e
) {
2172 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2176 private void retrieveGroupV2Avatar(
2177 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2178 ) throws IOException
{
2179 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2181 var tmpFile
= IOUtils
.createTempFile();
2182 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2184 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2185 var encryptedData
= IOUtils
.readFully(input
);
2187 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2188 outputStream
.write(decryptedData
);
2191 Files
.delete(tmpFile
.toPath());
2192 } catch (IOException e
) {
2193 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2200 private void retrieveProfileAvatar(
2201 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2202 ) throws IOException
{
2203 var tmpFile
= IOUtils
.createTempFile();
2204 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2207 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2208 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2209 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2212 Files
.delete(tmpFile
.toPath());
2213 } catch (IOException e
) {
2214 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2221 private void retrieveAttachment(
2222 final SignalServiceAttachment attachment
, final OutputStream outputStream
2223 ) throws IOException
{
2224 if (attachment
.isPointer()) {
2225 var pointer
= attachment
.asPointer();
2226 retrieveAttachmentPointer(pointer
, outputStream
);
2228 var stream
= attachment
.asStream();
2229 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2233 private void retrieveAttachmentPointer(
2234 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2235 ) throws IOException
{
2236 var tmpFile
= IOUtils
.createTempFile();
2237 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2238 IOUtils
.copyStream(input
, outputStream
);
2239 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2240 throw new IOException(e
);
2243 Files
.delete(tmpFile
.toPath());
2244 } catch (IOException e
) {
2245 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2252 private InputStream
retrieveAttachmentAsStream(
2253 SignalServiceAttachmentPointer pointer
, File tmpFile
2254 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2255 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2258 void sendGroups() throws IOException
, UntrustedIdentityException
{
2259 var groupsFile
= IOUtils
.createTempFile();
2262 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2263 var out
= new DeviceGroupsOutputStream(fos
);
2264 for (var record : getGroups()) {
2265 if (record instanceof GroupInfoV1
) {
2266 var groupInfo
= (GroupInfoV1
) record;
2267 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2268 Optional
.fromNullable(groupInfo
.name
),
2269 groupInfo
.getMembers()
2271 .map(this::resolveSignalServiceAddress
)
2272 .collect(Collectors
.toList()),
2273 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2274 groupInfo
.isMember(account
.getSelfRecipientId()),
2275 Optional
.of(groupInfo
.messageExpirationTime
),
2276 Optional
.fromNullable(groupInfo
.color
),
2279 groupInfo
.archived
));
2284 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2285 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2286 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2287 .withStream(groupsFileStream
)
2288 .withContentType("application/octet-stream")
2289 .withLength(groupsFile
.length())
2292 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2297 Files
.delete(groupsFile
.toPath());
2298 } catch (IOException e
) {
2299 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2304 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2305 var contactsFile
= IOUtils
.createTempFile();
2308 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2309 var out
= new DeviceContactsOutputStream(fos
);
2310 for (var contactPair
: account
.getContactStore().getContacts()) {
2311 final var recipientId
= contactPair
.first();
2312 final var contact
= contactPair
.second();
2313 final var address
= resolveSignalServiceAddress(recipientId
);
2315 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2316 VerifiedMessage verifiedMessage
= null;
2317 if (currentIdentity
!= null) {
2318 verifiedMessage
= new VerifiedMessage(address
,
2319 currentIdentity
.getIdentityKey(),
2320 currentIdentity
.getTrustLevel().toVerifiedState(),
2321 currentIdentity
.getDateAdded().getTime());
2324 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2325 out
.write(new DeviceContact(address
,
2326 Optional
.fromNullable(contact
.getName()),
2327 createContactAvatarAttachment(address
),
2328 Optional
.fromNullable(contact
.getColor()),
2329 Optional
.fromNullable(verifiedMessage
),
2330 Optional
.fromNullable(profileKey
),
2331 contact
.isBlocked(),
2332 Optional
.of(contact
.getMessageExpirationTime()),
2334 contact
.isArchived()));
2337 if (account
.getProfileKey() != null) {
2338 // Send our own profile key as well
2339 out
.write(new DeviceContact(account
.getSelfAddress(),
2344 Optional
.of(account
.getProfileKey()),
2352 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2353 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2354 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2355 .withStream(contactsFileStream
)
2356 .withContentType("application/octet-stream")
2357 .withLength(contactsFile
.length())
2360 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2365 Files
.delete(contactsFile
.toPath());
2366 } catch (IOException e
) {
2367 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2372 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2373 var addresses
= new ArrayList
<SignalServiceAddress
>();
2374 for (var record : account
.getContactStore().getContacts()) {
2375 if (record.second().isBlocked()) {
2376 addresses
.add(resolveSignalServiceAddress(record.first()));
2379 var groupIds
= new ArrayList
<byte[]>();
2380 for (var record : getGroups()) {
2381 if (record.isBlocked()) {
2382 groupIds
.add(record.getGroupId().serialize());
2385 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2388 private void sendVerifiedMessage(
2389 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2390 ) throws IOException
, UntrustedIdentityException
{
2391 var verifiedMessage
= new VerifiedMessage(destination
,
2393 trustLevel
.toVerifiedState(),
2394 System
.currentTimeMillis());
2395 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2398 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2399 return account
.getContactStore().getContacts();
2402 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2403 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2404 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2405 if (recipient
== null) {
2409 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2410 return recipient
.getContact().getName();
2413 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2414 return recipient
.getProfile().getDisplayName();
2420 public GroupInfo
getGroup(GroupId groupId
) {
2421 final var group
= account
.getGroupStore().getGroup(groupId
);
2422 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2423 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2424 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2425 account
.getGroupStore().updateGroup(group
);
2430 public List
<IdentityInfo
> getIdentities() {
2431 return account
.getIdentityKeyStore().getIdentities();
2434 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2435 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2436 return identity
== null ? List
.of() : List
.of(identity
);
2440 * Trust this the identity with this fingerprint
2442 * @param name username of the identity
2443 * @param fingerprint Fingerprint
2445 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2446 var recipientId
= canonicalizeAndResolveRecipient(name
);
2447 return trustIdentity(recipientId
,
2448 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2449 TrustLevel
.TRUSTED_VERIFIED
);
2453 * Trust this the identity with this safety number
2455 * @param name username of the identity
2456 * @param safetyNumber Safety number
2458 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2459 var recipientId
= canonicalizeAndResolveRecipient(name
);
2460 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2461 return trustIdentity(recipientId
,
2462 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2463 TrustLevel
.TRUSTED_VERIFIED
);
2467 * Trust all keys of this identity without verification
2469 * @param name username of the identity
2471 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2472 var recipientId
= canonicalizeAndResolveRecipient(name
);
2473 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2476 private boolean trustIdentity(
2477 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2479 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2480 if (identity
== null) {
2484 if (!verifier
.apply(identity
.getIdentityKey())) {
2488 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2490 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2491 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2492 } catch (IOException
| UntrustedIdentityException e
) {
2493 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2499 public String
computeSafetyNumber(
2500 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2502 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2503 account
.getSelfAddress(),
2504 getIdentityKeyPair().getPublicKey(),
2510 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2511 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2513 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2514 return resolveSignalServiceAddress(canonicalizedNumber
);
2518 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2519 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2521 return resolveSignalServiceAddress(address
);
2525 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2526 if (address
.matches(account
.getSelfAddress())) {
2527 return account
.getSelfAddress();
2530 return account
.getRecipientStore().resolveServiceAddress(address
);
2533 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2534 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2537 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2538 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2540 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2542 return resolveRecipient(canonicalizedNumber
);
2545 private RecipientId
resolveRecipient(final String identifier
) {
2546 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2548 return resolveRecipient(address
);
2551 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2552 return account
.getRecipientStore().resolveRecipient(address
);
2555 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2556 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2560 public void close() throws IOException
{
2564 void close(boolean closeAccount
) throws IOException
{
2565 executor
.shutdown();
2567 if (messagePipe
!= null) {
2568 messagePipe
.shutdown();
2572 if (unidentifiedMessagePipe
!= null) {
2573 unidentifiedMessagePipe
.shutdown();
2574 unidentifiedMessagePipe
= null;
2577 if (closeAccount
&& account
!= null) {
2583 public interface ReceiveMessageHandler
{
2585 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);