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
.UnidentifiedAccessHelper
;
37 import org
.asamk
.signal
.manager
.jobs
.Context
;
38 import org
.asamk
.signal
.manager
.jobs
.Job
;
39 import org
.asamk
.signal
.manager
.jobs
.RetrieveStickerPackJob
;
40 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
41 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
42 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
43 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
44 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
45 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
46 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
47 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
48 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
49 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
50 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
51 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
52 import org
.asamk
.signal
.manager
.util
.IOUtils
;
53 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
54 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
55 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
56 import org
.asamk
.signal
.manager
.util
.Utils
;
57 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
58 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
59 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
60 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
61 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
62 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
63 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
64 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
65 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
66 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
67 import org
.signal
.libsignal
.metadata
.SelfSendException
;
68 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
69 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
70 import org
.signal
.zkgroup
.InvalidInputException
;
71 import org
.signal
.zkgroup
.VerificationFailedException
;
72 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
73 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
74 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
75 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
76 import org
.slf4j
.Logger
;
77 import org
.slf4j
.LoggerFactory
;
78 import org
.whispersystems
.libsignal
.IdentityKey
;
79 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
80 import org
.whispersystems
.libsignal
.InvalidKeyException
;
81 import org
.whispersystems
.libsignal
.InvalidMessageException
;
82 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
83 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
84 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
85 import org
.whispersystems
.libsignal
.util
.Pair
;
86 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
87 import org
.whispersystems
.signalservice
.api
.InvalidMessageStructureException
;
88 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
89 import org
.whispersystems
.signalservice
.api
.crypto
.ContentHint
;
90 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
91 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
92 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
93 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
94 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
95 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
96 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
105 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
106 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
107 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
118 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
119 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
120 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
121 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.ConflictException
;
122 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
123 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
124 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
125 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
126 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
127 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
128 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
129 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
130 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
131 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
132 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
133 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
134 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
135 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
136 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
138 import java
.io
.Closeable
;
140 import java
.io
.FileInputStream
;
141 import java
.io
.FileOutputStream
;
142 import java
.io
.IOException
;
143 import java
.io
.InputStream
;
144 import java
.io
.OutputStream
;
146 import java
.net
.URISyntaxException
;
147 import java
.net
.URLEncoder
;
148 import java
.nio
.charset
.StandardCharsets
;
149 import java
.nio
.file
.Files
;
150 import java
.security
.SignatureException
;
151 import java
.util
.ArrayList
;
152 import java
.util
.Arrays
;
153 import java
.util
.Base64
;
154 import java
.util
.Collection
;
155 import java
.util
.Date
;
156 import java
.util
.HashSet
;
157 import java
.util
.List
;
158 import java
.util
.Map
;
159 import java
.util
.Set
;
160 import java
.util
.UUID
;
161 import java
.util
.concurrent
.ExecutorService
;
162 import java
.util
.concurrent
.Executors
;
163 import java
.util
.concurrent
.TimeUnit
;
164 import java
.util
.concurrent
.TimeoutException
;
165 import java
.util
.concurrent
.locks
.ReentrantLock
;
166 import java
.util
.function
.Function
;
167 import java
.util
.stream
.Collectors
;
169 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
171 public class Manager
implements Closeable
{
173 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
175 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
176 private final SignalDependencies dependencies
;
178 private SignalAccount account
;
180 private final ExecutorService executor
= Executors
.newCachedThreadPool();
182 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
183 private final ProfileHelper profileHelper
;
184 private final GroupV2Helper groupV2Helper
;
185 private final PinHelper pinHelper
;
186 private final AvatarStore avatarStore
;
187 private final AttachmentStore attachmentStore
;
188 private final StickerPackStore stickerPackStore
;
189 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
190 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
193 public Lock
acquire() {
195 return LEGACY_LOCK
::unlock
;
200 SignalAccount account
,
201 PathConfig pathConfig
,
202 ServiceEnvironmentConfig serviceEnvironmentConfig
,
205 this.account
= account
;
206 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
208 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
209 account
.getUsername(),
210 account
.getPassword(),
211 account
.getDeviceId());
212 this.dependencies
= new SignalDependencies(account
.getSelfAddress(),
213 serviceEnvironmentConfig
,
216 account
.getSignalProtocolStore(),
219 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
221 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
222 account
.getProfileStore()::getProfileKey
,
223 this::getRecipientProfile
,
224 this::getSenderCertificate
);
225 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
226 unidentifiedAccessHelper
::getAccessFor
,
227 dependencies
::getProfileService
,
228 dependencies
::getMessageReceiver
,
229 this::resolveSignalServiceAddress
);
230 this.groupV2Helper
= new GroupV2Helper(this::getRecipientProfileKeyCredential
,
231 this::getRecipientProfile
,
232 account
::getSelfRecipientId
,
233 dependencies
.getGroupsV2Operations(),
234 dependencies
.getGroupsV2Api(),
235 this::getGroupAuthForToday
,
236 this::resolveSignalServiceAddress
);
237 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
238 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
239 this.stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
242 public String
getUsername() {
243 return account
.getUsername();
246 public SignalServiceAddress
getSelfAddress() {
247 return account
.getSelfAddress();
250 public RecipientId
getSelfRecipientId() {
251 return account
.getSelfRecipientId();
254 private IdentityKeyPair
getIdentityKeyPair() {
255 return account
.getIdentityKeyPair();
258 public int getDeviceId() {
259 return account
.getDeviceId();
262 public static Manager
init(
263 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
264 ) throws IOException
, NotRegisteredException
{
265 var pathConfig
= PathConfig
.createDefault(settingsPath
);
267 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
268 throw new NotRegisteredException();
271 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true);
273 if (!account
.isRegistered()) {
274 throw new NotRegisteredException();
277 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
279 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
282 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
283 var pathConfig
= PathConfig
.createDefault(settingsPath
);
284 final var dataPath
= pathConfig
.getDataPath();
285 final var files
= dataPath
.listFiles();
291 return Arrays
.stream(files
)
292 .filter(File
::isFile
)
294 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
295 .collect(Collectors
.toList());
298 public void checkAccountState() throws IOException
{
299 if (account
.getLastReceiveTimestamp() == 0) {
300 logger
.warn("The Signal protocol expects that incoming messages are regularly received.");
302 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
303 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
306 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
310 if (dependencies
.getAccountManager().getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
313 if (account
.getUuid() == null) {
314 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
316 updateAccountAttributes();
320 * This is used for checking a set of phone numbers for registration on Signal
322 * @param numbers The set of phone number in question
323 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
324 * @throws IOException if its unable to get the contacts to check if they're registered
326 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
327 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
328 var contactDetails
= getRegisteredUsers(numbers
);
330 var registeredUsers
= contactDetails
.keySet();
332 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
335 public void updateAccountAttributes() throws IOException
{
336 dependencies
.getAccountManager()
337 .setAccountAttributes(account
.getEncryptedDeviceName(),
339 account
.getLocalRegistrationId(),
341 // set legacy pin only if no KBS master key is set
342 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
343 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
344 account
.getSelfUnidentifiedAccessKey(),
345 account
.isUnrestrictedUnidentifiedAccess(),
347 account
.isDiscoverableByPhoneNumber());
351 * @param givenName if null, the previous givenName will be kept
352 * @param familyName if null, the previous familyName will be kept
353 * @param about if null, the previous about text will be kept
354 * @param aboutEmoji if null, the previous about emoji will be kept
355 * @param avatar if avatar is null the image from the local avatar store is used (if present),
357 public void setProfile(
358 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
359 ) throws IOException
{
360 var profile
= getRecipientProfile(account
.getSelfRecipientId());
361 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
362 if (givenName
!= null) {
363 builder
.withGivenName(givenName
);
365 if (familyName
!= null) {
366 builder
.withFamilyName(familyName
);
369 builder
.withAbout(about
);
371 if (aboutEmoji
!= null) {
372 builder
.withAboutEmoji(aboutEmoji
);
374 var newProfile
= builder
.build();
376 try (final var streamDetails
= avatar
== null
377 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
378 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
379 dependencies
.getAccountManager()
380 .setVersionedProfile(account
.getUuid(),
381 account
.getProfileKey(),
382 newProfile
.getInternalServiceName(),
383 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
384 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
389 if (avatar
!= null) {
390 if (avatar
.isPresent()) {
391 avatarStore
.storeProfileAvatar(getSelfAddress(),
392 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
394 avatarStore
.deleteProfileAvatar(getSelfAddress());
397 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
400 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
401 } catch (UntrustedIdentityException ignored
) {
405 public void unregister() throws IOException
{
406 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
407 // If this is the master device, other users can't send messages to this number anymore.
408 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
409 dependencies
.getAccountManager().setGcmId(Optional
.absent());
411 account
.setRegistered(false);
414 public void deleteAccount() throws IOException
{
415 dependencies
.getAccountManager().deleteAccount();
417 account
.setRegistered(false);
420 public List
<Device
> getLinkedDevices() throws IOException
{
421 var devices
= dependencies
.getAccountManager().getDevices();
422 account
.setMultiDevice(devices
.size() > 1);
423 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
424 return devices
.stream().map(d
-> {
425 String deviceName
= d
.getName();
426 if (deviceName
!= null) {
428 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
429 } catch (IOException e
) {
430 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
433 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
434 }).collect(Collectors
.toList());
437 public void removeLinkedDevices(int deviceId
) throws IOException
{
438 dependencies
.getAccountManager().removeDevice(deviceId
);
439 var devices
= dependencies
.getAccountManager().getDevices();
440 account
.setMultiDevice(devices
.size() > 1);
443 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
444 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
446 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
449 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
450 var identityKeyPair
= getIdentityKeyPair();
451 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
453 dependencies
.getAccountManager()
454 .addDevice(deviceIdentifier
,
457 Optional
.of(account
.getProfileKey().serialize()),
459 account
.setMultiDevice(true);
462 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
463 if (!account
.isMasterDevice()) {
464 throw new RuntimeException("Only master device can set a PIN");
466 if (pin
.isPresent()) {
467 final var masterKey
= account
.getPinMasterKey() != null
468 ? account
.getPinMasterKey()
469 : KeyUtils
.createMasterKey();
471 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
473 account
.setRegistrationLockPin(pin
.get(), masterKey
);
476 pinHelper
.removeRegistrationLockPin();
478 account
.setRegistrationLockPin(null, null);
482 void refreshPreKeys() throws IOException
{
483 var oneTimePreKeys
= generatePreKeys();
484 final var identityKeyPair
= getIdentityKeyPair();
485 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
487 dependencies
.getAccountManager().setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
490 private List
<PreKeyRecord
> generatePreKeys() {
491 final var offset
= account
.getPreKeyIdOffset();
493 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
494 account
.addPreKeys(records
);
499 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
500 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
502 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
503 account
.addSignedPreKey(record);
508 public Profile
getRecipientProfile(
509 RecipientId recipientId
511 return getRecipientProfile(recipientId
, false);
514 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
516 Profile
getRecipientProfile(
517 RecipientId recipientId
, boolean force
519 var profile
= account
.getProfileStore().getProfile(recipientId
);
521 var now
= System
.currentTimeMillis();
522 // Profiles are cached for 24h before retrieving them again, unless forced
523 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
527 synchronized (pendingProfileRequest
) {
528 if (pendingProfileRequest
.contains(recipientId
)) {
531 pendingProfileRequest
.add(recipientId
);
533 final SignalServiceProfile encryptedProfile
;
535 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
537 synchronized (pendingProfileRequest
) {
538 pendingProfileRequest
.remove(recipientId
);
541 if (encryptedProfile
== null) {
545 profile
= decryptProfileIfKeyKnown(recipientId
, encryptedProfile
);
546 account
.getProfileStore().storeProfile(recipientId
, profile
);
551 private Profile
decryptProfileIfKeyKnown(
552 final RecipientId recipientId
, final SignalServiceProfile encryptedProfile
554 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
555 if (profileKey
== null) {
556 return new Profile(System
.currentTimeMillis(),
561 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
562 ProfileUtils
.getCapabilities(encryptedProfile
));
565 return decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
568 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
570 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
571 } catch (IOException e
) {
572 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
577 private ProfileAndCredential
retrieveProfileAndCredential(
578 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
579 ) throws IOException
{
580 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
581 final var profile
= profileAndCredential
.getProfile();
584 var newIdentity
= account
.getIdentityKeyStore()
585 .saveIdentity(recipientId
,
586 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
590 account
.getSessionStore().archiveSessions(recipientId
);
592 } catch (InvalidKeyException ignored
) {
593 logger
.warn("Got invalid identity key in profile for {}",
594 resolveSignalServiceAddress(recipientId
).getIdentifier());
596 return profileAndCredential
;
599 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
600 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
601 if (profileKeyCredential
!= null) {
602 return profileKeyCredential
;
605 ProfileAndCredential profileAndCredential
;
607 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
608 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
609 } catch (IOException e
) {
610 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
614 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
615 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
617 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
618 if (profileKey
!= null) {
619 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
621 profileAndCredential
.getProfile());
622 account
.getProfileStore().storeProfile(recipientId
, profile
);
625 return profileKeyCredential
;
628 private Profile
decryptProfileAndDownloadAvatar(
629 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
631 if (encryptedProfile
.getAvatar() != null) {
632 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
635 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
638 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
639 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
640 if (streamDetails
== null) {
641 return Optional
.absent();
644 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
647 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
648 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
649 if (streamDetails
== null) {
650 return Optional
.absent();
653 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
656 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
657 var g
= getGroup(groupId
);
659 throw new GroupNotFoundException(groupId
);
661 if (!g
.isMember(account
.getSelfRecipientId())) {
662 throw new NotAGroupMemberException(groupId
, g
.getTitle());
667 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
668 var g
= getGroup(groupId
);
670 throw new GroupNotFoundException(groupId
);
672 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
673 throw new NotAGroupMemberException(groupId
, g
.getTitle());
678 public List
<GroupInfo
> getGroups() {
679 return account
.getGroupStore().getGroups();
682 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
683 String messageText
, List
<String
> attachments
, GroupId groupId
684 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
685 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
686 if (attachments
!= null) {
687 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
690 return sendGroupMessage(messageBuilder
, groupId
);
693 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
694 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
695 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
696 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
697 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
699 resolveSignalServiceAddress(targetAuthorRecipientId
),
700 targetSentTimestamp
);
701 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
703 return sendGroupMessage(messageBuilder
, groupId
);
706 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
707 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
708 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
709 final var g
= getGroupForSending(groupId
);
711 GroupUtils
.setGroupContext(messageBuilder
, g
);
712 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
714 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
717 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(
718 GroupId groupId
, Set
<String
> groupAdmins
719 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, InvalidNumberException
, LastGroupAdminException
{
720 var group
= getGroupForUpdating(groupId
);
721 if (group
instanceof GroupInfoV1
) {
722 return quitGroupV1((GroupInfoV1
) group
);
725 final var newAdmins
= getSignalServiceAddresses(groupAdmins
);
727 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
728 } catch (ConflictException e
) {
729 // Detected conflicting update, refreshing group and trying again
730 group
= getGroup(groupId
, true);
731 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
735 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV1(final GroupInfoV1 groupInfoV1
) throws IOException
{
736 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
737 .withId(groupInfoV1
.getGroupId().serialize())
740 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
741 groupInfoV1
.removeMember(account
.getSelfRecipientId());
742 account
.getGroupStore().updateGroup(groupInfoV1
);
743 return sendMessage(messageBuilder
, groupInfoV1
.getMembersWithout(account
.getSelfRecipientId()));
746 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV2(
747 final GroupInfoV2 groupInfoV2
, final Set
<RecipientId
> newAdmins
748 ) throws LastGroupAdminException
, IOException
{
749 final var currentAdmins
= groupInfoV2
.getAdminMembers();
750 newAdmins
.removeAll(currentAdmins
);
751 newAdmins
.retainAll(groupInfoV2
.getMembers());
752 if (currentAdmins
.contains(getSelfRecipientId())
753 && currentAdmins
.size() == 1
754 && groupInfoV2
.getMembers().size() > 1
755 && newAdmins
.size() == 0) {
756 // Last admin can't leave the group, unless she's also the last member
757 throw new LastGroupAdminException(groupInfoV2
.getGroupId(), groupInfoV2
.getTitle());
759 final var groupGroupChangePair
= groupV2Helper
.leaveGroup(groupInfoV2
, newAdmins
);
760 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
761 var messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
762 account
.getGroupStore().updateGroup(groupInfoV2
);
763 return sendMessage(messageBuilder
, groupInfoV2
.getMembersWithout(account
.getSelfRecipientId()));
766 public void deleteGroup(GroupId groupId
) throws IOException
{
767 account
.getGroupStore().deleteGroup(groupId
);
768 avatarStore
.deleteGroupAvatar(groupId
);
771 public Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
772 String name
, List
<String
> members
, File avatarFile
773 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
774 return createGroup(name
, members
== null ?
null : getSignalServiceAddresses(members
), avatarFile
);
777 private Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
778 String name
, Set
<RecipientId
> members
, File avatarFile
779 ) throws IOException
, AttachmentInvalidException
{
780 final var selfRecipientId
= account
.getSelfRecipientId();
781 if (members
!= null && members
.contains(selfRecipientId
)) {
782 members
= new HashSet
<>(members
);
783 members
.remove(selfRecipientId
);
786 var gv2Pair
= groupV2Helper
.createGroup(name
== null ?
"" : name
,
787 members
== null ? Set
.of() : members
,
790 SignalServiceDataMessage
.Builder messageBuilder
;
791 if (gv2Pair
== null) {
792 // Failed to create v2 group, creating v1 group instead
793 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
794 gv1
.addMembers(List
.of(selfRecipientId
));
795 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
796 return new Pair
<>(gv1
.getGroupId(), result
.second());
799 final var gv2
= gv2Pair
.first();
800 final var decryptedGroup
= gv2Pair
.second();
802 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
803 if (avatarFile
!= null) {
804 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
805 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
807 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
808 account
.getGroupStore().updateGroup(gv2
);
810 final var result
= sendMessage(messageBuilder
, gv2
.getMembersIncludingPendingWithout(selfRecipientId
));
811 return new Pair
<>(gv2
.getGroupId(), result
.second());
814 public Pair
<Long
, List
<SendMessageResult
>> updateGroup(
818 List
<String
> members
,
819 List
<String
> removeMembers
,
821 List
<String
> removeAdmins
,
822 boolean resetGroupLink
,
823 GroupLinkState groupLinkState
,
824 GroupPermission addMemberPermission
,
825 GroupPermission editDetailsPermission
,
827 Integer expirationTimer
828 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
829 return updateGroup(groupId
,
832 members
== null ?
null : getSignalServiceAddresses(members
),
833 removeMembers
== null ?
null : getSignalServiceAddresses(removeMembers
),
834 admins
== null ?
null : getSignalServiceAddresses(admins
),
835 removeAdmins
== null ?
null : getSignalServiceAddresses(removeAdmins
),
839 editDetailsPermission
,
844 private Pair
<Long
, List
<SendMessageResult
>> updateGroup(
845 final GroupId groupId
,
847 final String description
,
848 final Set
<RecipientId
> members
,
849 final Set
<RecipientId
> removeMembers
,
850 final Set
<RecipientId
> admins
,
851 final Set
<RecipientId
> removeAdmins
,
852 final boolean resetGroupLink
,
853 final GroupLinkState groupLinkState
,
854 final GroupPermission addMemberPermission
,
855 final GroupPermission editDetailsPermission
,
856 final File avatarFile
,
857 final Integer expirationTimer
858 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
859 var group
= getGroupForUpdating(groupId
);
861 if (group
instanceof GroupInfoV2
) {
863 return updateGroupV2((GroupInfoV2
) group
,
873 editDetailsPermission
,
876 } catch (ConflictException e
) {
877 // Detected conflicting update, refreshing group and trying again
878 group
= getGroup(groupId
, true);
879 return updateGroupV2((GroupInfoV2
) group
,
889 editDetailsPermission
,
895 final var gv1
= (GroupInfoV1
) group
;
896 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
897 if (expirationTimer
!= null) {
898 setExpirationTimer(gv1
, expirationTimer
);
903 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV1(
904 final GroupInfoV1 gv1
, final String name
, final Set
<RecipientId
> members
, final File avatarFile
905 ) throws IOException
, AttachmentInvalidException
{
906 updateGroupV1Details(gv1
, name
, members
, avatarFile
);
907 var messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
909 account
.getGroupStore().updateGroup(gv1
);
911 return sendMessage(messageBuilder
, gv1
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
914 private void updateGroupV1Details(
915 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
916 ) throws IOException
{
921 if (members
!= null) {
922 final var newMemberAddresses
= members
.stream()
923 .filter(member
-> !g
.isMember(member
))
924 .map(this::resolveSignalServiceAddress
)
925 .collect(Collectors
.toList());
926 final var newE164Members
= new HashSet
<String
>();
927 for (var member
: newMemberAddresses
) {
928 if (!member
.getNumber().isPresent()) {
931 newE164Members
.add(member
.getNumber().get());
934 final var registeredUsers
= getRegisteredUsers(newE164Members
);
935 if (registeredUsers
.size() != newE164Members
.size()) {
936 // Some of the new members are not registered on Signal
937 newE164Members
.removeAll(registeredUsers
.keySet());
938 throw new IOException("Failed to add members "
939 + String
.join(", ", newE164Members
)
940 + " to group: Not registered on Signal");
943 g
.addMembers(members
);
946 if (avatarFile
!= null) {
947 avatarStore
.storeGroupAvatar(g
.getGroupId(),
948 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
952 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV2(
953 final GroupInfoV2 group
,
955 final String description
,
956 final Set
<RecipientId
> members
,
957 final Set
<RecipientId
> removeMembers
,
958 final Set
<RecipientId
> admins
,
959 final Set
<RecipientId
> removeAdmins
,
960 final boolean resetGroupLink
,
961 final GroupLinkState groupLinkState
,
962 final GroupPermission addMemberPermission
,
963 final GroupPermission editDetailsPermission
,
964 final File avatarFile
,
965 Integer expirationTimer
966 ) throws IOException
{
967 Pair
<Long
, List
<SendMessageResult
>> result
= null;
968 if (group
.isPendingMember(account
.getSelfRecipientId())) {
969 var groupGroupChangePair
= groupV2Helper
.acceptInvite(group
);
970 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
973 if (members
!= null) {
974 final var newMembers
= new HashSet
<>(members
);
975 newMembers
.removeAll(group
.getMembers());
976 if (newMembers
.size() > 0) {
977 var groupGroupChangePair
= groupV2Helper
.addMembers(group
, newMembers
);
978 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
982 if (removeMembers
!= null) {
983 var existingRemoveMembers
= new HashSet
<>(removeMembers
);
984 existingRemoveMembers
.retainAll(group
.getMembers());
985 existingRemoveMembers
.remove(getSelfRecipientId());// self can be removed with sendQuitGroupMessage
986 if (existingRemoveMembers
.size() > 0) {
987 var groupGroupChangePair
= groupV2Helper
.removeMembers(group
, existingRemoveMembers
);
988 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
991 var pendingRemoveMembers
= new HashSet
<>(removeMembers
);
992 pendingRemoveMembers
.retainAll(group
.getPendingMembers());
993 if (pendingRemoveMembers
.size() > 0) {
994 var groupGroupChangePair
= groupV2Helper
.revokeInvitedMembers(group
, pendingRemoveMembers
);
995 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
999 if (admins
!= null) {
1000 final var newAdmins
= new HashSet
<>(admins
);
1001 newAdmins
.retainAll(group
.getMembers());
1002 newAdmins
.removeAll(group
.getAdminMembers());
1003 if (newAdmins
.size() > 0) {
1004 for (var admin
: newAdmins
) {
1005 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, true);
1006 result
= sendUpdateGroupV2Message(group
,
1007 groupGroupChangePair
.first(),
1008 groupGroupChangePair
.second());
1013 if (removeAdmins
!= null) {
1014 final var existingRemoveAdmins
= new HashSet
<>(removeAdmins
);
1015 existingRemoveAdmins
.retainAll(group
.getAdminMembers());
1016 if (existingRemoveAdmins
.size() > 0) {
1017 for (var admin
: existingRemoveAdmins
) {
1018 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, false);
1019 result
= sendUpdateGroupV2Message(group
,
1020 groupGroupChangePair
.first(),
1021 groupGroupChangePair
.second());
1026 if (resetGroupLink
) {
1027 var groupGroupChangePair
= groupV2Helper
.resetGroupLinkPassword(group
);
1028 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1031 if (groupLinkState
!= null) {
1032 var groupGroupChangePair
= groupV2Helper
.setGroupLinkState(group
, groupLinkState
);
1033 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1036 if (addMemberPermission
!= null) {
1037 var groupGroupChangePair
= groupV2Helper
.setAddMemberPermission(group
, addMemberPermission
);
1038 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1041 if (editDetailsPermission
!= null) {
1042 var groupGroupChangePair
= groupV2Helper
.setEditDetailsPermission(group
, editDetailsPermission
);
1043 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1046 if (expirationTimer
!= null) {
1047 var groupGroupChangePair
= groupV2Helper
.setMessageExpirationTimer(group
, expirationTimer
);
1048 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1051 if (name
!= null || description
!= null || avatarFile
!= null) {
1052 var groupGroupChangePair
= groupV2Helper
.updateGroup(group
, name
, description
, avatarFile
);
1053 if (avatarFile
!= null) {
1054 avatarStore
.storeGroupAvatar(group
.getGroupId(),
1055 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
1057 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1063 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
1064 GroupInviteLinkUrl inviteLinkUrl
1065 ) throws IOException
, GroupLinkNotActiveException
{
1066 final var groupJoinInfo
= groupV2Helper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
1067 inviteLinkUrl
.getPassword());
1068 final var groupChange
= groupV2Helper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
1069 inviteLinkUrl
.getPassword(),
1071 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
1072 groupJoinInfo
.getRevision() + 1,
1073 groupChange
.toByteArray());
1075 if (group
.getGroup() == null) {
1076 // Only requested member, can't send update to group members
1077 return new Pair
<>(group
.getGroupId(), List
.of());
1080 final var result
= sendUpdateGroupV2Message(group
, group
.getGroup(), groupChange
);
1082 return new Pair
<>(group
.getGroupId(), result
.second());
1085 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupV2Message(
1086 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
1087 ) throws IOException
{
1088 final var selfRecipientId
= account
.getSelfRecipientId();
1089 final var members
= group
.getMembersIncludingPendingWithout(selfRecipientId
);
1090 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
1091 members
.addAll(group
.getMembersIncludingPendingWithout(selfRecipientId
));
1093 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
1094 account
.getGroupStore().updateGroup(group
);
1095 return sendMessage(messageBuilder
, members
);
1098 private static int currentTimeDays() {
1099 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
1102 private GroupsV2AuthorizationString
getGroupAuthForToday(
1103 final GroupSecretParams groupSecretParams
1104 ) throws IOException
{
1105 final var today
= currentTimeDays();
1106 // Returns credentials for the next 7 days
1107 final var credentials
= dependencies
.getGroupsV2Api().getCredentials(today
);
1108 // TODO cache credentials until they expire
1109 var authCredentialResponse
= credentials
.get(today
);
1111 return dependencies
.getGroupsV2Api()
1112 .getGroupsV2AuthorizationString(account
.getUuid(),
1115 authCredentialResponse
);
1116 } catch (VerificationFailedException e
) {
1117 throw new IOException(e
);
1121 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
1122 GroupIdV1 groupId
, SignalServiceAddress recipient
1123 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
1125 var group
= getGroupForSending(groupId
);
1126 if (!(group
instanceof GroupInfoV1
)) {
1127 throw new RuntimeException("Received an invalid group request for a v2 group!");
1129 g
= (GroupInfoV1
) group
;
1131 final var recipientId
= resolveRecipient(recipient
);
1132 if (!g
.isMember(recipientId
)) {
1133 throw new NotAGroupMemberException(groupId
, g
.name
);
1136 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
1138 // Send group message only to the recipient who requested it
1139 return sendMessage(messageBuilder
, Set
.of(recipientId
));
1142 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
1143 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
1144 .withId(g
.getGroupId().serialize())
1146 .withMembers(g
.getMembers()
1148 .map(this::resolveSignalServiceAddress
)
1149 .collect(Collectors
.toList()));
1152 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
1153 if (attachment
.isPresent()) {
1154 group
.withAvatar(attachment
.get());
1156 } catch (IOException e
) {
1157 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
1160 return SignalServiceDataMessage
.newBuilder()
1161 .asGroupMessage(group
.build())
1162 .withExpiration(g
.getMessageExpirationTime());
1165 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
1166 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
1167 .withRevision(g
.getGroup().getRevision())
1168 .withSignedGroupChange(signedGroupChange
);
1169 return SignalServiceDataMessage
.newBuilder()
1170 .asGroupMessage(group
.build())
1171 .withExpiration(g
.getMessageExpirationTime());
1174 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
1175 GroupIdV1 groupId
, SignalServiceAddress recipient
1176 ) throws IOException
{
1177 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
1179 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
1181 // Send group info request message to the recipient who sent us a message with this groupId
1182 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1186 SignalServiceAddress remoteAddress
, long messageId
1187 ) throws IOException
, UntrustedIdentityException
{
1188 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1190 System
.currentTimeMillis());
1192 dependencies
.getMessageSender()
1193 .sendReceipt(remoteAddress
,
1194 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1198 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1199 String messageText
, List
<String
> attachments
, List
<String
> recipients
1200 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1201 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1202 if (attachments
!= null) {
1203 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1205 // Upload attachments here, so we only upload once even for multiple recipients
1206 var messageSender
= dependencies
.getMessageSender();
1207 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1208 for (var attachment
: attachmentStreams
) {
1209 if (attachment
.isStream()) {
1210 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1211 } else if (attachment
.isPointer()) {
1212 attachmentPointers
.add(attachment
.asPointer());
1216 messageBuilder
.withAttachments(attachmentPointers
);
1218 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1221 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1222 String messageText
, List
<String
> attachments
1223 ) throws IOException
, AttachmentInvalidException
{
1224 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1225 if (attachments
!= null) {
1226 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1228 return sendSelfMessage(messageBuilder
);
1231 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1232 long targetSentTimestamp
, List
<String
> recipients
1233 ) throws IOException
, InvalidNumberException
{
1234 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1235 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1236 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1239 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1240 long targetSentTimestamp
, GroupId groupId
1241 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1242 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1243 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1244 return sendGroupMessage(messageBuilder
, groupId
);
1247 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1248 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1249 ) throws IOException
, InvalidNumberException
{
1250 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1251 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1253 resolveSignalServiceAddress(targetAuthorRecipientId
),
1254 targetSentTimestamp
);
1255 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1256 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1259 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1260 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1262 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1264 return sendMessage(messageBuilder
, signalServiceAddresses
);
1265 } catch (Exception e
) {
1266 for (var address
: signalServiceAddresses
) {
1267 handleEndSession(address
);
1273 void renewSession(RecipientId recipientId
) throws IOException
{
1274 account
.getSessionStore().archiveSessions(recipientId
);
1275 if (!recipientId
.equals(getSelfRecipientId())) {
1276 sendNullMessage(recipientId
);
1280 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1281 if (!account
.isMasterDevice()) {
1282 throw new NotMasterDeviceException();
1284 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1285 var contact
= account
.getContactStore().getContact(recipientId
);
1286 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1287 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1290 public void setContactBlocked(
1291 String number
, boolean blocked
1292 ) throws InvalidNumberException
, NotMasterDeviceException
{
1293 if (!account
.isMasterDevice()) {
1294 throw new NotMasterDeviceException();
1296 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1299 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1300 var contact
= account
.getContactStore().getContact(recipientId
);
1301 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1302 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1305 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1306 var group
= getGroup(groupId
);
1307 if (group
== null) {
1308 throw new GroupNotFoundException(groupId
);
1311 group
.setBlocked(blocked
);
1312 account
.getGroupStore().updateGroup(group
);
1315 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1316 var contact
= account
.getContactStore().getContact(recipientId
);
1317 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1320 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1321 account
.getContactStore()
1322 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1325 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1326 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1327 sendMessage(messageBuilder
, Set
.of(recipientId
));
1331 * Change the expiration timer for a contact
1333 public void setExpirationTimer(
1334 String number
, int messageExpirationTimer
1335 ) throws IOException
, InvalidNumberException
{
1336 var recipientId
= canonicalizeAndResolveRecipient(number
);
1337 setExpirationTimer(recipientId
, messageExpirationTimer
);
1338 sendExpirationTimerUpdate(recipientId
);
1342 * Change the expiration timer for a group
1344 private void setExpirationTimer(
1345 GroupInfoV1 groupInfoV1
, int messageExpirationTimer
1346 ) throws NotAGroupMemberException
, GroupNotFoundException
, IOException
{
1347 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1348 account
.getGroupStore().updateGroup(groupInfoV1
);
1349 sendExpirationTimerUpdate(groupInfoV1
.getGroupId());
1352 private void sendExpirationTimerUpdate(GroupIdV1 groupId
) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1353 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1354 sendGroupMessage(messageBuilder
, groupId
);
1358 * Upload the sticker pack from path.
1360 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1361 * @return if successful, returns the URL to install the sticker pack in the signal app
1363 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1364 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1366 var messageSender
= dependencies
.getMessageSender();
1368 var packKey
= KeyUtils
.createStickerUploadKey();
1369 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1370 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
1372 var sticker
= new Sticker(packId
, packKey
);
1373 account
.getStickerStore().updateSticker(sticker
);
1376 return new URI("https",
1380 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
1382 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
)).toString();
1383 } catch (URISyntaxException e
) {
1384 throw new AssertionError(e
);
1388 public void requestAllSyncData() throws IOException
{
1389 requestSyncGroups();
1390 requestSyncContacts();
1391 requestSyncBlocked();
1392 requestSyncConfiguration();
1396 private void requestSyncGroups() throws IOException
{
1397 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1398 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1400 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1402 sendSyncMessage(message
);
1403 } catch (UntrustedIdentityException e
) {
1404 throw new AssertionError(e
);
1408 private void requestSyncContacts() throws IOException
{
1409 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1410 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1412 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1414 sendSyncMessage(message
);
1415 } catch (UntrustedIdentityException e
) {
1416 throw new AssertionError(e
);
1420 private void requestSyncBlocked() throws IOException
{
1421 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1422 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1424 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1426 sendSyncMessage(message
);
1427 } catch (UntrustedIdentityException e
) {
1428 throw new AssertionError(e
);
1432 private void requestSyncConfiguration() throws IOException
{
1433 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1434 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1436 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1438 sendSyncMessage(message
);
1439 } catch (UntrustedIdentityException e
) {
1440 throw new AssertionError(e
);
1444 private void requestSyncKeys() throws IOException
{
1445 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1446 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1448 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1450 sendSyncMessage(message
);
1451 } catch (UntrustedIdentityException e
) {
1452 throw new AssertionError(e
);
1456 private byte[] getSenderCertificate() {
1459 if (account
.isPhoneNumberShared()) {
1460 certificate
= dependencies
.getAccountManager().getSenderCertificate();
1462 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
1464 } catch (IOException e
) {
1465 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1468 // TODO cache for a day
1472 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1473 var messageSender
= dependencies
.getMessageSender();
1474 messageSender
.sendSyncMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1477 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1478 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1479 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1481 for (var number
: numbers
) {
1482 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1483 if (resolvedAddress
.getUuid().isPresent()) {
1484 signalServiceAddresses
.add(resolvedAddress
);
1486 addressesMissingUuid
.add(resolvedAddress
);
1490 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1491 .map(a
-> a
.getNumber().get())
1492 .collect(Collectors
.toSet());
1493 Map
<String
, UUID
> registeredUsers
;
1495 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1496 } catch (IOException e
) {
1497 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1498 registeredUsers
= Map
.of();
1501 for (var address
: addressesMissingUuid
) {
1502 final var number
= address
.getNumber().get();
1503 if (registeredUsers
.containsKey(number
)) {
1504 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1505 registeredUsers
.get(number
),
1507 signalServiceAddresses
.add(newAddress
);
1509 signalServiceAddresses
.add(address
);
1513 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1516 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1517 final var address
= resolveSignalServiceAddress(recipientId
);
1518 if (!address
.getNumber().isPresent()) {
1521 final var number
= address
.getNumber().get();
1522 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1523 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1526 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1528 return dependencies
.getAccountManager()
1529 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1531 serviceEnvironmentConfig
.getCdsMrenclave());
1532 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1533 throw new IOException(e
);
1537 public void sendTypingMessage(
1538 TypingAction action
, Set
<String
> recipients
1539 ) throws IOException
, UntrustedIdentityException
, InvalidNumberException
{
1540 sendTypingMessageInternal(action
, getSignalServiceAddresses(recipients
));
1543 private void sendTypingMessageInternal(
1544 TypingAction action
, Set
<RecipientId
> recipientIds
1545 ) throws IOException
, UntrustedIdentityException
{
1546 final var timestamp
= System
.currentTimeMillis();
1547 var message
= new SignalServiceTypingMessage(action
.toSignalService(), timestamp
, Optional
.absent());
1548 var messageSender
= dependencies
.getMessageSender();
1549 for (var recipientId
: recipientIds
) {
1550 final var address
= resolveSignalServiceAddress(recipientId
);
1551 messageSender
.sendTyping(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
), message
);
1555 public void sendGroupTypingMessage(
1556 TypingAction action
, GroupId groupId
1557 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1558 final var timestamp
= System
.currentTimeMillis();
1559 final var g
= getGroupForSending(groupId
);
1560 final var message
= new SignalServiceTypingMessage(action
.toSignalService(),
1562 Optional
.of(groupId
.serialize()));
1563 final var messageSender
= dependencies
.getMessageSender();
1564 final var recipientIdList
= new ArrayList
<>(g
.getMembersWithout(account
.getSelfRecipientId()));
1565 final var addresses
= recipientIdList
.stream()
1566 .map(this::resolveSignalServiceAddress
)
1567 .collect(Collectors
.toList());
1568 messageSender
.sendTyping(addresses
, unidentifiedAccessHelper
.getAccessFor(recipientIdList
), message
, null);
1571 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1572 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1573 ) throws IOException
{
1574 final var timestamp
= System
.currentTimeMillis();
1575 messageBuilder
.withTimestamp(timestamp
);
1577 SignalServiceDataMessage message
= null;
1579 message
= messageBuilder
.build();
1580 if (message
.getGroupContext().isPresent()) {
1582 var messageSender
= dependencies
.getMessageSender();
1583 final var isRecipientUpdate
= false;
1584 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1585 final var addresses
= recipientIdList
.stream()
1586 .map(this::resolveSignalServiceAddress
)
1587 .collect(Collectors
.toList());
1588 var result
= messageSender
.sendDataMessage(addresses
,
1589 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1591 ContentHint
.DEFAULT
,
1593 sendResult
-> logger
.trace("Partial message send result: {}", sendResult
.isSuccess()),
1596 for (var r
: result
) {
1597 if (r
.getIdentityFailure() != null) {
1598 final var recipientId
= resolveRecipient(r
.getAddress());
1599 final var newIdentity
= account
.getIdentityKeyStore()
1600 .saveIdentity(recipientId
, r
.getIdentityFailure().getIdentityKey(), new Date());
1602 account
.getSessionStore().archiveSessions(recipientId
);
1607 return new Pair
<>(timestamp
, result
);
1608 } catch (UntrustedIdentityException e
) {
1609 return new Pair
<>(timestamp
, List
.of());
1612 // Send to all individually, so sync messages are sent correctly
1613 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1614 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1615 for (var recipientId
: recipientIds
) {
1616 final var contact
= account
.getContactStore().getContact(recipientId
);
1617 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1618 messageBuilder
.withExpiration(expirationTime
);
1619 message
= messageBuilder
.build();
1620 results
.add(sendMessage(recipientId
, message
));
1622 return new Pair
<>(timestamp
, results
);
1625 if (message
!= null && message
.isEndSession()) {
1626 for (var recipient
: recipientIds
) {
1627 handleEndSession(recipient
);
1633 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1634 SignalServiceDataMessage
.Builder messageBuilder
1635 ) throws IOException
{
1636 final var timestamp
= System
.currentTimeMillis();
1637 messageBuilder
.withTimestamp(timestamp
);
1638 final var recipientId
= account
.getSelfRecipientId();
1640 final var contact
= account
.getContactStore().getContact(recipientId
);
1641 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1642 messageBuilder
.withExpiration(expirationTime
);
1644 var message
= messageBuilder
.build();
1645 final var result
= sendSelfMessage(message
);
1646 return new Pair
<>(timestamp
, result
);
1649 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1650 var messageSender
= dependencies
.getMessageSender();
1652 var recipientId
= account
.getSelfRecipientId();
1654 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipientId
);
1655 var recipient
= resolveSignalServiceAddress(recipientId
);
1656 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1657 message
.getTimestamp(),
1659 message
.getExpiresInSeconds(),
1660 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1662 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1665 return messageSender
.sendSyncMessage(syncMessage
, unidentifiedAccess
);
1666 } catch (UntrustedIdentityException e
) {
1667 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1671 private SendMessageResult
sendMessage(
1672 RecipientId recipientId
, SignalServiceDataMessage message
1673 ) throws IOException
{
1674 var messageSender
= dependencies
.getMessageSender();
1676 final var address
= resolveSignalServiceAddress(recipientId
);
1679 return messageSender
.sendDataMessage(address
,
1680 unidentifiedAccessHelper
.getAccessFor(recipientId
),
1681 ContentHint
.DEFAULT
,
1683 } catch (UnregisteredUserException e
) {
1684 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1685 return messageSender
.sendDataMessage(resolveSignalServiceAddress(newRecipientId
),
1686 unidentifiedAccessHelper
.getAccessFor(newRecipientId
),
1687 ContentHint
.DEFAULT
,
1690 } catch (UntrustedIdentityException e
) {
1691 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1695 private SendMessageResult
sendNullMessage(RecipientId recipientId
) throws IOException
{
1696 var messageSender
= dependencies
.getMessageSender();
1698 final var address
= resolveSignalServiceAddress(recipientId
);
1701 return messageSender
.sendNullMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
));
1702 } catch (UnregisteredUserException e
) {
1703 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1704 final var newAddress
= resolveSignalServiceAddress(newRecipientId
);
1705 return messageSender
.sendNullMessage(newAddress
, unidentifiedAccessHelper
.getAccessFor(newRecipientId
));
1707 } catch (UntrustedIdentityException e
) {
1708 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1712 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, ProtocolUntrustedIdentityException
, InvalidMessageStructureException
{
1713 return dependencies
.getCipher().decrypt(envelope
);
1716 private void handleEndSession(RecipientId recipientId
) {
1717 account
.getSessionStore().deleteAllSessions(recipientId
);
1720 private List
<HandleAction
> handleSignalServiceDataMessage(
1721 SignalServiceDataMessage message
,
1723 SignalServiceAddress source
,
1724 SignalServiceAddress destination
,
1725 boolean ignoreAttachments
1727 var actions
= new ArrayList
<HandleAction
>();
1728 if (message
.getGroupContext().isPresent()) {
1729 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1730 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1731 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1732 var group
= getGroup(groupId
);
1733 if (group
== null || group
instanceof GroupInfoV1
) {
1734 var groupV1
= (GroupInfoV1
) group
;
1735 switch (groupInfo
.getType()) {
1737 if (groupV1
== null) {
1738 groupV1
= new GroupInfoV1(groupId
);
1741 if (groupInfo
.getAvatar().isPresent()) {
1742 var avatar
= groupInfo
.getAvatar().get();
1743 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1746 if (groupInfo
.getName().isPresent()) {
1747 groupV1
.name
= groupInfo
.getName().get();
1750 if (groupInfo
.getMembers().isPresent()) {
1751 groupV1
.addMembers(groupInfo
.getMembers()
1754 .map(this::resolveRecipient
)
1755 .collect(Collectors
.toSet()));
1758 account
.getGroupStore().updateGroup(groupV1
);
1762 if (groupV1
== null && !isSync
) {
1763 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1767 if (groupV1
!= null) {
1768 groupV1
.removeMember(resolveRecipient(source
));
1769 account
.getGroupStore().updateGroup(groupV1
);
1774 if (groupV1
!= null && !isSync
) {
1775 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1780 // Received a group v1 message for a v2 group
1783 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1784 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1785 final var groupMasterKey
= groupContext
.getMasterKey();
1787 getOrMigrateGroup(groupMasterKey
,
1788 groupContext
.getRevision(),
1789 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1793 final var conversationPartnerAddress
= isSync ? destination
: source
;
1794 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1795 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1797 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1798 if (message
.getGroupContext().isPresent()) {
1799 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1800 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1801 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1802 if (group
!= null) {
1803 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1804 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1805 account
.getGroupStore().updateGroup(group
);
1808 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1809 // disappearing message timer already stored in the DecryptedGroup
1811 } else if (conversationPartnerAddress
!= null) {
1812 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1815 if (!ignoreAttachments
) {
1816 if (message
.getAttachments().isPresent()) {
1817 for (var attachment
: message
.getAttachments().get()) {
1818 downloadAttachment(attachment
);
1821 if (message
.getSharedContacts().isPresent()) {
1822 for (var contact
: message
.getSharedContacts().get()) {
1823 if (contact
.getAvatar().isPresent()) {
1824 downloadAttachment(contact
.getAvatar().get().getAttachment());
1829 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1830 final ProfileKey profileKey
;
1832 profileKey
= new ProfileKey(message
.getProfileKey().get());
1833 } catch (InvalidInputException e
) {
1834 throw new AssertionError(e
);
1836 if (source
.matches(account
.getSelfAddress())) {
1837 this.account
.setProfileKey(profileKey
);
1839 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1841 if (message
.getPreviews().isPresent()) {
1842 final var previews
= message
.getPreviews().get();
1843 for (var preview
: previews
) {
1844 if (preview
.getImage().isPresent()) {
1845 downloadAttachment(preview
.getImage().get());
1849 if (message
.getQuote().isPresent()) {
1850 final var quote
= message
.getQuote().get();
1852 for (var quotedAttachment
: quote
.getAttachments()) {
1853 final var thumbnail
= quotedAttachment
.getThumbnail();
1854 if (thumbnail
!= null) {
1855 downloadAttachment(thumbnail
);
1859 if (message
.getSticker().isPresent()) {
1860 final var messageSticker
= message
.getSticker().get();
1861 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1862 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1863 if (sticker
== null) {
1864 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1865 account
.getStickerStore().updateSticker(sticker
);
1867 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, messageSticker
.getPackKey()));
1872 private GroupInfoV2
getOrMigrateGroup(
1873 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1875 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1877 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1878 var groupInfo
= getGroup(groupId
);
1879 final GroupInfoV2 groupInfoV2
;
1880 if (groupInfo
instanceof GroupInfoV1
) {
1881 // Received a v2 group message for a v1 group, we need to locally migrate the group
1882 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1883 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1884 logger
.info("Locally migrated group {} to group v2, id: {}",
1885 groupInfo
.getGroupId().toBase64(),
1886 groupInfoV2
.getGroupId().toBase64());
1887 } else if (groupInfo
instanceof GroupInfoV2
) {
1888 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1890 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1893 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1894 DecryptedGroup group
= null;
1895 if (signedGroupChange
!= null
1896 && groupInfoV2
.getGroup() != null
1897 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1898 group
= groupV2Helper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(),
1902 if (group
== null) {
1903 group
= groupV2Helper
.getDecryptedGroup(groupSecretParams
);
1905 if (group
!= null) {
1906 storeProfileKeysFromMembers(group
);
1907 final var avatar
= group
.getAvatar();
1908 if (avatar
!= null && !avatar
.isEmpty()) {
1909 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1912 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1913 account
.getGroupStore().updateGroup(groupInfoV2
);
1919 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1920 for (var member
: group
.getMembersList()) {
1921 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
1922 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
1924 account
.getProfileStore()
1925 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
1926 } catch (InvalidInputException ignored
) {
1931 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1932 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1933 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1934 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1935 if (actions
!= null) {
1936 queuedActions
.addAll(actions
);
1939 for (var action
: queuedActions
) {
1941 action
.execute(this);
1942 } catch (Throwable e
) {
1943 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1944 Thread
.currentThread().interrupt();
1946 logger
.warn("Message action failed.", e
);
1951 private List
<HandleAction
> retryFailedReceivedMessage(
1952 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1954 var envelope
= cachedMessage
.loadEnvelope();
1955 if (envelope
== null) {
1958 SignalServiceContent content
= null;
1959 List
<HandleAction
> actions
= null;
1960 if (!envelope
.isReceipt()) {
1962 content
= decryptMessage(envelope
);
1963 } catch (ProtocolUntrustedIdentityException e
) {
1964 if (!envelope
.hasSource()) {
1965 final var identifier
= e
.getSender();
1966 final var recipientId
= resolveRecipient(identifier
);
1968 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1969 } catch (IOException ioException
) {
1970 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1974 } catch (Exception er
) {
1975 // All other errors are not recoverable, so delete the cached message
1976 cachedMessage
.delete();
1979 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1981 handler
.handleMessage(envelope
, content
, null);
1982 cachedMessage
.delete();
1986 public void receiveMessages(
1989 boolean returnOnTimeout
,
1990 boolean ignoreAttachments
,
1991 ReceiveMessageHandler handler
1992 ) throws IOException
, InterruptedException
{
1993 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1995 Set
<HandleAction
> queuedActions
= null;
1997 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1998 signalWebSocket
.connect();
2000 var hasCaughtUpWithOldMessages
= false;
2002 while (!Thread
.interrupted()) {
2003 SignalServiceEnvelope envelope
;
2004 SignalServiceContent content
= null;
2005 Exception exception
= null;
2006 final CachedMessage
[] cachedMessage
= {null};
2007 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
2008 logger
.debug("Checking for new message from server");
2010 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
2011 final var recipientId
= envelope1
.hasSource()
2012 ?
resolveRecipient(envelope1
.getSourceIdentifier())
2014 // store message on disk, before acknowledging receipt to the server
2015 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
2017 logger
.debug("New message received from server");
2018 if (result
.isPresent()) {
2019 envelope
= result
.get();
2021 // Received indicator that server queue is empty
2022 hasCaughtUpWithOldMessages
= true;
2024 if (queuedActions
!= null) {
2025 for (var action
: queuedActions
) {
2027 action
.execute(this);
2028 } catch (Throwable e
) {
2029 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
2030 Thread
.currentThread().interrupt();
2032 logger
.warn("Message action failed.", e
);
2035 queuedActions
.clear();
2036 queuedActions
= null;
2039 // Continue to wait another timeout for new messages
2042 } catch (AssertionError e
) {
2043 if (e
.getCause() instanceof InterruptedException
) {
2044 throw (InterruptedException
) e
.getCause();
2048 } catch (WebSocketUnavailableException e
) {
2049 logger
.debug("Pipe unexpectedly unavailable, connecting");
2050 signalWebSocket
.connect();
2052 } catch (TimeoutException e
) {
2053 if (returnOnTimeout
) return;
2057 if (envelope
.hasSource()) {
2058 // Store uuid if we don't have it already
2059 // address/uuid in envelope is sent by server
2060 resolveRecipientTrusted(envelope
.getSourceAddress());
2062 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
2063 if (!envelope
.isReceipt()) {
2065 content
= decryptMessage(envelope
);
2066 } catch (Exception e
) {
2069 if (!envelope
.hasSource() && content
!= null) {
2070 // Store uuid if we don't have it already
2071 // address/uuid is validated by unidentified sender certificate
2072 resolveRecipientTrusted(content
.getSender());
2074 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
2075 if (exception
instanceof ProtocolInvalidMessageException
) {
2076 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
2077 logger
.debug("Received invalid message, queuing renew session action.");
2078 actions
.add(new RenewSessionAction(sender
));
2080 if (hasCaughtUpWithOldMessages
) {
2081 for (var action
: actions
) {
2083 action
.execute(this);
2084 } catch (Throwable e
) {
2085 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
2086 Thread
.currentThread().interrupt();
2088 logger
.warn("Message action failed.", e
);
2092 if (queuedActions
== null) {
2093 queuedActions
= new HashSet
<>();
2095 queuedActions
.addAll(actions
);
2098 if (isMessageBlocked(envelope
, content
)) {
2099 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
2100 } else if (notAGroupMember
) {
2101 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
2103 handler
.handleMessage(envelope
, content
, exception
);
2105 if (cachedMessage
[0] != null) {
2106 if (exception
instanceof ProtocolUntrustedIdentityException
) {
2107 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
2108 final var recipientId
= resolveRecipient(identifier
);
2109 queuedActions
.add(new RetrieveProfileAction(recipientId
));
2110 if (!envelope
.hasSource()) {
2112 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
2113 } catch (IOException ioException
) {
2114 logger
.warn("Failed to move cached message to recipient folder: {}",
2115 ioException
.getMessage());
2119 cachedMessage
[0].delete();
2125 private boolean isMessageBlocked(
2126 SignalServiceEnvelope envelope
, SignalServiceContent content
2128 SignalServiceAddress source
;
2129 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2130 source
= envelope
.getSourceAddress();
2131 } else if (content
!= null) {
2132 source
= content
.getSender();
2136 final var recipientId
= resolveRecipient(source
);
2137 if (isContactBlocked(recipientId
)) {
2141 if (content
!= null && content
.getDataMessage().isPresent()) {
2142 var message
= content
.getDataMessage().get();
2143 if (message
.getGroupContext().isPresent()) {
2144 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2145 var group
= getGroup(groupId
);
2146 if (group
!= null && group
.isBlocked()) {
2154 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
2155 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
2156 return isContactBlocked(recipientId
);
2159 private boolean isContactBlocked(final RecipientId recipientId
) {
2160 var sourceContact
= account
.getContactStore().getContact(recipientId
);
2161 return sourceContact
!= null && sourceContact
.isBlocked();
2164 private boolean isNotAGroupMember(
2165 SignalServiceEnvelope envelope
, SignalServiceContent content
2167 SignalServiceAddress source
;
2168 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2169 source
= envelope
.getSourceAddress();
2170 } else if (content
!= null) {
2171 source
= content
.getSender();
2176 if (content
!= null && content
.getDataMessage().isPresent()) {
2177 var message
= content
.getDataMessage().get();
2178 if (message
.getGroupContext().isPresent()) {
2179 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
2180 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
2181 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
2185 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2186 var group
= getGroup(groupId
);
2187 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
2195 private List
<HandleAction
> handleMessage(
2196 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
2198 var actions
= new ArrayList
<HandleAction
>();
2199 if (content
!= null) {
2200 final SignalServiceAddress sender
;
2201 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2202 sender
= envelope
.getSourceAddress();
2204 sender
= content
.getSender();
2207 if (content
.getDataMessage().isPresent()) {
2208 var message
= content
.getDataMessage().get();
2210 if (content
.isNeedsReceipt()) {
2211 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
2214 actions
.addAll(handleSignalServiceDataMessage(message
,
2217 account
.getSelfAddress(),
2218 ignoreAttachments
));
2220 if (content
.getSyncMessage().isPresent()) {
2221 account
.setMultiDevice(true);
2222 var syncMessage
= content
.getSyncMessage().get();
2223 if (syncMessage
.getSent().isPresent()) {
2224 var message
= syncMessage
.getSent().get();
2225 final var destination
= message
.getDestination().orNull();
2226 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
2230 ignoreAttachments
));
2232 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
2233 var rm
= syncMessage
.getRequest().get();
2234 if (rm
.isContactsRequest()) {
2235 actions
.add(SendSyncContactsAction
.create());
2237 if (rm
.isGroupsRequest()) {
2238 actions
.add(SendSyncGroupsAction
.create());
2240 if (rm
.isBlockedListRequest()) {
2241 actions
.add(SendSyncBlockedListAction
.create());
2243 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2245 if (syncMessage
.getGroups().isPresent()) {
2246 File tmpFile
= null;
2248 tmpFile
= IOUtils
.createTempFile();
2249 final var groupsMessage
= syncMessage
.getGroups().get();
2250 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2251 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2256 } catch (IOException e
) {
2257 logger
.warn("Sync groups contained invalid group, ignoring: {}", e
.getMessage());
2263 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2264 if (syncGroup
!= null) {
2265 if (g
.getName().isPresent()) {
2266 syncGroup
.name
= g
.getName().get();
2268 syncGroup
.addMembers(g
.getMembers()
2270 .map(this::resolveRecipient
)
2271 .collect(Collectors
.toSet()));
2272 if (!g
.isActive()) {
2273 syncGroup
.removeMember(account
.getSelfRecipientId());
2275 // Add ourself to the member set as it's marked as active
2276 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2278 syncGroup
.blocked
= g
.isBlocked();
2279 if (g
.getColor().isPresent()) {
2280 syncGroup
.color
= g
.getColor().get();
2283 if (g
.getAvatar().isPresent()) {
2284 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2286 syncGroup
.archived
= g
.isArchived();
2287 account
.getGroupStore().updateGroup(syncGroup
);
2291 } catch (Exception e
) {
2292 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2296 if (tmpFile
!= null) {
2298 Files
.delete(tmpFile
.toPath());
2299 } catch (IOException e
) {
2300 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2307 if (syncMessage
.getBlockedList().isPresent()) {
2308 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2309 for (var address
: blockedListMessage
.getAddresses()) {
2310 setContactBlocked(resolveRecipient(address
), true);
2312 for (var groupId
: blockedListMessage
.getGroupIds()
2314 .map(GroupId
::unknownVersion
)
2315 .collect(Collectors
.toSet())) {
2317 setGroupBlocked(groupId
, true);
2318 } catch (GroupNotFoundException e
) {
2319 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2320 groupId
.toBase64());
2324 if (syncMessage
.getContacts().isPresent()) {
2325 File tmpFile
= null;
2327 tmpFile
= IOUtils
.createTempFile();
2328 final var contactsMessage
= syncMessage
.getContacts().get();
2329 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2330 .asPointer(), tmpFile
)) {
2331 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2336 } catch (IOException e
) {
2337 logger
.warn("Sync contacts contained invalid contact, ignoring: {}",
2344 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2345 account
.setProfileKey(c
.getProfileKey().get());
2347 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2348 var contact
= account
.getContactStore().getContact(recipientId
);
2349 final var builder
= contact
== null
2350 ? Contact
.newBuilder()
2351 : Contact
.newBuilder(contact
);
2352 if (c
.getName().isPresent()) {
2353 builder
.withName(c
.getName().get());
2355 if (c
.getColor().isPresent()) {
2356 builder
.withColor(c
.getColor().get());
2358 if (c
.getProfileKey().isPresent()) {
2359 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2361 if (c
.getVerified().isPresent()) {
2362 final var verifiedMessage
= c
.getVerified().get();
2363 account
.getIdentityKeyStore()
2364 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2365 verifiedMessage
.getIdentityKey(),
2366 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2368 if (c
.getExpirationTimer().isPresent()) {
2369 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2371 builder
.withBlocked(c
.isBlocked());
2372 builder
.withArchived(c
.isArchived());
2373 account
.getContactStore().storeContact(recipientId
, builder
.build());
2375 if (c
.getAvatar().isPresent()) {
2376 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2380 } catch (Exception e
) {
2381 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2385 if (tmpFile
!= null) {
2387 Files
.delete(tmpFile
.toPath());
2388 } catch (IOException e
) {
2389 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2396 if (syncMessage
.getVerified().isPresent()) {
2397 final var verifiedMessage
= syncMessage
.getVerified().get();
2398 account
.getIdentityKeyStore()
2399 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2400 verifiedMessage
.getIdentityKey(),
2401 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2403 if (syncMessage
.getStickerPackOperations().isPresent()) {
2404 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2405 for (var m
: stickerPackOperationMessages
) {
2406 if (!m
.getPackId().isPresent()) {
2409 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2410 final var installed
= !m
.getType().isPresent()
2411 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
;
2413 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2414 if (m
.getPackKey().isPresent()) {
2415 if (sticker
== null) {
2416 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2419 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, m
.getPackKey().get()));
2423 if (sticker
!= null) {
2424 sticker
.setInstalled(installed
);
2425 account
.getStickerStore().updateSticker(sticker
);
2429 if (syncMessage
.getFetchType().isPresent()) {
2430 switch (syncMessage
.getFetchType().get()) {
2432 getRecipientProfile(account
.getSelfRecipientId(), true);
2433 case STORAGE_MANIFEST
:
2437 if (syncMessage
.getKeys().isPresent()) {
2438 final var keysMessage
= syncMessage
.getKeys().get();
2439 if (keysMessage
.getStorageService().isPresent()) {
2440 final var storageKey
= keysMessage
.getStorageService().get();
2441 account
.setStorageKey(storageKey
);
2444 if (syncMessage
.getConfiguration().isPresent()) {
2452 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2454 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2455 } catch (IOException e
) {
2456 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2460 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2462 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2463 } catch (IOException e
) {
2464 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2468 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2470 avatarStore
.storeGroupAvatar(groupId
,
2471 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2472 } catch (IOException e
) {
2473 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2477 private void downloadProfileAvatar(
2478 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2481 avatarStore
.storeProfileAvatar(address
,
2482 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2483 } catch (Throwable e
) {
2484 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
2485 Thread
.currentThread().interrupt();
2487 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2491 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2492 return attachmentStore
.getAttachmentFile(attachmentId
);
2495 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2496 if (!attachment
.isPointer()) {
2497 logger
.warn("Invalid state, can't store an attachment stream.");
2500 var pointer
= attachment
.asPointer();
2501 if (pointer
.getPreview().isPresent()) {
2502 final var preview
= pointer
.getPreview().get();
2504 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2505 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2506 } catch (IOException e
) {
2507 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2512 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2513 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2514 } catch (IOException e
) {
2515 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2519 private void retrieveGroupV2Avatar(
2520 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2521 ) throws IOException
{
2522 var groupOperations
= dependencies
.getGroupsV2Operations().forGroup(groupSecretParams
);
2524 var tmpFile
= IOUtils
.createTempFile();
2525 try (InputStream input
= dependencies
.getMessageReceiver()
2526 .retrieveGroupsV2ProfileAvatar(cdnKey
, tmpFile
, ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2527 var encryptedData
= IOUtils
.readFully(input
);
2529 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2530 outputStream
.write(decryptedData
);
2533 Files
.delete(tmpFile
.toPath());
2534 } catch (IOException e
) {
2535 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2542 private void retrieveProfileAvatar(
2543 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2544 ) throws IOException
{
2545 var tmpFile
= IOUtils
.createTempFile();
2546 try (var input
= dependencies
.getMessageReceiver()
2547 .retrieveProfileAvatar(avatarPath
,
2550 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2551 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2552 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2555 Files
.delete(tmpFile
.toPath());
2556 } catch (IOException e
) {
2557 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2564 private void retrieveAttachment(
2565 final SignalServiceAttachment attachment
, final OutputStream outputStream
2566 ) throws IOException
{
2567 if (attachment
.isPointer()) {
2568 var pointer
= attachment
.asPointer();
2569 retrieveAttachmentPointer(pointer
, outputStream
);
2571 var stream
= attachment
.asStream();
2572 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2576 private void retrieveAttachmentPointer(
2577 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2578 ) throws IOException
{
2579 var tmpFile
= IOUtils
.createTempFile();
2580 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2581 IOUtils
.copyStream(input
, outputStream
);
2582 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2583 throw new IOException(e
);
2586 Files
.delete(tmpFile
.toPath());
2587 } catch (IOException e
) {
2588 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2595 private InputStream
retrieveAttachmentAsStream(
2596 SignalServiceAttachmentPointer pointer
, File tmpFile
2597 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2598 return dependencies
.getMessageReceiver()
2599 .retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2602 void sendGroups() throws IOException
, UntrustedIdentityException
{
2603 var groupsFile
= IOUtils
.createTempFile();
2606 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2607 var out
= new DeviceGroupsOutputStream(fos
);
2608 for (var record : getGroups()) {
2609 if (record instanceof GroupInfoV1
) {
2610 var groupInfo
= (GroupInfoV1
) record;
2611 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2612 Optional
.fromNullable(groupInfo
.name
),
2613 groupInfo
.getMembers()
2615 .map(this::resolveSignalServiceAddress
)
2616 .collect(Collectors
.toList()),
2617 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2618 groupInfo
.isMember(account
.getSelfRecipientId()),
2619 Optional
.of(groupInfo
.messageExpirationTime
),
2620 Optional
.fromNullable(groupInfo
.color
),
2623 groupInfo
.archived
));
2628 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2629 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2630 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2631 .withStream(groupsFileStream
)
2632 .withContentType("application/octet-stream")
2633 .withLength(groupsFile
.length())
2636 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2641 Files
.delete(groupsFile
.toPath());
2642 } catch (IOException e
) {
2643 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2648 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2649 var contactsFile
= IOUtils
.createTempFile();
2652 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2653 var out
= new DeviceContactsOutputStream(fos
);
2654 for (var contactPair
: account
.getContactStore().getContacts()) {
2655 final var recipientId
= contactPair
.first();
2656 final var contact
= contactPair
.second();
2657 final var address
= resolveSignalServiceAddress(recipientId
);
2659 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2660 VerifiedMessage verifiedMessage
= null;
2661 if (currentIdentity
!= null) {
2662 verifiedMessage
= new VerifiedMessage(address
,
2663 currentIdentity
.getIdentityKey(),
2664 currentIdentity
.getTrustLevel().toVerifiedState(),
2665 currentIdentity
.getDateAdded().getTime());
2668 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2669 out
.write(new DeviceContact(address
,
2670 Optional
.fromNullable(contact
.getName()),
2671 createContactAvatarAttachment(address
),
2672 Optional
.fromNullable(contact
.getColor()),
2673 Optional
.fromNullable(verifiedMessage
),
2674 Optional
.fromNullable(profileKey
),
2675 contact
.isBlocked(),
2676 Optional
.of(contact
.getMessageExpirationTime()),
2678 contact
.isArchived()));
2681 if (account
.getProfileKey() != null) {
2682 // Send our own profile key as well
2683 out
.write(new DeviceContact(account
.getSelfAddress(),
2688 Optional
.of(account
.getProfileKey()),
2696 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2697 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2698 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2699 .withStream(contactsFileStream
)
2700 .withContentType("application/octet-stream")
2701 .withLength(contactsFile
.length())
2704 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2709 Files
.delete(contactsFile
.toPath());
2710 } catch (IOException e
) {
2711 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2716 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2717 var addresses
= new ArrayList
<SignalServiceAddress
>();
2718 for (var record : account
.getContactStore().getContacts()) {
2719 if (record.second().isBlocked()) {
2720 addresses
.add(resolveSignalServiceAddress(record.first()));
2723 var groupIds
= new ArrayList
<byte[]>();
2724 for (var record : getGroups()) {
2725 if (record.isBlocked()) {
2726 groupIds
.add(record.getGroupId().serialize());
2729 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2732 private void sendVerifiedMessage(
2733 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2734 ) throws IOException
, UntrustedIdentityException
{
2735 var verifiedMessage
= new VerifiedMessage(destination
,
2737 trustLevel
.toVerifiedState(),
2738 System
.currentTimeMillis());
2739 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2742 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2743 return account
.getContactStore().getContacts();
2746 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2747 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2748 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2749 if (recipient
== null) {
2753 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2754 return recipient
.getContact().getName();
2757 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2758 return recipient
.getProfile().getDisplayName();
2764 public GroupInfo
getGroup(GroupId groupId
) {
2765 return getGroup(groupId
, false);
2768 public GroupInfo
getGroup(GroupId groupId
, boolean forceUpdate
) {
2769 final var group
= account
.getGroupStore().getGroup(groupId
);
2770 if (group
instanceof GroupInfoV2
&& (forceUpdate
|| ((GroupInfoV2
) group
).getGroup() == null)) {
2771 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2772 ((GroupInfoV2
) group
).setGroup(groupV2Helper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2773 account
.getGroupStore().updateGroup(group
);
2778 public List
<IdentityInfo
> getIdentities() {
2779 return account
.getIdentityKeyStore().getIdentities();
2782 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2783 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2784 return identity
== null ? List
.of() : List
.of(identity
);
2788 * Trust this the identity with this fingerprint
2790 * @param name username of the identity
2791 * @param fingerprint Fingerprint
2793 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2794 var recipientId
= canonicalizeAndResolveRecipient(name
);
2795 return trustIdentity(recipientId
,
2796 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2797 TrustLevel
.TRUSTED_VERIFIED
);
2801 * Trust this the identity with this safety number
2803 * @param name username of the identity
2804 * @param safetyNumber Safety number
2806 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2807 var recipientId
= canonicalizeAndResolveRecipient(name
);
2808 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2809 return trustIdentity(recipientId
,
2810 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2811 TrustLevel
.TRUSTED_VERIFIED
);
2815 * Trust all keys of this identity without verification
2817 * @param name username of the identity
2819 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2820 var recipientId
= canonicalizeAndResolveRecipient(name
);
2821 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2824 private boolean trustIdentity(
2825 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2827 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2828 if (identity
== null) {
2832 if (!verifier
.apply(identity
.getIdentityKey())) {
2836 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2838 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2839 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2840 } catch (IOException
| UntrustedIdentityException e
) {
2841 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2847 public String
computeSafetyNumber(
2848 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2850 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2851 account
.getSelfAddress(),
2852 getIdentityKeyPair().getPublicKey(),
2858 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2859 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2861 return resolveSignalServiceAddress(address
);
2865 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2866 if (address
.matches(account
.getSelfAddress())) {
2867 return account
.getSelfAddress();
2870 return account
.getRecipientStore().resolveServiceAddress(address
);
2873 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2874 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2877 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2878 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2880 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2882 return resolveRecipient(canonicalizedNumber
);
2885 private RecipientId
resolveRecipient(final String identifier
) {
2886 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2888 return resolveRecipient(address
);
2891 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2892 return account
.getRecipientStore().resolveRecipient(address
);
2895 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2896 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2899 private void enqueueJob(Job job
) {
2900 var context
= new Context(account
,
2901 dependencies
.getAccountManager(),
2902 dependencies
.getMessageReceiver(),
2908 public void close() throws IOException
{
2912 void close(boolean closeAccount
) throws IOException
{
2913 executor
.shutdown();
2915 dependencies
.getSignalWebSocket().disconnect();
2917 if (closeAccount
&& account
!= null) {
2923 public interface ReceiveMessageHandler
{
2925 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);