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
.config
.ServiceConfig
;
21 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
22 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
23 import org
.asamk
.signal
.manager
.groups
.GroupId
;
24 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
25 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
26 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
27 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
28 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
29 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
30 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
31 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
32 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
33 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
34 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
35 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
36 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
37 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
38 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
39 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
40 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
41 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
42 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
43 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
44 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
45 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
46 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
47 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
48 import org
.asamk
.signal
.manager
.util
.IOUtils
;
49 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
50 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
51 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
52 import org
.asamk
.signal
.manager
.util
.Utils
;
53 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
54 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
56 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
57 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
58 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
59 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
60 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
61 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
62 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
63 import org
.signal
.libsignal
.metadata
.SelfSendException
;
64 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
65 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
66 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
67 import org
.signal
.zkgroup
.InvalidInputException
;
68 import org
.signal
.zkgroup
.VerificationFailedException
;
69 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
70 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
71 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
72 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
73 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
74 import org
.slf4j
.Logger
;
75 import org
.slf4j
.LoggerFactory
;
76 import org
.whispersystems
.libsignal
.IdentityKey
;
77 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
78 import org
.whispersystems
.libsignal
.InvalidKeyException
;
79 import org
.whispersystems
.libsignal
.InvalidMessageException
;
80 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
81 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
82 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
83 import org
.whispersystems
.libsignal
.util
.Pair
;
84 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
85 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
86 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
87 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
88 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
89 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
90 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
91 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
92 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
93 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
94 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
95 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
96 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
106 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
107 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
121 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
122 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
123 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
124 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
125 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
126 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
127 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
128 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
129 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
130 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
131 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
132 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
133 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
134 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
135 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
136 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
137 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
138 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
139 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
141 import java
.io
.Closeable
;
143 import java
.io
.FileInputStream
;
144 import java
.io
.FileOutputStream
;
145 import java
.io
.IOException
;
146 import java
.io
.InputStream
;
147 import java
.io
.OutputStream
;
149 import java
.net
.URISyntaxException
;
150 import java
.net
.URLEncoder
;
151 import java
.nio
.charset
.StandardCharsets
;
152 import java
.nio
.file
.Files
;
153 import java
.security
.SignatureException
;
154 import java
.util
.ArrayList
;
155 import java
.util
.Arrays
;
156 import java
.util
.Base64
;
157 import java
.util
.Collection
;
158 import java
.util
.Date
;
159 import java
.util
.HashSet
;
160 import java
.util
.List
;
161 import java
.util
.Map
;
162 import java
.util
.Set
;
163 import java
.util
.UUID
;
164 import java
.util
.concurrent
.ExecutorService
;
165 import java
.util
.concurrent
.Executors
;
166 import java
.util
.concurrent
.TimeUnit
;
167 import java
.util
.concurrent
.TimeoutException
;
168 import java
.util
.concurrent
.locks
.ReentrantLock
;
169 import java
.util
.function
.Function
;
170 import java
.util
.stream
.Collectors
;
172 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
174 public class Manager
implements Closeable
{
176 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
178 private final CertificateValidator certificateValidator
;
180 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
181 private final String userAgent
;
183 private SignalAccount account
;
184 private final SignalServiceAccountManager accountManager
;
185 private final GroupsV2Api groupsV2Api
;
186 private final GroupsV2Operations groupsV2Operations
;
187 private final SignalServiceMessageReceiver messageReceiver
;
188 private final ClientZkProfileOperations clientZkProfileOperations
;
190 private final ExecutorService executor
= Executors
.newCachedThreadPool();
192 private SignalServiceMessagePipe messagePipe
= null;
193 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
195 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
196 private final ProfileHelper profileHelper
;
197 private final GroupV2Helper groupV2Helper
;
198 private final PinHelper pinHelper
;
199 private final AvatarStore avatarStore
;
200 private final AttachmentStore attachmentStore
;
201 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
202 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
205 public Lock
acquire() {
207 return LEGACY_LOCK
::unlock
;
212 SignalAccount account
,
213 PathConfig pathConfig
,
214 ServiceEnvironmentConfig serviceEnvironmentConfig
,
217 this.account
= account
;
218 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
219 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
220 this.userAgent
= userAgent
;
221 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
222 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
223 final SleepTimer timer
= new UptimeSleepTimer();
224 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
225 new DynamicCredentialsProvider(account
.getUuid(),
226 account
.getUsername(),
227 account
.getPassword(),
228 account
.getDeviceId()),
231 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
233 this.groupsV2Api
= accountManager
.getGroupsV2Api();
234 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
235 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
236 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
237 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
240 this.pinHelper
= new PinHelper(keyBackupService
);
241 this.clientZkProfileOperations
= capabilities
.isGv2()
242 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
243 .getProfileOperations()
245 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
247 account
.getUsername(),
248 account
.getPassword(),
249 account
.getDeviceId(),
253 clientZkProfileOperations
,
254 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
256 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
257 account
.getProfileStore()::getProfileKey
,
258 this::getRecipientProfile
,
259 this::getSenderCertificate
);
260 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
261 unidentifiedAccessHelper
::getAccessFor
,
262 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
263 () -> messageReceiver
,
264 this::resolveSignalServiceAddress
);
265 this.groupV2Helper
= new GroupV2Helper(this::getRecipientProfileKeyCredential
,
266 this::getRecipientProfile
,
267 account
::getSelfRecipientId
,
270 this::getGroupAuthForToday
,
271 this::resolveSignalServiceAddress
);
272 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
273 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
276 public String
getUsername() {
277 return account
.getUsername();
280 public SignalServiceAddress
getSelfAddress() {
281 return account
.getSelfAddress();
284 public RecipientId
getSelfRecipientId() {
285 return account
.getSelfRecipientId();
288 private IdentityKeyPair
getIdentityKeyPair() {
289 return account
.getIdentityKeyPair();
292 public int getDeviceId() {
293 return account
.getDeviceId();
296 public static Manager
init(
297 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
298 ) throws IOException
, NotRegisteredException
{
299 var pathConfig
= PathConfig
.createDefault(settingsPath
);
301 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
302 throw new NotRegisteredException();
305 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true);
307 if (!account
.isRegistered()) {
308 throw new NotRegisteredException();
311 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
313 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
316 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
317 var pathConfig
= PathConfig
.createDefault(settingsPath
);
318 final var dataPath
= pathConfig
.getDataPath();
319 final var files
= dataPath
.listFiles();
325 return Arrays
.stream(files
)
326 .filter(File
::isFile
)
328 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
329 .collect(Collectors
.toList());
332 public void checkAccountState() throws IOException
{
333 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
336 if (account
.getUuid() == null) {
337 account
.setUuid(accountManager
.getOwnUuid());
339 updateAccountAttributes();
343 * This is used for checking a set of phone numbers for registration on Signal
345 * @param numbers The set of phone number in question
346 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
347 * @throws IOException if its unable to get the contacts to check if they're registered
349 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
350 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
351 var contactDetails
= getRegisteredUsers(numbers
);
353 var registeredUsers
= contactDetails
.keySet();
355 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
358 public void updateAccountAttributes() throws IOException
{
359 accountManager
.setAccountAttributes(account
.getEncryptedDeviceName(),
361 account
.getLocalRegistrationId(),
363 // set legacy pin only if no KBS master key is set
364 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
365 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
366 account
.getSelfUnidentifiedAccessKey(),
367 account
.isUnrestrictedUnidentifiedAccess(),
369 account
.isDiscoverableByPhoneNumber());
373 * @param givenName if null, the previous givenName will be kept
374 * @param familyName if null, the previous familyName will be kept
375 * @param about if null, the previous about text will be kept
376 * @param aboutEmoji if null, the previous about emoji will be kept
377 * @param avatar if avatar is null the image from the local avatar store is used (if present),
379 public void setProfile(
380 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
381 ) throws IOException
{
382 var profile
= getRecipientProfile(account
.getSelfRecipientId());
383 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
384 if (givenName
!= null) {
385 builder
.withGivenName(givenName
);
387 if (familyName
!= null) {
388 builder
.withFamilyName(familyName
);
391 builder
.withAbout(about
);
393 if (aboutEmoji
!= null) {
394 builder
.withAboutEmoji(aboutEmoji
);
396 var newProfile
= builder
.build();
398 try (final var streamDetails
= avatar
== null
399 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
400 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
401 accountManager
.setVersionedProfile(account
.getUuid(),
402 account
.getProfileKey(),
403 newProfile
.getInternalServiceName(),
404 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
405 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
410 if (avatar
!= null) {
411 if (avatar
.isPresent()) {
412 avatarStore
.storeProfileAvatar(getSelfAddress(),
413 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
415 avatarStore
.deleteProfileAvatar(getSelfAddress());
418 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
421 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
422 } catch (UntrustedIdentityException ignored
) {
426 public void unregister() throws IOException
{
427 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
428 // If this is the master device, other users can't send messages to this number anymore.
429 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
430 accountManager
.setGcmId(Optional
.absent());
432 account
.setRegistered(false);
435 public void deleteAccount() throws IOException
{
436 accountManager
.deleteAccount();
438 account
.setRegistered(false);
441 public List
<Device
> getLinkedDevices() throws IOException
{
442 var devices
= accountManager
.getDevices();
443 account
.setMultiDevice(devices
.size() > 1);
444 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
445 return devices
.stream().map(d
-> {
446 String deviceName
= d
.getName();
447 if (deviceName
!= null) {
449 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
450 } catch (IOException e
) {
451 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
454 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
455 }).collect(Collectors
.toList());
458 public void removeLinkedDevices(int deviceId
) throws IOException
{
459 accountManager
.removeDevice(deviceId
);
460 var devices
= accountManager
.getDevices();
461 account
.setMultiDevice(devices
.size() > 1);
464 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
465 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
467 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
470 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
471 var identityKeyPair
= getIdentityKeyPair();
472 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
474 accountManager
.addDevice(deviceIdentifier
,
477 Optional
.of(account
.getProfileKey().serialize()),
479 account
.setMultiDevice(true);
482 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
483 if (!account
.isMasterDevice()) {
484 throw new RuntimeException("Only master device can set a PIN");
486 if (pin
.isPresent()) {
487 final var masterKey
= account
.getPinMasterKey() != null
488 ? account
.getPinMasterKey()
489 : KeyUtils
.createMasterKey();
491 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
493 account
.setRegistrationLockPin(pin
.get(), masterKey
);
495 // Remove legacy registration lock
496 accountManager
.removeRegistrationLockV1();
499 pinHelper
.removeRegistrationLockPin();
501 account
.setRegistrationLockPin(null, null);
505 void refreshPreKeys() throws IOException
{
506 var oneTimePreKeys
= generatePreKeys();
507 final var identityKeyPair
= getIdentityKeyPair();
508 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
510 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
513 private List
<PreKeyRecord
> generatePreKeys() {
514 final var offset
= account
.getPreKeyIdOffset();
516 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
517 account
.addPreKeys(records
);
522 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
523 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
525 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
526 account
.addSignedPreKey(record);
531 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
532 if (messagePipe
== null) {
533 messagePipe
= messageReceiver
.createMessagePipe();
538 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
539 if (unidentifiedMessagePipe
== null) {
540 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
542 return unidentifiedMessagePipe
;
545 private SignalServiceMessageSender
createMessageSender() {
546 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
548 account
.getUsername(),
549 account
.getPassword(),
550 account
.getDeviceId(),
551 account
.getSignalProtocolStore(),
554 account
.isMultiDevice(),
555 Optional
.fromNullable(messagePipe
),
556 Optional
.fromNullable(unidentifiedMessagePipe
),
558 clientZkProfileOperations
,
560 ServiceConfig
.MAX_ENVELOPE_SIZE
,
561 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
564 public Profile
getRecipientProfile(
565 RecipientId recipientId
567 return getRecipientProfile(recipientId
, false);
570 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
572 Profile
getRecipientProfile(
573 RecipientId recipientId
, boolean force
575 var profile
= account
.getProfileStore().getProfile(recipientId
);
577 var now
= new Date().getTime();
578 // Profiles are cached for 24h before retrieving them again, unless forced
579 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
583 synchronized (pendingProfileRequest
) {
584 if (pendingProfileRequest
.contains(recipientId
)) {
587 pendingProfileRequest
.add(recipientId
);
589 final SignalServiceProfile encryptedProfile
;
591 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
593 synchronized (pendingProfileRequest
) {
594 pendingProfileRequest
.remove(recipientId
);
597 if (encryptedProfile
== null) {
601 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
602 if (profileKey
== null) {
603 profile
= new Profile(new Date().getTime(),
608 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
609 ProfileUtils
.getCapabilities(encryptedProfile
));
611 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
613 account
.getProfileStore().storeProfile(recipientId
, profile
);
618 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
620 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
621 } catch (IOException e
) {
622 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
627 private ProfileAndCredential
retrieveProfileAndCredential(
628 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
629 ) throws IOException
{
630 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
631 final var profile
= profileAndCredential
.getProfile();
634 var newIdentity
= account
.getIdentityKeyStore()
635 .saveIdentity(recipientId
,
636 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
640 account
.getSessionStore().archiveSessions(recipientId
);
642 } catch (InvalidKeyException ignored
) {
643 logger
.warn("Got invalid identity key in profile for {}",
644 resolveSignalServiceAddress(recipientId
).getLegacyIdentifier());
646 return profileAndCredential
;
649 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
650 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
651 if (profileKeyCredential
!= null) {
652 return profileKeyCredential
;
655 ProfileAndCredential profileAndCredential
;
657 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
658 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
659 } catch (IOException e
) {
660 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
664 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
665 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
667 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
668 if (profileKey
!= null) {
669 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
671 profileAndCredential
.getProfile());
672 account
.getProfileStore().storeProfile(recipientId
, profile
);
675 return profileKeyCredential
;
678 private Profile
decryptProfileAndDownloadAvatar(
679 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
681 if (encryptedProfile
.getAvatar() != null) {
682 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
685 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
688 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
689 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
690 if (streamDetails
== null) {
691 return Optional
.absent();
694 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
697 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
698 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
699 if (streamDetails
== null) {
700 return Optional
.absent();
703 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
706 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
707 var g
= getGroup(groupId
);
709 throw new GroupNotFoundException(groupId
);
711 if (!g
.isMember(account
.getSelfRecipientId())) {
712 throw new NotAGroupMemberException(groupId
, g
.getTitle());
717 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
718 var g
= getGroup(groupId
);
720 throw new GroupNotFoundException(groupId
);
722 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
723 throw new NotAGroupMemberException(groupId
, g
.getTitle());
728 public List
<GroupInfo
> getGroups() {
729 return account
.getGroupStore().getGroups();
732 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
733 String messageText
, List
<String
> attachments
, GroupId groupId
734 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
735 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
736 if (attachments
!= null) {
737 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
740 return sendGroupMessage(messageBuilder
, groupId
);
743 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
744 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
745 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
746 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
747 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
749 resolveSignalServiceAddress(targetAuthorRecipientId
),
750 targetSentTimestamp
);
751 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
753 return sendGroupMessage(messageBuilder
, groupId
);
756 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
757 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
758 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
759 final var g
= getGroupForSending(groupId
);
761 GroupUtils
.setGroupContext(messageBuilder
, g
);
762 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
764 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
767 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(
768 GroupId groupId
, Set
<String
> groupAdmins
769 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, InvalidNumberException
, LastGroupAdminException
{
770 SignalServiceDataMessage
.Builder messageBuilder
;
772 final var g
= getGroupForUpdating(groupId
);
773 if (g
instanceof GroupInfoV1
) {
774 var groupInfoV1
= (GroupInfoV1
) g
;
775 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
776 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
777 groupInfoV1
.removeMember(account
.getSelfRecipientId());
778 account
.getGroupStore().updateGroup(groupInfoV1
);
780 final var groupInfoV2
= (GroupInfoV2
) g
;
781 final var currentAdmins
= g
.getAdminMembers();
782 final var newAdmins
= getSignalServiceAddresses(groupAdmins
);
783 newAdmins
.removeAll(currentAdmins
);
784 newAdmins
.retainAll(g
.getMembers());
785 if (currentAdmins
.contains(getSelfRecipientId())
786 && currentAdmins
.size() == 1
787 && g
.getMembers().size() > 1
788 && newAdmins
.size() == 0) {
789 // Last admin can't leave the group, unless she's also the last member
790 throw new LastGroupAdminException(g
.getGroupId(), g
.getTitle());
792 final var groupGroupChangePair
= groupV2Helper
.leaveGroup(groupInfoV2
, newAdmins
);
793 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
794 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
795 account
.getGroupStore().updateGroup(groupInfoV2
);
798 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
801 public Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
802 String name
, List
<String
> members
, File avatarFile
803 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
804 return createGroup(name
, members
== null ?
null : getSignalServiceAddresses(members
), avatarFile
);
807 private Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
808 String name
, Set
<RecipientId
> members
, File avatarFile
809 ) throws IOException
, AttachmentInvalidException
{
810 final var selfRecipientId
= account
.getSelfRecipientId();
811 if (members
!= null && members
.contains(selfRecipientId
)) {
812 members
= new HashSet
<>(members
);
813 members
.remove(selfRecipientId
);
816 var gv2Pair
= groupV2Helper
.createGroup(name
== null ?
"" : name
,
817 members
== null ? Set
.of() : members
,
820 SignalServiceDataMessage
.Builder messageBuilder
;
821 if (gv2Pair
== null) {
822 // Failed to create v2 group, creating v1 group instead
823 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
824 gv1
.addMembers(List
.of(selfRecipientId
));
825 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
826 return new Pair
<>(gv1
.getGroupId(), result
.second());
829 final var gv2
= gv2Pair
.first();
830 final var decryptedGroup
= gv2Pair
.second();
832 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
833 if (avatarFile
!= null) {
834 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
835 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
837 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
838 account
.getGroupStore().updateGroup(gv2
);
840 final var result
= sendMessage(messageBuilder
, gv2
.getMembersIncludingPendingWithout(selfRecipientId
));
841 return new Pair
<>(gv2
.getGroupId(), result
.second());
844 public Pair
<Long
, List
<SendMessageResult
>> updateGroup(
848 List
<String
> members
,
849 List
<String
> removeMembers
,
851 List
<String
> removeAdmins
,
852 boolean resetGroupLink
,
853 GroupLinkState groupLinkState
,
854 GroupPermission addMemberPermission
,
855 GroupPermission editDetailsPermission
,
857 Integer expirationTimer
858 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
859 return updateGroup(groupId
,
862 members
== null ?
null : getSignalServiceAddresses(members
),
863 removeMembers
== null ?
null : getSignalServiceAddresses(removeMembers
),
864 admins
== null ?
null : getSignalServiceAddresses(admins
),
865 removeAdmins
== null ?
null : getSignalServiceAddresses(removeAdmins
),
869 editDetailsPermission
,
874 private Pair
<Long
, List
<SendMessageResult
>> updateGroup(
875 final GroupId groupId
,
877 final String description
,
878 final Set
<RecipientId
> members
,
879 final Set
<RecipientId
> removeMembers
,
880 final Set
<RecipientId
> admins
,
881 final Set
<RecipientId
> removeAdmins
,
882 final boolean resetGroupLink
,
883 final GroupLinkState groupLinkState
,
884 final GroupPermission addMemberPermission
,
885 final GroupPermission editDetailsPermission
,
886 final File avatarFile
,
887 final Integer expirationTimer
888 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
889 var group
= getGroupForUpdating(groupId
);
891 if (group
instanceof GroupInfoV2
) {
892 return updateGroupV2((GroupInfoV2
) group
,
902 editDetailsPermission
,
907 final var gv1
= (GroupInfoV1
) group
;
908 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
909 if (expirationTimer
!= null) {
910 setExpirationTimer(gv1
, expirationTimer
);
915 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV1(
916 final GroupInfoV1 gv1
, final String name
, final Set
<RecipientId
> members
, final File avatarFile
917 ) throws IOException
, AttachmentInvalidException
{
918 updateGroupV1Details(gv1
, name
, members
, avatarFile
);
919 var messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
921 account
.getGroupStore().updateGroup(gv1
);
923 return sendMessage(messageBuilder
, gv1
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
926 private void updateGroupV1Details(
927 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
928 ) throws IOException
{
933 if (members
!= null) {
934 final var newMemberAddresses
= members
.stream()
935 .filter(member
-> !g
.isMember(member
))
936 .map(this::resolveSignalServiceAddress
)
937 .collect(Collectors
.toList());
938 final var newE164Members
= new HashSet
<String
>();
939 for (var member
: newMemberAddresses
) {
940 if (!member
.getNumber().isPresent()) {
943 newE164Members
.add(member
.getNumber().get());
946 final var registeredUsers
= getRegisteredUsers(newE164Members
);
947 if (registeredUsers
.size() != newE164Members
.size()) {
948 // Some of the new members are not registered on Signal
949 newE164Members
.removeAll(registeredUsers
.keySet());
950 throw new IOException("Failed to add members "
951 + String
.join(", ", newE164Members
)
952 + " to group: Not registered on Signal");
955 g
.addMembers(members
);
958 if (avatarFile
!= null) {
959 avatarStore
.storeGroupAvatar(g
.getGroupId(),
960 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
964 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV2(
965 final GroupInfoV2 group
,
967 final String description
,
968 final Set
<RecipientId
> members
,
969 final Set
<RecipientId
> removeMembers
,
970 final Set
<RecipientId
> admins
,
971 final Set
<RecipientId
> removeAdmins
,
972 final boolean resetGroupLink
,
973 final GroupLinkState groupLinkState
,
974 final GroupPermission addMemberPermission
,
975 final GroupPermission editDetailsPermission
,
976 final File avatarFile
,
977 Integer expirationTimer
978 ) throws IOException
{
979 Pair
<Long
, List
<SendMessageResult
>> result
= null;
980 if (group
.isPendingMember(account
.getSelfRecipientId())) {
981 var groupGroupChangePair
= groupV2Helper
.acceptInvite(group
);
982 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
985 if (members
!= null) {
986 final var newMembers
= new HashSet
<>(members
);
987 newMembers
.removeAll(group
.getMembers());
988 if (newMembers
.size() > 0) {
989 var groupGroupChangePair
= groupV2Helper
.addMembers(group
, newMembers
);
990 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
994 if (removeMembers
!= null) {
995 var existingRemoveMembers
= new HashSet
<>(removeMembers
);
996 existingRemoveMembers
.retainAll(group
.getMembers());
997 existingRemoveMembers
.remove(getSelfRecipientId());// self can be removed with sendQuitGroupMessage
998 if (existingRemoveMembers
.size() > 0) {
999 var groupGroupChangePair
= groupV2Helper
.removeMembers(group
, existingRemoveMembers
);
1000 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1003 var pendingRemoveMembers
= new HashSet
<>(removeMembers
);
1004 pendingRemoveMembers
.retainAll(group
.getPendingMembers());
1005 if (pendingRemoveMembers
.size() > 0) {
1006 var groupGroupChangePair
= groupV2Helper
.revokeInvitedMembers(group
, pendingRemoveMembers
);
1007 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1011 if (admins
!= null) {
1012 final var newAdmins
= new HashSet
<>(admins
);
1013 newAdmins
.retainAll(group
.getMembers());
1014 newAdmins
.removeAll(group
.getAdminMembers());
1015 if (newAdmins
.size() > 0) {
1016 for (var admin
: newAdmins
) {
1017 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, true);
1018 result
= sendUpdateGroupV2Message(group
,
1019 groupGroupChangePair
.first(),
1020 groupGroupChangePair
.second());
1025 if (removeAdmins
!= null) {
1026 final var existingRemoveAdmins
= new HashSet
<>(removeAdmins
);
1027 existingRemoveAdmins
.retainAll(group
.getAdminMembers());
1028 if (existingRemoveAdmins
.size() > 0) {
1029 for (var admin
: existingRemoveAdmins
) {
1030 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, false);
1031 result
= sendUpdateGroupV2Message(group
,
1032 groupGroupChangePair
.first(),
1033 groupGroupChangePair
.second());
1038 if (resetGroupLink
) {
1039 var groupGroupChangePair
= groupV2Helper
.resetGroupLinkPassword(group
);
1040 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1043 if (groupLinkState
!= null) {
1044 var groupGroupChangePair
= groupV2Helper
.setGroupLinkState(group
, groupLinkState
);
1045 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1048 if (addMemberPermission
!= null) {
1049 var groupGroupChangePair
= groupV2Helper
.setAddMemberPermission(group
, addMemberPermission
);
1050 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1053 if (editDetailsPermission
!= null) {
1054 var groupGroupChangePair
= groupV2Helper
.setEditDetailsPermission(group
, editDetailsPermission
);
1055 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1058 if (expirationTimer
!= null) {
1059 var groupGroupChangePair
= groupV2Helper
.setMessageExpirationTimer(group
, expirationTimer
);
1060 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1063 if (name
!= null || description
!= null || avatarFile
!= null) {
1064 var groupGroupChangePair
= groupV2Helper
.updateGroup(group
, name
, description
, avatarFile
);
1065 if (avatarFile
!= null) {
1066 avatarStore
.storeGroupAvatar(group
.getGroupId(),
1067 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
1069 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1075 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
1076 GroupInviteLinkUrl inviteLinkUrl
1077 ) throws IOException
, GroupLinkNotActiveException
{
1078 final var groupJoinInfo
= groupV2Helper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
1079 inviteLinkUrl
.getPassword());
1080 final var groupChange
= groupV2Helper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
1081 inviteLinkUrl
.getPassword(),
1083 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
1084 groupJoinInfo
.getRevision() + 1,
1085 groupChange
.toByteArray());
1087 if (group
.getGroup() == null) {
1088 // Only requested member, can't send update to group members
1089 return new Pair
<>(group
.getGroupId(), List
.of());
1092 final var result
= sendUpdateGroupV2Message(group
, group
.getGroup(), groupChange
);
1094 return new Pair
<>(group
.getGroupId(), result
.second());
1097 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupV2Message(
1098 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
1099 ) throws IOException
{
1100 final var selfRecipientId
= account
.getSelfRecipientId();
1101 final var members
= group
.getMembersIncludingPendingWithout(selfRecipientId
);
1102 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
1103 members
.addAll(group
.getMembersIncludingPendingWithout(selfRecipientId
));
1105 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
1106 account
.getGroupStore().updateGroup(group
);
1107 return sendMessage(messageBuilder
, members
);
1110 private static int currentTimeDays() {
1111 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
1114 private GroupsV2AuthorizationString
getGroupAuthForToday(
1115 final GroupSecretParams groupSecretParams
1116 ) throws IOException
{
1117 final var today
= currentTimeDays();
1118 // Returns credentials for the next 7 days
1119 final var credentials
= groupsV2Api
.getCredentials(today
);
1120 // TODO cache credentials until they expire
1121 var authCredentialResponse
= credentials
.get(today
);
1123 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
1126 authCredentialResponse
);
1127 } catch (VerificationFailedException e
) {
1128 throw new IOException(e
);
1132 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
1133 GroupIdV1 groupId
, SignalServiceAddress recipient
1134 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
1136 var group
= getGroupForSending(groupId
);
1137 if (!(group
instanceof GroupInfoV1
)) {
1138 throw new RuntimeException("Received an invalid group request for a v2 group!");
1140 g
= (GroupInfoV1
) group
;
1142 final var recipientId
= resolveRecipient(recipient
);
1143 if (!g
.isMember(recipientId
)) {
1144 throw new NotAGroupMemberException(groupId
, g
.name
);
1147 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
1149 // Send group message only to the recipient who requested it
1150 return sendMessage(messageBuilder
, Set
.of(recipientId
));
1153 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
1154 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
1155 .withId(g
.getGroupId().serialize())
1157 .withMembers(g
.getMembers()
1159 .map(this::resolveSignalServiceAddress
)
1160 .collect(Collectors
.toList()));
1163 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
1164 if (attachment
.isPresent()) {
1165 group
.withAvatar(attachment
.get());
1167 } catch (IOException e
) {
1168 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
1171 return SignalServiceDataMessage
.newBuilder()
1172 .asGroupMessage(group
.build())
1173 .withExpiration(g
.getMessageExpirationTime());
1176 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
1177 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
1178 .withRevision(g
.getGroup().getRevision())
1179 .withSignedGroupChange(signedGroupChange
);
1180 return SignalServiceDataMessage
.newBuilder()
1181 .asGroupMessage(group
.build())
1182 .withExpiration(g
.getMessageExpirationTime());
1185 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
1186 GroupIdV1 groupId
, SignalServiceAddress recipient
1187 ) throws IOException
{
1188 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
1190 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
1192 // Send group info request message to the recipient who sent us a message with this groupId
1193 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1197 SignalServiceAddress remoteAddress
, long messageId
1198 ) throws IOException
, UntrustedIdentityException
{
1199 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1201 System
.currentTimeMillis());
1203 createMessageSender().sendReceipt(remoteAddress
,
1204 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1208 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1209 String messageText
, List
<String
> attachments
, List
<String
> recipients
1210 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1211 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1212 if (attachments
!= null) {
1213 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1215 // Upload attachments here, so we only upload once even for multiple recipients
1216 var messageSender
= createMessageSender();
1217 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1218 for (var attachment
: attachmentStreams
) {
1219 if (attachment
.isStream()) {
1220 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1221 } else if (attachment
.isPointer()) {
1222 attachmentPointers
.add(attachment
.asPointer());
1226 messageBuilder
.withAttachments(attachmentPointers
);
1228 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1231 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1232 String messageText
, List
<String
> attachments
1233 ) throws IOException
, AttachmentInvalidException
{
1234 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1235 if (attachments
!= null) {
1236 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1238 return sendSelfMessage(messageBuilder
);
1241 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1242 long targetSentTimestamp
, List
<String
> recipients
1243 ) throws IOException
, InvalidNumberException
{
1244 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1245 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1246 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1249 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1250 long targetSentTimestamp
, GroupId groupId
1251 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1252 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1253 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1254 return sendGroupMessage(messageBuilder
, groupId
);
1257 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1258 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1259 ) throws IOException
, InvalidNumberException
{
1260 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1261 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1263 resolveSignalServiceAddress(targetAuthorRecipientId
),
1264 targetSentTimestamp
);
1265 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1266 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1269 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1270 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1272 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1274 return sendMessage(messageBuilder
, signalServiceAddresses
);
1275 } catch (Exception e
) {
1276 for (var address
: signalServiceAddresses
) {
1277 handleEndSession(address
);
1283 void renewSession(RecipientId recipientId
) throws IOException
{
1284 account
.getSessionStore().archiveSessions(recipientId
);
1285 if (!recipientId
.equals(getSelfRecipientId())) {
1286 sendNullMessage(recipientId
);
1290 public String
getContactName(String number
) throws InvalidNumberException
{
1291 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1292 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1295 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1296 if (!account
.isMasterDevice()) {
1297 throw new NotMasterDeviceException();
1299 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1300 var contact
= account
.getContactStore().getContact(recipientId
);
1301 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1302 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1305 public void setContactBlocked(
1306 String number
, boolean blocked
1307 ) throws InvalidNumberException
, NotMasterDeviceException
{
1308 if (!account
.isMasterDevice()) {
1309 throw new NotMasterDeviceException();
1311 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1314 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1315 var contact
= account
.getContactStore().getContact(recipientId
);
1316 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1317 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1320 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1321 var group
= getGroup(groupId
);
1322 if (group
== null) {
1323 throw new GroupNotFoundException(groupId
);
1326 group
.setBlocked(blocked
);
1327 account
.getGroupStore().updateGroup(group
);
1330 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1331 var contact
= account
.getContactStore().getContact(recipientId
);
1332 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1335 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1336 account
.getContactStore()
1337 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1340 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1341 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1342 sendMessage(messageBuilder
, Set
.of(recipientId
));
1346 * Change the expiration timer for a contact
1348 public void setExpirationTimer(
1349 String number
, int messageExpirationTimer
1350 ) throws IOException
, InvalidNumberException
{
1351 var recipientId
= canonicalizeAndResolveRecipient(number
);
1352 setExpirationTimer(recipientId
, messageExpirationTimer
);
1353 sendExpirationTimerUpdate(recipientId
);
1357 * Change the expiration timer for a group
1359 private void setExpirationTimer(
1360 GroupInfoV1 groupInfoV1
, int messageExpirationTimer
1361 ) throws NotAGroupMemberException
, GroupNotFoundException
, IOException
{
1362 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1363 account
.getGroupStore().updateGroup(groupInfoV1
);
1364 sendExpirationTimerUpdate(groupInfoV1
.getGroupId());
1367 private void sendExpirationTimerUpdate(GroupIdV1 groupId
) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1368 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1369 sendGroupMessage(messageBuilder
, groupId
);
1373 * Upload the sticker pack from path.
1375 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1376 * @return if successful, returns the URL to install the sticker pack in the signal app
1378 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1379 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1381 var messageSender
= createMessageSender();
1383 var packKey
= KeyUtils
.createStickerUploadKey();
1384 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1386 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1387 account
.getStickerStore().updateSticker(sticker
);
1390 return new URI("https",
1393 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1394 Hex
.toStringCondensed(packKey
),
1395 StandardCharsets
.UTF_8
)).toString();
1396 } catch (URISyntaxException e
) {
1397 throw new AssertionError(e
);
1401 public void requestAllSyncData() throws IOException
{
1402 requestSyncGroups();
1403 requestSyncContacts();
1404 requestSyncBlocked();
1405 requestSyncConfiguration();
1409 private void requestSyncGroups() throws IOException
{
1410 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1411 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1413 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1415 sendSyncMessage(message
);
1416 } catch (UntrustedIdentityException e
) {
1417 throw new AssertionError(e
);
1421 private void requestSyncContacts() throws IOException
{
1422 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1423 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1425 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1427 sendSyncMessage(message
);
1428 } catch (UntrustedIdentityException e
) {
1429 throw new AssertionError(e
);
1433 private void requestSyncBlocked() throws IOException
{
1434 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1435 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1437 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1439 sendSyncMessage(message
);
1440 } catch (UntrustedIdentityException e
) {
1441 throw new AssertionError(e
);
1445 private void requestSyncConfiguration() throws IOException
{
1446 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1447 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1449 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1451 sendSyncMessage(message
);
1452 } catch (UntrustedIdentityException e
) {
1453 throw new AssertionError(e
);
1457 private void requestSyncKeys() throws IOException
{
1458 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1459 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1461 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1463 sendSyncMessage(message
);
1464 } catch (UntrustedIdentityException e
) {
1465 throw new AssertionError(e
);
1469 private byte[] getSenderCertificate() {
1472 if (account
.isPhoneNumberShared()) {
1473 certificate
= accountManager
.getSenderCertificate();
1475 certificate
= accountManager
.getSenderCertificateForPhoneNumberPrivacy();
1477 } catch (IOException e
) {
1478 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1481 // TODO cache for a day
1485 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1486 var messageSender
= createMessageSender();
1487 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1490 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1491 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1492 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1494 for (var number
: numbers
) {
1495 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1496 if (resolvedAddress
.getUuid().isPresent()) {
1497 signalServiceAddresses
.add(resolvedAddress
);
1499 addressesMissingUuid
.add(resolvedAddress
);
1503 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1504 .map(a
-> a
.getNumber().get())
1505 .collect(Collectors
.toSet());
1506 Map
<String
, UUID
> registeredUsers
;
1508 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1509 } catch (IOException e
) {
1510 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1511 registeredUsers
= Map
.of();
1514 for (var address
: addressesMissingUuid
) {
1515 final var number
= address
.getNumber().get();
1516 if (registeredUsers
.containsKey(number
)) {
1517 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1518 registeredUsers
.get(number
),
1520 signalServiceAddresses
.add(newAddress
);
1522 signalServiceAddresses
.add(address
);
1526 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1529 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1530 final var address
= resolveSignalServiceAddress(recipientId
);
1531 if (!address
.getNumber().isPresent()) {
1534 final var number
= address
.getNumber().get();
1535 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1536 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1539 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1541 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1543 serviceEnvironmentConfig
.getCdsMrenclave());
1544 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1545 throw new IOException(e
);
1549 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1550 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1551 ) throws IOException
{
1552 final var timestamp
= System
.currentTimeMillis();
1553 messageBuilder
.withTimestamp(timestamp
);
1554 getOrCreateMessagePipe();
1555 getOrCreateUnidentifiedMessagePipe();
1556 SignalServiceDataMessage message
= null;
1558 message
= messageBuilder
.build();
1559 if (message
.getGroupContext().isPresent()) {
1561 var messageSender
= createMessageSender();
1562 final var isRecipientUpdate
= false;
1563 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1564 final var addresses
= recipientIdList
.stream()
1565 .map(this::resolveSignalServiceAddress
)
1566 .collect(Collectors
.toList());
1567 var result
= messageSender
.sendMessage(addresses
,
1568 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1572 for (var r
: result
) {
1573 if (r
.getIdentityFailure() != null) {
1574 final var recipientId
= resolveRecipient(r
.getAddress());
1575 final var newIdentity
= account
.getIdentityKeyStore()
1576 .saveIdentity(recipientId
, r
.getIdentityFailure().getIdentityKey(), new Date());
1578 account
.getSessionStore().archiveSessions(recipientId
);
1583 return new Pair
<>(timestamp
, result
);
1584 } catch (UntrustedIdentityException e
) {
1585 return new Pair
<>(timestamp
, List
.of());
1588 // Send to all individually, so sync messages are sent correctly
1589 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1590 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1591 for (var recipientId
: recipientIds
) {
1592 final var contact
= account
.getContactStore().getContact(recipientId
);
1593 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1594 messageBuilder
.withExpiration(expirationTime
);
1595 message
= messageBuilder
.build();
1596 results
.add(sendMessage(recipientId
, message
));
1598 return new Pair
<>(timestamp
, results
);
1601 if (message
!= null && message
.isEndSession()) {
1602 for (var recipient
: recipientIds
) {
1603 handleEndSession(recipient
);
1609 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1610 SignalServiceDataMessage
.Builder messageBuilder
1611 ) throws IOException
{
1612 final var timestamp
= System
.currentTimeMillis();
1613 messageBuilder
.withTimestamp(timestamp
);
1614 getOrCreateMessagePipe();
1615 getOrCreateUnidentifiedMessagePipe();
1616 final var recipientId
= account
.getSelfRecipientId();
1618 final var contact
= account
.getContactStore().getContact(recipientId
);
1619 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1620 messageBuilder
.withExpiration(expirationTime
);
1622 var message
= messageBuilder
.build();
1623 final var result
= sendSelfMessage(message
);
1624 return new Pair
<>(timestamp
, result
);
1627 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1628 var messageSender
= createMessageSender();
1630 var recipientId
= account
.getSelfRecipientId();
1632 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipientId
);
1633 var recipient
= resolveSignalServiceAddress(recipientId
);
1634 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1635 message
.getTimestamp(),
1637 message
.getExpiresInSeconds(),
1638 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1640 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1643 var startTime
= System
.currentTimeMillis();
1644 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1645 return SendMessageResult
.success(recipient
,
1646 unidentifiedAccess
.isPresent(),
1648 System
.currentTimeMillis() - startTime
);
1649 } catch (UntrustedIdentityException e
) {
1650 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1654 private SendMessageResult
sendMessage(
1655 RecipientId recipientId
, SignalServiceDataMessage message
1656 ) throws IOException
{
1657 var messageSender
= createMessageSender();
1659 final var address
= resolveSignalServiceAddress(recipientId
);
1662 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
), message
);
1663 } catch (UnregisteredUserException e
) {
1664 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1665 return messageSender
.sendMessage(resolveSignalServiceAddress(newRecipientId
),
1666 unidentifiedAccessHelper
.getAccessFor(newRecipientId
),
1669 } catch (UntrustedIdentityException e
) {
1670 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1674 private SendMessageResult
sendNullMessage(RecipientId recipientId
) throws IOException
{
1675 var messageSender
= createMessageSender();
1677 final var address
= resolveSignalServiceAddress(recipientId
);
1680 return messageSender
.sendNullMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
));
1681 } catch (UnregisteredUserException e
) {
1682 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1683 final var newAddress
= resolveSignalServiceAddress(newRecipientId
);
1684 return messageSender
.sendNullMessage(newAddress
, unidentifiedAccessHelper
.getAccessFor(newRecipientId
));
1686 } catch (UntrustedIdentityException e
) {
1687 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1691 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, ProtocolUntrustedIdentityException
{
1692 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1693 account
.getSignalProtocolStore(),
1695 certificateValidator
);
1696 return cipher
.decrypt(envelope
);
1699 private void handleEndSession(RecipientId recipientId
) {
1700 account
.getSessionStore().deleteAllSessions(recipientId
);
1703 private List
<HandleAction
> handleSignalServiceDataMessage(
1704 SignalServiceDataMessage message
,
1706 SignalServiceAddress source
,
1707 SignalServiceAddress destination
,
1708 boolean ignoreAttachments
1710 var actions
= new ArrayList
<HandleAction
>();
1711 if (message
.getGroupContext().isPresent()) {
1712 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1713 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1714 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1715 var group
= getGroup(groupId
);
1716 if (group
== null || group
instanceof GroupInfoV1
) {
1717 var groupV1
= (GroupInfoV1
) group
;
1718 switch (groupInfo
.getType()) {
1720 if (groupV1
== null) {
1721 groupV1
= new GroupInfoV1(groupId
);
1724 if (groupInfo
.getAvatar().isPresent()) {
1725 var avatar
= groupInfo
.getAvatar().get();
1726 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1729 if (groupInfo
.getName().isPresent()) {
1730 groupV1
.name
= groupInfo
.getName().get();
1733 if (groupInfo
.getMembers().isPresent()) {
1734 groupV1
.addMembers(groupInfo
.getMembers()
1737 .map(this::resolveRecipient
)
1738 .collect(Collectors
.toSet()));
1741 account
.getGroupStore().updateGroup(groupV1
);
1745 if (groupV1
== null && !isSync
) {
1746 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1750 if (groupV1
!= null) {
1751 groupV1
.removeMember(resolveRecipient(source
));
1752 account
.getGroupStore().updateGroup(groupV1
);
1757 if (groupV1
!= null && !isSync
) {
1758 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1763 // Received a group v1 message for a v2 group
1766 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1767 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1768 final var groupMasterKey
= groupContext
.getMasterKey();
1770 getOrMigrateGroup(groupMasterKey
,
1771 groupContext
.getRevision(),
1772 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1776 final var conversationPartnerAddress
= isSync ? destination
: source
;
1777 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1778 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1780 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1781 if (message
.getGroupContext().isPresent()) {
1782 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1783 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1784 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1785 if (group
!= null) {
1786 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1787 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1788 account
.getGroupStore().updateGroup(group
);
1791 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1792 // disappearing message timer already stored in the DecryptedGroup
1794 } else if (conversationPartnerAddress
!= null) {
1795 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1798 if (!ignoreAttachments
) {
1799 if (message
.getAttachments().isPresent()) {
1800 for (var attachment
: message
.getAttachments().get()) {
1801 downloadAttachment(attachment
);
1804 if (message
.getSharedContacts().isPresent()) {
1805 for (var contact
: message
.getSharedContacts().get()) {
1806 if (contact
.getAvatar().isPresent()) {
1807 downloadAttachment(contact
.getAvatar().get().getAttachment());
1812 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1813 final ProfileKey profileKey
;
1815 profileKey
= new ProfileKey(message
.getProfileKey().get());
1816 } catch (InvalidInputException e
) {
1817 throw new AssertionError(e
);
1819 if (source
.matches(account
.getSelfAddress())) {
1820 this.account
.setProfileKey(profileKey
);
1822 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1824 if (message
.getPreviews().isPresent()) {
1825 final var previews
= message
.getPreviews().get();
1826 for (var preview
: previews
) {
1827 if (preview
.getImage().isPresent()) {
1828 downloadAttachment(preview
.getImage().get());
1832 if (message
.getQuote().isPresent()) {
1833 final var quote
= message
.getQuote().get();
1835 for (var quotedAttachment
: quote
.getAttachments()) {
1836 final var thumbnail
= quotedAttachment
.getThumbnail();
1837 if (thumbnail
!= null) {
1838 downloadAttachment(thumbnail
);
1842 if (message
.getSticker().isPresent()) {
1843 final var messageSticker
= message
.getSticker().get();
1844 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1845 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1846 if (sticker
== null) {
1847 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1848 account
.getStickerStore().updateSticker(sticker
);
1854 private GroupInfoV2
getOrMigrateGroup(
1855 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1857 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1859 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1860 var groupInfo
= getGroup(groupId
);
1861 final GroupInfoV2 groupInfoV2
;
1862 if (groupInfo
instanceof GroupInfoV1
) {
1863 // Received a v2 group message for a v1 group, we need to locally migrate the group
1864 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1865 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1866 logger
.info("Locally migrated group {} to group v2, id: {}",
1867 groupInfo
.getGroupId().toBase64(),
1868 groupInfoV2
.getGroupId().toBase64());
1869 } else if (groupInfo
instanceof GroupInfoV2
) {
1870 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1872 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1875 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1876 DecryptedGroup group
= null;
1877 if (signedGroupChange
!= null
1878 && groupInfoV2
.getGroup() != null
1879 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1880 group
= groupV2Helper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(),
1884 if (group
== null) {
1885 group
= groupV2Helper
.getDecryptedGroup(groupSecretParams
);
1887 if (group
!= null) {
1888 storeProfileKeysFromMembers(group
);
1889 final var avatar
= group
.getAvatar();
1890 if (avatar
!= null && !avatar
.isEmpty()) {
1891 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1894 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1895 account
.getGroupStore().updateGroup(groupInfoV2
);
1901 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1902 for (var member
: group
.getMembersList()) {
1903 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
1904 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
1906 account
.getProfileStore()
1907 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
1908 } catch (InvalidInputException ignored
) {
1913 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1914 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1915 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1916 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1917 if (actions
!= null) {
1918 queuedActions
.addAll(actions
);
1921 for (var action
: queuedActions
) {
1923 action
.execute(this);
1924 } catch (Throwable e
) {
1925 logger
.warn("Message action failed.", e
);
1930 private List
<HandleAction
> retryFailedReceivedMessage(
1931 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1933 var envelope
= cachedMessage
.loadEnvelope();
1934 if (envelope
== null) {
1937 SignalServiceContent content
= null;
1938 List
<HandleAction
> actions
= null;
1939 if (!envelope
.isReceipt()) {
1941 content
= decryptMessage(envelope
);
1942 } catch (ProtocolUntrustedIdentityException e
) {
1943 if (!envelope
.hasSource()) {
1944 final var identifier
= e
.getSender();
1945 final var recipientId
= resolveRecipient(identifier
);
1947 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1948 } catch (IOException ioException
) {
1949 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1953 } catch (Exception er
) {
1954 // All other errors are not recoverable, so delete the cached message
1955 cachedMessage
.delete();
1958 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1960 handler
.handleMessage(envelope
, content
, null);
1961 cachedMessage
.delete();
1965 public void receiveMessages(
1968 boolean returnOnTimeout
,
1969 boolean ignoreAttachments
,
1970 ReceiveMessageHandler handler
1971 ) throws IOException
{
1972 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1974 Set
<HandleAction
> queuedActions
= null;
1976 final var messagePipe
= getOrCreateMessagePipe();
1978 var hasCaughtUpWithOldMessages
= false;
1981 SignalServiceEnvelope envelope
;
1982 SignalServiceContent content
= null;
1983 Exception exception
= null;
1984 final CachedMessage
[] cachedMessage
= {null};
1986 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1987 final var recipientId
= envelope1
.hasSource()
1988 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1990 // store message on disk, before acknowledging receipt to the server
1991 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1993 if (result
.isPresent()) {
1994 envelope
= result
.get();
1996 // Received indicator that server queue is empty
1997 hasCaughtUpWithOldMessages
= true;
1999 if (queuedActions
!= null) {
2000 for (var action
: queuedActions
) {
2002 action
.execute(this);
2003 } catch (Throwable e
) {
2004 logger
.warn("Message action failed.", e
);
2007 queuedActions
.clear();
2008 queuedActions
= null;
2011 // Continue to wait another timeout for new messages
2014 } catch (TimeoutException e
) {
2015 if (returnOnTimeout
) return;
2019 if (envelope
.hasSource()) {
2020 // Store uuid if we don't have it already
2021 // address/uuid in envelope is sent by server
2022 resolveRecipientTrusted(envelope
.getSourceAddress());
2024 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
2025 if (!envelope
.isReceipt()) {
2027 content
= decryptMessage(envelope
);
2028 } catch (Exception e
) {
2031 if (!envelope
.hasSource() && content
!= null) {
2032 // Store uuid if we don't have it already
2033 // address/uuid is validated by unidentified sender certificate
2034 resolveRecipientTrusted(content
.getSender());
2036 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
2037 if (exception
instanceof ProtocolInvalidMessageException
) {
2038 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
2039 logger
.debug("Received invalid message, queuing renew session action.");
2040 actions
.add(new RenewSessionAction(sender
));
2042 if (hasCaughtUpWithOldMessages
) {
2043 for (var action
: actions
) {
2045 action
.execute(this);
2046 } catch (Throwable e
) {
2047 logger
.warn("Message action failed.", e
);
2051 if (queuedActions
== null) {
2052 queuedActions
= new HashSet
<>();
2054 queuedActions
.addAll(actions
);
2057 if (isMessageBlocked(envelope
, content
)) {
2058 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
2059 } else if (notAGroupMember
) {
2060 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
2062 handler
.handleMessage(envelope
, content
, exception
);
2064 if (cachedMessage
[0] != null) {
2065 if (exception
instanceof ProtocolUntrustedIdentityException
) {
2066 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
2067 final var recipientId
= resolveRecipient(identifier
);
2068 queuedActions
.add(new RetrieveProfileAction(recipientId
));
2069 if (!envelope
.hasSource()) {
2071 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
2072 } catch (IOException ioException
) {
2073 logger
.warn("Failed to move cached message to recipient folder: {}",
2074 ioException
.getMessage());
2078 cachedMessage
[0].delete();
2084 private boolean isMessageBlocked(
2085 SignalServiceEnvelope envelope
, SignalServiceContent content
2087 SignalServiceAddress source
;
2088 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2089 source
= envelope
.getSourceAddress();
2090 } else if (content
!= null) {
2091 source
= content
.getSender();
2095 final var recipientId
= resolveRecipient(source
);
2096 if (isContactBlocked(recipientId
)) {
2100 if (content
!= null && content
.getDataMessage().isPresent()) {
2101 var message
= content
.getDataMessage().get();
2102 if (message
.getGroupContext().isPresent()) {
2103 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2104 var group
= getGroup(groupId
);
2105 if (group
!= null && group
.isBlocked()) {
2113 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
2114 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
2115 return isContactBlocked(recipientId
);
2118 private boolean isContactBlocked(final RecipientId recipientId
) {
2119 var sourceContact
= account
.getContactStore().getContact(recipientId
);
2120 return sourceContact
!= null && sourceContact
.isBlocked();
2123 private boolean isNotAGroupMember(
2124 SignalServiceEnvelope envelope
, SignalServiceContent content
2126 SignalServiceAddress source
;
2127 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2128 source
= envelope
.getSourceAddress();
2129 } else if (content
!= null) {
2130 source
= content
.getSender();
2135 if (content
!= null && content
.getDataMessage().isPresent()) {
2136 var message
= content
.getDataMessage().get();
2137 if (message
.getGroupContext().isPresent()) {
2138 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
2139 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
2140 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
2144 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2145 var group
= getGroup(groupId
);
2146 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
2154 private List
<HandleAction
> handleMessage(
2155 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
2157 var actions
= new ArrayList
<HandleAction
>();
2158 if (content
!= null) {
2159 final SignalServiceAddress sender
;
2160 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2161 sender
= envelope
.getSourceAddress();
2163 sender
= content
.getSender();
2166 if (content
.getDataMessage().isPresent()) {
2167 var message
= content
.getDataMessage().get();
2169 if (content
.isNeedsReceipt()) {
2170 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
2173 actions
.addAll(handleSignalServiceDataMessage(message
,
2176 account
.getSelfAddress(),
2177 ignoreAttachments
));
2179 if (content
.getSyncMessage().isPresent()) {
2180 account
.setMultiDevice(true);
2181 var syncMessage
= content
.getSyncMessage().get();
2182 if (syncMessage
.getSent().isPresent()) {
2183 var message
= syncMessage
.getSent().get();
2184 final var destination
= message
.getDestination().orNull();
2185 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
2189 ignoreAttachments
));
2191 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
2192 var rm
= syncMessage
.getRequest().get();
2193 if (rm
.isContactsRequest()) {
2194 actions
.add(SendSyncContactsAction
.create());
2196 if (rm
.isGroupsRequest()) {
2197 actions
.add(SendSyncGroupsAction
.create());
2199 if (rm
.isBlockedListRequest()) {
2200 actions
.add(SendSyncBlockedListAction
.create());
2202 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2204 if (syncMessage
.getGroups().isPresent()) {
2205 File tmpFile
= null;
2207 tmpFile
= IOUtils
.createTempFile();
2208 final var groupsMessage
= syncMessage
.getGroups().get();
2209 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2210 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2212 while ((g
= s
.read()) != null) {
2213 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2214 if (syncGroup
!= null) {
2215 if (g
.getName().isPresent()) {
2216 syncGroup
.name
= g
.getName().get();
2218 syncGroup
.addMembers(g
.getMembers()
2220 .map(this::resolveRecipient
)
2221 .collect(Collectors
.toSet()));
2222 if (!g
.isActive()) {
2223 syncGroup
.removeMember(account
.getSelfRecipientId());
2225 // Add ourself to the member set as it's marked as active
2226 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2228 syncGroup
.blocked
= g
.isBlocked();
2229 if (g
.getColor().isPresent()) {
2230 syncGroup
.color
= g
.getColor().get();
2233 if (g
.getAvatar().isPresent()) {
2234 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2236 syncGroup
.archived
= g
.isArchived();
2237 account
.getGroupStore().updateGroup(syncGroup
);
2241 } catch (Exception e
) {
2242 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2246 if (tmpFile
!= null) {
2248 Files
.delete(tmpFile
.toPath());
2249 } catch (IOException e
) {
2250 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2257 if (syncMessage
.getBlockedList().isPresent()) {
2258 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2259 for (var address
: blockedListMessage
.getAddresses()) {
2260 setContactBlocked(resolveRecipient(address
), true);
2262 for (var groupId
: blockedListMessage
.getGroupIds()
2264 .map(GroupId
::unknownVersion
)
2265 .collect(Collectors
.toSet())) {
2267 setGroupBlocked(groupId
, true);
2268 } catch (GroupNotFoundException e
) {
2269 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2270 groupId
.toBase64());
2274 if (syncMessage
.getContacts().isPresent()) {
2275 File tmpFile
= null;
2277 tmpFile
= IOUtils
.createTempFile();
2278 final var contactsMessage
= syncMessage
.getContacts().get();
2279 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2280 .asPointer(), tmpFile
)) {
2281 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2283 while ((c
= s
.read()) != null) {
2284 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2285 account
.setProfileKey(c
.getProfileKey().get());
2287 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2288 var contact
= account
.getContactStore().getContact(recipientId
);
2289 final var builder
= contact
== null
2290 ? Contact
.newBuilder()
2291 : Contact
.newBuilder(contact
);
2292 if (c
.getName().isPresent()) {
2293 builder
.withName(c
.getName().get());
2295 if (c
.getColor().isPresent()) {
2296 builder
.withColor(c
.getColor().get());
2298 if (c
.getProfileKey().isPresent()) {
2299 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2301 if (c
.getVerified().isPresent()) {
2302 final var verifiedMessage
= c
.getVerified().get();
2303 account
.getIdentityKeyStore()
2304 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2305 verifiedMessage
.getIdentityKey(),
2306 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2308 if (c
.getExpirationTimer().isPresent()) {
2309 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2311 builder
.withBlocked(c
.isBlocked());
2312 builder
.withArchived(c
.isArchived());
2313 account
.getContactStore().storeContact(recipientId
, builder
.build());
2315 if (c
.getAvatar().isPresent()) {
2316 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2320 } catch (Exception e
) {
2321 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2325 if (tmpFile
!= null) {
2327 Files
.delete(tmpFile
.toPath());
2328 } catch (IOException e
) {
2329 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2336 if (syncMessage
.getVerified().isPresent()) {
2337 final var verifiedMessage
= syncMessage
.getVerified().get();
2338 account
.getIdentityKeyStore()
2339 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2340 verifiedMessage
.getIdentityKey(),
2341 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2343 if (syncMessage
.getStickerPackOperations().isPresent()) {
2344 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2345 for (var m
: stickerPackOperationMessages
) {
2346 if (!m
.getPackId().isPresent()) {
2349 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2350 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2351 if (sticker
== null) {
2352 if (!m
.getPackKey().isPresent()) {
2355 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2357 sticker
.setInstalled(!m
.getType().isPresent()
2358 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2359 account
.getStickerStore().updateSticker(sticker
);
2362 if (syncMessage
.getFetchType().isPresent()) {
2363 switch (syncMessage
.getFetchType().get()) {
2365 getRecipientProfile(account
.getSelfRecipientId(), true);
2366 case STORAGE_MANIFEST
:
2370 if (syncMessage
.getKeys().isPresent()) {
2371 final var keysMessage
= syncMessage
.getKeys().get();
2372 if (keysMessage
.getStorageService().isPresent()) {
2373 final var storageKey
= keysMessage
.getStorageService().get();
2374 account
.setStorageKey(storageKey
);
2377 if (syncMessage
.getConfiguration().isPresent()) {
2385 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2387 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2388 } catch (IOException e
) {
2389 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2393 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2395 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2396 } catch (IOException e
) {
2397 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2401 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2403 avatarStore
.storeGroupAvatar(groupId
,
2404 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2405 } catch (IOException e
) {
2406 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2410 private void downloadProfileAvatar(
2411 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2414 avatarStore
.storeProfileAvatar(address
,
2415 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2416 } catch (Throwable e
) {
2417 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2421 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2422 return attachmentStore
.getAttachmentFile(attachmentId
);
2425 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2426 if (!attachment
.isPointer()) {
2427 logger
.warn("Invalid state, can't store an attachment stream.");
2430 var pointer
= attachment
.asPointer();
2431 if (pointer
.getPreview().isPresent()) {
2432 final var preview
= pointer
.getPreview().get();
2434 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2435 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2436 } catch (IOException e
) {
2437 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2442 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2443 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2444 } catch (IOException e
) {
2445 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2449 private void retrieveGroupV2Avatar(
2450 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2451 ) throws IOException
{
2452 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2454 var tmpFile
= IOUtils
.createTempFile();
2455 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2457 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2458 var encryptedData
= IOUtils
.readFully(input
);
2460 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2461 outputStream
.write(decryptedData
);
2464 Files
.delete(tmpFile
.toPath());
2465 } catch (IOException e
) {
2466 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2473 private void retrieveProfileAvatar(
2474 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2475 ) throws IOException
{
2476 var tmpFile
= IOUtils
.createTempFile();
2477 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2480 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2481 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2482 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2485 Files
.delete(tmpFile
.toPath());
2486 } catch (IOException e
) {
2487 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2494 private void retrieveAttachment(
2495 final SignalServiceAttachment attachment
, final OutputStream outputStream
2496 ) throws IOException
{
2497 if (attachment
.isPointer()) {
2498 var pointer
= attachment
.asPointer();
2499 retrieveAttachmentPointer(pointer
, outputStream
);
2501 var stream
= attachment
.asStream();
2502 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2506 private void retrieveAttachmentPointer(
2507 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2508 ) throws IOException
{
2509 var tmpFile
= IOUtils
.createTempFile();
2510 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2511 IOUtils
.copyStream(input
, outputStream
);
2512 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2513 throw new IOException(e
);
2516 Files
.delete(tmpFile
.toPath());
2517 } catch (IOException e
) {
2518 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2525 private InputStream
retrieveAttachmentAsStream(
2526 SignalServiceAttachmentPointer pointer
, File tmpFile
2527 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2528 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2531 void sendGroups() throws IOException
, UntrustedIdentityException
{
2532 var groupsFile
= IOUtils
.createTempFile();
2535 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2536 var out
= new DeviceGroupsOutputStream(fos
);
2537 for (var record : getGroups()) {
2538 if (record instanceof GroupInfoV1
) {
2539 var groupInfo
= (GroupInfoV1
) record;
2540 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2541 Optional
.fromNullable(groupInfo
.name
),
2542 groupInfo
.getMembers()
2544 .map(this::resolveSignalServiceAddress
)
2545 .collect(Collectors
.toList()),
2546 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2547 groupInfo
.isMember(account
.getSelfRecipientId()),
2548 Optional
.of(groupInfo
.messageExpirationTime
),
2549 Optional
.fromNullable(groupInfo
.color
),
2552 groupInfo
.archived
));
2557 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2558 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2559 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2560 .withStream(groupsFileStream
)
2561 .withContentType("application/octet-stream")
2562 .withLength(groupsFile
.length())
2565 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2570 Files
.delete(groupsFile
.toPath());
2571 } catch (IOException e
) {
2572 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2577 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2578 var contactsFile
= IOUtils
.createTempFile();
2581 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2582 var out
= new DeviceContactsOutputStream(fos
);
2583 for (var contactPair
: account
.getContactStore().getContacts()) {
2584 final var recipientId
= contactPair
.first();
2585 final var contact
= contactPair
.second();
2586 final var address
= resolveSignalServiceAddress(recipientId
);
2588 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2589 VerifiedMessage verifiedMessage
= null;
2590 if (currentIdentity
!= null) {
2591 verifiedMessage
= new VerifiedMessage(address
,
2592 currentIdentity
.getIdentityKey(),
2593 currentIdentity
.getTrustLevel().toVerifiedState(),
2594 currentIdentity
.getDateAdded().getTime());
2597 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2598 out
.write(new DeviceContact(address
,
2599 Optional
.fromNullable(contact
.getName()),
2600 createContactAvatarAttachment(address
),
2601 Optional
.fromNullable(contact
.getColor()),
2602 Optional
.fromNullable(verifiedMessage
),
2603 Optional
.fromNullable(profileKey
),
2604 contact
.isBlocked(),
2605 Optional
.of(contact
.getMessageExpirationTime()),
2607 contact
.isArchived()));
2610 if (account
.getProfileKey() != null) {
2611 // Send our own profile key as well
2612 out
.write(new DeviceContact(account
.getSelfAddress(),
2617 Optional
.of(account
.getProfileKey()),
2625 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2626 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2627 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2628 .withStream(contactsFileStream
)
2629 .withContentType("application/octet-stream")
2630 .withLength(contactsFile
.length())
2633 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2638 Files
.delete(contactsFile
.toPath());
2639 } catch (IOException e
) {
2640 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2645 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2646 var addresses
= new ArrayList
<SignalServiceAddress
>();
2647 for (var record : account
.getContactStore().getContacts()) {
2648 if (record.second().isBlocked()) {
2649 addresses
.add(resolveSignalServiceAddress(record.first()));
2652 var groupIds
= new ArrayList
<byte[]>();
2653 for (var record : getGroups()) {
2654 if (record.isBlocked()) {
2655 groupIds
.add(record.getGroupId().serialize());
2658 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2661 private void sendVerifiedMessage(
2662 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2663 ) throws IOException
, UntrustedIdentityException
{
2664 var verifiedMessage
= new VerifiedMessage(destination
,
2666 trustLevel
.toVerifiedState(),
2667 System
.currentTimeMillis());
2668 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2671 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2672 return account
.getContactStore().getContacts();
2675 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2676 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2677 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2678 if (recipient
== null) {
2682 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2683 return recipient
.getContact().getName();
2686 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2687 return recipient
.getProfile().getDisplayName();
2693 public GroupInfo
getGroup(GroupId groupId
) {
2694 final var group
= account
.getGroupStore().getGroup(groupId
);
2695 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2696 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2697 ((GroupInfoV2
) group
).setGroup(groupV2Helper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2698 account
.getGroupStore().updateGroup(group
);
2703 public List
<IdentityInfo
> getIdentities() {
2704 return account
.getIdentityKeyStore().getIdentities();
2707 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2708 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2709 return identity
== null ? List
.of() : List
.of(identity
);
2713 * Trust this the identity with this fingerprint
2715 * @param name username of the identity
2716 * @param fingerprint Fingerprint
2718 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2719 var recipientId
= canonicalizeAndResolveRecipient(name
);
2720 return trustIdentity(recipientId
,
2721 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2722 TrustLevel
.TRUSTED_VERIFIED
);
2726 * Trust this the identity with this safety number
2728 * @param name username of the identity
2729 * @param safetyNumber Safety number
2731 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2732 var recipientId
= canonicalizeAndResolveRecipient(name
);
2733 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2734 return trustIdentity(recipientId
,
2735 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2736 TrustLevel
.TRUSTED_VERIFIED
);
2740 * Trust all keys of this identity without verification
2742 * @param name username of the identity
2744 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2745 var recipientId
= canonicalizeAndResolveRecipient(name
);
2746 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2749 private boolean trustIdentity(
2750 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2752 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2753 if (identity
== null) {
2757 if (!verifier
.apply(identity
.getIdentityKey())) {
2761 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2763 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2764 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2765 } catch (IOException
| UntrustedIdentityException e
) {
2766 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2772 public String
computeSafetyNumber(
2773 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2775 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2776 account
.getSelfAddress(),
2777 getIdentityKeyPair().getPublicKey(),
2783 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2784 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2786 return resolveSignalServiceAddress(address
);
2790 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2791 if (address
.matches(account
.getSelfAddress())) {
2792 return account
.getSelfAddress();
2795 return account
.getRecipientStore().resolveServiceAddress(address
);
2798 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2799 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2802 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2803 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2805 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2807 return resolveRecipient(canonicalizedNumber
);
2810 private RecipientId
resolveRecipient(final String identifier
) {
2811 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2813 return resolveRecipient(address
);
2816 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2817 return account
.getRecipientStore().resolveRecipient(address
);
2820 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2821 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2825 public void close() throws IOException
{
2829 void close(boolean closeAccount
) throws IOException
{
2830 executor
.shutdown();
2832 if (messagePipe
!= null) {
2833 messagePipe
.shutdown();
2837 if (unidentifiedMessagePipe
!= null) {
2838 unidentifiedMessagePipe
.shutdown();
2839 unidentifiedMessagePipe
= null;
2842 if (closeAccount
&& account
!= null) {
2848 public interface ReceiveMessageHandler
{
2850 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);