2 Copyright (C) 2015-2021 AsamK and contributors
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.signal
.manager
.api
.Device
;
20 import org
.asamk
.signal
.manager
.api
.TypingAction
;
21 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
22 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
23 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
24 import org
.asamk
.signal
.manager
.groups
.GroupId
;
25 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
26 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
27 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
28 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
29 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
30 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
31 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
32 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
33 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
34 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
35 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
36 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
37 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
38 import org
.asamk
.signal
.manager
.jobs
.Context
;
39 import org
.asamk
.signal
.manager
.jobs
.Job
;
40 import org
.asamk
.signal
.manager
.jobs
.RetrieveStickerPackJob
;
41 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
42 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
43 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
44 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
45 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
46 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
47 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
48 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
49 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
50 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
51 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
52 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
53 import org
.asamk
.signal
.manager
.util
.IOUtils
;
54 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
55 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
56 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
57 import org
.asamk
.signal
.manager
.util
.Utils
;
58 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
59 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
60 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
61 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
62 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
63 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
64 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
65 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
66 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
67 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
68 import org
.signal
.libsignal
.metadata
.SelfSendException
;
69 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
70 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
71 import org
.signal
.zkgroup
.InvalidInputException
;
72 import org
.signal
.zkgroup
.VerificationFailedException
;
73 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
74 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
75 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
76 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
77 import org
.slf4j
.Logger
;
78 import org
.slf4j
.LoggerFactory
;
79 import org
.whispersystems
.libsignal
.IdentityKey
;
80 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
81 import org
.whispersystems
.libsignal
.InvalidKeyException
;
82 import org
.whispersystems
.libsignal
.InvalidMessageException
;
83 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
84 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
85 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
86 import org
.whispersystems
.libsignal
.util
.Pair
;
87 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
88 import org
.whispersystems
.signalservice
.api
.InvalidMessageStructureException
;
89 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
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
.SignalServiceSyncMessage
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
117 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
118 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
119 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
120 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.ConflictException
;
121 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
122 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
123 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
124 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
125 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
126 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
127 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
128 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
129 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
130 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
131 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
132 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
133 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
134 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
136 import java
.io
.Closeable
;
138 import java
.io
.FileInputStream
;
139 import java
.io
.FileOutputStream
;
140 import java
.io
.IOException
;
141 import java
.io
.InputStream
;
142 import java
.io
.OutputStream
;
144 import java
.net
.URISyntaxException
;
145 import java
.net
.URLEncoder
;
146 import java
.nio
.charset
.StandardCharsets
;
147 import java
.nio
.file
.Files
;
148 import java
.security
.SignatureException
;
149 import java
.util
.ArrayList
;
150 import java
.util
.Arrays
;
151 import java
.util
.Base64
;
152 import java
.util
.Collection
;
153 import java
.util
.Date
;
154 import java
.util
.HashSet
;
155 import java
.util
.List
;
156 import java
.util
.Map
;
157 import java
.util
.Set
;
158 import java
.util
.UUID
;
159 import java
.util
.concurrent
.ExecutorService
;
160 import java
.util
.concurrent
.Executors
;
161 import java
.util
.concurrent
.TimeUnit
;
162 import java
.util
.concurrent
.TimeoutException
;
163 import java
.util
.concurrent
.locks
.ReentrantLock
;
164 import java
.util
.function
.Function
;
165 import java
.util
.stream
.Collectors
;
167 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
169 public class Manager
implements Closeable
{
171 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
173 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
174 private final SignalDependencies dependencies
;
176 private SignalAccount account
;
178 private final ExecutorService executor
= Executors
.newCachedThreadPool();
180 private final ProfileHelper profileHelper
;
181 private final GroupV2Helper groupV2Helper
;
182 private final PinHelper pinHelper
;
183 private final SendHelper sendHelper
;
185 private final AvatarStore avatarStore
;
186 private final AttachmentStore attachmentStore
;
187 private final StickerPackStore stickerPackStore
;
188 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
189 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
192 public Lock
acquire() {
194 return LEGACY_LOCK
::unlock
;
199 SignalAccount account
,
200 PathConfig pathConfig
,
201 ServiceEnvironmentConfig serviceEnvironmentConfig
,
204 this.account
= account
;
205 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
207 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
208 account
.getUsername(),
209 account
.getPassword(),
210 account
.getDeviceId());
211 this.dependencies
= new SignalDependencies(account
.getSelfAddress(),
212 serviceEnvironmentConfig
,
215 account
.getSignalProtocolStore(),
218 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
220 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
221 account
.getProfileStore()::getProfileKey
,
222 this::getRecipientProfile
,
223 this::getSenderCertificate
);
224 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
225 unidentifiedAccessHelper
::getAccessFor
,
226 dependencies
::getProfileService
,
227 dependencies
::getMessageReceiver
,
228 this::resolveSignalServiceAddress
);
229 this.groupV2Helper
= new GroupV2Helper(this::getRecipientProfileKeyCredential
,
230 this::getRecipientProfile
,
231 account
::getSelfRecipientId
,
232 dependencies
.getGroupsV2Operations(),
233 dependencies
.getGroupsV2Api(),
234 this::getGroupAuthForToday
,
235 this::resolveSignalServiceAddress
);
236 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
237 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
238 this.stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
239 this.sendHelper
= new SendHelper(account
,
241 unidentifiedAccessHelper
,
242 this::resolveSignalServiceAddress
,
243 this::resolveRecipient
,
244 this::handleIdentityFailure
,
246 this::refreshRegisteredUser
);
249 public String
getUsername() {
250 return account
.getUsername();
253 public SignalServiceAddress
getSelfAddress() {
254 return account
.getSelfAddress();
257 public RecipientId
getSelfRecipientId() {
258 return account
.getSelfRecipientId();
261 private IdentityKeyPair
getIdentityKeyPair() {
262 return account
.getIdentityKeyPair();
265 public int getDeviceId() {
266 return account
.getDeviceId();
269 public static Manager
init(
270 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
271 ) throws IOException
, NotRegisteredException
{
272 var pathConfig
= PathConfig
.createDefault(settingsPath
);
274 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
275 throw new NotRegisteredException();
278 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true);
280 if (!account
.isRegistered()) {
281 throw new NotRegisteredException();
284 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
286 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
289 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
290 var pathConfig
= PathConfig
.createDefault(settingsPath
);
291 final var dataPath
= pathConfig
.getDataPath();
292 final var files
= dataPath
.listFiles();
298 return Arrays
.stream(files
)
299 .filter(File
::isFile
)
301 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
302 .collect(Collectors
.toList());
305 public void checkAccountState() throws IOException
{
306 if (account
.getLastReceiveTimestamp() == 0) {
307 logger
.warn("The Signal protocol expects that incoming messages are regularly received.");
309 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
310 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
313 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
317 if (dependencies
.getAccountManager().getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
320 if (account
.getUuid() == null) {
321 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
323 updateAccountAttributes();
327 * This is used for checking a set of phone numbers for registration on Signal
329 * @param numbers The set of phone number in question
330 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
331 * @throws IOException if its unable to get the contacts to check if they're registered
333 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
334 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
335 var contactDetails
= getRegisteredUsers(numbers
);
337 var registeredUsers
= contactDetails
.keySet();
339 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
342 public void updateAccountAttributes() throws IOException
{
343 dependencies
.getAccountManager()
344 .setAccountAttributes(account
.getEncryptedDeviceName(),
346 account
.getLocalRegistrationId(),
348 // set legacy pin only if no KBS master key is set
349 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
350 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
351 account
.getSelfUnidentifiedAccessKey(),
352 account
.isUnrestrictedUnidentifiedAccess(),
354 account
.isDiscoverableByPhoneNumber());
358 * @param givenName if null, the previous givenName will be kept
359 * @param familyName if null, the previous familyName will be kept
360 * @param about if null, the previous about text will be kept
361 * @param aboutEmoji if null, the previous about emoji will be kept
362 * @param avatar if avatar is null the image from the local avatar store is used (if present),
364 public void setProfile(
365 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
366 ) throws IOException
{
367 var profile
= getRecipientProfile(account
.getSelfRecipientId());
368 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
369 if (givenName
!= null) {
370 builder
.withGivenName(givenName
);
372 if (familyName
!= null) {
373 builder
.withFamilyName(familyName
);
376 builder
.withAbout(about
);
378 if (aboutEmoji
!= null) {
379 builder
.withAboutEmoji(aboutEmoji
);
381 var newProfile
= builder
.build();
383 try (final var streamDetails
= avatar
== null
384 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
385 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
386 dependencies
.getAccountManager()
387 .setVersionedProfile(account
.getUuid(),
388 account
.getProfileKey(),
389 newProfile
.getInternalServiceName(),
390 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
391 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
396 if (avatar
!= null) {
397 if (avatar
.isPresent()) {
398 avatarStore
.storeProfileAvatar(getSelfAddress(),
399 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
401 avatarStore
.deleteProfileAvatar(getSelfAddress());
404 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
406 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
409 public void unregister() throws IOException
{
410 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
411 // If this is the master device, other users can't send messages to this number anymore.
412 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
413 dependencies
.getAccountManager().setGcmId(Optional
.absent());
415 account
.setRegistered(false);
418 public void deleteAccount() throws IOException
{
419 dependencies
.getAccountManager().deleteAccount();
421 account
.setRegistered(false);
424 public List
<Device
> getLinkedDevices() throws IOException
{
425 var devices
= dependencies
.getAccountManager().getDevices();
426 account
.setMultiDevice(devices
.size() > 1);
427 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
428 return devices
.stream().map(d
-> {
429 String deviceName
= d
.getName();
430 if (deviceName
!= null) {
432 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
433 } catch (IOException e
) {
434 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
437 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
438 }).collect(Collectors
.toList());
441 public void removeLinkedDevices(int deviceId
) throws IOException
{
442 dependencies
.getAccountManager().removeDevice(deviceId
);
443 var devices
= dependencies
.getAccountManager().getDevices();
444 account
.setMultiDevice(devices
.size() > 1);
447 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
448 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
450 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
453 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
454 var identityKeyPair
= getIdentityKeyPair();
455 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
457 dependencies
.getAccountManager()
458 .addDevice(deviceIdentifier
,
461 Optional
.of(account
.getProfileKey().serialize()),
463 account
.setMultiDevice(true);
466 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
467 if (!account
.isMasterDevice()) {
468 throw new RuntimeException("Only master device can set a PIN");
470 if (pin
.isPresent()) {
471 final var masterKey
= account
.getPinMasterKey() != null
472 ? account
.getPinMasterKey()
473 : KeyUtils
.createMasterKey();
475 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
477 account
.setRegistrationLockPin(pin
.get(), masterKey
);
480 pinHelper
.removeRegistrationLockPin();
482 account
.setRegistrationLockPin(null, null);
486 void refreshPreKeys() throws IOException
{
487 var oneTimePreKeys
= generatePreKeys();
488 final var identityKeyPair
= getIdentityKeyPair();
489 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
491 dependencies
.getAccountManager().setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
494 private List
<PreKeyRecord
> generatePreKeys() {
495 final var offset
= account
.getPreKeyIdOffset();
497 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
498 account
.addPreKeys(records
);
503 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
504 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
506 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
507 account
.addSignedPreKey(record);
512 public Profile
getRecipientProfile(
513 RecipientId recipientId
515 return getRecipientProfile(recipientId
, false);
518 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
520 Profile
getRecipientProfile(
521 RecipientId recipientId
, boolean force
523 var profile
= account
.getProfileStore().getProfile(recipientId
);
525 var now
= System
.currentTimeMillis();
526 // Profiles are cached for 24h before retrieving them again, unless forced
527 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
531 synchronized (pendingProfileRequest
) {
532 if (pendingProfileRequest
.contains(recipientId
)) {
535 pendingProfileRequest
.add(recipientId
);
537 final SignalServiceProfile encryptedProfile
;
539 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
541 synchronized (pendingProfileRequest
) {
542 pendingProfileRequest
.remove(recipientId
);
545 if (encryptedProfile
== null) {
549 profile
= decryptProfileIfKeyKnown(recipientId
, encryptedProfile
);
550 account
.getProfileStore().storeProfile(recipientId
, profile
);
555 private Profile
decryptProfileIfKeyKnown(
556 final RecipientId recipientId
, final SignalServiceProfile encryptedProfile
558 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
559 if (profileKey
== null) {
560 return new Profile(System
.currentTimeMillis(),
565 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
566 ProfileUtils
.getCapabilities(encryptedProfile
));
569 return decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
572 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
574 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
575 } catch (IOException e
) {
576 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
581 private ProfileAndCredential
retrieveProfileAndCredential(
582 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
583 ) throws IOException
{
584 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
585 final var profile
= profileAndCredential
.getProfile();
588 var newIdentity
= account
.getIdentityKeyStore()
589 .saveIdentity(recipientId
,
590 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
594 account
.getSessionStore().archiveSessions(recipientId
);
596 } catch (InvalidKeyException ignored
) {
597 logger
.warn("Got invalid identity key in profile for {}",
598 resolveSignalServiceAddress(recipientId
).getIdentifier());
600 return profileAndCredential
;
603 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
604 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
605 if (profileKeyCredential
!= null) {
606 return profileKeyCredential
;
609 ProfileAndCredential profileAndCredential
;
611 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
612 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
613 } catch (IOException e
) {
614 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
618 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
619 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
621 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
622 if (profileKey
!= null) {
623 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
625 profileAndCredential
.getProfile());
626 account
.getProfileStore().storeProfile(recipientId
, profile
);
629 return profileKeyCredential
;
632 private Profile
decryptProfileAndDownloadAvatar(
633 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
635 if (encryptedProfile
.getAvatar() != null) {
636 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
639 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
642 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
643 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
644 if (streamDetails
== null) {
645 return Optional
.absent();
648 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
651 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
652 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
653 if (streamDetails
== null) {
654 return Optional
.absent();
657 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
660 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
661 var g
= getGroup(groupId
);
663 throw new GroupNotFoundException(groupId
);
665 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
666 throw new NotAGroupMemberException(groupId
, g
.getTitle());
671 public List
<GroupInfo
> getGroups() {
672 return account
.getGroupStore().getGroups();
675 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
676 String messageText
, List
<String
> attachments
, GroupId groupId
677 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
678 final var messageBuilder
= createMessageBuilder().withBody(messageText
);
679 if (attachments
!= null) {
680 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
683 return sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
686 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
687 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
688 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
689 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
690 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
692 resolveSignalServiceAddress(targetAuthorRecipientId
),
693 targetSentTimestamp
);
694 final var messageBuilder
= createMessageBuilder().withReaction(reaction
);
696 return sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
699 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(
700 GroupId groupId
, Set
<String
> groupAdmins
701 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, InvalidNumberException
, LastGroupAdminException
{
702 var group
= getGroupForUpdating(groupId
);
703 if (group
instanceof GroupInfoV1
) {
704 return quitGroupV1((GroupInfoV1
) group
);
707 final var newAdmins
= getRecipientIds(groupAdmins
);
709 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
710 } catch (ConflictException e
) {
711 // Detected conflicting update, refreshing group and trying again
712 group
= getGroup(groupId
, true);
713 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
717 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV1(final GroupInfoV1 groupInfoV1
) throws IOException
{
718 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
719 .withId(groupInfoV1
.getGroupId().serialize())
722 var messageBuilder
= createMessageBuilder().asGroupMessage(group
);
723 groupInfoV1
.removeMember(account
.getSelfRecipientId());
724 account
.getGroupStore().updateGroup(groupInfoV1
);
725 return sendHelper
.sendGroupMessage(messageBuilder
.build(),
726 groupInfoV1
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
729 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV2(
730 final GroupInfoV2 groupInfoV2
, final Set
<RecipientId
> newAdmins
731 ) throws LastGroupAdminException
, IOException
{
732 final var currentAdmins
= groupInfoV2
.getAdminMembers();
733 newAdmins
.removeAll(currentAdmins
);
734 newAdmins
.retainAll(groupInfoV2
.getMembers());
735 if (currentAdmins
.contains(getSelfRecipientId())
736 && currentAdmins
.size() == 1
737 && groupInfoV2
.getMembers().size() > 1
738 && newAdmins
.size() == 0) {
739 // Last admin can't leave the group, unless she's also the last member
740 throw new LastGroupAdminException(groupInfoV2
.getGroupId(), groupInfoV2
.getTitle());
742 final var groupGroupChangePair
= groupV2Helper
.leaveGroup(groupInfoV2
, newAdmins
);
743 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
744 var messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
745 account
.getGroupStore().updateGroup(groupInfoV2
);
746 return sendHelper
.sendGroupMessage(messageBuilder
.build(),
747 groupInfoV2
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
750 public void deleteGroup(GroupId groupId
) throws IOException
{
751 account
.getGroupStore().deleteGroup(groupId
);
752 avatarStore
.deleteGroupAvatar(groupId
);
755 public Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
756 String name
, List
<String
> members
, File avatarFile
757 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
758 return createGroup(name
, members
== null ?
null : getRecipientIds(members
), avatarFile
);
761 private Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
762 String name
, Set
<RecipientId
> members
, File avatarFile
763 ) throws IOException
, AttachmentInvalidException
{
764 final var selfRecipientId
= account
.getSelfRecipientId();
765 if (members
!= null && members
.contains(selfRecipientId
)) {
766 members
= new HashSet
<>(members
);
767 members
.remove(selfRecipientId
);
770 var gv2Pair
= groupV2Helper
.createGroup(name
== null ?
"" : name
,
771 members
== null ? Set
.of() : members
,
774 SignalServiceDataMessage
.Builder messageBuilder
;
775 if (gv2Pair
== null) {
776 // Failed to create v2 group, creating v1 group instead
777 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
778 gv1
.addMembers(List
.of(selfRecipientId
));
779 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
780 return new Pair
<>(gv1
.getGroupId(), result
.second());
783 final var gv2
= gv2Pair
.first();
784 final var decryptedGroup
= gv2Pair
.second();
786 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
787 if (avatarFile
!= null) {
788 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
789 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
791 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
792 account
.getGroupStore().updateGroup(gv2
);
794 final var result
= sendHelper
.sendGroupMessage(messageBuilder
.build(),
795 gv2
.getMembersIncludingPendingWithout(selfRecipientId
));
796 return new Pair
<>(gv2
.getGroupId(), result
.second());
799 public Pair
<Long
, List
<SendMessageResult
>> updateGroup(
803 List
<String
> members
,
804 List
<String
> removeMembers
,
806 List
<String
> removeAdmins
,
807 boolean resetGroupLink
,
808 GroupLinkState groupLinkState
,
809 GroupPermission addMemberPermission
,
810 GroupPermission editDetailsPermission
,
812 Integer expirationTimer
813 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
814 return updateGroup(groupId
,
817 members
== null ?
null : getRecipientIds(members
),
818 removeMembers
== null ?
null : getRecipientIds(removeMembers
),
819 admins
== null ?
null : getRecipientIds(admins
),
820 removeAdmins
== null ?
null : getRecipientIds(removeAdmins
),
824 editDetailsPermission
,
829 private Pair
<Long
, List
<SendMessageResult
>> updateGroup(
830 final GroupId groupId
,
832 final String description
,
833 final Set
<RecipientId
> members
,
834 final Set
<RecipientId
> removeMembers
,
835 final Set
<RecipientId
> admins
,
836 final Set
<RecipientId
> removeAdmins
,
837 final boolean resetGroupLink
,
838 final GroupLinkState groupLinkState
,
839 final GroupPermission addMemberPermission
,
840 final GroupPermission editDetailsPermission
,
841 final File avatarFile
,
842 final Integer expirationTimer
843 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
844 var group
= getGroupForUpdating(groupId
);
846 if (group
instanceof GroupInfoV2
) {
848 return updateGroupV2((GroupInfoV2
) group
,
858 editDetailsPermission
,
861 } catch (ConflictException e
) {
862 // Detected conflicting update, refreshing group and trying again
863 group
= getGroup(groupId
, true);
864 return updateGroupV2((GroupInfoV2
) group
,
874 editDetailsPermission
,
880 final var gv1
= (GroupInfoV1
) group
;
881 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
882 if (expirationTimer
!= null) {
883 setExpirationTimer(gv1
, expirationTimer
);
888 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV1(
889 final GroupInfoV1 gv1
, final String name
, final Set
<RecipientId
> members
, final File avatarFile
890 ) throws IOException
, AttachmentInvalidException
{
891 updateGroupV1Details(gv1
, name
, members
, avatarFile
);
892 var messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
894 account
.getGroupStore().updateGroup(gv1
);
896 return sendHelper
.sendGroupMessage(messageBuilder
.build(),
897 gv1
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
900 private void updateGroupV1Details(
901 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
902 ) throws IOException
{
907 if (members
!= null) {
908 final var newMemberAddresses
= members
.stream()
909 .filter(member
-> !g
.isMember(member
))
910 .map(this::resolveSignalServiceAddress
)
911 .collect(Collectors
.toList());
912 final var newE164Members
= new HashSet
<String
>();
913 for (var member
: newMemberAddresses
) {
914 if (!member
.getNumber().isPresent()) {
917 newE164Members
.add(member
.getNumber().get());
920 final var registeredUsers
= getRegisteredUsers(newE164Members
);
921 if (registeredUsers
.size() != newE164Members
.size()) {
922 // Some of the new members are not registered on Signal
923 newE164Members
.removeAll(registeredUsers
.keySet());
924 throw new IOException("Failed to add members "
925 + String
.join(", ", newE164Members
)
926 + " to group: Not registered on Signal");
929 g
.addMembers(members
);
932 if (avatarFile
!= null) {
933 avatarStore
.storeGroupAvatar(g
.getGroupId(),
934 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
938 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV2(
939 final GroupInfoV2 group
,
941 final String description
,
942 final Set
<RecipientId
> members
,
943 final Set
<RecipientId
> removeMembers
,
944 final Set
<RecipientId
> admins
,
945 final Set
<RecipientId
> removeAdmins
,
946 final boolean resetGroupLink
,
947 final GroupLinkState groupLinkState
,
948 final GroupPermission addMemberPermission
,
949 final GroupPermission editDetailsPermission
,
950 final File avatarFile
,
951 Integer expirationTimer
952 ) throws IOException
{
953 Pair
<Long
, List
<SendMessageResult
>> result
= null;
954 if (group
.isPendingMember(account
.getSelfRecipientId())) {
955 var groupGroupChangePair
= groupV2Helper
.acceptInvite(group
);
956 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
959 if (members
!= null) {
960 final var newMembers
= new HashSet
<>(members
);
961 newMembers
.removeAll(group
.getMembers());
962 if (newMembers
.size() > 0) {
963 var groupGroupChangePair
= groupV2Helper
.addMembers(group
, newMembers
);
964 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
968 if (removeMembers
!= null) {
969 var existingRemoveMembers
= new HashSet
<>(removeMembers
);
970 existingRemoveMembers
.retainAll(group
.getMembers());
971 existingRemoveMembers
.remove(getSelfRecipientId());// self can be removed with sendQuitGroupMessage
972 if (existingRemoveMembers
.size() > 0) {
973 var groupGroupChangePair
= groupV2Helper
.removeMembers(group
, existingRemoveMembers
);
974 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
977 var pendingRemoveMembers
= new HashSet
<>(removeMembers
);
978 pendingRemoveMembers
.retainAll(group
.getPendingMembers());
979 if (pendingRemoveMembers
.size() > 0) {
980 var groupGroupChangePair
= groupV2Helper
.revokeInvitedMembers(group
, pendingRemoveMembers
);
981 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
985 if (admins
!= null) {
986 final var newAdmins
= new HashSet
<>(admins
);
987 newAdmins
.retainAll(group
.getMembers());
988 newAdmins
.removeAll(group
.getAdminMembers());
989 if (newAdmins
.size() > 0) {
990 for (var admin
: newAdmins
) {
991 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, true);
992 result
= sendUpdateGroupV2Message(group
,
993 groupGroupChangePair
.first(),
994 groupGroupChangePair
.second());
999 if (removeAdmins
!= null) {
1000 final var existingRemoveAdmins
= new HashSet
<>(removeAdmins
);
1001 existingRemoveAdmins
.retainAll(group
.getAdminMembers());
1002 if (existingRemoveAdmins
.size() > 0) {
1003 for (var admin
: existingRemoveAdmins
) {
1004 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, false);
1005 result
= sendUpdateGroupV2Message(group
,
1006 groupGroupChangePair
.first(),
1007 groupGroupChangePair
.second());
1012 if (resetGroupLink
) {
1013 var groupGroupChangePair
= groupV2Helper
.resetGroupLinkPassword(group
);
1014 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1017 if (groupLinkState
!= null) {
1018 var groupGroupChangePair
= groupV2Helper
.setGroupLinkState(group
, groupLinkState
);
1019 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1022 if (addMemberPermission
!= null) {
1023 var groupGroupChangePair
= groupV2Helper
.setAddMemberPermission(group
, addMemberPermission
);
1024 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1027 if (editDetailsPermission
!= null) {
1028 var groupGroupChangePair
= groupV2Helper
.setEditDetailsPermission(group
, editDetailsPermission
);
1029 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1032 if (expirationTimer
!= null) {
1033 var groupGroupChangePair
= groupV2Helper
.setMessageExpirationTimer(group
, expirationTimer
);
1034 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1037 if (name
!= null || description
!= null || avatarFile
!= null) {
1038 var groupGroupChangePair
= groupV2Helper
.updateGroup(group
, name
, description
, avatarFile
);
1039 if (avatarFile
!= null) {
1040 avatarStore
.storeGroupAvatar(group
.getGroupId(),
1041 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
1043 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1049 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
1050 GroupInviteLinkUrl inviteLinkUrl
1051 ) throws IOException
, GroupLinkNotActiveException
{
1052 final var groupJoinInfo
= groupV2Helper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
1053 inviteLinkUrl
.getPassword());
1054 final var groupChange
= groupV2Helper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
1055 inviteLinkUrl
.getPassword(),
1057 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
1058 groupJoinInfo
.getRevision() + 1,
1059 groupChange
.toByteArray());
1061 if (group
.getGroup() == null) {
1062 // Only requested member, can't send update to group members
1063 return new Pair
<>(group
.getGroupId(), List
.of());
1066 final var result
= sendUpdateGroupV2Message(group
, group
.getGroup(), groupChange
);
1068 return new Pair
<>(group
.getGroupId(), result
.second());
1071 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupV2Message(
1072 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
1073 ) throws IOException
{
1074 final var selfRecipientId
= account
.getSelfRecipientId();
1075 final var members
= group
.getMembersIncludingPendingWithout(selfRecipientId
);
1076 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
1077 members
.addAll(group
.getMembersIncludingPendingWithout(selfRecipientId
));
1079 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
1080 account
.getGroupStore().updateGroup(group
);
1081 return sendHelper
.sendGroupMessage(messageBuilder
.build(), members
);
1084 private static int currentTimeDays() {
1085 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
1088 private GroupsV2AuthorizationString
getGroupAuthForToday(
1089 final GroupSecretParams groupSecretParams
1090 ) throws IOException
{
1091 final var today
= currentTimeDays();
1092 // Returns credentials for the next 7 days
1093 final var credentials
= dependencies
.getGroupsV2Api().getCredentials(today
);
1094 // TODO cache credentials until they expire
1095 var authCredentialResponse
= credentials
.get(today
);
1097 return dependencies
.getGroupsV2Api()
1098 .getGroupsV2AuthorizationString(account
.getUuid(),
1101 authCredentialResponse
);
1102 } catch (VerificationFailedException e
) {
1103 throw new IOException(e
);
1107 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
1108 GroupIdV1 groupId
, SignalServiceAddress recipient
1109 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
1111 var group
= getGroupForUpdating(groupId
);
1112 if (!(group
instanceof GroupInfoV1
)) {
1113 throw new IOException("Received an invalid group request for a v2 group!");
1115 g
= (GroupInfoV1
) group
;
1117 final var recipientId
= resolveRecipient(recipient
);
1118 if (!g
.isMember(recipientId
)) {
1119 throw new NotAGroupMemberException(groupId
, g
.name
);
1122 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
1124 // Send group message only to the recipient who requested it
1125 return sendHelper
.sendGroupMessage(messageBuilder
.build(), Set
.of(recipientId
));
1128 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
1129 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
1130 .withId(g
.getGroupId().serialize())
1132 .withMembers(g
.getMembers()
1134 .map(this::resolveSignalServiceAddress
)
1135 .collect(Collectors
.toList()));
1138 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
1139 if (attachment
.isPresent()) {
1140 group
.withAvatar(attachment
.get());
1142 } catch (IOException e
) {
1143 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
1146 return createMessageBuilder().asGroupMessage(group
.build()).withExpiration(g
.getMessageExpirationTime());
1149 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
1150 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
1151 .withRevision(g
.getGroup().getRevision())
1152 .withSignedGroupChange(signedGroupChange
);
1153 return createMessageBuilder().asGroupMessage(group
.build()).withExpiration(g
.getMessageExpirationTime());
1156 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
1157 GroupIdV1 groupId
, SignalServiceAddress recipient
1158 ) throws IOException
{
1159 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
1161 var messageBuilder
= createMessageBuilder().asGroupMessage(group
.build());
1163 // Send group info request message to the recipient who sent us a message with this groupId
1164 return sendHelper
.sendGroupMessage(messageBuilder
.build(), Set
.of(resolveRecipient(recipient
)));
1168 SignalServiceAddress remoteAddress
, long messageId
1169 ) throws IOException
, UntrustedIdentityException
{
1170 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1172 System
.currentTimeMillis());
1174 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(remoteAddress
));
1177 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1178 String messageText
, List
<String
> attachments
, List
<String
> recipients
1179 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1180 final var messageBuilder
= createMessageBuilder().withBody(messageText
);
1181 if (attachments
!= null) {
1182 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1184 // Upload attachments here, so we only upload once even for multiple recipients
1185 var messageSender
= dependencies
.getMessageSender();
1186 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1187 for (var attachment
: attachmentStreams
) {
1188 if (attachment
.isStream()) {
1189 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1190 } else if (attachment
.isPointer()) {
1191 attachmentPointers
.add(attachment
.asPointer());
1195 messageBuilder
.withAttachments(attachmentPointers
);
1197 return sendHelper
.sendMessage(messageBuilder
, getRecipientIds(recipients
));
1200 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1201 String messageText
, List
<String
> attachments
1202 ) throws IOException
, AttachmentInvalidException
{
1203 final var messageBuilder
= createMessageBuilder().withBody(messageText
);
1204 if (attachments
!= null) {
1205 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1207 return sendHelper
.sendSelfMessage(messageBuilder
);
1210 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1211 long targetSentTimestamp
, List
<String
> recipients
1212 ) throws IOException
, InvalidNumberException
{
1213 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1214 final var messageBuilder
= createMessageBuilder().withRemoteDelete(delete
);
1215 return sendHelper
.sendMessage(messageBuilder
, getRecipientIds(recipients
));
1218 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1219 long targetSentTimestamp
, GroupId groupId
1220 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1221 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1222 final var messageBuilder
= createMessageBuilder().withRemoteDelete(delete
);
1223 return sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
1226 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1227 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1228 ) throws IOException
, InvalidNumberException
{
1229 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1230 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1232 resolveSignalServiceAddress(targetAuthorRecipientId
),
1233 targetSentTimestamp
);
1234 final var messageBuilder
= createMessageBuilder().withReaction(reaction
);
1235 return sendHelper
.sendMessage(messageBuilder
, getRecipientIds(recipients
));
1238 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1239 var messageBuilder
= createMessageBuilder().asEndSessionMessage();
1241 final var recipientIds
= getRecipientIds(recipients
);
1243 return sendHelper
.sendMessage(messageBuilder
, recipientIds
);
1245 for (var recipientId
: recipientIds
) {
1246 handleEndSession(recipientId
);
1251 void renewSession(RecipientId recipientId
) throws IOException
{
1252 account
.getSessionStore().archiveSessions(recipientId
);
1253 if (!recipientId
.equals(getSelfRecipientId())) {
1254 sendHelper
.sendNullMessage(recipientId
);
1258 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1259 if (!account
.isMasterDevice()) {
1260 throw new NotMasterDeviceException();
1262 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1263 var contact
= account
.getContactStore().getContact(recipientId
);
1264 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1265 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1268 public void setContactBlocked(
1269 String number
, boolean blocked
1270 ) throws InvalidNumberException
, NotMasterDeviceException
{
1271 if (!account
.isMasterDevice()) {
1272 throw new NotMasterDeviceException();
1274 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1277 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1278 var contact
= account
.getContactStore().getContact(recipientId
);
1279 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1280 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1283 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1284 var group
= getGroup(groupId
);
1285 if (group
== null) {
1286 throw new GroupNotFoundException(groupId
);
1289 group
.setBlocked(blocked
);
1290 account
.getGroupStore().updateGroup(group
);
1293 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1294 var contact
= account
.getContactStore().getContact(recipientId
);
1295 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1298 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1299 account
.getContactStore()
1300 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1303 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1304 final var messageBuilder
= createMessageBuilder().asExpirationUpdate();
1305 sendHelper
.sendMessage(messageBuilder
, Set
.of(recipientId
));
1309 * Change the expiration timer for a contact
1311 public void setExpirationTimer(
1312 String number
, int messageExpirationTimer
1313 ) throws IOException
, InvalidNumberException
{
1314 var recipientId
= canonicalizeAndResolveRecipient(number
);
1315 setExpirationTimer(recipientId
, messageExpirationTimer
);
1316 sendExpirationTimerUpdate(recipientId
);
1320 * Change the expiration timer for a group
1322 private void setExpirationTimer(
1323 GroupInfoV1 groupInfoV1
, int messageExpirationTimer
1324 ) throws NotAGroupMemberException
, GroupNotFoundException
, IOException
{
1325 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1326 account
.getGroupStore().updateGroup(groupInfoV1
);
1327 sendExpirationTimerUpdate(groupInfoV1
.getGroupId());
1330 private void sendExpirationTimerUpdate(GroupIdV1 groupId
) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1331 final var messageBuilder
= createMessageBuilder().asExpirationUpdate();
1332 sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
1336 * Upload the sticker pack from path.
1338 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1339 * @return if successful, returns the URL to install the sticker pack in the signal app
1341 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1342 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1344 var messageSender
= dependencies
.getMessageSender();
1346 var packKey
= KeyUtils
.createStickerUploadKey();
1347 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1348 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
1350 var sticker
= new Sticker(packId
, packKey
);
1351 account
.getStickerStore().updateSticker(sticker
);
1354 return new URI("https",
1358 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
1360 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
)).toString();
1361 } catch (URISyntaxException e
) {
1362 throw new AssertionError(e
);
1366 public void requestAllSyncData() throws IOException
{
1367 requestSyncGroups();
1368 requestSyncContacts();
1369 requestSyncBlocked();
1370 requestSyncConfiguration();
1374 private void requestSyncGroups() throws IOException
{
1375 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1376 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1378 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1379 sendHelper
.sendSyncMessage(message
);
1382 private void requestSyncContacts() throws IOException
{
1383 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1384 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1386 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1387 sendHelper
.sendSyncMessage(message
);
1390 private void requestSyncBlocked() throws IOException
{
1391 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1392 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1394 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1395 sendHelper
.sendSyncMessage(message
);
1398 private void requestSyncConfiguration() throws IOException
{
1399 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1400 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1402 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1403 sendHelper
.sendSyncMessage(message
);
1406 private void requestSyncKeys() throws IOException
{
1407 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1408 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1410 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1411 sendHelper
.sendSyncMessage(message
);
1414 private byte[] getSenderCertificate() {
1417 if (account
.isPhoneNumberShared()) {
1418 certificate
= dependencies
.getAccountManager().getSenderCertificate();
1420 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
1422 } catch (IOException e
) {
1423 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1426 // TODO cache for a day
1430 private Set
<RecipientId
> getRecipientIds(Collection
<String
> numbers
) throws InvalidNumberException
{
1431 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1432 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1434 for (var number
: numbers
) {
1435 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1436 if (resolvedAddress
.getUuid().isPresent()) {
1437 signalServiceAddresses
.add(resolvedAddress
);
1439 addressesMissingUuid
.add(resolvedAddress
);
1443 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1444 .map(a
-> a
.getNumber().get())
1445 .collect(Collectors
.toSet());
1446 Map
<String
, UUID
> registeredUsers
;
1448 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1449 } catch (IOException e
) {
1450 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1451 registeredUsers
= Map
.of();
1454 for (var address
: addressesMissingUuid
) {
1455 final var number
= address
.getNumber().get();
1456 if (registeredUsers
.containsKey(number
)) {
1457 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1458 registeredUsers
.get(number
),
1460 signalServiceAddresses
.add(newAddress
);
1462 signalServiceAddresses
.add(address
);
1466 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1469 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1470 final var address
= resolveSignalServiceAddress(recipientId
);
1471 if (!address
.getNumber().isPresent()) {
1474 final var number
= address
.getNumber().get();
1475 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1476 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1479 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1481 return dependencies
.getAccountManager()
1482 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1484 serviceEnvironmentConfig
.getCdsMrenclave());
1485 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1486 throw new IOException(e
);
1490 public void sendTypingMessage(
1491 TypingAction action
, Set
<String
> recipients
1492 ) throws IOException
, UntrustedIdentityException
, InvalidNumberException
{
1493 final var timestamp
= System
.currentTimeMillis();
1494 var message
= new SignalServiceTypingMessage(action
.toSignalService(), timestamp
, Optional
.absent());
1495 sendHelper
.sendTypingMessage(message
, getRecipientIds(recipients
));
1498 public void sendGroupTypingMessage(
1499 TypingAction action
, GroupId groupId
1500 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1501 final var timestamp
= System
.currentTimeMillis();
1502 final var message
= new SignalServiceTypingMessage(action
.toSignalService(),
1504 Optional
.of(groupId
.serialize()));
1505 sendHelper
.sendGroupTypingMessage(message
, groupId
);
1508 private SignalServiceDataMessage
.Builder
createMessageBuilder() {
1509 final var timestamp
= System
.currentTimeMillis();
1511 var messageBuilder
= SignalServiceDataMessage
.newBuilder();
1512 messageBuilder
.withTimestamp(timestamp
);
1513 return messageBuilder
;
1516 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, ProtocolUntrustedIdentityException
, InvalidMessageStructureException
{
1517 return dependencies
.getCipher().decrypt(envelope
);
1520 private void handleEndSession(RecipientId recipientId
) {
1521 account
.getSessionStore().deleteAllSessions(recipientId
);
1524 private List
<HandleAction
> handleSignalServiceDataMessage(
1525 SignalServiceDataMessage message
,
1527 SignalServiceAddress source
,
1528 SignalServiceAddress destination
,
1529 boolean ignoreAttachments
1531 var actions
= new ArrayList
<HandleAction
>();
1532 if (message
.getGroupContext().isPresent()) {
1533 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1534 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1535 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1536 var group
= getGroup(groupId
);
1537 if (group
== null || group
instanceof GroupInfoV1
) {
1538 var groupV1
= (GroupInfoV1
) group
;
1539 switch (groupInfo
.getType()) {
1541 if (groupV1
== null) {
1542 groupV1
= new GroupInfoV1(groupId
);
1545 if (groupInfo
.getAvatar().isPresent()) {
1546 var avatar
= groupInfo
.getAvatar().get();
1547 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1550 if (groupInfo
.getName().isPresent()) {
1551 groupV1
.name
= groupInfo
.getName().get();
1554 if (groupInfo
.getMembers().isPresent()) {
1555 groupV1
.addMembers(groupInfo
.getMembers()
1558 .map(this::resolveRecipient
)
1559 .collect(Collectors
.toSet()));
1562 account
.getGroupStore().updateGroup(groupV1
);
1566 if (groupV1
== null && !isSync
) {
1567 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1571 if (groupV1
!= null) {
1572 groupV1
.removeMember(resolveRecipient(source
));
1573 account
.getGroupStore().updateGroup(groupV1
);
1578 if (groupV1
!= null && !isSync
) {
1579 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1584 // Received a group v1 message for a v2 group
1587 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1588 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1589 final var groupMasterKey
= groupContext
.getMasterKey();
1591 getOrMigrateGroup(groupMasterKey
,
1592 groupContext
.getRevision(),
1593 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1597 final var conversationPartnerAddress
= isSync ? destination
: source
;
1598 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1599 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1601 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1602 if (message
.getGroupContext().isPresent()) {
1603 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1604 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1605 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1606 if (group
!= null) {
1607 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1608 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1609 account
.getGroupStore().updateGroup(group
);
1612 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1613 // disappearing message timer already stored in the DecryptedGroup
1615 } else if (conversationPartnerAddress
!= null) {
1616 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1619 if (!ignoreAttachments
) {
1620 if (message
.getAttachments().isPresent()) {
1621 for (var attachment
: message
.getAttachments().get()) {
1622 downloadAttachment(attachment
);
1625 if (message
.getSharedContacts().isPresent()) {
1626 for (var contact
: message
.getSharedContacts().get()) {
1627 if (contact
.getAvatar().isPresent()) {
1628 downloadAttachment(contact
.getAvatar().get().getAttachment());
1633 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1634 final ProfileKey profileKey
;
1636 profileKey
= new ProfileKey(message
.getProfileKey().get());
1637 } catch (InvalidInputException e
) {
1638 throw new AssertionError(e
);
1640 if (source
.matches(account
.getSelfAddress())) {
1641 this.account
.setProfileKey(profileKey
);
1643 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1645 if (message
.getPreviews().isPresent()) {
1646 final var previews
= message
.getPreviews().get();
1647 for (var preview
: previews
) {
1648 if (preview
.getImage().isPresent()) {
1649 downloadAttachment(preview
.getImage().get());
1653 if (message
.getQuote().isPresent()) {
1654 final var quote
= message
.getQuote().get();
1656 for (var quotedAttachment
: quote
.getAttachments()) {
1657 final var thumbnail
= quotedAttachment
.getThumbnail();
1658 if (thumbnail
!= null) {
1659 downloadAttachment(thumbnail
);
1663 if (message
.getSticker().isPresent()) {
1664 final var messageSticker
= message
.getSticker().get();
1665 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1666 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1667 if (sticker
== null) {
1668 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1669 account
.getStickerStore().updateSticker(sticker
);
1671 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, messageSticker
.getPackKey()));
1676 private GroupInfoV2
getOrMigrateGroup(
1677 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1679 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1681 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1682 var groupInfo
= getGroup(groupId
);
1683 final GroupInfoV2 groupInfoV2
;
1684 if (groupInfo
instanceof GroupInfoV1
) {
1685 // Received a v2 group message for a v1 group, we need to locally migrate the group
1686 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1687 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1688 logger
.info("Locally migrated group {} to group v2, id: {}",
1689 groupInfo
.getGroupId().toBase64(),
1690 groupInfoV2
.getGroupId().toBase64());
1691 } else if (groupInfo
instanceof GroupInfoV2
) {
1692 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1694 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1697 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1698 DecryptedGroup group
= null;
1699 if (signedGroupChange
!= null
1700 && groupInfoV2
.getGroup() != null
1701 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1702 group
= groupV2Helper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(),
1706 if (group
== null) {
1707 group
= groupV2Helper
.getDecryptedGroup(groupSecretParams
);
1709 if (group
!= null) {
1710 storeProfileKeysFromMembers(group
);
1711 final var avatar
= group
.getAvatar();
1712 if (avatar
!= null && !avatar
.isEmpty()) {
1713 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1716 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1717 account
.getGroupStore().updateGroup(groupInfoV2
);
1723 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1724 for (var member
: group
.getMembersList()) {
1725 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
1726 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
1728 account
.getProfileStore()
1729 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
1730 } catch (InvalidInputException ignored
) {
1735 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1736 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1737 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1738 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1739 if (actions
!= null) {
1740 queuedActions
.addAll(actions
);
1743 for (var action
: queuedActions
) {
1745 action
.execute(this);
1746 } catch (Throwable e
) {
1747 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1748 Thread
.currentThread().interrupt();
1750 logger
.warn("Message action failed.", e
);
1755 private List
<HandleAction
> retryFailedReceivedMessage(
1756 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1758 var envelope
= cachedMessage
.loadEnvelope();
1759 if (envelope
== null) {
1762 SignalServiceContent content
= null;
1763 List
<HandleAction
> actions
= null;
1764 if (!envelope
.isReceipt()) {
1766 content
= decryptMessage(envelope
);
1767 } catch (ProtocolUntrustedIdentityException e
) {
1768 if (!envelope
.hasSource()) {
1769 final var identifier
= e
.getSender();
1770 final var recipientId
= resolveRecipient(identifier
);
1772 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1773 } catch (IOException ioException
) {
1774 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1778 } catch (Exception er
) {
1779 // All other errors are not recoverable, so delete the cached message
1780 cachedMessage
.delete();
1783 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1785 handler
.handleMessage(envelope
, content
, null);
1786 cachedMessage
.delete();
1790 public void receiveMessages(
1793 boolean returnOnTimeout
,
1794 boolean ignoreAttachments
,
1795 ReceiveMessageHandler handler
1796 ) throws IOException
, InterruptedException
{
1797 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1799 Set
<HandleAction
> queuedActions
= null;
1801 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1802 signalWebSocket
.connect();
1804 var hasCaughtUpWithOldMessages
= false;
1806 while (!Thread
.interrupted()) {
1807 SignalServiceEnvelope envelope
;
1808 SignalServiceContent content
= null;
1809 Exception exception
= null;
1810 final CachedMessage
[] cachedMessage
= {null};
1811 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
1812 logger
.debug("Checking for new message from server");
1814 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1815 final var recipientId
= envelope1
.hasSource()
1816 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1818 // store message on disk, before acknowledging receipt to the server
1819 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1821 logger
.debug("New message received from server");
1822 if (result
.isPresent()) {
1823 envelope
= result
.get();
1825 // Received indicator that server queue is empty
1826 hasCaughtUpWithOldMessages
= true;
1828 if (queuedActions
!= null) {
1829 for (var action
: queuedActions
) {
1831 action
.execute(this);
1832 } catch (Throwable e
) {
1833 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1834 Thread
.currentThread().interrupt();
1836 logger
.warn("Message action failed.", e
);
1839 queuedActions
.clear();
1840 queuedActions
= null;
1843 // Continue to wait another timeout for new messages
1846 } catch (AssertionError e
) {
1847 if (e
.getCause() instanceof InterruptedException
) {
1848 throw (InterruptedException
) e
.getCause();
1852 } catch (WebSocketUnavailableException e
) {
1853 logger
.debug("Pipe unexpectedly unavailable, connecting");
1854 signalWebSocket
.connect();
1856 } catch (TimeoutException e
) {
1857 if (returnOnTimeout
) return;
1861 if (envelope
.hasSource()) {
1862 // Store uuid if we don't have it already
1863 // address/uuid in envelope is sent by server
1864 resolveRecipientTrusted(envelope
.getSourceAddress());
1866 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1867 if (!envelope
.isReceipt()) {
1869 content
= decryptMessage(envelope
);
1870 } catch (Exception e
) {
1873 if (!envelope
.hasSource() && content
!= null) {
1874 // Store uuid if we don't have it already
1875 // address/uuid is validated by unidentified sender certificate
1876 resolveRecipientTrusted(content
.getSender());
1878 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1879 if (exception
instanceof ProtocolInvalidMessageException
) {
1880 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
1881 logger
.debug("Received invalid message, queuing renew session action.");
1882 actions
.add(new RenewSessionAction(sender
));
1884 if (hasCaughtUpWithOldMessages
) {
1885 for (var action
: actions
) {
1887 action
.execute(this);
1888 } catch (Throwable e
) {
1889 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1890 Thread
.currentThread().interrupt();
1892 logger
.warn("Message action failed.", e
);
1896 if (queuedActions
== null) {
1897 queuedActions
= new HashSet
<>();
1899 queuedActions
.addAll(actions
);
1902 if (isMessageBlocked(envelope
, content
)) {
1903 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1904 } else if (notAGroupMember
) {
1905 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1907 handler
.handleMessage(envelope
, content
, exception
);
1909 if (cachedMessage
[0] != null) {
1910 if (exception
instanceof ProtocolUntrustedIdentityException
) {
1911 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
1912 final var recipientId
= resolveRecipient(identifier
);
1913 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1914 if (!envelope
.hasSource()) {
1916 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1917 } catch (IOException ioException
) {
1918 logger
.warn("Failed to move cached message to recipient folder: {}",
1919 ioException
.getMessage());
1923 cachedMessage
[0].delete();
1929 private boolean isMessageBlocked(
1930 SignalServiceEnvelope envelope
, SignalServiceContent content
1932 SignalServiceAddress source
;
1933 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1934 source
= envelope
.getSourceAddress();
1935 } else if (content
!= null) {
1936 source
= content
.getSender();
1940 final var recipientId
= resolveRecipient(source
);
1941 if (isContactBlocked(recipientId
)) {
1945 if (content
!= null && content
.getDataMessage().isPresent()) {
1946 var message
= content
.getDataMessage().get();
1947 if (message
.getGroupContext().isPresent()) {
1948 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1949 var group
= getGroup(groupId
);
1950 if (group
!= null && group
.isBlocked()) {
1958 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
1959 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
1960 return isContactBlocked(recipientId
);
1963 private boolean isContactBlocked(final RecipientId recipientId
) {
1964 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1965 return sourceContact
!= null && sourceContact
.isBlocked();
1968 private boolean isNotAGroupMember(
1969 SignalServiceEnvelope envelope
, SignalServiceContent content
1971 SignalServiceAddress source
;
1972 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1973 source
= envelope
.getSourceAddress();
1974 } else if (content
!= null) {
1975 source
= content
.getSender();
1980 if (content
!= null && content
.getDataMessage().isPresent()) {
1981 var message
= content
.getDataMessage().get();
1982 if (message
.getGroupContext().isPresent()) {
1983 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1984 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1985 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1989 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1990 var group
= getGroup(groupId
);
1991 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
1999 private List
<HandleAction
> handleMessage(
2000 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
2002 var actions
= new ArrayList
<HandleAction
>();
2003 if (content
!= null) {
2004 final SignalServiceAddress sender
;
2005 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2006 sender
= envelope
.getSourceAddress();
2008 sender
= content
.getSender();
2011 if (content
.getDataMessage().isPresent()) {
2012 var message
= content
.getDataMessage().get();
2014 if (content
.isNeedsReceipt()) {
2015 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
2018 actions
.addAll(handleSignalServiceDataMessage(message
,
2021 account
.getSelfAddress(),
2022 ignoreAttachments
));
2024 if (content
.getSyncMessage().isPresent()) {
2025 account
.setMultiDevice(true);
2026 var syncMessage
= content
.getSyncMessage().get();
2027 if (syncMessage
.getSent().isPresent()) {
2028 var message
= syncMessage
.getSent().get();
2029 final var destination
= message
.getDestination().orNull();
2030 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
2034 ignoreAttachments
));
2036 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
2037 var rm
= syncMessage
.getRequest().get();
2038 if (rm
.isContactsRequest()) {
2039 actions
.add(SendSyncContactsAction
.create());
2041 if (rm
.isGroupsRequest()) {
2042 actions
.add(SendSyncGroupsAction
.create());
2044 if (rm
.isBlockedListRequest()) {
2045 actions
.add(SendSyncBlockedListAction
.create());
2047 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2049 if (syncMessage
.getGroups().isPresent()) {
2050 File tmpFile
= null;
2052 tmpFile
= IOUtils
.createTempFile();
2053 final var groupsMessage
= syncMessage
.getGroups().get();
2054 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2055 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2060 } catch (IOException e
) {
2061 logger
.warn("Sync groups contained invalid group, ignoring: {}", e
.getMessage());
2067 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2068 if (syncGroup
!= null) {
2069 if (g
.getName().isPresent()) {
2070 syncGroup
.name
= g
.getName().get();
2072 syncGroup
.addMembers(g
.getMembers()
2074 .map(this::resolveRecipient
)
2075 .collect(Collectors
.toSet()));
2076 if (!g
.isActive()) {
2077 syncGroup
.removeMember(account
.getSelfRecipientId());
2079 // Add ourself to the member set as it's marked as active
2080 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2082 syncGroup
.blocked
= g
.isBlocked();
2083 if (g
.getColor().isPresent()) {
2084 syncGroup
.color
= g
.getColor().get();
2087 if (g
.getAvatar().isPresent()) {
2088 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2090 syncGroup
.archived
= g
.isArchived();
2091 account
.getGroupStore().updateGroup(syncGroup
);
2095 } catch (Exception e
) {
2096 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2100 if (tmpFile
!= null) {
2102 Files
.delete(tmpFile
.toPath());
2103 } catch (IOException e
) {
2104 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2111 if (syncMessage
.getBlockedList().isPresent()) {
2112 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2113 for (var address
: blockedListMessage
.getAddresses()) {
2114 setContactBlocked(resolveRecipient(address
), true);
2116 for (var groupId
: blockedListMessage
.getGroupIds()
2118 .map(GroupId
::unknownVersion
)
2119 .collect(Collectors
.toSet())) {
2121 setGroupBlocked(groupId
, true);
2122 } catch (GroupNotFoundException e
) {
2123 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2124 groupId
.toBase64());
2128 if (syncMessage
.getContacts().isPresent()) {
2129 File tmpFile
= null;
2131 tmpFile
= IOUtils
.createTempFile();
2132 final var contactsMessage
= syncMessage
.getContacts().get();
2133 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2134 .asPointer(), tmpFile
)) {
2135 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2140 } catch (IOException e
) {
2141 logger
.warn("Sync contacts contained invalid contact, ignoring: {}",
2148 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2149 account
.setProfileKey(c
.getProfileKey().get());
2151 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2152 var contact
= account
.getContactStore().getContact(recipientId
);
2153 final var builder
= contact
== null
2154 ? Contact
.newBuilder()
2155 : Contact
.newBuilder(contact
);
2156 if (c
.getName().isPresent()) {
2157 builder
.withName(c
.getName().get());
2159 if (c
.getColor().isPresent()) {
2160 builder
.withColor(c
.getColor().get());
2162 if (c
.getProfileKey().isPresent()) {
2163 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2165 if (c
.getVerified().isPresent()) {
2166 final var verifiedMessage
= c
.getVerified().get();
2167 account
.getIdentityKeyStore()
2168 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2169 verifiedMessage
.getIdentityKey(),
2170 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2172 if (c
.getExpirationTimer().isPresent()) {
2173 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2175 builder
.withBlocked(c
.isBlocked());
2176 builder
.withArchived(c
.isArchived());
2177 account
.getContactStore().storeContact(recipientId
, builder
.build());
2179 if (c
.getAvatar().isPresent()) {
2180 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2184 } catch (Exception e
) {
2185 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2189 if (tmpFile
!= null) {
2191 Files
.delete(tmpFile
.toPath());
2192 } catch (IOException e
) {
2193 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2200 if (syncMessage
.getVerified().isPresent()) {
2201 final var verifiedMessage
= syncMessage
.getVerified().get();
2202 account
.getIdentityKeyStore()
2203 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2204 verifiedMessage
.getIdentityKey(),
2205 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2207 if (syncMessage
.getStickerPackOperations().isPresent()) {
2208 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2209 for (var m
: stickerPackOperationMessages
) {
2210 if (!m
.getPackId().isPresent()) {
2213 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2214 final var installed
= !m
.getType().isPresent()
2215 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
;
2217 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2218 if (m
.getPackKey().isPresent()) {
2219 if (sticker
== null) {
2220 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2223 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, m
.getPackKey().get()));
2227 if (sticker
!= null) {
2228 sticker
.setInstalled(installed
);
2229 account
.getStickerStore().updateSticker(sticker
);
2233 if (syncMessage
.getFetchType().isPresent()) {
2234 switch (syncMessage
.getFetchType().get()) {
2236 getRecipientProfile(account
.getSelfRecipientId(), true);
2237 case STORAGE_MANIFEST
:
2241 if (syncMessage
.getKeys().isPresent()) {
2242 final var keysMessage
= syncMessage
.getKeys().get();
2243 if (keysMessage
.getStorageService().isPresent()) {
2244 final var storageKey
= keysMessage
.getStorageService().get();
2245 account
.setStorageKey(storageKey
);
2248 if (syncMessage
.getConfiguration().isPresent()) {
2256 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2258 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2259 } catch (IOException e
) {
2260 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2264 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2266 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2267 } catch (IOException e
) {
2268 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2272 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2274 avatarStore
.storeGroupAvatar(groupId
,
2275 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2276 } catch (IOException e
) {
2277 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2281 private void downloadProfileAvatar(
2282 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2285 avatarStore
.storeProfileAvatar(address
,
2286 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2287 } catch (Throwable e
) {
2288 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
2289 Thread
.currentThread().interrupt();
2291 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2295 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2296 return attachmentStore
.getAttachmentFile(attachmentId
);
2299 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2300 if (!attachment
.isPointer()) {
2301 logger
.warn("Invalid state, can't store an attachment stream.");
2304 var pointer
= attachment
.asPointer();
2305 if (pointer
.getPreview().isPresent()) {
2306 final var preview
= pointer
.getPreview().get();
2308 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2309 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2310 } catch (IOException e
) {
2311 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2316 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2317 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2318 } catch (IOException e
) {
2319 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2323 private void retrieveGroupV2Avatar(
2324 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2325 ) throws IOException
{
2326 var groupOperations
= dependencies
.getGroupsV2Operations().forGroup(groupSecretParams
);
2328 var tmpFile
= IOUtils
.createTempFile();
2329 try (InputStream input
= dependencies
.getMessageReceiver()
2330 .retrieveGroupsV2ProfileAvatar(cdnKey
, tmpFile
, ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2331 var encryptedData
= IOUtils
.readFully(input
);
2333 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2334 outputStream
.write(decryptedData
);
2337 Files
.delete(tmpFile
.toPath());
2338 } catch (IOException e
) {
2339 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2346 private void retrieveProfileAvatar(
2347 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2348 ) throws IOException
{
2349 var tmpFile
= IOUtils
.createTempFile();
2350 try (var input
= dependencies
.getMessageReceiver()
2351 .retrieveProfileAvatar(avatarPath
,
2354 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2355 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2356 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2359 Files
.delete(tmpFile
.toPath());
2360 } catch (IOException e
) {
2361 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2368 private void retrieveAttachment(
2369 final SignalServiceAttachment attachment
, final OutputStream outputStream
2370 ) throws IOException
{
2371 if (attachment
.isPointer()) {
2372 var pointer
= attachment
.asPointer();
2373 retrieveAttachmentPointer(pointer
, outputStream
);
2375 var stream
= attachment
.asStream();
2376 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2380 private void retrieveAttachmentPointer(
2381 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2382 ) throws IOException
{
2383 var tmpFile
= IOUtils
.createTempFile();
2384 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2385 IOUtils
.copyStream(input
, outputStream
);
2386 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2387 throw new IOException(e
);
2390 Files
.delete(tmpFile
.toPath());
2391 } catch (IOException e
) {
2392 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2399 private InputStream
retrieveAttachmentAsStream(
2400 SignalServiceAttachmentPointer pointer
, File tmpFile
2401 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2402 return dependencies
.getMessageReceiver()
2403 .retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2406 void sendGroups() throws IOException
{
2407 var groupsFile
= IOUtils
.createTempFile();
2410 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2411 var out
= new DeviceGroupsOutputStream(fos
);
2412 for (var record : getGroups()) {
2413 if (record instanceof GroupInfoV1
) {
2414 var groupInfo
= (GroupInfoV1
) record;
2415 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2416 Optional
.fromNullable(groupInfo
.name
),
2417 groupInfo
.getMembers()
2419 .map(this::resolveSignalServiceAddress
)
2420 .collect(Collectors
.toList()),
2421 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2422 groupInfo
.isMember(account
.getSelfRecipientId()),
2423 Optional
.of(groupInfo
.messageExpirationTime
),
2424 Optional
.fromNullable(groupInfo
.color
),
2427 groupInfo
.archived
));
2432 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2433 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2434 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2435 .withStream(groupsFileStream
)
2436 .withContentType("application/octet-stream")
2437 .withLength(groupsFile
.length())
2440 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2445 Files
.delete(groupsFile
.toPath());
2446 } catch (IOException e
) {
2447 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2452 public void sendContacts() throws IOException
{
2453 var contactsFile
= IOUtils
.createTempFile();
2456 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2457 var out
= new DeviceContactsOutputStream(fos
);
2458 for (var contactPair
: account
.getContactStore().getContacts()) {
2459 final var recipientId
= contactPair
.first();
2460 final var contact
= contactPair
.second();
2461 final var address
= resolveSignalServiceAddress(recipientId
);
2463 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2464 VerifiedMessage verifiedMessage
= null;
2465 if (currentIdentity
!= null) {
2466 verifiedMessage
= new VerifiedMessage(address
,
2467 currentIdentity
.getIdentityKey(),
2468 currentIdentity
.getTrustLevel().toVerifiedState(),
2469 currentIdentity
.getDateAdded().getTime());
2472 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2473 out
.write(new DeviceContact(address
,
2474 Optional
.fromNullable(contact
.getName()),
2475 createContactAvatarAttachment(address
),
2476 Optional
.fromNullable(contact
.getColor()),
2477 Optional
.fromNullable(verifiedMessage
),
2478 Optional
.fromNullable(profileKey
),
2479 contact
.isBlocked(),
2480 Optional
.of(contact
.getMessageExpirationTime()),
2482 contact
.isArchived()));
2485 if (account
.getProfileKey() != null) {
2486 // Send our own profile key as well
2487 out
.write(new DeviceContact(account
.getSelfAddress(),
2492 Optional
.of(account
.getProfileKey()),
2500 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2501 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2502 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2503 .withStream(contactsFileStream
)
2504 .withContentType("application/octet-stream")
2505 .withLength(contactsFile
.length())
2508 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
,
2514 Files
.delete(contactsFile
.toPath());
2515 } catch (IOException e
) {
2516 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2521 void sendBlockedList() throws IOException
{
2522 var addresses
= new ArrayList
<SignalServiceAddress
>();
2523 for (var record : account
.getContactStore().getContacts()) {
2524 if (record.second().isBlocked()) {
2525 addresses
.add(resolveSignalServiceAddress(record.first()));
2528 var groupIds
= new ArrayList
<byte[]>();
2529 for (var record : getGroups()) {
2530 if (record.isBlocked()) {
2531 groupIds
.add(record.getGroupId().serialize());
2534 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2537 private void sendVerifiedMessage(
2538 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2539 ) throws IOException
{
2540 var verifiedMessage
= new VerifiedMessage(destination
,
2542 trustLevel
.toVerifiedState(),
2543 System
.currentTimeMillis());
2544 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2547 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2548 return account
.getContactStore().getContacts();
2551 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2552 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2553 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2554 if (recipient
== null) {
2558 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2559 return recipient
.getContact().getName();
2562 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2563 return recipient
.getProfile().getDisplayName();
2569 public GroupInfo
getGroup(GroupId groupId
) {
2570 return getGroup(groupId
, false);
2573 public GroupInfo
getGroup(GroupId groupId
, boolean forceUpdate
) {
2574 final var group
= account
.getGroupStore().getGroup(groupId
);
2575 if (group
instanceof GroupInfoV2
&& (forceUpdate
|| ((GroupInfoV2
) group
).getGroup() == null)) {
2576 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2577 ((GroupInfoV2
) group
).setGroup(groupV2Helper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2578 account
.getGroupStore().updateGroup(group
);
2583 public List
<IdentityInfo
> getIdentities() {
2584 return account
.getIdentityKeyStore().getIdentities();
2587 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2588 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2589 return identity
== null ? List
.of() : List
.of(identity
);
2593 * Trust this the identity with this fingerprint
2595 * @param name username of the identity
2596 * @param fingerprint Fingerprint
2598 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2599 var recipientId
= canonicalizeAndResolveRecipient(name
);
2600 return trustIdentity(recipientId
,
2601 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2602 TrustLevel
.TRUSTED_VERIFIED
);
2606 * Trust this the identity with this safety number
2608 * @param name username of the identity
2609 * @param safetyNumber Safety number
2611 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2612 var recipientId
= canonicalizeAndResolveRecipient(name
);
2613 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2614 return trustIdentity(recipientId
,
2615 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2616 TrustLevel
.TRUSTED_VERIFIED
);
2620 * Trust all keys of this identity without verification
2622 * @param name username of the identity
2624 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2625 var recipientId
= canonicalizeAndResolveRecipient(name
);
2626 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2629 private boolean trustIdentity(
2630 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2632 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2633 if (identity
== null) {
2637 if (!verifier
.apply(identity
.getIdentityKey())) {
2641 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2643 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2644 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2645 } catch (IOException e
) {
2646 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2652 private void handleIdentityFailure(
2653 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
2655 final var identityKey
= identityFailure
.getIdentityKey();
2656 if (identityKey
!= null) {
2657 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
2659 account
.getSessionStore().archiveSessions(recipientId
);
2662 // Retrieve profile to get the current identity key from the server
2663 retrieveEncryptedProfile(recipientId
);
2667 public String
computeSafetyNumber(
2668 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2670 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2671 account
.getSelfAddress(),
2672 getIdentityKeyPair().getPublicKey(),
2678 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2679 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2681 return resolveSignalServiceAddress(address
);
2685 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2686 if (address
.matches(account
.getSelfAddress())) {
2687 return account
.getSelfAddress();
2690 return account
.getRecipientStore().resolveServiceAddress(address
);
2693 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2694 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2697 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2698 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2700 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2702 return resolveRecipient(canonicalizedNumber
);
2705 private RecipientId
resolveRecipient(final String identifier
) {
2706 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2708 return resolveRecipient(address
);
2711 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2712 return account
.getRecipientStore().resolveRecipient(address
);
2715 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2716 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2719 private void enqueueJob(Job job
) {
2720 var context
= new Context(account
,
2721 dependencies
.getAccountManager(),
2722 dependencies
.getMessageReceiver(),
2728 public void close() throws IOException
{
2732 void close(boolean closeAccount
) throws IOException
{
2733 executor
.shutdown();
2735 dependencies
.getSignalWebSocket().disconnect();
2737 if (closeAccount
&& account
!= null) {
2743 public interface ReceiveMessageHandler
{
2745 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);