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
.GroupUtils
;
29 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
30 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
31 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
32 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
33 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
34 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
35 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
36 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
37 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
38 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
39 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
40 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
41 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
42 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
43 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
44 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
45 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
46 import org
.asamk
.signal
.manager
.util
.IOUtils
;
47 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
48 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
49 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
50 import org
.asamk
.signal
.manager
.util
.Utils
;
51 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
52 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
53 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
54 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
56 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
57 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
58 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
59 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
60 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
61 import org
.signal
.libsignal
.metadata
.SelfSendException
;
62 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
63 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
64 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
65 import org
.signal
.zkgroup
.InvalidInputException
;
66 import org
.signal
.zkgroup
.VerificationFailedException
;
67 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
68 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
69 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
70 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
71 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
72 import org
.slf4j
.Logger
;
73 import org
.slf4j
.LoggerFactory
;
74 import org
.whispersystems
.libsignal
.IdentityKey
;
75 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
76 import org
.whispersystems
.libsignal
.InvalidKeyException
;
77 import org
.whispersystems
.libsignal
.InvalidMessageException
;
78 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
79 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
80 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
81 import org
.whispersystems
.libsignal
.util
.Pair
;
82 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
83 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
84 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
85 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
86 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
87 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
88 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
89 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
90 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
91 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
92 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
93 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
94 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
95 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
96 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
106 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
107 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
119 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
120 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
121 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
122 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
123 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
124 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
125 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
126 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
127 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
128 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
129 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
130 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
131 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
132 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
133 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
134 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
135 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
136 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
137 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
139 import java
.io
.Closeable
;
141 import java
.io
.FileInputStream
;
142 import java
.io
.FileOutputStream
;
143 import java
.io
.IOException
;
144 import java
.io
.InputStream
;
145 import java
.io
.OutputStream
;
147 import java
.net
.URISyntaxException
;
148 import java
.net
.URLEncoder
;
149 import java
.nio
.charset
.StandardCharsets
;
150 import java
.nio
.file
.Files
;
151 import java
.security
.SignatureException
;
152 import java
.util
.ArrayList
;
153 import java
.util
.Arrays
;
154 import java
.util
.Base64
;
155 import java
.util
.Collection
;
156 import java
.util
.Date
;
157 import java
.util
.HashSet
;
158 import java
.util
.List
;
159 import java
.util
.Map
;
160 import java
.util
.Set
;
161 import java
.util
.UUID
;
162 import java
.util
.concurrent
.ExecutorService
;
163 import java
.util
.concurrent
.Executors
;
164 import java
.util
.concurrent
.TimeUnit
;
165 import java
.util
.concurrent
.TimeoutException
;
166 import java
.util
.concurrent
.locks
.ReentrantLock
;
167 import java
.util
.function
.Function
;
168 import java
.util
.stream
.Collectors
;
170 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
172 public class Manager
implements Closeable
{
174 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
176 private final CertificateValidator certificateValidator
;
178 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
179 private final String userAgent
;
181 private SignalAccount account
;
182 private final SignalServiceAccountManager accountManager
;
183 private final GroupsV2Api groupsV2Api
;
184 private final GroupsV2Operations groupsV2Operations
;
185 private final SignalServiceMessageReceiver messageReceiver
;
186 private final ClientZkProfileOperations clientZkProfileOperations
;
188 private final ExecutorService executor
= Executors
.newCachedThreadPool();
190 private SignalServiceMessagePipe messagePipe
= null;
191 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
193 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
194 private final ProfileHelper profileHelper
;
195 private final GroupV2Helper groupV2Helper
;
196 private final PinHelper pinHelper
;
197 private final AvatarStore avatarStore
;
198 private final AttachmentStore attachmentStore
;
199 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
200 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
203 public Lock
acquire() {
205 return LEGACY_LOCK
::unlock
;
210 SignalAccount account
,
211 PathConfig pathConfig
,
212 ServiceEnvironmentConfig serviceEnvironmentConfig
,
215 this.account
= account
;
216 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
217 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
218 this.userAgent
= userAgent
;
219 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
220 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
221 final SleepTimer timer
= new UptimeSleepTimer();
222 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
223 new DynamicCredentialsProvider(account
.getUuid(),
224 account
.getUsername(),
225 account
.getPassword(),
226 account
.getDeviceId()),
229 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
231 this.groupsV2Api
= accountManager
.getGroupsV2Api();
232 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
233 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
234 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
235 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
238 this.pinHelper
= new PinHelper(keyBackupService
);
239 this.clientZkProfileOperations
= capabilities
.isGv2()
240 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
241 .getProfileOperations()
243 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
245 account
.getUsername(),
246 account
.getPassword(),
247 account
.getDeviceId(),
251 clientZkProfileOperations
,
252 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
254 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
255 account
.getProfileStore()::getProfileKey
,
256 this::getRecipientProfile
,
257 this::getSenderCertificate
);
258 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
259 unidentifiedAccessHelper
::getAccessFor
,
260 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
261 () -> messageReceiver
,
262 this::resolveSignalServiceAddress
);
263 this.groupV2Helper
= new GroupV2Helper(this::getRecipientProfileKeyCredential
,
264 this::getRecipientProfile
,
265 account
::getSelfRecipientId
,
268 this::getGroupAuthForToday
,
269 this::resolveSignalServiceAddress
);
270 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
271 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
274 public String
getUsername() {
275 return account
.getUsername();
278 public SignalServiceAddress
getSelfAddress() {
279 return account
.getSelfAddress();
282 public RecipientId
getSelfRecipientId() {
283 return account
.getSelfRecipientId();
286 private IdentityKeyPair
getIdentityKeyPair() {
287 return account
.getIdentityKeyPair();
290 public int getDeviceId() {
291 return account
.getDeviceId();
294 public static Manager
init(
295 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
296 ) throws IOException
, NotRegisteredException
{
297 var pathConfig
= PathConfig
.createDefault(settingsPath
);
299 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
300 throw new NotRegisteredException();
303 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true);
305 if (!account
.isRegistered()) {
306 throw new NotRegisteredException();
309 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
311 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
314 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
315 var pathConfig
= PathConfig
.createDefault(settingsPath
);
316 final var dataPath
= pathConfig
.getDataPath();
317 final var files
= dataPath
.listFiles();
323 return Arrays
.stream(files
)
324 .filter(File
::isFile
)
326 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
327 .collect(Collectors
.toList());
330 public void checkAccountState() throws IOException
{
331 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
334 if (account
.getUuid() == null) {
335 account
.setUuid(accountManager
.getOwnUuid());
337 updateAccountAttributes();
341 * This is used for checking a set of phone numbers for registration on Signal
343 * @param numbers The set of phone number in question
344 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
345 * @throws IOException if its unable to get the contacts to check if they're registered
347 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
348 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
349 var contactDetails
= getRegisteredUsers(numbers
);
351 var registeredUsers
= contactDetails
.keySet();
353 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
356 public void updateAccountAttributes() throws IOException
{
357 accountManager
.setAccountAttributes(account
.getEncryptedDeviceName(),
359 account
.getLocalRegistrationId(),
361 // set legacy pin only if no KBS master key is set
362 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
363 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
364 account
.getSelfUnidentifiedAccessKey(),
365 account
.isUnrestrictedUnidentifiedAccess(),
367 account
.isDiscoverableByPhoneNumber());
371 * @param givenName if null, the previous givenName will be kept
372 * @param familyName if null, the previous familyName will be kept
373 * @param about if null, the previous about text will be kept
374 * @param aboutEmoji if null, the previous about emoji will be kept
375 * @param avatar if avatar is null the image from the local avatar store is used (if present),
377 public void setProfile(
378 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
379 ) throws IOException
{
380 var profile
= getRecipientProfile(account
.getSelfRecipientId());
381 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
382 if (givenName
!= null) {
383 builder
.withGivenName(givenName
);
385 if (familyName
!= null) {
386 builder
.withFamilyName(familyName
);
389 builder
.withAbout(about
);
391 if (aboutEmoji
!= null) {
392 builder
.withAboutEmoji(aboutEmoji
);
394 var newProfile
= builder
.build();
396 try (final var streamDetails
= avatar
== null
397 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
398 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
399 accountManager
.setVersionedProfile(account
.getUuid(),
400 account
.getProfileKey(),
401 newProfile
.getInternalServiceName(),
402 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
403 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
408 if (avatar
!= null) {
409 if (avatar
.isPresent()) {
410 avatarStore
.storeProfileAvatar(getSelfAddress(),
411 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
413 avatarStore
.deleteProfileAvatar(getSelfAddress());
416 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
419 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
420 } catch (UntrustedIdentityException ignored
) {
424 public void unregister() throws IOException
{
425 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
426 // If this is the master device, other users can't send messages to this number anymore.
427 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
428 accountManager
.setGcmId(Optional
.absent());
430 account
.setRegistered(false);
433 public void deleteAccount() throws IOException
{
434 accountManager
.deleteAccount();
436 account
.setRegistered(false);
439 public List
<Device
> getLinkedDevices() throws IOException
{
440 var devices
= accountManager
.getDevices();
441 account
.setMultiDevice(devices
.size() > 1);
442 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
443 return devices
.stream().map(d
-> {
444 String deviceName
= d
.getName();
445 if (deviceName
!= null) {
447 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
448 } catch (IOException e
) {
449 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
452 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
453 }).collect(Collectors
.toList());
456 public void removeLinkedDevices(int deviceId
) throws IOException
{
457 accountManager
.removeDevice(deviceId
);
458 var devices
= accountManager
.getDevices();
459 account
.setMultiDevice(devices
.size() > 1);
462 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
463 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
465 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
468 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
469 var identityKeyPair
= getIdentityKeyPair();
470 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
472 accountManager
.addDevice(deviceIdentifier
,
475 Optional
.of(account
.getProfileKey().serialize()),
477 account
.setMultiDevice(true);
480 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
481 if (!account
.isMasterDevice()) {
482 throw new RuntimeException("Only master device can set a PIN");
484 if (pin
.isPresent()) {
485 final var masterKey
= account
.getPinMasterKey() != null
486 ? account
.getPinMasterKey()
487 : KeyUtils
.createMasterKey();
489 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
491 account
.setRegistrationLockPin(pin
.get(), masterKey
);
493 // Remove legacy registration lock
494 accountManager
.removeRegistrationLockV1();
497 pinHelper
.removeRegistrationLockPin();
499 account
.setRegistrationLockPin(null, null);
503 void refreshPreKeys() throws IOException
{
504 var oneTimePreKeys
= generatePreKeys();
505 final var identityKeyPair
= getIdentityKeyPair();
506 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
508 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
511 private List
<PreKeyRecord
> generatePreKeys() {
512 final var offset
= account
.getPreKeyIdOffset();
514 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
515 account
.addPreKeys(records
);
520 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
521 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
523 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
524 account
.addSignedPreKey(record);
529 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
530 if (messagePipe
== null) {
531 messagePipe
= messageReceiver
.createMessagePipe();
536 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
537 if (unidentifiedMessagePipe
== null) {
538 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
540 return unidentifiedMessagePipe
;
543 private SignalServiceMessageSender
createMessageSender() {
544 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
546 account
.getUsername(),
547 account
.getPassword(),
548 account
.getDeviceId(),
549 account
.getSignalProtocolStore(),
552 account
.isMultiDevice(),
553 Optional
.fromNullable(messagePipe
),
554 Optional
.fromNullable(unidentifiedMessagePipe
),
556 clientZkProfileOperations
,
558 ServiceConfig
.MAX_ENVELOPE_SIZE
,
559 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
562 public Profile
getRecipientProfile(
563 RecipientId recipientId
565 return getRecipientProfile(recipientId
, false);
568 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
570 Profile
getRecipientProfile(
571 RecipientId recipientId
, boolean force
573 var profile
= account
.getProfileStore().getProfile(recipientId
);
575 var now
= new Date().getTime();
576 // Profiles are cached for 24h before retrieving them again, unless forced
577 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
581 synchronized (pendingProfileRequest
) {
582 if (pendingProfileRequest
.contains(recipientId
)) {
585 pendingProfileRequest
.add(recipientId
);
587 final SignalServiceProfile encryptedProfile
;
589 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
591 synchronized (pendingProfileRequest
) {
592 pendingProfileRequest
.remove(recipientId
);
595 if (encryptedProfile
== null) {
599 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
600 if (profileKey
== null) {
601 profile
= new Profile(new Date().getTime(),
606 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
607 ProfileUtils
.getCapabilities(encryptedProfile
));
609 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
611 account
.getProfileStore().storeProfile(recipientId
, profile
);
616 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
618 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
619 } catch (IOException e
) {
620 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
625 private ProfileAndCredential
retrieveProfileAndCredential(
626 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
627 ) throws IOException
{
628 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
629 final var profile
= profileAndCredential
.getProfile();
632 var newIdentity
= account
.getIdentityKeyStore()
633 .saveIdentity(recipientId
,
634 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
638 account
.getSessionStore().archiveSessions(recipientId
);
640 } catch (InvalidKeyException ignored
) {
641 logger
.warn("Got invalid identity key in profile for {}",
642 resolveSignalServiceAddress(recipientId
).getLegacyIdentifier());
644 return profileAndCredential
;
647 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
648 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
649 if (profileKeyCredential
!= null) {
650 return profileKeyCredential
;
653 ProfileAndCredential profileAndCredential
;
655 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
656 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
657 } catch (IOException e
) {
658 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
662 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
663 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
665 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
666 if (profileKey
!= null) {
667 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
669 profileAndCredential
.getProfile());
670 account
.getProfileStore().storeProfile(recipientId
, profile
);
673 return profileKeyCredential
;
676 private Profile
decryptProfileAndDownloadAvatar(
677 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
679 if (encryptedProfile
.getAvatar() != null) {
680 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
683 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
686 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
687 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
688 if (streamDetails
== null) {
689 return Optional
.absent();
692 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
695 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
696 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
697 if (streamDetails
== null) {
698 return Optional
.absent();
701 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
704 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
705 var g
= getGroup(groupId
);
707 throw new GroupNotFoundException(groupId
);
709 if (!g
.isMember(account
.getSelfRecipientId())) {
710 throw new NotAGroupMemberException(groupId
, g
.getTitle());
715 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
716 var g
= getGroup(groupId
);
718 throw new GroupNotFoundException(groupId
);
720 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
721 throw new NotAGroupMemberException(groupId
, g
.getTitle());
726 public List
<GroupInfo
> getGroups() {
727 return account
.getGroupStore().getGroups();
730 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
731 String messageText
, List
<String
> attachments
, GroupId groupId
732 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
733 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
734 if (attachments
!= null) {
735 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
738 return sendGroupMessage(messageBuilder
, groupId
);
741 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
742 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
743 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
744 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
745 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
747 resolveSignalServiceAddress(targetAuthorRecipientId
),
748 targetSentTimestamp
);
749 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
751 return sendGroupMessage(messageBuilder
, groupId
);
754 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
755 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
756 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
757 final var g
= getGroupForSending(groupId
);
759 GroupUtils
.setGroupContext(messageBuilder
, g
);
760 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
762 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
765 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
766 SignalServiceDataMessage
.Builder messageBuilder
;
768 final var g
= getGroupForUpdating(groupId
);
769 if (g
instanceof GroupInfoV1
) {
770 var groupInfoV1
= (GroupInfoV1
) g
;
771 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
772 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
773 groupInfoV1
.removeMember(account
.getSelfRecipientId());
774 account
.getGroupStore().updateGroup(groupInfoV1
);
776 final var groupInfoV2
= (GroupInfoV2
) g
;
777 final var groupGroupChangePair
= groupV2Helper
.leaveGroup(groupInfoV2
);
778 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
779 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
780 account
.getGroupStore().updateGroup(groupInfoV2
);
783 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
786 public Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
787 String name
, List
<String
> members
, File avatarFile
788 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
789 return createGroup(name
, members
== null ?
null : getSignalServiceAddresses(members
), avatarFile
);
792 private Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
793 String name
, Set
<RecipientId
> members
, File avatarFile
794 ) throws IOException
, AttachmentInvalidException
{
795 final var selfRecipientId
= account
.getSelfRecipientId();
796 if (members
!= null && members
.contains(selfRecipientId
)) {
797 members
= new HashSet
<>(members
);
798 members
.remove(selfRecipientId
);
801 var gv2Pair
= groupV2Helper
.createGroup(name
== null ?
"" : name
,
802 members
== null ? Set
.of() : members
,
805 SignalServiceDataMessage
.Builder messageBuilder
;
806 if (gv2Pair
== null) {
807 // Failed to create v2 group, creating v1 group instead
808 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
809 gv1
.addMembers(List
.of(selfRecipientId
));
810 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
811 return new Pair
<>(gv1
.getGroupId(), result
.second());
814 final var gv2
= gv2Pair
.first();
815 final var decryptedGroup
= gv2Pair
.second();
817 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
818 if (avatarFile
!= null) {
819 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
820 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
822 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
823 account
.getGroupStore().updateGroup(gv2
);
825 final var result
= sendMessage(messageBuilder
, gv2
.getMembersIncludingPendingWithout(selfRecipientId
));
826 return new Pair
<>(gv2
.getGroupId(), result
.second());
829 public Pair
<Long
, List
<SendMessageResult
>> updateGroup(
833 List
<String
> members
,
834 List
<String
> removeMembers
,
836 List
<String
> removeAdmins
,
837 boolean resetGroupLink
,
838 GroupLinkState groupLinkState
,
840 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
841 return updateGroup(groupId
,
844 members
== null ?
null : getSignalServiceAddresses(members
),
845 removeMembers
== null ?
null : getSignalServiceAddresses(removeMembers
),
846 admins
== null ?
null : getSignalServiceAddresses(admins
),
847 removeAdmins
== null ?
null : getSignalServiceAddresses(removeAdmins
),
853 private Pair
<Long
, List
<SendMessageResult
>> updateGroup(
854 final GroupId groupId
,
856 final String description
,
857 final Set
<RecipientId
> members
,
858 final Set
<RecipientId
> removeMembers
,
859 final Set
<RecipientId
> admins
,
860 final Set
<RecipientId
> removeAdmins
,
861 final boolean resetGroupLink
,
862 final GroupLinkState groupLinkState
,
863 final File avatarFile
864 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
865 var group
= getGroupForUpdating(groupId
);
867 if (group
instanceof GroupInfoV2
) {
868 return updateGroupV2((GroupInfoV2
) group
,
880 return updateGroupV1((GroupInfoV1
) group
, name
, members
, avatarFile
);
883 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV1(
884 final GroupInfoV1 gv1
, final String name
, final Set
<RecipientId
> members
, final File avatarFile
885 ) throws IOException
, AttachmentInvalidException
{
886 updateGroupV1Details(gv1
, name
, members
, avatarFile
);
887 var messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
889 account
.getGroupStore().updateGroup(gv1
);
891 return sendMessage(messageBuilder
, gv1
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
894 private void updateGroupV1Details(
895 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
896 ) throws IOException
{
901 if (members
!= null) {
902 final var newMemberAddresses
= members
.stream()
903 .filter(member
-> !g
.isMember(member
))
904 .map(this::resolveSignalServiceAddress
)
905 .collect(Collectors
.toList());
906 final var newE164Members
= new HashSet
<String
>();
907 for (var member
: newMemberAddresses
) {
908 if (!member
.getNumber().isPresent()) {
911 newE164Members
.add(member
.getNumber().get());
914 final var registeredUsers
= getRegisteredUsers(newE164Members
);
915 if (registeredUsers
.size() != newE164Members
.size()) {
916 // Some of the new members are not registered on Signal
917 newE164Members
.removeAll(registeredUsers
.keySet());
918 throw new IOException("Failed to add members "
919 + String
.join(", ", newE164Members
)
920 + " to group: Not registered on Signal");
923 g
.addMembers(members
);
926 if (avatarFile
!= null) {
927 avatarStore
.storeGroupAvatar(g
.getGroupId(),
928 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
932 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV2(
933 final GroupInfoV2 group
,
935 final String description
,
936 final Set
<RecipientId
> members
,
937 final Set
<RecipientId
> removeMembers
,
938 final Set
<RecipientId
> admins
,
939 final Set
<RecipientId
> removeAdmins
,
940 final boolean resetGroupLink
,
941 final GroupLinkState groupLinkState
,
942 final File avatarFile
943 ) throws IOException
{
944 Pair
<Long
, List
<SendMessageResult
>> result
= null;
945 if (group
.isPendingMember(account
.getSelfRecipientId())) {
946 var groupGroupChangePair
= groupV2Helper
.acceptInvite(group
);
947 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
950 if (members
!= null) {
951 final var newMembers
= new HashSet
<>(members
);
952 newMembers
.removeAll(group
.getMembers());
953 if (newMembers
.size() > 0) {
954 var groupGroupChangePair
= groupV2Helper
.addMembers(group
, newMembers
);
955 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
959 if (removeMembers
!= null) {
960 var existingRemoveMembers
= new HashSet
<>(removeMembers
);
961 existingRemoveMembers
.retainAll(group
.getMembers());
962 existingRemoveMembers
.remove(getSelfRecipientId());// self can be removed with sendQuitGroupMessage
963 if (existingRemoveMembers
.size() > 0) {
964 var groupGroupChangePair
= groupV2Helper
.removeMembers(group
, existingRemoveMembers
);
965 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
968 var pendingRemoveMembers
= new HashSet
<>(removeMembers
);
969 pendingRemoveMembers
.retainAll(group
.getPendingMembers());
970 if (pendingRemoveMembers
.size() > 0) {
971 var groupGroupChangePair
= groupV2Helper
.revokeInvitedMembers(group
, pendingRemoveMembers
);
972 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
976 if (admins
!= null) {
977 final var newAdmins
= new HashSet
<>(admins
);
978 newAdmins
.retainAll(group
.getMembers());
979 newAdmins
.removeAll(group
.getAdminMembers());
980 if (newAdmins
.size() > 0) {
981 for (var admin
: newAdmins
) {
982 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, true);
983 result
= sendUpdateGroupV2Message(group
,
984 groupGroupChangePair
.first(),
985 groupGroupChangePair
.second());
990 if (removeAdmins
!= null) {
991 final var existingRemoveAdmins
= new HashSet
<>(removeAdmins
);
992 existingRemoveAdmins
.retainAll(group
.getAdminMembers());
993 if (existingRemoveAdmins
.size() > 0) {
994 for (var admin
: existingRemoveAdmins
) {
995 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, false);
996 result
= sendUpdateGroupV2Message(group
,
997 groupGroupChangePair
.first(),
998 groupGroupChangePair
.second());
1003 if (resetGroupLink
) {
1004 var groupGroupChangePair
= groupV2Helper
.resetGroupLinkPassword(group
);
1005 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1008 if (groupLinkState
!= null) {
1009 var groupGroupChangePair
= groupV2Helper
.setGroupLinkState(group
, groupLinkState
);
1010 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1013 if (result
== null || name
!= null || description
!= null || avatarFile
!= null) {
1014 var groupGroupChangePair
= groupV2Helper
.updateGroup(group
, name
, description
, avatarFile
);
1015 if (avatarFile
!= null) {
1016 avatarStore
.storeGroupAvatar(group
.getGroupId(),
1017 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
1019 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1025 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
1026 GroupInviteLinkUrl inviteLinkUrl
1027 ) throws IOException
, GroupLinkNotActiveException
{
1028 final var groupJoinInfo
= groupV2Helper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
1029 inviteLinkUrl
.getPassword());
1030 final var groupChange
= groupV2Helper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
1031 inviteLinkUrl
.getPassword(),
1033 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
1034 groupJoinInfo
.getRevision() + 1,
1035 groupChange
.toByteArray());
1037 if (group
.getGroup() == null) {
1038 // Only requested member, can't send update to group members
1039 return new Pair
<>(group
.getGroupId(), List
.of());
1042 final var result
= sendUpdateGroupV2Message(group
, group
.getGroup(), groupChange
);
1044 return new Pair
<>(group
.getGroupId(), result
.second());
1047 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupV2Message(
1048 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
1049 ) throws IOException
{
1050 final var selfRecipientId
= account
.getSelfRecipientId();
1051 final var members
= group
.getMembersIncludingPendingWithout(selfRecipientId
);
1052 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
1053 members
.addAll(group
.getMembersIncludingPendingWithout(selfRecipientId
));
1055 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
1056 account
.getGroupStore().updateGroup(group
);
1057 return sendMessage(messageBuilder
, members
);
1060 private static int currentTimeDays() {
1061 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
1064 private GroupsV2AuthorizationString
getGroupAuthForToday(
1065 final GroupSecretParams groupSecretParams
1066 ) throws IOException
{
1067 final var today
= currentTimeDays();
1068 // Returns credentials for the next 7 days
1069 final var credentials
= groupsV2Api
.getCredentials(today
);
1070 // TODO cache credentials until they expire
1071 var authCredentialResponse
= credentials
.get(today
);
1073 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
1076 authCredentialResponse
);
1077 } catch (VerificationFailedException e
) {
1078 throw new IOException(e
);
1082 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
1083 GroupIdV1 groupId
, SignalServiceAddress recipient
1084 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
1086 var group
= getGroupForSending(groupId
);
1087 if (!(group
instanceof GroupInfoV1
)) {
1088 throw new RuntimeException("Received an invalid group request for a v2 group!");
1090 g
= (GroupInfoV1
) group
;
1092 final var recipientId
= resolveRecipient(recipient
);
1093 if (!g
.isMember(recipientId
)) {
1094 throw new NotAGroupMemberException(groupId
, g
.name
);
1097 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
1099 // Send group message only to the recipient who requested it
1100 return sendMessage(messageBuilder
, Set
.of(recipientId
));
1103 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
1104 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
1105 .withId(g
.getGroupId().serialize())
1107 .withMembers(g
.getMembers()
1109 .map(this::resolveSignalServiceAddress
)
1110 .collect(Collectors
.toList()));
1113 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
1114 if (attachment
.isPresent()) {
1115 group
.withAvatar(attachment
.get());
1117 } catch (IOException e
) {
1118 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
1121 return SignalServiceDataMessage
.newBuilder()
1122 .asGroupMessage(group
.build())
1123 .withExpiration(g
.getMessageExpirationTime());
1126 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
1127 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
1128 .withRevision(g
.getGroup().getRevision())
1129 .withSignedGroupChange(signedGroupChange
);
1130 return SignalServiceDataMessage
.newBuilder()
1131 .asGroupMessage(group
.build())
1132 .withExpiration(g
.getMessageExpirationTime());
1135 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
1136 GroupIdV1 groupId
, SignalServiceAddress recipient
1137 ) throws IOException
{
1138 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
1140 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
1142 // Send group info request message to the recipient who sent us a message with this groupId
1143 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1147 SignalServiceAddress remoteAddress
, long messageId
1148 ) throws IOException
, UntrustedIdentityException
{
1149 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1151 System
.currentTimeMillis());
1153 createMessageSender().sendReceipt(remoteAddress
,
1154 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1158 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1159 String messageText
, List
<String
> attachments
, List
<String
> recipients
1160 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1161 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1162 if (attachments
!= null) {
1163 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1165 // Upload attachments here, so we only upload once even for multiple recipients
1166 var messageSender
= createMessageSender();
1167 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1168 for (var attachment
: attachmentStreams
) {
1169 if (attachment
.isStream()) {
1170 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1171 } else if (attachment
.isPointer()) {
1172 attachmentPointers
.add(attachment
.asPointer());
1176 messageBuilder
.withAttachments(attachmentPointers
);
1178 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1181 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1182 String messageText
, List
<String
> attachments
1183 ) throws IOException
, AttachmentInvalidException
{
1184 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1185 if (attachments
!= null) {
1186 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1188 return sendSelfMessage(messageBuilder
);
1191 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1192 long targetSentTimestamp
, List
<String
> recipients
1193 ) throws IOException
, InvalidNumberException
{
1194 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1195 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1196 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1199 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1200 long targetSentTimestamp
, GroupId groupId
1201 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1202 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1203 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1204 return sendGroupMessage(messageBuilder
, groupId
);
1207 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1208 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1209 ) throws IOException
, InvalidNumberException
{
1210 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1211 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1213 resolveSignalServiceAddress(targetAuthorRecipientId
),
1214 targetSentTimestamp
);
1215 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1216 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1219 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1220 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1222 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1224 return sendMessage(messageBuilder
, signalServiceAddresses
);
1225 } catch (Exception e
) {
1226 for (var address
: signalServiceAddresses
) {
1227 handleEndSession(address
);
1233 void renewSession(RecipientId recipientId
) throws IOException
{
1234 account
.getSessionStore().archiveSessions(recipientId
);
1235 if (!recipientId
.equals(getSelfRecipientId())) {
1236 sendNullMessage(recipientId
);
1240 public String
getContactName(String number
) throws InvalidNumberException
{
1241 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1242 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1245 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1246 if (!account
.isMasterDevice()) {
1247 throw new NotMasterDeviceException();
1249 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1250 var contact
= account
.getContactStore().getContact(recipientId
);
1251 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1252 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1255 public void setContactBlocked(
1256 String number
, boolean blocked
1257 ) throws InvalidNumberException
, NotMasterDeviceException
{
1258 if (!account
.isMasterDevice()) {
1259 throw new NotMasterDeviceException();
1261 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1264 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1265 var contact
= account
.getContactStore().getContact(recipientId
);
1266 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1267 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1270 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1271 var group
= getGroup(groupId
);
1272 if (group
== null) {
1273 throw new GroupNotFoundException(groupId
);
1276 group
.setBlocked(blocked
);
1277 account
.getGroupStore().updateGroup(group
);
1280 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1281 var contact
= account
.getContactStore().getContact(recipientId
);
1282 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1285 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1286 account
.getContactStore()
1287 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1290 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1291 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1292 sendMessage(messageBuilder
, Set
.of(recipientId
));
1296 * Change the expiration timer for a contact
1298 public void setExpirationTimer(
1299 String number
, int messageExpirationTimer
1300 ) throws IOException
, InvalidNumberException
{
1301 var recipientId
= canonicalizeAndResolveRecipient(number
);
1302 setExpirationTimer(recipientId
, messageExpirationTimer
);
1303 sendExpirationTimerUpdate(recipientId
);
1307 * Change the expiration timer for a group
1309 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1310 var g
= getGroup(groupId
);
1311 if (g
instanceof GroupInfoV1
) {
1312 var groupInfoV1
= (GroupInfoV1
) g
;
1313 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1314 account
.getGroupStore().updateGroup(groupInfoV1
);
1316 throw new RuntimeException("TODO Not implemented!");
1321 * Upload the sticker pack from path.
1323 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1324 * @return if successful, returns the URL to install the sticker pack in the signal app
1326 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1327 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1329 var messageSender
= createMessageSender();
1331 var packKey
= KeyUtils
.createStickerUploadKey();
1332 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1334 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1335 account
.getStickerStore().updateSticker(sticker
);
1338 return new URI("https",
1341 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1342 Hex
.toStringCondensed(packKey
),
1343 StandardCharsets
.UTF_8
)).toString();
1344 } catch (URISyntaxException e
) {
1345 throw new AssertionError(e
);
1349 public void requestAllSyncData() throws IOException
{
1350 requestSyncGroups();
1351 requestSyncContacts();
1352 requestSyncBlocked();
1353 requestSyncConfiguration();
1357 private void requestSyncGroups() throws IOException
{
1358 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1359 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1361 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1363 sendSyncMessage(message
);
1364 } catch (UntrustedIdentityException e
) {
1365 throw new AssertionError(e
);
1369 private void requestSyncContacts() throws IOException
{
1370 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1371 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1373 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1375 sendSyncMessage(message
);
1376 } catch (UntrustedIdentityException e
) {
1377 throw new AssertionError(e
);
1381 private void requestSyncBlocked() throws IOException
{
1382 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1383 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1385 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1387 sendSyncMessage(message
);
1388 } catch (UntrustedIdentityException e
) {
1389 throw new AssertionError(e
);
1393 private void requestSyncConfiguration() throws IOException
{
1394 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1395 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1397 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1399 sendSyncMessage(message
);
1400 } catch (UntrustedIdentityException e
) {
1401 throw new AssertionError(e
);
1405 private void requestSyncKeys() throws IOException
{
1406 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1407 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1409 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1411 sendSyncMessage(message
);
1412 } catch (UntrustedIdentityException e
) {
1413 throw new AssertionError(e
);
1417 private byte[] getSenderCertificate() {
1420 if (account
.isPhoneNumberShared()) {
1421 certificate
= accountManager
.getSenderCertificate();
1423 certificate
= accountManager
.getSenderCertificateForPhoneNumberPrivacy();
1425 } catch (IOException e
) {
1426 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1429 // TODO cache for a day
1433 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1434 var messageSender
= createMessageSender();
1435 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1438 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1439 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1440 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1442 for (var number
: numbers
) {
1443 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1444 if (resolvedAddress
.getUuid().isPresent()) {
1445 signalServiceAddresses
.add(resolvedAddress
);
1447 addressesMissingUuid
.add(resolvedAddress
);
1451 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1452 .map(a
-> a
.getNumber().get())
1453 .collect(Collectors
.toSet());
1454 Map
<String
, UUID
> registeredUsers
;
1456 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1457 } catch (IOException e
) {
1458 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1459 registeredUsers
= Map
.of();
1462 for (var address
: addressesMissingUuid
) {
1463 final var number
= address
.getNumber().get();
1464 if (registeredUsers
.containsKey(number
)) {
1465 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1466 registeredUsers
.get(number
),
1468 signalServiceAddresses
.add(newAddress
);
1470 signalServiceAddresses
.add(address
);
1474 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1477 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1478 final var address
= resolveSignalServiceAddress(recipientId
);
1479 if (!address
.getNumber().isPresent()) {
1482 final var number
= address
.getNumber().get();
1483 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1484 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1487 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1489 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1491 serviceEnvironmentConfig
.getCdsMrenclave());
1492 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1493 throw new IOException(e
);
1497 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1498 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1499 ) throws IOException
{
1500 final var timestamp
= System
.currentTimeMillis();
1501 messageBuilder
.withTimestamp(timestamp
);
1502 getOrCreateMessagePipe();
1503 getOrCreateUnidentifiedMessagePipe();
1504 SignalServiceDataMessage message
= null;
1506 message
= messageBuilder
.build();
1507 if (message
.getGroupContext().isPresent()) {
1509 var messageSender
= createMessageSender();
1510 final var isRecipientUpdate
= false;
1511 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1512 final var addresses
= recipientIdList
.stream()
1513 .map(this::resolveSignalServiceAddress
)
1514 .collect(Collectors
.toList());
1515 var result
= messageSender
.sendMessage(addresses
,
1516 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1520 for (var r
: result
) {
1521 if (r
.getIdentityFailure() != null) {
1522 final var recipientId
= resolveRecipient(r
.getAddress());
1523 final var newIdentity
= account
.getIdentityKeyStore()
1524 .saveIdentity(recipientId
, r
.getIdentityFailure().getIdentityKey(), new Date());
1526 account
.getSessionStore().archiveSessions(recipientId
);
1531 return new Pair
<>(timestamp
, result
);
1532 } catch (UntrustedIdentityException e
) {
1533 return new Pair
<>(timestamp
, List
.of());
1536 // Send to all individually, so sync messages are sent correctly
1537 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1538 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1539 for (var recipientId
: recipientIds
) {
1540 final var contact
= account
.getContactStore().getContact(recipientId
);
1541 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1542 messageBuilder
.withExpiration(expirationTime
);
1543 message
= messageBuilder
.build();
1544 results
.add(sendMessage(recipientId
, message
));
1546 return new Pair
<>(timestamp
, results
);
1549 if (message
!= null && message
.isEndSession()) {
1550 for (var recipient
: recipientIds
) {
1551 handleEndSession(recipient
);
1557 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1558 SignalServiceDataMessage
.Builder messageBuilder
1559 ) throws IOException
{
1560 final var timestamp
= System
.currentTimeMillis();
1561 messageBuilder
.withTimestamp(timestamp
);
1562 getOrCreateMessagePipe();
1563 getOrCreateUnidentifiedMessagePipe();
1564 final var recipientId
= account
.getSelfRecipientId();
1566 final var contact
= account
.getContactStore().getContact(recipientId
);
1567 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1568 messageBuilder
.withExpiration(expirationTime
);
1570 var message
= messageBuilder
.build();
1571 final var result
= sendSelfMessage(message
);
1572 return new Pair
<>(timestamp
, result
);
1575 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1576 var messageSender
= createMessageSender();
1578 var recipientId
= account
.getSelfRecipientId();
1580 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipientId
);
1581 var recipient
= resolveSignalServiceAddress(recipientId
);
1582 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1583 message
.getTimestamp(),
1585 message
.getExpiresInSeconds(),
1586 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1588 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1591 var startTime
= System
.currentTimeMillis();
1592 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1593 return SendMessageResult
.success(recipient
,
1594 unidentifiedAccess
.isPresent(),
1596 System
.currentTimeMillis() - startTime
);
1597 } catch (UntrustedIdentityException e
) {
1598 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1602 private SendMessageResult
sendMessage(
1603 RecipientId recipientId
, SignalServiceDataMessage message
1604 ) throws IOException
{
1605 var messageSender
= createMessageSender();
1607 final var address
= resolveSignalServiceAddress(recipientId
);
1610 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
), message
);
1611 } catch (UnregisteredUserException e
) {
1612 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1613 return messageSender
.sendMessage(resolveSignalServiceAddress(newRecipientId
),
1614 unidentifiedAccessHelper
.getAccessFor(newRecipientId
),
1617 } catch (UntrustedIdentityException e
) {
1618 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1622 private SendMessageResult
sendNullMessage(RecipientId recipientId
) throws IOException
{
1623 var messageSender
= createMessageSender();
1625 final var address
= resolveSignalServiceAddress(recipientId
);
1628 return messageSender
.sendNullMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
));
1629 } catch (UnregisteredUserException e
) {
1630 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1631 final var newAddress
= resolveSignalServiceAddress(newRecipientId
);
1632 return messageSender
.sendNullMessage(newAddress
, unidentifiedAccessHelper
.getAccessFor(newRecipientId
));
1634 } catch (UntrustedIdentityException e
) {
1635 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1639 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, ProtocolUntrustedIdentityException
{
1640 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1641 account
.getSignalProtocolStore(),
1643 certificateValidator
);
1644 return cipher
.decrypt(envelope
);
1647 private void handleEndSession(RecipientId recipientId
) {
1648 account
.getSessionStore().deleteAllSessions(recipientId
);
1651 private List
<HandleAction
> handleSignalServiceDataMessage(
1652 SignalServiceDataMessage message
,
1654 SignalServiceAddress source
,
1655 SignalServiceAddress destination
,
1656 boolean ignoreAttachments
1658 var actions
= new ArrayList
<HandleAction
>();
1659 if (message
.getGroupContext().isPresent()) {
1660 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1661 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1662 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1663 var group
= getGroup(groupId
);
1664 if (group
== null || group
instanceof GroupInfoV1
) {
1665 var groupV1
= (GroupInfoV1
) group
;
1666 switch (groupInfo
.getType()) {
1668 if (groupV1
== null) {
1669 groupV1
= new GroupInfoV1(groupId
);
1672 if (groupInfo
.getAvatar().isPresent()) {
1673 var avatar
= groupInfo
.getAvatar().get();
1674 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1677 if (groupInfo
.getName().isPresent()) {
1678 groupV1
.name
= groupInfo
.getName().get();
1681 if (groupInfo
.getMembers().isPresent()) {
1682 groupV1
.addMembers(groupInfo
.getMembers()
1685 .map(this::resolveRecipient
)
1686 .collect(Collectors
.toSet()));
1689 account
.getGroupStore().updateGroup(groupV1
);
1693 if (groupV1
== null && !isSync
) {
1694 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1698 if (groupV1
!= null) {
1699 groupV1
.removeMember(resolveRecipient(source
));
1700 account
.getGroupStore().updateGroup(groupV1
);
1705 if (groupV1
!= null && !isSync
) {
1706 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1711 // Received a group v1 message for a v2 group
1714 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1715 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1716 final var groupMasterKey
= groupContext
.getMasterKey();
1718 getOrMigrateGroup(groupMasterKey
,
1719 groupContext
.getRevision(),
1720 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1724 final var conversationPartnerAddress
= isSync ? destination
: source
;
1725 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1726 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1728 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1729 if (message
.getGroupContext().isPresent()) {
1730 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1731 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1732 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1733 if (group
!= null) {
1734 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1735 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1736 account
.getGroupStore().updateGroup(group
);
1739 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1740 // disappearing message timer already stored in the DecryptedGroup
1742 } else if (conversationPartnerAddress
!= null) {
1743 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1746 if (!ignoreAttachments
) {
1747 if (message
.getAttachments().isPresent()) {
1748 for (var attachment
: message
.getAttachments().get()) {
1749 downloadAttachment(attachment
);
1752 if (message
.getSharedContacts().isPresent()) {
1753 for (var contact
: message
.getSharedContacts().get()) {
1754 if (contact
.getAvatar().isPresent()) {
1755 downloadAttachment(contact
.getAvatar().get().getAttachment());
1760 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1761 final ProfileKey profileKey
;
1763 profileKey
= new ProfileKey(message
.getProfileKey().get());
1764 } catch (InvalidInputException e
) {
1765 throw new AssertionError(e
);
1767 if (source
.matches(account
.getSelfAddress())) {
1768 this.account
.setProfileKey(profileKey
);
1770 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1772 if (message
.getPreviews().isPresent()) {
1773 final var previews
= message
.getPreviews().get();
1774 for (var preview
: previews
) {
1775 if (preview
.getImage().isPresent()) {
1776 downloadAttachment(preview
.getImage().get());
1780 if (message
.getQuote().isPresent()) {
1781 final var quote
= message
.getQuote().get();
1783 for (var quotedAttachment
: quote
.getAttachments()) {
1784 final var thumbnail
= quotedAttachment
.getThumbnail();
1785 if (thumbnail
!= null) {
1786 downloadAttachment(thumbnail
);
1790 if (message
.getSticker().isPresent()) {
1791 final var messageSticker
= message
.getSticker().get();
1792 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1793 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1794 if (sticker
== null) {
1795 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1796 account
.getStickerStore().updateSticker(sticker
);
1802 private GroupInfoV2
getOrMigrateGroup(
1803 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1805 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1807 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1808 var groupInfo
= getGroup(groupId
);
1809 final GroupInfoV2 groupInfoV2
;
1810 if (groupInfo
instanceof GroupInfoV1
) {
1811 // Received a v2 group message for a v1 group, we need to locally migrate the group
1812 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1813 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1814 logger
.info("Locally migrated group {} to group v2, id: {}",
1815 groupInfo
.getGroupId().toBase64(),
1816 groupInfoV2
.getGroupId().toBase64());
1817 } else if (groupInfo
instanceof GroupInfoV2
) {
1818 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1820 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1823 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1824 DecryptedGroup group
= null;
1825 if (signedGroupChange
!= null
1826 && groupInfoV2
.getGroup() != null
1827 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1828 group
= groupV2Helper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(),
1832 if (group
== null) {
1833 group
= groupV2Helper
.getDecryptedGroup(groupSecretParams
);
1835 if (group
!= null) {
1836 storeProfileKeysFromMembers(group
);
1837 final var avatar
= group
.getAvatar();
1838 if (avatar
!= null && !avatar
.isEmpty()) {
1839 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1842 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1843 account
.getGroupStore().updateGroup(groupInfoV2
);
1849 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1850 for (var member
: group
.getMembersList()) {
1851 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
1852 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
1854 account
.getProfileStore()
1855 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
1856 } catch (InvalidInputException ignored
) {
1861 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1862 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1863 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1864 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1865 if (actions
!= null) {
1866 queuedActions
.addAll(actions
);
1869 for (var action
: queuedActions
) {
1871 action
.execute(this);
1872 } catch (Throwable e
) {
1873 logger
.warn("Message action failed.", e
);
1878 private List
<HandleAction
> retryFailedReceivedMessage(
1879 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1881 var envelope
= cachedMessage
.loadEnvelope();
1882 if (envelope
== null) {
1885 SignalServiceContent content
= null;
1886 List
<HandleAction
> actions
= null;
1887 if (!envelope
.isReceipt()) {
1889 content
= decryptMessage(envelope
);
1890 } catch (ProtocolUntrustedIdentityException e
) {
1891 if (!envelope
.hasSource()) {
1892 final var identifier
= e
.getSender();
1893 final var recipientId
= resolveRecipient(identifier
);
1895 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1896 } catch (IOException ioException
) {
1897 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1901 } catch (Exception er
) {
1902 // All other errors are not recoverable, so delete the cached message
1903 cachedMessage
.delete();
1906 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1908 handler
.handleMessage(envelope
, content
, null);
1909 cachedMessage
.delete();
1913 public void receiveMessages(
1916 boolean returnOnTimeout
,
1917 boolean ignoreAttachments
,
1918 ReceiveMessageHandler handler
1919 ) throws IOException
{
1920 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1922 Set
<HandleAction
> queuedActions
= null;
1924 final var messagePipe
= getOrCreateMessagePipe();
1926 var hasCaughtUpWithOldMessages
= false;
1929 SignalServiceEnvelope envelope
;
1930 SignalServiceContent content
= null;
1931 Exception exception
= null;
1932 final CachedMessage
[] cachedMessage
= {null};
1934 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1935 final var recipientId
= envelope1
.hasSource()
1936 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1938 // store message on disk, before acknowledging receipt to the server
1939 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1941 if (result
.isPresent()) {
1942 envelope
= result
.get();
1944 // Received indicator that server queue is empty
1945 hasCaughtUpWithOldMessages
= true;
1947 if (queuedActions
!= null) {
1948 for (var action
: queuedActions
) {
1950 action
.execute(this);
1951 } catch (Throwable e
) {
1952 logger
.warn("Message action failed.", e
);
1955 queuedActions
.clear();
1956 queuedActions
= null;
1959 // Continue to wait another timeout for new messages
1962 } catch (TimeoutException e
) {
1963 if (returnOnTimeout
) return;
1967 if (envelope
.hasSource()) {
1968 // Store uuid if we don't have it already
1969 // address/uuid in envelope is sent by server
1970 resolveRecipientTrusted(envelope
.getSourceAddress());
1972 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1973 if (!envelope
.isReceipt()) {
1975 content
= decryptMessage(envelope
);
1976 } catch (Exception e
) {
1979 if (!envelope
.hasSource() && content
!= null) {
1980 // Store uuid if we don't have it already
1981 // address/uuid is validated by unidentified sender certificate
1982 resolveRecipientTrusted(content
.getSender());
1984 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1985 if (exception
instanceof ProtocolInvalidMessageException
) {
1986 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
1987 logger
.debug("Received invalid message, queuing renew session action.");
1988 actions
.add(new RenewSessionAction(sender
));
1990 if (hasCaughtUpWithOldMessages
) {
1991 for (var action
: actions
) {
1993 action
.execute(this);
1994 } catch (Throwable e
) {
1995 logger
.warn("Message action failed.", e
);
1999 if (queuedActions
== null) {
2000 queuedActions
= new HashSet
<>();
2002 queuedActions
.addAll(actions
);
2005 if (isMessageBlocked(envelope
, content
)) {
2006 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
2007 } else if (notAGroupMember
) {
2008 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
2010 handler
.handleMessage(envelope
, content
, exception
);
2012 if (cachedMessage
[0] != null) {
2013 if (exception
instanceof ProtocolUntrustedIdentityException
) {
2014 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
2015 final var recipientId
= resolveRecipient(identifier
);
2016 queuedActions
.add(new RetrieveProfileAction(recipientId
));
2017 if (!envelope
.hasSource()) {
2019 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
2020 } catch (IOException ioException
) {
2021 logger
.warn("Failed to move cached message to recipient folder: {}",
2022 ioException
.getMessage());
2026 cachedMessage
[0].delete();
2032 private boolean isMessageBlocked(
2033 SignalServiceEnvelope envelope
, SignalServiceContent content
2035 SignalServiceAddress source
;
2036 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2037 source
= envelope
.getSourceAddress();
2038 } else if (content
!= null) {
2039 source
= content
.getSender();
2043 final var recipientId
= resolveRecipient(source
);
2044 if (isContactBlocked(recipientId
)) {
2048 if (content
!= null && content
.getDataMessage().isPresent()) {
2049 var message
= content
.getDataMessage().get();
2050 if (message
.getGroupContext().isPresent()) {
2051 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2052 var group
= getGroup(groupId
);
2053 if (group
!= null && group
.isBlocked()) {
2061 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
2062 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
2063 return isContactBlocked(recipientId
);
2066 private boolean isContactBlocked(final RecipientId recipientId
) {
2067 var sourceContact
= account
.getContactStore().getContact(recipientId
);
2068 return sourceContact
!= null && sourceContact
.isBlocked();
2071 private boolean isNotAGroupMember(
2072 SignalServiceEnvelope envelope
, SignalServiceContent content
2074 SignalServiceAddress source
;
2075 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2076 source
= envelope
.getSourceAddress();
2077 } else if (content
!= null) {
2078 source
= content
.getSender();
2083 if (content
!= null && content
.getDataMessage().isPresent()) {
2084 var message
= content
.getDataMessage().get();
2085 if (message
.getGroupContext().isPresent()) {
2086 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
2087 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
2088 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
2092 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2093 var group
= getGroup(groupId
);
2094 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
2102 private List
<HandleAction
> handleMessage(
2103 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
2105 var actions
= new ArrayList
<HandleAction
>();
2106 if (content
!= null) {
2107 final SignalServiceAddress sender
;
2108 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2109 sender
= envelope
.getSourceAddress();
2111 sender
= content
.getSender();
2114 if (content
.getDataMessage().isPresent()) {
2115 var message
= content
.getDataMessage().get();
2117 if (content
.isNeedsReceipt()) {
2118 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
2121 actions
.addAll(handleSignalServiceDataMessage(message
,
2124 account
.getSelfAddress(),
2125 ignoreAttachments
));
2127 if (content
.getSyncMessage().isPresent()) {
2128 account
.setMultiDevice(true);
2129 var syncMessage
= content
.getSyncMessage().get();
2130 if (syncMessage
.getSent().isPresent()) {
2131 var message
= syncMessage
.getSent().get();
2132 final var destination
= message
.getDestination().orNull();
2133 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
2137 ignoreAttachments
));
2139 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
2140 var rm
= syncMessage
.getRequest().get();
2141 if (rm
.isContactsRequest()) {
2142 actions
.add(SendSyncContactsAction
.create());
2144 if (rm
.isGroupsRequest()) {
2145 actions
.add(SendSyncGroupsAction
.create());
2147 if (rm
.isBlockedListRequest()) {
2148 actions
.add(SendSyncBlockedListAction
.create());
2150 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2152 if (syncMessage
.getGroups().isPresent()) {
2153 File tmpFile
= null;
2155 tmpFile
= IOUtils
.createTempFile();
2156 final var groupsMessage
= syncMessage
.getGroups().get();
2157 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2158 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2160 while ((g
= s
.read()) != null) {
2161 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2162 if (syncGroup
!= null) {
2163 if (g
.getName().isPresent()) {
2164 syncGroup
.name
= g
.getName().get();
2166 syncGroup
.addMembers(g
.getMembers()
2168 .map(this::resolveRecipient
)
2169 .collect(Collectors
.toSet()));
2170 if (!g
.isActive()) {
2171 syncGroup
.removeMember(account
.getSelfRecipientId());
2173 // Add ourself to the member set as it's marked as active
2174 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2176 syncGroup
.blocked
= g
.isBlocked();
2177 if (g
.getColor().isPresent()) {
2178 syncGroup
.color
= g
.getColor().get();
2181 if (g
.getAvatar().isPresent()) {
2182 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2184 syncGroup
.archived
= g
.isArchived();
2185 account
.getGroupStore().updateGroup(syncGroup
);
2189 } catch (Exception e
) {
2190 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2194 if (tmpFile
!= null) {
2196 Files
.delete(tmpFile
.toPath());
2197 } catch (IOException e
) {
2198 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2205 if (syncMessage
.getBlockedList().isPresent()) {
2206 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2207 for (var address
: blockedListMessage
.getAddresses()) {
2208 setContactBlocked(resolveRecipient(address
), true);
2210 for (var groupId
: blockedListMessage
.getGroupIds()
2212 .map(GroupId
::unknownVersion
)
2213 .collect(Collectors
.toSet())) {
2215 setGroupBlocked(groupId
, true);
2216 } catch (GroupNotFoundException e
) {
2217 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2218 groupId
.toBase64());
2222 if (syncMessage
.getContacts().isPresent()) {
2223 File tmpFile
= null;
2225 tmpFile
= IOUtils
.createTempFile();
2226 final var contactsMessage
= syncMessage
.getContacts().get();
2227 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2228 .asPointer(), tmpFile
)) {
2229 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2231 while ((c
= s
.read()) != null) {
2232 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2233 account
.setProfileKey(c
.getProfileKey().get());
2235 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2236 var contact
= account
.getContactStore().getContact(recipientId
);
2237 final var builder
= contact
== null
2238 ? Contact
.newBuilder()
2239 : Contact
.newBuilder(contact
);
2240 if (c
.getName().isPresent()) {
2241 builder
.withName(c
.getName().get());
2243 if (c
.getColor().isPresent()) {
2244 builder
.withColor(c
.getColor().get());
2246 if (c
.getProfileKey().isPresent()) {
2247 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2249 if (c
.getVerified().isPresent()) {
2250 final var verifiedMessage
= c
.getVerified().get();
2251 account
.getIdentityKeyStore()
2252 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2253 verifiedMessage
.getIdentityKey(),
2254 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2256 if (c
.getExpirationTimer().isPresent()) {
2257 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2259 builder
.withBlocked(c
.isBlocked());
2260 builder
.withArchived(c
.isArchived());
2261 account
.getContactStore().storeContact(recipientId
, builder
.build());
2263 if (c
.getAvatar().isPresent()) {
2264 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2268 } catch (Exception e
) {
2269 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2273 if (tmpFile
!= null) {
2275 Files
.delete(tmpFile
.toPath());
2276 } catch (IOException e
) {
2277 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2284 if (syncMessage
.getVerified().isPresent()) {
2285 final var verifiedMessage
= syncMessage
.getVerified().get();
2286 account
.getIdentityKeyStore()
2287 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2288 verifiedMessage
.getIdentityKey(),
2289 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2291 if (syncMessage
.getStickerPackOperations().isPresent()) {
2292 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2293 for (var m
: stickerPackOperationMessages
) {
2294 if (!m
.getPackId().isPresent()) {
2297 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2298 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2299 if (sticker
== null) {
2300 if (!m
.getPackKey().isPresent()) {
2303 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2305 sticker
.setInstalled(!m
.getType().isPresent()
2306 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2307 account
.getStickerStore().updateSticker(sticker
);
2310 if (syncMessage
.getFetchType().isPresent()) {
2311 switch (syncMessage
.getFetchType().get()) {
2313 getRecipientProfile(account
.getSelfRecipientId(), true);
2314 case STORAGE_MANIFEST
:
2318 if (syncMessage
.getKeys().isPresent()) {
2319 final var keysMessage
= syncMessage
.getKeys().get();
2320 if (keysMessage
.getStorageService().isPresent()) {
2321 final var storageKey
= keysMessage
.getStorageService().get();
2322 account
.setStorageKey(storageKey
);
2325 if (syncMessage
.getConfiguration().isPresent()) {
2333 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2335 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2336 } catch (IOException e
) {
2337 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2341 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2343 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2344 } catch (IOException e
) {
2345 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2349 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2351 avatarStore
.storeGroupAvatar(groupId
,
2352 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2353 } catch (IOException e
) {
2354 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2358 private void downloadProfileAvatar(
2359 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2362 avatarStore
.storeProfileAvatar(address
,
2363 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2364 } catch (Throwable e
) {
2365 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2369 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2370 return attachmentStore
.getAttachmentFile(attachmentId
);
2373 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2374 if (!attachment
.isPointer()) {
2375 logger
.warn("Invalid state, can't store an attachment stream.");
2378 var pointer
= attachment
.asPointer();
2379 if (pointer
.getPreview().isPresent()) {
2380 final var preview
= pointer
.getPreview().get();
2382 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2383 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2384 } catch (IOException e
) {
2385 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2390 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2391 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2392 } catch (IOException e
) {
2393 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2397 private void retrieveGroupV2Avatar(
2398 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2399 ) throws IOException
{
2400 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2402 var tmpFile
= IOUtils
.createTempFile();
2403 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2405 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2406 var encryptedData
= IOUtils
.readFully(input
);
2408 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2409 outputStream
.write(decryptedData
);
2412 Files
.delete(tmpFile
.toPath());
2413 } catch (IOException e
) {
2414 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2421 private void retrieveProfileAvatar(
2422 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2423 ) throws IOException
{
2424 var tmpFile
= IOUtils
.createTempFile();
2425 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2428 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2429 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2430 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2433 Files
.delete(tmpFile
.toPath());
2434 } catch (IOException e
) {
2435 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2442 private void retrieveAttachment(
2443 final SignalServiceAttachment attachment
, final OutputStream outputStream
2444 ) throws IOException
{
2445 if (attachment
.isPointer()) {
2446 var pointer
= attachment
.asPointer();
2447 retrieveAttachmentPointer(pointer
, outputStream
);
2449 var stream
= attachment
.asStream();
2450 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2454 private void retrieveAttachmentPointer(
2455 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2456 ) throws IOException
{
2457 var tmpFile
= IOUtils
.createTempFile();
2458 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2459 IOUtils
.copyStream(input
, outputStream
);
2460 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2461 throw new IOException(e
);
2464 Files
.delete(tmpFile
.toPath());
2465 } catch (IOException e
) {
2466 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2473 private InputStream
retrieveAttachmentAsStream(
2474 SignalServiceAttachmentPointer pointer
, File tmpFile
2475 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2476 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2479 void sendGroups() throws IOException
, UntrustedIdentityException
{
2480 var groupsFile
= IOUtils
.createTempFile();
2483 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2484 var out
= new DeviceGroupsOutputStream(fos
);
2485 for (var record : getGroups()) {
2486 if (record instanceof GroupInfoV1
) {
2487 var groupInfo
= (GroupInfoV1
) record;
2488 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2489 Optional
.fromNullable(groupInfo
.name
),
2490 groupInfo
.getMembers()
2492 .map(this::resolveSignalServiceAddress
)
2493 .collect(Collectors
.toList()),
2494 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2495 groupInfo
.isMember(account
.getSelfRecipientId()),
2496 Optional
.of(groupInfo
.messageExpirationTime
),
2497 Optional
.fromNullable(groupInfo
.color
),
2500 groupInfo
.archived
));
2505 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2506 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2507 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2508 .withStream(groupsFileStream
)
2509 .withContentType("application/octet-stream")
2510 .withLength(groupsFile
.length())
2513 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2518 Files
.delete(groupsFile
.toPath());
2519 } catch (IOException e
) {
2520 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2525 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2526 var contactsFile
= IOUtils
.createTempFile();
2529 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2530 var out
= new DeviceContactsOutputStream(fos
);
2531 for (var contactPair
: account
.getContactStore().getContacts()) {
2532 final var recipientId
= contactPair
.first();
2533 final var contact
= contactPair
.second();
2534 final var address
= resolveSignalServiceAddress(recipientId
);
2536 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2537 VerifiedMessage verifiedMessage
= null;
2538 if (currentIdentity
!= null) {
2539 verifiedMessage
= new VerifiedMessage(address
,
2540 currentIdentity
.getIdentityKey(),
2541 currentIdentity
.getTrustLevel().toVerifiedState(),
2542 currentIdentity
.getDateAdded().getTime());
2545 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2546 out
.write(new DeviceContact(address
,
2547 Optional
.fromNullable(contact
.getName()),
2548 createContactAvatarAttachment(address
),
2549 Optional
.fromNullable(contact
.getColor()),
2550 Optional
.fromNullable(verifiedMessage
),
2551 Optional
.fromNullable(profileKey
),
2552 contact
.isBlocked(),
2553 Optional
.of(contact
.getMessageExpirationTime()),
2555 contact
.isArchived()));
2558 if (account
.getProfileKey() != null) {
2559 // Send our own profile key as well
2560 out
.write(new DeviceContact(account
.getSelfAddress(),
2565 Optional
.of(account
.getProfileKey()),
2573 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2574 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2575 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2576 .withStream(contactsFileStream
)
2577 .withContentType("application/octet-stream")
2578 .withLength(contactsFile
.length())
2581 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2586 Files
.delete(contactsFile
.toPath());
2587 } catch (IOException e
) {
2588 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2593 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2594 var addresses
= new ArrayList
<SignalServiceAddress
>();
2595 for (var record : account
.getContactStore().getContacts()) {
2596 if (record.second().isBlocked()) {
2597 addresses
.add(resolveSignalServiceAddress(record.first()));
2600 var groupIds
= new ArrayList
<byte[]>();
2601 for (var record : getGroups()) {
2602 if (record.isBlocked()) {
2603 groupIds
.add(record.getGroupId().serialize());
2606 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2609 private void sendVerifiedMessage(
2610 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2611 ) throws IOException
, UntrustedIdentityException
{
2612 var verifiedMessage
= new VerifiedMessage(destination
,
2614 trustLevel
.toVerifiedState(),
2615 System
.currentTimeMillis());
2616 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2619 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2620 return account
.getContactStore().getContacts();
2623 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2624 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2625 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2626 if (recipient
== null) {
2630 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2631 return recipient
.getContact().getName();
2634 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2635 return recipient
.getProfile().getDisplayName();
2641 public GroupInfo
getGroup(GroupId groupId
) {
2642 final var group
= account
.getGroupStore().getGroup(groupId
);
2643 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2644 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2645 ((GroupInfoV2
) group
).setGroup(groupV2Helper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2646 account
.getGroupStore().updateGroup(group
);
2651 public List
<IdentityInfo
> getIdentities() {
2652 return account
.getIdentityKeyStore().getIdentities();
2655 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2656 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2657 return identity
== null ? List
.of() : List
.of(identity
);
2661 * Trust this the identity with this fingerprint
2663 * @param name username of the identity
2664 * @param fingerprint Fingerprint
2666 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2667 var recipientId
= canonicalizeAndResolveRecipient(name
);
2668 return trustIdentity(recipientId
,
2669 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2670 TrustLevel
.TRUSTED_VERIFIED
);
2674 * Trust this the identity with this safety number
2676 * @param name username of the identity
2677 * @param safetyNumber Safety number
2679 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2680 var recipientId
= canonicalizeAndResolveRecipient(name
);
2681 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2682 return trustIdentity(recipientId
,
2683 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2684 TrustLevel
.TRUSTED_VERIFIED
);
2688 * Trust all keys of this identity without verification
2690 * @param name username of the identity
2692 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2693 var recipientId
= canonicalizeAndResolveRecipient(name
);
2694 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2697 private boolean trustIdentity(
2698 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2700 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2701 if (identity
== null) {
2705 if (!verifier
.apply(identity
.getIdentityKey())) {
2709 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2711 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2712 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2713 } catch (IOException
| UntrustedIdentityException e
) {
2714 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2720 public String
computeSafetyNumber(
2721 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2723 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2724 account
.getSelfAddress(),
2725 getIdentityKeyPair().getPublicKey(),
2731 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2732 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2734 return resolveSignalServiceAddress(address
);
2738 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2739 if (address
.matches(account
.getSelfAddress())) {
2740 return account
.getSelfAddress();
2743 return account
.getRecipientStore().resolveServiceAddress(address
);
2746 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2747 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2750 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2751 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2753 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2755 return resolveRecipient(canonicalizedNumber
);
2758 private RecipientId
resolveRecipient(final String identifier
) {
2759 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2761 return resolveRecipient(address
);
2764 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2765 return account
.getRecipientStore().resolveRecipient(address
);
2768 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2769 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2773 public void close() throws IOException
{
2777 void close(boolean closeAccount
) throws IOException
{
2778 executor
.shutdown();
2780 if (messagePipe
!= null) {
2781 messagePipe
.shutdown();
2785 if (unidentifiedMessagePipe
!= null) {
2786 unidentifiedMessagePipe
.shutdown();
2787 unidentifiedMessagePipe
= null;
2790 if (closeAccount
&& account
!= null) {
2796 public interface ReceiveMessageHandler
{
2798 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);