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
.SignalSessionLock
;
87 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
88 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
89 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
90 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
91 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
92 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
93 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
94 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
95 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
96 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
105 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
106 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
107 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
118 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
119 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
120 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
121 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
122 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
123 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
124 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
125 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
126 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
127 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
128 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
129 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
130 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
131 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
132 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
133 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
134 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
135 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
136 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
138 import java
.io
.Closeable
;
140 import java
.io
.FileInputStream
;
141 import java
.io
.FileOutputStream
;
142 import java
.io
.IOException
;
143 import java
.io
.InputStream
;
144 import java
.io
.OutputStream
;
146 import java
.net
.URISyntaxException
;
147 import java
.net
.URLEncoder
;
148 import java
.nio
.charset
.StandardCharsets
;
149 import java
.nio
.file
.Files
;
150 import java
.security
.SignatureException
;
151 import java
.util
.ArrayList
;
152 import java
.util
.Arrays
;
153 import java
.util
.Base64
;
154 import java
.util
.Collection
;
155 import java
.util
.Date
;
156 import java
.util
.HashSet
;
157 import java
.util
.List
;
158 import java
.util
.Map
;
159 import java
.util
.Set
;
160 import java
.util
.UUID
;
161 import java
.util
.concurrent
.ExecutorService
;
162 import java
.util
.concurrent
.Executors
;
163 import java
.util
.concurrent
.TimeUnit
;
164 import java
.util
.concurrent
.TimeoutException
;
165 import java
.util
.concurrent
.locks
.ReentrantLock
;
166 import java
.util
.function
.Function
;
167 import java
.util
.stream
.Collectors
;
169 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
171 public class Manager
implements Closeable
{
173 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
175 private final CertificateValidator certificateValidator
;
177 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
178 private final String userAgent
;
180 private SignalAccount account
;
181 private final SignalServiceAccountManager accountManager
;
182 private final GroupsV2Api groupsV2Api
;
183 private final GroupsV2Operations groupsV2Operations
;
184 private final SignalServiceMessageReceiver messageReceiver
;
185 private final ClientZkProfileOperations clientZkProfileOperations
;
187 private final ExecutorService executor
= Executors
.newCachedThreadPool();
189 private SignalServiceMessagePipe messagePipe
= null;
190 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
192 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
193 private final ProfileHelper profileHelper
;
194 private final GroupHelper groupHelper
;
195 private final PinHelper pinHelper
;
196 private final AvatarStore avatarStore
;
197 private final AttachmentStore attachmentStore
;
198 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
199 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
202 public Lock
acquire() {
204 return LEGACY_LOCK
::unlock
;
209 SignalAccount account
,
210 PathConfig pathConfig
,
211 ServiceEnvironmentConfig serviceEnvironmentConfig
,
214 this.account
= account
;
215 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
216 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
217 this.userAgent
= userAgent
;
218 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
219 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
220 final SleepTimer timer
= new UptimeSleepTimer();
221 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
222 new DynamicCredentialsProvider(account
.getUuid(),
223 account
.getUsername(),
224 account
.getPassword(),
225 account
.getDeviceId()),
228 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
230 this.groupsV2Api
= accountManager
.getGroupsV2Api();
231 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
232 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
233 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
234 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
237 this.pinHelper
= new PinHelper(keyBackupService
);
238 this.clientZkProfileOperations
= capabilities
.isGv2()
239 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
240 .getProfileOperations()
242 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
244 account
.getUsername(),
245 account
.getPassword(),
246 account
.getDeviceId(),
250 clientZkProfileOperations
,
251 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
253 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
254 account
.getProfileStore()::getProfileKey
,
255 this::getRecipientProfile
,
256 this::getSenderCertificate
);
257 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
258 unidentifiedAccessHelper
::getAccessFor
,
259 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
260 () -> messageReceiver
,
261 this::resolveSignalServiceAddress
);
262 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
263 this::getRecipientProfile
,
264 account
::getSelfRecipientId
,
267 this::getGroupAuthForToday
,
268 this::resolveSignalServiceAddress
);
269 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
270 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
273 public String
getUsername() {
274 return account
.getUsername();
277 public SignalServiceAddress
getSelfAddress() {
278 return account
.getSelfAddress();
281 public RecipientId
getSelfRecipientId() {
282 return account
.getSelfRecipientId();
285 private IdentityKeyPair
getIdentityKeyPair() {
286 return account
.getIdentityKeyPair();
289 public int getDeviceId() {
290 return account
.getDeviceId();
293 public static Manager
init(
294 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
295 ) throws IOException
, NotRegisteredException
{
296 var pathConfig
= PathConfig
.createDefault(settingsPath
);
298 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
299 throw new NotRegisteredException();
302 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true);
304 if (!account
.isRegistered()) {
305 throw new NotRegisteredException();
308 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
310 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
313 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
314 var pathConfig
= PathConfig
.createDefault(settingsPath
);
315 final var dataPath
= pathConfig
.getDataPath();
316 final var files
= dataPath
.listFiles();
322 return Arrays
.stream(files
)
323 .filter(File
::isFile
)
325 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
326 .collect(Collectors
.toList());
329 public void checkAccountState() throws IOException
{
330 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
333 if (account
.getUuid() == null) {
334 account
.setUuid(accountManager
.getOwnUuid());
336 updateAccountAttributes();
340 * This is used for checking a set of phone numbers for registration on Signal
342 * @param numbers The set of phone number in question
343 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
344 * @throws IOException if its unable to get the contacts to check if they're registered
346 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
347 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
348 var contactDetails
= getRegisteredUsers(numbers
);
350 var registeredUsers
= contactDetails
.keySet();
352 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
355 public void updateAccountAttributes() throws IOException
{
356 accountManager
.setAccountAttributes(account
.getEncryptedDeviceName(),
358 account
.getLocalRegistrationId(),
360 // set legacy pin only if no KBS master key is set
361 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
362 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
363 account
.getSelfUnidentifiedAccessKey(),
364 account
.isUnrestrictedUnidentifiedAccess(),
366 account
.isDiscoverableByPhoneNumber());
370 * @param givenName if null, the previous givenName will be kept
371 * @param familyName if null, the previous familyName will be kept
372 * @param about if null, the previous about text will be kept
373 * @param aboutEmoji if null, the previous about emoji will be kept
374 * @param avatar if avatar is null the image from the local avatar store is used (if present),
376 public void setProfile(
377 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
378 ) throws IOException
{
379 var profile
= getRecipientProfile(account
.getSelfRecipientId());
380 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
381 if (givenName
!= null) {
382 builder
.withGivenName(givenName
);
384 if (familyName
!= null) {
385 builder
.withFamilyName(familyName
);
388 builder
.withAbout(about
);
390 if (aboutEmoji
!= null) {
391 builder
.withAboutEmoji(aboutEmoji
);
393 var newProfile
= builder
.build();
395 try (final var streamDetails
= avatar
== null
396 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
397 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
398 accountManager
.setVersionedProfile(account
.getUuid(),
399 account
.getProfileKey(),
400 newProfile
.getInternalServiceName(),
401 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
402 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
407 if (avatar
!= null) {
408 if (avatar
.isPresent()) {
409 avatarStore
.storeProfileAvatar(getSelfAddress(),
410 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
412 avatarStore
.deleteProfileAvatar(getSelfAddress());
415 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
418 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
419 } catch (UntrustedIdentityException ignored
) {
423 public void unregister() throws IOException
{
424 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
425 // If this is the master device, other users can't send messages to this number anymore.
426 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
427 accountManager
.setGcmId(Optional
.absent());
429 account
.setRegistered(false);
432 public void deleteAccount() throws IOException
{
433 accountManager
.deleteAccount();
435 account
.setRegistered(false);
438 public List
<Device
> getLinkedDevices() throws IOException
{
439 var devices
= accountManager
.getDevices();
440 account
.setMultiDevice(devices
.size() > 1);
441 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
442 return devices
.stream().map(d
-> {
443 String deviceName
= d
.getName();
444 if (deviceName
!= null) {
446 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
447 } catch (IOException e
) {
448 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
451 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
452 }).collect(Collectors
.toList());
455 public void removeLinkedDevices(int deviceId
) throws IOException
{
456 accountManager
.removeDevice(deviceId
);
457 var devices
= accountManager
.getDevices();
458 account
.setMultiDevice(devices
.size() > 1);
461 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
462 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
464 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
467 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
468 var identityKeyPair
= getIdentityKeyPair();
469 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
471 accountManager
.addDevice(deviceIdentifier
,
474 Optional
.of(account
.getProfileKey().serialize()),
476 account
.setMultiDevice(true);
479 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
480 if (!account
.isMasterDevice()) {
481 throw new RuntimeException("Only master device can set a PIN");
483 if (pin
.isPresent()) {
484 final var masterKey
= account
.getPinMasterKey() != null
485 ? account
.getPinMasterKey()
486 : KeyUtils
.createMasterKey();
488 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
490 account
.setRegistrationLockPin(pin
.get(), masterKey
);
492 // Remove legacy registration lock
493 accountManager
.removeRegistrationLockV1();
496 pinHelper
.removeRegistrationLockPin();
498 account
.setRegistrationLockPin(null, null);
502 void refreshPreKeys() throws IOException
{
503 var oneTimePreKeys
= generatePreKeys();
504 final var identityKeyPair
= getIdentityKeyPair();
505 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
507 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
510 private List
<PreKeyRecord
> generatePreKeys() {
511 final var offset
= account
.getPreKeyIdOffset();
513 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
514 account
.addPreKeys(records
);
519 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
520 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
522 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
523 account
.addSignedPreKey(record);
528 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
529 if (messagePipe
== null) {
530 messagePipe
= messageReceiver
.createMessagePipe();
535 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
536 if (unidentifiedMessagePipe
== null) {
537 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
539 return unidentifiedMessagePipe
;
542 private SignalServiceMessageSender
createMessageSender() {
543 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
545 account
.getUsername(),
546 account
.getPassword(),
547 account
.getDeviceId(),
548 account
.getSignalProtocolStore(),
551 account
.isMultiDevice(),
552 Optional
.fromNullable(messagePipe
),
553 Optional
.fromNullable(unidentifiedMessagePipe
),
555 clientZkProfileOperations
,
557 ServiceConfig
.MAX_ENVELOPE_SIZE
,
558 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
561 public Profile
getRecipientProfile(
562 RecipientId recipientId
564 return getRecipientProfile(recipientId
, false);
567 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
569 Profile
getRecipientProfile(
570 RecipientId recipientId
, boolean force
572 var profile
= account
.getProfileStore().getProfile(recipientId
);
574 var now
= new Date().getTime();
575 // Profiles are cached for 24h before retrieving them again, unless forced
576 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
580 synchronized (pendingProfileRequest
) {
581 if (pendingProfileRequest
.contains(recipientId
)) {
584 pendingProfileRequest
.add(recipientId
);
586 final SignalServiceProfile encryptedProfile
;
588 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
590 synchronized (pendingProfileRequest
) {
591 pendingProfileRequest
.remove(recipientId
);
594 if (encryptedProfile
== null) {
598 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
599 if (profileKey
== null) {
600 profile
= new Profile(new Date().getTime(),
605 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
606 ProfileUtils
.getCapabilities(encryptedProfile
));
608 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
610 account
.getProfileStore().storeProfile(recipientId
, profile
);
615 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
617 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
618 } catch (IOException e
) {
619 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
624 private ProfileAndCredential
retrieveProfileAndCredential(
625 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
626 ) throws IOException
{
627 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
628 final var profile
= profileAndCredential
.getProfile();
631 var newIdentity
= account
.getIdentityKeyStore()
632 .saveIdentity(recipientId
,
633 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
637 account
.getSessionStore().archiveSessions(recipientId
);
639 } catch (InvalidKeyException ignored
) {
640 logger
.warn("Got invalid identity key in profile for {}",
641 resolveSignalServiceAddress(recipientId
).getLegacyIdentifier());
643 return profileAndCredential
;
646 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
647 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
648 if (profileKeyCredential
!= null) {
649 return profileKeyCredential
;
652 ProfileAndCredential profileAndCredential
;
654 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
655 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
656 } catch (IOException e
) {
657 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
661 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
662 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
664 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
665 if (profileKey
!= null) {
666 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
668 profileAndCredential
.getProfile());
669 account
.getProfileStore().storeProfile(recipientId
, profile
);
672 return profileKeyCredential
;
675 private Profile
decryptProfileAndDownloadAvatar(
676 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
678 if (encryptedProfile
.getAvatar() != null) {
679 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
682 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
685 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
686 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
687 if (streamDetails
== null) {
688 return Optional
.absent();
691 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
694 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
695 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
696 if (streamDetails
== null) {
697 return Optional
.absent();
700 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
703 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
704 var g
= getGroup(groupId
);
706 throw new GroupNotFoundException(groupId
);
708 if (!g
.isMember(account
.getSelfRecipientId())) {
709 throw new NotAGroupMemberException(groupId
, g
.getTitle());
714 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
715 var g
= getGroup(groupId
);
717 throw new GroupNotFoundException(groupId
);
719 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
720 throw new NotAGroupMemberException(groupId
, g
.getTitle());
725 public List
<GroupInfo
> getGroups() {
726 return account
.getGroupStore().getGroups();
729 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
730 String messageText
, List
<String
> attachments
, GroupId groupId
731 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
732 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
733 if (attachments
!= null) {
734 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
737 return sendGroupMessage(messageBuilder
, groupId
);
740 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
741 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
742 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
743 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
744 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
746 resolveSignalServiceAddress(targetAuthorRecipientId
),
747 targetSentTimestamp
);
748 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
750 return sendGroupMessage(messageBuilder
, groupId
);
753 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
754 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
755 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
756 final var g
= getGroupForSending(groupId
);
758 GroupUtils
.setGroupContext(messageBuilder
, g
);
759 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
761 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
764 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
765 SignalServiceDataMessage
.Builder messageBuilder
;
767 final var g
= getGroupForUpdating(groupId
);
768 if (g
instanceof GroupInfoV1
) {
769 var groupInfoV1
= (GroupInfoV1
) g
;
770 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
771 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
772 groupInfoV1
.removeMember(account
.getSelfRecipientId());
773 account
.getGroupStore().updateGroup(groupInfoV1
);
775 final var groupInfoV2
= (GroupInfoV2
) g
;
776 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
777 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
778 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
779 account
.getGroupStore().updateGroup(groupInfoV2
);
782 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
785 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
786 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
787 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
788 final var membersRecipientIds
= members
== null ?
null : getSignalServiceAddresses(members
);
789 if (membersRecipientIds
!= null) {
790 membersRecipientIds
.remove(account
.getSelfRecipientId());
792 return sendUpdateGroupMessage(groupId
, name
, membersRecipientIds
, avatarFile
);
795 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
796 GroupId groupId
, String name
, Set
<RecipientId
> members
, File avatarFile
797 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
799 SignalServiceDataMessage
.Builder messageBuilder
;
800 if (groupId
== null) {
802 var gv2Pair
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
803 members
== null ? Set
.of() : members
,
805 if (gv2Pair
== null) {
806 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
807 gv1
.addMembers(List
.of(account
.getSelfRecipientId()));
808 updateGroupV1(gv1
, name
, members
, avatarFile
);
809 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
812 final var gv2
= gv2Pair
.first();
813 final var decryptedGroup
= gv2Pair
.second();
815 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
816 if (avatarFile
!= null) {
817 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
818 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
820 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
824 var group
= getGroupForUpdating(groupId
);
825 if (group
instanceof GroupInfoV2
) {
826 final var groupInfoV2
= (GroupInfoV2
) group
;
828 Pair
<Long
, List
<SendMessageResult
>> result
= null;
829 if (groupInfoV2
.isPendingMember(account
.getSelfRecipientId())) {
830 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
831 result
= sendUpdateGroupMessage(groupInfoV2
,
832 groupGroupChangePair
.first(),
833 groupGroupChangePair
.second());
836 if (members
!= null) {
837 final var newMembers
= new HashSet
<>(members
);
838 newMembers
.removeAll(group
.getMembers());
839 if (newMembers
.size() > 0) {
840 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
841 result
= sendUpdateGroupMessage(groupInfoV2
,
842 groupGroupChangePair
.first(),
843 groupGroupChangePair
.second());
846 if (result
== null || name
!= null || avatarFile
!= null) {
847 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
848 if (avatarFile
!= null) {
849 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
850 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
852 result
= sendUpdateGroupMessage(groupInfoV2
,
853 groupGroupChangePair
.first(),
854 groupGroupChangePair
.second());
857 return new Pair
<>(group
.getGroupId(), result
.second());
859 var gv1
= (GroupInfoV1
) group
;
860 updateGroupV1(gv1
, name
, members
, avatarFile
);
861 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
866 account
.getGroupStore().updateGroup(g
);
868 final var result
= sendMessage(messageBuilder
,
869 g
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
870 return new Pair
<>(g
.getGroupId(), result
.second());
873 private void updateGroupV1(
874 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
875 ) throws IOException
{
880 if (members
!= null) {
881 final var newMemberAddresses
= members
.stream()
882 .filter(member
-> !g
.isMember(member
))
883 .map(this::resolveSignalServiceAddress
)
884 .collect(Collectors
.toList());
885 final var newE164Members
= new HashSet
<String
>();
886 for (var member
: newMemberAddresses
) {
887 if (!member
.getNumber().isPresent()) {
890 newE164Members
.add(member
.getNumber().get());
893 final var registeredUsers
= getRegisteredUsers(newE164Members
);
894 if (registeredUsers
.size() != newE164Members
.size()) {
895 // Some of the new members are not registered on Signal
896 newE164Members
.removeAll(registeredUsers
.keySet());
897 throw new IOException("Failed to add members "
898 + String
.join(", ", newE164Members
)
899 + " to group: Not registered on Signal");
902 g
.addMembers(members
);
905 if (avatarFile
!= null) {
906 avatarStore
.storeGroupAvatar(g
.getGroupId(),
907 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
911 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
912 GroupInviteLinkUrl inviteLinkUrl
913 ) throws IOException
, GroupLinkNotActiveException
{
914 return sendJoinGroupMessage(inviteLinkUrl
);
917 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
918 GroupInviteLinkUrl inviteLinkUrl
919 ) throws IOException
, GroupLinkNotActiveException
{
920 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
921 inviteLinkUrl
.getPassword());
922 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
923 inviteLinkUrl
.getPassword(),
925 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
926 groupJoinInfo
.getRevision() + 1,
927 groupChange
.toByteArray());
929 if (group
.getGroup() == null) {
930 // Only requested member, can't send update to group members
931 return new Pair
<>(group
.getGroupId(), List
.of());
934 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
936 return new Pair
<>(group
.getGroupId(), result
.second());
939 private static int currentTimeDays() {
940 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
943 private GroupsV2AuthorizationString
getGroupAuthForToday(
944 final GroupSecretParams groupSecretParams
945 ) throws IOException
{
946 final var today
= currentTimeDays();
947 // Returns credentials for the next 7 days
948 final var credentials
= groupsV2Api
.getCredentials(today
);
949 // TODO cache credentials until they expire
950 var authCredentialResponse
= credentials
.get(today
);
952 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
955 authCredentialResponse
);
956 } catch (VerificationFailedException e
) {
957 throw new IOException(e
);
961 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
962 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
963 ) throws IOException
{
964 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
965 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
966 account
.getGroupStore().updateGroup(group
);
967 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
970 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
971 GroupIdV1 groupId
, SignalServiceAddress recipient
972 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
974 var group
= getGroupForSending(groupId
);
975 if (!(group
instanceof GroupInfoV1
)) {
976 throw new RuntimeException("Received an invalid group request for a v2 group!");
978 g
= (GroupInfoV1
) group
;
980 final var recipientId
= resolveRecipient(recipient
);
981 if (!g
.isMember(recipientId
)) {
982 throw new NotAGroupMemberException(groupId
, g
.name
);
985 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
987 // Send group message only to the recipient who requested it
988 return sendMessage(messageBuilder
, Set
.of(recipientId
));
991 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
992 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
993 .withId(g
.getGroupId().serialize())
995 .withMembers(g
.getMembers()
997 .map(this::resolveSignalServiceAddress
)
998 .collect(Collectors
.toList()));
1001 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
1002 if (attachment
.isPresent()) {
1003 group
.withAvatar(attachment
.get());
1005 } catch (IOException e
) {
1006 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
1009 return SignalServiceDataMessage
.newBuilder()
1010 .asGroupMessage(group
.build())
1011 .withExpiration(g
.getMessageExpirationTime());
1014 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
1015 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
1016 .withRevision(g
.getGroup().getRevision())
1017 .withSignedGroupChange(signedGroupChange
);
1018 return SignalServiceDataMessage
.newBuilder()
1019 .asGroupMessage(group
.build())
1020 .withExpiration(g
.getMessageExpirationTime());
1023 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
1024 GroupIdV1 groupId
, SignalServiceAddress recipient
1025 ) throws IOException
{
1026 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
1028 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
1030 // Send group info request message to the recipient who sent us a message with this groupId
1031 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1035 SignalServiceAddress remoteAddress
, long messageId
1036 ) throws IOException
, UntrustedIdentityException
{
1037 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1039 System
.currentTimeMillis());
1041 createMessageSender().sendReceipt(remoteAddress
,
1042 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1046 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1047 String messageText
, List
<String
> attachments
, List
<String
> recipients
1048 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1049 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1050 if (attachments
!= null) {
1051 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1053 // Upload attachments here, so we only upload once even for multiple recipients
1054 var messageSender
= createMessageSender();
1055 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1056 for (var attachment
: attachmentStreams
) {
1057 if (attachment
.isStream()) {
1058 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1059 } else if (attachment
.isPointer()) {
1060 attachmentPointers
.add(attachment
.asPointer());
1064 messageBuilder
.withAttachments(attachmentPointers
);
1066 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1069 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1070 String messageText
, List
<String
> attachments
1071 ) throws IOException
, AttachmentInvalidException
{
1072 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1073 if (attachments
!= null) {
1074 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1076 return sendSelfMessage(messageBuilder
);
1079 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1080 long targetSentTimestamp
, List
<String
> recipients
1081 ) throws IOException
, InvalidNumberException
{
1082 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1083 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1084 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1087 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1088 long targetSentTimestamp
, GroupId groupId
1089 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1090 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1091 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1092 return sendGroupMessage(messageBuilder
, groupId
);
1095 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1096 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1097 ) throws IOException
, InvalidNumberException
{
1098 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1099 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1101 resolveSignalServiceAddress(targetAuthorRecipientId
),
1102 targetSentTimestamp
);
1103 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1104 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1107 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1108 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1110 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1112 return sendMessage(messageBuilder
, signalServiceAddresses
);
1113 } catch (Exception e
) {
1114 for (var address
: signalServiceAddresses
) {
1115 handleEndSession(address
);
1121 void renewSession(RecipientId recipientId
) throws IOException
{
1122 account
.getSessionStore().archiveSessions(recipientId
);
1123 if (!recipientId
.equals(getSelfRecipientId())) {
1124 sendNullMessage(recipientId
);
1128 public String
getContactName(String number
) throws InvalidNumberException
{
1129 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1130 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1133 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1134 if (!account
.isMasterDevice()) {
1135 throw new NotMasterDeviceException();
1137 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1138 var contact
= account
.getContactStore().getContact(recipientId
);
1139 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1140 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1143 public void setContactBlocked(
1144 String number
, boolean blocked
1145 ) throws InvalidNumberException
, NotMasterDeviceException
{
1146 if (!account
.isMasterDevice()) {
1147 throw new NotMasterDeviceException();
1149 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1152 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1153 var contact
= account
.getContactStore().getContact(recipientId
);
1154 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1155 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1158 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1159 var group
= getGroup(groupId
);
1160 if (group
== null) {
1161 throw new GroupNotFoundException(groupId
);
1164 group
.setBlocked(blocked
);
1165 account
.getGroupStore().updateGroup(group
);
1168 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1169 var contact
= account
.getContactStore().getContact(recipientId
);
1170 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1173 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1174 account
.getContactStore()
1175 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1178 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1179 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1180 sendMessage(messageBuilder
, Set
.of(recipientId
));
1184 * Change the expiration timer for a contact
1186 public void setExpirationTimer(
1187 String number
, int messageExpirationTimer
1188 ) throws IOException
, InvalidNumberException
{
1189 var recipientId
= canonicalizeAndResolveRecipient(number
);
1190 setExpirationTimer(recipientId
, messageExpirationTimer
);
1191 sendExpirationTimerUpdate(recipientId
);
1195 * Change the expiration timer for a group
1197 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1198 var g
= getGroup(groupId
);
1199 if (g
instanceof GroupInfoV1
) {
1200 var groupInfoV1
= (GroupInfoV1
) g
;
1201 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1202 account
.getGroupStore().updateGroup(groupInfoV1
);
1204 throw new RuntimeException("TODO Not implemented!");
1209 * Upload the sticker pack from path.
1211 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1212 * @return if successful, returns the URL to install the sticker pack in the signal app
1214 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1215 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1217 var messageSender
= createMessageSender();
1219 var packKey
= KeyUtils
.createStickerUploadKey();
1220 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1222 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1223 account
.getStickerStore().updateSticker(sticker
);
1226 return new URI("https",
1229 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1230 Hex
.toStringCondensed(packKey
),
1231 StandardCharsets
.UTF_8
)).toString();
1232 } catch (URISyntaxException e
) {
1233 throw new AssertionError(e
);
1237 public void requestAllSyncData() throws IOException
{
1238 requestSyncGroups();
1239 requestSyncContacts();
1240 requestSyncBlocked();
1241 requestSyncConfiguration();
1245 private void requestSyncGroups() throws IOException
{
1246 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1247 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1249 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1251 sendSyncMessage(message
);
1252 } catch (UntrustedIdentityException e
) {
1253 throw new AssertionError(e
);
1257 private void requestSyncContacts() throws IOException
{
1258 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1259 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1261 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1263 sendSyncMessage(message
);
1264 } catch (UntrustedIdentityException e
) {
1265 throw new AssertionError(e
);
1269 private void requestSyncBlocked() throws IOException
{
1270 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1271 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1273 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1275 sendSyncMessage(message
);
1276 } catch (UntrustedIdentityException e
) {
1277 throw new AssertionError(e
);
1281 private void requestSyncConfiguration() throws IOException
{
1282 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1283 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1285 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1287 sendSyncMessage(message
);
1288 } catch (UntrustedIdentityException e
) {
1289 throw new AssertionError(e
);
1293 private void requestSyncKeys() throws IOException
{
1294 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1295 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1297 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1299 sendSyncMessage(message
);
1300 } catch (UntrustedIdentityException e
) {
1301 throw new AssertionError(e
);
1305 private byte[] getSenderCertificate() {
1308 if (account
.isPhoneNumberShared()) {
1309 certificate
= accountManager
.getSenderCertificate();
1311 certificate
= accountManager
.getSenderCertificateForPhoneNumberPrivacy();
1313 } catch (IOException e
) {
1314 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1317 // TODO cache for a day
1321 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1322 var messageSender
= createMessageSender();
1323 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1326 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1327 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1328 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1330 for (var number
: numbers
) {
1331 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1332 if (resolvedAddress
.getUuid().isPresent()) {
1333 signalServiceAddresses
.add(resolvedAddress
);
1335 addressesMissingUuid
.add(resolvedAddress
);
1339 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1340 .map(a
-> a
.getNumber().get())
1341 .collect(Collectors
.toSet());
1342 Map
<String
, UUID
> registeredUsers
;
1344 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1345 } catch (IOException e
) {
1346 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1347 registeredUsers
= Map
.of();
1350 for (var address
: addressesMissingUuid
) {
1351 final var number
= address
.getNumber().get();
1352 if (registeredUsers
.containsKey(number
)) {
1353 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1354 registeredUsers
.get(number
),
1356 signalServiceAddresses
.add(newAddress
);
1358 signalServiceAddresses
.add(address
);
1362 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1365 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1366 final var address
= resolveSignalServiceAddress(recipientId
);
1367 if (!address
.getNumber().isPresent()) {
1370 final var number
= address
.getNumber().get();
1371 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1372 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1375 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1377 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1379 serviceEnvironmentConfig
.getCdsMrenclave());
1380 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1381 throw new IOException(e
);
1385 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1386 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1387 ) throws IOException
{
1388 final var timestamp
= System
.currentTimeMillis();
1389 messageBuilder
.withTimestamp(timestamp
);
1390 getOrCreateMessagePipe();
1391 getOrCreateUnidentifiedMessagePipe();
1392 SignalServiceDataMessage message
= null;
1394 message
= messageBuilder
.build();
1395 if (message
.getGroupContext().isPresent()) {
1397 var messageSender
= createMessageSender();
1398 final var isRecipientUpdate
= false;
1399 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1400 final var addresses
= recipientIdList
.stream()
1401 .map(this::resolveSignalServiceAddress
)
1402 .collect(Collectors
.toList());
1403 var result
= messageSender
.sendMessage(addresses
,
1404 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1408 for (var r
: result
) {
1409 if (r
.getIdentityFailure() != null) {
1410 final var recipientId
= resolveRecipient(r
.getAddress());
1411 final var newIdentity
= account
.getIdentityKeyStore()
1412 .saveIdentity(recipientId
, r
.getIdentityFailure().getIdentityKey(), new Date());
1414 account
.getSessionStore().archiveSessions(recipientId
);
1419 return new Pair
<>(timestamp
, result
);
1420 } catch (UntrustedIdentityException e
) {
1421 return new Pair
<>(timestamp
, List
.of());
1424 // Send to all individually, so sync messages are sent correctly
1425 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1426 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1427 for (var recipientId
: recipientIds
) {
1428 final var contact
= account
.getContactStore().getContact(recipientId
);
1429 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1430 messageBuilder
.withExpiration(expirationTime
);
1431 message
= messageBuilder
.build();
1432 results
.add(sendMessage(recipientId
, message
));
1434 return new Pair
<>(timestamp
, results
);
1437 if (message
!= null && message
.isEndSession()) {
1438 for (var recipient
: recipientIds
) {
1439 handleEndSession(recipient
);
1445 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1446 SignalServiceDataMessage
.Builder messageBuilder
1447 ) throws IOException
{
1448 final var timestamp
= System
.currentTimeMillis();
1449 messageBuilder
.withTimestamp(timestamp
);
1450 getOrCreateMessagePipe();
1451 getOrCreateUnidentifiedMessagePipe();
1452 final var recipientId
= account
.getSelfRecipientId();
1454 final var contact
= account
.getContactStore().getContact(recipientId
);
1455 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1456 messageBuilder
.withExpiration(expirationTime
);
1458 var message
= messageBuilder
.build();
1459 final var result
= sendSelfMessage(message
);
1460 return new Pair
<>(timestamp
, result
);
1463 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1464 var messageSender
= createMessageSender();
1466 var recipientId
= account
.getSelfRecipientId();
1468 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipientId
);
1469 var recipient
= resolveSignalServiceAddress(recipientId
);
1470 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1471 message
.getTimestamp(),
1473 message
.getExpiresInSeconds(),
1474 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1476 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1479 var startTime
= System
.currentTimeMillis();
1480 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1481 return SendMessageResult
.success(recipient
,
1482 unidentifiedAccess
.isPresent(),
1484 System
.currentTimeMillis() - startTime
);
1485 } catch (UntrustedIdentityException e
) {
1486 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1490 private SendMessageResult
sendMessage(
1491 RecipientId recipientId
, SignalServiceDataMessage message
1492 ) throws IOException
{
1493 var messageSender
= createMessageSender();
1495 final var address
= resolveSignalServiceAddress(recipientId
);
1498 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
), message
);
1499 } catch (UnregisteredUserException e
) {
1500 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1501 return messageSender
.sendMessage(resolveSignalServiceAddress(newRecipientId
),
1502 unidentifiedAccessHelper
.getAccessFor(newRecipientId
),
1505 } catch (UntrustedIdentityException e
) {
1506 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1510 private SendMessageResult
sendNullMessage(RecipientId recipientId
) throws IOException
{
1511 var messageSender
= createMessageSender();
1513 final var address
= resolveSignalServiceAddress(recipientId
);
1516 return messageSender
.sendNullMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
));
1517 } catch (UnregisteredUserException e
) {
1518 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1519 final var newAddress
= resolveSignalServiceAddress(newRecipientId
);
1520 return messageSender
.sendNullMessage(newAddress
, unidentifiedAccessHelper
.getAccessFor(newRecipientId
));
1522 } catch (UntrustedIdentityException e
) {
1523 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1527 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, ProtocolUntrustedIdentityException
{
1528 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1529 account
.getSignalProtocolStore(),
1531 certificateValidator
);
1532 return cipher
.decrypt(envelope
);
1535 private void handleEndSession(RecipientId recipientId
) {
1536 account
.getSessionStore().deleteAllSessions(recipientId
);
1539 private List
<HandleAction
> handleSignalServiceDataMessage(
1540 SignalServiceDataMessage message
,
1542 SignalServiceAddress source
,
1543 SignalServiceAddress destination
,
1544 boolean ignoreAttachments
1546 var actions
= new ArrayList
<HandleAction
>();
1547 if (message
.getGroupContext().isPresent()) {
1548 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1549 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1550 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1551 var group
= getGroup(groupId
);
1552 if (group
== null || group
instanceof GroupInfoV1
) {
1553 var groupV1
= (GroupInfoV1
) group
;
1554 switch (groupInfo
.getType()) {
1556 if (groupV1
== null) {
1557 groupV1
= new GroupInfoV1(groupId
);
1560 if (groupInfo
.getAvatar().isPresent()) {
1561 var avatar
= groupInfo
.getAvatar().get();
1562 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1565 if (groupInfo
.getName().isPresent()) {
1566 groupV1
.name
= groupInfo
.getName().get();
1569 if (groupInfo
.getMembers().isPresent()) {
1570 groupV1
.addMembers(groupInfo
.getMembers()
1573 .map(this::resolveRecipient
)
1574 .collect(Collectors
.toSet()));
1577 account
.getGroupStore().updateGroup(groupV1
);
1581 if (groupV1
== null && !isSync
) {
1582 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1586 if (groupV1
!= null) {
1587 groupV1
.removeMember(resolveRecipient(source
));
1588 account
.getGroupStore().updateGroup(groupV1
);
1593 if (groupV1
!= null && !isSync
) {
1594 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1599 // Received a group v1 message for a v2 group
1602 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1603 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1604 final var groupMasterKey
= groupContext
.getMasterKey();
1606 getOrMigrateGroup(groupMasterKey
,
1607 groupContext
.getRevision(),
1608 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1612 final var conversationPartnerAddress
= isSync ? destination
: source
;
1613 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1614 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1616 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1617 if (message
.getGroupContext().isPresent()) {
1618 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1619 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1620 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1621 if (group
!= null) {
1622 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1623 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1624 account
.getGroupStore().updateGroup(group
);
1627 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1628 // disappearing message timer already stored in the DecryptedGroup
1630 } else if (conversationPartnerAddress
!= null) {
1631 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1634 if (!ignoreAttachments
) {
1635 if (message
.getAttachments().isPresent()) {
1636 for (var attachment
: message
.getAttachments().get()) {
1637 downloadAttachment(attachment
);
1640 if (message
.getSharedContacts().isPresent()) {
1641 for (var contact
: message
.getSharedContacts().get()) {
1642 if (contact
.getAvatar().isPresent()) {
1643 downloadAttachment(contact
.getAvatar().get().getAttachment());
1648 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1649 final ProfileKey profileKey
;
1651 profileKey
= new ProfileKey(message
.getProfileKey().get());
1652 } catch (InvalidInputException e
) {
1653 throw new AssertionError(e
);
1655 if (source
.matches(account
.getSelfAddress())) {
1656 this.account
.setProfileKey(profileKey
);
1658 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1660 if (message
.getPreviews().isPresent()) {
1661 final var previews
= message
.getPreviews().get();
1662 for (var preview
: previews
) {
1663 if (preview
.getImage().isPresent()) {
1664 downloadAttachment(preview
.getImage().get());
1668 if (message
.getQuote().isPresent()) {
1669 final var quote
= message
.getQuote().get();
1671 for (var quotedAttachment
: quote
.getAttachments()) {
1672 final var thumbnail
= quotedAttachment
.getThumbnail();
1673 if (thumbnail
!= null) {
1674 downloadAttachment(thumbnail
);
1678 if (message
.getSticker().isPresent()) {
1679 final var messageSticker
= message
.getSticker().get();
1680 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1681 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1682 if (sticker
== null) {
1683 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1684 account
.getStickerStore().updateSticker(sticker
);
1690 private GroupInfoV2
getOrMigrateGroup(
1691 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1693 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1695 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1696 var groupInfo
= getGroup(groupId
);
1697 final GroupInfoV2 groupInfoV2
;
1698 if (groupInfo
instanceof GroupInfoV1
) {
1699 // Received a v2 group message for a v1 group, we need to locally migrate the group
1700 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1701 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1702 logger
.info("Locally migrated group {} to group v2, id: {}",
1703 groupInfo
.getGroupId().toBase64(),
1704 groupInfoV2
.getGroupId().toBase64());
1705 } else if (groupInfo
instanceof GroupInfoV2
) {
1706 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1708 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1711 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1712 DecryptedGroup group
= null;
1713 if (signedGroupChange
!= null
1714 && groupInfoV2
.getGroup() != null
1715 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1716 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1718 if (group
== null) {
1719 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1721 if (group
!= null) {
1722 storeProfileKeysFromMembers(group
);
1723 final var avatar
= group
.getAvatar();
1724 if (avatar
!= null && !avatar
.isEmpty()) {
1725 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1728 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1729 account
.getGroupStore().updateGroup(groupInfoV2
);
1735 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1736 for (var member
: group
.getMembersList()) {
1737 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
1738 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
1740 account
.getProfileStore()
1741 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
1742 } catch (InvalidInputException ignored
) {
1747 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1748 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1749 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1750 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1751 if (actions
!= null) {
1752 queuedActions
.addAll(actions
);
1755 for (var action
: queuedActions
) {
1757 action
.execute(this);
1758 } catch (Throwable e
) {
1759 logger
.warn("Message action failed.", e
);
1764 private List
<HandleAction
> retryFailedReceivedMessage(
1765 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1767 var envelope
= cachedMessage
.loadEnvelope();
1768 if (envelope
== null) {
1771 SignalServiceContent content
= null;
1772 List
<HandleAction
> actions
= null;
1773 if (!envelope
.isReceipt()) {
1775 content
= decryptMessage(envelope
);
1776 } catch (ProtocolUntrustedIdentityException e
) {
1777 if (!envelope
.hasSource()) {
1778 final var identifier
= e
.getSender();
1779 final var recipientId
= resolveRecipient(identifier
);
1781 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1782 } catch (IOException ioException
) {
1783 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1787 } catch (Exception er
) {
1788 // All other errors are not recoverable, so delete the cached message
1789 cachedMessage
.delete();
1792 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1794 handler
.handleMessage(envelope
, content
, null);
1795 cachedMessage
.delete();
1799 public void receiveMessages(
1802 boolean returnOnTimeout
,
1803 boolean ignoreAttachments
,
1804 ReceiveMessageHandler handler
1805 ) throws IOException
{
1806 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1808 Set
<HandleAction
> queuedActions
= null;
1810 final var messagePipe
= getOrCreateMessagePipe();
1812 var hasCaughtUpWithOldMessages
= false;
1815 SignalServiceEnvelope envelope
;
1816 SignalServiceContent content
= null;
1817 Exception exception
= null;
1818 final CachedMessage
[] cachedMessage
= {null};
1820 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1821 final var recipientId
= envelope1
.hasSource()
1822 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1824 // store message on disk, before acknowledging receipt to the server
1825 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1827 if (result
.isPresent()) {
1828 envelope
= result
.get();
1830 // Received indicator that server queue is empty
1831 hasCaughtUpWithOldMessages
= true;
1833 if (queuedActions
!= null) {
1834 for (var action
: queuedActions
) {
1836 action
.execute(this);
1837 } catch (Throwable e
) {
1838 logger
.warn("Message action failed.", e
);
1841 queuedActions
.clear();
1842 queuedActions
= null;
1845 // Continue to wait another timeout for new messages
1848 } catch (TimeoutException e
) {
1849 if (returnOnTimeout
) return;
1853 if (envelope
.hasSource()) {
1854 // Store uuid if we don't have it already
1855 // address/uuid in envelope is sent by server
1856 resolveRecipientTrusted(envelope
.getSourceAddress());
1858 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1859 if (!envelope
.isReceipt()) {
1861 content
= decryptMessage(envelope
);
1862 } catch (Exception e
) {
1865 if (!envelope
.hasSource() && content
!= null) {
1866 // Store uuid if we don't have it already
1867 // address/uuid is validated by unidentified sender certificate
1868 resolveRecipientTrusted(content
.getSender());
1870 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1871 if (exception
instanceof ProtocolInvalidMessageException
) {
1872 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
1873 logger
.debug("Received invalid message, queuing renew session action.");
1874 actions
.add(new RenewSessionAction(sender
));
1876 if (hasCaughtUpWithOldMessages
) {
1877 for (var action
: actions
) {
1879 action
.execute(this);
1880 } catch (Throwable e
) {
1881 logger
.warn("Message action failed.", e
);
1885 if (queuedActions
== null) {
1886 queuedActions
= new HashSet
<>();
1888 queuedActions
.addAll(actions
);
1891 if (isMessageBlocked(envelope
, content
)) {
1892 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1893 } else if (notAGroupMember
) {
1894 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1896 handler
.handleMessage(envelope
, content
, exception
);
1898 if (cachedMessage
[0] != null) {
1899 if (exception
instanceof ProtocolUntrustedIdentityException
) {
1900 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
1901 final var recipientId
= resolveRecipient(identifier
);
1902 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1903 if (!envelope
.hasSource()) {
1905 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1906 } catch (IOException ioException
) {
1907 logger
.warn("Failed to move cached message to recipient folder: {}",
1908 ioException
.getMessage());
1912 cachedMessage
[0].delete();
1918 private boolean isMessageBlocked(
1919 SignalServiceEnvelope envelope
, SignalServiceContent content
1921 SignalServiceAddress source
;
1922 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1923 source
= envelope
.getSourceAddress();
1924 } else if (content
!= null) {
1925 source
= content
.getSender();
1929 final var recipientId
= resolveRecipient(source
);
1930 if (isContactBlocked(recipientId
)) {
1934 if (content
!= null && content
.getDataMessage().isPresent()) {
1935 var message
= content
.getDataMessage().get();
1936 if (message
.getGroupContext().isPresent()) {
1937 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1938 var group
= getGroup(groupId
);
1939 if (group
!= null && group
.isBlocked()) {
1947 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
1948 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
1949 return isContactBlocked(recipientId
);
1952 private boolean isContactBlocked(final RecipientId recipientId
) {
1953 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1954 return sourceContact
!= null && sourceContact
.isBlocked();
1957 private boolean isNotAGroupMember(
1958 SignalServiceEnvelope envelope
, SignalServiceContent content
1960 SignalServiceAddress source
;
1961 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1962 source
= envelope
.getSourceAddress();
1963 } else if (content
!= null) {
1964 source
= content
.getSender();
1969 if (content
!= null && content
.getDataMessage().isPresent()) {
1970 var message
= content
.getDataMessage().get();
1971 if (message
.getGroupContext().isPresent()) {
1972 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1973 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1974 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1978 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1979 var group
= getGroup(groupId
);
1980 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
1988 private List
<HandleAction
> handleMessage(
1989 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1991 var actions
= new ArrayList
<HandleAction
>();
1992 if (content
!= null) {
1993 final SignalServiceAddress sender
;
1994 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1995 sender
= envelope
.getSourceAddress();
1997 sender
= content
.getSender();
2000 if (content
.getDataMessage().isPresent()) {
2001 var message
= content
.getDataMessage().get();
2003 if (content
.isNeedsReceipt()) {
2004 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
2007 actions
.addAll(handleSignalServiceDataMessage(message
,
2010 account
.getSelfAddress(),
2011 ignoreAttachments
));
2013 if (content
.getSyncMessage().isPresent()) {
2014 account
.setMultiDevice(true);
2015 var syncMessage
= content
.getSyncMessage().get();
2016 if (syncMessage
.getSent().isPresent()) {
2017 var message
= syncMessage
.getSent().get();
2018 final var destination
= message
.getDestination().orNull();
2019 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
2023 ignoreAttachments
));
2025 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
2026 var rm
= syncMessage
.getRequest().get();
2027 if (rm
.isContactsRequest()) {
2028 actions
.add(SendSyncContactsAction
.create());
2030 if (rm
.isGroupsRequest()) {
2031 actions
.add(SendSyncGroupsAction
.create());
2033 if (rm
.isBlockedListRequest()) {
2034 actions
.add(SendSyncBlockedListAction
.create());
2036 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2038 if (syncMessage
.getGroups().isPresent()) {
2039 File tmpFile
= null;
2041 tmpFile
= IOUtils
.createTempFile();
2042 final var groupsMessage
= syncMessage
.getGroups().get();
2043 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2044 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2046 while ((g
= s
.read()) != null) {
2047 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2048 if (syncGroup
!= null) {
2049 if (g
.getName().isPresent()) {
2050 syncGroup
.name
= g
.getName().get();
2052 syncGroup
.addMembers(g
.getMembers()
2054 .map(this::resolveRecipient
)
2055 .collect(Collectors
.toSet()));
2056 if (!g
.isActive()) {
2057 syncGroup
.removeMember(account
.getSelfRecipientId());
2059 // Add ourself to the member set as it's marked as active
2060 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2062 syncGroup
.blocked
= g
.isBlocked();
2063 if (g
.getColor().isPresent()) {
2064 syncGroup
.color
= g
.getColor().get();
2067 if (g
.getAvatar().isPresent()) {
2068 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2070 syncGroup
.archived
= g
.isArchived();
2071 account
.getGroupStore().updateGroup(syncGroup
);
2075 } catch (Exception e
) {
2076 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2080 if (tmpFile
!= null) {
2082 Files
.delete(tmpFile
.toPath());
2083 } catch (IOException e
) {
2084 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2091 if (syncMessage
.getBlockedList().isPresent()) {
2092 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2093 for (var address
: blockedListMessage
.getAddresses()) {
2094 setContactBlocked(resolveRecipient(address
), true);
2096 for (var groupId
: blockedListMessage
.getGroupIds()
2098 .map(GroupId
::unknownVersion
)
2099 .collect(Collectors
.toSet())) {
2101 setGroupBlocked(groupId
, true);
2102 } catch (GroupNotFoundException e
) {
2103 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2104 groupId
.toBase64());
2108 if (syncMessage
.getContacts().isPresent()) {
2109 File tmpFile
= null;
2111 tmpFile
= IOUtils
.createTempFile();
2112 final var contactsMessage
= syncMessage
.getContacts().get();
2113 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2114 .asPointer(), tmpFile
)) {
2115 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2117 while ((c
= s
.read()) != null) {
2118 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2119 account
.setProfileKey(c
.getProfileKey().get());
2121 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2122 var contact
= account
.getContactStore().getContact(recipientId
);
2123 final var builder
= contact
== null
2124 ? Contact
.newBuilder()
2125 : Contact
.newBuilder(contact
);
2126 if (c
.getName().isPresent()) {
2127 builder
.withName(c
.getName().get());
2129 if (c
.getColor().isPresent()) {
2130 builder
.withColor(c
.getColor().get());
2132 if (c
.getProfileKey().isPresent()) {
2133 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2135 if (c
.getVerified().isPresent()) {
2136 final var verifiedMessage
= c
.getVerified().get();
2137 account
.getIdentityKeyStore()
2138 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2139 verifiedMessage
.getIdentityKey(),
2140 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2142 if (c
.getExpirationTimer().isPresent()) {
2143 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2145 builder
.withBlocked(c
.isBlocked());
2146 builder
.withArchived(c
.isArchived());
2147 account
.getContactStore().storeContact(recipientId
, builder
.build());
2149 if (c
.getAvatar().isPresent()) {
2150 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2154 } catch (Exception e
) {
2155 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2159 if (tmpFile
!= null) {
2161 Files
.delete(tmpFile
.toPath());
2162 } catch (IOException e
) {
2163 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2170 if (syncMessage
.getVerified().isPresent()) {
2171 final var verifiedMessage
= syncMessage
.getVerified().get();
2172 account
.getIdentityKeyStore()
2173 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2174 verifiedMessage
.getIdentityKey(),
2175 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2177 if (syncMessage
.getStickerPackOperations().isPresent()) {
2178 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2179 for (var m
: stickerPackOperationMessages
) {
2180 if (!m
.getPackId().isPresent()) {
2183 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2184 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2185 if (sticker
== null) {
2186 if (!m
.getPackKey().isPresent()) {
2189 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2191 sticker
.setInstalled(!m
.getType().isPresent()
2192 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2193 account
.getStickerStore().updateSticker(sticker
);
2196 if (syncMessage
.getFetchType().isPresent()) {
2197 switch (syncMessage
.getFetchType().get()) {
2199 getRecipientProfile(account
.getSelfRecipientId(), true);
2200 case STORAGE_MANIFEST
:
2204 if (syncMessage
.getKeys().isPresent()) {
2205 final var keysMessage
= syncMessage
.getKeys().get();
2206 if (keysMessage
.getStorageService().isPresent()) {
2207 final var storageKey
= keysMessage
.getStorageService().get();
2208 account
.setStorageKey(storageKey
);
2211 if (syncMessage
.getConfiguration().isPresent()) {
2219 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2221 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2222 } catch (IOException e
) {
2223 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2227 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2229 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2230 } catch (IOException e
) {
2231 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2235 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2237 avatarStore
.storeGroupAvatar(groupId
,
2238 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2239 } catch (IOException e
) {
2240 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2244 private void downloadProfileAvatar(
2245 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2248 avatarStore
.storeProfileAvatar(address
,
2249 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2250 } catch (Throwable e
) {
2251 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2255 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2256 return attachmentStore
.getAttachmentFile(attachmentId
);
2259 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2260 if (!attachment
.isPointer()) {
2261 logger
.warn("Invalid state, can't store an attachment stream.");
2264 var pointer
= attachment
.asPointer();
2265 if (pointer
.getPreview().isPresent()) {
2266 final var preview
= pointer
.getPreview().get();
2268 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2269 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2270 } catch (IOException e
) {
2271 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2276 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2277 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2278 } catch (IOException e
) {
2279 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2283 private void retrieveGroupV2Avatar(
2284 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2285 ) throws IOException
{
2286 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2288 var tmpFile
= IOUtils
.createTempFile();
2289 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2291 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2292 var encryptedData
= IOUtils
.readFully(input
);
2294 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2295 outputStream
.write(decryptedData
);
2298 Files
.delete(tmpFile
.toPath());
2299 } catch (IOException e
) {
2300 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2307 private void retrieveProfileAvatar(
2308 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2309 ) throws IOException
{
2310 var tmpFile
= IOUtils
.createTempFile();
2311 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2314 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2315 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2316 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2319 Files
.delete(tmpFile
.toPath());
2320 } catch (IOException e
) {
2321 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2328 private void retrieveAttachment(
2329 final SignalServiceAttachment attachment
, final OutputStream outputStream
2330 ) throws IOException
{
2331 if (attachment
.isPointer()) {
2332 var pointer
= attachment
.asPointer();
2333 retrieveAttachmentPointer(pointer
, outputStream
);
2335 var stream
= attachment
.asStream();
2336 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2340 private void retrieveAttachmentPointer(
2341 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2342 ) throws IOException
{
2343 var tmpFile
= IOUtils
.createTempFile();
2344 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2345 IOUtils
.copyStream(input
, outputStream
);
2346 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2347 throw new IOException(e
);
2350 Files
.delete(tmpFile
.toPath());
2351 } catch (IOException e
) {
2352 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2359 private InputStream
retrieveAttachmentAsStream(
2360 SignalServiceAttachmentPointer pointer
, File tmpFile
2361 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2362 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2365 void sendGroups() throws IOException
, UntrustedIdentityException
{
2366 var groupsFile
= IOUtils
.createTempFile();
2369 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2370 var out
= new DeviceGroupsOutputStream(fos
);
2371 for (var record : getGroups()) {
2372 if (record instanceof GroupInfoV1
) {
2373 var groupInfo
= (GroupInfoV1
) record;
2374 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2375 Optional
.fromNullable(groupInfo
.name
),
2376 groupInfo
.getMembers()
2378 .map(this::resolveSignalServiceAddress
)
2379 .collect(Collectors
.toList()),
2380 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2381 groupInfo
.isMember(account
.getSelfRecipientId()),
2382 Optional
.of(groupInfo
.messageExpirationTime
),
2383 Optional
.fromNullable(groupInfo
.color
),
2386 groupInfo
.archived
));
2391 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2392 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2393 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2394 .withStream(groupsFileStream
)
2395 .withContentType("application/octet-stream")
2396 .withLength(groupsFile
.length())
2399 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2404 Files
.delete(groupsFile
.toPath());
2405 } catch (IOException e
) {
2406 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2411 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2412 var contactsFile
= IOUtils
.createTempFile();
2415 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2416 var out
= new DeviceContactsOutputStream(fos
);
2417 for (var contactPair
: account
.getContactStore().getContacts()) {
2418 final var recipientId
= contactPair
.first();
2419 final var contact
= contactPair
.second();
2420 final var address
= resolveSignalServiceAddress(recipientId
);
2422 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2423 VerifiedMessage verifiedMessage
= null;
2424 if (currentIdentity
!= null) {
2425 verifiedMessage
= new VerifiedMessage(address
,
2426 currentIdentity
.getIdentityKey(),
2427 currentIdentity
.getTrustLevel().toVerifiedState(),
2428 currentIdentity
.getDateAdded().getTime());
2431 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2432 out
.write(new DeviceContact(address
,
2433 Optional
.fromNullable(contact
.getName()),
2434 createContactAvatarAttachment(address
),
2435 Optional
.fromNullable(contact
.getColor()),
2436 Optional
.fromNullable(verifiedMessage
),
2437 Optional
.fromNullable(profileKey
),
2438 contact
.isBlocked(),
2439 Optional
.of(contact
.getMessageExpirationTime()),
2441 contact
.isArchived()));
2444 if (account
.getProfileKey() != null) {
2445 // Send our own profile key as well
2446 out
.write(new DeviceContact(account
.getSelfAddress(),
2451 Optional
.of(account
.getProfileKey()),
2459 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2460 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2461 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2462 .withStream(contactsFileStream
)
2463 .withContentType("application/octet-stream")
2464 .withLength(contactsFile
.length())
2467 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2472 Files
.delete(contactsFile
.toPath());
2473 } catch (IOException e
) {
2474 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2479 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2480 var addresses
= new ArrayList
<SignalServiceAddress
>();
2481 for (var record : account
.getContactStore().getContacts()) {
2482 if (record.second().isBlocked()) {
2483 addresses
.add(resolveSignalServiceAddress(record.first()));
2486 var groupIds
= new ArrayList
<byte[]>();
2487 for (var record : getGroups()) {
2488 if (record.isBlocked()) {
2489 groupIds
.add(record.getGroupId().serialize());
2492 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2495 private void sendVerifiedMessage(
2496 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2497 ) throws IOException
, UntrustedIdentityException
{
2498 var verifiedMessage
= new VerifiedMessage(destination
,
2500 trustLevel
.toVerifiedState(),
2501 System
.currentTimeMillis());
2502 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2505 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2506 return account
.getContactStore().getContacts();
2509 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2510 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2511 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2512 if (recipient
== null) {
2516 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2517 return recipient
.getContact().getName();
2520 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2521 return recipient
.getProfile().getDisplayName();
2527 public GroupInfo
getGroup(GroupId groupId
) {
2528 final var group
= account
.getGroupStore().getGroup(groupId
);
2529 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2530 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2531 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2532 account
.getGroupStore().updateGroup(group
);
2537 public List
<IdentityInfo
> getIdentities() {
2538 return account
.getIdentityKeyStore().getIdentities();
2541 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2542 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2543 return identity
== null ? List
.of() : List
.of(identity
);
2547 * Trust this the identity with this fingerprint
2549 * @param name username of the identity
2550 * @param fingerprint Fingerprint
2552 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2553 var recipientId
= canonicalizeAndResolveRecipient(name
);
2554 return trustIdentity(recipientId
,
2555 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2556 TrustLevel
.TRUSTED_VERIFIED
);
2560 * Trust this the identity with this safety number
2562 * @param name username of the identity
2563 * @param safetyNumber Safety number
2565 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2566 var recipientId
= canonicalizeAndResolveRecipient(name
);
2567 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2568 return trustIdentity(recipientId
,
2569 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2570 TrustLevel
.TRUSTED_VERIFIED
);
2574 * Trust all keys of this identity without verification
2576 * @param name username of the identity
2578 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2579 var recipientId
= canonicalizeAndResolveRecipient(name
);
2580 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2583 private boolean trustIdentity(
2584 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2586 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2587 if (identity
== null) {
2591 if (!verifier
.apply(identity
.getIdentityKey())) {
2595 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2597 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2598 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2599 } catch (IOException
| UntrustedIdentityException e
) {
2600 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2606 public String
computeSafetyNumber(
2607 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2609 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2610 account
.getSelfAddress(),
2611 getIdentityKeyPair().getPublicKey(),
2617 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2618 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2620 return resolveSignalServiceAddress(address
);
2624 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2625 if (address
.matches(account
.getSelfAddress())) {
2626 return account
.getSelfAddress();
2629 return account
.getRecipientStore().resolveServiceAddress(address
);
2632 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2633 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2636 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2637 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2639 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2641 return resolveRecipient(canonicalizedNumber
);
2644 private RecipientId
resolveRecipient(final String identifier
) {
2645 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2647 return resolveRecipient(address
);
2650 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2651 return account
.getRecipientStore().resolveRecipient(address
);
2654 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2655 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2659 public void close() throws IOException
{
2663 void close(boolean closeAccount
) throws IOException
{
2664 executor
.shutdown();
2666 if (messagePipe
!= null) {
2667 messagePipe
.shutdown();
2671 if (unidentifiedMessagePipe
!= null) {
2672 unidentifiedMessagePipe
.shutdown();
2673 unidentifiedMessagePipe
= null;
2676 if (closeAccount
&& account
!= null) {
2682 public interface ReceiveMessageHandler
{
2684 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);