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
, String description
, 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
, description
, membersRecipientIds
, avatarFile
);
795 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
796 GroupId groupId
, String name
, String description
, 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 // TODO set description as well
813 final var gv2
= gv2Pair
.first();
814 final var decryptedGroup
= gv2Pair
.second();
816 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
817 if (avatarFile
!= null) {
818 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
819 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
821 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
825 var group
= getGroupForUpdating(groupId
);
826 if (group
instanceof GroupInfoV2
) {
827 final var groupInfoV2
= (GroupInfoV2
) group
;
829 Pair
<Long
, List
<SendMessageResult
>> result
= null;
830 if (groupInfoV2
.isPendingMember(account
.getSelfRecipientId())) {
831 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
832 result
= sendUpdateGroupMessage(groupInfoV2
,
833 groupGroupChangePair
.first(),
834 groupGroupChangePair
.second());
837 if (members
!= null) {
838 final var newMembers
= new HashSet
<>(members
);
839 newMembers
.removeAll(group
.getMembers());
840 if (newMembers
.size() > 0) {
841 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
842 result
= sendUpdateGroupMessage(groupInfoV2
,
843 groupGroupChangePair
.first(),
844 groupGroupChangePair
.second());
847 if (result
== null || name
!= null || description
!= null || avatarFile
!= null) {
848 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, description
, avatarFile
);
849 if (avatarFile
!= null) {
850 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
851 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
853 result
= sendUpdateGroupMessage(groupInfoV2
,
854 groupGroupChangePair
.first(),
855 groupGroupChangePair
.second());
858 return new Pair
<>(group
.getGroupId(), result
.second());
860 var gv1
= (GroupInfoV1
) group
;
861 updateGroupV1(gv1
, name
, members
, avatarFile
);
862 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
867 account
.getGroupStore().updateGroup(g
);
869 final var result
= sendMessage(messageBuilder
,
870 g
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
871 return new Pair
<>(g
.getGroupId(), result
.second());
874 private void updateGroupV1(
875 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
876 ) throws IOException
{
881 if (members
!= null) {
882 final var newMemberAddresses
= members
.stream()
883 .filter(member
-> !g
.isMember(member
))
884 .map(this::resolveSignalServiceAddress
)
885 .collect(Collectors
.toList());
886 final var newE164Members
= new HashSet
<String
>();
887 for (var member
: newMemberAddresses
) {
888 if (!member
.getNumber().isPresent()) {
891 newE164Members
.add(member
.getNumber().get());
894 final var registeredUsers
= getRegisteredUsers(newE164Members
);
895 if (registeredUsers
.size() != newE164Members
.size()) {
896 // Some of the new members are not registered on Signal
897 newE164Members
.removeAll(registeredUsers
.keySet());
898 throw new IOException("Failed to add members "
899 + String
.join(", ", newE164Members
)
900 + " to group: Not registered on Signal");
903 g
.addMembers(members
);
906 if (avatarFile
!= null) {
907 avatarStore
.storeGroupAvatar(g
.getGroupId(),
908 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
912 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
913 GroupInviteLinkUrl inviteLinkUrl
914 ) throws IOException
, GroupLinkNotActiveException
{
915 return sendJoinGroupMessage(inviteLinkUrl
);
918 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
919 GroupInviteLinkUrl inviteLinkUrl
920 ) throws IOException
, GroupLinkNotActiveException
{
921 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
922 inviteLinkUrl
.getPassword());
923 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
924 inviteLinkUrl
.getPassword(),
926 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
927 groupJoinInfo
.getRevision() + 1,
928 groupChange
.toByteArray());
930 if (group
.getGroup() == null) {
931 // Only requested member, can't send update to group members
932 return new Pair
<>(group
.getGroupId(), List
.of());
935 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
937 return new Pair
<>(group
.getGroupId(), result
.second());
940 private static int currentTimeDays() {
941 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
944 private GroupsV2AuthorizationString
getGroupAuthForToday(
945 final GroupSecretParams groupSecretParams
946 ) throws IOException
{
947 final var today
= currentTimeDays();
948 // Returns credentials for the next 7 days
949 final var credentials
= groupsV2Api
.getCredentials(today
);
950 // TODO cache credentials until they expire
951 var authCredentialResponse
= credentials
.get(today
);
953 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
956 authCredentialResponse
);
957 } catch (VerificationFailedException e
) {
958 throw new IOException(e
);
962 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
963 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
964 ) throws IOException
{
965 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
966 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
967 account
.getGroupStore().updateGroup(group
);
968 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
971 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
972 GroupIdV1 groupId
, SignalServiceAddress recipient
973 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
975 var group
= getGroupForSending(groupId
);
976 if (!(group
instanceof GroupInfoV1
)) {
977 throw new RuntimeException("Received an invalid group request for a v2 group!");
979 g
= (GroupInfoV1
) group
;
981 final var recipientId
= resolveRecipient(recipient
);
982 if (!g
.isMember(recipientId
)) {
983 throw new NotAGroupMemberException(groupId
, g
.name
);
986 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
988 // Send group message only to the recipient who requested it
989 return sendMessage(messageBuilder
, Set
.of(recipientId
));
992 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
993 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
994 .withId(g
.getGroupId().serialize())
996 .withMembers(g
.getMembers()
998 .map(this::resolveSignalServiceAddress
)
999 .collect(Collectors
.toList()));
1002 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
1003 if (attachment
.isPresent()) {
1004 group
.withAvatar(attachment
.get());
1006 } catch (IOException e
) {
1007 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
1010 return SignalServiceDataMessage
.newBuilder()
1011 .asGroupMessage(group
.build())
1012 .withExpiration(g
.getMessageExpirationTime());
1015 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
1016 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
1017 .withRevision(g
.getGroup().getRevision())
1018 .withSignedGroupChange(signedGroupChange
);
1019 return SignalServiceDataMessage
.newBuilder()
1020 .asGroupMessage(group
.build())
1021 .withExpiration(g
.getMessageExpirationTime());
1024 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
1025 GroupIdV1 groupId
, SignalServiceAddress recipient
1026 ) throws IOException
{
1027 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
1029 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
1031 // Send group info request message to the recipient who sent us a message with this groupId
1032 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1036 SignalServiceAddress remoteAddress
, long messageId
1037 ) throws IOException
, UntrustedIdentityException
{
1038 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1040 System
.currentTimeMillis());
1042 createMessageSender().sendReceipt(remoteAddress
,
1043 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1047 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1048 String messageText
, List
<String
> attachments
, List
<String
> recipients
1049 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1050 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1051 if (attachments
!= null) {
1052 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1054 // Upload attachments here, so we only upload once even for multiple recipients
1055 var messageSender
= createMessageSender();
1056 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1057 for (var attachment
: attachmentStreams
) {
1058 if (attachment
.isStream()) {
1059 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1060 } else if (attachment
.isPointer()) {
1061 attachmentPointers
.add(attachment
.asPointer());
1065 messageBuilder
.withAttachments(attachmentPointers
);
1067 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1070 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1071 String messageText
, List
<String
> attachments
1072 ) throws IOException
, AttachmentInvalidException
{
1073 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1074 if (attachments
!= null) {
1075 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1077 return sendSelfMessage(messageBuilder
);
1080 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1081 long targetSentTimestamp
, List
<String
> recipients
1082 ) throws IOException
, InvalidNumberException
{
1083 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1084 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1085 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1088 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1089 long targetSentTimestamp
, GroupId groupId
1090 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1091 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1092 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1093 return sendGroupMessage(messageBuilder
, groupId
);
1096 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1097 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1098 ) throws IOException
, InvalidNumberException
{
1099 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1100 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1102 resolveSignalServiceAddress(targetAuthorRecipientId
),
1103 targetSentTimestamp
);
1104 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1105 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1108 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1109 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1111 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1113 return sendMessage(messageBuilder
, signalServiceAddresses
);
1114 } catch (Exception e
) {
1115 for (var address
: signalServiceAddresses
) {
1116 handleEndSession(address
);
1122 void renewSession(RecipientId recipientId
) throws IOException
{
1123 account
.getSessionStore().archiveSessions(recipientId
);
1124 if (!recipientId
.equals(getSelfRecipientId())) {
1125 sendNullMessage(recipientId
);
1129 public String
getContactName(String number
) throws InvalidNumberException
{
1130 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1131 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1134 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1135 if (!account
.isMasterDevice()) {
1136 throw new NotMasterDeviceException();
1138 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1139 var contact
= account
.getContactStore().getContact(recipientId
);
1140 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1141 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1144 public void setContactBlocked(
1145 String number
, boolean blocked
1146 ) throws InvalidNumberException
, NotMasterDeviceException
{
1147 if (!account
.isMasterDevice()) {
1148 throw new NotMasterDeviceException();
1150 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1153 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1154 var contact
= account
.getContactStore().getContact(recipientId
);
1155 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1156 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1159 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1160 var group
= getGroup(groupId
);
1161 if (group
== null) {
1162 throw new GroupNotFoundException(groupId
);
1165 group
.setBlocked(blocked
);
1166 account
.getGroupStore().updateGroup(group
);
1169 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1170 var contact
= account
.getContactStore().getContact(recipientId
);
1171 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1174 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1175 account
.getContactStore()
1176 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1179 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1180 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1181 sendMessage(messageBuilder
, Set
.of(recipientId
));
1185 * Change the expiration timer for a contact
1187 public void setExpirationTimer(
1188 String number
, int messageExpirationTimer
1189 ) throws IOException
, InvalidNumberException
{
1190 var recipientId
= canonicalizeAndResolveRecipient(number
);
1191 setExpirationTimer(recipientId
, messageExpirationTimer
);
1192 sendExpirationTimerUpdate(recipientId
);
1196 * Change the expiration timer for a group
1198 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1199 var g
= getGroup(groupId
);
1200 if (g
instanceof GroupInfoV1
) {
1201 var groupInfoV1
= (GroupInfoV1
) g
;
1202 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1203 account
.getGroupStore().updateGroup(groupInfoV1
);
1205 throw new RuntimeException("TODO Not implemented!");
1210 * Upload the sticker pack from path.
1212 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1213 * @return if successful, returns the URL to install the sticker pack in the signal app
1215 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1216 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1218 var messageSender
= createMessageSender();
1220 var packKey
= KeyUtils
.createStickerUploadKey();
1221 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1223 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1224 account
.getStickerStore().updateSticker(sticker
);
1227 return new URI("https",
1230 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1231 Hex
.toStringCondensed(packKey
),
1232 StandardCharsets
.UTF_8
)).toString();
1233 } catch (URISyntaxException e
) {
1234 throw new AssertionError(e
);
1238 public void requestAllSyncData() throws IOException
{
1239 requestSyncGroups();
1240 requestSyncContacts();
1241 requestSyncBlocked();
1242 requestSyncConfiguration();
1246 private void requestSyncGroups() throws IOException
{
1247 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1248 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1250 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1252 sendSyncMessage(message
);
1253 } catch (UntrustedIdentityException e
) {
1254 throw new AssertionError(e
);
1258 private void requestSyncContacts() throws IOException
{
1259 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1260 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1262 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1264 sendSyncMessage(message
);
1265 } catch (UntrustedIdentityException e
) {
1266 throw new AssertionError(e
);
1270 private void requestSyncBlocked() throws IOException
{
1271 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1272 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1274 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1276 sendSyncMessage(message
);
1277 } catch (UntrustedIdentityException e
) {
1278 throw new AssertionError(e
);
1282 private void requestSyncConfiguration() throws IOException
{
1283 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1284 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1286 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1288 sendSyncMessage(message
);
1289 } catch (UntrustedIdentityException e
) {
1290 throw new AssertionError(e
);
1294 private void requestSyncKeys() throws IOException
{
1295 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1296 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1298 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1300 sendSyncMessage(message
);
1301 } catch (UntrustedIdentityException e
) {
1302 throw new AssertionError(e
);
1306 private byte[] getSenderCertificate() {
1309 if (account
.isPhoneNumberShared()) {
1310 certificate
= accountManager
.getSenderCertificate();
1312 certificate
= accountManager
.getSenderCertificateForPhoneNumberPrivacy();
1314 } catch (IOException e
) {
1315 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1318 // TODO cache for a day
1322 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1323 var messageSender
= createMessageSender();
1324 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1327 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1328 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1329 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1331 for (var number
: numbers
) {
1332 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1333 if (resolvedAddress
.getUuid().isPresent()) {
1334 signalServiceAddresses
.add(resolvedAddress
);
1336 addressesMissingUuid
.add(resolvedAddress
);
1340 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1341 .map(a
-> a
.getNumber().get())
1342 .collect(Collectors
.toSet());
1343 Map
<String
, UUID
> registeredUsers
;
1345 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1346 } catch (IOException e
) {
1347 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1348 registeredUsers
= Map
.of();
1351 for (var address
: addressesMissingUuid
) {
1352 final var number
= address
.getNumber().get();
1353 if (registeredUsers
.containsKey(number
)) {
1354 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1355 registeredUsers
.get(number
),
1357 signalServiceAddresses
.add(newAddress
);
1359 signalServiceAddresses
.add(address
);
1363 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1366 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1367 final var address
= resolveSignalServiceAddress(recipientId
);
1368 if (!address
.getNumber().isPresent()) {
1371 final var number
= address
.getNumber().get();
1372 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1373 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1376 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1378 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1380 serviceEnvironmentConfig
.getCdsMrenclave());
1381 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1382 throw new IOException(e
);
1386 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1387 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1388 ) throws IOException
{
1389 final var timestamp
= System
.currentTimeMillis();
1390 messageBuilder
.withTimestamp(timestamp
);
1391 getOrCreateMessagePipe();
1392 getOrCreateUnidentifiedMessagePipe();
1393 SignalServiceDataMessage message
= null;
1395 message
= messageBuilder
.build();
1396 if (message
.getGroupContext().isPresent()) {
1398 var messageSender
= createMessageSender();
1399 final var isRecipientUpdate
= false;
1400 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1401 final var addresses
= recipientIdList
.stream()
1402 .map(this::resolveSignalServiceAddress
)
1403 .collect(Collectors
.toList());
1404 var result
= messageSender
.sendMessage(addresses
,
1405 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1409 for (var r
: result
) {
1410 if (r
.getIdentityFailure() != null) {
1411 final var recipientId
= resolveRecipient(r
.getAddress());
1412 final var newIdentity
= account
.getIdentityKeyStore()
1413 .saveIdentity(recipientId
, r
.getIdentityFailure().getIdentityKey(), new Date());
1415 account
.getSessionStore().archiveSessions(recipientId
);
1420 return new Pair
<>(timestamp
, result
);
1421 } catch (UntrustedIdentityException e
) {
1422 return new Pair
<>(timestamp
, List
.of());
1425 // Send to all individually, so sync messages are sent correctly
1426 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1427 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1428 for (var recipientId
: recipientIds
) {
1429 final var contact
= account
.getContactStore().getContact(recipientId
);
1430 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1431 messageBuilder
.withExpiration(expirationTime
);
1432 message
= messageBuilder
.build();
1433 results
.add(sendMessage(recipientId
, message
));
1435 return new Pair
<>(timestamp
, results
);
1438 if (message
!= null && message
.isEndSession()) {
1439 for (var recipient
: recipientIds
) {
1440 handleEndSession(recipient
);
1446 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1447 SignalServiceDataMessage
.Builder messageBuilder
1448 ) throws IOException
{
1449 final var timestamp
= System
.currentTimeMillis();
1450 messageBuilder
.withTimestamp(timestamp
);
1451 getOrCreateMessagePipe();
1452 getOrCreateUnidentifiedMessagePipe();
1453 final var recipientId
= account
.getSelfRecipientId();
1455 final var contact
= account
.getContactStore().getContact(recipientId
);
1456 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1457 messageBuilder
.withExpiration(expirationTime
);
1459 var message
= messageBuilder
.build();
1460 final var result
= sendSelfMessage(message
);
1461 return new Pair
<>(timestamp
, result
);
1464 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1465 var messageSender
= createMessageSender();
1467 var recipientId
= account
.getSelfRecipientId();
1469 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipientId
);
1470 var recipient
= resolveSignalServiceAddress(recipientId
);
1471 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1472 message
.getTimestamp(),
1474 message
.getExpiresInSeconds(),
1475 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1477 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1480 var startTime
= System
.currentTimeMillis();
1481 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1482 return SendMessageResult
.success(recipient
,
1483 unidentifiedAccess
.isPresent(),
1485 System
.currentTimeMillis() - startTime
);
1486 } catch (UntrustedIdentityException e
) {
1487 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1491 private SendMessageResult
sendMessage(
1492 RecipientId recipientId
, SignalServiceDataMessage message
1493 ) throws IOException
{
1494 var messageSender
= createMessageSender();
1496 final var address
= resolveSignalServiceAddress(recipientId
);
1499 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
), message
);
1500 } catch (UnregisteredUserException e
) {
1501 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1502 return messageSender
.sendMessage(resolveSignalServiceAddress(newRecipientId
),
1503 unidentifiedAccessHelper
.getAccessFor(newRecipientId
),
1506 } catch (UntrustedIdentityException e
) {
1507 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1511 private SendMessageResult
sendNullMessage(RecipientId recipientId
) throws IOException
{
1512 var messageSender
= createMessageSender();
1514 final var address
= resolveSignalServiceAddress(recipientId
);
1517 return messageSender
.sendNullMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
));
1518 } catch (UnregisteredUserException e
) {
1519 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1520 final var newAddress
= resolveSignalServiceAddress(newRecipientId
);
1521 return messageSender
.sendNullMessage(newAddress
, unidentifiedAccessHelper
.getAccessFor(newRecipientId
));
1523 } catch (UntrustedIdentityException e
) {
1524 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1528 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, ProtocolUntrustedIdentityException
{
1529 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1530 account
.getSignalProtocolStore(),
1532 certificateValidator
);
1533 return cipher
.decrypt(envelope
);
1536 private void handleEndSession(RecipientId recipientId
) {
1537 account
.getSessionStore().deleteAllSessions(recipientId
);
1540 private List
<HandleAction
> handleSignalServiceDataMessage(
1541 SignalServiceDataMessage message
,
1543 SignalServiceAddress source
,
1544 SignalServiceAddress destination
,
1545 boolean ignoreAttachments
1547 var actions
= new ArrayList
<HandleAction
>();
1548 if (message
.getGroupContext().isPresent()) {
1549 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1550 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1551 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1552 var group
= getGroup(groupId
);
1553 if (group
== null || group
instanceof GroupInfoV1
) {
1554 var groupV1
= (GroupInfoV1
) group
;
1555 switch (groupInfo
.getType()) {
1557 if (groupV1
== null) {
1558 groupV1
= new GroupInfoV1(groupId
);
1561 if (groupInfo
.getAvatar().isPresent()) {
1562 var avatar
= groupInfo
.getAvatar().get();
1563 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1566 if (groupInfo
.getName().isPresent()) {
1567 groupV1
.name
= groupInfo
.getName().get();
1570 if (groupInfo
.getMembers().isPresent()) {
1571 groupV1
.addMembers(groupInfo
.getMembers()
1574 .map(this::resolveRecipient
)
1575 .collect(Collectors
.toSet()));
1578 account
.getGroupStore().updateGroup(groupV1
);
1582 if (groupV1
== null && !isSync
) {
1583 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1587 if (groupV1
!= null) {
1588 groupV1
.removeMember(resolveRecipient(source
));
1589 account
.getGroupStore().updateGroup(groupV1
);
1594 if (groupV1
!= null && !isSync
) {
1595 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1600 // Received a group v1 message for a v2 group
1603 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1604 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1605 final var groupMasterKey
= groupContext
.getMasterKey();
1607 getOrMigrateGroup(groupMasterKey
,
1608 groupContext
.getRevision(),
1609 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1613 final var conversationPartnerAddress
= isSync ? destination
: source
;
1614 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1615 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1617 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1618 if (message
.getGroupContext().isPresent()) {
1619 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1620 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1621 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1622 if (group
!= null) {
1623 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1624 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1625 account
.getGroupStore().updateGroup(group
);
1628 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1629 // disappearing message timer already stored in the DecryptedGroup
1631 } else if (conversationPartnerAddress
!= null) {
1632 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1635 if (!ignoreAttachments
) {
1636 if (message
.getAttachments().isPresent()) {
1637 for (var attachment
: message
.getAttachments().get()) {
1638 downloadAttachment(attachment
);
1641 if (message
.getSharedContacts().isPresent()) {
1642 for (var contact
: message
.getSharedContacts().get()) {
1643 if (contact
.getAvatar().isPresent()) {
1644 downloadAttachment(contact
.getAvatar().get().getAttachment());
1649 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1650 final ProfileKey profileKey
;
1652 profileKey
= new ProfileKey(message
.getProfileKey().get());
1653 } catch (InvalidInputException e
) {
1654 throw new AssertionError(e
);
1656 if (source
.matches(account
.getSelfAddress())) {
1657 this.account
.setProfileKey(profileKey
);
1659 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1661 if (message
.getPreviews().isPresent()) {
1662 final var previews
= message
.getPreviews().get();
1663 for (var preview
: previews
) {
1664 if (preview
.getImage().isPresent()) {
1665 downloadAttachment(preview
.getImage().get());
1669 if (message
.getQuote().isPresent()) {
1670 final var quote
= message
.getQuote().get();
1672 for (var quotedAttachment
: quote
.getAttachments()) {
1673 final var thumbnail
= quotedAttachment
.getThumbnail();
1674 if (thumbnail
!= null) {
1675 downloadAttachment(thumbnail
);
1679 if (message
.getSticker().isPresent()) {
1680 final var messageSticker
= message
.getSticker().get();
1681 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1682 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1683 if (sticker
== null) {
1684 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1685 account
.getStickerStore().updateSticker(sticker
);
1691 private GroupInfoV2
getOrMigrateGroup(
1692 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1694 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1696 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1697 var groupInfo
= getGroup(groupId
);
1698 final GroupInfoV2 groupInfoV2
;
1699 if (groupInfo
instanceof GroupInfoV1
) {
1700 // Received a v2 group message for a v1 group, we need to locally migrate the group
1701 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1702 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1703 logger
.info("Locally migrated group {} to group v2, id: {}",
1704 groupInfo
.getGroupId().toBase64(),
1705 groupInfoV2
.getGroupId().toBase64());
1706 } else if (groupInfo
instanceof GroupInfoV2
) {
1707 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1709 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1712 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1713 DecryptedGroup group
= null;
1714 if (signedGroupChange
!= null
1715 && groupInfoV2
.getGroup() != null
1716 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1717 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1719 if (group
== null) {
1720 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1722 if (group
!= null) {
1723 storeProfileKeysFromMembers(group
);
1724 final var avatar
= group
.getAvatar();
1725 if (avatar
!= null && !avatar
.isEmpty()) {
1726 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1729 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1730 account
.getGroupStore().updateGroup(groupInfoV2
);
1736 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1737 for (var member
: group
.getMembersList()) {
1738 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
1739 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
1741 account
.getProfileStore()
1742 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
1743 } catch (InvalidInputException ignored
) {
1748 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1749 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1750 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1751 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1752 if (actions
!= null) {
1753 queuedActions
.addAll(actions
);
1756 for (var action
: queuedActions
) {
1758 action
.execute(this);
1759 } catch (Throwable e
) {
1760 logger
.warn("Message action failed.", e
);
1765 private List
<HandleAction
> retryFailedReceivedMessage(
1766 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1768 var envelope
= cachedMessage
.loadEnvelope();
1769 if (envelope
== null) {
1772 SignalServiceContent content
= null;
1773 List
<HandleAction
> actions
= null;
1774 if (!envelope
.isReceipt()) {
1776 content
= decryptMessage(envelope
);
1777 } catch (ProtocolUntrustedIdentityException e
) {
1778 if (!envelope
.hasSource()) {
1779 final var identifier
= e
.getSender();
1780 final var recipientId
= resolveRecipient(identifier
);
1782 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1783 } catch (IOException ioException
) {
1784 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1788 } catch (Exception er
) {
1789 // All other errors are not recoverable, so delete the cached message
1790 cachedMessage
.delete();
1793 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1795 handler
.handleMessage(envelope
, content
, null);
1796 cachedMessage
.delete();
1800 public void receiveMessages(
1803 boolean returnOnTimeout
,
1804 boolean ignoreAttachments
,
1805 ReceiveMessageHandler handler
1806 ) throws IOException
{
1807 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1809 Set
<HandleAction
> queuedActions
= null;
1811 final var messagePipe
= getOrCreateMessagePipe();
1813 var hasCaughtUpWithOldMessages
= false;
1816 SignalServiceEnvelope envelope
;
1817 SignalServiceContent content
= null;
1818 Exception exception
= null;
1819 final CachedMessage
[] cachedMessage
= {null};
1821 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1822 final var recipientId
= envelope1
.hasSource()
1823 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1825 // store message on disk, before acknowledging receipt to the server
1826 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1828 if (result
.isPresent()) {
1829 envelope
= result
.get();
1831 // Received indicator that server queue is empty
1832 hasCaughtUpWithOldMessages
= true;
1834 if (queuedActions
!= null) {
1835 for (var action
: queuedActions
) {
1837 action
.execute(this);
1838 } catch (Throwable e
) {
1839 logger
.warn("Message action failed.", e
);
1842 queuedActions
.clear();
1843 queuedActions
= null;
1846 // Continue to wait another timeout for new messages
1849 } catch (TimeoutException e
) {
1850 if (returnOnTimeout
) return;
1854 if (envelope
.hasSource()) {
1855 // Store uuid if we don't have it already
1856 // address/uuid in envelope is sent by server
1857 resolveRecipientTrusted(envelope
.getSourceAddress());
1859 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1860 if (!envelope
.isReceipt()) {
1862 content
= decryptMessage(envelope
);
1863 } catch (Exception e
) {
1866 if (!envelope
.hasSource() && content
!= null) {
1867 // Store uuid if we don't have it already
1868 // address/uuid is validated by unidentified sender certificate
1869 resolveRecipientTrusted(content
.getSender());
1871 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1872 if (exception
instanceof ProtocolInvalidMessageException
) {
1873 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
1874 logger
.debug("Received invalid message, queuing renew session action.");
1875 actions
.add(new RenewSessionAction(sender
));
1877 if (hasCaughtUpWithOldMessages
) {
1878 for (var action
: actions
) {
1880 action
.execute(this);
1881 } catch (Throwable e
) {
1882 logger
.warn("Message action failed.", e
);
1886 if (queuedActions
== null) {
1887 queuedActions
= new HashSet
<>();
1889 queuedActions
.addAll(actions
);
1892 if (isMessageBlocked(envelope
, content
)) {
1893 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1894 } else if (notAGroupMember
) {
1895 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1897 handler
.handleMessage(envelope
, content
, exception
);
1899 if (cachedMessage
[0] != null) {
1900 if (exception
instanceof ProtocolUntrustedIdentityException
) {
1901 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
1902 final var recipientId
= resolveRecipient(identifier
);
1903 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1904 if (!envelope
.hasSource()) {
1906 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1907 } catch (IOException ioException
) {
1908 logger
.warn("Failed to move cached message to recipient folder: {}",
1909 ioException
.getMessage());
1913 cachedMessage
[0].delete();
1919 private boolean isMessageBlocked(
1920 SignalServiceEnvelope envelope
, SignalServiceContent content
1922 SignalServiceAddress source
;
1923 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1924 source
= envelope
.getSourceAddress();
1925 } else if (content
!= null) {
1926 source
= content
.getSender();
1930 final var recipientId
= resolveRecipient(source
);
1931 if (isContactBlocked(recipientId
)) {
1935 if (content
!= null && content
.getDataMessage().isPresent()) {
1936 var message
= content
.getDataMessage().get();
1937 if (message
.getGroupContext().isPresent()) {
1938 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1939 var group
= getGroup(groupId
);
1940 if (group
!= null && group
.isBlocked()) {
1948 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
1949 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
1950 return isContactBlocked(recipientId
);
1953 private boolean isContactBlocked(final RecipientId recipientId
) {
1954 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1955 return sourceContact
!= null && sourceContact
.isBlocked();
1958 private boolean isNotAGroupMember(
1959 SignalServiceEnvelope envelope
, SignalServiceContent content
1961 SignalServiceAddress source
;
1962 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1963 source
= envelope
.getSourceAddress();
1964 } else if (content
!= null) {
1965 source
= content
.getSender();
1970 if (content
!= null && content
.getDataMessage().isPresent()) {
1971 var message
= content
.getDataMessage().get();
1972 if (message
.getGroupContext().isPresent()) {
1973 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1974 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1975 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1979 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1980 var group
= getGroup(groupId
);
1981 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
1989 private List
<HandleAction
> handleMessage(
1990 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1992 var actions
= new ArrayList
<HandleAction
>();
1993 if (content
!= null) {
1994 final SignalServiceAddress sender
;
1995 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1996 sender
= envelope
.getSourceAddress();
1998 sender
= content
.getSender();
2001 if (content
.getDataMessage().isPresent()) {
2002 var message
= content
.getDataMessage().get();
2004 if (content
.isNeedsReceipt()) {
2005 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
2008 actions
.addAll(handleSignalServiceDataMessage(message
,
2011 account
.getSelfAddress(),
2012 ignoreAttachments
));
2014 if (content
.getSyncMessage().isPresent()) {
2015 account
.setMultiDevice(true);
2016 var syncMessage
= content
.getSyncMessage().get();
2017 if (syncMessage
.getSent().isPresent()) {
2018 var message
= syncMessage
.getSent().get();
2019 final var destination
= message
.getDestination().orNull();
2020 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
2024 ignoreAttachments
));
2026 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
2027 var rm
= syncMessage
.getRequest().get();
2028 if (rm
.isContactsRequest()) {
2029 actions
.add(SendSyncContactsAction
.create());
2031 if (rm
.isGroupsRequest()) {
2032 actions
.add(SendSyncGroupsAction
.create());
2034 if (rm
.isBlockedListRequest()) {
2035 actions
.add(SendSyncBlockedListAction
.create());
2037 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2039 if (syncMessage
.getGroups().isPresent()) {
2040 File tmpFile
= null;
2042 tmpFile
= IOUtils
.createTempFile();
2043 final var groupsMessage
= syncMessage
.getGroups().get();
2044 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2045 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2047 while ((g
= s
.read()) != null) {
2048 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2049 if (syncGroup
!= null) {
2050 if (g
.getName().isPresent()) {
2051 syncGroup
.name
= g
.getName().get();
2053 syncGroup
.addMembers(g
.getMembers()
2055 .map(this::resolveRecipient
)
2056 .collect(Collectors
.toSet()));
2057 if (!g
.isActive()) {
2058 syncGroup
.removeMember(account
.getSelfRecipientId());
2060 // Add ourself to the member set as it's marked as active
2061 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2063 syncGroup
.blocked
= g
.isBlocked();
2064 if (g
.getColor().isPresent()) {
2065 syncGroup
.color
= g
.getColor().get();
2068 if (g
.getAvatar().isPresent()) {
2069 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2071 syncGroup
.archived
= g
.isArchived();
2072 account
.getGroupStore().updateGroup(syncGroup
);
2076 } catch (Exception e
) {
2077 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2081 if (tmpFile
!= null) {
2083 Files
.delete(tmpFile
.toPath());
2084 } catch (IOException e
) {
2085 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2092 if (syncMessage
.getBlockedList().isPresent()) {
2093 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2094 for (var address
: blockedListMessage
.getAddresses()) {
2095 setContactBlocked(resolveRecipient(address
), true);
2097 for (var groupId
: blockedListMessage
.getGroupIds()
2099 .map(GroupId
::unknownVersion
)
2100 .collect(Collectors
.toSet())) {
2102 setGroupBlocked(groupId
, true);
2103 } catch (GroupNotFoundException e
) {
2104 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2105 groupId
.toBase64());
2109 if (syncMessage
.getContacts().isPresent()) {
2110 File tmpFile
= null;
2112 tmpFile
= IOUtils
.createTempFile();
2113 final var contactsMessage
= syncMessage
.getContacts().get();
2114 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2115 .asPointer(), tmpFile
)) {
2116 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2118 while ((c
= s
.read()) != null) {
2119 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2120 account
.setProfileKey(c
.getProfileKey().get());
2122 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2123 var contact
= account
.getContactStore().getContact(recipientId
);
2124 final var builder
= contact
== null
2125 ? Contact
.newBuilder()
2126 : Contact
.newBuilder(contact
);
2127 if (c
.getName().isPresent()) {
2128 builder
.withName(c
.getName().get());
2130 if (c
.getColor().isPresent()) {
2131 builder
.withColor(c
.getColor().get());
2133 if (c
.getProfileKey().isPresent()) {
2134 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2136 if (c
.getVerified().isPresent()) {
2137 final var verifiedMessage
= c
.getVerified().get();
2138 account
.getIdentityKeyStore()
2139 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2140 verifiedMessage
.getIdentityKey(),
2141 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2143 if (c
.getExpirationTimer().isPresent()) {
2144 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2146 builder
.withBlocked(c
.isBlocked());
2147 builder
.withArchived(c
.isArchived());
2148 account
.getContactStore().storeContact(recipientId
, builder
.build());
2150 if (c
.getAvatar().isPresent()) {
2151 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2155 } catch (Exception e
) {
2156 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2160 if (tmpFile
!= null) {
2162 Files
.delete(tmpFile
.toPath());
2163 } catch (IOException e
) {
2164 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2171 if (syncMessage
.getVerified().isPresent()) {
2172 final var verifiedMessage
= syncMessage
.getVerified().get();
2173 account
.getIdentityKeyStore()
2174 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2175 verifiedMessage
.getIdentityKey(),
2176 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2178 if (syncMessage
.getStickerPackOperations().isPresent()) {
2179 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2180 for (var m
: stickerPackOperationMessages
) {
2181 if (!m
.getPackId().isPresent()) {
2184 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2185 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2186 if (sticker
== null) {
2187 if (!m
.getPackKey().isPresent()) {
2190 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2192 sticker
.setInstalled(!m
.getType().isPresent()
2193 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2194 account
.getStickerStore().updateSticker(sticker
);
2197 if (syncMessage
.getFetchType().isPresent()) {
2198 switch (syncMessage
.getFetchType().get()) {
2200 getRecipientProfile(account
.getSelfRecipientId(), true);
2201 case STORAGE_MANIFEST
:
2205 if (syncMessage
.getKeys().isPresent()) {
2206 final var keysMessage
= syncMessage
.getKeys().get();
2207 if (keysMessage
.getStorageService().isPresent()) {
2208 final var storageKey
= keysMessage
.getStorageService().get();
2209 account
.setStorageKey(storageKey
);
2212 if (syncMessage
.getConfiguration().isPresent()) {
2220 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2222 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2223 } catch (IOException e
) {
2224 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2228 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2230 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2231 } catch (IOException e
) {
2232 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2236 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2238 avatarStore
.storeGroupAvatar(groupId
,
2239 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2240 } catch (IOException e
) {
2241 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2245 private void downloadProfileAvatar(
2246 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2249 avatarStore
.storeProfileAvatar(address
,
2250 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2251 } catch (Throwable e
) {
2252 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2256 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2257 return attachmentStore
.getAttachmentFile(attachmentId
);
2260 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2261 if (!attachment
.isPointer()) {
2262 logger
.warn("Invalid state, can't store an attachment stream.");
2265 var pointer
= attachment
.asPointer();
2266 if (pointer
.getPreview().isPresent()) {
2267 final var preview
= pointer
.getPreview().get();
2269 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2270 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2271 } catch (IOException e
) {
2272 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2277 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2278 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2279 } catch (IOException e
) {
2280 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2284 private void retrieveGroupV2Avatar(
2285 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2286 ) throws IOException
{
2287 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2289 var tmpFile
= IOUtils
.createTempFile();
2290 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2292 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2293 var encryptedData
= IOUtils
.readFully(input
);
2295 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2296 outputStream
.write(decryptedData
);
2299 Files
.delete(tmpFile
.toPath());
2300 } catch (IOException e
) {
2301 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2308 private void retrieveProfileAvatar(
2309 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2310 ) throws IOException
{
2311 var tmpFile
= IOUtils
.createTempFile();
2312 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2315 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2316 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2317 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2320 Files
.delete(tmpFile
.toPath());
2321 } catch (IOException e
) {
2322 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2329 private void retrieveAttachment(
2330 final SignalServiceAttachment attachment
, final OutputStream outputStream
2331 ) throws IOException
{
2332 if (attachment
.isPointer()) {
2333 var pointer
= attachment
.asPointer();
2334 retrieveAttachmentPointer(pointer
, outputStream
);
2336 var stream
= attachment
.asStream();
2337 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2341 private void retrieveAttachmentPointer(
2342 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2343 ) throws IOException
{
2344 var tmpFile
= IOUtils
.createTempFile();
2345 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2346 IOUtils
.copyStream(input
, outputStream
);
2347 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2348 throw new IOException(e
);
2351 Files
.delete(tmpFile
.toPath());
2352 } catch (IOException e
) {
2353 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2360 private InputStream
retrieveAttachmentAsStream(
2361 SignalServiceAttachmentPointer pointer
, File tmpFile
2362 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2363 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2366 void sendGroups() throws IOException
, UntrustedIdentityException
{
2367 var groupsFile
= IOUtils
.createTempFile();
2370 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2371 var out
= new DeviceGroupsOutputStream(fos
);
2372 for (var record : getGroups()) {
2373 if (record instanceof GroupInfoV1
) {
2374 var groupInfo
= (GroupInfoV1
) record;
2375 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2376 Optional
.fromNullable(groupInfo
.name
),
2377 groupInfo
.getMembers()
2379 .map(this::resolveSignalServiceAddress
)
2380 .collect(Collectors
.toList()),
2381 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2382 groupInfo
.isMember(account
.getSelfRecipientId()),
2383 Optional
.of(groupInfo
.messageExpirationTime
),
2384 Optional
.fromNullable(groupInfo
.color
),
2387 groupInfo
.archived
));
2392 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2393 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2394 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2395 .withStream(groupsFileStream
)
2396 .withContentType("application/octet-stream")
2397 .withLength(groupsFile
.length())
2400 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2405 Files
.delete(groupsFile
.toPath());
2406 } catch (IOException e
) {
2407 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2412 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2413 var contactsFile
= IOUtils
.createTempFile();
2416 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2417 var out
= new DeviceContactsOutputStream(fos
);
2418 for (var contactPair
: account
.getContactStore().getContacts()) {
2419 final var recipientId
= contactPair
.first();
2420 final var contact
= contactPair
.second();
2421 final var address
= resolveSignalServiceAddress(recipientId
);
2423 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2424 VerifiedMessage verifiedMessage
= null;
2425 if (currentIdentity
!= null) {
2426 verifiedMessage
= new VerifiedMessage(address
,
2427 currentIdentity
.getIdentityKey(),
2428 currentIdentity
.getTrustLevel().toVerifiedState(),
2429 currentIdentity
.getDateAdded().getTime());
2432 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2433 out
.write(new DeviceContact(address
,
2434 Optional
.fromNullable(contact
.getName()),
2435 createContactAvatarAttachment(address
),
2436 Optional
.fromNullable(contact
.getColor()),
2437 Optional
.fromNullable(verifiedMessage
),
2438 Optional
.fromNullable(profileKey
),
2439 contact
.isBlocked(),
2440 Optional
.of(contact
.getMessageExpirationTime()),
2442 contact
.isArchived()));
2445 if (account
.getProfileKey() != null) {
2446 // Send our own profile key as well
2447 out
.write(new DeviceContact(account
.getSelfAddress(),
2452 Optional
.of(account
.getProfileKey()),
2460 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2461 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2462 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2463 .withStream(contactsFileStream
)
2464 .withContentType("application/octet-stream")
2465 .withLength(contactsFile
.length())
2468 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2473 Files
.delete(contactsFile
.toPath());
2474 } catch (IOException e
) {
2475 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2480 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2481 var addresses
= new ArrayList
<SignalServiceAddress
>();
2482 for (var record : account
.getContactStore().getContacts()) {
2483 if (record.second().isBlocked()) {
2484 addresses
.add(resolveSignalServiceAddress(record.first()));
2487 var groupIds
= new ArrayList
<byte[]>();
2488 for (var record : getGroups()) {
2489 if (record.isBlocked()) {
2490 groupIds
.add(record.getGroupId().serialize());
2493 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2496 private void sendVerifiedMessage(
2497 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2498 ) throws IOException
, UntrustedIdentityException
{
2499 var verifiedMessage
= new VerifiedMessage(destination
,
2501 trustLevel
.toVerifiedState(),
2502 System
.currentTimeMillis());
2503 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2506 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2507 return account
.getContactStore().getContacts();
2510 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2511 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2512 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2513 if (recipient
== null) {
2517 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2518 return recipient
.getContact().getName();
2521 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2522 return recipient
.getProfile().getDisplayName();
2528 public GroupInfo
getGroup(GroupId groupId
) {
2529 final var group
= account
.getGroupStore().getGroup(groupId
);
2530 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2531 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2532 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2533 account
.getGroupStore().updateGroup(group
);
2538 public List
<IdentityInfo
> getIdentities() {
2539 return account
.getIdentityKeyStore().getIdentities();
2542 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2543 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2544 return identity
== null ? List
.of() : List
.of(identity
);
2548 * Trust this the identity with this fingerprint
2550 * @param name username of the identity
2551 * @param fingerprint Fingerprint
2553 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2554 var recipientId
= canonicalizeAndResolveRecipient(name
);
2555 return trustIdentity(recipientId
,
2556 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2557 TrustLevel
.TRUSTED_VERIFIED
);
2561 * Trust this the identity with this safety number
2563 * @param name username of the identity
2564 * @param safetyNumber Safety number
2566 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2567 var recipientId
= canonicalizeAndResolveRecipient(name
);
2568 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2569 return trustIdentity(recipientId
,
2570 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2571 TrustLevel
.TRUSTED_VERIFIED
);
2575 * Trust all keys of this identity without verification
2577 * @param name username of the identity
2579 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2580 var recipientId
= canonicalizeAndResolveRecipient(name
);
2581 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2584 private boolean trustIdentity(
2585 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2587 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2588 if (identity
== null) {
2592 if (!verifier
.apply(identity
.getIdentityKey())) {
2596 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2598 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2599 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2600 } catch (IOException
| UntrustedIdentityException e
) {
2601 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2607 public String
computeSafetyNumber(
2608 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2610 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2611 account
.getSelfAddress(),
2612 getIdentityKeyPair().getPublicKey(),
2618 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2619 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2621 return resolveSignalServiceAddress(address
);
2625 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2626 if (address
.matches(account
.getSelfAddress())) {
2627 return account
.getSelfAddress();
2630 return account
.getRecipientStore().resolveServiceAddress(address
);
2633 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2634 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2637 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2638 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2640 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2642 return resolveRecipient(canonicalizedNumber
);
2645 private RecipientId
resolveRecipient(final String identifier
) {
2646 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2648 return resolveRecipient(address
);
2651 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2652 return account
.getRecipientStore().resolveRecipient(address
);
2655 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2656 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2660 public void close() throws IOException
{
2664 void close(boolean closeAccount
) throws IOException
{
2665 executor
.shutdown();
2667 if (messagePipe
!= null) {
2668 messagePipe
.shutdown();
2672 if (unidentifiedMessagePipe
!= null) {
2673 unidentifiedMessagePipe
.shutdown();
2674 unidentifiedMessagePipe
= null;
2677 if (closeAccount
&& account
!= null) {
2683 public interface ReceiveMessageHandler
{
2685 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);