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
.api
.Device
;
20 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
21 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
22 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
23 import org
.asamk
.signal
.manager
.groups
.GroupId
;
24 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
25 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
26 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
27 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
28 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
29 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
30 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
31 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
32 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
33 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
34 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
35 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
36 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
37 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
38 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
39 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
40 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
41 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
42 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
43 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
44 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
45 import org
.asamk
.signal
.manager
.util
.IOUtils
;
46 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
47 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
48 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
49 import org
.asamk
.signal
.manager
.util
.Utils
;
50 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
51 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
52 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
53 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
54 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
56 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
57 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
58 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
59 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
60 import org
.signal
.libsignal
.metadata
.SelfSendException
;
61 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
62 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
63 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
64 import org
.signal
.zkgroup
.InvalidInputException
;
65 import org
.signal
.zkgroup
.VerificationFailedException
;
66 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
67 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
68 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
69 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
70 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
71 import org
.slf4j
.Logger
;
72 import org
.slf4j
.LoggerFactory
;
73 import org
.whispersystems
.libsignal
.IdentityKey
;
74 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
75 import org
.whispersystems
.libsignal
.InvalidKeyException
;
76 import org
.whispersystems
.libsignal
.InvalidMessageException
;
77 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
78 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
79 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
80 import org
.whispersystems
.libsignal
.util
.Pair
;
81 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
82 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
83 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
84 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
85 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
86 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
87 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
88 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
89 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
90 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
91 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
92 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
93 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
94 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
95 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
96 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
104 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
105 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
106 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
107 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
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
.DeviceNameUtil
;
123 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
124 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
125 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
126 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
127 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
128 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
129 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
130 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
131 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
132 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
133 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
134 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
135 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
137 import java
.io
.Closeable
;
139 import java
.io
.FileInputStream
;
140 import java
.io
.FileOutputStream
;
141 import java
.io
.IOException
;
142 import java
.io
.InputStream
;
143 import java
.io
.OutputStream
;
145 import java
.net
.URISyntaxException
;
146 import java
.net
.URLEncoder
;
147 import java
.nio
.charset
.StandardCharsets
;
148 import java
.nio
.file
.Files
;
149 import java
.security
.SignatureException
;
150 import java
.util
.ArrayList
;
151 import java
.util
.Arrays
;
152 import java
.util
.Base64
;
153 import java
.util
.Collection
;
154 import java
.util
.Date
;
155 import java
.util
.HashSet
;
156 import java
.util
.List
;
157 import java
.util
.Map
;
158 import java
.util
.Set
;
159 import java
.util
.UUID
;
160 import java
.util
.concurrent
.ExecutorService
;
161 import java
.util
.concurrent
.Executors
;
162 import java
.util
.concurrent
.TimeUnit
;
163 import java
.util
.concurrent
.TimeoutException
;
164 import java
.util
.function
.Function
;
165 import java
.util
.stream
.Collectors
;
167 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
169 public class Manager
implements Closeable
{
171 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
173 private final CertificateValidator certificateValidator
;
175 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
176 private final String userAgent
;
178 private SignalAccount account
;
179 private final SignalServiceAccountManager accountManager
;
180 private final GroupsV2Api groupsV2Api
;
181 private final GroupsV2Operations groupsV2Operations
;
182 private final SignalServiceMessageReceiver messageReceiver
;
183 private final ClientZkProfileOperations clientZkProfileOperations
;
185 private final ExecutorService executor
= Executors
.newCachedThreadPool();
187 private SignalServiceMessagePipe messagePipe
= null;
188 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
190 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
191 private final ProfileHelper profileHelper
;
192 private final GroupHelper groupHelper
;
193 private final PinHelper pinHelper
;
194 private final AvatarStore avatarStore
;
195 private final AttachmentStore attachmentStore
;
198 SignalAccount account
,
199 PathConfig pathConfig
,
200 ServiceEnvironmentConfig serviceEnvironmentConfig
,
203 this.account
= account
;
204 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
205 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
206 this.userAgent
= userAgent
;
207 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
208 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
209 final SleepTimer timer
= new UptimeSleepTimer();
210 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
211 new DynamicCredentialsProvider(account
.getUuid(),
212 account
.getUsername(),
213 account
.getPassword(),
214 account
.getDeviceId()),
217 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
219 this.groupsV2Api
= accountManager
.getGroupsV2Api();
220 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
221 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
222 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
223 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
226 this.pinHelper
= new PinHelper(keyBackupService
);
227 this.clientZkProfileOperations
= capabilities
.isGv2()
228 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
229 .getProfileOperations()
231 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
233 account
.getUsername(),
234 account
.getPassword(),
235 account
.getDeviceId(),
239 clientZkProfileOperations
,
240 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
242 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
243 account
.getProfileStore()::getProfileKey
,
244 this::getRecipientProfile
,
245 this::getSenderCertificate
);
246 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
247 unidentifiedAccessHelper
::getAccessFor
,
248 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
249 () -> messageReceiver
,
250 this::resolveSignalServiceAddress
);
251 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
252 this::getRecipientProfile
,
253 account
::getSelfRecipientId
,
256 this::getGroupAuthForToday
,
257 this::resolveSignalServiceAddress
);
258 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
259 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
262 public String
getUsername() {
263 return account
.getUsername();
266 public SignalServiceAddress
getSelfAddress() {
267 return account
.getSelfAddress();
270 public RecipientId
getSelfRecipientId() {
271 return account
.getSelfRecipientId();
274 private IdentityKeyPair
getIdentityKeyPair() {
275 return account
.getIdentityKeyPair();
278 public int getDeviceId() {
279 return account
.getDeviceId();
282 public static Manager
init(
283 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
284 ) throws IOException
, NotRegisteredException
{
285 var pathConfig
= PathConfig
.createDefault(settingsPath
);
287 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
288 throw new NotRegisteredException();
291 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true);
293 if (!account
.isRegistered()) {
294 throw new NotRegisteredException();
297 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
299 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
302 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
303 var pathConfig
= PathConfig
.createDefault(settingsPath
);
304 final var dataPath
= pathConfig
.getDataPath();
305 final var files
= dataPath
.listFiles();
311 return Arrays
.stream(files
)
312 .filter(File
::isFile
)
314 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
315 .collect(Collectors
.toList());
318 public void checkAccountState() throws IOException
{
319 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
322 if (account
.getUuid() == null) {
323 account
.setUuid(accountManager
.getOwnUuid());
325 updateAccountAttributes();
329 * This is used for checking a set of phone numbers for registration on Signal
331 * @param numbers The set of phone number in question
332 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
333 * @throws IOException if its unable to get the contacts to check if they're registered
335 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
336 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
337 var contactDetails
= getRegisteredUsers(numbers
);
339 var registeredUsers
= contactDetails
.keySet();
341 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
344 public void updateAccountAttributes() throws IOException
{
345 accountManager
.setAccountAttributes(account
.getEncryptedDeviceName(),
347 account
.getLocalRegistrationId(),
349 // set legacy pin only if no KBS master key is set
350 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
351 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
352 account
.getSelfUnidentifiedAccessKey(),
353 account
.isUnrestrictedUnidentifiedAccess(),
355 account
.isDiscoverableByPhoneNumber());
359 * @param givenName if null, the previous givenName will be kept
360 * @param familyName if null, the previous familyName will be kept
361 * @param about if null, the previous about text will be kept
362 * @param aboutEmoji if null, the previous about emoji will be kept
363 * @param avatar if avatar is null the image from the local avatar store is used (if present),
365 public void setProfile(
366 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
367 ) throws IOException
{
368 var profile
= getRecipientProfile(account
.getSelfRecipientId());
369 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
370 if (givenName
!= null) {
371 builder
.withGivenName(givenName
);
373 if (familyName
!= null) {
374 builder
.withFamilyName(familyName
);
377 builder
.withAbout(about
);
379 if (aboutEmoji
!= null) {
380 builder
.withAboutEmoji(aboutEmoji
);
382 var newProfile
= builder
.build();
384 try (final var streamDetails
= avatar
== null
385 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
386 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
387 accountManager
.setVersionedProfile(account
.getUuid(),
388 account
.getProfileKey(),
389 newProfile
.getInternalServiceName(),
390 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
391 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
395 if (avatar
!= null) {
396 if (avatar
.isPresent()) {
397 avatarStore
.storeProfileAvatar(getSelfAddress(),
398 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
400 avatarStore
.deleteProfileAvatar(getSelfAddress());
403 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
406 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
407 } catch (UntrustedIdentityException ignored
) {
411 public void unregister() throws IOException
{
412 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
413 // If this is the master device, other users can't send messages to this number anymore.
414 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
415 accountManager
.setGcmId(Optional
.absent());
417 account
.setRegistered(false);
420 public void deleteAccount() throws IOException
{
421 accountManager
.deleteAccount();
423 account
.setRegistered(false);
426 public List
<Device
> getLinkedDevices() throws IOException
{
427 var devices
= accountManager
.getDevices();
428 account
.setMultiDevice(devices
.size() > 1);
429 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
430 return devices
.stream().map(d
-> {
431 String deviceName
= d
.getName();
432 if (deviceName
!= null) {
434 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
435 } catch (IOException e
) {
436 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
439 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
440 }).collect(Collectors
.toList());
443 public void removeLinkedDevices(int deviceId
) throws IOException
{
444 accountManager
.removeDevice(deviceId
);
445 var devices
= accountManager
.getDevices();
446 account
.setMultiDevice(devices
.size() > 1);
449 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
450 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
452 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
455 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
456 var identityKeyPair
= getIdentityKeyPair();
457 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
459 accountManager
.addDevice(deviceIdentifier
,
462 Optional
.of(account
.getProfileKey().serialize()),
464 account
.setMultiDevice(true);
467 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
468 if (!account
.isMasterDevice()) {
469 throw new RuntimeException("Only master device can set a PIN");
471 if (pin
.isPresent()) {
472 final var masterKey
= account
.getPinMasterKey() != null
473 ? account
.getPinMasterKey()
474 : KeyUtils
.createMasterKey();
476 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
478 account
.setRegistrationLockPin(pin
.get(), masterKey
);
480 // Remove legacy registration lock
481 accountManager
.removeRegistrationLockV1();
484 pinHelper
.removeRegistrationLockPin();
486 account
.setRegistrationLockPin(null, null);
490 void refreshPreKeys() throws IOException
{
491 var oneTimePreKeys
= generatePreKeys();
492 final var identityKeyPair
= getIdentityKeyPair();
493 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
495 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
498 private List
<PreKeyRecord
> generatePreKeys() {
499 final var offset
= account
.getPreKeyIdOffset();
501 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
502 account
.addPreKeys(records
);
507 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
508 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
510 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
511 account
.addSignedPreKey(record);
516 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
517 if (messagePipe
== null) {
518 messagePipe
= messageReceiver
.createMessagePipe();
523 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
524 if (unidentifiedMessagePipe
== null) {
525 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
527 return unidentifiedMessagePipe
;
530 private SignalServiceMessageSender
createMessageSender() {
531 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
533 account
.getUsername(),
534 account
.getPassword(),
535 account
.getDeviceId(),
536 account
.getSignalProtocolStore(),
538 account
.isMultiDevice(),
539 Optional
.fromNullable(messagePipe
),
540 Optional
.fromNullable(unidentifiedMessagePipe
),
542 clientZkProfileOperations
,
544 ServiceConfig
.MAX_ENVELOPE_SIZE
,
545 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
548 public Profile
getRecipientProfile(
549 RecipientId recipientId
551 return getRecipientProfile(recipientId
, false);
554 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
556 Profile
getRecipientProfile(
557 RecipientId recipientId
, boolean force
559 var profile
= account
.getProfileStore().getProfile(recipientId
);
561 var now
= new Date().getTime();
562 // Profiles are cached for 24h before retrieving them again, unless forced
563 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
567 synchronized (pendingProfileRequest
) {
568 if (pendingProfileRequest
.contains(recipientId
)) {
571 pendingProfileRequest
.add(recipientId
);
573 final SignalServiceProfile encryptedProfile
;
575 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
577 synchronized (pendingProfileRequest
) {
578 pendingProfileRequest
.remove(recipientId
);
581 if (encryptedProfile
== null) {
585 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
586 if (profileKey
== null) {
587 profile
= new Profile(new Date().getTime(),
592 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
593 ProfileUtils
.getCapabilities(encryptedProfile
));
595 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
597 account
.getProfileStore().storeProfile(recipientId
, profile
);
602 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
604 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
605 } catch (IOException e
) {
606 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
611 private ProfileAndCredential
retrieveProfileAndCredential(
612 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
613 ) throws IOException
{
614 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
615 final var profile
= profileAndCredential
.getProfile();
618 var newIdentity
= account
.getIdentityKeyStore()
619 .saveIdentity(recipientId
,
620 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
624 account
.getSessionStore().archiveSessions(recipientId
);
626 } catch (InvalidKeyException ignored
) {
627 logger
.warn("Got invalid identity key in profile for {}",
628 resolveSignalServiceAddress(recipientId
).getLegacyIdentifier());
630 return profileAndCredential
;
633 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
634 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
635 if (profileKeyCredential
!= null) {
636 return profileKeyCredential
;
639 ProfileAndCredential profileAndCredential
;
641 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
642 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
643 } catch (IOException e
) {
644 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
648 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
649 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
651 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
652 if (profileKey
!= null) {
653 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
655 profileAndCredential
.getProfile());
656 account
.getProfileStore().storeProfile(recipientId
, profile
);
659 return profileKeyCredential
;
662 private Profile
decryptProfileAndDownloadAvatar(
663 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
665 if (encryptedProfile
.getAvatar() != null) {
666 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
669 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
672 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
673 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
674 if (streamDetails
== null) {
675 return Optional
.absent();
678 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
681 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
682 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
683 if (streamDetails
== null) {
684 return Optional
.absent();
687 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
690 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
691 var g
= getGroup(groupId
);
693 throw new GroupNotFoundException(groupId
);
695 if (!g
.isMember(account
.getSelfRecipientId())) {
696 throw new NotAGroupMemberException(groupId
, g
.getTitle());
701 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
702 var g
= getGroup(groupId
);
704 throw new GroupNotFoundException(groupId
);
706 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
707 throw new NotAGroupMemberException(groupId
, g
.getTitle());
712 public List
<GroupInfo
> getGroups() {
713 return account
.getGroupStore().getGroups();
716 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
717 String messageText
, List
<String
> attachments
, GroupId groupId
718 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
719 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
720 if (attachments
!= null) {
721 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
724 return sendGroupMessage(messageBuilder
, groupId
);
727 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
728 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
729 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
730 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
731 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
733 resolveSignalServiceAddress(targetAuthorRecipientId
),
734 targetSentTimestamp
);
735 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
737 return sendGroupMessage(messageBuilder
, groupId
);
740 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
741 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
742 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
743 final var g
= getGroupForSending(groupId
);
745 GroupUtils
.setGroupContext(messageBuilder
, g
);
746 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
748 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
751 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
752 SignalServiceDataMessage
.Builder messageBuilder
;
754 final var g
= getGroupForUpdating(groupId
);
755 if (g
instanceof GroupInfoV1
) {
756 var groupInfoV1
= (GroupInfoV1
) g
;
757 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
758 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
759 groupInfoV1
.removeMember(account
.getSelfRecipientId());
760 account
.getGroupStore().updateGroup(groupInfoV1
);
762 final var groupInfoV2
= (GroupInfoV2
) g
;
763 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
764 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
765 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
766 account
.getGroupStore().updateGroup(groupInfoV2
);
769 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
772 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
773 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
774 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
775 return sendUpdateGroupMessage(groupId
,
777 members
== null ?
null : getSignalServiceAddresses(members
),
781 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
782 GroupId groupId
, String name
, Set
<RecipientId
> members
, File avatarFile
783 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
785 SignalServiceDataMessage
.Builder messageBuilder
;
786 if (groupId
== null) {
788 var gv2Pair
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
789 members
== null ? Set
.of() : members
,
791 if (gv2Pair
== null) {
792 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
793 gv1
.addMembers(List
.of(account
.getSelfRecipientId()));
794 updateGroupV1(gv1
, name
, members
, avatarFile
);
795 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
798 final var gv2
= gv2Pair
.first();
799 final var decryptedGroup
= gv2Pair
.second();
801 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
802 if (avatarFile
!= null) {
803 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
804 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
806 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
810 var group
= getGroupForUpdating(groupId
);
811 if (group
instanceof GroupInfoV2
) {
812 final var groupInfoV2
= (GroupInfoV2
) group
;
814 Pair
<Long
, List
<SendMessageResult
>> result
= null;
815 if (groupInfoV2
.isPendingMember(account
.getSelfRecipientId())) {
816 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
817 result
= sendUpdateGroupMessage(groupInfoV2
,
818 groupGroupChangePair
.first(),
819 groupGroupChangePair
.second());
822 if (members
!= null) {
823 final var newMembers
= new HashSet
<>(members
);
824 newMembers
.removeAll(group
.getMembers());
825 if (newMembers
.size() > 0) {
826 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
827 result
= sendUpdateGroupMessage(groupInfoV2
,
828 groupGroupChangePair
.first(),
829 groupGroupChangePair
.second());
832 if (result
== null || name
!= null || avatarFile
!= null) {
833 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
834 if (avatarFile
!= null) {
835 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
836 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
838 result
= sendUpdateGroupMessage(groupInfoV2
,
839 groupGroupChangePair
.first(),
840 groupGroupChangePair
.second());
843 return new Pair
<>(group
.getGroupId(), result
.second());
845 var gv1
= (GroupInfoV1
) group
;
846 updateGroupV1(gv1
, name
, members
, avatarFile
);
847 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
852 account
.getGroupStore().updateGroup(g
);
854 final var result
= sendMessage(messageBuilder
,
855 g
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
856 return new Pair
<>(g
.getGroupId(), result
.second());
859 private void updateGroupV1(
860 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
861 ) throws IOException
{
866 if (members
!= null) {
867 final var newMemberAddresses
= members
.stream()
868 .filter(member
-> !g
.isMember(member
))
869 .map(this::resolveSignalServiceAddress
)
870 .collect(Collectors
.toList());
871 final var newE164Members
= new HashSet
<String
>();
872 for (var member
: newMemberAddresses
) {
873 if (!member
.getNumber().isPresent()) {
876 newE164Members
.add(member
.getNumber().get());
879 final var registeredUsers
= getRegisteredUsers(newE164Members
);
880 if (registeredUsers
.size() != newE164Members
.size()) {
881 // Some of the new members are not registered on Signal
882 newE164Members
.removeAll(registeredUsers
.keySet());
883 throw new IOException("Failed to add members "
884 + String
.join(", ", newE164Members
)
885 + " to group: Not registered on Signal");
888 g
.addMembers(members
);
891 if (avatarFile
!= null) {
892 avatarStore
.storeGroupAvatar(g
.getGroupId(),
893 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
897 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
898 GroupInviteLinkUrl inviteLinkUrl
899 ) throws IOException
, GroupLinkNotActiveException
{
900 return sendJoinGroupMessage(inviteLinkUrl
);
903 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
904 GroupInviteLinkUrl inviteLinkUrl
905 ) throws IOException
, GroupLinkNotActiveException
{
906 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
907 inviteLinkUrl
.getPassword());
908 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
909 inviteLinkUrl
.getPassword(),
911 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
912 groupJoinInfo
.getRevision() + 1,
913 groupChange
.toByteArray());
915 if (group
.getGroup() == null) {
916 // Only requested member, can't send update to group members
917 return new Pair
<>(group
.getGroupId(), List
.of());
920 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
922 return new Pair
<>(group
.getGroupId(), result
.second());
925 private static int currentTimeDays() {
926 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
929 private GroupsV2AuthorizationString
getGroupAuthForToday(
930 final GroupSecretParams groupSecretParams
931 ) throws IOException
{
932 final var today
= currentTimeDays();
933 // Returns credentials for the next 7 days
934 final var credentials
= groupsV2Api
.getCredentials(today
);
935 // TODO cache credentials until they expire
936 var authCredentialResponse
= credentials
.get(today
);
938 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
941 authCredentialResponse
);
942 } catch (VerificationFailedException e
) {
943 throw new IOException(e
);
947 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
948 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
949 ) throws IOException
{
950 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
951 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
952 account
.getGroupStore().updateGroup(group
);
953 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
956 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
957 GroupIdV1 groupId
, SignalServiceAddress recipient
958 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
960 var group
= getGroupForSending(groupId
);
961 if (!(group
instanceof GroupInfoV1
)) {
962 throw new RuntimeException("Received an invalid group request for a v2 group!");
964 g
= (GroupInfoV1
) group
;
966 final var recipientId
= resolveRecipient(recipient
);
967 if (!g
.isMember(recipientId
)) {
968 throw new NotAGroupMemberException(groupId
, g
.name
);
971 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
973 // Send group message only to the recipient who requested it
974 return sendMessage(messageBuilder
, Set
.of(recipientId
));
977 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
978 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
979 .withId(g
.getGroupId().serialize())
981 .withMembers(g
.getMembers()
983 .map(this::resolveSignalServiceAddress
)
984 .collect(Collectors
.toList()));
987 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
988 if (attachment
.isPresent()) {
989 group
.withAvatar(attachment
.get());
991 } catch (IOException e
) {
992 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
995 return SignalServiceDataMessage
.newBuilder()
996 .asGroupMessage(group
.build())
997 .withExpiration(g
.getMessageExpirationTime());
1000 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
1001 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
1002 .withRevision(g
.getGroup().getRevision())
1003 .withSignedGroupChange(signedGroupChange
);
1004 return SignalServiceDataMessage
.newBuilder()
1005 .asGroupMessage(group
.build())
1006 .withExpiration(g
.getMessageExpirationTime());
1009 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
1010 GroupIdV1 groupId
, SignalServiceAddress recipient
1011 ) throws IOException
{
1012 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
1014 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
1016 // Send group info request message to the recipient who sent us a message with this groupId
1017 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1021 SignalServiceAddress remoteAddress
, long messageId
1022 ) throws IOException
, UntrustedIdentityException
{
1023 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1025 System
.currentTimeMillis());
1027 createMessageSender().sendReceipt(remoteAddress
,
1028 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1032 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1033 String messageText
, List
<String
> attachments
, List
<String
> recipients
1034 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1035 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1036 if (attachments
!= null) {
1037 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1039 // Upload attachments here, so we only upload once even for multiple recipients
1040 var messageSender
= createMessageSender();
1041 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1042 for (var attachment
: attachmentStreams
) {
1043 if (attachment
.isStream()) {
1044 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1045 } else if (attachment
.isPointer()) {
1046 attachmentPointers
.add(attachment
.asPointer());
1050 messageBuilder
.withAttachments(attachmentPointers
);
1052 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1055 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1056 String messageText
, List
<String
> attachments
1057 ) throws IOException
, AttachmentInvalidException
{
1058 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1059 if (attachments
!= null) {
1060 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1062 return sendSelfMessage(messageBuilder
);
1065 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1066 long targetSentTimestamp
, List
<String
> recipients
1067 ) throws IOException
, InvalidNumberException
{
1068 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1069 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1070 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1073 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1074 long targetSentTimestamp
, GroupId groupId
1075 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1076 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1077 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1078 return sendGroupMessage(messageBuilder
, groupId
);
1081 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1082 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1083 ) throws IOException
, InvalidNumberException
{
1084 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1085 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1087 resolveSignalServiceAddress(targetAuthorRecipientId
),
1088 targetSentTimestamp
);
1089 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1090 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1093 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1094 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1096 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1098 return sendMessage(messageBuilder
, signalServiceAddresses
);
1099 } catch (Exception e
) {
1100 for (var address
: signalServiceAddresses
) {
1101 handleEndSession(address
);
1107 SendMessageResult
renewSession(RecipientId recipientId
) throws IOException
{
1108 account
.getSessionStore().archiveSessions(recipientId
);
1109 return sendNullMessage(recipientId
);
1112 public String
getContactName(String number
) throws InvalidNumberException
{
1113 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1114 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1117 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1118 if (!account
.isMasterDevice()) {
1119 throw new NotMasterDeviceException();
1121 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1122 var contact
= account
.getContactStore().getContact(recipientId
);
1123 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1124 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1127 public void setContactBlocked(
1128 String number
, boolean blocked
1129 ) throws InvalidNumberException
, NotMasterDeviceException
{
1130 if (!account
.isMasterDevice()) {
1131 throw new NotMasterDeviceException();
1133 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1136 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1137 var contact
= account
.getContactStore().getContact(recipientId
);
1138 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1139 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1142 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1143 var group
= getGroup(groupId
);
1144 if (group
== null) {
1145 throw new GroupNotFoundException(groupId
);
1148 group
.setBlocked(blocked
);
1149 account
.getGroupStore().updateGroup(group
);
1152 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1153 var contact
= account
.getContactStore().getContact(recipientId
);
1154 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1157 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1158 account
.getContactStore()
1159 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1162 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1163 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1164 sendMessage(messageBuilder
, Set
.of(recipientId
));
1168 * Change the expiration timer for a contact
1170 public void setExpirationTimer(
1171 String number
, int messageExpirationTimer
1172 ) throws IOException
, InvalidNumberException
{
1173 var recipientId
= canonicalizeAndResolveRecipient(number
);
1174 setExpirationTimer(recipientId
, messageExpirationTimer
);
1175 sendExpirationTimerUpdate(recipientId
);
1179 * Change the expiration timer for a group
1181 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1182 var g
= getGroup(groupId
);
1183 if (g
instanceof GroupInfoV1
) {
1184 var groupInfoV1
= (GroupInfoV1
) g
;
1185 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1186 account
.getGroupStore().updateGroup(groupInfoV1
);
1188 throw new RuntimeException("TODO Not implemented!");
1193 * Upload the sticker pack from path.
1195 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1196 * @return if successful, returns the URL to install the sticker pack in the signal app
1198 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1199 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1201 var messageSender
= createMessageSender();
1203 var packKey
= KeyUtils
.createStickerUploadKey();
1204 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1206 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1207 account
.getStickerStore().updateSticker(sticker
);
1210 return new URI("https",
1213 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1214 Hex
.toStringCondensed(packKey
),
1215 StandardCharsets
.UTF_8
)).toString();
1216 } catch (URISyntaxException e
) {
1217 throw new AssertionError(e
);
1221 public void requestAllSyncData() throws IOException
{
1222 requestSyncGroups();
1223 requestSyncContacts();
1224 requestSyncBlocked();
1225 requestSyncConfiguration();
1229 private void requestSyncGroups() throws IOException
{
1230 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1231 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1233 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1235 sendSyncMessage(message
);
1236 } catch (UntrustedIdentityException e
) {
1237 throw new AssertionError(e
);
1241 private void requestSyncContacts() throws IOException
{
1242 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1243 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1245 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1247 sendSyncMessage(message
);
1248 } catch (UntrustedIdentityException e
) {
1249 throw new AssertionError(e
);
1253 private void requestSyncBlocked() throws IOException
{
1254 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1255 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1257 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1259 sendSyncMessage(message
);
1260 } catch (UntrustedIdentityException e
) {
1261 throw new AssertionError(e
);
1265 private void requestSyncConfiguration() throws IOException
{
1266 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1267 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1269 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1271 sendSyncMessage(message
);
1272 } catch (UntrustedIdentityException e
) {
1273 throw new AssertionError(e
);
1277 private void requestSyncKeys() throws IOException
{
1278 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1279 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1281 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1283 sendSyncMessage(message
);
1284 } catch (UntrustedIdentityException e
) {
1285 throw new AssertionError(e
);
1289 private byte[] getSenderCertificate() {
1292 if (account
.isPhoneNumberShared()) {
1293 certificate
= accountManager
.getSenderCertificate();
1295 certificate
= accountManager
.getSenderCertificateForPhoneNumberPrivacy();
1297 } catch (IOException e
) {
1298 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1301 // TODO cache for a day
1305 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1306 var messageSender
= createMessageSender();
1307 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1310 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1311 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1312 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1314 for (var number
: numbers
) {
1315 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1316 if (resolvedAddress
.getUuid().isPresent()) {
1317 signalServiceAddresses
.add(resolvedAddress
);
1319 addressesMissingUuid
.add(resolvedAddress
);
1323 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1324 .map(a
-> a
.getNumber().get())
1325 .collect(Collectors
.toSet());
1326 Map
<String
, UUID
> registeredUsers
;
1328 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1329 } catch (IOException e
) {
1330 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1331 registeredUsers
= Map
.of();
1334 for (var address
: addressesMissingUuid
) {
1335 final var number
= address
.getNumber().get();
1336 if (registeredUsers
.containsKey(number
)) {
1337 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1338 registeredUsers
.get(number
),
1340 signalServiceAddresses
.add(newAddress
);
1342 signalServiceAddresses
.add(address
);
1346 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1349 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1350 final var address
= resolveSignalServiceAddress(recipientId
);
1351 if (!address
.getNumber().isPresent()) {
1354 final var number
= address
.getNumber().get();
1355 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1356 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1359 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1361 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1363 serviceEnvironmentConfig
.getCdsMrenclave());
1364 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1365 throw new IOException(e
);
1369 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1370 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1371 ) throws IOException
{
1372 final var timestamp
= System
.currentTimeMillis();
1373 messageBuilder
.withTimestamp(timestamp
);
1374 getOrCreateMessagePipe();
1375 getOrCreateUnidentifiedMessagePipe();
1376 SignalServiceDataMessage message
= null;
1378 message
= messageBuilder
.build();
1379 if (message
.getGroupContext().isPresent()) {
1381 var messageSender
= createMessageSender();
1382 final var isRecipientUpdate
= false;
1383 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1384 final var addresses
= recipientIdList
.stream()
1385 .map(this::resolveSignalServiceAddress
)
1386 .collect(Collectors
.toList());
1387 var result
= messageSender
.sendMessage(addresses
,
1388 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1392 for (var r
: result
) {
1393 if (r
.getIdentityFailure() != null) {
1394 final var recipientId
= resolveRecipient(r
.getAddress());
1395 final var newIdentity
= account
.getIdentityKeyStore()
1396 .saveIdentity(recipientId
, r
.getIdentityFailure().getIdentityKey(), new Date());
1398 account
.getSessionStore().archiveSessions(recipientId
);
1403 return new Pair
<>(timestamp
, result
);
1404 } catch (UntrustedIdentityException e
) {
1405 return new Pair
<>(timestamp
, List
.of());
1408 // Send to all individually, so sync messages are sent correctly
1409 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1410 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1411 for (var recipientId
: recipientIds
) {
1412 final var contact
= account
.getContactStore().getContact(recipientId
);
1413 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1414 messageBuilder
.withExpiration(expirationTime
);
1415 message
= messageBuilder
.build();
1416 results
.add(sendMessage(recipientId
, message
));
1418 return new Pair
<>(timestamp
, results
);
1421 if (message
!= null && message
.isEndSession()) {
1422 for (var recipient
: recipientIds
) {
1423 handleEndSession(recipient
);
1429 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1430 SignalServiceDataMessage
.Builder messageBuilder
1431 ) throws IOException
{
1432 final var timestamp
= System
.currentTimeMillis();
1433 messageBuilder
.withTimestamp(timestamp
);
1434 getOrCreateMessagePipe();
1435 getOrCreateUnidentifiedMessagePipe();
1436 final var recipientId
= account
.getSelfRecipientId();
1438 final var contact
= account
.getContactStore().getContact(recipientId
);
1439 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1440 messageBuilder
.withExpiration(expirationTime
);
1442 var message
= messageBuilder
.build();
1443 final var result
= sendSelfMessage(message
);
1444 return new Pair
<>(timestamp
, result
);
1447 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1448 var messageSender
= createMessageSender();
1450 var recipientId
= account
.getSelfRecipientId();
1452 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipientId
);
1453 var recipient
= resolveSignalServiceAddress(recipientId
);
1454 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1455 message
.getTimestamp(),
1457 message
.getExpiresInSeconds(),
1458 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1460 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1463 var startTime
= System
.currentTimeMillis();
1464 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1465 return SendMessageResult
.success(recipient
,
1466 unidentifiedAccess
.isPresent(),
1468 System
.currentTimeMillis() - startTime
);
1469 } catch (UntrustedIdentityException e
) {
1470 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1474 private SendMessageResult
sendMessage(
1475 RecipientId recipientId
, SignalServiceDataMessage message
1476 ) throws IOException
{
1477 var messageSender
= createMessageSender();
1479 final var address
= resolveSignalServiceAddress(recipientId
);
1482 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
), message
);
1483 } catch (UnregisteredUserException e
) {
1484 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1485 return messageSender
.sendMessage(resolveSignalServiceAddress(newRecipientId
),
1486 unidentifiedAccessHelper
.getAccessFor(newRecipientId
),
1489 } catch (UntrustedIdentityException e
) {
1490 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1494 private SendMessageResult
sendNullMessage(RecipientId recipientId
) throws IOException
{
1495 var messageSender
= createMessageSender();
1497 final var address
= resolveSignalServiceAddress(recipientId
);
1500 return messageSender
.sendNullMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
));
1501 } catch (UnregisteredUserException e
) {
1502 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1503 final var newAddress
= resolveSignalServiceAddress(newRecipientId
);
1504 return messageSender
.sendNullMessage(newAddress
, unidentifiedAccessHelper
.getAccessFor(newRecipientId
));
1506 } catch (UntrustedIdentityException e
) {
1507 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1511 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1512 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1513 account
.getSignalProtocolStore(),
1514 certificateValidator
);
1516 return cipher
.decrypt(envelope
);
1517 } catch (ProtocolUntrustedIdentityException e
) {
1518 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1519 throw (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1521 throw new AssertionError(e
);
1525 private void handleEndSession(RecipientId recipientId
) {
1526 account
.getSessionStore().deleteAllSessions(recipientId
);
1529 private List
<HandleAction
> handleSignalServiceDataMessage(
1530 SignalServiceDataMessage message
,
1532 SignalServiceAddress source
,
1533 SignalServiceAddress destination
,
1534 boolean ignoreAttachments
1536 var actions
= new ArrayList
<HandleAction
>();
1537 if (message
.getGroupContext().isPresent()) {
1538 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1539 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1540 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1541 var group
= getGroup(groupId
);
1542 if (group
== null || group
instanceof GroupInfoV1
) {
1543 var groupV1
= (GroupInfoV1
) group
;
1544 switch (groupInfo
.getType()) {
1546 if (groupV1
== null) {
1547 groupV1
= new GroupInfoV1(groupId
);
1550 if (groupInfo
.getAvatar().isPresent()) {
1551 var avatar
= groupInfo
.getAvatar().get();
1552 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1555 if (groupInfo
.getName().isPresent()) {
1556 groupV1
.name
= groupInfo
.getName().get();
1559 if (groupInfo
.getMembers().isPresent()) {
1560 groupV1
.addMembers(groupInfo
.getMembers()
1563 .map(this::resolveRecipient
)
1564 .collect(Collectors
.toSet()));
1567 account
.getGroupStore().updateGroup(groupV1
);
1571 if (groupV1
== null && !isSync
) {
1572 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1576 if (groupV1
!= null) {
1577 groupV1
.removeMember(resolveRecipient(source
));
1578 account
.getGroupStore().updateGroup(groupV1
);
1583 if (groupV1
!= null && !isSync
) {
1584 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1589 // Received a group v1 message for a v2 group
1592 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1593 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1594 final var groupMasterKey
= groupContext
.getMasterKey();
1596 getOrMigrateGroup(groupMasterKey
,
1597 groupContext
.getRevision(),
1598 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1602 final var conversationPartnerAddress
= isSync ? destination
: source
;
1603 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1604 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1606 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1607 if (message
.getGroupContext().isPresent()) {
1608 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1609 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1610 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1611 if (group
!= null) {
1612 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1613 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1614 account
.getGroupStore().updateGroup(group
);
1617 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1618 // disappearing message timer already stored in the DecryptedGroup
1620 } else if (conversationPartnerAddress
!= null) {
1621 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1624 if (!ignoreAttachments
) {
1625 if (message
.getAttachments().isPresent()) {
1626 for (var attachment
: message
.getAttachments().get()) {
1627 downloadAttachment(attachment
);
1630 if (message
.getSharedContacts().isPresent()) {
1631 for (var contact
: message
.getSharedContacts().get()) {
1632 if (contact
.getAvatar().isPresent()) {
1633 downloadAttachment(contact
.getAvatar().get().getAttachment());
1638 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1639 final ProfileKey profileKey
;
1641 profileKey
= new ProfileKey(message
.getProfileKey().get());
1642 } catch (InvalidInputException e
) {
1643 throw new AssertionError(e
);
1645 if (source
.matches(account
.getSelfAddress())) {
1646 this.account
.setProfileKey(profileKey
);
1648 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1650 if (message
.getPreviews().isPresent()) {
1651 final var previews
= message
.getPreviews().get();
1652 for (var preview
: previews
) {
1653 if (preview
.getImage().isPresent()) {
1654 downloadAttachment(preview
.getImage().get());
1658 if (message
.getQuote().isPresent()) {
1659 final var quote
= message
.getQuote().get();
1661 for (var quotedAttachment
: quote
.getAttachments()) {
1662 final var thumbnail
= quotedAttachment
.getThumbnail();
1663 if (thumbnail
!= null) {
1664 downloadAttachment(thumbnail
);
1668 if (message
.getSticker().isPresent()) {
1669 final var messageSticker
= message
.getSticker().get();
1670 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1671 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1672 if (sticker
== null) {
1673 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1674 account
.getStickerStore().updateSticker(sticker
);
1680 private GroupInfoV2
getOrMigrateGroup(
1681 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1683 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1685 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1686 var groupInfo
= getGroup(groupId
);
1687 final GroupInfoV2 groupInfoV2
;
1688 if (groupInfo
instanceof GroupInfoV1
) {
1689 // Received a v2 group message for a v1 group, we need to locally migrate the group
1690 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1691 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1692 logger
.info("Locally migrated group {} to group v2, id: {}",
1693 groupInfo
.getGroupId().toBase64(),
1694 groupInfoV2
.getGroupId().toBase64());
1695 } else if (groupInfo
instanceof GroupInfoV2
) {
1696 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1698 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1701 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1702 DecryptedGroup group
= null;
1703 if (signedGroupChange
!= null
1704 && groupInfoV2
.getGroup() != null
1705 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1706 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1708 if (group
== null) {
1709 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1711 if (group
!= null) {
1712 storeProfileKeysFromMembers(group
);
1713 final var avatar
= group
.getAvatar();
1714 if (avatar
!= null && !avatar
.isEmpty()) {
1715 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1718 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1719 account
.getGroupStore().updateGroup(groupInfoV2
);
1725 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1726 for (var member
: group
.getMembersList()) {
1727 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
1728 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
1730 account
.getProfileStore()
1731 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
1732 } catch (InvalidInputException ignored
) {
1737 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1738 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1739 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1740 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1741 if (actions
!= null) {
1742 queuedActions
.addAll(actions
);
1745 for (var action
: queuedActions
) {
1747 action
.execute(this);
1748 } catch (Throwable e
) {
1749 logger
.warn("Message action failed.", e
);
1754 private List
<HandleAction
> retryFailedReceivedMessage(
1755 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1757 var envelope
= cachedMessage
.loadEnvelope();
1758 if (envelope
== null) {
1761 SignalServiceContent content
= null;
1762 List
<HandleAction
> actions
= null;
1763 if (!envelope
.isReceipt()) {
1765 content
= decryptMessage(envelope
);
1766 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1767 if (!envelope
.hasSource()) {
1768 final var identifier
= ((org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
).getName();
1769 final var recipientId
= resolveRecipient(identifier
);
1771 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1772 } catch (IOException ioException
) {
1773 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1777 } catch (Exception er
) {
1778 // All other errors are not recoverable, so delete the cached message
1779 cachedMessage
.delete();
1782 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1784 handler
.handleMessage(envelope
, content
, null);
1785 cachedMessage
.delete();
1789 public void receiveMessages(
1792 boolean returnOnTimeout
,
1793 boolean ignoreAttachments
,
1794 ReceiveMessageHandler handler
1795 ) throws IOException
{
1796 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1798 Set
<HandleAction
> queuedActions
= null;
1800 final var messagePipe
= getOrCreateMessagePipe();
1802 var hasCaughtUpWithOldMessages
= false;
1805 SignalServiceEnvelope envelope
;
1806 SignalServiceContent content
= null;
1807 Exception exception
= null;
1808 final CachedMessage
[] cachedMessage
= {null};
1810 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1811 final var recipientId
= envelope1
.hasSource()
1812 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1814 // store message on disk, before acknowledging receipt to the server
1815 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1817 if (result
.isPresent()) {
1818 envelope
= result
.get();
1820 // Received indicator that server queue is empty
1821 hasCaughtUpWithOldMessages
= true;
1823 if (queuedActions
!= null) {
1824 for (var action
: queuedActions
) {
1826 action
.execute(this);
1827 } catch (Throwable e
) {
1828 logger
.warn("Message action failed.", e
);
1831 queuedActions
.clear();
1832 queuedActions
= null;
1835 // Continue to wait another timeout for new messages
1838 } catch (TimeoutException e
) {
1839 if (returnOnTimeout
) return;
1843 if (envelope
.hasSource()) {
1844 // Store uuid if we don't have it already
1845 // address/uuid in envelope is sent by server
1846 resolveRecipientTrusted(envelope
.getSourceAddress());
1848 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1849 if (!envelope
.isReceipt()) {
1851 content
= decryptMessage(envelope
);
1852 } catch (Exception e
) {
1855 if (!envelope
.hasSource() && content
!= null) {
1856 // Store uuid if we don't have it already
1857 // address/uuid is validated by unidentified sender certificate
1858 resolveRecipientTrusted(content
.getSender());
1860 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1861 if (exception
instanceof ProtocolInvalidMessageException
) {
1862 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
1863 logger
.debug("Received invalid message, queuing renew session action.");
1864 actions
.add(new RenewSessionAction(sender
));
1866 if (hasCaughtUpWithOldMessages
) {
1867 for (var action
: actions
) {
1869 action
.execute(this);
1870 } catch (Throwable e
) {
1871 logger
.warn("Message action failed.", e
);
1875 if (queuedActions
== null) {
1876 queuedActions
= new HashSet
<>();
1878 queuedActions
.addAll(actions
);
1881 if (isMessageBlocked(envelope
, content
)) {
1882 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1883 } else if (notAGroupMember
) {
1884 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1886 handler
.handleMessage(envelope
, content
, exception
);
1888 if (cachedMessage
[0] != null) {
1889 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1890 final var identifier
= ((org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
).getName();
1891 final var recipientId
= resolveRecipient(identifier
);
1892 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1893 if (!envelope
.hasSource()) {
1895 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1896 } catch (IOException ioException
) {
1897 logger
.warn("Failed to move cached message to recipient folder: {}",
1898 ioException
.getMessage());
1902 cachedMessage
[0].delete();
1908 private boolean isMessageBlocked(
1909 SignalServiceEnvelope envelope
, SignalServiceContent content
1911 SignalServiceAddress source
;
1912 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1913 source
= envelope
.getSourceAddress();
1914 } else if (content
!= null) {
1915 source
= content
.getSender();
1919 final var recipientId
= resolveRecipient(source
);
1920 if (isContactBlocked(recipientId
)) {
1924 if (content
!= null && content
.getDataMessage().isPresent()) {
1925 var message
= content
.getDataMessage().get();
1926 if (message
.getGroupContext().isPresent()) {
1927 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1928 var group
= getGroup(groupId
);
1929 if (group
!= null && group
.isBlocked()) {
1937 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
1938 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
1939 return isContactBlocked(recipientId
);
1942 private boolean isContactBlocked(final RecipientId recipientId
) {
1943 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1944 return sourceContact
!= null && sourceContact
.isBlocked();
1947 private boolean isNotAGroupMember(
1948 SignalServiceEnvelope envelope
, SignalServiceContent content
1950 SignalServiceAddress source
;
1951 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1952 source
= envelope
.getSourceAddress();
1953 } else if (content
!= null) {
1954 source
= content
.getSender();
1959 if (content
!= null && content
.getDataMessage().isPresent()) {
1960 var message
= content
.getDataMessage().get();
1961 if (message
.getGroupContext().isPresent()) {
1962 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1963 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1964 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1968 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1969 var group
= getGroup(groupId
);
1970 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
1978 private List
<HandleAction
> handleMessage(
1979 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1981 var actions
= new ArrayList
<HandleAction
>();
1982 if (content
!= null) {
1983 final SignalServiceAddress sender
;
1984 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1985 sender
= envelope
.getSourceAddress();
1987 sender
= content
.getSender();
1990 if (content
.getDataMessage().isPresent()) {
1991 var message
= content
.getDataMessage().get();
1993 if (content
.isNeedsReceipt()) {
1994 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1997 actions
.addAll(handleSignalServiceDataMessage(message
,
2000 account
.getSelfAddress(),
2001 ignoreAttachments
));
2003 if (content
.getSyncMessage().isPresent()) {
2004 account
.setMultiDevice(true);
2005 var syncMessage
= content
.getSyncMessage().get();
2006 if (syncMessage
.getSent().isPresent()) {
2007 var message
= syncMessage
.getSent().get();
2008 final var destination
= message
.getDestination().orNull();
2009 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
2013 ignoreAttachments
));
2015 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
2016 var rm
= syncMessage
.getRequest().get();
2017 if (rm
.isContactsRequest()) {
2018 actions
.add(SendSyncContactsAction
.create());
2020 if (rm
.isGroupsRequest()) {
2021 actions
.add(SendSyncGroupsAction
.create());
2023 if (rm
.isBlockedListRequest()) {
2024 actions
.add(SendSyncBlockedListAction
.create());
2026 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2028 if (syncMessage
.getGroups().isPresent()) {
2029 File tmpFile
= null;
2031 tmpFile
= IOUtils
.createTempFile();
2032 final var groupsMessage
= syncMessage
.getGroups().get();
2033 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2034 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2036 while ((g
= s
.read()) != null) {
2037 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2038 if (syncGroup
!= null) {
2039 if (g
.getName().isPresent()) {
2040 syncGroup
.name
= g
.getName().get();
2042 syncGroup
.addMembers(g
.getMembers()
2044 .map(this::resolveRecipient
)
2045 .collect(Collectors
.toSet()));
2046 if (!g
.isActive()) {
2047 syncGroup
.removeMember(account
.getSelfRecipientId());
2049 // Add ourself to the member set as it's marked as active
2050 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2052 syncGroup
.blocked
= g
.isBlocked();
2053 if (g
.getColor().isPresent()) {
2054 syncGroup
.color
= g
.getColor().get();
2057 if (g
.getAvatar().isPresent()) {
2058 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2060 syncGroup
.archived
= g
.isArchived();
2061 account
.getGroupStore().updateGroup(syncGroup
);
2065 } catch (Exception e
) {
2066 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2070 if (tmpFile
!= null) {
2072 Files
.delete(tmpFile
.toPath());
2073 } catch (IOException e
) {
2074 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2081 if (syncMessage
.getBlockedList().isPresent()) {
2082 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2083 for (var address
: blockedListMessage
.getAddresses()) {
2084 setContactBlocked(resolveRecipient(address
), true);
2086 for (var groupId
: blockedListMessage
.getGroupIds()
2088 .map(GroupId
::unknownVersion
)
2089 .collect(Collectors
.toSet())) {
2091 setGroupBlocked(groupId
, true);
2092 } catch (GroupNotFoundException e
) {
2093 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2094 groupId
.toBase64());
2098 if (syncMessage
.getContacts().isPresent()) {
2099 File tmpFile
= null;
2101 tmpFile
= IOUtils
.createTempFile();
2102 final var contactsMessage
= syncMessage
.getContacts().get();
2103 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2104 .asPointer(), tmpFile
)) {
2105 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2107 while ((c
= s
.read()) != null) {
2108 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2109 account
.setProfileKey(c
.getProfileKey().get());
2111 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2112 var contact
= account
.getContactStore().getContact(recipientId
);
2113 final var builder
= contact
== null
2114 ? Contact
.newBuilder()
2115 : Contact
.newBuilder(contact
);
2116 if (c
.getName().isPresent()) {
2117 builder
.withName(c
.getName().get());
2119 if (c
.getColor().isPresent()) {
2120 builder
.withColor(c
.getColor().get());
2122 if (c
.getProfileKey().isPresent()) {
2123 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2125 if (c
.getVerified().isPresent()) {
2126 final var verifiedMessage
= c
.getVerified().get();
2127 account
.getIdentityKeyStore()
2128 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2129 verifiedMessage
.getIdentityKey(),
2130 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2132 if (c
.getExpirationTimer().isPresent()) {
2133 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2135 builder
.withBlocked(c
.isBlocked());
2136 builder
.withArchived(c
.isArchived());
2137 account
.getContactStore().storeContact(recipientId
, builder
.build());
2139 if (c
.getAvatar().isPresent()) {
2140 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2144 } catch (Exception e
) {
2145 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2149 if (tmpFile
!= null) {
2151 Files
.delete(tmpFile
.toPath());
2152 } catch (IOException e
) {
2153 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2160 if (syncMessage
.getVerified().isPresent()) {
2161 final var verifiedMessage
= syncMessage
.getVerified().get();
2162 account
.getIdentityKeyStore()
2163 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2164 verifiedMessage
.getIdentityKey(),
2165 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2167 if (syncMessage
.getStickerPackOperations().isPresent()) {
2168 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2169 for (var m
: stickerPackOperationMessages
) {
2170 if (!m
.getPackId().isPresent()) {
2173 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2174 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2175 if (sticker
== null) {
2176 if (!m
.getPackKey().isPresent()) {
2179 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2181 sticker
.setInstalled(!m
.getType().isPresent()
2182 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2183 account
.getStickerStore().updateSticker(sticker
);
2186 if (syncMessage
.getFetchType().isPresent()) {
2187 switch (syncMessage
.getFetchType().get()) {
2189 getRecipientProfile(account
.getSelfRecipientId(), true);
2190 case STORAGE_MANIFEST
:
2194 if (syncMessage
.getKeys().isPresent()) {
2195 final var keysMessage
= syncMessage
.getKeys().get();
2196 if (keysMessage
.getStorageService().isPresent()) {
2197 final var storageKey
= keysMessage
.getStorageService().get();
2198 account
.setStorageKey(storageKey
);
2201 if (syncMessage
.getConfiguration().isPresent()) {
2209 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2211 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2212 } catch (IOException e
) {
2213 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2217 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2219 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2220 } catch (IOException e
) {
2221 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2225 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2227 avatarStore
.storeGroupAvatar(groupId
,
2228 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2229 } catch (IOException e
) {
2230 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2234 private void downloadProfileAvatar(
2235 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2238 avatarStore
.storeProfileAvatar(address
,
2239 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2240 } catch (Throwable e
) {
2241 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2245 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2246 return attachmentStore
.getAttachmentFile(attachmentId
);
2249 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2250 if (!attachment
.isPointer()) {
2251 logger
.warn("Invalid state, can't store an attachment stream.");
2254 var pointer
= attachment
.asPointer();
2255 if (pointer
.getPreview().isPresent()) {
2256 final var preview
= pointer
.getPreview().get();
2258 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2259 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2260 } catch (IOException e
) {
2261 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2266 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2267 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2268 } catch (IOException e
) {
2269 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2273 private void retrieveGroupV2Avatar(
2274 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2275 ) throws IOException
{
2276 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2278 var tmpFile
= IOUtils
.createTempFile();
2279 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2281 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2282 var encryptedData
= IOUtils
.readFully(input
);
2284 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2285 outputStream
.write(decryptedData
);
2288 Files
.delete(tmpFile
.toPath());
2289 } catch (IOException e
) {
2290 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2297 private void retrieveProfileAvatar(
2298 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2299 ) throws IOException
{
2300 var tmpFile
= IOUtils
.createTempFile();
2301 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2304 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2305 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2306 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2309 Files
.delete(tmpFile
.toPath());
2310 } catch (IOException e
) {
2311 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2318 private void retrieveAttachment(
2319 final SignalServiceAttachment attachment
, final OutputStream outputStream
2320 ) throws IOException
{
2321 if (attachment
.isPointer()) {
2322 var pointer
= attachment
.asPointer();
2323 retrieveAttachmentPointer(pointer
, outputStream
);
2325 var stream
= attachment
.asStream();
2326 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2330 private void retrieveAttachmentPointer(
2331 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2332 ) throws IOException
{
2333 var tmpFile
= IOUtils
.createTempFile();
2334 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2335 IOUtils
.copyStream(input
, outputStream
);
2336 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2337 throw new IOException(e
);
2340 Files
.delete(tmpFile
.toPath());
2341 } catch (IOException e
) {
2342 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2349 private InputStream
retrieveAttachmentAsStream(
2350 SignalServiceAttachmentPointer pointer
, File tmpFile
2351 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2352 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2355 void sendGroups() throws IOException
, UntrustedIdentityException
{
2356 var groupsFile
= IOUtils
.createTempFile();
2359 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2360 var out
= new DeviceGroupsOutputStream(fos
);
2361 for (var record : getGroups()) {
2362 if (record instanceof GroupInfoV1
) {
2363 var groupInfo
= (GroupInfoV1
) record;
2364 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2365 Optional
.fromNullable(groupInfo
.name
),
2366 groupInfo
.getMembers()
2368 .map(this::resolveSignalServiceAddress
)
2369 .collect(Collectors
.toList()),
2370 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2371 groupInfo
.isMember(account
.getSelfRecipientId()),
2372 Optional
.of(groupInfo
.messageExpirationTime
),
2373 Optional
.fromNullable(groupInfo
.color
),
2376 groupInfo
.archived
));
2381 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2382 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2383 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2384 .withStream(groupsFileStream
)
2385 .withContentType("application/octet-stream")
2386 .withLength(groupsFile
.length())
2389 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2394 Files
.delete(groupsFile
.toPath());
2395 } catch (IOException e
) {
2396 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2401 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2402 var contactsFile
= IOUtils
.createTempFile();
2405 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2406 var out
= new DeviceContactsOutputStream(fos
);
2407 for (var contactPair
: account
.getContactStore().getContacts()) {
2408 final var recipientId
= contactPair
.first();
2409 final var contact
= contactPair
.second();
2410 final var address
= resolveSignalServiceAddress(recipientId
);
2412 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2413 VerifiedMessage verifiedMessage
= null;
2414 if (currentIdentity
!= null) {
2415 verifiedMessage
= new VerifiedMessage(address
,
2416 currentIdentity
.getIdentityKey(),
2417 currentIdentity
.getTrustLevel().toVerifiedState(),
2418 currentIdentity
.getDateAdded().getTime());
2421 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2422 out
.write(new DeviceContact(address
,
2423 Optional
.fromNullable(contact
.getName()),
2424 createContactAvatarAttachment(address
),
2425 Optional
.fromNullable(contact
.getColor()),
2426 Optional
.fromNullable(verifiedMessage
),
2427 Optional
.fromNullable(profileKey
),
2428 contact
.isBlocked(),
2429 Optional
.of(contact
.getMessageExpirationTime()),
2431 contact
.isArchived()));
2434 if (account
.getProfileKey() != null) {
2435 // Send our own profile key as well
2436 out
.write(new DeviceContact(account
.getSelfAddress(),
2441 Optional
.of(account
.getProfileKey()),
2449 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2450 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2451 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2452 .withStream(contactsFileStream
)
2453 .withContentType("application/octet-stream")
2454 .withLength(contactsFile
.length())
2457 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2462 Files
.delete(contactsFile
.toPath());
2463 } catch (IOException e
) {
2464 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2469 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2470 var addresses
= new ArrayList
<SignalServiceAddress
>();
2471 for (var record : account
.getContactStore().getContacts()) {
2472 if (record.second().isBlocked()) {
2473 addresses
.add(resolveSignalServiceAddress(record.first()));
2476 var groupIds
= new ArrayList
<byte[]>();
2477 for (var record : getGroups()) {
2478 if (record.isBlocked()) {
2479 groupIds
.add(record.getGroupId().serialize());
2482 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2485 private void sendVerifiedMessage(
2486 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2487 ) throws IOException
, UntrustedIdentityException
{
2488 var verifiedMessage
= new VerifiedMessage(destination
,
2490 trustLevel
.toVerifiedState(),
2491 System
.currentTimeMillis());
2492 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2495 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2496 return account
.getContactStore().getContacts();
2499 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2500 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2501 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2502 if (recipient
== null) {
2506 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2507 return recipient
.getContact().getName();
2510 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2511 return recipient
.getProfile().getDisplayName();
2517 public GroupInfo
getGroup(GroupId groupId
) {
2518 final var group
= account
.getGroupStore().getGroup(groupId
);
2519 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2520 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2521 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2522 account
.getGroupStore().updateGroup(group
);
2527 public List
<IdentityInfo
> getIdentities() {
2528 return account
.getIdentityKeyStore().getIdentities();
2531 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2532 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2533 return identity
== null ? List
.of() : List
.of(identity
);
2537 * Trust this the identity with this fingerprint
2539 * @param name username of the identity
2540 * @param fingerprint Fingerprint
2542 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2543 var recipientId
= canonicalizeAndResolveRecipient(name
);
2544 return trustIdentity(recipientId
,
2545 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2546 TrustLevel
.TRUSTED_VERIFIED
);
2550 * Trust this the identity with this safety number
2552 * @param name username of the identity
2553 * @param safetyNumber Safety number
2555 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2556 var recipientId
= canonicalizeAndResolveRecipient(name
);
2557 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2558 return trustIdentity(recipientId
,
2559 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2560 TrustLevel
.TRUSTED_VERIFIED
);
2564 * Trust all keys of this identity without verification
2566 * @param name username of the identity
2568 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2569 var recipientId
= canonicalizeAndResolveRecipient(name
);
2570 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2573 private boolean trustIdentity(
2574 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2576 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2577 if (identity
== null) {
2581 if (!verifier
.apply(identity
.getIdentityKey())) {
2585 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2587 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2588 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2589 } catch (IOException
| UntrustedIdentityException e
) {
2590 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2596 public String
computeSafetyNumber(
2597 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2599 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2600 account
.getSelfAddress(),
2601 getIdentityKeyPair().getPublicKey(),
2607 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2608 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2610 return resolveSignalServiceAddress(address
);
2614 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2615 if (address
.matches(account
.getSelfAddress())) {
2616 return account
.getSelfAddress();
2619 return account
.getRecipientStore().resolveServiceAddress(address
);
2622 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2623 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2626 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2627 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2629 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2631 return resolveRecipient(canonicalizedNumber
);
2634 private RecipientId
resolveRecipient(final String identifier
) {
2635 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2637 return resolveRecipient(address
);
2640 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2641 return account
.getRecipientStore().resolveRecipient(address
);
2644 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2645 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2649 public void close() throws IOException
{
2653 void close(boolean closeAccount
) throws IOException
{
2654 executor
.shutdown();
2656 if (messagePipe
!= null) {
2657 messagePipe
.shutdown();
2661 if (unidentifiedMessagePipe
!= null) {
2662 unidentifiedMessagePipe
.shutdown();
2663 unidentifiedMessagePipe
= null;
2666 if (closeAccount
&& account
!= null) {
2672 public interface ReceiveMessageHandler
{
2674 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);