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
.api
.Message
;
21 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
22 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
23 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
24 import org
.asamk
.signal
.manager
.api
.TypingAction
;
25 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
26 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
27 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
28 import org
.asamk
.signal
.manager
.groups
.GroupId
;
29 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
30 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
31 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
32 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
33 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
34 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
35 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
36 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
37 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
38 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
39 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
40 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
41 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
42 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
43 import org
.asamk
.signal
.manager
.jobs
.Context
;
44 import org
.asamk
.signal
.manager
.jobs
.Job
;
45 import org
.asamk
.signal
.manager
.jobs
.RetrieveStickerPackJob
;
46 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
47 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
48 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
49 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
50 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
51 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
52 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
53 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
55 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
56 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
57 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
58 import org
.asamk
.signal
.manager
.util
.IOUtils
;
59 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
60 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
61 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
62 import org
.asamk
.signal
.manager
.util
.Utils
;
63 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
64 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
65 import org
.signal
.zkgroup
.InvalidInputException
;
66 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
67 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
68 import org
.slf4j
.Logger
;
69 import org
.slf4j
.LoggerFactory
;
70 import org
.whispersystems
.libsignal
.IdentityKey
;
71 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
72 import org
.whispersystems
.libsignal
.InvalidKeyException
;
73 import org
.whispersystems
.libsignal
.InvalidMessageException
;
74 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
75 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
76 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintParsingException
;
77 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintVersionMismatchException
;
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
.SignalSessionLock
;
83 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
84 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
85 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
86 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
87 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
88 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
89 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
90 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
91 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
92 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
93 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
94 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
95 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
96 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
97 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
98 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
99 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
100 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
101 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
102 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
103 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
104 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
105 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
106 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
107 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
108 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
109 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
110 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
111 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
112 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
113 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
114 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
115 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
116 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
117 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
118 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
119 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
120 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
121 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
122 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
124 import java
.io
.Closeable
;
126 import java
.io
.FileInputStream
;
127 import java
.io
.FileOutputStream
;
128 import java
.io
.IOException
;
129 import java
.io
.InputStream
;
130 import java
.io
.OutputStream
;
132 import java
.net
.URISyntaxException
;
133 import java
.net
.URLEncoder
;
134 import java
.nio
.charset
.StandardCharsets
;
135 import java
.nio
.file
.Files
;
136 import java
.security
.SignatureException
;
137 import java
.util
.ArrayList
;
138 import java
.util
.Arrays
;
139 import java
.util
.Base64
;
140 import java
.util
.Collection
;
141 import java
.util
.Date
;
142 import java
.util
.HashMap
;
143 import java
.util
.HashSet
;
144 import java
.util
.List
;
145 import java
.util
.Map
;
146 import java
.util
.Set
;
147 import java
.util
.UUID
;
148 import java
.util
.concurrent
.ExecutorService
;
149 import java
.util
.concurrent
.Executors
;
150 import java
.util
.concurrent
.TimeUnit
;
151 import java
.util
.concurrent
.TimeoutException
;
152 import java
.util
.concurrent
.locks
.ReentrantLock
;
153 import java
.util
.function
.Function
;
154 import java
.util
.stream
.Collectors
;
156 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
158 public class Manager
implements Closeable
{
160 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
162 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
163 private final SignalDependencies dependencies
;
165 private SignalAccount account
;
167 private final ExecutorService executor
= Executors
.newCachedThreadPool();
169 private final ProfileHelper profileHelper
;
170 private final PinHelper pinHelper
;
171 private final SendHelper sendHelper
;
172 private final GroupHelper groupHelper
;
174 private final AvatarStore avatarStore
;
175 private final AttachmentStore attachmentStore
;
176 private final StickerPackStore stickerPackStore
;
177 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
178 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
181 public Lock
acquire() {
183 return LEGACY_LOCK
::unlock
;
188 SignalAccount account
,
189 PathConfig pathConfig
,
190 ServiceEnvironmentConfig serviceEnvironmentConfig
,
193 this.account
= account
;
194 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
196 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
197 account
.getUsername(),
198 account
.getPassword(),
199 account
.getDeviceId());
200 this.dependencies
= new SignalDependencies(account
.getSelfAddress(),
201 serviceEnvironmentConfig
,
204 account
.getSignalProtocolStore(),
207 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
209 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
210 account
.getProfileStore()::getProfileKey
,
211 this::getRecipientProfile
,
212 this::getSenderCertificate
);
213 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
214 unidentifiedAccessHelper
::getAccessFor
,
215 dependencies
::getProfileService
,
216 dependencies
::getMessageReceiver
,
217 this::resolveSignalServiceAddress
);
218 final GroupV2Helper groupV2Helper
= new GroupV2Helper(this::getRecipientProfileKeyCredential
,
219 this::getRecipientProfile
,
220 account
::getSelfRecipientId
,
221 dependencies
.getGroupsV2Operations(),
222 dependencies
.getGroupsV2Api(),
223 this::resolveSignalServiceAddress
);
224 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
225 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
226 this.stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
227 this.sendHelper
= new SendHelper(account
,
229 unidentifiedAccessHelper
,
230 this::resolveSignalServiceAddress
,
231 this::resolveRecipient
,
232 this::handleIdentityFailure
,
234 this::refreshRegisteredUser
);
235 this.groupHelper
= new GroupHelper(account
,
240 this::resolveSignalServiceAddress
,
241 this::resolveRecipient
);
244 public String
getUsername() {
245 return account
.getUsername();
248 public SignalServiceAddress
getSelfAddress() {
249 return account
.getSelfAddress();
252 public RecipientId
getSelfRecipientId() {
253 return account
.getSelfRecipientId();
256 private IdentityKeyPair
getIdentityKeyPair() {
257 return account
.getIdentityKeyPair();
260 public int getDeviceId() {
261 return account
.getDeviceId();
264 public static Manager
init(
267 ServiceEnvironment serviceEnvironment
,
269 final TrustNewIdentity trustNewIdentity
270 ) throws IOException
, NotRegisteredException
{
271 var pathConfig
= PathConfig
.createDefault(settingsPath
);
273 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
274 throw new NotRegisteredException();
277 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true, trustNewIdentity
);
279 if (!account
.isRegistered()) {
280 throw new NotRegisteredException();
283 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
285 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
288 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
289 var pathConfig
= PathConfig
.createDefault(settingsPath
);
290 final var dataPath
= pathConfig
.getDataPath();
291 final var files
= dataPath
.listFiles();
297 return Arrays
.stream(files
)
298 .filter(File
::isFile
)
300 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
301 .collect(Collectors
.toList());
304 public void checkAccountState() throws IOException
{
305 if (account
.getLastReceiveTimestamp() == 0) {
306 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
308 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
309 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
312 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
316 if (dependencies
.getAccountManager().getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
319 if (account
.getUuid() == null) {
320 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
322 updateAccountAttributes();
326 * This is used for checking a set of phone numbers for registration on Signal
328 * @param numbers The set of phone number in question
329 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
330 * @throws IOException if its unable to get the contacts to check if they're registered
332 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
333 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
335 return canonicalizePhoneNumber(n
);
336 } catch (InvalidNumberException e
) {
341 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
342 var contactDetails
= getRegisteredUsers(canonicalizedNumbers
.values()
344 .filter(s
-> !s
.isEmpty())
345 .collect(Collectors
.toSet()));
347 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
348 final var number
= canonicalizedNumbers
.get(n
);
349 final var uuid
= contactDetails
.get(number
);
350 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
354 public void updateAccountAttributes() throws IOException
{
355 dependencies
.getAccountManager()
356 .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 dependencies
.getAccountManager()
399 .setVersionedProfile(account
.getUuid(),
400 account
.getProfileKey(),
401 newProfile
.getInternalServiceName(),
402 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
403 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
408 if (avatar
!= null) {
409 if (avatar
.isPresent()) {
410 avatarStore
.storeProfileAvatar(getSelfAddress(),
411 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
413 avatarStore
.deleteProfileAvatar(getSelfAddress());
416 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
418 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
421 public void unregister() throws IOException
{
422 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
423 // If this is the master device, other users can't send messages to this number anymore.
424 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
425 dependencies
.getAccountManager().setGcmId(Optional
.absent());
427 account
.setRegistered(false);
430 public void deleteAccount() throws IOException
{
431 dependencies
.getAccountManager().deleteAccount();
433 account
.setRegistered(false);
436 public List
<Device
> getLinkedDevices() throws IOException
{
437 var devices
= dependencies
.getAccountManager().getDevices();
438 account
.setMultiDevice(devices
.size() > 1);
439 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
440 return devices
.stream().map(d
-> {
441 String deviceName
= d
.getName();
442 if (deviceName
!= null) {
444 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
445 } catch (IOException e
) {
446 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
449 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
450 }).collect(Collectors
.toList());
453 public void removeLinkedDevices(int deviceId
) throws IOException
{
454 dependencies
.getAccountManager().removeDevice(deviceId
);
455 var devices
= dependencies
.getAccountManager().getDevices();
456 account
.setMultiDevice(devices
.size() > 1);
459 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
460 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
462 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
465 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
466 var identityKeyPair
= getIdentityKeyPair();
467 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
469 dependencies
.getAccountManager()
470 .addDevice(deviceIdentifier
,
473 Optional
.of(account
.getProfileKey().serialize()),
475 account
.setMultiDevice(true);
478 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
479 if (!account
.isMasterDevice()) {
480 throw new RuntimeException("Only master device can set a PIN");
482 if (pin
.isPresent()) {
483 final var masterKey
= account
.getPinMasterKey() != null
484 ? account
.getPinMasterKey()
485 : KeyUtils
.createMasterKey();
487 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
489 account
.setRegistrationLockPin(pin
.get(), masterKey
);
492 pinHelper
.removeRegistrationLockPin();
494 account
.setRegistrationLockPin(null, null);
498 void refreshPreKeys() throws IOException
{
499 var oneTimePreKeys
= generatePreKeys();
500 final var identityKeyPair
= getIdentityKeyPair();
501 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
503 dependencies
.getAccountManager().setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
506 private List
<PreKeyRecord
> generatePreKeys() {
507 final var offset
= account
.getPreKeyIdOffset();
509 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
510 account
.addPreKeys(records
);
515 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
516 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
518 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
519 account
.addSignedPreKey(record);
524 public Profile
getRecipientProfile(
525 RecipientId recipientId
527 return getRecipientProfile(recipientId
, false);
530 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
532 Profile
getRecipientProfile(
533 RecipientId recipientId
, boolean force
535 var profile
= account
.getProfileStore().getProfile(recipientId
);
537 var now
= System
.currentTimeMillis();
538 // Profiles are cached for 24h before retrieving them again, unless forced
539 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
543 synchronized (pendingProfileRequest
) {
544 if (pendingProfileRequest
.contains(recipientId
)) {
547 pendingProfileRequest
.add(recipientId
);
549 final SignalServiceProfile encryptedProfile
;
551 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
553 synchronized (pendingProfileRequest
) {
554 pendingProfileRequest
.remove(recipientId
);
557 if (encryptedProfile
== null) {
561 profile
= decryptProfileIfKeyKnown(recipientId
, encryptedProfile
);
562 account
.getProfileStore().storeProfile(recipientId
, profile
);
567 private Profile
decryptProfileIfKeyKnown(
568 final RecipientId recipientId
, final SignalServiceProfile encryptedProfile
570 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
571 if (profileKey
== null) {
572 return new Profile(System
.currentTimeMillis(),
577 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
578 ProfileUtils
.getCapabilities(encryptedProfile
));
581 return decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
584 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
586 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
587 } catch (IOException e
) {
588 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
593 private ProfileAndCredential
retrieveProfileAndCredential(
594 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
595 ) throws IOException
{
596 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
597 final var profile
= profileAndCredential
.getProfile();
600 var newIdentity
= account
.getIdentityKeyStore()
601 .saveIdentity(recipientId
,
602 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
606 account
.getSessionStore().archiveSessions(recipientId
);
608 } catch (InvalidKeyException ignored
) {
609 logger
.warn("Got invalid identity key in profile for {}",
610 resolveSignalServiceAddress(recipientId
).getIdentifier());
612 return profileAndCredential
;
615 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
616 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
617 if (profileKeyCredential
!= null) {
618 return profileKeyCredential
;
621 ProfileAndCredential profileAndCredential
;
623 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
624 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
625 } catch (IOException e
) {
626 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
630 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
631 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
633 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
634 if (profileKey
!= null) {
635 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
637 profileAndCredential
.getProfile());
638 account
.getProfileStore().storeProfile(recipientId
, profile
);
641 return profileKeyCredential
;
644 private Profile
decryptProfileAndDownloadAvatar(
645 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
647 if (encryptedProfile
.getAvatar() != null) {
648 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
651 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
654 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
655 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
656 if (streamDetails
== null) {
657 return Optional
.absent();
660 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
663 public List
<GroupInfo
> getGroups() {
664 return account
.getGroupStore().getGroups();
667 public SendGroupMessageResults
sendQuitGroupMessage(
668 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
669 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
670 final var newAdmins
= getRecipientIds(groupAdmins
);
671 return groupHelper
.quitGroup(groupId
, newAdmins
);
674 public void deleteGroup(GroupId groupId
) throws IOException
{
675 account
.getGroupStore().deleteGroup(groupId
);
676 avatarStore
.deleteGroupAvatar(groupId
);
679 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
680 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
681 ) throws IOException
, AttachmentInvalidException
{
682 return groupHelper
.createGroup(name
, members
== null ?
null : getRecipientIds(members
), avatarFile
);
685 public SendGroupMessageResults
updateGroup(
689 Set
<RecipientIdentifier
.Single
> members
,
690 Set
<RecipientIdentifier
.Single
> removeMembers
,
691 Set
<RecipientIdentifier
.Single
> admins
,
692 Set
<RecipientIdentifier
.Single
> removeAdmins
,
693 boolean resetGroupLink
,
694 GroupLinkState groupLinkState
,
695 GroupPermission addMemberPermission
,
696 GroupPermission editDetailsPermission
,
698 Integer expirationTimer
,
699 Boolean isAnnouncementGroup
700 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
701 return groupHelper
.updateGroup(groupId
,
704 members
== null ?
null : getRecipientIds(members
),
705 removeMembers
== null ?
null : getRecipientIds(removeMembers
),
706 admins
== null ?
null : getRecipientIds(admins
),
707 removeAdmins
== null ?
null : getRecipientIds(removeAdmins
),
711 editDetailsPermission
,
714 isAnnouncementGroup
);
717 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
718 GroupInviteLinkUrl inviteLinkUrl
719 ) throws IOException
, GroupLinkNotActiveException
{
720 return groupHelper
.joinGroup(inviteLinkUrl
);
723 public SendMessageResults
sendMessage(
724 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
725 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
726 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
727 long timestamp
= System
.currentTimeMillis();
728 messageBuilder
.withTimestamp(timestamp
);
729 for (final var recipient
: recipients
) {
730 if (recipient
instanceof RecipientIdentifier
.Single
) {
731 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
732 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
733 results
.put(recipient
, List
.of(result
));
734 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
735 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
736 results
.put(recipient
, List
.of(result
));
737 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
738 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
739 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
740 results
.put(recipient
, result
);
743 return new SendMessageResults(timestamp
, results
);
746 public void sendTypingMessage(
747 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
748 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
{
749 final var timestamp
= System
.currentTimeMillis();
750 for (var recipient
: recipients
) {
751 if (recipient
instanceof RecipientIdentifier
.Single
) {
752 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
753 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
754 sendHelper
.sendTypingMessage(message
, recipientId
);
755 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
756 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
757 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
758 sendHelper
.sendGroupTypingMessage(message
, groupId
);
763 SendGroupMessageResults
sendGroupInfoMessage(
764 GroupIdV1 groupId
, SignalServiceAddress recipient
765 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
766 final var recipientId
= resolveRecipient(recipient
);
767 return groupHelper
.sendGroupInfoMessage(groupId
, recipientId
);
770 SendGroupMessageResults
sendGroupInfoRequest(
771 GroupIdV1 groupId
, SignalServiceAddress recipient
772 ) throws IOException
{
773 final var recipientId
= resolveRecipient(recipient
);
774 return groupHelper
.sendGroupInfoRequest(groupId
, recipientId
);
777 public void sendReadReceipt(
778 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
779 ) throws IOException
, UntrustedIdentityException
{
780 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
782 System
.currentTimeMillis());
784 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
787 public void sendViewedReceipt(
788 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
789 ) throws IOException
, UntrustedIdentityException
{
790 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
792 System
.currentTimeMillis());
794 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
797 void sendDeliveryReceipt(
798 SignalServiceAddress remoteAddress
, List
<Long
> messageIds
799 ) throws IOException
, UntrustedIdentityException
{
800 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
802 System
.currentTimeMillis());
804 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(remoteAddress
));
807 public SendMessageResults
sendMessage(
808 Message message
, Set
<RecipientIdentifier
> recipients
809 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
{
810 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
811 applyMessage(messageBuilder
, message
);
812 return sendMessage(messageBuilder
, recipients
);
815 private void applyMessage(
816 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
817 ) throws AttachmentInvalidException
, IOException
{
818 messageBuilder
.withBody(message
.getMessageText());
819 if (message
.getAttachments() != null) {
820 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(message
.getAttachments());
822 // Upload attachments here, so we only upload once even for multiple recipients
823 var messageSender
= dependencies
.getMessageSender();
824 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
825 for (var attachment
: attachmentStreams
) {
826 if (attachment
.isStream()) {
827 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
828 } else if (attachment
.isPointer()) {
829 attachmentPointers
.add(attachment
.asPointer());
833 messageBuilder
.withAttachments(attachmentPointers
);
837 public SendMessageResults
sendRemoteDeleteMessage(
838 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
839 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
840 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
841 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
842 return sendMessage(messageBuilder
, recipients
);
845 public SendMessageResults
sendMessageReaction(
848 RecipientIdentifier
.Single targetAuthor
,
849 long targetSentTimestamp
,
850 Set
<RecipientIdentifier
> recipients
851 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
852 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
853 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
855 resolveSignalServiceAddress(targetAuthorRecipientId
),
856 targetSentTimestamp
);
857 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
858 return sendMessage(messageBuilder
, recipients
);
861 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
862 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
865 return sendMessage(messageBuilder
,
866 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
867 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
868 throw new AssertionError(e
);
870 for (var recipient
: recipients
) {
871 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
872 handleEndSession(recipientId
);
877 void renewSession(RecipientId recipientId
) throws IOException
{
878 account
.getSessionStore().archiveSessions(recipientId
);
879 if (!recipientId
.equals(getSelfRecipientId())) {
880 sendHelper
.sendNullMessage(recipientId
);
884 public void setContactName(
885 RecipientIdentifier
.Single recipient
, String name
886 ) throws NotMasterDeviceException
{
887 if (!account
.isMasterDevice()) {
888 throw new NotMasterDeviceException();
890 final var recipientId
= resolveRecipient(recipient
);
891 var contact
= account
.getContactStore().getContact(recipientId
);
892 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
893 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
896 public void setContactBlocked(
897 RecipientIdentifier
.Single recipient
, boolean blocked
898 ) throws NotMasterDeviceException
{
899 if (!account
.isMasterDevice()) {
900 throw new NotMasterDeviceException();
902 setContactBlocked(resolveRecipient(recipient
), blocked
);
905 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
906 var contact
= account
.getContactStore().getContact(recipientId
);
907 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
908 // TODO cycle our profile key
909 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
912 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
913 var group
= getGroup(groupId
);
915 throw new GroupNotFoundException(groupId
);
918 group
.setBlocked(blocked
);
919 // TODO cycle our profile key
920 account
.getGroupStore().updateGroup(group
);
924 * Change the expiration timer for a contact
926 public void setExpirationTimer(
927 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
928 ) throws IOException
{
929 var recipientId
= resolveRecipient(recipient
);
930 setExpirationTimer(recipientId
, messageExpirationTimer
);
931 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
933 sendMessage(messageBuilder
, Set
.of(recipient
));
934 } catch (NotAGroupMemberException
| GroupNotFoundException e
) {
935 throw new AssertionError(e
);
939 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
940 var contact
= account
.getContactStore().getContact(recipientId
);
941 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
944 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
945 account
.getContactStore()
946 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
950 * Upload the sticker pack from path.
952 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
953 * @return if successful, returns the URL to install the sticker pack in the signal app
955 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
956 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
958 var messageSender
= dependencies
.getMessageSender();
960 var packKey
= KeyUtils
.createStickerUploadKey();
961 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
962 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
964 var sticker
= new Sticker(packId
, packKey
);
965 account
.getStickerStore().updateSticker(sticker
);
968 return new URI("https",
972 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
974 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
975 } catch (URISyntaxException e
) {
976 throw new AssertionError(e
);
980 public void requestAllSyncData() throws IOException
{
982 requestSyncContacts();
983 requestSyncBlocked();
984 requestSyncConfiguration();
988 private void requestSyncGroups() throws IOException
{
989 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
990 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
992 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
993 sendHelper
.sendSyncMessage(message
);
996 private void requestSyncContacts() throws IOException
{
997 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
998 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1000 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1001 sendHelper
.sendSyncMessage(message
);
1004 private void requestSyncBlocked() throws IOException
{
1005 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1006 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1008 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1009 sendHelper
.sendSyncMessage(message
);
1012 private void requestSyncConfiguration() throws IOException
{
1013 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1014 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1016 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1017 sendHelper
.sendSyncMessage(message
);
1020 private void requestSyncKeys() throws IOException
{
1021 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1022 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1024 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1025 sendHelper
.sendSyncMessage(message
);
1028 private byte[] getSenderCertificate() {
1031 if (account
.isPhoneNumberShared()) {
1032 certificate
= dependencies
.getAccountManager().getSenderCertificate();
1034 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
1036 } catch (IOException e
) {
1037 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1040 // TODO cache for a day
1044 private Set
<RecipientId
> getRecipientIds(Collection
<RecipientIdentifier
.Single
> recipients
) {
1045 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(recipients
.size());
1046 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1048 for (var number
: recipients
) {
1049 final var resolvedAddress
= resolveSignalServiceAddress(resolveRecipient(number
));
1050 if (resolvedAddress
.getUuid().isPresent()) {
1051 signalServiceAddresses
.add(resolvedAddress
);
1053 addressesMissingUuid
.add(resolvedAddress
);
1057 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1058 .map(a
-> a
.getNumber().get())
1059 .collect(Collectors
.toSet());
1060 Map
<String
, UUID
> registeredUsers
;
1062 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1063 } catch (IOException e
) {
1064 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1065 registeredUsers
= Map
.of();
1068 for (var address
: addressesMissingUuid
) {
1069 final var number
= address
.getNumber().get();
1070 if (registeredUsers
.containsKey(number
)) {
1071 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1072 registeredUsers
.get(number
),
1074 signalServiceAddresses
.add(newAddress
);
1076 signalServiceAddresses
.add(address
);
1080 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1083 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1084 final var address
= resolveSignalServiceAddress(recipientId
);
1085 if (!address
.getNumber().isPresent()) {
1088 final var number
= address
.getNumber().get();
1089 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1090 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1093 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1094 final Map
<String
, UUID
> registeredUsers
;
1096 registeredUsers
= dependencies
.getAccountManager()
1097 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1099 serviceEnvironmentConfig
.getCdsMrenclave());
1100 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1101 throw new IOException(e
);
1104 // Store numbers as recipients so we have the number/uuid association
1105 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
1107 return registeredUsers
;
1110 public void sendTypingMessage(
1111 TypingAction action
, Set
<RecipientIdentifier
> recipients
1112 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
{
1113 sendTypingMessage(action
.toSignalService(), recipients
);
1116 private void handleEndSession(RecipientId recipientId
) {
1117 account
.getSessionStore().deleteAllSessions(recipientId
);
1120 private List
<HandleAction
> handleSignalServiceDataMessage(
1121 SignalServiceDataMessage message
,
1123 SignalServiceAddress source
,
1124 SignalServiceAddress destination
,
1125 boolean ignoreAttachments
1127 var actions
= new ArrayList
<HandleAction
>();
1128 if (message
.getGroupContext().isPresent()) {
1129 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1130 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1131 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1132 var group
= getGroup(groupId
);
1133 if (group
== null || group
instanceof GroupInfoV1
) {
1134 var groupV1
= (GroupInfoV1
) group
;
1135 switch (groupInfo
.getType()) {
1137 if (groupV1
== null) {
1138 groupV1
= new GroupInfoV1(groupId
);
1141 if (groupInfo
.getAvatar().isPresent()) {
1142 var avatar
= groupInfo
.getAvatar().get();
1143 downloadGroupAvatar(groupV1
.getGroupId(), avatar
);
1146 if (groupInfo
.getName().isPresent()) {
1147 groupV1
.name
= groupInfo
.getName().get();
1150 if (groupInfo
.getMembers().isPresent()) {
1151 groupV1
.addMembers(groupInfo
.getMembers()
1154 .map(this::resolveRecipient
)
1155 .collect(Collectors
.toSet()));
1158 account
.getGroupStore().updateGroup(groupV1
);
1162 if (groupV1
== null && !isSync
) {
1163 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1167 if (groupV1
!= null) {
1168 groupV1
.removeMember(resolveRecipient(source
));
1169 account
.getGroupStore().updateGroup(groupV1
);
1174 if (groupV1
!= null && !isSync
) {
1175 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1180 // Received a group v1 message for a v2 group
1183 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1184 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1185 final var groupMasterKey
= groupContext
.getMasterKey();
1187 groupHelper
.getOrMigrateGroup(groupMasterKey
,
1188 groupContext
.getRevision(),
1189 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1193 final var conversationPartnerAddress
= isSync ? destination
: source
;
1194 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1195 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1197 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1198 if (message
.getGroupContext().isPresent()) {
1199 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1200 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1201 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1202 if (group
!= null) {
1203 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1204 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1205 account
.getGroupStore().updateGroup(group
);
1208 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1209 // disappearing message timer already stored in the DecryptedGroup
1211 } else if (conversationPartnerAddress
!= null) {
1212 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1215 if (!ignoreAttachments
) {
1216 if (message
.getAttachments().isPresent()) {
1217 for (var attachment
: message
.getAttachments().get()) {
1218 downloadAttachment(attachment
);
1221 if (message
.getSharedContacts().isPresent()) {
1222 for (var contact
: message
.getSharedContacts().get()) {
1223 if (contact
.getAvatar().isPresent()) {
1224 downloadAttachment(contact
.getAvatar().get().getAttachment());
1229 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1230 final ProfileKey profileKey
;
1232 profileKey
= new ProfileKey(message
.getProfileKey().get());
1233 } catch (InvalidInputException e
) {
1234 throw new AssertionError(e
);
1236 if (source
.matches(account
.getSelfAddress())) {
1237 this.account
.setProfileKey(profileKey
);
1239 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1241 if (message
.getPreviews().isPresent()) {
1242 final var previews
= message
.getPreviews().get();
1243 for (var preview
: previews
) {
1244 if (preview
.getImage().isPresent()) {
1245 downloadAttachment(preview
.getImage().get());
1249 if (message
.getQuote().isPresent()) {
1250 final var quote
= message
.getQuote().get();
1252 for (var quotedAttachment
: quote
.getAttachments()) {
1253 final var thumbnail
= quotedAttachment
.getThumbnail();
1254 if (thumbnail
!= null) {
1255 downloadAttachment(thumbnail
);
1259 if (message
.getSticker().isPresent()) {
1260 final var messageSticker
= message
.getSticker().get();
1261 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1262 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1263 if (sticker
== null) {
1264 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1265 account
.getStickerStore().updateSticker(sticker
);
1267 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, messageSticker
.getPackKey()));
1272 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1273 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1274 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1275 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1276 if (actions
!= null) {
1277 queuedActions
.addAll(actions
);
1280 handleQueuedActions(queuedActions
);
1283 private List
<HandleAction
> retryFailedReceivedMessage(
1284 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1286 var envelope
= cachedMessage
.loadEnvelope();
1287 if (envelope
== null) {
1290 SignalServiceContent content
= null;
1291 List
<HandleAction
> actions
= null;
1292 if (!envelope
.isReceipt()) {
1294 content
= dependencies
.getCipher().decrypt(envelope
);
1295 } catch (ProtocolUntrustedIdentityException e
) {
1296 if (!envelope
.hasSource()) {
1297 final var identifier
= e
.getSender();
1298 final var recipientId
= resolveRecipient(identifier
);
1300 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1301 } catch (IOException ioException
) {
1302 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1306 } catch (Exception er
) {
1307 // All other errors are not recoverable, so delete the cached message
1308 cachedMessage
.delete();
1311 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1313 handler
.handleMessage(envelope
, content
, null);
1314 cachedMessage
.delete();
1318 public void receiveMessages(
1321 boolean returnOnTimeout
,
1322 boolean ignoreAttachments
,
1323 ReceiveMessageHandler handler
1324 ) throws IOException
{
1325 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1327 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1329 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1330 signalWebSocket
.connect();
1332 var hasCaughtUpWithOldMessages
= false;
1334 while (!Thread
.interrupted()) {
1335 SignalServiceEnvelope envelope
;
1336 SignalServiceContent content
= null;
1337 Exception exception
= null;
1338 final CachedMessage
[] cachedMessage
= {null};
1339 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
1340 logger
.debug("Checking for new message from server");
1342 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1343 final var recipientId
= envelope1
.hasSource()
1344 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1346 // store message on disk, before acknowledging receipt to the server
1347 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1349 logger
.debug("New message received from server");
1350 if (result
.isPresent()) {
1351 envelope
= result
.get();
1353 // Received indicator that server queue is empty
1354 hasCaughtUpWithOldMessages
= true;
1356 handleQueuedActions(queuedActions
);
1357 queuedActions
.clear();
1359 // Continue to wait another timeout for new messages
1362 } catch (AssertionError e
) {
1363 if (e
.getCause() instanceof InterruptedException
) {
1364 Thread
.currentThread().interrupt();
1369 } catch (WebSocketUnavailableException e
) {
1370 logger
.debug("Pipe unexpectedly unavailable, connecting");
1371 signalWebSocket
.connect();
1373 } catch (TimeoutException e
) {
1374 if (returnOnTimeout
) return;
1378 if (envelope
.hasSource()) {
1379 // Store uuid if we don't have it already
1380 // address/uuid in envelope is sent by server
1381 resolveRecipientTrusted(envelope
.getSourceAddress());
1383 if (!envelope
.isReceipt()) {
1385 content
= dependencies
.getCipher().decrypt(envelope
);
1386 } catch (Exception e
) {
1389 if (!envelope
.hasSource() && content
!= null) {
1390 // Store uuid if we don't have it already
1391 // address/uuid is validated by unidentified sender certificate
1392 resolveRecipientTrusted(content
.getSender());
1394 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1395 if (exception
instanceof ProtocolInvalidMessageException
) {
1396 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
1397 logger
.debug("Received invalid message, queuing renew session action.");
1398 actions
.add(new RenewSessionAction(sender
));
1400 if (hasCaughtUpWithOldMessages
) {
1401 for (var action
: actions
) {
1403 action
.execute(this);
1404 } catch (Throwable e
) {
1405 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1406 Thread
.currentThread().interrupt();
1408 logger
.warn("Message action failed.", e
);
1412 queuedActions
.addAll(actions
);
1415 final var notAllowedToSendToGroup
= isNotAllowedToSendToGroup(envelope
, content
);
1416 if (isMessageBlocked(envelope
, content
)) {
1417 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1418 } else if (notAllowedToSendToGroup
) {
1419 logger
.info("Ignoring a group message from an unauthorized sender (no member or admin): {} {}",
1420 (envelope
.hasSource() ? envelope
.getSourceAddress() : content
.getSender()).getIdentifier(),
1421 envelope
.getTimestamp());
1423 handler
.handleMessage(envelope
, content
, exception
);
1425 if (cachedMessage
[0] != null) {
1426 if (exception
instanceof ProtocolUntrustedIdentityException
) {
1427 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
1428 final var recipientId
= resolveRecipient(identifier
);
1429 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1430 if (!envelope
.hasSource()) {
1432 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1433 } catch (IOException ioException
) {
1434 logger
.warn("Failed to move cached message to recipient folder: {}",
1435 ioException
.getMessage());
1439 cachedMessage
[0].delete();
1443 handleQueuedActions(queuedActions
);
1446 private void handleQueuedActions(final Set
<HandleAction
> queuedActions
) {
1447 for (var action
: queuedActions
) {
1449 action
.execute(this);
1450 } catch (Throwable e
) {
1451 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1452 Thread
.currentThread().interrupt();
1454 logger
.warn("Message action failed.", e
);
1459 private boolean isMessageBlocked(
1460 SignalServiceEnvelope envelope
, SignalServiceContent content
1462 SignalServiceAddress source
;
1463 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1464 source
= envelope
.getSourceAddress();
1465 } else if (content
!= null) {
1466 source
= content
.getSender();
1470 final var recipientId
= resolveRecipient(source
);
1471 if (isContactBlocked(recipientId
)) {
1475 if (content
!= null && content
.getDataMessage().isPresent()) {
1476 var message
= content
.getDataMessage().get();
1477 if (message
.getGroupContext().isPresent()) {
1478 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1479 var group
= getGroup(groupId
);
1480 if (group
!= null && group
.isBlocked()) {
1488 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1489 final var recipientId
= resolveRecipient(recipient
);
1490 return isContactBlocked(recipientId
);
1493 private boolean isContactBlocked(final RecipientId recipientId
) {
1494 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1495 return sourceContact
!= null && sourceContact
.isBlocked();
1498 private boolean isNotAllowedToSendToGroup(
1499 SignalServiceEnvelope envelope
, SignalServiceContent content
1501 SignalServiceAddress source
;
1502 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1503 source
= envelope
.getSourceAddress();
1504 } else if (content
!= null) {
1505 source
= content
.getSender();
1510 if (content
== null || !content
.getDataMessage().isPresent()) {
1514 var message
= content
.getDataMessage().get();
1515 if (!message
.getGroupContext().isPresent()) {
1519 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1520 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1521 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1526 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1527 var group
= getGroup(groupId
);
1528 if (group
== null) {
1532 final var recipientId
= resolveRecipient(source
);
1533 return !group
.isMember(recipientId
) || (
1534 group
.isAnnouncementGroup() && !group
.isAdmin(recipientId
)
1538 private List
<HandleAction
> handleMessage(
1539 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1541 var actions
= new ArrayList
<HandleAction
>();
1542 if (content
!= null) {
1543 final SignalServiceAddress sender
;
1544 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1545 sender
= envelope
.getSourceAddress();
1547 sender
= content
.getSender();
1550 if (content
.getDataMessage().isPresent()) {
1551 var message
= content
.getDataMessage().get();
1553 if (content
.isNeedsReceipt()) {
1554 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1557 actions
.addAll(handleSignalServiceDataMessage(message
,
1560 account
.getSelfAddress(),
1561 ignoreAttachments
));
1563 if (content
.getSyncMessage().isPresent()) {
1564 account
.setMultiDevice(true);
1565 var syncMessage
= content
.getSyncMessage().get();
1566 if (syncMessage
.getSent().isPresent()) {
1567 var message
= syncMessage
.getSent().get();
1568 final var destination
= message
.getDestination().orNull();
1569 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1573 ignoreAttachments
));
1575 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
1576 var rm
= syncMessage
.getRequest().get();
1577 if (rm
.isContactsRequest()) {
1578 actions
.add(SendSyncContactsAction
.create());
1580 if (rm
.isGroupsRequest()) {
1581 actions
.add(SendSyncGroupsAction
.create());
1583 if (rm
.isBlockedListRequest()) {
1584 actions
.add(SendSyncBlockedListAction
.create());
1586 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1588 if (syncMessage
.getGroups().isPresent()) {
1589 File tmpFile
= null;
1591 tmpFile
= IOUtils
.createTempFile();
1592 final var groupsMessage
= syncMessage
.getGroups().get();
1593 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1594 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1599 } catch (IOException e
) {
1600 logger
.warn("Sync groups contained invalid group, ignoring: {}", e
.getMessage());
1606 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1607 if (syncGroup
!= null) {
1608 if (g
.getName().isPresent()) {
1609 syncGroup
.name
= g
.getName().get();
1611 syncGroup
.addMembers(g
.getMembers()
1613 .map(this::resolveRecipient
)
1614 .collect(Collectors
.toSet()));
1615 if (!g
.isActive()) {
1616 syncGroup
.removeMember(account
.getSelfRecipientId());
1618 // Add ourself to the member set as it's marked as active
1619 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
1621 syncGroup
.blocked
= g
.isBlocked();
1622 if (g
.getColor().isPresent()) {
1623 syncGroup
.color
= g
.getColor().get();
1626 if (g
.getAvatar().isPresent()) {
1627 downloadGroupAvatar(syncGroup
.getGroupId(), g
.getAvatar().get());
1629 syncGroup
.archived
= g
.isArchived();
1630 account
.getGroupStore().updateGroup(syncGroup
);
1634 } catch (Exception e
) {
1635 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1639 if (tmpFile
!= null) {
1641 Files
.delete(tmpFile
.toPath());
1642 } catch (IOException e
) {
1643 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1650 if (syncMessage
.getBlockedList().isPresent()) {
1651 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1652 for (var address
: blockedListMessage
.getAddresses()) {
1653 setContactBlocked(resolveRecipient(address
), true);
1655 for (var groupId
: blockedListMessage
.getGroupIds()
1657 .map(GroupId
::unknownVersion
)
1658 .collect(Collectors
.toSet())) {
1660 setGroupBlocked(groupId
, true);
1661 } catch (GroupNotFoundException e
) {
1662 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1663 groupId
.toBase64());
1667 if (syncMessage
.getContacts().isPresent()) {
1668 File tmpFile
= null;
1670 tmpFile
= IOUtils
.createTempFile();
1671 final var contactsMessage
= syncMessage
.getContacts().get();
1672 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1673 .asPointer(), tmpFile
)) {
1674 var s
= new DeviceContactsInputStream(attachmentAsStream
);
1679 } catch (IOException e
) {
1680 logger
.warn("Sync contacts contained invalid contact, ignoring: {}",
1687 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1688 account
.setProfileKey(c
.getProfileKey().get());
1690 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
1691 var contact
= account
.getContactStore().getContact(recipientId
);
1692 final var builder
= contact
== null
1693 ? Contact
.newBuilder()
1694 : Contact
.newBuilder(contact
);
1695 if (c
.getName().isPresent()) {
1696 builder
.withName(c
.getName().get());
1698 if (c
.getColor().isPresent()) {
1699 builder
.withColor(c
.getColor().get());
1701 if (c
.getProfileKey().isPresent()) {
1702 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
1704 if (c
.getVerified().isPresent()) {
1705 final var verifiedMessage
= c
.getVerified().get();
1706 account
.getIdentityKeyStore()
1707 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
1708 verifiedMessage
.getIdentityKey(),
1709 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1711 if (c
.getExpirationTimer().isPresent()) {
1712 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
1714 builder
.withBlocked(c
.isBlocked());
1715 builder
.withArchived(c
.isArchived());
1716 account
.getContactStore().storeContact(recipientId
, builder
.build());
1718 if (c
.getAvatar().isPresent()) {
1719 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
1723 } catch (Exception e
) {
1724 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1728 if (tmpFile
!= null) {
1730 Files
.delete(tmpFile
.toPath());
1731 } catch (IOException e
) {
1732 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1739 if (syncMessage
.getVerified().isPresent()) {
1740 final var verifiedMessage
= syncMessage
.getVerified().get();
1741 account
.getIdentityKeyStore()
1742 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
1743 verifiedMessage
.getIdentityKey(),
1744 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1746 if (syncMessage
.getStickerPackOperations().isPresent()) {
1747 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
1748 for (var m
: stickerPackOperationMessages
) {
1749 if (!m
.getPackId().isPresent()) {
1752 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
1753 final var installed
= !m
.getType().isPresent()
1754 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
;
1756 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1757 if (m
.getPackKey().isPresent()) {
1758 if (sticker
== null) {
1759 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
1762 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, m
.getPackKey().get()));
1766 if (sticker
!= null) {
1767 sticker
.setInstalled(installed
);
1768 account
.getStickerStore().updateSticker(sticker
);
1772 if (syncMessage
.getFetchType().isPresent()) {
1773 switch (syncMessage
.getFetchType().get()) {
1775 getRecipientProfile(account
.getSelfRecipientId(), true);
1776 case STORAGE_MANIFEST
:
1780 if (syncMessage
.getKeys().isPresent()) {
1781 final var keysMessage
= syncMessage
.getKeys().get();
1782 if (keysMessage
.getStorageService().isPresent()) {
1783 final var storageKey
= keysMessage
.getStorageService().get();
1784 account
.setStorageKey(storageKey
);
1787 if (syncMessage
.getConfiguration().isPresent()) {
1795 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
1797 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
1798 } catch (IOException e
) {
1799 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
1803 private void downloadGroupAvatar(GroupIdV1 groupId
, SignalServiceAttachment avatar
) {
1805 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
1806 } catch (IOException e
) {
1807 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
1811 private void downloadProfileAvatar(
1812 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
1815 avatarStore
.storeProfileAvatar(address
,
1816 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
1817 } catch (Throwable e
) {
1818 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1819 Thread
.currentThread().interrupt();
1821 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
1825 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
1826 return attachmentStore
.getAttachmentFile(attachmentId
);
1829 private void downloadAttachment(final SignalServiceAttachment attachment
) {
1830 if (!attachment
.isPointer()) {
1831 logger
.warn("Invalid state, can't store an attachment stream.");
1834 var pointer
= attachment
.asPointer();
1835 if (pointer
.getPreview().isPresent()) {
1836 final var preview
= pointer
.getPreview().get();
1838 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
1839 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
1840 } catch (IOException e
) {
1841 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
1846 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
1847 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
1848 } catch (IOException e
) {
1849 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
1853 private void retrieveProfileAvatar(
1854 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
1855 ) throws IOException
{
1856 var tmpFile
= IOUtils
.createTempFile();
1857 try (var input
= dependencies
.getMessageReceiver()
1858 .retrieveProfileAvatar(avatarPath
,
1861 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
1862 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
1863 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
1866 Files
.delete(tmpFile
.toPath());
1867 } catch (IOException e
) {
1868 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
1875 private void retrieveAttachment(
1876 final SignalServiceAttachment attachment
, final OutputStream outputStream
1877 ) throws IOException
{
1878 if (attachment
.isPointer()) {
1879 var pointer
= attachment
.asPointer();
1880 retrieveAttachmentPointer(pointer
, outputStream
);
1882 var stream
= attachment
.asStream();
1883 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
1887 private void retrieveAttachmentPointer(
1888 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
1889 ) throws IOException
{
1890 var tmpFile
= IOUtils
.createTempFile();
1891 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
1892 IOUtils
.copyStream(input
, outputStream
);
1893 } catch (MissingConfigurationException
| InvalidMessageException e
) {
1894 throw new IOException(e
);
1897 Files
.delete(tmpFile
.toPath());
1898 } catch (IOException e
) {
1899 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
1906 private InputStream
retrieveAttachmentAsStream(
1907 SignalServiceAttachmentPointer pointer
, File tmpFile
1908 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
1909 return dependencies
.getMessageReceiver()
1910 .retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
1913 void sendGroups() throws IOException
{
1914 var groupsFile
= IOUtils
.createTempFile();
1917 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1918 var out
= new DeviceGroupsOutputStream(fos
);
1919 for (var record : getGroups()) {
1920 if (record instanceof GroupInfoV1
) {
1921 var groupInfo
= (GroupInfoV1
) record;
1922 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
1923 Optional
.fromNullable(groupInfo
.name
),
1924 groupInfo
.getMembers()
1926 .map(this::resolveSignalServiceAddress
)
1927 .collect(Collectors
.toList()),
1928 groupHelper
.createGroupAvatarAttachment(groupInfo
.getGroupId()),
1929 groupInfo
.isMember(account
.getSelfRecipientId()),
1930 Optional
.of(groupInfo
.messageExpirationTime
),
1931 Optional
.fromNullable(groupInfo
.color
),
1934 groupInfo
.archived
));
1939 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1940 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
1941 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1942 .withStream(groupsFileStream
)
1943 .withContentType("application/octet-stream")
1944 .withLength(groupsFile
.length())
1947 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1952 Files
.delete(groupsFile
.toPath());
1953 } catch (IOException e
) {
1954 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
1959 public void sendContacts() throws IOException
{
1960 var contactsFile
= IOUtils
.createTempFile();
1963 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1964 var out
= new DeviceContactsOutputStream(fos
);
1965 for (var contactPair
: account
.getContactStore().getContacts()) {
1966 final var recipientId
= contactPair
.first();
1967 final var contact
= contactPair
.second();
1968 final var address
= resolveSignalServiceAddress(recipientId
);
1970 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1971 VerifiedMessage verifiedMessage
= null;
1972 if (currentIdentity
!= null) {
1973 verifiedMessage
= new VerifiedMessage(address
,
1974 currentIdentity
.getIdentityKey(),
1975 currentIdentity
.getTrustLevel().toVerifiedState(),
1976 currentIdentity
.getDateAdded().getTime());
1979 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
1980 out
.write(new DeviceContact(address
,
1981 Optional
.fromNullable(contact
.getName()),
1982 createContactAvatarAttachment(address
),
1983 Optional
.fromNullable(contact
.getColor()),
1984 Optional
.fromNullable(verifiedMessage
),
1985 Optional
.fromNullable(profileKey
),
1986 contact
.isBlocked(),
1987 Optional
.of(contact
.getMessageExpirationTime()),
1989 contact
.isArchived()));
1992 if (account
.getProfileKey() != null) {
1993 // Send our own profile key as well
1994 out
.write(new DeviceContact(account
.getSelfAddress(),
1999 Optional
.of(account
.getProfileKey()),
2007 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2008 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2009 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2010 .withStream(contactsFileStream
)
2011 .withContentType("application/octet-stream")
2012 .withLength(contactsFile
.length())
2015 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
,
2021 Files
.delete(contactsFile
.toPath());
2022 } catch (IOException e
) {
2023 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2028 void sendBlockedList() throws IOException
{
2029 var addresses
= new ArrayList
<SignalServiceAddress
>();
2030 for (var record : account
.getContactStore().getContacts()) {
2031 if (record.second().isBlocked()) {
2032 addresses
.add(resolveSignalServiceAddress(record.first()));
2035 var groupIds
= new ArrayList
<byte[]>();
2036 for (var record : getGroups()) {
2037 if (record.isBlocked()) {
2038 groupIds
.add(record.getGroupId().serialize());
2041 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2044 private void sendVerifiedMessage(
2045 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2046 ) throws IOException
{
2047 var verifiedMessage
= new VerifiedMessage(destination
,
2049 trustLevel
.toVerifiedState(),
2050 System
.currentTimeMillis());
2051 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2054 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2055 return account
.getContactStore().getContacts();
2058 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
2059 final var recipientId
= resolveRecipient(recipientIdentifier
);
2060 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2061 if (recipient
== null) {
2065 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2066 return recipient
.getContact().getName();
2069 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2070 return recipient
.getProfile().getDisplayName();
2076 public GroupInfo
getGroup(GroupId groupId
) {
2077 return groupHelper
.getGroup(groupId
);
2080 public List
<IdentityInfo
> getIdentities() {
2081 return account
.getIdentityKeyStore().getIdentities();
2084 public List
<IdentityInfo
> getIdentities(RecipientIdentifier
.Single recipient
) {
2085 final var identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
2086 return identity
== null ? List
.of() : List
.of(identity
);
2090 * Trust this the identity with this fingerprint
2092 * @param recipient username of the identity
2093 * @param fingerprint Fingerprint
2095 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
2096 var recipientId
= resolveRecipient(recipient
);
2097 return trustIdentity(recipientId
,
2098 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2099 TrustLevel
.TRUSTED_VERIFIED
);
2103 * Trust this the identity with this safety number
2105 * @param recipient username of the identity
2106 * @param safetyNumber Safety number
2108 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
2109 var recipientId
= resolveRecipient(recipient
);
2110 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2111 return trustIdentity(recipientId
,
2112 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2113 TrustLevel
.TRUSTED_VERIFIED
);
2117 * Trust this the identity with this scannable safety number
2119 * @param recipient username of the identity
2120 * @param safetyNumber Scannable safety number
2122 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
2123 var recipientId
= resolveRecipient(recipient
);
2124 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2125 return trustIdentity(recipientId
, identityKey
-> {
2126 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
2128 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
2129 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
2132 }, TrustLevel
.TRUSTED_VERIFIED
);
2136 * Trust all keys of this identity without verification
2138 * @param recipient username of the identity
2140 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
2141 var recipientId
= resolveRecipient(recipient
);
2142 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2145 private boolean trustIdentity(
2146 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2148 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2149 if (identity
== null) {
2153 if (!verifier
.apply(identity
.getIdentityKey())) {
2157 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2159 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2160 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2161 } catch (IOException e
) {
2162 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2168 private void handleIdentityFailure(
2169 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
2171 final var identityKey
= identityFailure
.getIdentityKey();
2172 if (identityKey
!= null) {
2173 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
2175 account
.getSessionStore().archiveSessions(recipientId
);
2178 // Retrieve profile to get the current identity key from the server
2179 retrieveEncryptedProfile(recipientId
);
2183 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
2184 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
2185 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
2188 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
2189 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
2190 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
2193 private Fingerprint
computeSafetyNumberFingerprint(
2194 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
2196 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
2197 account
.getSelfAddress(),
2198 getIdentityKeyPair().getPublicKey(),
2204 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2205 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2207 return resolveSignalServiceAddress(address
);
2211 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2212 if (address
.matches(account
.getSelfAddress())) {
2213 return account
.getSelfAddress();
2216 return account
.getRecipientStore().resolveServiceAddress(address
);
2219 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2220 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2223 private String
canonicalizePhoneNumber(final String number
) throws InvalidNumberException
{
2224 return PhoneNumberFormatter
.formatNumber(number
, account
.getUsername());
2227 private RecipientId
resolveRecipient(final String identifier
) {
2228 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2230 return resolveRecipient(address
);
2233 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) {
2234 final SignalServiceAddress address
;
2235 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
2236 address
= new SignalServiceAddress(((RecipientIdentifier
.Uuid
) recipient
).uuid
, null);
2238 address
= new SignalServiceAddress(null, ((RecipientIdentifier
.Number
) recipient
).number
);
2241 return resolveRecipient(address
);
2244 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2245 return account
.getRecipientStore().resolveRecipient(address
);
2248 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2249 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2252 private void enqueueJob(Job job
) {
2253 var context
= new Context(account
,
2254 dependencies
.getAccountManager(),
2255 dependencies
.getMessageReceiver(),
2261 public void close() throws IOException
{
2265 void close(boolean closeAccount
) throws IOException
{
2266 executor
.shutdown();
2268 dependencies
.getSignalWebSocket().disconnect();
2270 if (closeAccount
&& account
!= null) {
2276 public interface ReceiveMessageHandler
{
2278 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);