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 givenName if null, the previous givenName will be kept
358 * @param familyName if null, the previous familyName will be kept
359 * @param about if null, the previous about text will be kept
360 * @param aboutEmoji if null, the previous about emoji will be kept
361 * @param avatar if avatar is null the image from the local avatar store is used (if present),
363 public void setProfile(
364 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
365 ) throws IOException
{
366 var profile
= getRecipientProfile(account
.getSelfRecipientId());
367 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
368 if (givenName
!= null) {
369 builder
.withGivenName(givenName
);
371 if (familyName
!= null) {
372 builder
.withFamilyName(familyName
);
375 builder
.withAbout(about
);
377 if (aboutEmoji
!= null) {
378 builder
.withAboutEmoji(aboutEmoji
);
380 var newProfile
= builder
.build();
382 try (final var streamDetails
= avatar
== null
383 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
384 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
385 accountManager
.setVersionedProfile(account
.getUuid(),
386 account
.getProfileKey(),
387 newProfile
.getInternalServiceName(),
388 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
389 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
393 if (avatar
!= null) {
394 if (avatar
.isPresent()) {
395 avatarStore
.storeProfileAvatar(getSelfAddress(),
396 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
398 avatarStore
.deleteProfileAvatar(getSelfAddress());
401 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
404 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
405 } catch (UntrustedIdentityException ignored
) {
409 public void unregister() throws IOException
{
410 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
411 // If this is the master device, other users can't send messages to this number anymore.
412 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
413 accountManager
.setGcmId(Optional
.absent());
415 account
.setRegistered(false);
418 public void deleteAccount() throws IOException
{
419 accountManager
.deleteAccount();
421 account
.setRegistered(false);
424 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
425 var devices
= accountManager
.getDevices();
426 account
.setMultiDevice(devices
.size() > 1);
430 public void removeLinkedDevices(int deviceId
) throws IOException
{
431 accountManager
.removeDevice(deviceId
);
432 var devices
= accountManager
.getDevices();
433 account
.setMultiDevice(devices
.size() > 1);
436 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
437 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
439 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
442 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
443 var identityKeyPair
= getIdentityKeyPair();
444 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
446 accountManager
.addDevice(deviceIdentifier
,
449 Optional
.of(account
.getProfileKey().serialize()),
451 account
.setMultiDevice(true);
454 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
455 if (!account
.isMasterDevice()) {
456 throw new RuntimeException("Only master device can set a PIN");
458 if (pin
.isPresent()) {
459 final var masterKey
= account
.getPinMasterKey() != null
460 ? account
.getPinMasterKey()
461 : KeyUtils
.createMasterKey();
463 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
465 account
.setRegistrationLockPin(pin
.get(), masterKey
);
467 // Remove legacy registration lock
468 accountManager
.removeRegistrationLockV1();
471 pinHelper
.removeRegistrationLockPin();
473 account
.setRegistrationLockPin(null, null);
477 void refreshPreKeys() throws IOException
{
478 var oneTimePreKeys
= generatePreKeys();
479 final var identityKeyPair
= getIdentityKeyPair();
480 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
482 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
485 private List
<PreKeyRecord
> generatePreKeys() {
486 final var offset
= account
.getPreKeyIdOffset();
488 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
489 account
.addPreKeys(records
);
494 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
495 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
497 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
498 account
.addSignedPreKey(record);
503 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
504 if (messagePipe
== null) {
505 messagePipe
= messageReceiver
.createMessagePipe();
510 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
511 if (unidentifiedMessagePipe
== null) {
512 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
514 return unidentifiedMessagePipe
;
517 private SignalServiceMessageSender
createMessageSender() {
518 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
520 account
.getUsername(),
521 account
.getPassword(),
522 account
.getDeviceId(),
523 account
.getSignalProtocolStore(),
525 account
.isMultiDevice(),
526 Optional
.fromNullable(messagePipe
),
527 Optional
.fromNullable(unidentifiedMessagePipe
),
529 clientZkProfileOperations
,
531 ServiceConfig
.MAX_ENVELOPE_SIZE
,
532 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
535 public Profile
getRecipientProfile(
536 RecipientId recipientId
538 return getRecipientProfile(recipientId
, false);
541 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
543 Profile
getRecipientProfile(
544 RecipientId recipientId
, boolean force
546 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
547 if (profileKey
== null) {
549 // retrieve profile to get identity key
550 retrieveEncryptedProfile(recipientId
);
554 var profile
= account
.getProfileStore().getProfile(recipientId
);
556 var now
= new Date().getTime();
557 // Profiles are cached for 24h before retrieving them again, unless forced
558 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
562 synchronized (pendingProfileRequest
) {
563 if (pendingProfileRequest
.contains(recipientId
)) {
566 pendingProfileRequest
.add(recipientId
);
568 final SignalServiceProfile encryptedProfile
;
570 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
572 synchronized (pendingProfileRequest
) {
573 pendingProfileRequest
.remove(recipientId
);
576 if (encryptedProfile
== null) {
580 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
581 account
.getProfileStore().storeProfile(recipientId
, profile
);
586 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
588 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
589 } catch (IOException e
) {
590 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
595 private ProfileAndCredential
retrieveProfileAndCredential(
596 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
597 ) throws IOException
{
598 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
599 final var profile
= profileAndCredential
.getProfile();
602 var newIdentity
= account
.getIdentityKeyStore()
603 .saveIdentity(recipientId
,
604 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
608 account
.getSessionStore().archiveSessions(recipientId
);
610 } catch (InvalidKeyException ignored
) {
611 logger
.warn("Got invalid identity key in profile for {}",
612 resolveSignalServiceAddress(recipientId
).getLegacyIdentifier());
614 return profileAndCredential
;
617 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
618 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
619 if (profileKeyCredential
!= null) {
620 return profileKeyCredential
;
623 ProfileAndCredential profileAndCredential
;
625 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
626 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
627 } catch (IOException e
) {
628 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
632 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
633 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
635 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
636 if (profileKey
!= null) {
637 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
639 profileAndCredential
.getProfile());
640 account
.getProfileStore().storeProfile(recipientId
, profile
);
643 return profileKeyCredential
;
646 private Profile
decryptProfileAndDownloadAvatar(
647 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
649 if (encryptedProfile
.getAvatar() != null) {
650 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
653 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
656 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
657 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
658 if (streamDetails
== null) {
659 return Optional
.absent();
662 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
665 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
666 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
667 if (streamDetails
== null) {
668 return Optional
.absent();
671 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
674 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
675 var g
= getGroup(groupId
);
677 throw new GroupNotFoundException(groupId
);
679 if (!g
.isMember(account
.getSelfRecipientId())) {
680 throw new NotAGroupMemberException(groupId
, g
.getTitle());
685 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
686 var g
= getGroup(groupId
);
688 throw new GroupNotFoundException(groupId
);
690 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
691 throw new NotAGroupMemberException(groupId
, g
.getTitle());
696 public List
<GroupInfo
> getGroups() {
697 return account
.getGroupStore().getGroups();
700 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
701 String messageText
, List
<String
> attachments
, GroupId groupId
702 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
703 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
704 if (attachments
!= null) {
705 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
708 return sendGroupMessage(messageBuilder
, groupId
);
711 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
712 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
713 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
714 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
715 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
717 resolveSignalServiceAddress(targetAuthorRecipientId
),
718 targetSentTimestamp
);
719 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
721 return sendGroupMessage(messageBuilder
, groupId
);
724 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
725 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
726 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
727 final var g
= getGroupForSending(groupId
);
729 GroupUtils
.setGroupContext(messageBuilder
, g
);
730 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
732 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
735 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
736 SignalServiceDataMessage
.Builder messageBuilder
;
738 final var g
= getGroupForUpdating(groupId
);
739 if (g
instanceof GroupInfoV1
) {
740 var groupInfoV1
= (GroupInfoV1
) g
;
741 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
742 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
743 groupInfoV1
.removeMember(account
.getSelfRecipientId());
744 account
.getGroupStore().updateGroup(groupInfoV1
);
746 final var groupInfoV2
= (GroupInfoV2
) g
;
747 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
748 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
749 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
750 account
.getGroupStore().updateGroup(groupInfoV2
);
753 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
756 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
757 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
758 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
759 return sendUpdateGroupMessage(groupId
,
761 members
== null ?
null : getSignalServiceAddresses(members
),
765 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
766 GroupId groupId
, String name
, Set
<RecipientId
> members
, File avatarFile
767 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
769 SignalServiceDataMessage
.Builder messageBuilder
;
770 if (groupId
== null) {
772 var gv2Pair
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
773 members
== null ? Set
.of() : members
,
775 if (gv2Pair
== null) {
776 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
777 gv1
.addMembers(List
.of(account
.getSelfRecipientId()));
778 updateGroupV1(gv1
, name
, members
, avatarFile
);
779 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
782 final var gv2
= gv2Pair
.first();
783 final var decryptedGroup
= gv2Pair
.second();
785 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
786 if (avatarFile
!= null) {
787 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
788 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
790 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
794 var group
= getGroupForUpdating(groupId
);
795 if (group
instanceof GroupInfoV2
) {
796 final var groupInfoV2
= (GroupInfoV2
) group
;
798 Pair
<Long
, List
<SendMessageResult
>> result
= null;
799 if (groupInfoV2
.isPendingMember(account
.getSelfRecipientId())) {
800 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
801 result
= sendUpdateGroupMessage(groupInfoV2
,
802 groupGroupChangePair
.first(),
803 groupGroupChangePair
.second());
806 if (members
!= null) {
807 final var newMembers
= new HashSet
<>(members
);
808 newMembers
.removeAll(group
.getMembers());
809 if (newMembers
.size() > 0) {
810 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
811 result
= sendUpdateGroupMessage(groupInfoV2
,
812 groupGroupChangePair
.first(),
813 groupGroupChangePair
.second());
816 if (result
== null || name
!= null || avatarFile
!= null) {
817 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
818 if (avatarFile
!= null) {
819 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
820 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
822 result
= sendUpdateGroupMessage(groupInfoV2
,
823 groupGroupChangePair
.first(),
824 groupGroupChangePair
.second());
827 return new Pair
<>(group
.getGroupId(), result
.second());
829 var gv1
= (GroupInfoV1
) group
;
830 updateGroupV1(gv1
, name
, members
, avatarFile
);
831 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
836 account
.getGroupStore().updateGroup(g
);
838 final var result
= sendMessage(messageBuilder
,
839 g
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
840 return new Pair
<>(g
.getGroupId(), result
.second());
843 private void updateGroupV1(
844 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
845 ) throws IOException
{
850 if (members
!= null) {
851 final var newMemberAddresses
= members
.stream()
852 .filter(member
-> !g
.isMember(member
))
853 .map(this::resolveSignalServiceAddress
)
854 .collect(Collectors
.toList());
855 final var newE164Members
= new HashSet
<String
>();
856 for (var member
: newMemberAddresses
) {
857 if (!member
.getNumber().isPresent()) {
860 newE164Members
.add(member
.getNumber().get());
863 final var registeredUsers
= getRegisteredUsers(newE164Members
);
864 if (registeredUsers
.size() != newE164Members
.size()) {
865 // Some of the new members are not registered on Signal
866 newE164Members
.removeAll(registeredUsers
.keySet());
867 throw new IOException("Failed to add members "
868 + String
.join(", ", newE164Members
)
869 + " to group: Not registered on Signal");
872 g
.addMembers(members
);
875 if (avatarFile
!= null) {
876 avatarStore
.storeGroupAvatar(g
.getGroupId(),
877 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
881 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
882 GroupInviteLinkUrl inviteLinkUrl
883 ) throws IOException
, GroupLinkNotActiveException
{
884 return sendJoinGroupMessage(inviteLinkUrl
);
887 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
888 GroupInviteLinkUrl inviteLinkUrl
889 ) throws IOException
, GroupLinkNotActiveException
{
890 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
891 inviteLinkUrl
.getPassword());
892 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
893 inviteLinkUrl
.getPassword(),
895 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
896 groupJoinInfo
.getRevision() + 1,
897 groupChange
.toByteArray());
899 if (group
.getGroup() == null) {
900 // Only requested member, can't send update to group members
901 return new Pair
<>(group
.getGroupId(), List
.of());
904 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
906 return new Pair
<>(group
.getGroupId(), result
.second());
909 private static int currentTimeDays() {
910 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
913 private GroupsV2AuthorizationString
getGroupAuthForToday(
914 final GroupSecretParams groupSecretParams
915 ) throws IOException
{
916 final var today
= currentTimeDays();
917 // Returns credentials for the next 7 days
918 final var credentials
= groupsV2Api
.getCredentials(today
);
919 // TODO cache credentials until they expire
920 var authCredentialResponse
= credentials
.get(today
);
922 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
925 authCredentialResponse
);
926 } catch (VerificationFailedException e
) {
927 throw new IOException(e
);
931 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
932 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
933 ) throws IOException
{
934 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
935 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
936 account
.getGroupStore().updateGroup(group
);
937 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
940 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
941 GroupIdV1 groupId
, SignalServiceAddress recipient
942 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
944 var group
= getGroupForSending(groupId
);
945 if (!(group
instanceof GroupInfoV1
)) {
946 throw new RuntimeException("Received an invalid group request for a v2 group!");
948 g
= (GroupInfoV1
) group
;
950 final var recipientId
= resolveRecipient(recipient
);
951 if (!g
.isMember(recipientId
)) {
952 throw new NotAGroupMemberException(groupId
, g
.name
);
955 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
957 // Send group message only to the recipient who requested it
958 return sendMessage(messageBuilder
, Set
.of(recipientId
));
961 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
962 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
963 .withId(g
.getGroupId().serialize())
965 .withMembers(g
.getMembers()
967 .map(this::resolveSignalServiceAddress
)
968 .collect(Collectors
.toList()));
971 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
972 if (attachment
.isPresent()) {
973 group
.withAvatar(attachment
.get());
975 } catch (IOException e
) {
976 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
979 return SignalServiceDataMessage
.newBuilder()
980 .asGroupMessage(group
.build())
981 .withExpiration(g
.getMessageExpirationTime());
984 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
985 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
986 .withRevision(g
.getGroup().getRevision())
987 .withSignedGroupChange(signedGroupChange
);
988 return SignalServiceDataMessage
.newBuilder()
989 .asGroupMessage(group
.build())
990 .withExpiration(g
.getMessageExpirationTime());
993 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
994 GroupIdV1 groupId
, SignalServiceAddress recipient
995 ) throws IOException
{
996 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
998 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
1000 // Send group info request message to the recipient who sent us a message with this groupId
1001 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1005 SignalServiceAddress remoteAddress
, long messageId
1006 ) throws IOException
, UntrustedIdentityException
{
1007 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1009 System
.currentTimeMillis());
1011 createMessageSender().sendReceipt(remoteAddress
,
1012 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1016 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1017 String messageText
, List
<String
> attachments
, List
<String
> recipients
1018 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1019 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1020 if (attachments
!= null) {
1021 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1023 // Upload attachments here, so we only upload once even for multiple recipients
1024 var messageSender
= createMessageSender();
1025 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1026 for (var attachment
: attachmentStreams
) {
1027 if (attachment
.isStream()) {
1028 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1029 } else if (attachment
.isPointer()) {
1030 attachmentPointers
.add(attachment
.asPointer());
1034 messageBuilder
.withAttachments(attachmentPointers
);
1036 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1039 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1040 String messageText
, List
<String
> attachments
1041 ) throws IOException
, AttachmentInvalidException
{
1042 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1043 if (attachments
!= null) {
1044 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1046 return sendSelfMessage(messageBuilder
);
1049 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1050 long targetSentTimestamp
, List
<String
> recipients
1051 ) throws IOException
, InvalidNumberException
{
1052 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1053 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1054 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1057 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1058 long targetSentTimestamp
, GroupId groupId
1059 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1060 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1061 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1062 return sendGroupMessage(messageBuilder
, groupId
);
1065 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1066 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1067 ) throws IOException
, InvalidNumberException
{
1068 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1069 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1071 resolveSignalServiceAddress(targetAuthorRecipientId
),
1072 targetSentTimestamp
);
1073 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1074 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1077 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1078 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1080 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1082 return sendMessage(messageBuilder
, signalServiceAddresses
);
1083 } catch (Exception e
) {
1084 for (var address
: signalServiceAddresses
) {
1085 handleEndSession(address
);
1091 SendMessageResult
renewSession(RecipientId recipientId
) throws IOException
{
1092 account
.getSessionStore().archiveSessions(recipientId
);
1093 return sendNullMessage(recipientId
);
1096 public String
getContactName(String number
) throws InvalidNumberException
{
1097 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1098 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1101 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1102 if (!account
.isMasterDevice()) {
1103 throw new NotMasterDeviceException();
1105 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1106 var contact
= account
.getContactStore().getContact(recipientId
);
1107 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1108 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1111 public void setContactBlocked(
1112 String number
, boolean blocked
1113 ) throws InvalidNumberException
, NotMasterDeviceException
{
1114 if (!account
.isMasterDevice()) {
1115 throw new NotMasterDeviceException();
1117 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1120 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1121 var contact
= account
.getContactStore().getContact(recipientId
);
1122 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1123 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1126 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1127 var group
= getGroup(groupId
);
1128 if (group
== null) {
1129 throw new GroupNotFoundException(groupId
);
1132 group
.setBlocked(blocked
);
1133 account
.getGroupStore().updateGroup(group
);
1136 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1137 var contact
= account
.getContactStore().getContact(recipientId
);
1138 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1141 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1142 account
.getContactStore()
1143 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1146 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1147 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1148 sendMessage(messageBuilder
, Set
.of(recipientId
));
1152 * Change the expiration timer for a contact
1154 public void setExpirationTimer(
1155 String number
, int messageExpirationTimer
1156 ) throws IOException
, InvalidNumberException
{
1157 var recipientId
= canonicalizeAndResolveRecipient(number
);
1158 setExpirationTimer(recipientId
, messageExpirationTimer
);
1159 sendExpirationTimerUpdate(recipientId
);
1163 * Change the expiration timer for a group
1165 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1166 var g
= getGroup(groupId
);
1167 if (g
instanceof GroupInfoV1
) {
1168 var groupInfoV1
= (GroupInfoV1
) g
;
1169 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1170 account
.getGroupStore().updateGroup(groupInfoV1
);
1172 throw new RuntimeException("TODO Not implemented!");
1177 * Upload the sticker pack from path.
1179 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1180 * @return if successful, returns the URL to install the sticker pack in the signal app
1182 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1183 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1185 var messageSender
= createMessageSender();
1187 var packKey
= KeyUtils
.createStickerUploadKey();
1188 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1190 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1191 account
.getStickerStore().updateSticker(sticker
);
1194 return new URI("https",
1197 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1198 Hex
.toStringCondensed(packKey
),
1199 StandardCharsets
.UTF_8
)).toString();
1200 } catch (URISyntaxException e
) {
1201 throw new AssertionError(e
);
1205 public void requestAllSyncData() throws IOException
{
1206 requestSyncGroups();
1207 requestSyncContacts();
1208 requestSyncBlocked();
1209 requestSyncConfiguration();
1213 private void requestSyncGroups() throws IOException
{
1214 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1215 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1217 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1219 sendSyncMessage(message
);
1220 } catch (UntrustedIdentityException e
) {
1221 throw new AssertionError(e
);
1225 private void requestSyncContacts() throws IOException
{
1226 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1227 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1229 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1231 sendSyncMessage(message
);
1232 } catch (UntrustedIdentityException e
) {
1233 throw new AssertionError(e
);
1237 private void requestSyncBlocked() throws IOException
{
1238 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1239 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1241 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1243 sendSyncMessage(message
);
1244 } catch (UntrustedIdentityException e
) {
1245 throw new AssertionError(e
);
1249 private void requestSyncConfiguration() throws IOException
{
1250 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1251 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1253 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1255 sendSyncMessage(message
);
1256 } catch (UntrustedIdentityException e
) {
1257 throw new AssertionError(e
);
1261 private void requestSyncKeys() throws IOException
{
1262 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1263 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1265 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1267 sendSyncMessage(message
);
1268 } catch (UntrustedIdentityException e
) {
1269 throw new AssertionError(e
);
1273 private byte[] getSenderCertificate() {
1274 // TODO support UUID capable sender certificates
1275 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1278 certificate
= accountManager
.getSenderCertificate();
1279 } catch (IOException e
) {
1280 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1283 // TODO cache for a day
1287 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1288 var messageSender
= createMessageSender();
1289 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1292 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1293 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1294 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1296 for (var number
: numbers
) {
1297 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1298 if (resolvedAddress
.getUuid().isPresent()) {
1299 signalServiceAddresses
.add(resolvedAddress
);
1301 addressesMissingUuid
.add(resolvedAddress
);
1305 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1306 .map(a
-> a
.getNumber().get())
1307 .collect(Collectors
.toSet());
1308 Map
<String
, UUID
> registeredUsers
;
1310 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1311 } catch (IOException e
) {
1312 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1313 registeredUsers
= Map
.of();
1316 for (var address
: addressesMissingUuid
) {
1317 final var number
= address
.getNumber().get();
1318 if (registeredUsers
.containsKey(number
)) {
1319 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1320 registeredUsers
.get(number
),
1322 signalServiceAddresses
.add(newAddress
);
1324 signalServiceAddresses
.add(address
);
1328 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1331 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1332 final var address
= resolveSignalServiceAddress(recipientId
);
1333 if (!address
.getNumber().isPresent()) {
1336 final var number
= address
.getNumber().get();
1337 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1338 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1341 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1343 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1345 serviceEnvironmentConfig
.getCdsMrenclave());
1346 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1347 throw new IOException(e
);
1351 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1352 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1353 ) throws IOException
{
1354 final var timestamp
= System
.currentTimeMillis();
1355 messageBuilder
.withTimestamp(timestamp
);
1356 getOrCreateMessagePipe();
1357 getOrCreateUnidentifiedMessagePipe();
1358 SignalServiceDataMessage message
= null;
1360 message
= messageBuilder
.build();
1361 if (message
.getGroupContext().isPresent()) {
1363 var messageSender
= createMessageSender();
1364 final var isRecipientUpdate
= false;
1365 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1366 final var addresses
= recipientIdList
.stream()
1367 .map(this::resolveSignalServiceAddress
)
1368 .collect(Collectors
.toList());
1369 var result
= messageSender
.sendMessage(addresses
,
1370 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1374 for (var r
: result
) {
1375 if (r
.getIdentityFailure() != null) {
1376 final var recipientId
= resolveRecipient(r
.getAddress());
1377 final var newIdentity
= account
.getIdentityKeyStore()
1378 .saveIdentity(recipientId
, r
.getIdentityFailure().getIdentityKey(), new Date());
1380 account
.getSessionStore().archiveSessions(recipientId
);
1385 return new Pair
<>(timestamp
, result
);
1386 } catch (UntrustedIdentityException e
) {
1387 return new Pair
<>(timestamp
, List
.of());
1390 // Send to all individually, so sync messages are sent correctly
1391 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1392 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1393 for (var recipientId
: recipientIds
) {
1394 final var contact
= account
.getContactStore().getContact(recipientId
);
1395 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1396 messageBuilder
.withExpiration(expirationTime
);
1397 message
= messageBuilder
.build();
1398 results
.add(sendMessage(recipientId
, message
));
1400 return new Pair
<>(timestamp
, results
);
1403 if (message
!= null && message
.isEndSession()) {
1404 for (var recipient
: recipientIds
) {
1405 handleEndSession(recipient
);
1411 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1412 SignalServiceDataMessage
.Builder messageBuilder
1413 ) throws IOException
{
1414 final var timestamp
= System
.currentTimeMillis();
1415 messageBuilder
.withTimestamp(timestamp
);
1416 getOrCreateMessagePipe();
1417 getOrCreateUnidentifiedMessagePipe();
1418 final var recipientId
= account
.getSelfRecipientId();
1420 final var contact
= account
.getContactStore().getContact(recipientId
);
1421 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1422 messageBuilder
.withExpiration(expirationTime
);
1424 var message
= messageBuilder
.build();
1425 final var result
= sendSelfMessage(message
);
1426 return new Pair
<>(timestamp
, result
);
1429 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1430 var messageSender
= createMessageSender();
1432 var recipientId
= account
.getSelfRecipientId();
1434 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipientId
);
1435 var recipient
= resolveSignalServiceAddress(recipientId
);
1436 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1437 message
.getTimestamp(),
1439 message
.getExpiresInSeconds(),
1440 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1442 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1445 var startTime
= System
.currentTimeMillis();
1446 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1447 return SendMessageResult
.success(recipient
,
1448 unidentifiedAccess
.isPresent(),
1450 System
.currentTimeMillis() - startTime
);
1451 } catch (UntrustedIdentityException e
) {
1452 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1456 private SendMessageResult
sendMessage(
1457 RecipientId recipientId
, SignalServiceDataMessage message
1458 ) throws IOException
{
1459 var messageSender
= createMessageSender();
1461 final var address
= resolveSignalServiceAddress(recipientId
);
1464 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
), message
);
1465 } catch (UnregisteredUserException e
) {
1466 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1467 return messageSender
.sendMessage(resolveSignalServiceAddress(newRecipientId
),
1468 unidentifiedAccessHelper
.getAccessFor(newRecipientId
),
1471 } catch (UntrustedIdentityException e
) {
1472 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1476 private SendMessageResult
sendNullMessage(RecipientId recipientId
) throws IOException
{
1477 var messageSender
= createMessageSender();
1479 final var address
= resolveSignalServiceAddress(recipientId
);
1482 return messageSender
.sendNullMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
));
1483 } catch (UnregisteredUserException e
) {
1484 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1485 final var newAddress
= resolveSignalServiceAddress(newRecipientId
);
1486 return messageSender
.sendNullMessage(newAddress
, unidentifiedAccessHelper
.getAccessFor(newRecipientId
));
1488 } catch (UntrustedIdentityException e
) {
1489 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1493 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1494 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1495 account
.getSignalProtocolStore(),
1496 certificateValidator
);
1498 return cipher
.decrypt(envelope
);
1499 } catch (ProtocolUntrustedIdentityException e
) {
1500 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1501 throw (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1503 throw new AssertionError(e
);
1507 private void handleEndSession(RecipientId recipientId
) {
1508 account
.getSessionStore().deleteAllSessions(recipientId
);
1511 private List
<HandleAction
> handleSignalServiceDataMessage(
1512 SignalServiceDataMessage message
,
1514 SignalServiceAddress source
,
1515 SignalServiceAddress destination
,
1516 boolean ignoreAttachments
1518 var actions
= new ArrayList
<HandleAction
>();
1519 if (message
.getGroupContext().isPresent()) {
1520 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1521 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1522 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1523 var group
= getGroup(groupId
);
1524 if (group
== null || group
instanceof GroupInfoV1
) {
1525 var groupV1
= (GroupInfoV1
) group
;
1526 switch (groupInfo
.getType()) {
1528 if (groupV1
== null) {
1529 groupV1
= new GroupInfoV1(groupId
);
1532 if (groupInfo
.getAvatar().isPresent()) {
1533 var avatar
= groupInfo
.getAvatar().get();
1534 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1537 if (groupInfo
.getName().isPresent()) {
1538 groupV1
.name
= groupInfo
.getName().get();
1541 if (groupInfo
.getMembers().isPresent()) {
1542 groupV1
.addMembers(groupInfo
.getMembers()
1545 .map(this::resolveRecipient
)
1546 .collect(Collectors
.toSet()));
1549 account
.getGroupStore().updateGroup(groupV1
);
1553 if (groupV1
== null && !isSync
) {
1554 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1558 if (groupV1
!= null) {
1559 groupV1
.removeMember(resolveRecipient(source
));
1560 account
.getGroupStore().updateGroup(groupV1
);
1565 if (groupV1
!= null && !isSync
) {
1566 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1571 // Received a group v1 message for a v2 group
1574 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1575 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1576 final var groupMasterKey
= groupContext
.getMasterKey();
1578 getOrMigrateGroup(groupMasterKey
,
1579 groupContext
.getRevision(),
1580 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1584 final var conversationPartnerAddress
= isSync ? destination
: source
;
1585 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1586 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1588 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1589 if (message
.getGroupContext().isPresent()) {
1590 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1591 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1592 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1593 if (group
!= null) {
1594 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1595 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1596 account
.getGroupStore().updateGroup(group
);
1599 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1600 // disappearing message timer already stored in the DecryptedGroup
1602 } else if (conversationPartnerAddress
!= null) {
1603 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1606 if (!ignoreAttachments
) {
1607 if (message
.getAttachments().isPresent()) {
1608 for (var attachment
: message
.getAttachments().get()) {
1609 downloadAttachment(attachment
);
1612 if (message
.getSharedContacts().isPresent()) {
1613 for (var contact
: message
.getSharedContacts().get()) {
1614 if (contact
.getAvatar().isPresent()) {
1615 downloadAttachment(contact
.getAvatar().get().getAttachment());
1620 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1621 final ProfileKey profileKey
;
1623 profileKey
= new ProfileKey(message
.getProfileKey().get());
1624 } catch (InvalidInputException e
) {
1625 throw new AssertionError(e
);
1627 if (source
.matches(account
.getSelfAddress())) {
1628 this.account
.setProfileKey(profileKey
);
1630 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1632 if (message
.getPreviews().isPresent()) {
1633 final var previews
= message
.getPreviews().get();
1634 for (var preview
: previews
) {
1635 if (preview
.getImage().isPresent()) {
1636 downloadAttachment(preview
.getImage().get());
1640 if (message
.getQuote().isPresent()) {
1641 final var quote
= message
.getQuote().get();
1643 for (var quotedAttachment
: quote
.getAttachments()) {
1644 final var thumbnail
= quotedAttachment
.getThumbnail();
1645 if (thumbnail
!= null) {
1646 downloadAttachment(thumbnail
);
1650 if (message
.getSticker().isPresent()) {
1651 final var messageSticker
= message
.getSticker().get();
1652 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1653 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1654 if (sticker
== null) {
1655 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1656 account
.getStickerStore().updateSticker(sticker
);
1662 private GroupInfoV2
getOrMigrateGroup(
1663 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1665 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1667 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1668 var groupInfo
= getGroup(groupId
);
1669 final GroupInfoV2 groupInfoV2
;
1670 if (groupInfo
instanceof GroupInfoV1
) {
1671 // Received a v2 group message for a v1 group, we need to locally migrate the group
1672 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1673 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1674 logger
.info("Locally migrated group {} to group v2, id: {}",
1675 groupInfo
.getGroupId().toBase64(),
1676 groupInfoV2
.getGroupId().toBase64());
1677 } else if (groupInfo
instanceof GroupInfoV2
) {
1678 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1680 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1683 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1684 DecryptedGroup group
= null;
1685 if (signedGroupChange
!= null
1686 && groupInfoV2
.getGroup() != null
1687 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1688 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1690 if (group
== null) {
1691 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1693 if (group
!= null) {
1694 storeProfileKeysFromMembers(group
);
1695 final var avatar
= group
.getAvatar();
1696 if (avatar
!= null && !avatar
.isEmpty()) {
1697 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1700 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1701 account
.getGroupStore().updateGroup(groupInfoV2
);
1707 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1708 for (var member
: group
.getMembersList()) {
1709 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
1710 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
1712 account
.getProfileStore()
1713 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
1714 } catch (InvalidInputException ignored
) {
1719 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1720 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1721 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1722 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1723 if (actions
!= null) {
1724 queuedActions
.addAll(actions
);
1727 for (var action
: queuedActions
) {
1729 action
.execute(this);
1730 } catch (Throwable e
) {
1731 logger
.warn("Message action failed.", e
);
1736 private List
<HandleAction
> retryFailedReceivedMessage(
1737 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1739 var envelope
= cachedMessage
.loadEnvelope();
1740 if (envelope
== null) {
1743 SignalServiceContent content
= null;
1744 List
<HandleAction
> actions
= null;
1745 if (!envelope
.isReceipt()) {
1747 content
= decryptMessage(envelope
);
1748 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1749 if (!envelope
.hasSource()) {
1750 final var identifier
= ((org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
).getName();
1751 final var recipientId
= resolveRecipient(identifier
);
1753 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1754 } catch (IOException ioException
) {
1755 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1759 } catch (Exception er
) {
1760 // All other errors are not recoverable, so delete the cached message
1761 cachedMessage
.delete();
1764 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1766 handler
.handleMessage(envelope
, content
, null);
1767 cachedMessage
.delete();
1771 public void receiveMessages(
1774 boolean returnOnTimeout
,
1775 boolean ignoreAttachments
,
1776 ReceiveMessageHandler handler
1777 ) throws IOException
{
1778 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1780 Set
<HandleAction
> queuedActions
= null;
1782 final var messagePipe
= getOrCreateMessagePipe();
1784 var hasCaughtUpWithOldMessages
= false;
1787 SignalServiceEnvelope envelope
;
1788 SignalServiceContent content
= null;
1789 Exception exception
= null;
1790 final CachedMessage
[] cachedMessage
= {null};
1792 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1793 final var recipientId
= envelope1
.hasSource()
1794 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1796 // store message on disk, before acknowledging receipt to the server
1797 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1799 if (result
.isPresent()) {
1800 envelope
= result
.get();
1802 // Received indicator that server queue is empty
1803 hasCaughtUpWithOldMessages
= true;
1805 if (queuedActions
!= null) {
1806 for (var action
: queuedActions
) {
1808 action
.execute(this);
1809 } catch (Throwable e
) {
1810 logger
.warn("Message action failed.", e
);
1813 queuedActions
.clear();
1814 queuedActions
= null;
1817 // Continue to wait another timeout for new messages
1820 } catch (TimeoutException e
) {
1821 if (returnOnTimeout
) return;
1825 if (envelope
.hasSource()) {
1826 // Store uuid if we don't have it already
1827 resolveRecipientTrusted(envelope
.getSourceAddress());
1829 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1830 if (!envelope
.isReceipt()) {
1832 content
= decryptMessage(envelope
);
1833 } catch (Exception e
) {
1836 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1837 if (exception
instanceof ProtocolInvalidMessageException
) {
1838 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
1839 logger
.debug("Received invalid message, queuing renew session action.");
1840 actions
.add(new RenewSessionAction(sender
));
1842 if (hasCaughtUpWithOldMessages
) {
1843 for (var action
: actions
) {
1845 action
.execute(this);
1846 } catch (Throwable e
) {
1847 logger
.warn("Message action failed.", e
);
1851 if (queuedActions
== null) {
1852 queuedActions
= new HashSet
<>();
1854 queuedActions
.addAll(actions
);
1857 if (isMessageBlocked(envelope
, content
)) {
1858 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1859 } else if (notAGroupMember
) {
1860 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1862 handler
.handleMessage(envelope
, content
, exception
);
1864 if (cachedMessage
[0] != null) {
1865 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1866 final var identifier
= ((org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
).getName();
1867 final var recipientId
= resolveRecipient(identifier
);
1868 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1869 if (!envelope
.hasSource()) {
1871 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1872 } catch (IOException ioException
) {
1873 logger
.warn("Failed to move cached message to recipient folder: {}",
1874 ioException
.getMessage());
1878 cachedMessage
[0].delete();
1884 private boolean isMessageBlocked(
1885 SignalServiceEnvelope envelope
, SignalServiceContent content
1887 SignalServiceAddress source
;
1888 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1889 source
= envelope
.getSourceAddress();
1890 } else if (content
!= null) {
1891 source
= content
.getSender();
1895 final var recipientId
= resolveRecipient(source
);
1896 if (isContactBlocked(recipientId
)) {
1900 if (content
!= null && content
.getDataMessage().isPresent()) {
1901 var message
= content
.getDataMessage().get();
1902 if (message
.getGroupContext().isPresent()) {
1903 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1904 var group
= getGroup(groupId
);
1905 if (group
!= null && group
.isBlocked()) {
1913 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
1914 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
1915 return isContactBlocked(recipientId
);
1918 private boolean isContactBlocked(final RecipientId recipientId
) {
1919 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1920 return sourceContact
!= null && sourceContact
.isBlocked();
1923 private boolean isNotAGroupMember(
1924 SignalServiceEnvelope envelope
, SignalServiceContent content
1926 SignalServiceAddress source
;
1927 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1928 source
= envelope
.getSourceAddress();
1929 } else if (content
!= null) {
1930 source
= content
.getSender();
1935 if (content
!= null && content
.getDataMessage().isPresent()) {
1936 var message
= content
.getDataMessage().get();
1937 if (message
.getGroupContext().isPresent()) {
1938 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1939 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1940 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1944 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1945 var group
= getGroup(groupId
);
1946 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
1954 private List
<HandleAction
> handleMessage(
1955 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1957 var actions
= new ArrayList
<HandleAction
>();
1958 if (content
!= null) {
1959 final SignalServiceAddress sender
;
1960 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1961 sender
= envelope
.getSourceAddress();
1963 sender
= content
.getSender();
1966 if (content
.getDataMessage().isPresent()) {
1967 var message
= content
.getDataMessage().get();
1969 if (content
.isNeedsReceipt()) {
1970 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1973 actions
.addAll(handleSignalServiceDataMessage(message
,
1976 account
.getSelfAddress(),
1977 ignoreAttachments
));
1979 if (content
.getSyncMessage().isPresent()) {
1980 account
.setMultiDevice(true);
1981 var syncMessage
= content
.getSyncMessage().get();
1982 if (syncMessage
.getSent().isPresent()) {
1983 var message
= syncMessage
.getSent().get();
1984 final var destination
= message
.getDestination().orNull();
1985 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1989 ignoreAttachments
));
1991 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
1992 var rm
= syncMessage
.getRequest().get();
1993 if (rm
.isContactsRequest()) {
1994 actions
.add(SendSyncContactsAction
.create());
1996 if (rm
.isGroupsRequest()) {
1997 actions
.add(SendSyncGroupsAction
.create());
1999 if (rm
.isBlockedListRequest()) {
2000 actions
.add(SendSyncBlockedListAction
.create());
2002 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2004 if (syncMessage
.getGroups().isPresent()) {
2005 File tmpFile
= null;
2007 tmpFile
= IOUtils
.createTempFile();
2008 final var groupsMessage
= syncMessage
.getGroups().get();
2009 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2010 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2012 while ((g
= s
.read()) != null) {
2013 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2014 if (syncGroup
!= null) {
2015 if (g
.getName().isPresent()) {
2016 syncGroup
.name
= g
.getName().get();
2018 syncGroup
.addMembers(g
.getMembers()
2020 .map(this::resolveRecipient
)
2021 .collect(Collectors
.toSet()));
2022 if (!g
.isActive()) {
2023 syncGroup
.removeMember(account
.getSelfRecipientId());
2025 // Add ourself to the member set as it's marked as active
2026 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2028 syncGroup
.blocked
= g
.isBlocked();
2029 if (g
.getColor().isPresent()) {
2030 syncGroup
.color
= g
.getColor().get();
2033 if (g
.getAvatar().isPresent()) {
2034 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2036 syncGroup
.archived
= g
.isArchived();
2037 account
.getGroupStore().updateGroup(syncGroup
);
2041 } catch (Exception e
) {
2042 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2046 if (tmpFile
!= null) {
2048 Files
.delete(tmpFile
.toPath());
2049 } catch (IOException e
) {
2050 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2057 if (syncMessage
.getBlockedList().isPresent()) {
2058 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2059 for (var address
: blockedListMessage
.getAddresses()) {
2060 setContactBlocked(resolveRecipient(address
), true);
2062 for (var groupId
: blockedListMessage
.getGroupIds()
2064 .map(GroupId
::unknownVersion
)
2065 .collect(Collectors
.toSet())) {
2067 setGroupBlocked(groupId
, true);
2068 } catch (GroupNotFoundException e
) {
2069 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2070 groupId
.toBase64());
2074 if (syncMessage
.getContacts().isPresent()) {
2075 File tmpFile
= null;
2077 tmpFile
= IOUtils
.createTempFile();
2078 final var contactsMessage
= syncMessage
.getContacts().get();
2079 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2080 .asPointer(), tmpFile
)) {
2081 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2083 while ((c
= s
.read()) != null) {
2084 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2085 account
.setProfileKey(c
.getProfileKey().get());
2087 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2088 var contact
= account
.getContactStore().getContact(recipientId
);
2089 final var builder
= contact
== null
2090 ? Contact
.newBuilder()
2091 : Contact
.newBuilder(contact
);
2092 if (c
.getName().isPresent()) {
2093 builder
.withName(c
.getName().get());
2095 if (c
.getColor().isPresent()) {
2096 builder
.withColor(c
.getColor().get());
2098 if (c
.getProfileKey().isPresent()) {
2099 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2101 if (c
.getVerified().isPresent()) {
2102 final var verifiedMessage
= c
.getVerified().get();
2103 account
.getIdentityKeyStore()
2104 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2105 verifiedMessage
.getIdentityKey(),
2106 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2108 if (c
.getExpirationTimer().isPresent()) {
2109 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2111 builder
.withBlocked(c
.isBlocked());
2112 builder
.withArchived(c
.isArchived());
2113 account
.getContactStore().storeContact(recipientId
, builder
.build());
2115 if (c
.getAvatar().isPresent()) {
2116 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2120 } catch (Exception e
) {
2121 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2125 if (tmpFile
!= null) {
2127 Files
.delete(tmpFile
.toPath());
2128 } catch (IOException e
) {
2129 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2136 if (syncMessage
.getVerified().isPresent()) {
2137 final var verifiedMessage
= syncMessage
.getVerified().get();
2138 account
.getIdentityKeyStore()
2139 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2140 verifiedMessage
.getIdentityKey(),
2141 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2143 if (syncMessage
.getStickerPackOperations().isPresent()) {
2144 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2145 for (var m
: stickerPackOperationMessages
) {
2146 if (!m
.getPackId().isPresent()) {
2149 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2150 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2151 if (sticker
== null) {
2152 if (!m
.getPackKey().isPresent()) {
2155 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2157 sticker
.setInstalled(!m
.getType().isPresent()
2158 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2159 account
.getStickerStore().updateSticker(sticker
);
2162 if (syncMessage
.getFetchType().isPresent()) {
2163 switch (syncMessage
.getFetchType().get()) {
2165 getRecipientProfile(account
.getSelfRecipientId(), true);
2166 case STORAGE_MANIFEST
:
2170 if (syncMessage
.getKeys().isPresent()) {
2171 final var keysMessage
= syncMessage
.getKeys().get();
2172 if (keysMessage
.getStorageService().isPresent()) {
2173 final var storageKey
= keysMessage
.getStorageService().get();
2174 account
.setStorageKey(storageKey
);
2177 if (syncMessage
.getConfiguration().isPresent()) {
2185 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2187 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2188 } catch (IOException e
) {
2189 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2193 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2195 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2196 } catch (IOException e
) {
2197 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2201 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2203 avatarStore
.storeGroupAvatar(groupId
,
2204 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2205 } catch (IOException e
) {
2206 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2210 private void downloadProfileAvatar(
2211 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2214 avatarStore
.storeProfileAvatar(address
,
2215 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2216 } catch (Throwable e
) {
2217 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2221 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2222 return attachmentStore
.getAttachmentFile(attachmentId
);
2225 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2226 if (!attachment
.isPointer()) {
2227 logger
.warn("Invalid state, can't store an attachment stream.");
2230 var pointer
= attachment
.asPointer();
2231 if (pointer
.getPreview().isPresent()) {
2232 final var preview
= pointer
.getPreview().get();
2234 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2235 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2236 } catch (IOException e
) {
2237 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2242 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2243 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2244 } catch (IOException e
) {
2245 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2249 private void retrieveGroupV2Avatar(
2250 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2251 ) throws IOException
{
2252 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2254 var tmpFile
= IOUtils
.createTempFile();
2255 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2257 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2258 var encryptedData
= IOUtils
.readFully(input
);
2260 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2261 outputStream
.write(decryptedData
);
2264 Files
.delete(tmpFile
.toPath());
2265 } catch (IOException e
) {
2266 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2273 private void retrieveProfileAvatar(
2274 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2275 ) throws IOException
{
2276 var tmpFile
= IOUtils
.createTempFile();
2277 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2280 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2281 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2282 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2285 Files
.delete(tmpFile
.toPath());
2286 } catch (IOException e
) {
2287 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2294 private void retrieveAttachment(
2295 final SignalServiceAttachment attachment
, final OutputStream outputStream
2296 ) throws IOException
{
2297 if (attachment
.isPointer()) {
2298 var pointer
= attachment
.asPointer();
2299 retrieveAttachmentPointer(pointer
, outputStream
);
2301 var stream
= attachment
.asStream();
2302 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2306 private void retrieveAttachmentPointer(
2307 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2308 ) throws IOException
{
2309 var tmpFile
= IOUtils
.createTempFile();
2310 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2311 IOUtils
.copyStream(input
, outputStream
);
2312 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2313 throw new IOException(e
);
2316 Files
.delete(tmpFile
.toPath());
2317 } catch (IOException e
) {
2318 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2325 private InputStream
retrieveAttachmentAsStream(
2326 SignalServiceAttachmentPointer pointer
, File tmpFile
2327 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2328 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2331 void sendGroups() throws IOException
, UntrustedIdentityException
{
2332 var groupsFile
= IOUtils
.createTempFile();
2335 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2336 var out
= new DeviceGroupsOutputStream(fos
);
2337 for (var record : getGroups()) {
2338 if (record instanceof GroupInfoV1
) {
2339 var groupInfo
= (GroupInfoV1
) record;
2340 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2341 Optional
.fromNullable(groupInfo
.name
),
2342 groupInfo
.getMembers()
2344 .map(this::resolveSignalServiceAddress
)
2345 .collect(Collectors
.toList()),
2346 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2347 groupInfo
.isMember(account
.getSelfRecipientId()),
2348 Optional
.of(groupInfo
.messageExpirationTime
),
2349 Optional
.fromNullable(groupInfo
.color
),
2352 groupInfo
.archived
));
2357 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2358 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2359 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2360 .withStream(groupsFileStream
)
2361 .withContentType("application/octet-stream")
2362 .withLength(groupsFile
.length())
2365 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2370 Files
.delete(groupsFile
.toPath());
2371 } catch (IOException e
) {
2372 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2377 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2378 var contactsFile
= IOUtils
.createTempFile();
2381 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2382 var out
= new DeviceContactsOutputStream(fos
);
2383 for (var contactPair
: account
.getContactStore().getContacts()) {
2384 final var recipientId
= contactPair
.first();
2385 final var contact
= contactPair
.second();
2386 final var address
= resolveSignalServiceAddress(recipientId
);
2388 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2389 VerifiedMessage verifiedMessage
= null;
2390 if (currentIdentity
!= null) {
2391 verifiedMessage
= new VerifiedMessage(address
,
2392 currentIdentity
.getIdentityKey(),
2393 currentIdentity
.getTrustLevel().toVerifiedState(),
2394 currentIdentity
.getDateAdded().getTime());
2397 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2398 out
.write(new DeviceContact(address
,
2399 Optional
.fromNullable(contact
.getName()),
2400 createContactAvatarAttachment(address
),
2401 Optional
.fromNullable(contact
.getColor()),
2402 Optional
.fromNullable(verifiedMessage
),
2403 Optional
.fromNullable(profileKey
),
2404 contact
.isBlocked(),
2405 Optional
.of(contact
.getMessageExpirationTime()),
2407 contact
.isArchived()));
2410 if (account
.getProfileKey() != null) {
2411 // Send our own profile key as well
2412 out
.write(new DeviceContact(account
.getSelfAddress(),
2417 Optional
.of(account
.getProfileKey()),
2425 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2426 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2427 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2428 .withStream(contactsFileStream
)
2429 .withContentType("application/octet-stream")
2430 .withLength(contactsFile
.length())
2433 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2438 Files
.delete(contactsFile
.toPath());
2439 } catch (IOException e
) {
2440 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2445 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2446 var addresses
= new ArrayList
<SignalServiceAddress
>();
2447 for (var record : account
.getContactStore().getContacts()) {
2448 if (record.second().isBlocked()) {
2449 addresses
.add(resolveSignalServiceAddress(record.first()));
2452 var groupIds
= new ArrayList
<byte[]>();
2453 for (var record : getGroups()) {
2454 if (record.isBlocked()) {
2455 groupIds
.add(record.getGroupId().serialize());
2458 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2461 private void sendVerifiedMessage(
2462 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2463 ) throws IOException
, UntrustedIdentityException
{
2464 var verifiedMessage
= new VerifiedMessage(destination
,
2466 trustLevel
.toVerifiedState(),
2467 System
.currentTimeMillis());
2468 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2471 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2472 return account
.getContactStore().getContacts();
2475 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2476 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2477 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2478 if (recipient
== null) {
2482 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2483 return recipient
.getContact().getName();
2486 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2487 return recipient
.getProfile().getDisplayName();
2493 public GroupInfo
getGroup(GroupId groupId
) {
2494 final var group
= account
.getGroupStore().getGroup(groupId
);
2495 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2496 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2497 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2498 account
.getGroupStore().updateGroup(group
);
2503 public List
<IdentityInfo
> getIdentities() {
2504 return account
.getIdentityKeyStore().getIdentities();
2507 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2508 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2509 return identity
== null ? List
.of() : List
.of(identity
);
2513 * Trust this the identity with this fingerprint
2515 * @param name username of the identity
2516 * @param fingerprint Fingerprint
2518 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2519 var recipientId
= canonicalizeAndResolveRecipient(name
);
2520 return trustIdentity(recipientId
,
2521 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2522 TrustLevel
.TRUSTED_VERIFIED
);
2526 * Trust this the identity with this safety number
2528 * @param name username of the identity
2529 * @param safetyNumber Safety number
2531 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2532 var recipientId
= canonicalizeAndResolveRecipient(name
);
2533 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2534 return trustIdentity(recipientId
,
2535 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2536 TrustLevel
.TRUSTED_VERIFIED
);
2540 * Trust all keys of this identity without verification
2542 * @param name username of the identity
2544 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2545 var recipientId
= canonicalizeAndResolveRecipient(name
);
2546 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2549 private boolean trustIdentity(
2550 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2552 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2553 if (identity
== null) {
2557 if (!verifier
.apply(identity
.getIdentityKey())) {
2561 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2563 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2564 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2565 } catch (IOException
| UntrustedIdentityException e
) {
2566 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2572 public String
computeSafetyNumber(
2573 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2575 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2576 account
.getSelfAddress(),
2577 getIdentityKeyPair().getPublicKey(),
2583 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2584 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2586 return resolveSignalServiceAddress(address
);
2590 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2591 if (address
.matches(account
.getSelfAddress())) {
2592 return account
.getSelfAddress();
2595 return account
.getRecipientStore().resolveServiceAddress(address
);
2598 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2599 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2602 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2603 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2605 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2607 return resolveRecipient(canonicalizedNumber
);
2610 private RecipientId
resolveRecipient(final String identifier
) {
2611 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2613 return resolveRecipient(address
);
2616 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2617 return account
.getRecipientStore().resolveRecipient(address
);
2620 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2621 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2625 public void close() throws IOException
{
2629 void close(boolean closeAccount
) throws IOException
{
2630 executor
.shutdown();
2632 if (messagePipe
!= null) {
2633 messagePipe
.shutdown();
2637 if (unidentifiedMessagePipe
!= null) {
2638 unidentifiedMessagePipe
.shutdown();
2639 unidentifiedMessagePipe
= null;
2642 if (closeAccount
&& account
!= null) {
2648 public interface ReceiveMessageHandler
{
2650 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);