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
.GroupSendingNotAllowedException
;
35 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
36 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
37 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
38 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
39 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
40 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
41 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
42 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
43 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
44 import org
.asamk
.signal
.manager
.jobs
.Context
;
45 import org
.asamk
.signal
.manager
.jobs
.Job
;
46 import org
.asamk
.signal
.manager
.jobs
.RetrieveStickerPackJob
;
47 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
48 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
49 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
50 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
51 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
52 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
53 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
56 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
57 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
58 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
59 import org
.asamk
.signal
.manager
.util
.IOUtils
;
60 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
61 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
62 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
63 import org
.asamk
.signal
.manager
.util
.Utils
;
64 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
65 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
66 import org
.signal
.zkgroup
.InvalidInputException
;
67 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
68 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
69 import org
.slf4j
.Logger
;
70 import org
.slf4j
.LoggerFactory
;
71 import org
.whispersystems
.libsignal
.IdentityKey
;
72 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
73 import org
.whispersystems
.libsignal
.InvalidKeyException
;
74 import org
.whispersystems
.libsignal
.InvalidMessageException
;
75 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
76 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
77 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintParsingException
;
78 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintVersionMismatchException
;
79 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
80 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
81 import org
.whispersystems
.libsignal
.util
.Pair
;
82 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
83 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
84 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
85 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
86 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
87 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
88 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
89 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
90 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
91 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
92 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
93 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
94 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
95 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
96 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
97 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
98 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
99 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
100 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
101 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
102 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
103 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
104 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
105 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
106 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
107 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
109 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
110 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
111 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
112 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
113 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
114 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
115 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
116 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
117 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
118 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
119 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
120 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
121 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
122 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
123 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
125 import java
.io
.Closeable
;
127 import java
.io
.FileInputStream
;
128 import java
.io
.FileOutputStream
;
129 import java
.io
.IOException
;
130 import java
.io
.InputStream
;
131 import java
.io
.OutputStream
;
133 import java
.net
.URISyntaxException
;
134 import java
.net
.URLEncoder
;
135 import java
.nio
.charset
.StandardCharsets
;
136 import java
.nio
.file
.Files
;
137 import java
.security
.SignatureException
;
138 import java
.util
.ArrayList
;
139 import java
.util
.Arrays
;
140 import java
.util
.Base64
;
141 import java
.util
.Collection
;
142 import java
.util
.Date
;
143 import java
.util
.HashMap
;
144 import java
.util
.HashSet
;
145 import java
.util
.List
;
146 import java
.util
.Map
;
147 import java
.util
.Set
;
148 import java
.util
.UUID
;
149 import java
.util
.concurrent
.ExecutorService
;
150 import java
.util
.concurrent
.Executors
;
151 import java
.util
.concurrent
.TimeUnit
;
152 import java
.util
.concurrent
.TimeoutException
;
153 import java
.util
.concurrent
.locks
.ReentrantLock
;
154 import java
.util
.function
.Function
;
155 import java
.util
.stream
.Collectors
;
157 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
159 public class Manager
implements Closeable
{
161 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
163 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
164 private final SignalDependencies dependencies
;
166 private SignalAccount account
;
168 private final ExecutorService executor
= Executors
.newCachedThreadPool();
170 private final ProfileHelper profileHelper
;
171 private final PinHelper pinHelper
;
172 private final SendHelper sendHelper
;
173 private final GroupHelper groupHelper
;
175 private final AvatarStore avatarStore
;
176 private final AttachmentStore attachmentStore
;
177 private final StickerPackStore stickerPackStore
;
178 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
179 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
182 public Lock
acquire() {
184 return LEGACY_LOCK
::unlock
;
189 SignalAccount account
,
190 PathConfig pathConfig
,
191 ServiceEnvironmentConfig serviceEnvironmentConfig
,
194 this.account
= account
;
195 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
197 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
198 account
.getUsername(),
199 account
.getPassword(),
200 account
.getDeviceId());
201 this.dependencies
= new SignalDependencies(account
.getSelfAddress(),
202 serviceEnvironmentConfig
,
205 account
.getSignalProtocolStore(),
208 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
210 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
211 account
.getProfileStore()::getProfileKey
,
212 this::getRecipientProfile
,
213 this::getSenderCertificate
);
214 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
215 unidentifiedAccessHelper
::getAccessFor
,
216 dependencies
::getProfileService
,
217 dependencies
::getMessageReceiver
,
218 this::resolveSignalServiceAddress
);
219 final GroupV2Helper groupV2Helper
= new GroupV2Helper(this::getRecipientProfileKeyCredential
,
220 this::getRecipientProfile
,
221 account
::getSelfRecipientId
,
222 dependencies
.getGroupsV2Operations(),
223 dependencies
.getGroupsV2Api(),
224 this::resolveSignalServiceAddress
);
225 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
226 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
227 this.stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
228 this.sendHelper
= new SendHelper(account
,
230 unidentifiedAccessHelper
,
231 this::resolveSignalServiceAddress
,
232 this::resolveRecipient
,
233 this::handleIdentityFailure
,
235 this::refreshRegisteredUser
);
236 this.groupHelper
= new GroupHelper(account
,
241 this::resolveSignalServiceAddress
,
242 this::resolveRecipient
);
245 public String
getUsername() {
246 return account
.getUsername();
249 public SignalServiceAddress
getSelfAddress() {
250 return account
.getSelfAddress();
253 public RecipientId
getSelfRecipientId() {
254 return account
.getSelfRecipientId();
257 private IdentityKeyPair
getIdentityKeyPair() {
258 return account
.getIdentityKeyPair();
261 public int getDeviceId() {
262 return account
.getDeviceId();
265 public static Manager
init(
268 ServiceEnvironment serviceEnvironment
,
270 final TrustNewIdentity trustNewIdentity
271 ) throws IOException
, NotRegisteredException
{
272 var pathConfig
= PathConfig
.createDefault(settingsPath
);
274 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
275 throw new NotRegisteredException();
278 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true, trustNewIdentity
);
280 if (!account
.isRegistered()) {
281 throw new NotRegisteredException();
284 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
286 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
289 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
290 var pathConfig
= PathConfig
.createDefault(settingsPath
);
291 final var dataPath
= pathConfig
.getDataPath();
292 final var files
= dataPath
.listFiles();
298 return Arrays
.stream(files
)
299 .filter(File
::isFile
)
301 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
302 .collect(Collectors
.toList());
305 public void checkAccountState() throws IOException
{
306 if (account
.getLastReceiveTimestamp() == 0) {
307 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
309 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
310 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
313 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
317 if (dependencies
.getAccountManager().getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
320 if (account
.getUuid() == null) {
321 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
323 updateAccountAttributes();
327 * This is used for checking a set of phone numbers for registration on Signal
329 * @param numbers The set of phone number in question
330 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
331 * @throws IOException if its unable to get the contacts to check if they're registered
333 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
334 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
336 return canonicalizePhoneNumber(n
);
337 } catch (InvalidNumberException e
) {
342 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
343 var contactDetails
= getRegisteredUsers(canonicalizedNumbers
.values()
345 .filter(s
-> !s
.isEmpty())
346 .collect(Collectors
.toSet()));
348 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
349 final var number
= canonicalizedNumbers
.get(n
);
350 final var uuid
= contactDetails
.get(number
);
351 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
355 public void updateAccountAttributes() throws IOException
{
356 dependencies
.getAccountManager()
357 .setAccountAttributes(account
.getEncryptedDeviceName(),
359 account
.getLocalRegistrationId(),
361 // set legacy pin only if no KBS master key is set
362 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
363 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
364 account
.getSelfUnidentifiedAccessKey(),
365 account
.isUnrestrictedUnidentifiedAccess(),
367 account
.isDiscoverableByPhoneNumber());
371 * @param givenName if null, the previous givenName will be kept
372 * @param familyName if null, the previous familyName will be kept
373 * @param about if null, the previous about text will be kept
374 * @param aboutEmoji if null, the previous about emoji will be kept
375 * @param avatar if avatar is null the image from the local avatar store is used (if present),
377 public void setProfile(
378 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
379 ) throws IOException
{
380 var profile
= getRecipientProfile(account
.getSelfRecipientId());
381 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
382 if (givenName
!= null) {
383 builder
.withGivenName(givenName
);
385 if (familyName
!= null) {
386 builder
.withFamilyName(familyName
);
389 builder
.withAbout(about
);
391 if (aboutEmoji
!= null) {
392 builder
.withAboutEmoji(aboutEmoji
);
394 var newProfile
= builder
.build();
396 try (final var streamDetails
= avatar
== null
397 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
398 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
399 dependencies
.getAccountManager()
400 .setVersionedProfile(account
.getUuid(),
401 account
.getProfileKey(),
402 newProfile
.getInternalServiceName(),
403 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
404 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
409 if (avatar
!= null) {
410 if (avatar
.isPresent()) {
411 avatarStore
.storeProfileAvatar(getSelfAddress(),
412 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
414 avatarStore
.deleteProfileAvatar(getSelfAddress());
417 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
419 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
422 public void unregister() throws IOException
{
423 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
424 // If this is the master device, other users can't send messages to this number anymore.
425 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
426 dependencies
.getAccountManager().setGcmId(Optional
.absent());
428 account
.setRegistered(false);
431 public void deleteAccount() throws IOException
{
432 dependencies
.getAccountManager().deleteAccount();
434 account
.setRegistered(false);
437 public List
<Device
> getLinkedDevices() throws IOException
{
438 var devices
= dependencies
.getAccountManager().getDevices();
439 account
.setMultiDevice(devices
.size() > 1);
440 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
441 return devices
.stream().map(d
-> {
442 String deviceName
= d
.getName();
443 if (deviceName
!= null) {
445 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
446 } catch (IOException e
) {
447 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
450 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
451 }).collect(Collectors
.toList());
454 public void removeLinkedDevices(int deviceId
) throws IOException
{
455 dependencies
.getAccountManager().removeDevice(deviceId
);
456 var devices
= dependencies
.getAccountManager().getDevices();
457 account
.setMultiDevice(devices
.size() > 1);
460 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
461 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
463 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
466 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
467 var identityKeyPair
= getIdentityKeyPair();
468 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
470 dependencies
.getAccountManager()
471 .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
);
493 pinHelper
.removeRegistrationLockPin();
495 account
.setRegistrationLockPin(null, null);
499 void refreshPreKeys() throws IOException
{
500 var oneTimePreKeys
= generatePreKeys();
501 final var identityKeyPair
= getIdentityKeyPair();
502 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
504 dependencies
.getAccountManager().setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
507 private List
<PreKeyRecord
> generatePreKeys() {
508 final var offset
= account
.getPreKeyIdOffset();
510 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
511 account
.addPreKeys(records
);
516 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
517 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
519 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
520 account
.addSignedPreKey(record);
525 public Profile
getRecipientProfile(
526 RecipientId recipientId
528 return getRecipientProfile(recipientId
, false);
531 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
533 Profile
getRecipientProfile(
534 RecipientId recipientId
, boolean force
536 var profile
= account
.getProfileStore().getProfile(recipientId
);
538 var now
= System
.currentTimeMillis();
539 // Profiles are cached for 24h before retrieving them again, unless forced
540 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
544 synchronized (pendingProfileRequest
) {
545 if (pendingProfileRequest
.contains(recipientId
)) {
548 pendingProfileRequest
.add(recipientId
);
550 final SignalServiceProfile encryptedProfile
;
552 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
554 synchronized (pendingProfileRequest
) {
555 pendingProfileRequest
.remove(recipientId
);
558 if (encryptedProfile
== null) {
562 profile
= decryptProfileIfKeyKnown(recipientId
, encryptedProfile
);
563 account
.getProfileStore().storeProfile(recipientId
, profile
);
568 private Profile
decryptProfileIfKeyKnown(
569 final RecipientId recipientId
, final SignalServiceProfile encryptedProfile
571 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
572 if (profileKey
== null) {
573 return new Profile(System
.currentTimeMillis(),
578 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
579 ProfileUtils
.getCapabilities(encryptedProfile
));
582 return decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
585 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
587 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
588 } catch (IOException e
) {
589 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
594 private ProfileAndCredential
retrieveProfileAndCredential(
595 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
596 ) throws IOException
{
597 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
598 final var profile
= profileAndCredential
.getProfile();
601 var newIdentity
= account
.getIdentityKeyStore()
602 .saveIdentity(recipientId
,
603 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
607 account
.getSessionStore().archiveSessions(recipientId
);
609 } catch (InvalidKeyException ignored
) {
610 logger
.warn("Got invalid identity key in profile for {}",
611 resolveSignalServiceAddress(recipientId
).getIdentifier());
613 return profileAndCredential
;
616 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
617 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
618 if (profileKeyCredential
!= null) {
619 return profileKeyCredential
;
622 ProfileAndCredential profileAndCredential
;
624 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
625 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
626 } catch (IOException e
) {
627 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
631 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
632 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
634 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
635 if (profileKey
!= null) {
636 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
638 profileAndCredential
.getProfile());
639 account
.getProfileStore().storeProfile(recipientId
, profile
);
642 return profileKeyCredential
;
645 private Profile
decryptProfileAndDownloadAvatar(
646 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
648 if (encryptedProfile
.getAvatar() != null) {
649 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
652 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
655 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
656 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
657 if (streamDetails
== null) {
658 return Optional
.absent();
661 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
664 public List
<GroupInfo
> getGroups() {
665 return account
.getGroupStore().getGroups();
668 public SendGroupMessageResults
quitGroup(
669 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
670 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
671 final var newAdmins
= getRecipientIds(groupAdmins
);
672 return groupHelper
.quitGroup(groupId
, newAdmins
);
675 public void deleteGroup(GroupId groupId
) throws IOException
{
676 account
.getGroupStore().deleteGroup(groupId
);
677 avatarStore
.deleteGroupAvatar(groupId
);
680 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
681 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
682 ) throws IOException
, AttachmentInvalidException
{
683 return groupHelper
.createGroup(name
, members
== null ?
null : getRecipientIds(members
), avatarFile
);
686 public SendGroupMessageResults
updateGroup(
690 Set
<RecipientIdentifier
.Single
> members
,
691 Set
<RecipientIdentifier
.Single
> removeMembers
,
692 Set
<RecipientIdentifier
.Single
> admins
,
693 Set
<RecipientIdentifier
.Single
> removeAdmins
,
694 boolean resetGroupLink
,
695 GroupLinkState groupLinkState
,
696 GroupPermission addMemberPermission
,
697 GroupPermission editDetailsPermission
,
699 Integer expirationTimer
,
700 Boolean isAnnouncementGroup
701 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
702 return groupHelper
.updateGroup(groupId
,
705 members
== null ?
null : getRecipientIds(members
),
706 removeMembers
== null ?
null : getRecipientIds(removeMembers
),
707 admins
== null ?
null : getRecipientIds(admins
),
708 removeAdmins
== null ?
null : getRecipientIds(removeAdmins
),
712 editDetailsPermission
,
715 isAnnouncementGroup
);
718 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
719 GroupInviteLinkUrl inviteLinkUrl
720 ) throws IOException
, GroupLinkNotActiveException
{
721 return groupHelper
.joinGroup(inviteLinkUrl
);
724 public SendMessageResults
sendMessage(
725 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
726 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
727 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
728 long timestamp
= System
.currentTimeMillis();
729 messageBuilder
.withTimestamp(timestamp
);
730 for (final var recipient
: recipients
) {
731 if (recipient
instanceof RecipientIdentifier
.Single
) {
732 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
733 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
734 results
.put(recipient
, List
.of(result
));
735 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
736 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
737 results
.put(recipient
, List
.of(result
));
738 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
739 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
740 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
741 results
.put(recipient
, result
);
744 return new SendMessageResults(timestamp
, results
);
747 public void sendTypingMessage(
748 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
749 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
750 final var timestamp
= System
.currentTimeMillis();
751 for (var recipient
: recipients
) {
752 if (recipient
instanceof RecipientIdentifier
.Single
) {
753 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
754 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
755 sendHelper
.sendTypingMessage(message
, recipientId
);
756 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
757 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
758 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
759 sendHelper
.sendGroupTypingMessage(message
, groupId
);
764 SendGroupMessageResults
sendGroupInfoMessage(
765 GroupIdV1 groupId
, SignalServiceAddress recipient
766 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
767 final var recipientId
= resolveRecipient(recipient
);
768 return groupHelper
.sendGroupInfoMessage(groupId
, recipientId
);
771 SendGroupMessageResults
sendGroupInfoRequest(
772 GroupIdV1 groupId
, SignalServiceAddress recipient
773 ) throws IOException
{
774 final var recipientId
= resolveRecipient(recipient
);
775 return groupHelper
.sendGroupInfoRequest(groupId
, recipientId
);
778 public void sendReadReceipt(
779 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
780 ) throws IOException
, UntrustedIdentityException
{
781 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
783 System
.currentTimeMillis());
785 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
788 public void sendViewedReceipt(
789 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
790 ) throws IOException
, UntrustedIdentityException
{
791 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
793 System
.currentTimeMillis());
795 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
798 void sendDeliveryReceipt(
799 SignalServiceAddress remoteAddress
, List
<Long
> messageIds
800 ) throws IOException
, UntrustedIdentityException
{
801 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
803 System
.currentTimeMillis());
805 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(remoteAddress
));
808 public SendMessageResults
sendMessage(
809 Message message
, Set
<RecipientIdentifier
> recipients
810 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
811 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
812 applyMessage(messageBuilder
, message
);
813 return sendMessage(messageBuilder
, recipients
);
816 private void applyMessage(
817 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
818 ) throws AttachmentInvalidException
, IOException
{
819 messageBuilder
.withBody(message
.getMessageText());
820 if (message
.getAttachments() != null) {
821 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(message
.getAttachments());
823 // Upload attachments here, so we only upload once even for multiple recipients
824 var messageSender
= dependencies
.getMessageSender();
825 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
826 for (var attachment
: attachmentStreams
) {
827 if (attachment
.isStream()) {
828 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
829 } else if (attachment
.isPointer()) {
830 attachmentPointers
.add(attachment
.asPointer());
834 messageBuilder
.withAttachments(attachmentPointers
);
838 public SendMessageResults
sendRemoteDeleteMessage(
839 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
840 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
841 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
842 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
843 return sendMessage(messageBuilder
, recipients
);
846 public SendMessageResults
sendMessageReaction(
849 RecipientIdentifier
.Single targetAuthor
,
850 long targetSentTimestamp
,
851 Set
<RecipientIdentifier
> recipients
852 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
853 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
854 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
856 resolveSignalServiceAddress(targetAuthorRecipientId
),
857 targetSentTimestamp
);
858 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
859 return sendMessage(messageBuilder
, recipients
);
862 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
863 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
866 return sendMessage(messageBuilder
,
867 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
868 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
869 throw new AssertionError(e
);
871 for (var recipient
: recipients
) {
872 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
873 handleEndSession(recipientId
);
878 void renewSession(RecipientId recipientId
) throws IOException
{
879 account
.getSessionStore().archiveSessions(recipientId
);
880 if (!recipientId
.equals(getSelfRecipientId())) {
881 sendHelper
.sendNullMessage(recipientId
);
885 public void setContactName(
886 RecipientIdentifier
.Single recipient
, String name
887 ) throws NotMasterDeviceException
{
888 if (!account
.isMasterDevice()) {
889 throw new NotMasterDeviceException();
891 final var recipientId
= resolveRecipient(recipient
);
892 var contact
= account
.getContactStore().getContact(recipientId
);
893 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
894 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
897 public void setContactBlocked(
898 RecipientIdentifier
.Single recipient
, boolean blocked
899 ) throws NotMasterDeviceException
{
900 if (!account
.isMasterDevice()) {
901 throw new NotMasterDeviceException();
903 setContactBlocked(resolveRecipient(recipient
), blocked
);
906 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
907 var contact
= account
.getContactStore().getContact(recipientId
);
908 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
909 // TODO cycle our profile key
910 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
913 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
914 var group
= getGroup(groupId
);
916 throw new GroupNotFoundException(groupId
);
919 group
.setBlocked(blocked
);
920 // TODO cycle our profile key
921 account
.getGroupStore().updateGroup(group
);
925 * Change the expiration timer for a contact
927 public void setExpirationTimer(
928 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
929 ) throws IOException
{
930 var recipientId
= resolveRecipient(recipient
);
931 setExpirationTimer(recipientId
, messageExpirationTimer
);
932 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
934 sendMessage(messageBuilder
, Set
.of(recipient
));
935 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
936 throw new AssertionError(e
);
940 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
941 var contact
= account
.getContactStore().getContact(recipientId
);
942 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
945 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
946 account
.getContactStore()
947 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
951 * Upload the sticker pack from path.
953 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
954 * @return if successful, returns the URL to install the sticker pack in the signal app
956 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
957 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
959 var messageSender
= dependencies
.getMessageSender();
961 var packKey
= KeyUtils
.createStickerUploadKey();
962 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
963 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
965 var sticker
= new Sticker(packId
, packKey
);
966 account
.getStickerStore().updateSticker(sticker
);
969 return new URI("https",
973 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
975 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
976 } catch (URISyntaxException e
) {
977 throw new AssertionError(e
);
981 public void requestAllSyncData() throws IOException
{
983 requestSyncContacts();
984 requestSyncBlocked();
985 requestSyncConfiguration();
989 private void requestSyncGroups() throws IOException
{
990 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
991 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
993 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
994 sendHelper
.sendSyncMessage(message
);
997 private void requestSyncContacts() throws IOException
{
998 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
999 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1001 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1002 sendHelper
.sendSyncMessage(message
);
1005 private void requestSyncBlocked() throws IOException
{
1006 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1007 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1009 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1010 sendHelper
.sendSyncMessage(message
);
1013 private void requestSyncConfiguration() throws IOException
{
1014 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1015 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1017 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1018 sendHelper
.sendSyncMessage(message
);
1021 private void requestSyncKeys() throws IOException
{
1022 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1023 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1025 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1026 sendHelper
.sendSyncMessage(message
);
1029 private byte[] getSenderCertificate() {
1032 if (account
.isPhoneNumberShared()) {
1033 certificate
= dependencies
.getAccountManager().getSenderCertificate();
1035 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
1037 } catch (IOException e
) {
1038 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1041 // TODO cache for a day
1045 private Set
<RecipientId
> getRecipientIds(Collection
<RecipientIdentifier
.Single
> recipients
) {
1046 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(recipients
.size());
1047 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1049 for (var number
: recipients
) {
1050 final var resolvedAddress
= resolveSignalServiceAddress(resolveRecipient(number
));
1051 if (resolvedAddress
.getUuid().isPresent()) {
1052 signalServiceAddresses
.add(resolvedAddress
);
1054 addressesMissingUuid
.add(resolvedAddress
);
1058 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1059 .map(a
-> a
.getNumber().get())
1060 .collect(Collectors
.toSet());
1061 Map
<String
, UUID
> registeredUsers
;
1063 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1064 } catch (IOException e
) {
1065 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1066 registeredUsers
= Map
.of();
1069 for (var address
: addressesMissingUuid
) {
1070 final var number
= address
.getNumber().get();
1071 if (registeredUsers
.containsKey(number
)) {
1072 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1073 registeredUsers
.get(number
),
1075 signalServiceAddresses
.add(newAddress
);
1077 signalServiceAddresses
.add(address
);
1081 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1084 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1085 final var address
= resolveSignalServiceAddress(recipientId
);
1086 if (!address
.getNumber().isPresent()) {
1089 final var number
= address
.getNumber().get();
1090 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1091 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1094 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1095 final Map
<String
, UUID
> registeredUsers
;
1097 registeredUsers
= dependencies
.getAccountManager()
1098 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1100 serviceEnvironmentConfig
.getCdsMrenclave());
1101 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1102 throw new IOException(e
);
1105 // Store numbers as recipients so we have the number/uuid association
1106 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
1108 return registeredUsers
;
1111 public void sendTypingMessage(
1112 TypingAction action
, Set
<RecipientIdentifier
> recipients
1113 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
1114 sendTypingMessage(action
.toSignalService(), recipients
);
1117 private void handleEndSession(RecipientId recipientId
) {
1118 account
.getSessionStore().deleteAllSessions(recipientId
);
1121 private List
<HandleAction
> handleSignalServiceDataMessage(
1122 SignalServiceDataMessage message
,
1124 SignalServiceAddress source
,
1125 SignalServiceAddress destination
,
1126 boolean ignoreAttachments
1128 var actions
= new ArrayList
<HandleAction
>();
1129 if (message
.getGroupContext().isPresent()) {
1130 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1131 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1132 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1133 var group
= getGroup(groupId
);
1134 if (group
== null || group
instanceof GroupInfoV1
) {
1135 var groupV1
= (GroupInfoV1
) group
;
1136 switch (groupInfo
.getType()) {
1138 if (groupV1
== null) {
1139 groupV1
= new GroupInfoV1(groupId
);
1142 if (groupInfo
.getAvatar().isPresent()) {
1143 var avatar
= groupInfo
.getAvatar().get();
1144 downloadGroupAvatar(groupV1
.getGroupId(), avatar
);
1147 if (groupInfo
.getName().isPresent()) {
1148 groupV1
.name
= groupInfo
.getName().get();
1151 if (groupInfo
.getMembers().isPresent()) {
1152 groupV1
.addMembers(groupInfo
.getMembers()
1155 .map(this::resolveRecipient
)
1156 .collect(Collectors
.toSet()));
1159 account
.getGroupStore().updateGroup(groupV1
);
1163 if (groupV1
== null && !isSync
) {
1164 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1168 if (groupV1
!= null) {
1169 groupV1
.removeMember(resolveRecipient(source
));
1170 account
.getGroupStore().updateGroup(groupV1
);
1175 if (groupV1
!= null && !isSync
) {
1176 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1181 // Received a group v1 message for a v2 group
1184 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1185 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1186 final var groupMasterKey
= groupContext
.getMasterKey();
1188 groupHelper
.getOrMigrateGroup(groupMasterKey
,
1189 groupContext
.getRevision(),
1190 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1194 final var conversationPartnerAddress
= isSync ? destination
: source
;
1195 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1196 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1198 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1199 if (message
.getGroupContext().isPresent()) {
1200 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1201 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1202 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1203 if (group
!= null) {
1204 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1205 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1206 account
.getGroupStore().updateGroup(group
);
1209 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1210 // disappearing message timer already stored in the DecryptedGroup
1212 } else if (conversationPartnerAddress
!= null) {
1213 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1216 if (!ignoreAttachments
) {
1217 if (message
.getAttachments().isPresent()) {
1218 for (var attachment
: message
.getAttachments().get()) {
1219 downloadAttachment(attachment
);
1222 if (message
.getSharedContacts().isPresent()) {
1223 for (var contact
: message
.getSharedContacts().get()) {
1224 if (contact
.getAvatar().isPresent()) {
1225 downloadAttachment(contact
.getAvatar().get().getAttachment());
1230 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1231 final ProfileKey profileKey
;
1233 profileKey
= new ProfileKey(message
.getProfileKey().get());
1234 } catch (InvalidInputException e
) {
1235 throw new AssertionError(e
);
1237 if (source
.matches(account
.getSelfAddress())) {
1238 this.account
.setProfileKey(profileKey
);
1240 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1242 if (message
.getPreviews().isPresent()) {
1243 final var previews
= message
.getPreviews().get();
1244 for (var preview
: previews
) {
1245 if (preview
.getImage().isPresent()) {
1246 downloadAttachment(preview
.getImage().get());
1250 if (message
.getQuote().isPresent()) {
1251 final var quote
= message
.getQuote().get();
1253 for (var quotedAttachment
: quote
.getAttachments()) {
1254 final var thumbnail
= quotedAttachment
.getThumbnail();
1255 if (thumbnail
!= null) {
1256 downloadAttachment(thumbnail
);
1260 if (message
.getSticker().isPresent()) {
1261 final var messageSticker
= message
.getSticker().get();
1262 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1263 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1264 if (sticker
== null) {
1265 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1266 account
.getStickerStore().updateSticker(sticker
);
1268 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, messageSticker
.getPackKey()));
1273 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1274 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1275 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1276 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1277 if (actions
!= null) {
1278 queuedActions
.addAll(actions
);
1281 handleQueuedActions(queuedActions
);
1284 private List
<HandleAction
> retryFailedReceivedMessage(
1285 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1287 var envelope
= cachedMessage
.loadEnvelope();
1288 if (envelope
== null) {
1291 SignalServiceContent content
= null;
1292 List
<HandleAction
> actions
= null;
1293 if (!envelope
.isReceipt()) {
1295 content
= dependencies
.getCipher().decrypt(envelope
);
1296 } catch (ProtocolUntrustedIdentityException e
) {
1297 if (!envelope
.hasSource()) {
1298 final var identifier
= e
.getSender();
1299 final var recipientId
= resolveRecipient(identifier
);
1301 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1302 } catch (IOException ioException
) {
1303 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1307 } catch (Exception er
) {
1308 // All other errors are not recoverable, so delete the cached message
1309 cachedMessage
.delete();
1312 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1314 handler
.handleMessage(envelope
, content
, null);
1315 cachedMessage
.delete();
1319 public void receiveMessages(
1322 boolean returnOnTimeout
,
1323 boolean ignoreAttachments
,
1324 ReceiveMessageHandler handler
1325 ) throws IOException
{
1326 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1328 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1330 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1331 signalWebSocket
.connect();
1333 var hasCaughtUpWithOldMessages
= false;
1335 while (!Thread
.interrupted()) {
1336 SignalServiceEnvelope envelope
;
1337 SignalServiceContent content
= null;
1338 Exception exception
= null;
1339 final CachedMessage
[] cachedMessage
= {null};
1340 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
1341 logger
.debug("Checking for new message from server");
1343 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1344 final var recipientId
= envelope1
.hasSource()
1345 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1347 // store message on disk, before acknowledging receipt to the server
1348 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1350 logger
.debug("New message received from server");
1351 if (result
.isPresent()) {
1352 envelope
= result
.get();
1354 // Received indicator that server queue is empty
1355 hasCaughtUpWithOldMessages
= true;
1357 handleQueuedActions(queuedActions
);
1358 queuedActions
.clear();
1360 // Continue to wait another timeout for new messages
1363 } catch (AssertionError e
) {
1364 if (e
.getCause() instanceof InterruptedException
) {
1365 Thread
.currentThread().interrupt();
1370 } catch (WebSocketUnavailableException e
) {
1371 logger
.debug("Pipe unexpectedly unavailable, connecting");
1372 signalWebSocket
.connect();
1374 } catch (TimeoutException e
) {
1375 if (returnOnTimeout
) return;
1379 if (envelope
.hasSource()) {
1380 // Store uuid if we don't have it already
1381 // address/uuid in envelope is sent by server
1382 resolveRecipientTrusted(envelope
.getSourceAddress());
1384 if (!envelope
.isReceipt()) {
1386 content
= dependencies
.getCipher().decrypt(envelope
);
1387 } catch (Exception e
) {
1390 if (!envelope
.hasSource() && content
!= null) {
1391 // Store uuid if we don't have it already
1392 // address/uuid is validated by unidentified sender certificate
1393 resolveRecipientTrusted(content
.getSender());
1395 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1396 if (exception
instanceof ProtocolInvalidMessageException
) {
1397 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
1398 logger
.debug("Received invalid message, queuing renew session action.");
1399 actions
.add(new RenewSessionAction(sender
));
1401 if (hasCaughtUpWithOldMessages
) {
1402 for (var action
: actions
) {
1404 action
.execute(this);
1405 } catch (Throwable e
) {
1406 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1407 Thread
.currentThread().interrupt();
1409 logger
.warn("Message action failed.", e
);
1413 queuedActions
.addAll(actions
);
1416 final var notAllowedToSendToGroup
= isNotAllowedToSendToGroup(envelope
, content
);
1417 if (isMessageBlocked(envelope
, content
)) {
1418 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1419 } else if (notAllowedToSendToGroup
) {
1420 logger
.info("Ignoring a group message from an unauthorized sender (no member or admin): {} {}",
1421 (envelope
.hasSource() ? envelope
.getSourceAddress() : content
.getSender()).getIdentifier(),
1422 envelope
.getTimestamp());
1424 handler
.handleMessage(envelope
, content
, exception
);
1426 if (cachedMessage
[0] != null) {
1427 if (exception
instanceof ProtocolUntrustedIdentityException
) {
1428 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
1429 final var recipientId
= resolveRecipient(identifier
);
1430 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1431 if (!envelope
.hasSource()) {
1433 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1434 } catch (IOException ioException
) {
1435 logger
.warn("Failed to move cached message to recipient folder: {}",
1436 ioException
.getMessage());
1440 cachedMessage
[0].delete();
1444 handleQueuedActions(queuedActions
);
1447 private void handleQueuedActions(final Set
<HandleAction
> queuedActions
) {
1448 for (var action
: queuedActions
) {
1450 action
.execute(this);
1451 } catch (Throwable e
) {
1452 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1453 Thread
.currentThread().interrupt();
1455 logger
.warn("Message action failed.", e
);
1460 private boolean isMessageBlocked(
1461 SignalServiceEnvelope envelope
, SignalServiceContent content
1463 SignalServiceAddress source
;
1464 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1465 source
= envelope
.getSourceAddress();
1466 } else if (content
!= null) {
1467 source
= content
.getSender();
1471 final var recipientId
= resolveRecipient(source
);
1472 if (isContactBlocked(recipientId
)) {
1476 if (content
!= null && content
.getDataMessage().isPresent()) {
1477 var message
= content
.getDataMessage().get();
1478 if (message
.getGroupContext().isPresent()) {
1479 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1480 var group
= getGroup(groupId
);
1481 if (group
!= null && group
.isBlocked()) {
1489 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1490 final var recipientId
= resolveRecipient(recipient
);
1491 return isContactBlocked(recipientId
);
1494 private boolean isContactBlocked(final RecipientId recipientId
) {
1495 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1496 return sourceContact
!= null && sourceContact
.isBlocked();
1499 private boolean isNotAllowedToSendToGroup(
1500 SignalServiceEnvelope envelope
, SignalServiceContent content
1502 SignalServiceAddress source
;
1503 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1504 source
= envelope
.getSourceAddress();
1505 } else if (content
!= null) {
1506 source
= content
.getSender();
1511 if (content
== null || !content
.getDataMessage().isPresent()) {
1515 var message
= content
.getDataMessage().get();
1516 if (!message
.getGroupContext().isPresent()) {
1520 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1521 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1522 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1527 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1528 var group
= getGroup(groupId
);
1529 if (group
== null) {
1533 final var recipientId
= resolveRecipient(source
);
1534 if (!group
.isMember(recipientId
)) {
1538 if (group
.isAnnouncementGroup() && !group
.isAdmin(recipientId
)) {
1539 return message
.getBody().isPresent()
1540 || message
.getAttachments().isPresent()
1541 || message
.getQuote()
1543 || message
.getPreviews().isPresent()
1544 || message
.getMentions().isPresent()
1545 || message
.getSticker().isPresent();
1550 private List
<HandleAction
> handleMessage(
1551 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1553 var actions
= new ArrayList
<HandleAction
>();
1554 if (content
!= null) {
1555 final SignalServiceAddress sender
;
1556 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1557 sender
= envelope
.getSourceAddress();
1559 sender
= content
.getSender();
1562 if (content
.getDataMessage().isPresent()) {
1563 var message
= content
.getDataMessage().get();
1565 if (content
.isNeedsReceipt()) {
1566 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1569 actions
.addAll(handleSignalServiceDataMessage(message
,
1572 account
.getSelfAddress(),
1573 ignoreAttachments
));
1575 if (content
.getSyncMessage().isPresent()) {
1576 account
.setMultiDevice(true);
1577 var syncMessage
= content
.getSyncMessage().get();
1578 if (syncMessage
.getSent().isPresent()) {
1579 var message
= syncMessage
.getSent().get();
1580 final var destination
= message
.getDestination().orNull();
1581 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1585 ignoreAttachments
));
1587 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
1588 var rm
= syncMessage
.getRequest().get();
1589 if (rm
.isContactsRequest()) {
1590 actions
.add(SendSyncContactsAction
.create());
1592 if (rm
.isGroupsRequest()) {
1593 actions
.add(SendSyncGroupsAction
.create());
1595 if (rm
.isBlockedListRequest()) {
1596 actions
.add(SendSyncBlockedListAction
.create());
1598 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1600 if (syncMessage
.getGroups().isPresent()) {
1601 File tmpFile
= null;
1603 tmpFile
= IOUtils
.createTempFile();
1604 final var groupsMessage
= syncMessage
.getGroups().get();
1605 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1606 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1611 } catch (IOException e
) {
1612 logger
.warn("Sync groups contained invalid group, ignoring: {}", e
.getMessage());
1618 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1619 if (syncGroup
!= null) {
1620 if (g
.getName().isPresent()) {
1621 syncGroup
.name
= g
.getName().get();
1623 syncGroup
.addMembers(g
.getMembers()
1625 .map(this::resolveRecipient
)
1626 .collect(Collectors
.toSet()));
1627 if (!g
.isActive()) {
1628 syncGroup
.removeMember(account
.getSelfRecipientId());
1630 // Add ourself to the member set as it's marked as active
1631 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
1633 syncGroup
.blocked
= g
.isBlocked();
1634 if (g
.getColor().isPresent()) {
1635 syncGroup
.color
= g
.getColor().get();
1638 if (g
.getAvatar().isPresent()) {
1639 downloadGroupAvatar(syncGroup
.getGroupId(), g
.getAvatar().get());
1641 syncGroup
.archived
= g
.isArchived();
1642 account
.getGroupStore().updateGroup(syncGroup
);
1646 } catch (Exception e
) {
1647 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1651 if (tmpFile
!= null) {
1653 Files
.delete(tmpFile
.toPath());
1654 } catch (IOException e
) {
1655 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1662 if (syncMessage
.getBlockedList().isPresent()) {
1663 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1664 for (var address
: blockedListMessage
.getAddresses()) {
1665 setContactBlocked(resolveRecipient(address
), true);
1667 for (var groupId
: blockedListMessage
.getGroupIds()
1669 .map(GroupId
::unknownVersion
)
1670 .collect(Collectors
.toSet())) {
1672 setGroupBlocked(groupId
, true);
1673 } catch (GroupNotFoundException e
) {
1674 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1675 groupId
.toBase64());
1679 if (syncMessage
.getContacts().isPresent()) {
1680 File tmpFile
= null;
1682 tmpFile
= IOUtils
.createTempFile();
1683 final var contactsMessage
= syncMessage
.getContacts().get();
1684 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1685 .asPointer(), tmpFile
)) {
1686 var s
= new DeviceContactsInputStream(attachmentAsStream
);
1691 } catch (IOException e
) {
1692 logger
.warn("Sync contacts contained invalid contact, ignoring: {}",
1699 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1700 account
.setProfileKey(c
.getProfileKey().get());
1702 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
1703 var contact
= account
.getContactStore().getContact(recipientId
);
1704 final var builder
= contact
== null
1705 ? Contact
.newBuilder()
1706 : Contact
.newBuilder(contact
);
1707 if (c
.getName().isPresent()) {
1708 builder
.withName(c
.getName().get());
1710 if (c
.getColor().isPresent()) {
1711 builder
.withColor(c
.getColor().get());
1713 if (c
.getProfileKey().isPresent()) {
1714 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
1716 if (c
.getVerified().isPresent()) {
1717 final var verifiedMessage
= c
.getVerified().get();
1718 account
.getIdentityKeyStore()
1719 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
1720 verifiedMessage
.getIdentityKey(),
1721 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1723 if (c
.getExpirationTimer().isPresent()) {
1724 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
1726 builder
.withBlocked(c
.isBlocked());
1727 builder
.withArchived(c
.isArchived());
1728 account
.getContactStore().storeContact(recipientId
, builder
.build());
1730 if (c
.getAvatar().isPresent()) {
1731 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
1735 } catch (Exception e
) {
1736 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1740 if (tmpFile
!= null) {
1742 Files
.delete(tmpFile
.toPath());
1743 } catch (IOException e
) {
1744 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1751 if (syncMessage
.getVerified().isPresent()) {
1752 final var verifiedMessage
= syncMessage
.getVerified().get();
1753 account
.getIdentityKeyStore()
1754 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
1755 verifiedMessage
.getIdentityKey(),
1756 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1758 if (syncMessage
.getStickerPackOperations().isPresent()) {
1759 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
1760 for (var m
: stickerPackOperationMessages
) {
1761 if (!m
.getPackId().isPresent()) {
1764 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
1765 final var installed
= !m
.getType().isPresent()
1766 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
;
1768 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1769 if (m
.getPackKey().isPresent()) {
1770 if (sticker
== null) {
1771 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
1774 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, m
.getPackKey().get()));
1778 if (sticker
!= null) {
1779 sticker
.setInstalled(installed
);
1780 account
.getStickerStore().updateSticker(sticker
);
1784 if (syncMessage
.getFetchType().isPresent()) {
1785 switch (syncMessage
.getFetchType().get()) {
1787 getRecipientProfile(account
.getSelfRecipientId(), true);
1788 case STORAGE_MANIFEST
:
1792 if (syncMessage
.getKeys().isPresent()) {
1793 final var keysMessage
= syncMessage
.getKeys().get();
1794 if (keysMessage
.getStorageService().isPresent()) {
1795 final var storageKey
= keysMessage
.getStorageService().get();
1796 account
.setStorageKey(storageKey
);
1799 if (syncMessage
.getConfiguration().isPresent()) {
1807 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
1809 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
1810 } catch (IOException e
) {
1811 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
1815 private void downloadGroupAvatar(GroupIdV1 groupId
, SignalServiceAttachment avatar
) {
1817 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
1818 } catch (IOException e
) {
1819 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
1823 private void downloadProfileAvatar(
1824 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
1827 avatarStore
.storeProfileAvatar(address
,
1828 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
1829 } catch (Throwable e
) {
1830 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1831 Thread
.currentThread().interrupt();
1833 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
1837 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
1838 return attachmentStore
.getAttachmentFile(attachmentId
);
1841 private void downloadAttachment(final SignalServiceAttachment attachment
) {
1842 if (!attachment
.isPointer()) {
1843 logger
.warn("Invalid state, can't store an attachment stream.");
1846 var pointer
= attachment
.asPointer();
1847 if (pointer
.getPreview().isPresent()) {
1848 final var preview
= pointer
.getPreview().get();
1850 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
1851 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
1852 } catch (IOException e
) {
1853 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
1858 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
1859 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
1860 } catch (IOException e
) {
1861 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
1865 private void retrieveProfileAvatar(
1866 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
1867 ) throws IOException
{
1868 var tmpFile
= IOUtils
.createTempFile();
1869 try (var input
= dependencies
.getMessageReceiver()
1870 .retrieveProfileAvatar(avatarPath
,
1873 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
1874 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
1875 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
1878 Files
.delete(tmpFile
.toPath());
1879 } catch (IOException e
) {
1880 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
1887 private void retrieveAttachment(
1888 final SignalServiceAttachment attachment
, final OutputStream outputStream
1889 ) throws IOException
{
1890 if (attachment
.isPointer()) {
1891 var pointer
= attachment
.asPointer();
1892 retrieveAttachmentPointer(pointer
, outputStream
);
1894 var stream
= attachment
.asStream();
1895 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
1899 private void retrieveAttachmentPointer(
1900 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
1901 ) throws IOException
{
1902 var tmpFile
= IOUtils
.createTempFile();
1903 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
1904 IOUtils
.copyStream(input
, outputStream
);
1905 } catch (MissingConfigurationException
| InvalidMessageException e
) {
1906 throw new IOException(e
);
1909 Files
.delete(tmpFile
.toPath());
1910 } catch (IOException e
) {
1911 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
1918 private InputStream
retrieveAttachmentAsStream(
1919 SignalServiceAttachmentPointer pointer
, File tmpFile
1920 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
1921 return dependencies
.getMessageReceiver()
1922 .retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
1925 void sendGroups() throws IOException
{
1926 var groupsFile
= IOUtils
.createTempFile();
1929 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1930 var out
= new DeviceGroupsOutputStream(fos
);
1931 for (var record : getGroups()) {
1932 if (record instanceof GroupInfoV1
) {
1933 var groupInfo
= (GroupInfoV1
) record;
1934 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
1935 Optional
.fromNullable(groupInfo
.name
),
1936 groupInfo
.getMembers()
1938 .map(this::resolveSignalServiceAddress
)
1939 .collect(Collectors
.toList()),
1940 groupHelper
.createGroupAvatarAttachment(groupInfo
.getGroupId()),
1941 groupInfo
.isMember(account
.getSelfRecipientId()),
1942 Optional
.of(groupInfo
.messageExpirationTime
),
1943 Optional
.fromNullable(groupInfo
.color
),
1946 groupInfo
.archived
));
1951 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1952 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
1953 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1954 .withStream(groupsFileStream
)
1955 .withContentType("application/octet-stream")
1956 .withLength(groupsFile
.length())
1959 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1964 Files
.delete(groupsFile
.toPath());
1965 } catch (IOException e
) {
1966 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
1971 public void sendContacts() throws IOException
{
1972 var contactsFile
= IOUtils
.createTempFile();
1975 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1976 var out
= new DeviceContactsOutputStream(fos
);
1977 for (var contactPair
: account
.getContactStore().getContacts()) {
1978 final var recipientId
= contactPair
.first();
1979 final var contact
= contactPair
.second();
1980 final var address
= resolveSignalServiceAddress(recipientId
);
1982 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1983 VerifiedMessage verifiedMessage
= null;
1984 if (currentIdentity
!= null) {
1985 verifiedMessage
= new VerifiedMessage(address
,
1986 currentIdentity
.getIdentityKey(),
1987 currentIdentity
.getTrustLevel().toVerifiedState(),
1988 currentIdentity
.getDateAdded().getTime());
1991 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
1992 out
.write(new DeviceContact(address
,
1993 Optional
.fromNullable(contact
.getName()),
1994 createContactAvatarAttachment(address
),
1995 Optional
.fromNullable(contact
.getColor()),
1996 Optional
.fromNullable(verifiedMessage
),
1997 Optional
.fromNullable(profileKey
),
1998 contact
.isBlocked(),
1999 Optional
.of(contact
.getMessageExpirationTime()),
2001 contact
.isArchived()));
2004 if (account
.getProfileKey() != null) {
2005 // Send our own profile key as well
2006 out
.write(new DeviceContact(account
.getSelfAddress(),
2011 Optional
.of(account
.getProfileKey()),
2019 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2020 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2021 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2022 .withStream(contactsFileStream
)
2023 .withContentType("application/octet-stream")
2024 .withLength(contactsFile
.length())
2027 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
,
2033 Files
.delete(contactsFile
.toPath());
2034 } catch (IOException e
) {
2035 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2040 void sendBlockedList() throws IOException
{
2041 var addresses
= new ArrayList
<SignalServiceAddress
>();
2042 for (var record : account
.getContactStore().getContacts()) {
2043 if (record.second().isBlocked()) {
2044 addresses
.add(resolveSignalServiceAddress(record.first()));
2047 var groupIds
= new ArrayList
<byte[]>();
2048 for (var record : getGroups()) {
2049 if (record.isBlocked()) {
2050 groupIds
.add(record.getGroupId().serialize());
2053 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2056 private void sendVerifiedMessage(
2057 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2058 ) throws IOException
{
2059 var verifiedMessage
= new VerifiedMessage(destination
,
2061 trustLevel
.toVerifiedState(),
2062 System
.currentTimeMillis());
2063 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2066 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2067 return account
.getContactStore().getContacts();
2070 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
2071 final var recipientId
= resolveRecipient(recipientIdentifier
);
2072 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2073 if (recipient
== null) {
2077 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2078 return recipient
.getContact().getName();
2081 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2082 return recipient
.getProfile().getDisplayName();
2088 public GroupInfo
getGroup(GroupId groupId
) {
2089 return groupHelper
.getGroup(groupId
);
2092 public List
<IdentityInfo
> getIdentities() {
2093 return account
.getIdentityKeyStore().getIdentities();
2096 public List
<IdentityInfo
> getIdentities(RecipientIdentifier
.Single recipient
) {
2097 final var identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
2098 return identity
== null ? List
.of() : List
.of(identity
);
2102 * Trust this the identity with this fingerprint
2104 * @param recipient username of the identity
2105 * @param fingerprint Fingerprint
2107 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
2108 var recipientId
= resolveRecipient(recipient
);
2109 return trustIdentity(recipientId
,
2110 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2111 TrustLevel
.TRUSTED_VERIFIED
);
2115 * Trust this the identity with this safety number
2117 * @param recipient username of the identity
2118 * @param safetyNumber Safety number
2120 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
2121 var recipientId
= resolveRecipient(recipient
);
2122 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2123 return trustIdentity(recipientId
,
2124 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2125 TrustLevel
.TRUSTED_VERIFIED
);
2129 * Trust this the identity with this scannable safety number
2131 * @param recipient username of the identity
2132 * @param safetyNumber Scannable safety number
2134 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
2135 var recipientId
= resolveRecipient(recipient
);
2136 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2137 return trustIdentity(recipientId
, identityKey
-> {
2138 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
2140 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
2141 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
2144 }, TrustLevel
.TRUSTED_VERIFIED
);
2148 * Trust all keys of this identity without verification
2150 * @param recipient username of the identity
2152 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
2153 var recipientId
= resolveRecipient(recipient
);
2154 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2157 private boolean trustIdentity(
2158 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2160 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2161 if (identity
== null) {
2165 if (!verifier
.apply(identity
.getIdentityKey())) {
2169 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2171 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2172 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2173 } catch (IOException e
) {
2174 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2180 private void handleIdentityFailure(
2181 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
2183 final var identityKey
= identityFailure
.getIdentityKey();
2184 if (identityKey
!= null) {
2185 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
2187 account
.getSessionStore().archiveSessions(recipientId
);
2190 // Retrieve profile to get the current identity key from the server
2191 retrieveEncryptedProfile(recipientId
);
2195 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
2196 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
2197 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
2200 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
2201 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
2202 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
2205 private Fingerprint
computeSafetyNumberFingerprint(
2206 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
2208 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
2209 account
.getSelfAddress(),
2210 getIdentityKeyPair().getPublicKey(),
2216 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2217 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2219 return resolveSignalServiceAddress(address
);
2223 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2224 if (address
.matches(account
.getSelfAddress())) {
2225 return account
.getSelfAddress();
2228 return account
.getRecipientStore().resolveServiceAddress(address
);
2231 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2232 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2235 private String
canonicalizePhoneNumber(final String number
) throws InvalidNumberException
{
2236 return PhoneNumberFormatter
.formatNumber(number
, account
.getUsername());
2239 private RecipientId
resolveRecipient(final String identifier
) {
2240 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2242 return resolveRecipient(address
);
2245 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) {
2246 final SignalServiceAddress address
;
2247 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
2248 address
= new SignalServiceAddress(((RecipientIdentifier
.Uuid
) recipient
).uuid
, null);
2250 address
= new SignalServiceAddress(null, ((RecipientIdentifier
.Number
) recipient
).number
);
2253 return resolveRecipient(address
);
2256 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2257 return account
.getRecipientStore().resolveRecipient(address
);
2260 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2261 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2264 private void enqueueJob(Job job
) {
2265 var context
= new Context(account
,
2266 dependencies
.getAccountManager(),
2267 dependencies
.getMessageReceiver(),
2273 public void close() throws IOException
{
2277 void close(boolean closeAccount
) throws IOException
{
2278 executor
.shutdown();
2280 dependencies
.getSignalWebSocket().disconnect();
2282 if (closeAccount
&& account
!= null) {
2288 public interface ReceiveMessageHandler
{
2290 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);