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
.TypingAction
;
21 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
22 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
23 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
24 import org
.asamk
.signal
.manager
.groups
.GroupId
;
25 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
26 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
27 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
28 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
29 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
30 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
31 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
32 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
33 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
34 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
35 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
36 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
37 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
38 import org
.asamk
.signal
.manager
.jobs
.Context
;
39 import org
.asamk
.signal
.manager
.jobs
.Job
;
40 import org
.asamk
.signal
.manager
.jobs
.RetrieveStickerPackJob
;
41 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
42 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
43 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
44 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
45 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
46 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
47 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
48 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
49 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
50 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
51 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
52 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
53 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
54 import org
.asamk
.signal
.manager
.util
.IOUtils
;
55 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
56 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
57 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
58 import org
.asamk
.signal
.manager
.util
.Utils
;
59 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
60 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
61 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
62 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
63 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
64 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
65 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
66 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
67 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
68 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
69 import org
.signal
.libsignal
.metadata
.SelfSendException
;
70 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
71 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
72 import org
.signal
.zkgroup
.InvalidInputException
;
73 import org
.signal
.zkgroup
.VerificationFailedException
;
74 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
75 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
76 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
77 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
78 import org
.slf4j
.Logger
;
79 import org
.slf4j
.LoggerFactory
;
80 import org
.whispersystems
.libsignal
.IdentityKey
;
81 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
82 import org
.whispersystems
.libsignal
.InvalidKeyException
;
83 import org
.whispersystems
.libsignal
.InvalidMessageException
;
84 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
85 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
86 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintParsingException
;
87 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintVersionMismatchException
;
88 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
89 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
90 import org
.whispersystems
.libsignal
.util
.Pair
;
91 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
92 import org
.whispersystems
.signalservice
.api
.InvalidMessageStructureException
;
93 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
94 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
95 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
96 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
106 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
107 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
108 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
121 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
122 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
123 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
124 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.ConflictException
;
125 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
126 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
127 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
128 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
129 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
130 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
131 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
132 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
133 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
134 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
135 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
136 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
137 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
138 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
140 import java
.io
.Closeable
;
142 import java
.io
.FileInputStream
;
143 import java
.io
.FileOutputStream
;
144 import java
.io
.IOException
;
145 import java
.io
.InputStream
;
146 import java
.io
.OutputStream
;
148 import java
.net
.URISyntaxException
;
149 import java
.net
.URLEncoder
;
150 import java
.nio
.charset
.StandardCharsets
;
151 import java
.nio
.file
.Files
;
152 import java
.security
.SignatureException
;
153 import java
.util
.ArrayList
;
154 import java
.util
.Arrays
;
155 import java
.util
.Base64
;
156 import java
.util
.Collection
;
157 import java
.util
.Date
;
158 import java
.util
.HashSet
;
159 import java
.util
.List
;
160 import java
.util
.Map
;
161 import java
.util
.Set
;
162 import java
.util
.UUID
;
163 import java
.util
.concurrent
.ExecutorService
;
164 import java
.util
.concurrent
.Executors
;
165 import java
.util
.concurrent
.TimeUnit
;
166 import java
.util
.concurrent
.TimeoutException
;
167 import java
.util
.concurrent
.locks
.ReentrantLock
;
168 import java
.util
.function
.Function
;
169 import java
.util
.stream
.Collectors
;
171 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
173 public class Manager
implements Closeable
{
175 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
177 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
178 private final SignalDependencies dependencies
;
180 private SignalAccount account
;
182 private final ExecutorService executor
= Executors
.newCachedThreadPool();
184 private final ProfileHelper profileHelper
;
185 private final GroupV2Helper groupV2Helper
;
186 private final PinHelper pinHelper
;
187 private final SendHelper sendHelper
;
189 private final AvatarStore avatarStore
;
190 private final AttachmentStore attachmentStore
;
191 private final StickerPackStore stickerPackStore
;
192 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
193 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
196 public Lock
acquire() {
198 return LEGACY_LOCK
::unlock
;
203 SignalAccount account
,
204 PathConfig pathConfig
,
205 ServiceEnvironmentConfig serviceEnvironmentConfig
,
208 this.account
= account
;
209 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
211 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
212 account
.getUsername(),
213 account
.getPassword(),
214 account
.getDeviceId());
215 this.dependencies
= new SignalDependencies(account
.getSelfAddress(),
216 serviceEnvironmentConfig
,
219 account
.getSignalProtocolStore(),
222 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
224 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
225 account
.getProfileStore()::getProfileKey
,
226 this::getRecipientProfile
,
227 this::getSenderCertificate
);
228 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
229 unidentifiedAccessHelper
::getAccessFor
,
230 dependencies
::getProfileService
,
231 dependencies
::getMessageReceiver
,
232 this::resolveSignalServiceAddress
);
233 this.groupV2Helper
= new GroupV2Helper(this::getRecipientProfileKeyCredential
,
234 this::getRecipientProfile
,
235 account
::getSelfRecipientId
,
236 dependencies
.getGroupsV2Operations(),
237 dependencies
.getGroupsV2Api(),
238 this::getGroupAuthForToday
,
239 this::resolveSignalServiceAddress
);
240 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
241 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
242 this.stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
243 this.sendHelper
= new SendHelper(account
,
245 unidentifiedAccessHelper
,
246 this::resolveSignalServiceAddress
,
247 this::resolveRecipient
,
248 this::handleIdentityFailure
,
250 this::refreshRegisteredUser
);
253 public String
getUsername() {
254 return account
.getUsername();
257 public SignalServiceAddress
getSelfAddress() {
258 return account
.getSelfAddress();
261 public RecipientId
getSelfRecipientId() {
262 return account
.getSelfRecipientId();
265 private IdentityKeyPair
getIdentityKeyPair() {
266 return account
.getIdentityKeyPair();
269 public int getDeviceId() {
270 return account
.getDeviceId();
273 public static Manager
init(
276 ServiceEnvironment serviceEnvironment
,
278 final TrustNewIdentity trustNewIdentity
279 ) throws IOException
, NotRegisteredException
{
280 var pathConfig
= PathConfig
.createDefault(settingsPath
);
282 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
283 throw new NotRegisteredException();
286 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true, trustNewIdentity
);
288 if (!account
.isRegistered()) {
289 throw new NotRegisteredException();
292 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
294 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
297 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
298 var pathConfig
= PathConfig
.createDefault(settingsPath
);
299 final var dataPath
= pathConfig
.getDataPath();
300 final var files
= dataPath
.listFiles();
306 return Arrays
.stream(files
)
307 .filter(File
::isFile
)
309 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
310 .collect(Collectors
.toList());
313 public void checkAccountState() throws IOException
{
314 if (account
.getLastReceiveTimestamp() == 0) {
315 logger
.warn("The Signal protocol expects that incoming messages are regularly received.");
317 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
318 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
321 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
325 if (dependencies
.getAccountManager().getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
328 if (account
.getUuid() == null) {
329 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
331 updateAccountAttributes();
335 * This is used for checking a set of phone numbers for registration on Signal
337 * @param numbers The set of phone number in question
338 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
339 * @throws IOException if its unable to get the contacts to check if they're registered
341 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
342 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
344 return canonicalizePhoneNumber(n
);
345 } catch (InvalidNumberException e
) {
350 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
351 var contactDetails
= getRegisteredUsers(canonicalizedNumbers
.values()
353 .filter(s
-> !s
.isEmpty())
354 .collect(Collectors
.toSet()));
356 // Store numbers as recipients so we have the number/uuid association
357 contactDetails
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
359 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
360 final var number
= canonicalizedNumbers
.get(n
);
361 final var uuid
= contactDetails
.get(number
);
362 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
366 public void updateAccountAttributes() throws IOException
{
367 dependencies
.getAccountManager()
368 .setAccountAttributes(account
.getEncryptedDeviceName(),
370 account
.getLocalRegistrationId(),
372 // set legacy pin only if no KBS master key is set
373 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
374 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
375 account
.getSelfUnidentifiedAccessKey(),
376 account
.isUnrestrictedUnidentifiedAccess(),
378 account
.isDiscoverableByPhoneNumber());
382 * @param givenName if null, the previous givenName will be kept
383 * @param familyName if null, the previous familyName will be kept
384 * @param about if null, the previous about text will be kept
385 * @param aboutEmoji if null, the previous about emoji will be kept
386 * @param avatar if avatar is null the image from the local avatar store is used (if present),
388 public void setProfile(
389 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
390 ) throws IOException
{
391 var profile
= getRecipientProfile(account
.getSelfRecipientId());
392 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
393 if (givenName
!= null) {
394 builder
.withGivenName(givenName
);
396 if (familyName
!= null) {
397 builder
.withFamilyName(familyName
);
400 builder
.withAbout(about
);
402 if (aboutEmoji
!= null) {
403 builder
.withAboutEmoji(aboutEmoji
);
405 var newProfile
= builder
.build();
407 try (final var streamDetails
= avatar
== null
408 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
409 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
410 dependencies
.getAccountManager()
411 .setVersionedProfile(account
.getUuid(),
412 account
.getProfileKey(),
413 newProfile
.getInternalServiceName(),
414 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
415 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
420 if (avatar
!= null) {
421 if (avatar
.isPresent()) {
422 avatarStore
.storeProfileAvatar(getSelfAddress(),
423 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
425 avatarStore
.deleteProfileAvatar(getSelfAddress());
428 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
430 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
433 public void unregister() throws IOException
{
434 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
435 // If this is the master device, other users can't send messages to this number anymore.
436 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
437 dependencies
.getAccountManager().setGcmId(Optional
.absent());
439 account
.setRegistered(false);
442 public void deleteAccount() throws IOException
{
443 dependencies
.getAccountManager().deleteAccount();
445 account
.setRegistered(false);
448 public List
<Device
> getLinkedDevices() throws IOException
{
449 var devices
= dependencies
.getAccountManager().getDevices();
450 account
.setMultiDevice(devices
.size() > 1);
451 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
452 return devices
.stream().map(d
-> {
453 String deviceName
= d
.getName();
454 if (deviceName
!= null) {
456 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
457 } catch (IOException e
) {
458 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
461 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
462 }).collect(Collectors
.toList());
465 public void removeLinkedDevices(int deviceId
) throws IOException
{
466 dependencies
.getAccountManager().removeDevice(deviceId
);
467 var devices
= dependencies
.getAccountManager().getDevices();
468 account
.setMultiDevice(devices
.size() > 1);
471 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
472 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
474 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
477 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
478 var identityKeyPair
= getIdentityKeyPair();
479 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
481 dependencies
.getAccountManager()
482 .addDevice(deviceIdentifier
,
485 Optional
.of(account
.getProfileKey().serialize()),
487 account
.setMultiDevice(true);
490 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
491 if (!account
.isMasterDevice()) {
492 throw new RuntimeException("Only master device can set a PIN");
494 if (pin
.isPresent()) {
495 final var masterKey
= account
.getPinMasterKey() != null
496 ? account
.getPinMasterKey()
497 : KeyUtils
.createMasterKey();
499 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
501 account
.setRegistrationLockPin(pin
.get(), masterKey
);
504 pinHelper
.removeRegistrationLockPin();
506 account
.setRegistrationLockPin(null, null);
510 void refreshPreKeys() throws IOException
{
511 var oneTimePreKeys
= generatePreKeys();
512 final var identityKeyPair
= getIdentityKeyPair();
513 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
515 dependencies
.getAccountManager().setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
518 private List
<PreKeyRecord
> generatePreKeys() {
519 final var offset
= account
.getPreKeyIdOffset();
521 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
522 account
.addPreKeys(records
);
527 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
528 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
530 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
531 account
.addSignedPreKey(record);
536 public Profile
getRecipientProfile(
537 RecipientId recipientId
539 return getRecipientProfile(recipientId
, false);
542 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
544 Profile
getRecipientProfile(
545 RecipientId recipientId
, boolean force
547 var profile
= account
.getProfileStore().getProfile(recipientId
);
549 var now
= System
.currentTimeMillis();
550 // Profiles are cached for 24h before retrieving them again, unless forced
551 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
555 synchronized (pendingProfileRequest
) {
556 if (pendingProfileRequest
.contains(recipientId
)) {
559 pendingProfileRequest
.add(recipientId
);
561 final SignalServiceProfile encryptedProfile
;
563 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
565 synchronized (pendingProfileRequest
) {
566 pendingProfileRequest
.remove(recipientId
);
569 if (encryptedProfile
== null) {
573 profile
= decryptProfileIfKeyKnown(recipientId
, encryptedProfile
);
574 account
.getProfileStore().storeProfile(recipientId
, profile
);
579 private Profile
decryptProfileIfKeyKnown(
580 final RecipientId recipientId
, final SignalServiceProfile encryptedProfile
582 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
583 if (profileKey
== null) {
584 return new Profile(System
.currentTimeMillis(),
589 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
590 ProfileUtils
.getCapabilities(encryptedProfile
));
593 return decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
596 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
598 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
599 } catch (IOException e
) {
600 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
605 private ProfileAndCredential
retrieveProfileAndCredential(
606 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
607 ) throws IOException
{
608 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
609 final var profile
= profileAndCredential
.getProfile();
612 var newIdentity
= account
.getIdentityKeyStore()
613 .saveIdentity(recipientId
,
614 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
618 account
.getSessionStore().archiveSessions(recipientId
);
620 } catch (InvalidKeyException ignored
) {
621 logger
.warn("Got invalid identity key in profile for {}",
622 resolveSignalServiceAddress(recipientId
).getIdentifier());
624 return profileAndCredential
;
627 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
628 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
629 if (profileKeyCredential
!= null) {
630 return profileKeyCredential
;
633 ProfileAndCredential profileAndCredential
;
635 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
636 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
637 } catch (IOException e
) {
638 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
642 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
643 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
645 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
646 if (profileKey
!= null) {
647 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
649 profileAndCredential
.getProfile());
650 account
.getProfileStore().storeProfile(recipientId
, profile
);
653 return profileKeyCredential
;
656 private Profile
decryptProfileAndDownloadAvatar(
657 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
659 if (encryptedProfile
.getAvatar() != null) {
660 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
663 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
666 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
667 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
668 if (streamDetails
== null) {
669 return Optional
.absent();
672 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
675 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
676 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
677 if (streamDetails
== null) {
678 return Optional
.absent();
681 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
684 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
685 var g
= getGroup(groupId
);
687 throw new GroupNotFoundException(groupId
);
689 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
690 throw new NotAGroupMemberException(groupId
, g
.getTitle());
695 public List
<GroupInfo
> getGroups() {
696 return account
.getGroupStore().getGroups();
699 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
700 String messageText
, List
<String
> attachments
, GroupId groupId
701 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
702 final var messageBuilder
= createMessageBuilder().withBody(messageText
);
703 if (attachments
!= null) {
704 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
707 return sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
710 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
711 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
712 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
713 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
714 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
716 resolveSignalServiceAddress(targetAuthorRecipientId
),
717 targetSentTimestamp
);
718 final var messageBuilder
= createMessageBuilder().withReaction(reaction
);
720 return sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
723 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(
724 GroupId groupId
, Set
<String
> groupAdmins
725 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, InvalidNumberException
, LastGroupAdminException
{
726 var group
= getGroupForUpdating(groupId
);
727 if (group
instanceof GroupInfoV1
) {
728 return quitGroupV1((GroupInfoV1
) group
);
731 final var newAdmins
= getRecipientIds(groupAdmins
);
733 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
734 } catch (ConflictException e
) {
735 // Detected conflicting update, refreshing group and trying again
736 group
= getGroup(groupId
, true);
737 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
741 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV1(final GroupInfoV1 groupInfoV1
) throws IOException
{
742 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
743 .withId(groupInfoV1
.getGroupId().serialize())
746 var messageBuilder
= createMessageBuilder().asGroupMessage(group
);
747 groupInfoV1
.removeMember(account
.getSelfRecipientId());
748 account
.getGroupStore().updateGroup(groupInfoV1
);
749 return sendHelper
.sendGroupMessage(messageBuilder
.build(),
750 groupInfoV1
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
753 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV2(
754 final GroupInfoV2 groupInfoV2
, final Set
<RecipientId
> newAdmins
755 ) throws LastGroupAdminException
, IOException
{
756 final var currentAdmins
= groupInfoV2
.getAdminMembers();
757 newAdmins
.removeAll(currentAdmins
);
758 newAdmins
.retainAll(groupInfoV2
.getMembers());
759 if (currentAdmins
.contains(getSelfRecipientId())
760 && currentAdmins
.size() == 1
761 && groupInfoV2
.getMembers().size() > 1
762 && newAdmins
.size() == 0) {
763 // Last admin can't leave the group, unless she's also the last member
764 throw new LastGroupAdminException(groupInfoV2
.getGroupId(), groupInfoV2
.getTitle());
766 final var groupGroupChangePair
= groupV2Helper
.leaveGroup(groupInfoV2
, newAdmins
);
767 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
768 var messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
769 account
.getGroupStore().updateGroup(groupInfoV2
);
770 return sendHelper
.sendGroupMessage(messageBuilder
.build(),
771 groupInfoV2
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
774 public void deleteGroup(GroupId groupId
) throws IOException
{
775 account
.getGroupStore().deleteGroup(groupId
);
776 avatarStore
.deleteGroupAvatar(groupId
);
779 public Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
780 String name
, List
<String
> members
, File avatarFile
781 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
782 return createGroup(name
, members
== null ?
null : getRecipientIds(members
), avatarFile
);
785 private Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
786 String name
, Set
<RecipientId
> members
, File avatarFile
787 ) throws IOException
, AttachmentInvalidException
{
788 final var selfRecipientId
= account
.getSelfRecipientId();
789 if (members
!= null && members
.contains(selfRecipientId
)) {
790 members
= new HashSet
<>(members
);
791 members
.remove(selfRecipientId
);
794 var gv2Pair
= groupV2Helper
.createGroup(name
== null ?
"" : name
,
795 members
== null ? Set
.of() : members
,
798 SignalServiceDataMessage
.Builder messageBuilder
;
799 if (gv2Pair
== null) {
800 // Failed to create v2 group, creating v1 group instead
801 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
802 gv1
.addMembers(List
.of(selfRecipientId
));
803 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
804 return new Pair
<>(gv1
.getGroupId(), result
.second());
807 final var gv2
= gv2Pair
.first();
808 final var decryptedGroup
= gv2Pair
.second();
810 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
811 if (avatarFile
!= null) {
812 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
813 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
815 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
816 account
.getGroupStore().updateGroup(gv2
);
818 final var result
= sendHelper
.sendGroupMessage(messageBuilder
.build(),
819 gv2
.getMembersIncludingPendingWithout(selfRecipientId
));
820 return new Pair
<>(gv2
.getGroupId(), result
.second());
823 public Pair
<Long
, List
<SendMessageResult
>> updateGroup(
827 List
<String
> members
,
828 List
<String
> removeMembers
,
830 List
<String
> removeAdmins
,
831 boolean resetGroupLink
,
832 GroupLinkState groupLinkState
,
833 GroupPermission addMemberPermission
,
834 GroupPermission editDetailsPermission
,
836 Integer expirationTimer
,
837 Boolean isAnnouncementGroup
838 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
839 return updateGroup(groupId
,
842 members
== null ?
null : getRecipientIds(members
),
843 removeMembers
== null ?
null : getRecipientIds(removeMembers
),
844 admins
== null ?
null : getRecipientIds(admins
),
845 removeAdmins
== null ?
null : getRecipientIds(removeAdmins
),
849 editDetailsPermission
,
852 isAnnouncementGroup
);
855 private Pair
<Long
, List
<SendMessageResult
>> updateGroup(
856 final GroupId groupId
,
858 final String description
,
859 final Set
<RecipientId
> members
,
860 final Set
<RecipientId
> removeMembers
,
861 final Set
<RecipientId
> admins
,
862 final Set
<RecipientId
> removeAdmins
,
863 final boolean resetGroupLink
,
864 final GroupLinkState groupLinkState
,
865 final GroupPermission addMemberPermission
,
866 final GroupPermission editDetailsPermission
,
867 final File avatarFile
,
868 final Integer expirationTimer
,
869 final Boolean isAnnouncementGroup
870 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
871 var group
= getGroupForUpdating(groupId
);
873 if (group
instanceof GroupInfoV2
) {
875 return updateGroupV2((GroupInfoV2
) group
,
885 editDetailsPermission
,
888 isAnnouncementGroup
);
889 } catch (ConflictException e
) {
890 // Detected conflicting update, refreshing group and trying again
891 group
= getGroup(groupId
, true);
892 return updateGroupV2((GroupInfoV2
) group
,
902 editDetailsPermission
,
905 isAnnouncementGroup
);
909 final var gv1
= (GroupInfoV1
) group
;
910 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
911 if (expirationTimer
!= null) {
912 setExpirationTimer(gv1
, expirationTimer
);
917 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV1(
918 final GroupInfoV1 gv1
, final String name
, final Set
<RecipientId
> members
, final File avatarFile
919 ) throws IOException
, AttachmentInvalidException
{
920 updateGroupV1Details(gv1
, name
, members
, avatarFile
);
921 var messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
923 account
.getGroupStore().updateGroup(gv1
);
925 return sendHelper
.sendGroupMessage(messageBuilder
.build(),
926 gv1
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
929 private void updateGroupV1Details(
930 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
931 ) throws IOException
{
936 if (members
!= null) {
937 final var newMemberAddresses
= members
.stream()
938 .filter(member
-> !g
.isMember(member
))
939 .map(this::resolveSignalServiceAddress
)
940 .collect(Collectors
.toList());
941 final var newE164Members
= new HashSet
<String
>();
942 for (var member
: newMemberAddresses
) {
943 if (!member
.getNumber().isPresent()) {
946 newE164Members
.add(member
.getNumber().get());
949 final var registeredUsers
= getRegisteredUsers(newE164Members
);
950 if (registeredUsers
.size() != newE164Members
.size()) {
951 // Some of the new members are not registered on Signal
952 newE164Members
.removeAll(registeredUsers
.keySet());
953 throw new IOException("Failed to add members "
954 + String
.join(", ", newE164Members
)
955 + " to group: Not registered on Signal");
958 g
.addMembers(members
);
961 if (avatarFile
!= null) {
962 avatarStore
.storeGroupAvatar(g
.getGroupId(),
963 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
967 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV2(
968 final GroupInfoV2 group
,
970 final String description
,
971 final Set
<RecipientId
> members
,
972 final Set
<RecipientId
> removeMembers
,
973 final Set
<RecipientId
> admins
,
974 final Set
<RecipientId
> removeAdmins
,
975 final boolean resetGroupLink
,
976 final GroupLinkState groupLinkState
,
977 final GroupPermission addMemberPermission
,
978 final GroupPermission editDetailsPermission
,
979 final File avatarFile
,
980 final Integer expirationTimer
,
981 final Boolean isAnnouncementGroup
982 ) throws IOException
{
983 Pair
<Long
, List
<SendMessageResult
>> result
= null;
984 if (group
.isPendingMember(account
.getSelfRecipientId())) {
985 var groupGroupChangePair
= groupV2Helper
.acceptInvite(group
);
986 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
989 if (members
!= null) {
990 final var newMembers
= new HashSet
<>(members
);
991 newMembers
.removeAll(group
.getMembers());
992 if (newMembers
.size() > 0) {
993 var groupGroupChangePair
= groupV2Helper
.addMembers(group
, newMembers
);
994 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
998 if (removeMembers
!= null) {
999 var existingRemoveMembers
= new HashSet
<>(removeMembers
);
1000 existingRemoveMembers
.retainAll(group
.getMembers());
1001 existingRemoveMembers
.remove(getSelfRecipientId());// self can be removed with sendQuitGroupMessage
1002 if (existingRemoveMembers
.size() > 0) {
1003 var groupGroupChangePair
= groupV2Helper
.removeMembers(group
, existingRemoveMembers
);
1004 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1007 var pendingRemoveMembers
= new HashSet
<>(removeMembers
);
1008 pendingRemoveMembers
.retainAll(group
.getPendingMembers());
1009 if (pendingRemoveMembers
.size() > 0) {
1010 var groupGroupChangePair
= groupV2Helper
.revokeInvitedMembers(group
, pendingRemoveMembers
);
1011 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1015 if (admins
!= null) {
1016 final var newAdmins
= new HashSet
<>(admins
);
1017 newAdmins
.retainAll(group
.getMembers());
1018 newAdmins
.removeAll(group
.getAdminMembers());
1019 if (newAdmins
.size() > 0) {
1020 for (var admin
: newAdmins
) {
1021 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, true);
1022 result
= sendUpdateGroupV2Message(group
,
1023 groupGroupChangePair
.first(),
1024 groupGroupChangePair
.second());
1029 if (removeAdmins
!= null) {
1030 final var existingRemoveAdmins
= new HashSet
<>(removeAdmins
);
1031 existingRemoveAdmins
.retainAll(group
.getAdminMembers());
1032 if (existingRemoveAdmins
.size() > 0) {
1033 for (var admin
: existingRemoveAdmins
) {
1034 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, false);
1035 result
= sendUpdateGroupV2Message(group
,
1036 groupGroupChangePair
.first(),
1037 groupGroupChangePair
.second());
1042 if (resetGroupLink
) {
1043 var groupGroupChangePair
= groupV2Helper
.resetGroupLinkPassword(group
);
1044 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1047 if (groupLinkState
!= null) {
1048 var groupGroupChangePair
= groupV2Helper
.setGroupLinkState(group
, groupLinkState
);
1049 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1052 if (addMemberPermission
!= null) {
1053 var groupGroupChangePair
= groupV2Helper
.setAddMemberPermission(group
, addMemberPermission
);
1054 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1057 if (editDetailsPermission
!= null) {
1058 var groupGroupChangePair
= groupV2Helper
.setEditDetailsPermission(group
, editDetailsPermission
);
1059 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1062 if (expirationTimer
!= null) {
1063 var groupGroupChangePair
= groupV2Helper
.setMessageExpirationTimer(group
, expirationTimer
);
1064 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1067 if (isAnnouncementGroup
!= null) {
1068 var groupGroupChangePair
= groupV2Helper
.setIsAnnouncementGroup(group
, isAnnouncementGroup
);
1069 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1072 if (name
!= null || description
!= null || avatarFile
!= null) {
1073 var groupGroupChangePair
= groupV2Helper
.updateGroup(group
, name
, description
, avatarFile
);
1074 if (avatarFile
!= null) {
1075 avatarStore
.storeGroupAvatar(group
.getGroupId(),
1076 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
1078 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1084 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
1085 GroupInviteLinkUrl inviteLinkUrl
1086 ) throws IOException
, GroupLinkNotActiveException
{
1087 final var groupJoinInfo
= groupV2Helper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
1088 inviteLinkUrl
.getPassword());
1089 final var groupChange
= groupV2Helper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
1090 inviteLinkUrl
.getPassword(),
1092 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
1093 groupJoinInfo
.getRevision() + 1,
1094 groupChange
.toByteArray());
1096 if (group
.getGroup() == null) {
1097 // Only requested member, can't send update to group members
1098 return new Pair
<>(group
.getGroupId(), List
.of());
1101 final var result
= sendUpdateGroupV2Message(group
, group
.getGroup(), groupChange
);
1103 return new Pair
<>(group
.getGroupId(), result
.second());
1106 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupV2Message(
1107 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
1108 ) throws IOException
{
1109 final var selfRecipientId
= account
.getSelfRecipientId();
1110 final var members
= group
.getMembersIncludingPendingWithout(selfRecipientId
);
1111 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
1112 members
.addAll(group
.getMembersIncludingPendingWithout(selfRecipientId
));
1114 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
1115 account
.getGroupStore().updateGroup(group
);
1116 return sendHelper
.sendGroupMessage(messageBuilder
.build(), members
);
1119 private static int currentTimeDays() {
1120 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
1123 private GroupsV2AuthorizationString
getGroupAuthForToday(
1124 final GroupSecretParams groupSecretParams
1125 ) throws IOException
{
1126 final var today
= currentTimeDays();
1127 // Returns credentials for the next 7 days
1128 final var credentials
= dependencies
.getGroupsV2Api().getCredentials(today
);
1129 // TODO cache credentials until they expire
1130 var authCredentialResponse
= credentials
.get(today
);
1132 return dependencies
.getGroupsV2Api()
1133 .getGroupsV2AuthorizationString(account
.getUuid(),
1136 authCredentialResponse
);
1137 } catch (VerificationFailedException e
) {
1138 throw new IOException(e
);
1142 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
1143 GroupIdV1 groupId
, SignalServiceAddress recipient
1144 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
1146 var group
= getGroupForUpdating(groupId
);
1147 if (!(group
instanceof GroupInfoV1
)) {
1148 throw new IOException("Received an invalid group request for a v2 group!");
1150 g
= (GroupInfoV1
) group
;
1152 final var recipientId
= resolveRecipient(recipient
);
1153 if (!g
.isMember(recipientId
)) {
1154 throw new NotAGroupMemberException(groupId
, g
.name
);
1157 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
1159 // Send group message only to the recipient who requested it
1160 return sendHelper
.sendGroupMessage(messageBuilder
.build(), Set
.of(recipientId
));
1163 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
1164 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
1165 .withId(g
.getGroupId().serialize())
1167 .withMembers(g
.getMembers()
1169 .map(this::resolveSignalServiceAddress
)
1170 .collect(Collectors
.toList()));
1173 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
1174 if (attachment
.isPresent()) {
1175 group
.withAvatar(attachment
.get());
1177 } catch (IOException e
) {
1178 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
1181 return createMessageBuilder().asGroupMessage(group
.build()).withExpiration(g
.getMessageExpirationTime());
1184 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
1185 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
1186 .withRevision(g
.getGroup().getRevision())
1187 .withSignedGroupChange(signedGroupChange
);
1188 return createMessageBuilder().asGroupMessage(group
.build()).withExpiration(g
.getMessageExpirationTime());
1191 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
1192 GroupIdV1 groupId
, SignalServiceAddress recipient
1193 ) throws IOException
{
1194 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
1196 var messageBuilder
= createMessageBuilder().asGroupMessage(group
.build());
1198 // Send group info request message to the recipient who sent us a message with this groupId
1199 return sendHelper
.sendGroupMessage(messageBuilder
.build(), Set
.of(resolveRecipient(recipient
)));
1202 public void sendReadReceipt(
1203 String sender
, List
<Long
> messageIds
1204 ) throws IOException
, UntrustedIdentityException
, InvalidNumberException
{
1205 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
1207 System
.currentTimeMillis());
1209 sendHelper
.sendReceiptMessage(receiptMessage
, canonicalizeAndResolveRecipient(sender
));
1212 public void sendViewedReceipt(
1213 String sender
, List
<Long
> messageIds
1214 ) throws IOException
, UntrustedIdentityException
, InvalidNumberException
{
1215 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
1217 System
.currentTimeMillis());
1219 sendHelper
.sendReceiptMessage(receiptMessage
, canonicalizeAndResolveRecipient(sender
));
1222 void sendDeliveryReceipt(
1223 SignalServiceAddress remoteAddress
, List
<Long
> messageIds
1224 ) throws IOException
, UntrustedIdentityException
{
1225 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1227 System
.currentTimeMillis());
1229 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(remoteAddress
));
1232 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1233 String messageText
, List
<String
> attachments
, List
<String
> recipients
1234 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1235 final var messageBuilder
= createMessageBuilder().withBody(messageText
);
1236 if (attachments
!= null) {
1237 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1239 // Upload attachments here, so we only upload once even for multiple recipients
1240 var messageSender
= dependencies
.getMessageSender();
1241 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1242 for (var attachment
: attachmentStreams
) {
1243 if (attachment
.isStream()) {
1244 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1245 } else if (attachment
.isPointer()) {
1246 attachmentPointers
.add(attachment
.asPointer());
1250 messageBuilder
.withAttachments(attachmentPointers
);
1252 return sendHelper
.sendMessage(messageBuilder
, getRecipientIds(recipients
));
1255 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1256 String messageText
, List
<String
> attachments
1257 ) throws IOException
, AttachmentInvalidException
{
1258 final var messageBuilder
= createMessageBuilder().withBody(messageText
);
1259 if (attachments
!= null) {
1260 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1262 return sendHelper
.sendSelfMessage(messageBuilder
);
1265 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1266 long targetSentTimestamp
, List
<String
> recipients
1267 ) throws IOException
, InvalidNumberException
{
1268 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1269 final var messageBuilder
= createMessageBuilder().withRemoteDelete(delete
);
1270 return sendHelper
.sendMessage(messageBuilder
, getRecipientIds(recipients
));
1273 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1274 long targetSentTimestamp
, GroupId groupId
1275 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1276 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1277 final var messageBuilder
= createMessageBuilder().withRemoteDelete(delete
);
1278 return sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
1281 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1282 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1283 ) throws IOException
, InvalidNumberException
{
1284 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1285 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1287 resolveSignalServiceAddress(targetAuthorRecipientId
),
1288 targetSentTimestamp
);
1289 final var messageBuilder
= createMessageBuilder().withReaction(reaction
);
1290 return sendHelper
.sendMessage(messageBuilder
, getRecipientIds(recipients
));
1293 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1294 var messageBuilder
= createMessageBuilder().asEndSessionMessage();
1296 final var recipientIds
= getRecipientIds(recipients
);
1298 return sendHelper
.sendMessage(messageBuilder
, recipientIds
);
1300 for (var recipientId
: recipientIds
) {
1301 handleEndSession(recipientId
);
1306 void renewSession(RecipientId recipientId
) throws IOException
{
1307 account
.getSessionStore().archiveSessions(recipientId
);
1308 if (!recipientId
.equals(getSelfRecipientId())) {
1309 sendHelper
.sendNullMessage(recipientId
);
1313 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1314 if (!account
.isMasterDevice()) {
1315 throw new NotMasterDeviceException();
1317 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1318 var contact
= account
.getContactStore().getContact(recipientId
);
1319 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1320 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1323 public void setContactBlocked(
1324 String number
, boolean blocked
1325 ) throws InvalidNumberException
, NotMasterDeviceException
{
1326 if (!account
.isMasterDevice()) {
1327 throw new NotMasterDeviceException();
1329 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1332 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1333 var contact
= account
.getContactStore().getContact(recipientId
);
1334 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1335 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1338 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1339 var group
= getGroup(groupId
);
1340 if (group
== null) {
1341 throw new GroupNotFoundException(groupId
);
1344 group
.setBlocked(blocked
);
1345 account
.getGroupStore().updateGroup(group
);
1348 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1349 var contact
= account
.getContactStore().getContact(recipientId
);
1350 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1353 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1354 account
.getContactStore()
1355 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1358 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1359 final var messageBuilder
= createMessageBuilder().asExpirationUpdate();
1360 sendHelper
.sendMessage(messageBuilder
, Set
.of(recipientId
));
1364 * Change the expiration timer for a contact
1366 public void setExpirationTimer(
1367 String number
, int messageExpirationTimer
1368 ) throws IOException
, InvalidNumberException
{
1369 var recipientId
= canonicalizeAndResolveRecipient(number
);
1370 setExpirationTimer(recipientId
, messageExpirationTimer
);
1371 sendExpirationTimerUpdate(recipientId
);
1375 * Change the expiration timer for a group
1377 private void setExpirationTimer(
1378 GroupInfoV1 groupInfoV1
, int messageExpirationTimer
1379 ) throws NotAGroupMemberException
, GroupNotFoundException
, IOException
{
1380 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1381 account
.getGroupStore().updateGroup(groupInfoV1
);
1382 sendExpirationTimerUpdate(groupInfoV1
.getGroupId());
1385 private void sendExpirationTimerUpdate(GroupIdV1 groupId
) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1386 final var messageBuilder
= createMessageBuilder().asExpirationUpdate();
1387 sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
1391 * Upload the sticker pack from path.
1393 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1394 * @return if successful, returns the URL to install the sticker pack in the signal app
1396 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1397 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1399 var messageSender
= dependencies
.getMessageSender();
1401 var packKey
= KeyUtils
.createStickerUploadKey();
1402 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1403 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
1405 var sticker
= new Sticker(packId
, packKey
);
1406 account
.getStickerStore().updateSticker(sticker
);
1409 return new URI("https",
1413 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
1415 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
)).toString();
1416 } catch (URISyntaxException e
) {
1417 throw new AssertionError(e
);
1421 public void requestAllSyncData() throws IOException
{
1422 requestSyncGroups();
1423 requestSyncContacts();
1424 requestSyncBlocked();
1425 requestSyncConfiguration();
1429 private void requestSyncGroups() throws IOException
{
1430 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1431 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1433 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1434 sendHelper
.sendSyncMessage(message
);
1437 private void requestSyncContacts() throws IOException
{
1438 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1439 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1441 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1442 sendHelper
.sendSyncMessage(message
);
1445 private void requestSyncBlocked() throws IOException
{
1446 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1447 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1449 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1450 sendHelper
.sendSyncMessage(message
);
1453 private void requestSyncConfiguration() throws IOException
{
1454 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1455 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1457 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1458 sendHelper
.sendSyncMessage(message
);
1461 private void requestSyncKeys() throws IOException
{
1462 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1463 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1465 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1466 sendHelper
.sendSyncMessage(message
);
1469 private byte[] getSenderCertificate() {
1472 if (account
.isPhoneNumberShared()) {
1473 certificate
= dependencies
.getAccountManager().getSenderCertificate();
1475 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
1477 } catch (IOException e
) {
1478 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1481 // TODO cache for a day
1485 private Set
<RecipientId
> getRecipientIds(Collection
<String
> numbers
) throws InvalidNumberException
{
1486 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1487 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1489 for (var number
: numbers
) {
1490 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1491 if (resolvedAddress
.getUuid().isPresent()) {
1492 signalServiceAddresses
.add(resolvedAddress
);
1494 addressesMissingUuid
.add(resolvedAddress
);
1498 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1499 .map(a
-> a
.getNumber().get())
1500 .collect(Collectors
.toSet());
1501 Map
<String
, UUID
> registeredUsers
;
1503 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1504 } catch (IOException e
) {
1505 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1506 registeredUsers
= Map
.of();
1509 for (var address
: addressesMissingUuid
) {
1510 final var number
= address
.getNumber().get();
1511 if (registeredUsers
.containsKey(number
)) {
1512 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1513 registeredUsers
.get(number
),
1515 signalServiceAddresses
.add(newAddress
);
1517 signalServiceAddresses
.add(address
);
1521 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1524 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1525 final var address
= resolveSignalServiceAddress(recipientId
);
1526 if (!address
.getNumber().isPresent()) {
1529 final var number
= address
.getNumber().get();
1530 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1531 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1534 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1536 return dependencies
.getAccountManager()
1537 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1539 serviceEnvironmentConfig
.getCdsMrenclave());
1540 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1541 throw new IOException(e
);
1545 public void sendTypingMessage(
1546 TypingAction action
, Set
<String
> recipients
1547 ) throws IOException
, UntrustedIdentityException
, InvalidNumberException
{
1548 final var timestamp
= System
.currentTimeMillis();
1549 var message
= new SignalServiceTypingMessage(action
.toSignalService(), timestamp
, Optional
.absent());
1550 sendHelper
.sendTypingMessage(message
, getRecipientIds(recipients
));
1553 public void sendGroupTypingMessage(
1554 TypingAction action
, GroupId groupId
1555 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1556 final var timestamp
= System
.currentTimeMillis();
1557 final var message
= new SignalServiceTypingMessage(action
.toSignalService(),
1559 Optional
.of(groupId
.serialize()));
1560 sendHelper
.sendGroupTypingMessage(message
, groupId
);
1563 private SignalServiceDataMessage
.Builder
createMessageBuilder() {
1564 final var timestamp
= System
.currentTimeMillis();
1566 var messageBuilder
= SignalServiceDataMessage
.newBuilder();
1567 messageBuilder
.withTimestamp(timestamp
);
1568 return messageBuilder
;
1571 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, ProtocolUntrustedIdentityException
, InvalidMessageStructureException
{
1572 return dependencies
.getCipher().decrypt(envelope
);
1575 private void handleEndSession(RecipientId recipientId
) {
1576 account
.getSessionStore().deleteAllSessions(recipientId
);
1579 private List
<HandleAction
> handleSignalServiceDataMessage(
1580 SignalServiceDataMessage message
,
1582 SignalServiceAddress source
,
1583 SignalServiceAddress destination
,
1584 boolean ignoreAttachments
1586 var actions
= new ArrayList
<HandleAction
>();
1587 if (message
.getGroupContext().isPresent()) {
1588 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1589 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1590 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1591 var group
= getGroup(groupId
);
1592 if (group
== null || group
instanceof GroupInfoV1
) {
1593 var groupV1
= (GroupInfoV1
) group
;
1594 switch (groupInfo
.getType()) {
1596 if (groupV1
== null) {
1597 groupV1
= new GroupInfoV1(groupId
);
1600 if (groupInfo
.getAvatar().isPresent()) {
1601 var avatar
= groupInfo
.getAvatar().get();
1602 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1605 if (groupInfo
.getName().isPresent()) {
1606 groupV1
.name
= groupInfo
.getName().get();
1609 if (groupInfo
.getMembers().isPresent()) {
1610 groupV1
.addMembers(groupInfo
.getMembers()
1613 .map(this::resolveRecipient
)
1614 .collect(Collectors
.toSet()));
1617 account
.getGroupStore().updateGroup(groupV1
);
1621 if (groupV1
== null && !isSync
) {
1622 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1626 if (groupV1
!= null) {
1627 groupV1
.removeMember(resolveRecipient(source
));
1628 account
.getGroupStore().updateGroup(groupV1
);
1633 if (groupV1
!= null && !isSync
) {
1634 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1639 // Received a group v1 message for a v2 group
1642 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1643 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1644 final var groupMasterKey
= groupContext
.getMasterKey();
1646 getOrMigrateGroup(groupMasterKey
,
1647 groupContext
.getRevision(),
1648 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1652 final var conversationPartnerAddress
= isSync ? destination
: source
;
1653 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1654 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1656 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1657 if (message
.getGroupContext().isPresent()) {
1658 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1659 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1660 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1661 if (group
!= null) {
1662 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1663 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1664 account
.getGroupStore().updateGroup(group
);
1667 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1668 // disappearing message timer already stored in the DecryptedGroup
1670 } else if (conversationPartnerAddress
!= null) {
1671 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1674 if (!ignoreAttachments
) {
1675 if (message
.getAttachments().isPresent()) {
1676 for (var attachment
: message
.getAttachments().get()) {
1677 downloadAttachment(attachment
);
1680 if (message
.getSharedContacts().isPresent()) {
1681 for (var contact
: message
.getSharedContacts().get()) {
1682 if (contact
.getAvatar().isPresent()) {
1683 downloadAttachment(contact
.getAvatar().get().getAttachment());
1688 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1689 final ProfileKey profileKey
;
1691 profileKey
= new ProfileKey(message
.getProfileKey().get());
1692 } catch (InvalidInputException e
) {
1693 throw new AssertionError(e
);
1695 if (source
.matches(account
.getSelfAddress())) {
1696 this.account
.setProfileKey(profileKey
);
1698 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1700 if (message
.getPreviews().isPresent()) {
1701 final var previews
= message
.getPreviews().get();
1702 for (var preview
: previews
) {
1703 if (preview
.getImage().isPresent()) {
1704 downloadAttachment(preview
.getImage().get());
1708 if (message
.getQuote().isPresent()) {
1709 final var quote
= message
.getQuote().get();
1711 for (var quotedAttachment
: quote
.getAttachments()) {
1712 final var thumbnail
= quotedAttachment
.getThumbnail();
1713 if (thumbnail
!= null) {
1714 downloadAttachment(thumbnail
);
1718 if (message
.getSticker().isPresent()) {
1719 final var messageSticker
= message
.getSticker().get();
1720 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1721 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1722 if (sticker
== null) {
1723 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1724 account
.getStickerStore().updateSticker(sticker
);
1726 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, messageSticker
.getPackKey()));
1731 private GroupInfoV2
getOrMigrateGroup(
1732 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1734 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1736 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1737 var groupInfo
= getGroup(groupId
);
1738 final GroupInfoV2 groupInfoV2
;
1739 if (groupInfo
instanceof GroupInfoV1
) {
1740 // Received a v2 group message for a v1 group, we need to locally migrate the group
1741 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1742 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1743 logger
.info("Locally migrated group {} to group v2, id: {}",
1744 groupInfo
.getGroupId().toBase64(),
1745 groupInfoV2
.getGroupId().toBase64());
1746 } else if (groupInfo
instanceof GroupInfoV2
) {
1747 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1749 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1752 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1753 DecryptedGroup group
= null;
1754 if (signedGroupChange
!= null
1755 && groupInfoV2
.getGroup() != null
1756 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1757 group
= groupV2Helper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(),
1761 if (group
== null) {
1762 group
= groupV2Helper
.getDecryptedGroup(groupSecretParams
);
1764 if (group
!= null) {
1765 storeProfileKeysFromMembers(group
);
1766 final var avatar
= group
.getAvatar();
1767 if (avatar
!= null && !avatar
.isEmpty()) {
1768 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1771 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1772 account
.getGroupStore().updateGroup(groupInfoV2
);
1778 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1779 for (var member
: group
.getMembersList()) {
1780 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
1781 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
1783 account
.getProfileStore()
1784 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
1785 } catch (InvalidInputException ignored
) {
1790 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1791 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1792 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1793 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1794 if (actions
!= null) {
1795 queuedActions
.addAll(actions
);
1798 handleQueuedActions(queuedActions
);
1801 private List
<HandleAction
> retryFailedReceivedMessage(
1802 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1804 var envelope
= cachedMessage
.loadEnvelope();
1805 if (envelope
== null) {
1808 SignalServiceContent content
= null;
1809 List
<HandleAction
> actions
= null;
1810 if (!envelope
.isReceipt()) {
1812 content
= decryptMessage(envelope
);
1813 } catch (ProtocolUntrustedIdentityException e
) {
1814 if (!envelope
.hasSource()) {
1815 final var identifier
= e
.getSender();
1816 final var recipientId
= resolveRecipient(identifier
);
1818 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1819 } catch (IOException ioException
) {
1820 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1824 } catch (Exception er
) {
1825 // All other errors are not recoverable, so delete the cached message
1826 cachedMessage
.delete();
1829 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1831 handler
.handleMessage(envelope
, content
, null);
1832 cachedMessage
.delete();
1836 public void receiveMessages(
1839 boolean returnOnTimeout
,
1840 boolean ignoreAttachments
,
1841 ReceiveMessageHandler handler
1842 ) throws IOException
{
1843 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1845 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1847 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1848 signalWebSocket
.connect();
1850 var hasCaughtUpWithOldMessages
= false;
1852 while (!Thread
.interrupted()) {
1853 SignalServiceEnvelope envelope
;
1854 SignalServiceContent content
= null;
1855 Exception exception
= null;
1856 final CachedMessage
[] cachedMessage
= {null};
1857 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
1858 logger
.debug("Checking for new message from server");
1860 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1861 final var recipientId
= envelope1
.hasSource()
1862 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1864 // store message on disk, before acknowledging receipt to the server
1865 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1867 logger
.debug("New message received from server");
1868 if (result
.isPresent()) {
1869 envelope
= result
.get();
1871 // Received indicator that server queue is empty
1872 hasCaughtUpWithOldMessages
= true;
1874 handleQueuedActions(queuedActions
);
1875 queuedActions
.clear();
1877 // Continue to wait another timeout for new messages
1880 } catch (AssertionError e
) {
1881 if (e
.getCause() instanceof InterruptedException
) {
1882 Thread
.currentThread().interrupt();
1887 } catch (WebSocketUnavailableException e
) {
1888 logger
.debug("Pipe unexpectedly unavailable, connecting");
1889 signalWebSocket
.connect();
1891 } catch (TimeoutException e
) {
1892 if (returnOnTimeout
) return;
1896 if (envelope
.hasSource()) {
1897 // Store uuid if we don't have it already
1898 // address/uuid in envelope is sent by server
1899 resolveRecipientTrusted(envelope
.getSourceAddress());
1901 if (!envelope
.isReceipt()) {
1903 content
= decryptMessage(envelope
);
1904 } catch (Exception e
) {
1907 if (!envelope
.hasSource() && content
!= null) {
1908 // Store uuid if we don't have it already
1909 // address/uuid is validated by unidentified sender certificate
1910 resolveRecipientTrusted(content
.getSender());
1912 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1913 if (exception
instanceof ProtocolInvalidMessageException
) {
1914 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
1915 logger
.debug("Received invalid message, queuing renew session action.");
1916 actions
.add(new RenewSessionAction(sender
));
1918 if (hasCaughtUpWithOldMessages
) {
1919 for (var action
: actions
) {
1921 action
.execute(this);
1922 } catch (Throwable e
) {
1923 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1924 Thread
.currentThread().interrupt();
1926 logger
.warn("Message action failed.", e
);
1930 queuedActions
.addAll(actions
);
1933 final var notAllowedToSendToGroup
= isNotAllowedToSendToGroup(envelope
, content
);
1934 if (isMessageBlocked(envelope
, content
)) {
1935 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1936 } else if (notAllowedToSendToGroup
) {
1937 logger
.info("Ignoring a group message from an unauthorized sender (no member or admin): {} {}",
1938 (envelope
.hasSource() ? envelope
.getSourceAddress() : content
.getSender()).getIdentifier(),
1939 envelope
.getTimestamp());
1941 handler
.handleMessage(envelope
, content
, exception
);
1943 if (cachedMessage
[0] != null) {
1944 if (exception
instanceof ProtocolUntrustedIdentityException
) {
1945 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
1946 final var recipientId
= resolveRecipient(identifier
);
1947 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1948 if (!envelope
.hasSource()) {
1950 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1951 } catch (IOException ioException
) {
1952 logger
.warn("Failed to move cached message to recipient folder: {}",
1953 ioException
.getMessage());
1957 cachedMessage
[0].delete();
1961 handleQueuedActions(queuedActions
);
1964 private void handleQueuedActions(final Set
<HandleAction
> queuedActions
) {
1965 for (var action
: queuedActions
) {
1967 action
.execute(this);
1968 } catch (Throwable e
) {
1969 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1970 Thread
.currentThread().interrupt();
1972 logger
.warn("Message action failed.", e
);
1977 private boolean isMessageBlocked(
1978 SignalServiceEnvelope envelope
, SignalServiceContent content
1980 SignalServiceAddress source
;
1981 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1982 source
= envelope
.getSourceAddress();
1983 } else if (content
!= null) {
1984 source
= content
.getSender();
1988 final var recipientId
= resolveRecipient(source
);
1989 if (isContactBlocked(recipientId
)) {
1993 if (content
!= null && content
.getDataMessage().isPresent()) {
1994 var message
= content
.getDataMessage().get();
1995 if (message
.getGroupContext().isPresent()) {
1996 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1997 var group
= getGroup(groupId
);
1998 if (group
!= null && group
.isBlocked()) {
2006 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
2007 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
2008 return isContactBlocked(recipientId
);
2011 private boolean isContactBlocked(final RecipientId recipientId
) {
2012 var sourceContact
= account
.getContactStore().getContact(recipientId
);
2013 return sourceContact
!= null && sourceContact
.isBlocked();
2016 private boolean isNotAllowedToSendToGroup(
2017 SignalServiceEnvelope envelope
, SignalServiceContent content
2019 SignalServiceAddress source
;
2020 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2021 source
= envelope
.getSourceAddress();
2022 } else if (content
!= null) {
2023 source
= content
.getSender();
2028 if (content
== null || !content
.getDataMessage().isPresent()) {
2032 var message
= content
.getDataMessage().get();
2033 if (!message
.getGroupContext().isPresent()) {
2037 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
2038 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
2039 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
2044 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2045 var group
= getGroup(groupId
);
2046 if (group
== null) {
2050 final var recipientId
= resolveRecipient(source
);
2051 return !group
.isMember(recipientId
) || (
2052 group
.isAnnouncementGroup() && !group
.isAdmin(recipientId
)
2056 private List
<HandleAction
> handleMessage(
2057 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
2059 var actions
= new ArrayList
<HandleAction
>();
2060 if (content
!= null) {
2061 final SignalServiceAddress sender
;
2062 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2063 sender
= envelope
.getSourceAddress();
2065 sender
= content
.getSender();
2068 if (content
.getDataMessage().isPresent()) {
2069 var message
= content
.getDataMessage().get();
2071 if (content
.isNeedsReceipt()) {
2072 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
2075 actions
.addAll(handleSignalServiceDataMessage(message
,
2078 account
.getSelfAddress(),
2079 ignoreAttachments
));
2081 if (content
.getSyncMessage().isPresent()) {
2082 account
.setMultiDevice(true);
2083 var syncMessage
= content
.getSyncMessage().get();
2084 if (syncMessage
.getSent().isPresent()) {
2085 var message
= syncMessage
.getSent().get();
2086 final var destination
= message
.getDestination().orNull();
2087 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
2091 ignoreAttachments
));
2093 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
2094 var rm
= syncMessage
.getRequest().get();
2095 if (rm
.isContactsRequest()) {
2096 actions
.add(SendSyncContactsAction
.create());
2098 if (rm
.isGroupsRequest()) {
2099 actions
.add(SendSyncGroupsAction
.create());
2101 if (rm
.isBlockedListRequest()) {
2102 actions
.add(SendSyncBlockedListAction
.create());
2104 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2106 if (syncMessage
.getGroups().isPresent()) {
2107 File tmpFile
= null;
2109 tmpFile
= IOUtils
.createTempFile();
2110 final var groupsMessage
= syncMessage
.getGroups().get();
2111 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2112 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2117 } catch (IOException e
) {
2118 logger
.warn("Sync groups contained invalid group, ignoring: {}", e
.getMessage());
2124 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2125 if (syncGroup
!= null) {
2126 if (g
.getName().isPresent()) {
2127 syncGroup
.name
= g
.getName().get();
2129 syncGroup
.addMembers(g
.getMembers()
2131 .map(this::resolveRecipient
)
2132 .collect(Collectors
.toSet()));
2133 if (!g
.isActive()) {
2134 syncGroup
.removeMember(account
.getSelfRecipientId());
2136 // Add ourself to the member set as it's marked as active
2137 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2139 syncGroup
.blocked
= g
.isBlocked();
2140 if (g
.getColor().isPresent()) {
2141 syncGroup
.color
= g
.getColor().get();
2144 if (g
.getAvatar().isPresent()) {
2145 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2147 syncGroup
.archived
= g
.isArchived();
2148 account
.getGroupStore().updateGroup(syncGroup
);
2152 } catch (Exception e
) {
2153 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2157 if (tmpFile
!= null) {
2159 Files
.delete(tmpFile
.toPath());
2160 } catch (IOException e
) {
2161 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2168 if (syncMessage
.getBlockedList().isPresent()) {
2169 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2170 for (var address
: blockedListMessage
.getAddresses()) {
2171 setContactBlocked(resolveRecipient(address
), true);
2173 for (var groupId
: blockedListMessage
.getGroupIds()
2175 .map(GroupId
::unknownVersion
)
2176 .collect(Collectors
.toSet())) {
2178 setGroupBlocked(groupId
, true);
2179 } catch (GroupNotFoundException e
) {
2180 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2181 groupId
.toBase64());
2185 if (syncMessage
.getContacts().isPresent()) {
2186 File tmpFile
= null;
2188 tmpFile
= IOUtils
.createTempFile();
2189 final var contactsMessage
= syncMessage
.getContacts().get();
2190 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2191 .asPointer(), tmpFile
)) {
2192 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2197 } catch (IOException e
) {
2198 logger
.warn("Sync contacts contained invalid contact, ignoring: {}",
2205 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2206 account
.setProfileKey(c
.getProfileKey().get());
2208 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2209 var contact
= account
.getContactStore().getContact(recipientId
);
2210 final var builder
= contact
== null
2211 ? Contact
.newBuilder()
2212 : Contact
.newBuilder(contact
);
2213 if (c
.getName().isPresent()) {
2214 builder
.withName(c
.getName().get());
2216 if (c
.getColor().isPresent()) {
2217 builder
.withColor(c
.getColor().get());
2219 if (c
.getProfileKey().isPresent()) {
2220 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2222 if (c
.getVerified().isPresent()) {
2223 final var verifiedMessage
= c
.getVerified().get();
2224 account
.getIdentityKeyStore()
2225 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2226 verifiedMessage
.getIdentityKey(),
2227 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2229 if (c
.getExpirationTimer().isPresent()) {
2230 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2232 builder
.withBlocked(c
.isBlocked());
2233 builder
.withArchived(c
.isArchived());
2234 account
.getContactStore().storeContact(recipientId
, builder
.build());
2236 if (c
.getAvatar().isPresent()) {
2237 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2241 } catch (Exception e
) {
2242 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2246 if (tmpFile
!= null) {
2248 Files
.delete(tmpFile
.toPath());
2249 } catch (IOException e
) {
2250 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2257 if (syncMessage
.getVerified().isPresent()) {
2258 final var verifiedMessage
= syncMessage
.getVerified().get();
2259 account
.getIdentityKeyStore()
2260 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2261 verifiedMessage
.getIdentityKey(),
2262 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2264 if (syncMessage
.getStickerPackOperations().isPresent()) {
2265 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2266 for (var m
: stickerPackOperationMessages
) {
2267 if (!m
.getPackId().isPresent()) {
2270 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2271 final var installed
= !m
.getType().isPresent()
2272 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
;
2274 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2275 if (m
.getPackKey().isPresent()) {
2276 if (sticker
== null) {
2277 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2280 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, m
.getPackKey().get()));
2284 if (sticker
!= null) {
2285 sticker
.setInstalled(installed
);
2286 account
.getStickerStore().updateSticker(sticker
);
2290 if (syncMessage
.getFetchType().isPresent()) {
2291 switch (syncMessage
.getFetchType().get()) {
2293 getRecipientProfile(account
.getSelfRecipientId(), true);
2294 case STORAGE_MANIFEST
:
2298 if (syncMessage
.getKeys().isPresent()) {
2299 final var keysMessage
= syncMessage
.getKeys().get();
2300 if (keysMessage
.getStorageService().isPresent()) {
2301 final var storageKey
= keysMessage
.getStorageService().get();
2302 account
.setStorageKey(storageKey
);
2305 if (syncMessage
.getConfiguration().isPresent()) {
2313 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2315 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2316 } catch (IOException e
) {
2317 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2321 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2323 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2324 } catch (IOException e
) {
2325 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2329 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2331 avatarStore
.storeGroupAvatar(groupId
,
2332 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2333 } catch (IOException e
) {
2334 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2338 private void downloadProfileAvatar(
2339 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2342 avatarStore
.storeProfileAvatar(address
,
2343 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2344 } catch (Throwable e
) {
2345 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
2346 Thread
.currentThread().interrupt();
2348 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2352 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2353 return attachmentStore
.getAttachmentFile(attachmentId
);
2356 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2357 if (!attachment
.isPointer()) {
2358 logger
.warn("Invalid state, can't store an attachment stream.");
2361 var pointer
= attachment
.asPointer();
2362 if (pointer
.getPreview().isPresent()) {
2363 final var preview
= pointer
.getPreview().get();
2365 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2366 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2367 } catch (IOException e
) {
2368 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2373 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2374 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2375 } catch (IOException e
) {
2376 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2380 private void retrieveGroupV2Avatar(
2381 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2382 ) throws IOException
{
2383 var groupOperations
= dependencies
.getGroupsV2Operations().forGroup(groupSecretParams
);
2385 var tmpFile
= IOUtils
.createTempFile();
2386 try (InputStream input
= dependencies
.getMessageReceiver()
2387 .retrieveGroupsV2ProfileAvatar(cdnKey
, tmpFile
, ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2388 var encryptedData
= IOUtils
.readFully(input
);
2390 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2391 outputStream
.write(decryptedData
);
2394 Files
.delete(tmpFile
.toPath());
2395 } catch (IOException e
) {
2396 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2403 private void retrieveProfileAvatar(
2404 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2405 ) throws IOException
{
2406 var tmpFile
= IOUtils
.createTempFile();
2407 try (var input
= dependencies
.getMessageReceiver()
2408 .retrieveProfileAvatar(avatarPath
,
2411 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2412 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2413 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2416 Files
.delete(tmpFile
.toPath());
2417 } catch (IOException e
) {
2418 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2425 private void retrieveAttachment(
2426 final SignalServiceAttachment attachment
, final OutputStream outputStream
2427 ) throws IOException
{
2428 if (attachment
.isPointer()) {
2429 var pointer
= attachment
.asPointer();
2430 retrieveAttachmentPointer(pointer
, outputStream
);
2432 var stream
= attachment
.asStream();
2433 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2437 private void retrieveAttachmentPointer(
2438 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2439 ) throws IOException
{
2440 var tmpFile
= IOUtils
.createTempFile();
2441 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2442 IOUtils
.copyStream(input
, outputStream
);
2443 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2444 throw new IOException(e
);
2447 Files
.delete(tmpFile
.toPath());
2448 } catch (IOException e
) {
2449 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2456 private InputStream
retrieveAttachmentAsStream(
2457 SignalServiceAttachmentPointer pointer
, File tmpFile
2458 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2459 return dependencies
.getMessageReceiver()
2460 .retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2463 void sendGroups() throws IOException
{
2464 var groupsFile
= IOUtils
.createTempFile();
2467 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2468 var out
= new DeviceGroupsOutputStream(fos
);
2469 for (var record : getGroups()) {
2470 if (record instanceof GroupInfoV1
) {
2471 var groupInfo
= (GroupInfoV1
) record;
2472 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2473 Optional
.fromNullable(groupInfo
.name
),
2474 groupInfo
.getMembers()
2476 .map(this::resolveSignalServiceAddress
)
2477 .collect(Collectors
.toList()),
2478 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2479 groupInfo
.isMember(account
.getSelfRecipientId()),
2480 Optional
.of(groupInfo
.messageExpirationTime
),
2481 Optional
.fromNullable(groupInfo
.color
),
2484 groupInfo
.archived
));
2489 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2490 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2491 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2492 .withStream(groupsFileStream
)
2493 .withContentType("application/octet-stream")
2494 .withLength(groupsFile
.length())
2497 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2502 Files
.delete(groupsFile
.toPath());
2503 } catch (IOException e
) {
2504 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2509 public void sendContacts() throws IOException
{
2510 var contactsFile
= IOUtils
.createTempFile();
2513 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2514 var out
= new DeviceContactsOutputStream(fos
);
2515 for (var contactPair
: account
.getContactStore().getContacts()) {
2516 final var recipientId
= contactPair
.first();
2517 final var contact
= contactPair
.second();
2518 final var address
= resolveSignalServiceAddress(recipientId
);
2520 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2521 VerifiedMessage verifiedMessage
= null;
2522 if (currentIdentity
!= null) {
2523 verifiedMessage
= new VerifiedMessage(address
,
2524 currentIdentity
.getIdentityKey(),
2525 currentIdentity
.getTrustLevel().toVerifiedState(),
2526 currentIdentity
.getDateAdded().getTime());
2529 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2530 out
.write(new DeviceContact(address
,
2531 Optional
.fromNullable(contact
.getName()),
2532 createContactAvatarAttachment(address
),
2533 Optional
.fromNullable(contact
.getColor()),
2534 Optional
.fromNullable(verifiedMessage
),
2535 Optional
.fromNullable(profileKey
),
2536 contact
.isBlocked(),
2537 Optional
.of(contact
.getMessageExpirationTime()),
2539 contact
.isArchived()));
2542 if (account
.getProfileKey() != null) {
2543 // Send our own profile key as well
2544 out
.write(new DeviceContact(account
.getSelfAddress(),
2549 Optional
.of(account
.getProfileKey()),
2557 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2558 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2559 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2560 .withStream(contactsFileStream
)
2561 .withContentType("application/octet-stream")
2562 .withLength(contactsFile
.length())
2565 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
,
2571 Files
.delete(contactsFile
.toPath());
2572 } catch (IOException e
) {
2573 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2578 void sendBlockedList() throws IOException
{
2579 var addresses
= new ArrayList
<SignalServiceAddress
>();
2580 for (var record : account
.getContactStore().getContacts()) {
2581 if (record.second().isBlocked()) {
2582 addresses
.add(resolveSignalServiceAddress(record.first()));
2585 var groupIds
= new ArrayList
<byte[]>();
2586 for (var record : getGroups()) {
2587 if (record.isBlocked()) {
2588 groupIds
.add(record.getGroupId().serialize());
2591 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2594 private void sendVerifiedMessage(
2595 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2596 ) throws IOException
{
2597 var verifiedMessage
= new VerifiedMessage(destination
,
2599 trustLevel
.toVerifiedState(),
2600 System
.currentTimeMillis());
2601 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2604 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2605 return account
.getContactStore().getContacts();
2608 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2609 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2610 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2611 if (recipient
== null) {
2615 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2616 return recipient
.getContact().getName();
2619 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2620 return recipient
.getProfile().getDisplayName();
2626 public GroupInfo
getGroup(GroupId groupId
) {
2627 return getGroup(groupId
, false);
2630 public GroupInfo
getGroup(GroupId groupId
, boolean forceUpdate
) {
2631 final var group
= account
.getGroupStore().getGroup(groupId
);
2632 if (group
instanceof GroupInfoV2
&& (forceUpdate
|| ((GroupInfoV2
) group
).getGroup() == null)) {
2633 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2634 ((GroupInfoV2
) group
).setGroup(groupV2Helper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2635 account
.getGroupStore().updateGroup(group
);
2640 public List
<IdentityInfo
> getIdentities() {
2641 return account
.getIdentityKeyStore().getIdentities();
2644 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2645 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2646 return identity
== null ? List
.of() : List
.of(identity
);
2650 * Trust this the identity with this fingerprint
2652 * @param name username of the identity
2653 * @param fingerprint Fingerprint
2655 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2656 var recipientId
= canonicalizeAndResolveRecipient(name
);
2657 return trustIdentity(recipientId
,
2658 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2659 TrustLevel
.TRUSTED_VERIFIED
);
2663 * Trust this the identity with this safety number
2665 * @param name username of the identity
2666 * @param safetyNumber Safety number
2668 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2669 var recipientId
= canonicalizeAndResolveRecipient(name
);
2670 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2671 return trustIdentity(recipientId
,
2672 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2673 TrustLevel
.TRUSTED_VERIFIED
);
2677 * Trust this the identity with this scannable safety number
2679 * @param name username of the identity
2680 * @param safetyNumber Scannable safety number
2682 public boolean trustIdentityVerifiedSafetyNumber(String name
, byte[] safetyNumber
) throws InvalidNumberException
{
2683 var recipientId
= canonicalizeAndResolveRecipient(name
);
2684 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2685 return trustIdentity(recipientId
, identityKey
-> {
2686 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
2688 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
2689 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
2692 }, TrustLevel
.TRUSTED_VERIFIED
);
2696 * Trust all keys of this identity without verification
2698 * @param name username of the identity
2700 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2701 var recipientId
= canonicalizeAndResolveRecipient(name
);
2702 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2705 private boolean trustIdentity(
2706 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2708 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2709 if (identity
== null) {
2713 if (!verifier
.apply(identity
.getIdentityKey())) {
2717 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2719 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2720 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2721 } catch (IOException e
) {
2722 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2728 private void handleIdentityFailure(
2729 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
2731 final var identityKey
= identityFailure
.getIdentityKey();
2732 if (identityKey
!= null) {
2733 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
2735 account
.getSessionStore().archiveSessions(recipientId
);
2738 // Retrieve profile to get the current identity key from the server
2739 retrieveEncryptedProfile(recipientId
);
2743 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
2744 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
2745 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
2748 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
2749 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
2750 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
2753 private Fingerprint
computeSafetyNumberFingerprint(
2754 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
2756 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
2757 account
.getSelfAddress(),
2758 getIdentityKeyPair().getPublicKey(),
2764 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2765 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2767 return resolveSignalServiceAddress(address
);
2771 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2772 if (address
.matches(account
.getSelfAddress())) {
2773 return account
.getSelfAddress();
2776 return account
.getRecipientStore().resolveServiceAddress(address
);
2779 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2780 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2783 private RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2784 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
) ? identifier
: canonicalizePhoneNumber(identifier
);
2786 return resolveRecipient(canonicalizedNumber
);
2789 private String
canonicalizePhoneNumber(final String number
) throws InvalidNumberException
{
2790 return PhoneNumberFormatter
.formatNumber(number
, account
.getUsername());
2793 private RecipientId
resolveRecipient(final String identifier
) {
2794 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2796 return resolveRecipient(address
);
2799 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2800 return account
.getRecipientStore().resolveRecipient(address
);
2803 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2804 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2807 private void enqueueJob(Job job
) {
2808 var context
= new Context(account
,
2809 dependencies
.getAccountManager(),
2810 dependencies
.getMessageReceiver(),
2816 public void close() throws IOException
{
2820 void close(boolean closeAccount
) throws IOException
{
2821 executor
.shutdown();
2823 dependencies
.getSignalWebSocket().disconnect();
2825 if (closeAccount
&& account
!= null) {
2831 public interface ReceiveMessageHandler
{
2833 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);