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
.push
.exceptions
.UnregisteredUserException
;
122 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
123 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
124 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
125 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
126 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
127 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
128 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
129 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
130 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
131 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
132 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
133 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
134 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
136 import java
.io
.Closeable
;
138 import java
.io
.FileInputStream
;
139 import java
.io
.FileOutputStream
;
140 import java
.io
.IOException
;
141 import java
.io
.InputStream
;
142 import java
.io
.OutputStream
;
144 import java
.net
.URISyntaxException
;
145 import java
.net
.URLEncoder
;
146 import java
.nio
.charset
.StandardCharsets
;
147 import java
.nio
.file
.Files
;
148 import java
.security
.SignatureException
;
149 import java
.util
.ArrayList
;
150 import java
.util
.Arrays
;
151 import java
.util
.Base64
;
152 import java
.util
.Collection
;
153 import java
.util
.Date
;
154 import java
.util
.HashSet
;
155 import java
.util
.List
;
156 import java
.util
.Map
;
157 import java
.util
.Set
;
158 import java
.util
.UUID
;
159 import java
.util
.concurrent
.ExecutorService
;
160 import java
.util
.concurrent
.Executors
;
161 import java
.util
.concurrent
.TimeUnit
;
162 import java
.util
.concurrent
.TimeoutException
;
163 import java
.util
.function
.Function
;
164 import java
.util
.stream
.Collectors
;
166 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
168 public class Manager
implements Closeable
{
170 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
172 private final CertificateValidator certificateValidator
;
174 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
175 private final String userAgent
;
177 private SignalAccount account
;
178 private final SignalServiceAccountManager accountManager
;
179 private final GroupsV2Api groupsV2Api
;
180 private final GroupsV2Operations groupsV2Operations
;
181 private final SignalServiceMessageReceiver messageReceiver
;
182 private final ClientZkProfileOperations clientZkProfileOperations
;
184 private final ExecutorService executor
= Executors
.newCachedThreadPool();
186 private SignalServiceMessagePipe messagePipe
= null;
187 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
189 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
190 private final ProfileHelper profileHelper
;
191 private final GroupHelper groupHelper
;
192 private final PinHelper pinHelper
;
193 private final AvatarStore avatarStore
;
194 private final AttachmentStore attachmentStore
;
197 SignalAccount account
,
198 PathConfig pathConfig
,
199 ServiceEnvironmentConfig serviceEnvironmentConfig
,
202 this.account
= account
;
203 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
204 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
205 this.userAgent
= userAgent
;
206 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
207 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
208 final SleepTimer timer
= new UptimeSleepTimer();
209 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
210 new DynamicCredentialsProvider(account
.getUuid(),
211 account
.getUsername(),
212 account
.getPassword(),
213 account
.getDeviceId()),
216 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
218 this.groupsV2Api
= accountManager
.getGroupsV2Api();
219 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
220 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
221 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
222 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
225 this.pinHelper
= new PinHelper(keyBackupService
);
226 this.clientZkProfileOperations
= capabilities
.isGv2()
227 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
228 .getProfileOperations()
230 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
232 account
.getUsername(),
233 account
.getPassword(),
234 account
.getDeviceId(),
238 clientZkProfileOperations
,
239 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
241 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
242 account
.getProfileStore()::getProfileKey
,
243 this::getRecipientProfile
,
244 this::getSenderCertificate
);
245 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
246 unidentifiedAccessHelper
::getAccessFor
,
247 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
248 () -> messageReceiver
,
249 this::resolveSignalServiceAddress
);
250 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
251 this::getRecipientProfile
,
252 account
::getSelfRecipientId
,
255 this::getGroupAuthForToday
,
256 this::resolveSignalServiceAddress
);
257 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
258 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
261 public String
getUsername() {
262 return account
.getUsername();
265 public SignalServiceAddress
getSelfAddress() {
266 return account
.getSelfAddress();
269 public RecipientId
getSelfRecipientId() {
270 return account
.getSelfRecipientId();
273 private IdentityKeyPair
getIdentityKeyPair() {
274 return account
.getIdentityKeyPair();
277 public int getDeviceId() {
278 return account
.getDeviceId();
281 public static Manager
init(
282 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
283 ) throws IOException
, NotRegisteredException
{
284 var pathConfig
= PathConfig
.createDefault(settingsPath
);
286 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
287 throw new NotRegisteredException();
290 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
292 if (!account
.isRegistered()) {
293 throw new NotRegisteredException();
296 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
298 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
301 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
302 var pathConfig
= PathConfig
.createDefault(settingsPath
);
303 final var dataPath
= pathConfig
.getDataPath();
304 final var files
= dataPath
.listFiles();
310 return Arrays
.stream(files
)
311 .filter(File
::isFile
)
313 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
314 .collect(Collectors
.toList());
317 public void checkAccountState() throws IOException
{
318 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
321 if (account
.getUuid() == null) {
322 account
.setUuid(accountManager
.getOwnUuid());
324 updateAccountAttributes();
328 * This is used for checking a set of phone numbers for registration on Signal
330 * @param numbers The set of phone number in question
331 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
332 * @throws IOException if its unable to get the contacts to check if they're registered
334 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
335 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
336 var contactDetails
= getRegisteredUsers(numbers
);
338 var registeredUsers
= contactDetails
.keySet();
340 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
343 public void updateAccountAttributes() throws IOException
{
344 accountManager
.setAccountAttributes(null,
345 account
.getLocalRegistrationId(),
347 // set legacy pin only if no KBS master key is set
348 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
349 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
350 account
.getSelfUnidentifiedAccessKey(),
351 account
.isUnrestrictedUnidentifiedAccess(),
353 account
.isDiscoverableByPhoneNumber());
357 * @param name if null, the previous name will be kept
358 * @param about if null, the previous about text will be kept
359 * @param aboutEmoji if null, the previous about emoji will be kept
360 * @param avatar if avatar is null the image from the local avatar store is used (if present),
361 * if it's Optional.absent(), the avatar will be removed
363 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
364 var profile
= getRecipientProfile(account
.getSelfRecipientId());
365 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
367 builder
.withGivenName(name
);
368 builder
.withFamilyName(null);
371 builder
.withAbout(about
);
373 if (aboutEmoji
!= null) {
374 builder
.withAboutEmoji(aboutEmoji
);
376 var newProfile
= builder
.build();
378 try (final var streamDetails
= avatar
== null
379 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
380 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
381 accountManager
.setVersionedProfile(account
.getUuid(),
382 account
.getProfileKey(),
383 newProfile
.getInternalServiceName(),
384 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
385 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
389 if (avatar
!= null) {
390 if (avatar
.isPresent()) {
391 avatarStore
.storeProfileAvatar(getSelfAddress(),
392 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
394 avatarStore
.deleteProfileAvatar(getSelfAddress());
397 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
400 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
401 } catch (UntrustedIdentityException ignored
) {
405 public void unregister() throws IOException
{
406 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
407 // If this is the master device, other users can't send messages to this number anymore.
408 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
409 accountManager
.setGcmId(Optional
.absent());
411 account
.setRegistered(false);
414 public void deleteAccount() throws IOException
{
415 accountManager
.deleteAccount();
417 account
.setRegistered(false);
420 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
421 var devices
= accountManager
.getDevices();
422 account
.setMultiDevice(devices
.size() > 1);
426 public void removeLinkedDevices(int deviceId
) throws IOException
{
427 accountManager
.removeDevice(deviceId
);
428 var devices
= accountManager
.getDevices();
429 account
.setMultiDevice(devices
.size() > 1);
432 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
433 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
435 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
438 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
439 var identityKeyPair
= getIdentityKeyPair();
440 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
442 accountManager
.addDevice(deviceIdentifier
,
445 Optional
.of(account
.getProfileKey().serialize()),
447 account
.setMultiDevice(true);
450 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
451 if (!account
.isMasterDevice()) {
452 throw new RuntimeException("Only master device can set a PIN");
454 if (pin
.isPresent()) {
455 final var masterKey
= account
.getPinMasterKey() != null
456 ? account
.getPinMasterKey()
457 : KeyUtils
.createMasterKey();
459 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
461 account
.setRegistrationLockPin(pin
.get(), masterKey
);
463 // Remove legacy registration lock
464 accountManager
.removeRegistrationLockV1();
467 pinHelper
.removeRegistrationLockPin();
469 account
.setRegistrationLockPin(null, null);
473 void refreshPreKeys() throws IOException
{
474 var oneTimePreKeys
= generatePreKeys();
475 final var identityKeyPair
= getIdentityKeyPair();
476 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
478 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
481 private List
<PreKeyRecord
> generatePreKeys() {
482 final var offset
= account
.getPreKeyIdOffset();
484 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
485 account
.addPreKeys(records
);
490 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
491 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
493 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
494 account
.addSignedPreKey(record);
499 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
500 if (messagePipe
== null) {
501 messagePipe
= messageReceiver
.createMessagePipe();
506 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
507 if (unidentifiedMessagePipe
== null) {
508 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
510 return unidentifiedMessagePipe
;
513 private SignalServiceMessageSender
createMessageSender() {
514 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
516 account
.getUsername(),
517 account
.getPassword(),
518 account
.getDeviceId(),
519 account
.getSignalProtocolStore(),
521 account
.isMultiDevice(),
522 Optional
.fromNullable(messagePipe
),
523 Optional
.fromNullable(unidentifiedMessagePipe
),
525 clientZkProfileOperations
,
527 ServiceConfig
.MAX_ENVELOPE_SIZE
,
528 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
531 public Profile
getRecipientProfile(
532 SignalServiceAddress address
534 return getRecipientProfile(resolveRecipient(address
), false);
537 public Profile
getRecipientProfile(
538 RecipientId recipientId
540 return getRecipientProfile(recipientId
, false);
543 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
545 Profile
getRecipientProfile(
546 RecipientId recipientId
, boolean force
548 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
549 if (profileKey
== null) {
551 // retrieve profile to get identity key
552 retrieveEncryptedProfile(recipientId
);
556 var profile
= account
.getProfileStore().getProfile(recipientId
);
558 var now
= new Date().getTime();
559 // Profiles are cached for 24h before retrieving them again, unless forced
560 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
564 synchronized (pendingProfileRequest
) {
565 if (pendingProfileRequest
.contains(recipientId
)) {
568 pendingProfileRequest
.add(recipientId
);
570 final SignalServiceProfile encryptedProfile
;
572 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
574 synchronized (pendingProfileRequest
) {
575 pendingProfileRequest
.remove(recipientId
);
578 if (encryptedProfile
== null) {
582 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
583 account
.getProfileStore().storeProfile(recipientId
, profile
);
588 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
590 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
591 } catch (IOException e
) {
592 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
597 private ProfileAndCredential
retrieveProfileAndCredential(
598 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
599 ) throws IOException
{
600 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
601 final var profile
= profileAndCredential
.getProfile();
604 account
.getIdentityKeyStore()
605 .saveIdentity(recipientId
,
606 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
608 } catch (InvalidKeyException ignored
) {
609 logger
.warn("Got invalid identity key in profile for {}",
610 resolveSignalServiceAddress(recipientId
).getLegacyIdentifier());
612 return profileAndCredential
;
615 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
616 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
617 if (profileKeyCredential
!= null) {
618 return profileKeyCredential
;
621 ProfileAndCredential profileAndCredential
;
623 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
624 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
625 } catch (IOException e
) {
626 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
630 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
631 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
633 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
634 if (profileKey
!= null) {
635 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
637 profileAndCredential
.getProfile());
638 account
.getProfileStore().storeProfile(recipientId
, profile
);
641 return profileKeyCredential
;
644 private Profile
decryptProfileAndDownloadAvatar(
645 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
647 if (encryptedProfile
.getAvatar() != null) {
648 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
651 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
654 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
655 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
656 if (streamDetails
== null) {
657 return Optional
.absent();
660 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
663 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
664 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
665 if (streamDetails
== null) {
666 return Optional
.absent();
669 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
672 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
673 var g
= getGroup(groupId
);
675 throw new GroupNotFoundException(groupId
);
677 if (!g
.isMember(account
.getSelfRecipientId())) {
678 throw new NotAGroupMemberException(groupId
, g
.getTitle());
683 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
684 var g
= getGroup(groupId
);
686 throw new GroupNotFoundException(groupId
);
688 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
689 throw new NotAGroupMemberException(groupId
, g
.getTitle());
694 public List
<GroupInfo
> getGroups() {
695 return account
.getGroupStore().getGroups();
698 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
699 String messageText
, List
<String
> attachments
, GroupId groupId
700 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
701 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
702 if (attachments
!= null) {
703 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
706 return sendGroupMessage(messageBuilder
, groupId
);
709 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
710 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
711 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
712 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
714 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
715 targetSentTimestamp
);
716 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
718 return sendGroupMessage(messageBuilder
, groupId
);
721 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
722 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
723 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
724 final var g
= getGroupForSending(groupId
);
726 GroupUtils
.setGroupContext(messageBuilder
, g
);
727 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
729 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
732 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
733 SignalServiceDataMessage
.Builder messageBuilder
;
735 final var g
= getGroupForUpdating(groupId
);
736 if (g
instanceof GroupInfoV1
) {
737 var groupInfoV1
= (GroupInfoV1
) g
;
738 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
739 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
740 groupInfoV1
.removeMember(account
.getSelfRecipientId());
741 account
.getGroupStore().updateGroup(groupInfoV1
);
743 final var groupInfoV2
= (GroupInfoV2
) g
;
744 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
745 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
746 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
747 account
.getGroupStore().updateGroup(groupInfoV2
);
750 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
753 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
754 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
755 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
756 return sendUpdateGroupMessage(groupId
,
758 members
== null ?
null : getSignalServiceAddresses(members
),
762 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
763 GroupId groupId
, String name
, Set
<RecipientId
> members
, File avatarFile
764 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
766 SignalServiceDataMessage
.Builder messageBuilder
;
767 if (groupId
== null) {
769 var gv2Pair
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
770 members
== null ? Set
.of() : members
,
772 if (gv2Pair
== null) {
773 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
774 gv1
.addMembers(List
.of(account
.getSelfRecipientId()));
775 updateGroupV1(gv1
, name
, members
, avatarFile
);
776 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
779 final var gv2
= gv2Pair
.first();
780 final var decryptedGroup
= gv2Pair
.second();
782 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
783 if (avatarFile
!= null) {
784 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
785 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
787 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
791 var group
= getGroupForUpdating(groupId
);
792 if (group
instanceof GroupInfoV2
) {
793 final var groupInfoV2
= (GroupInfoV2
) group
;
795 Pair
<Long
, List
<SendMessageResult
>> result
= null;
796 if (groupInfoV2
.isPendingMember(account
.getSelfRecipientId())) {
797 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
798 result
= sendUpdateGroupMessage(groupInfoV2
,
799 groupGroupChangePair
.first(),
800 groupGroupChangePair
.second());
803 if (members
!= null) {
804 final var newMembers
= new HashSet
<>(members
);
805 newMembers
.removeAll(group
.getMembers());
806 if (newMembers
.size() > 0) {
807 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
808 result
= sendUpdateGroupMessage(groupInfoV2
,
809 groupGroupChangePair
.first(),
810 groupGroupChangePair
.second());
813 if (result
== null || name
!= null || avatarFile
!= null) {
814 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
815 if (avatarFile
!= null) {
816 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
817 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
819 result
= sendUpdateGroupMessage(groupInfoV2
,
820 groupGroupChangePair
.first(),
821 groupGroupChangePair
.second());
824 return new Pair
<>(group
.getGroupId(), result
.second());
826 var gv1
= (GroupInfoV1
) group
;
827 updateGroupV1(gv1
, name
, members
, avatarFile
);
828 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
833 account
.getGroupStore().updateGroup(g
);
835 final var result
= sendMessage(messageBuilder
,
836 g
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
837 return new Pair
<>(g
.getGroupId(), result
.second());
840 private void updateGroupV1(
841 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
842 ) throws IOException
{
847 if (members
!= null) {
848 final var newMemberAddresses
= members
.stream()
849 .filter(member
-> !g
.isMember(member
))
850 .map(this::resolveSignalServiceAddress
)
851 .collect(Collectors
.toList());
852 final var newE164Members
= new HashSet
<String
>();
853 for (var member
: newMemberAddresses
) {
854 if (!member
.getNumber().isPresent()) {
857 newE164Members
.add(member
.getNumber().get());
860 final var registeredUsers
= getRegisteredUsers(newE164Members
);
861 if (registeredUsers
.size() != newE164Members
.size()) {
862 // Some of the new members are not registered on Signal
863 newE164Members
.removeAll(registeredUsers
.keySet());
864 throw new IOException("Failed to add members "
865 + String
.join(", ", newE164Members
)
866 + " to group: Not registered on Signal");
869 g
.addMembers(members
);
872 if (avatarFile
!= null) {
873 avatarStore
.storeGroupAvatar(g
.getGroupId(),
874 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
878 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
879 GroupInviteLinkUrl inviteLinkUrl
880 ) throws IOException
, GroupLinkNotActiveException
{
881 return sendJoinGroupMessage(inviteLinkUrl
);
884 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
885 GroupInviteLinkUrl inviteLinkUrl
886 ) throws IOException
, GroupLinkNotActiveException
{
887 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
888 inviteLinkUrl
.getPassword());
889 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
890 inviteLinkUrl
.getPassword(),
892 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
893 groupJoinInfo
.getRevision() + 1,
894 groupChange
.toByteArray());
896 if (group
.getGroup() == null) {
897 // Only requested member, can't send update to group members
898 return new Pair
<>(group
.getGroupId(), List
.of());
901 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
903 return new Pair
<>(group
.getGroupId(), result
.second());
906 private static int currentTimeDays() {
907 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
910 private GroupsV2AuthorizationString
getGroupAuthForToday(
911 final GroupSecretParams groupSecretParams
912 ) throws IOException
{
913 final var today
= currentTimeDays();
914 // Returns credentials for the next 7 days
915 final var credentials
= groupsV2Api
.getCredentials(today
);
916 // TODO cache credentials until they expire
917 var authCredentialResponse
= credentials
.get(today
);
919 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
922 authCredentialResponse
);
923 } catch (VerificationFailedException e
) {
924 throw new IOException(e
);
928 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
929 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
930 ) throws IOException
{
931 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
932 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
933 account
.getGroupStore().updateGroup(group
);
934 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
937 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
938 GroupIdV1 groupId
, SignalServiceAddress recipient
939 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
941 var group
= getGroupForSending(groupId
);
942 if (!(group
instanceof GroupInfoV1
)) {
943 throw new RuntimeException("Received an invalid group request for a v2 group!");
945 g
= (GroupInfoV1
) group
;
947 if (!g
.isMember(resolveRecipient(recipient
))) {
948 throw new NotAGroupMemberException(groupId
, g
.name
);
951 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
953 // Send group message only to the recipient who requested it
954 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
957 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
958 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
959 .withId(g
.getGroupId().serialize())
961 .withMembers(g
.getMembers()
963 .map(this::resolveSignalServiceAddress
)
964 .collect(Collectors
.toList()));
967 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
968 if (attachment
.isPresent()) {
969 group
.withAvatar(attachment
.get());
971 } catch (IOException e
) {
972 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
975 return SignalServiceDataMessage
.newBuilder()
976 .asGroupMessage(group
.build())
977 .withExpiration(g
.getMessageExpirationTime());
980 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
981 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
982 .withRevision(g
.getGroup().getRevision())
983 .withSignedGroupChange(signedGroupChange
);
984 return SignalServiceDataMessage
.newBuilder()
985 .asGroupMessage(group
.build())
986 .withExpiration(g
.getMessageExpirationTime());
989 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
990 GroupIdV1 groupId
, SignalServiceAddress recipient
991 ) throws IOException
{
992 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
994 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
996 // Send group info request message to the recipient who sent us a message with this groupId
997 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1001 SignalServiceAddress remoteAddress
, long messageId
1002 ) throws IOException
, UntrustedIdentityException
{
1003 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1005 System
.currentTimeMillis());
1007 createMessageSender().sendReceipt(remoteAddress
,
1008 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1012 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1013 String messageText
, List
<String
> attachments
, List
<String
> recipients
1014 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1015 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1016 if (attachments
!= null) {
1017 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1019 // Upload attachments here, so we only upload once even for multiple recipients
1020 var messageSender
= createMessageSender();
1021 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1022 for (var attachment
: attachmentStreams
) {
1023 if (attachment
.isStream()) {
1024 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1025 } else if (attachment
.isPointer()) {
1026 attachmentPointers
.add(attachment
.asPointer());
1030 messageBuilder
.withAttachments(attachmentPointers
);
1032 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1035 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1036 String messageText
, List
<String
> attachments
1037 ) throws IOException
, AttachmentInvalidException
{
1038 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1039 if (attachments
!= null) {
1040 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1042 return sendSelfMessage(messageBuilder
);
1045 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1046 long targetSentTimestamp
, List
<String
> recipients
1047 ) throws IOException
, InvalidNumberException
{
1048 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1049 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1050 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1053 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1054 long targetSentTimestamp
, GroupId groupId
1055 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1056 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1057 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1058 return sendGroupMessage(messageBuilder
, groupId
);
1061 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1062 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1063 ) throws IOException
, InvalidNumberException
{
1064 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1066 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1067 targetSentTimestamp
);
1068 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1069 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1072 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1073 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1075 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1077 return sendMessage(messageBuilder
, signalServiceAddresses
);
1078 } catch (Exception e
) {
1079 for (var address
: signalServiceAddresses
) {
1080 handleEndSession(address
);
1086 public String
getContactName(String number
) throws InvalidNumberException
{
1087 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1088 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1091 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1092 if (!account
.isMasterDevice()) {
1093 throw new NotMasterDeviceException();
1095 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1096 var contact
= account
.getContactStore().getContact(recipientId
);
1097 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1098 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1101 public void setContactBlocked(
1102 String number
, boolean blocked
1103 ) throws InvalidNumberException
, NotMasterDeviceException
{
1104 if (!account
.isMasterDevice()) {
1105 throw new NotMasterDeviceException();
1107 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1110 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1111 var contact
= account
.getContactStore().getContact(recipientId
);
1112 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1113 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1116 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1117 var group
= getGroup(groupId
);
1118 if (group
== null) {
1119 throw new GroupNotFoundException(groupId
);
1122 group
.setBlocked(blocked
);
1123 account
.getGroupStore().updateGroup(group
);
1126 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1127 var contact
= account
.getContactStore().getContact(recipientId
);
1128 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1131 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1132 account
.getContactStore()
1133 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1136 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1137 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1138 sendMessage(messageBuilder
, Set
.of(recipientId
));
1142 * Change the expiration timer for a contact
1144 public void setExpirationTimer(
1145 String number
, int messageExpirationTimer
1146 ) throws IOException
, InvalidNumberException
{
1147 var recipientId
= canonicalizeAndResolveRecipient(number
);
1148 setExpirationTimer(recipientId
, messageExpirationTimer
);
1149 sendExpirationTimerUpdate(recipientId
);
1153 * Change the expiration timer for a group
1155 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1156 var g
= getGroup(groupId
);
1157 if (g
instanceof GroupInfoV1
) {
1158 var groupInfoV1
= (GroupInfoV1
) g
;
1159 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1160 account
.getGroupStore().updateGroup(groupInfoV1
);
1162 throw new RuntimeException("TODO Not implemented!");
1167 * Upload the sticker pack from path.
1169 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1170 * @return if successful, returns the URL to install the sticker pack in the signal app
1172 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1173 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1175 var messageSender
= createMessageSender();
1177 var packKey
= KeyUtils
.createStickerUploadKey();
1178 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1180 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1181 account
.getStickerStore().updateSticker(sticker
);
1184 return new URI("https",
1187 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1188 Hex
.toStringCondensed(packKey
),
1189 StandardCharsets
.UTF_8
)).toString();
1190 } catch (URISyntaxException e
) {
1191 throw new AssertionError(e
);
1195 public void requestAllSyncData() throws IOException
{
1196 requestSyncGroups();
1197 requestSyncContacts();
1198 requestSyncBlocked();
1199 requestSyncConfiguration();
1203 private void requestSyncGroups() throws IOException
{
1204 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1205 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1207 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1209 sendSyncMessage(message
);
1210 } catch (UntrustedIdentityException e
) {
1211 throw new AssertionError(e
);
1215 private void requestSyncContacts() throws IOException
{
1216 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1217 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1219 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1221 sendSyncMessage(message
);
1222 } catch (UntrustedIdentityException e
) {
1223 throw new AssertionError(e
);
1227 private void requestSyncBlocked() throws IOException
{
1228 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1229 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1231 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1233 sendSyncMessage(message
);
1234 } catch (UntrustedIdentityException e
) {
1235 throw new AssertionError(e
);
1239 private void requestSyncConfiguration() throws IOException
{
1240 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1241 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1243 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1245 sendSyncMessage(message
);
1246 } catch (UntrustedIdentityException e
) {
1247 throw new AssertionError(e
);
1251 private void requestSyncKeys() throws IOException
{
1252 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1253 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1255 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1257 sendSyncMessage(message
);
1258 } catch (UntrustedIdentityException e
) {
1259 throw new AssertionError(e
);
1263 private byte[] getSenderCertificate() {
1264 // TODO support UUID capable sender certificates
1265 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1268 certificate
= accountManager
.getSenderCertificate();
1269 } catch (IOException e
) {
1270 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1273 // TODO cache for a day
1277 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1278 var messageSender
= createMessageSender();
1279 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1282 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1283 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1284 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1286 for (var number
: numbers
) {
1287 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1288 if (resolvedAddress
.getUuid().isPresent()) {
1289 signalServiceAddresses
.add(resolvedAddress
);
1291 addressesMissingUuid
.add(resolvedAddress
);
1295 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1296 .map(a
-> a
.getNumber().get())
1297 .collect(Collectors
.toSet());
1298 Map
<String
, UUID
> registeredUsers
;
1300 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1301 } catch (IOException e
) {
1302 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1303 registeredUsers
= Map
.of();
1306 for (var address
: addressesMissingUuid
) {
1307 final var number
= address
.getNumber().get();
1308 if (registeredUsers
.containsKey(number
)) {
1309 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1310 registeredUsers
.get(number
),
1312 signalServiceAddresses
.add(newAddress
);
1314 signalServiceAddresses
.add(address
);
1318 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1321 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1322 final var address
= resolveSignalServiceAddress(recipientId
);
1323 if (!address
.getNumber().isPresent()) {
1326 final var number
= address
.getNumber().get();
1327 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1328 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1331 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1333 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1335 serviceEnvironmentConfig
.getCdsMrenclave());
1336 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1337 throw new IOException(e
);
1341 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1342 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1343 ) throws IOException
{
1344 final var timestamp
= System
.currentTimeMillis();
1345 messageBuilder
.withTimestamp(timestamp
);
1346 getOrCreateMessagePipe();
1347 getOrCreateUnidentifiedMessagePipe();
1348 SignalServiceDataMessage message
= null;
1350 message
= messageBuilder
.build();
1351 if (message
.getGroupContext().isPresent()) {
1353 var messageSender
= createMessageSender();
1354 final var isRecipientUpdate
= false;
1355 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1356 final var addresses
= recipientIdList
.stream()
1357 .map(this::resolveSignalServiceAddress
)
1358 .collect(Collectors
.toList());
1359 var result
= messageSender
.sendMessage(addresses
,
1360 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1364 for (var r
: result
) {
1365 if (r
.getIdentityFailure() != null) {
1366 account
.getIdentityKeyStore().
1367 saveIdentity(resolveRecipient(r
.getAddress()),
1368 r
.getIdentityFailure().getIdentityKey(),
1373 return new Pair
<>(timestamp
, result
);
1374 } catch (UntrustedIdentityException e
) {
1375 return new Pair
<>(timestamp
, List
.of());
1378 // Send to all individually, so sync messages are sent correctly
1379 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1380 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1381 for (var recipientId
: recipientIds
) {
1382 final var contact
= account
.getContactStore().getContact(recipientId
);
1383 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1384 messageBuilder
.withExpiration(expirationTime
);
1385 message
= messageBuilder
.build();
1386 results
.add(sendMessage(resolveSignalServiceAddress(recipientId
), message
));
1388 return new Pair
<>(timestamp
, results
);
1391 if (message
!= null && message
.isEndSession()) {
1392 for (var recipient
: recipientIds
) {
1393 handleEndSession(recipient
);
1399 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1400 SignalServiceDataMessage
.Builder messageBuilder
1401 ) throws IOException
{
1402 final var timestamp
= System
.currentTimeMillis();
1403 messageBuilder
.withTimestamp(timestamp
);
1404 getOrCreateMessagePipe();
1405 getOrCreateUnidentifiedMessagePipe();
1406 final var recipientId
= account
.getSelfRecipientId();
1408 final var contact
= account
.getContactStore().getContact(recipientId
);
1409 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1410 messageBuilder
.withExpiration(expirationTime
);
1412 var message
= messageBuilder
.build();
1413 final var result
= sendSelfMessage(message
);
1414 return new Pair
<>(timestamp
, result
);
1417 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1418 var messageSender
= createMessageSender();
1420 var recipient
= account
.getSelfAddress();
1422 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(resolveRecipient(recipient
));
1423 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1424 message
.getTimestamp(),
1426 message
.getExpiresInSeconds(),
1427 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1429 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1432 var startTime
= System
.currentTimeMillis();
1433 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1434 return SendMessageResult
.success(recipient
,
1435 unidentifiedAccess
.isPresent(),
1437 System
.currentTimeMillis() - startTime
);
1438 } catch (UntrustedIdentityException e
) {
1439 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1443 private SendMessageResult
sendMessage(
1444 SignalServiceAddress address
, SignalServiceDataMessage message
1445 ) throws IOException
{
1446 var messageSender
= createMessageSender();
1448 final var recipientId
= resolveRecipient(address
);
1451 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
), message
);
1452 } catch (UnregisteredUserException e
) {
1453 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1454 return messageSender
.sendMessage(resolveSignalServiceAddress(newRecipientId
),
1455 unidentifiedAccessHelper
.getAccessFor(newRecipientId
),
1458 } catch (UntrustedIdentityException e
) {
1459 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1463 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1464 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1465 account
.getSignalProtocolStore(),
1466 certificateValidator
);
1468 return cipher
.decrypt(envelope
);
1469 } catch (ProtocolUntrustedIdentityException e
) {
1470 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1471 throw (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1473 throw new AssertionError(e
);
1477 private void handleEndSession(RecipientId recipientId
) {
1478 account
.getSessionStore().deleteAllSessions(recipientId
);
1481 private List
<HandleAction
> handleSignalServiceDataMessage(
1482 SignalServiceDataMessage message
,
1484 SignalServiceAddress source
,
1485 SignalServiceAddress destination
,
1486 boolean ignoreAttachments
1488 var actions
= new ArrayList
<HandleAction
>();
1489 if (message
.getGroupContext().isPresent()) {
1490 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1491 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1492 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1493 var group
= getGroup(groupId
);
1494 if (group
== null || group
instanceof GroupInfoV1
) {
1495 var groupV1
= (GroupInfoV1
) group
;
1496 switch (groupInfo
.getType()) {
1498 if (groupV1
== null) {
1499 groupV1
= new GroupInfoV1(groupId
);
1502 if (groupInfo
.getAvatar().isPresent()) {
1503 var avatar
= groupInfo
.getAvatar().get();
1504 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1507 if (groupInfo
.getName().isPresent()) {
1508 groupV1
.name
= groupInfo
.getName().get();
1511 if (groupInfo
.getMembers().isPresent()) {
1512 groupV1
.addMembers(groupInfo
.getMembers()
1515 .map(this::resolveRecipient
)
1516 .collect(Collectors
.toSet()));
1519 account
.getGroupStore().updateGroup(groupV1
);
1523 if (groupV1
== null && !isSync
) {
1524 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1528 if (groupV1
!= null) {
1529 groupV1
.removeMember(resolveRecipient(source
));
1530 account
.getGroupStore().updateGroup(groupV1
);
1535 if (groupV1
!= null && !isSync
) {
1536 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1541 // Received a group v1 message for a v2 group
1544 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1545 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1546 final var groupMasterKey
= groupContext
.getMasterKey();
1548 getOrMigrateGroup(groupMasterKey
,
1549 groupContext
.getRevision(),
1550 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1554 final var conversationPartnerAddress
= isSync ? destination
: source
;
1555 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1556 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1558 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1559 if (message
.getGroupContext().isPresent()) {
1560 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1561 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1562 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1563 if (group
!= null) {
1564 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1565 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1566 account
.getGroupStore().updateGroup(group
);
1569 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1570 // disappearing message timer already stored in the DecryptedGroup
1572 } else if (conversationPartnerAddress
!= null) {
1573 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1576 if (!ignoreAttachments
) {
1577 if (message
.getAttachments().isPresent()) {
1578 for (var attachment
: message
.getAttachments().get()) {
1579 downloadAttachment(attachment
);
1582 if (message
.getSharedContacts().isPresent()) {
1583 for (var contact
: message
.getSharedContacts().get()) {
1584 if (contact
.getAvatar().isPresent()) {
1585 downloadAttachment(contact
.getAvatar().get().getAttachment());
1590 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1591 final ProfileKey profileKey
;
1593 profileKey
= new ProfileKey(message
.getProfileKey().get());
1594 } catch (InvalidInputException e
) {
1595 throw new AssertionError(e
);
1597 if (source
.matches(account
.getSelfAddress())) {
1598 this.account
.setProfileKey(profileKey
);
1600 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1602 if (message
.getPreviews().isPresent()) {
1603 final var previews
= message
.getPreviews().get();
1604 for (var preview
: previews
) {
1605 if (preview
.getImage().isPresent()) {
1606 downloadAttachment(preview
.getImage().get());
1610 if (message
.getQuote().isPresent()) {
1611 final var quote
= message
.getQuote().get();
1613 for (var quotedAttachment
: quote
.getAttachments()) {
1614 final var thumbnail
= quotedAttachment
.getThumbnail();
1615 if (thumbnail
!= null) {
1616 downloadAttachment(thumbnail
);
1620 if (message
.getSticker().isPresent()) {
1621 final var messageSticker
= message
.getSticker().get();
1622 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1623 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1624 if (sticker
== null) {
1625 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1626 account
.getStickerStore().updateSticker(sticker
);
1632 private GroupInfoV2
getOrMigrateGroup(
1633 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1635 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1637 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1638 var groupInfo
= getGroup(groupId
);
1639 final GroupInfoV2 groupInfoV2
;
1640 if (groupInfo
instanceof GroupInfoV1
) {
1641 // Received a v2 group message for a v1 group, we need to locally migrate the group
1642 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1643 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1644 logger
.info("Locally migrated group {} to group v2, id: {}",
1645 groupInfo
.getGroupId().toBase64(),
1646 groupInfoV2
.getGroupId().toBase64());
1647 } else if (groupInfo
instanceof GroupInfoV2
) {
1648 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1650 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1653 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1654 DecryptedGroup group
= null;
1655 if (signedGroupChange
!= null
1656 && groupInfoV2
.getGroup() != null
1657 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1658 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1660 if (group
== null) {
1661 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1663 if (group
!= null) {
1664 storeProfileKeysFromMembers(group
);
1665 final var avatar
= group
.getAvatar();
1666 if (avatar
!= null && !avatar
.isEmpty()) {
1667 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1670 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1671 account
.getGroupStore().updateGroup(groupInfoV2
);
1677 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1678 for (var member
: group
.getMembersList()) {
1679 final var address
= resolveRecipient(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1680 .toByteArray()), null));
1682 account
.getProfileStore()
1683 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1684 } catch (InvalidInputException ignored
) {
1689 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1690 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1691 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1692 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1693 if (actions
!= null) {
1694 queuedActions
.addAll(actions
);
1697 for (var action
: queuedActions
) {
1699 action
.execute(this);
1700 } catch (Throwable e
) {
1701 logger
.warn("Message action failed.", e
);
1706 private List
<HandleAction
> retryFailedReceivedMessage(
1707 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1709 var envelope
= cachedMessage
.loadEnvelope();
1710 if (envelope
== null) {
1713 SignalServiceContent content
= null;
1714 List
<HandleAction
> actions
= null;
1715 if (!envelope
.isReceipt()) {
1717 content
= decryptMessage(envelope
);
1718 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1719 if (!envelope
.hasSource()) {
1720 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
)
1723 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1724 } catch (IOException ioException
) {
1725 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1729 } catch (Exception er
) {
1730 // All other errors are not recoverable, so delete the cached message
1731 cachedMessage
.delete();
1734 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1736 handler
.handleMessage(envelope
, content
, null);
1737 cachedMessage
.delete();
1741 public void receiveMessages(
1744 boolean returnOnTimeout
,
1745 boolean ignoreAttachments
,
1746 ReceiveMessageHandler handler
1747 ) throws IOException
{
1748 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1750 Set
<HandleAction
> queuedActions
= null;
1752 final var messagePipe
= getOrCreateMessagePipe();
1754 var hasCaughtUpWithOldMessages
= false;
1757 SignalServiceEnvelope envelope
;
1758 SignalServiceContent content
= null;
1759 Exception exception
= null;
1760 final CachedMessage
[] cachedMessage
= {null};
1762 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1763 final var recipientId
= envelope1
.hasSource()
1764 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1766 // store message on disk, before acknowledging receipt to the server
1767 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1769 if (result
.isPresent()) {
1770 envelope
= result
.get();
1772 // Received indicator that server queue is empty
1773 hasCaughtUpWithOldMessages
= true;
1775 if (queuedActions
!= null) {
1776 for (var action
: queuedActions
) {
1778 action
.execute(this);
1779 } catch (Throwable e
) {
1780 logger
.warn("Message action failed.", e
);
1783 queuedActions
.clear();
1784 queuedActions
= null;
1787 // Continue to wait another timeout for new messages
1790 } catch (TimeoutException e
) {
1791 if (returnOnTimeout
) return;
1795 if (envelope
.hasSource()) {
1796 // Store uuid if we don't have it already
1797 resolveRecipientTrusted(envelope
.getSourceAddress());
1799 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1800 if (!envelope
.isReceipt()) {
1802 content
= decryptMessage(envelope
);
1803 } catch (Exception e
) {
1806 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1807 if (hasCaughtUpWithOldMessages
) {
1808 for (var action
: actions
) {
1810 action
.execute(this);
1811 } catch (Throwable e
) {
1812 logger
.warn("Message action failed.", e
);
1816 if (queuedActions
== null) {
1817 queuedActions
= new HashSet
<>();
1819 queuedActions
.addAll(actions
);
1822 if (isMessageBlocked(envelope
, content
)) {
1823 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1824 } else if (notAGroupMember
) {
1825 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1827 handler
.handleMessage(envelope
, content
, exception
);
1829 if (cachedMessage
[0] != null) {
1830 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1831 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
)
1833 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1834 if (!envelope
.hasSource()) {
1836 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1837 } catch (IOException ioException
) {
1838 logger
.warn("Failed to move cached message to recipient folder: {}",
1839 ioException
.getMessage());
1843 cachedMessage
[0].delete();
1849 private boolean isMessageBlocked(
1850 SignalServiceEnvelope envelope
, SignalServiceContent content
1852 SignalServiceAddress source
;
1853 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1854 source
= envelope
.getSourceAddress();
1855 } else if (content
!= null) {
1856 source
= content
.getSender();
1860 final var recipientId
= resolveRecipient(source
);
1861 if (isContactBlocked(recipientId
)) {
1865 if (content
!= null && content
.getDataMessage().isPresent()) {
1866 var message
= content
.getDataMessage().get();
1867 if (message
.getGroupContext().isPresent()) {
1868 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1869 var group
= getGroup(groupId
);
1870 if (group
!= null && group
.isBlocked()) {
1878 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
1879 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
1880 return isContactBlocked(recipientId
);
1883 private boolean isContactBlocked(final RecipientId recipientId
) {
1884 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1885 return sourceContact
!= null && sourceContact
.isBlocked();
1888 private boolean isNotAGroupMember(
1889 SignalServiceEnvelope envelope
, SignalServiceContent content
1891 SignalServiceAddress source
;
1892 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1893 source
= envelope
.getSourceAddress();
1894 } else if (content
!= null) {
1895 source
= content
.getSender();
1900 if (content
!= null && content
.getDataMessage().isPresent()) {
1901 var message
= content
.getDataMessage().get();
1902 if (message
.getGroupContext().isPresent()) {
1903 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1904 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1905 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1909 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1910 var group
= getGroup(groupId
);
1911 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
1919 private List
<HandleAction
> handleMessage(
1920 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1922 var actions
= new ArrayList
<HandleAction
>();
1923 if (content
!= null) {
1924 final SignalServiceAddress sender
;
1925 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1926 sender
= envelope
.getSourceAddress();
1928 sender
= content
.getSender();
1931 if (content
.getDataMessage().isPresent()) {
1932 var message
= content
.getDataMessage().get();
1934 if (content
.isNeedsReceipt()) {
1935 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1938 actions
.addAll(handleSignalServiceDataMessage(message
,
1941 account
.getSelfAddress(),
1942 ignoreAttachments
));
1944 if (content
.getSyncMessage().isPresent()) {
1945 account
.setMultiDevice(true);
1946 var syncMessage
= content
.getSyncMessage().get();
1947 if (syncMessage
.getSent().isPresent()) {
1948 var message
= syncMessage
.getSent().get();
1949 final var destination
= message
.getDestination().orNull();
1950 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1954 ignoreAttachments
));
1956 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
1957 var rm
= syncMessage
.getRequest().get();
1958 if (rm
.isContactsRequest()) {
1959 actions
.add(SendSyncContactsAction
.create());
1961 if (rm
.isGroupsRequest()) {
1962 actions
.add(SendSyncGroupsAction
.create());
1964 if (rm
.isBlockedListRequest()) {
1965 actions
.add(SendSyncBlockedListAction
.create());
1967 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1969 if (syncMessage
.getGroups().isPresent()) {
1970 File tmpFile
= null;
1972 tmpFile
= IOUtils
.createTempFile();
1973 final var groupsMessage
= syncMessage
.getGroups().get();
1974 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1975 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1977 while ((g
= s
.read()) != null) {
1978 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1979 if (syncGroup
!= null) {
1980 if (g
.getName().isPresent()) {
1981 syncGroup
.name
= g
.getName().get();
1983 syncGroup
.addMembers(g
.getMembers()
1985 .map(this::resolveRecipient
)
1986 .collect(Collectors
.toSet()));
1987 if (!g
.isActive()) {
1988 syncGroup
.removeMember(account
.getSelfRecipientId());
1990 // Add ourself to the member set as it's marked as active
1991 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
1993 syncGroup
.blocked
= g
.isBlocked();
1994 if (g
.getColor().isPresent()) {
1995 syncGroup
.color
= g
.getColor().get();
1998 if (g
.getAvatar().isPresent()) {
1999 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2001 syncGroup
.archived
= g
.isArchived();
2002 account
.getGroupStore().updateGroup(syncGroup
);
2006 } catch (Exception e
) {
2007 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2011 if (tmpFile
!= null) {
2013 Files
.delete(tmpFile
.toPath());
2014 } catch (IOException e
) {
2015 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2022 if (syncMessage
.getBlockedList().isPresent()) {
2023 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2024 for (var address
: blockedListMessage
.getAddresses()) {
2025 setContactBlocked(resolveRecipient(address
), true);
2027 for (var groupId
: blockedListMessage
.getGroupIds()
2029 .map(GroupId
::unknownVersion
)
2030 .collect(Collectors
.toSet())) {
2032 setGroupBlocked(groupId
, true);
2033 } catch (GroupNotFoundException e
) {
2034 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2035 groupId
.toBase64());
2039 if (syncMessage
.getContacts().isPresent()) {
2040 File tmpFile
= null;
2042 tmpFile
= IOUtils
.createTempFile();
2043 final var contactsMessage
= syncMessage
.getContacts().get();
2044 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2045 .asPointer(), tmpFile
)) {
2046 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2048 while ((c
= s
.read()) != null) {
2049 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2050 account
.setProfileKey(c
.getProfileKey().get());
2052 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2053 var contact
= account
.getContactStore().getContact(recipientId
);
2054 final var builder
= contact
== null
2055 ? Contact
.newBuilder()
2056 : Contact
.newBuilder(contact
);
2057 if (c
.getName().isPresent()) {
2058 builder
.withName(c
.getName().get());
2060 if (c
.getColor().isPresent()) {
2061 builder
.withColor(c
.getColor().get());
2063 if (c
.getProfileKey().isPresent()) {
2064 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2066 if (c
.getVerified().isPresent()) {
2067 final var verifiedMessage
= c
.getVerified().get();
2068 account
.getIdentityKeyStore()
2069 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2070 verifiedMessage
.getIdentityKey(),
2071 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2073 if (c
.getExpirationTimer().isPresent()) {
2074 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2076 builder
.withBlocked(c
.isBlocked());
2077 builder
.withArchived(c
.isArchived());
2078 account
.getContactStore().storeContact(recipientId
, builder
.build());
2080 if (c
.getAvatar().isPresent()) {
2081 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2085 } catch (Exception e
) {
2086 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2090 if (tmpFile
!= null) {
2092 Files
.delete(tmpFile
.toPath());
2093 } catch (IOException e
) {
2094 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2101 if (syncMessage
.getVerified().isPresent()) {
2102 final var verifiedMessage
= syncMessage
.getVerified().get();
2103 account
.getIdentityKeyStore()
2104 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2105 verifiedMessage
.getIdentityKey(),
2106 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2108 if (syncMessage
.getStickerPackOperations().isPresent()) {
2109 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2110 for (var m
: stickerPackOperationMessages
) {
2111 if (!m
.getPackId().isPresent()) {
2114 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2115 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2116 if (sticker
== null) {
2117 if (!m
.getPackKey().isPresent()) {
2120 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2122 sticker
.setInstalled(!m
.getType().isPresent()
2123 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2124 account
.getStickerStore().updateSticker(sticker
);
2127 if (syncMessage
.getFetchType().isPresent()) {
2128 switch (syncMessage
.getFetchType().get()) {
2130 getRecipientProfile(account
.getSelfRecipientId(), true);
2131 case STORAGE_MANIFEST
:
2135 if (syncMessage
.getKeys().isPresent()) {
2136 final var keysMessage
= syncMessage
.getKeys().get();
2137 if (keysMessage
.getStorageService().isPresent()) {
2138 final var storageKey
= keysMessage
.getStorageService().get();
2139 account
.setStorageKey(storageKey
);
2142 if (syncMessage
.getConfiguration().isPresent()) {
2150 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2152 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2153 } catch (IOException e
) {
2154 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2158 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2160 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2161 } catch (IOException e
) {
2162 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2166 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2168 avatarStore
.storeGroupAvatar(groupId
,
2169 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2170 } catch (IOException e
) {
2171 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2175 private void downloadProfileAvatar(
2176 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2179 avatarStore
.storeProfileAvatar(address
,
2180 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2181 } catch (Throwable e
) {
2182 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2186 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2187 return attachmentStore
.getAttachmentFile(attachmentId
);
2190 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2191 if (!attachment
.isPointer()) {
2192 logger
.warn("Invalid state, can't store an attachment stream.");
2195 var pointer
= attachment
.asPointer();
2196 if (pointer
.getPreview().isPresent()) {
2197 final var preview
= pointer
.getPreview().get();
2199 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2200 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2201 } catch (IOException e
) {
2202 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2207 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2208 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2209 } catch (IOException e
) {
2210 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2214 private void retrieveGroupV2Avatar(
2215 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2216 ) throws IOException
{
2217 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2219 var tmpFile
= IOUtils
.createTempFile();
2220 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2222 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2223 var encryptedData
= IOUtils
.readFully(input
);
2225 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2226 outputStream
.write(decryptedData
);
2229 Files
.delete(tmpFile
.toPath());
2230 } catch (IOException e
) {
2231 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2238 private void retrieveProfileAvatar(
2239 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2240 ) throws IOException
{
2241 var tmpFile
= IOUtils
.createTempFile();
2242 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2245 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2246 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2247 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2250 Files
.delete(tmpFile
.toPath());
2251 } catch (IOException e
) {
2252 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2259 private void retrieveAttachment(
2260 final SignalServiceAttachment attachment
, final OutputStream outputStream
2261 ) throws IOException
{
2262 if (attachment
.isPointer()) {
2263 var pointer
= attachment
.asPointer();
2264 retrieveAttachmentPointer(pointer
, outputStream
);
2266 var stream
= attachment
.asStream();
2267 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2271 private void retrieveAttachmentPointer(
2272 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2273 ) throws IOException
{
2274 var tmpFile
= IOUtils
.createTempFile();
2275 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2276 IOUtils
.copyStream(input
, outputStream
);
2277 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2278 throw new IOException(e
);
2281 Files
.delete(tmpFile
.toPath());
2282 } catch (IOException e
) {
2283 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2290 private InputStream
retrieveAttachmentAsStream(
2291 SignalServiceAttachmentPointer pointer
, File tmpFile
2292 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2293 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2296 void sendGroups() throws IOException
, UntrustedIdentityException
{
2297 var groupsFile
= IOUtils
.createTempFile();
2300 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2301 var out
= new DeviceGroupsOutputStream(fos
);
2302 for (var record : getGroups()) {
2303 if (record instanceof GroupInfoV1
) {
2304 var groupInfo
= (GroupInfoV1
) record;
2305 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2306 Optional
.fromNullable(groupInfo
.name
),
2307 groupInfo
.getMembers()
2309 .map(this::resolveSignalServiceAddress
)
2310 .collect(Collectors
.toList()),
2311 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2312 groupInfo
.isMember(account
.getSelfRecipientId()),
2313 Optional
.of(groupInfo
.messageExpirationTime
),
2314 Optional
.fromNullable(groupInfo
.color
),
2317 groupInfo
.archived
));
2322 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2323 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2324 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2325 .withStream(groupsFileStream
)
2326 .withContentType("application/octet-stream")
2327 .withLength(groupsFile
.length())
2330 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2335 Files
.delete(groupsFile
.toPath());
2336 } catch (IOException e
) {
2337 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2342 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2343 var contactsFile
= IOUtils
.createTempFile();
2346 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2347 var out
= new DeviceContactsOutputStream(fos
);
2348 for (var contactPair
: account
.getContactStore().getContacts()) {
2349 final var recipientId
= contactPair
.first();
2350 final var contact
= contactPair
.second();
2351 final var address
= resolveSignalServiceAddress(recipientId
);
2353 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2354 VerifiedMessage verifiedMessage
= null;
2355 if (currentIdentity
!= null) {
2356 verifiedMessage
= new VerifiedMessage(address
,
2357 currentIdentity
.getIdentityKey(),
2358 currentIdentity
.getTrustLevel().toVerifiedState(),
2359 currentIdentity
.getDateAdded().getTime());
2362 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2363 out
.write(new DeviceContact(address
,
2364 Optional
.fromNullable(contact
.getName()),
2365 createContactAvatarAttachment(address
),
2366 Optional
.fromNullable(contact
.getColor()),
2367 Optional
.fromNullable(verifiedMessage
),
2368 Optional
.fromNullable(profileKey
),
2369 contact
.isBlocked(),
2370 Optional
.of(contact
.getMessageExpirationTime()),
2372 contact
.isArchived()));
2375 if (account
.getProfileKey() != null) {
2376 // Send our own profile key as well
2377 out
.write(new DeviceContact(account
.getSelfAddress(),
2382 Optional
.of(account
.getProfileKey()),
2390 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2391 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2392 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2393 .withStream(contactsFileStream
)
2394 .withContentType("application/octet-stream")
2395 .withLength(contactsFile
.length())
2398 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2403 Files
.delete(contactsFile
.toPath());
2404 } catch (IOException e
) {
2405 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2410 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2411 var addresses
= new ArrayList
<SignalServiceAddress
>();
2412 for (var record : account
.getContactStore().getContacts()) {
2413 if (record.second().isBlocked()) {
2414 addresses
.add(resolveSignalServiceAddress(record.first()));
2417 var groupIds
= new ArrayList
<byte[]>();
2418 for (var record : getGroups()) {
2419 if (record.isBlocked()) {
2420 groupIds
.add(record.getGroupId().serialize());
2423 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2426 private void sendVerifiedMessage(
2427 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2428 ) throws IOException
, UntrustedIdentityException
{
2429 var verifiedMessage
= new VerifiedMessage(destination
,
2431 trustLevel
.toVerifiedState(),
2432 System
.currentTimeMillis());
2433 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2436 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2437 return account
.getContactStore().getContacts();
2440 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2441 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2442 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2443 if (recipient
== null) {
2447 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2448 return recipient
.getContact().getName();
2451 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2452 return recipient
.getProfile().getDisplayName();
2458 public GroupInfo
getGroup(GroupId groupId
) {
2459 final var group
= account
.getGroupStore().getGroup(groupId
);
2460 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2461 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2462 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2463 account
.getGroupStore().updateGroup(group
);
2468 public List
<IdentityInfo
> getIdentities() {
2469 return account
.getIdentityKeyStore().getIdentities();
2472 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2473 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2474 return identity
== null ? List
.of() : List
.of(identity
);
2478 * Trust this the identity with this fingerprint
2480 * @param name username of the identity
2481 * @param fingerprint Fingerprint
2483 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2484 var recipientId
= canonicalizeAndResolveRecipient(name
);
2485 return trustIdentity(recipientId
,
2486 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2487 TrustLevel
.TRUSTED_VERIFIED
);
2491 * Trust this the identity with this safety number
2493 * @param name username of the identity
2494 * @param safetyNumber Safety number
2496 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2497 var recipientId
= canonicalizeAndResolveRecipient(name
);
2498 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2499 return trustIdentity(recipientId
,
2500 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2501 TrustLevel
.TRUSTED_VERIFIED
);
2505 * Trust all keys of this identity without verification
2507 * @param name username of the identity
2509 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2510 var recipientId
= canonicalizeAndResolveRecipient(name
);
2511 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2514 private boolean trustIdentity(
2515 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2517 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2518 if (identity
== null) {
2522 if (!verifier
.apply(identity
.getIdentityKey())) {
2526 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2528 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2529 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2530 } catch (IOException
| UntrustedIdentityException e
) {
2531 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2537 public String
computeSafetyNumber(
2538 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2540 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2541 account
.getSelfAddress(),
2542 getIdentityKeyPair().getPublicKey(),
2548 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2549 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2551 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2552 return resolveSignalServiceAddress(canonicalizedNumber
);
2556 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2557 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2559 return resolveSignalServiceAddress(address
);
2563 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2564 if (address
.matches(account
.getSelfAddress())) {
2565 return account
.getSelfAddress();
2568 return account
.getRecipientStore().resolveServiceAddress(address
);
2571 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2572 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2575 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2576 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2578 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2580 return resolveRecipient(canonicalizedNumber
);
2583 private RecipientId
resolveRecipient(final String identifier
) {
2584 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2586 return resolveRecipient(address
);
2589 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2590 return account
.getRecipientStore().resolveRecipient(address
);
2593 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2594 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2598 public void close() throws IOException
{
2602 void close(boolean closeAccount
) throws IOException
{
2603 executor
.shutdown();
2605 if (messagePipe
!= null) {
2606 messagePipe
.shutdown();
2610 if (unidentifiedMessagePipe
!= null) {
2611 unidentifiedMessagePipe
.shutdown();
2612 unidentifiedMessagePipe
= null;
2615 if (closeAccount
&& account
!= null) {
2621 public interface ReceiveMessageHandler
{
2623 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);