2 Copyright (C) 2015-2021 AsamK and contributors
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.signal
.manager
.api
.Device
;
20 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
21 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
22 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
23 import org
.asamk
.signal
.manager
.groups
.GroupId
;
24 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
25 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
26 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
27 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
28 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
29 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
30 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
31 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
32 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
33 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
34 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
35 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
36 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
37 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
38 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
39 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
40 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
41 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
42 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
43 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
44 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
45 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
46 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
47 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
48 import org
.asamk
.signal
.manager
.util
.IOUtils
;
49 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
50 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
51 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
52 import org
.asamk
.signal
.manager
.util
.Utils
;
53 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
54 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
56 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
57 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
58 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
59 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
60 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
61 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
62 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
63 import org
.signal
.libsignal
.metadata
.SelfSendException
;
64 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
65 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
66 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
67 import org
.signal
.zkgroup
.InvalidInputException
;
68 import org
.signal
.zkgroup
.VerificationFailedException
;
69 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
70 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
71 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
72 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
73 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
74 import org
.slf4j
.Logger
;
75 import org
.slf4j
.LoggerFactory
;
76 import org
.whispersystems
.libsignal
.IdentityKey
;
77 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
78 import org
.whispersystems
.libsignal
.InvalidKeyException
;
79 import org
.whispersystems
.libsignal
.InvalidMessageException
;
80 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
81 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
82 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
83 import org
.whispersystems
.libsignal
.util
.Pair
;
84 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
85 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
86 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
87 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
88 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
89 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
90 import org
.whispersystems
.signalservice
.api
.crypto
.ContentHint
;
91 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
92 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
93 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
94 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
95 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
96 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
97 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
106 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
107 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
108 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
121 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
122 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
123 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
124 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
125 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.ConflictException
;
126 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
127 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
128 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
129 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
130 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
131 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
132 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
133 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
134 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
135 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
136 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
137 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
138 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
139 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
140 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
141 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
143 import java
.io
.Closeable
;
145 import java
.io
.FileInputStream
;
146 import java
.io
.FileOutputStream
;
147 import java
.io
.IOException
;
148 import java
.io
.InputStream
;
149 import java
.io
.OutputStream
;
151 import java
.net
.URISyntaxException
;
152 import java
.net
.URLEncoder
;
153 import java
.nio
.charset
.StandardCharsets
;
154 import java
.nio
.file
.Files
;
155 import java
.security
.SignatureException
;
156 import java
.util
.ArrayList
;
157 import java
.util
.Arrays
;
158 import java
.util
.Base64
;
159 import java
.util
.Collection
;
160 import java
.util
.Date
;
161 import java
.util
.HashSet
;
162 import java
.util
.List
;
163 import java
.util
.Map
;
164 import java
.util
.Set
;
165 import java
.util
.UUID
;
166 import java
.util
.concurrent
.ExecutorService
;
167 import java
.util
.concurrent
.Executors
;
168 import java
.util
.concurrent
.TimeUnit
;
169 import java
.util
.concurrent
.TimeoutException
;
170 import java
.util
.concurrent
.locks
.ReentrantLock
;
171 import java
.util
.function
.Function
;
172 import java
.util
.stream
.Collectors
;
174 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
176 public class Manager
implements Closeable
{
178 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
180 private final CertificateValidator certificateValidator
;
182 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
183 private final String userAgent
;
185 private SignalAccount account
;
186 private final SignalServiceAccountManager accountManager
;
187 private final GroupsV2Api groupsV2Api
;
188 private final GroupsV2Operations groupsV2Operations
;
189 private final SignalServiceMessageReceiver messageReceiver
;
190 private final ClientZkProfileOperations clientZkProfileOperations
;
192 private final ExecutorService executor
= Executors
.newCachedThreadPool();
194 private SignalServiceMessagePipe messagePipe
= null;
195 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
197 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
198 private final ProfileHelper profileHelper
;
199 private final GroupV2Helper groupV2Helper
;
200 private final PinHelper pinHelper
;
201 private final AvatarStore avatarStore
;
202 private final AttachmentStore attachmentStore
;
203 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
204 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
207 public Lock
acquire() {
209 return LEGACY_LOCK
::unlock
;
214 SignalAccount account
,
215 PathConfig pathConfig
,
216 ServiceEnvironmentConfig serviceEnvironmentConfig
,
219 this.account
= account
;
220 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
221 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
222 this.userAgent
= userAgent
;
223 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
224 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
225 final SleepTimer timer
= new UptimeSleepTimer();
226 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
227 new DynamicCredentialsProvider(account
.getUuid(),
228 account
.getUsername(),
229 account
.getPassword(),
230 account
.getDeviceId()),
233 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
235 this.groupsV2Api
= accountManager
.getGroupsV2Api();
236 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
237 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
238 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
239 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
242 this.pinHelper
= new PinHelper(keyBackupService
);
243 this.clientZkProfileOperations
= capabilities
.isGv2()
244 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
245 .getProfileOperations()
247 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
249 account
.getUsername(),
250 account
.getPassword(),
251 account
.getDeviceId(),
255 clientZkProfileOperations
,
256 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
258 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
259 account
.getProfileStore()::getProfileKey
,
260 this::getRecipientProfile
,
261 this::getSenderCertificate
);
262 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
263 unidentifiedAccessHelper
::getAccessFor
,
264 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
265 () -> messageReceiver
,
266 this::resolveSignalServiceAddress
);
267 this.groupV2Helper
= new GroupV2Helper(this::getRecipientProfileKeyCredential
,
268 this::getRecipientProfile
,
269 account
::getSelfRecipientId
,
272 this::getGroupAuthForToday
,
273 this::resolveSignalServiceAddress
);
274 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
275 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
278 public String
getUsername() {
279 return account
.getUsername();
282 public SignalServiceAddress
getSelfAddress() {
283 return account
.getSelfAddress();
286 public RecipientId
getSelfRecipientId() {
287 return account
.getSelfRecipientId();
290 private IdentityKeyPair
getIdentityKeyPair() {
291 return account
.getIdentityKeyPair();
294 public int getDeviceId() {
295 return account
.getDeviceId();
298 public static Manager
init(
299 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
300 ) throws IOException
, NotRegisteredException
{
301 var pathConfig
= PathConfig
.createDefault(settingsPath
);
303 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
304 throw new NotRegisteredException();
307 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true);
309 if (!account
.isRegistered()) {
310 throw new NotRegisteredException();
313 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
315 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
318 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
319 var pathConfig
= PathConfig
.createDefault(settingsPath
);
320 final var dataPath
= pathConfig
.getDataPath();
321 final var files
= dataPath
.listFiles();
327 return Arrays
.stream(files
)
328 .filter(File
::isFile
)
330 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
331 .collect(Collectors
.toList());
334 public void checkAccountState() throws IOException
{
335 if (account
.getLastReceiveTimestamp() == 0) {
336 logger
.warn("The Signal protocol expects that incoming messages are regularly received.");
338 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
339 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
342 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
346 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
349 if (account
.getUuid() == null) {
350 account
.setUuid(accountManager
.getOwnUuid());
352 updateAccountAttributes();
356 * This is used for checking a set of phone numbers for registration on Signal
358 * @param numbers The set of phone number in question
359 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
360 * @throws IOException if its unable to get the contacts to check if they're registered
362 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
363 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
364 var contactDetails
= getRegisteredUsers(numbers
);
366 var registeredUsers
= contactDetails
.keySet();
368 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
371 public void updateAccountAttributes() throws IOException
{
372 accountManager
.setAccountAttributes(account
.getEncryptedDeviceName(),
374 account
.getLocalRegistrationId(),
376 // set legacy pin only if no KBS master key is set
377 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
378 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
379 account
.getSelfUnidentifiedAccessKey(),
380 account
.isUnrestrictedUnidentifiedAccess(),
382 account
.isDiscoverableByPhoneNumber());
386 * @param givenName if null, the previous givenName will be kept
387 * @param familyName if null, the previous familyName will be kept
388 * @param about if null, the previous about text will be kept
389 * @param aboutEmoji if null, the previous about emoji will be kept
390 * @param avatar if avatar is null the image from the local avatar store is used (if present),
392 public void setProfile(
393 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
394 ) throws IOException
{
395 var profile
= getRecipientProfile(account
.getSelfRecipientId());
396 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
397 if (givenName
!= null) {
398 builder
.withGivenName(givenName
);
400 if (familyName
!= null) {
401 builder
.withFamilyName(familyName
);
404 builder
.withAbout(about
);
406 if (aboutEmoji
!= null) {
407 builder
.withAboutEmoji(aboutEmoji
);
409 var newProfile
= builder
.build();
411 try (final var streamDetails
= avatar
== null
412 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
413 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
414 accountManager
.setVersionedProfile(account
.getUuid(),
415 account
.getProfileKey(),
416 newProfile
.getInternalServiceName(),
417 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
418 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
423 if (avatar
!= null) {
424 if (avatar
.isPresent()) {
425 avatarStore
.storeProfileAvatar(getSelfAddress(),
426 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
428 avatarStore
.deleteProfileAvatar(getSelfAddress());
431 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
434 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
435 } catch (UntrustedIdentityException ignored
) {
439 public void unregister() throws IOException
{
440 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
441 // If this is the master device, other users can't send messages to this number anymore.
442 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
443 accountManager
.setGcmId(Optional
.absent());
445 account
.setRegistered(false);
448 public void deleteAccount() throws IOException
{
449 accountManager
.deleteAccount();
451 account
.setRegistered(false);
454 public List
<Device
> getLinkedDevices() throws IOException
{
455 var devices
= accountManager
.getDevices();
456 account
.setMultiDevice(devices
.size() > 1);
457 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
458 return devices
.stream().map(d
-> {
459 String deviceName
= d
.getName();
460 if (deviceName
!= null) {
462 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
463 } catch (IOException e
) {
464 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
467 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
468 }).collect(Collectors
.toList());
471 public void removeLinkedDevices(int deviceId
) throws IOException
{
472 accountManager
.removeDevice(deviceId
);
473 var devices
= accountManager
.getDevices();
474 account
.setMultiDevice(devices
.size() > 1);
477 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
478 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
480 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
483 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
484 var identityKeyPair
= getIdentityKeyPair();
485 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
487 accountManager
.addDevice(deviceIdentifier
,
490 Optional
.of(account
.getProfileKey().serialize()),
492 account
.setMultiDevice(true);
495 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
496 if (!account
.isMasterDevice()) {
497 throw new RuntimeException("Only master device can set a PIN");
499 if (pin
.isPresent()) {
500 final var masterKey
= account
.getPinMasterKey() != null
501 ? account
.getPinMasterKey()
502 : KeyUtils
.createMasterKey();
504 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
506 account
.setRegistrationLockPin(pin
.get(), masterKey
);
508 // Remove legacy registration lock
509 accountManager
.removeRegistrationLockV1();
512 pinHelper
.removeRegistrationLockPin();
514 account
.setRegistrationLockPin(null, null);
518 void refreshPreKeys() throws IOException
{
519 var oneTimePreKeys
= generatePreKeys();
520 final var identityKeyPair
= getIdentityKeyPair();
521 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
523 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
526 private List
<PreKeyRecord
> generatePreKeys() {
527 final var offset
= account
.getPreKeyIdOffset();
529 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
530 account
.addPreKeys(records
);
535 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
536 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
538 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
539 account
.addSignedPreKey(record);
544 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
545 if (messagePipe
== null) {
546 messagePipe
= messageReceiver
.createMessagePipe();
551 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
552 if (unidentifiedMessagePipe
== null) {
553 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
555 return unidentifiedMessagePipe
;
558 private SignalServiceMessageSender
createMessageSender() {
559 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
561 account
.getUsername(),
562 account
.getPassword(),
563 account
.getDeviceId(),
564 account
.getSignalProtocolStore(),
567 account
.isMultiDevice(),
568 Optional
.fromNullable(messagePipe
),
569 Optional
.fromNullable(unidentifiedMessagePipe
),
571 clientZkProfileOperations
,
573 ServiceConfig
.MAX_ENVELOPE_SIZE
,
574 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
577 public Profile
getRecipientProfile(
578 RecipientId recipientId
580 return getRecipientProfile(recipientId
, false);
583 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
585 Profile
getRecipientProfile(
586 RecipientId recipientId
, boolean force
588 var profile
= account
.getProfileStore().getProfile(recipientId
);
590 var now
= System
.currentTimeMillis();
591 // Profiles are cached for 24h before retrieving them again, unless forced
592 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
596 synchronized (pendingProfileRequest
) {
597 if (pendingProfileRequest
.contains(recipientId
)) {
600 pendingProfileRequest
.add(recipientId
);
602 final SignalServiceProfile encryptedProfile
;
604 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
606 synchronized (pendingProfileRequest
) {
607 pendingProfileRequest
.remove(recipientId
);
610 if (encryptedProfile
== null) {
614 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
615 if (profileKey
== null) {
616 profile
= new Profile(System
.currentTimeMillis(),
621 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
622 ProfileUtils
.getCapabilities(encryptedProfile
));
624 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
626 account
.getProfileStore().storeProfile(recipientId
, profile
);
631 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
633 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
634 } catch (IOException e
) {
635 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
640 private ProfileAndCredential
retrieveProfileAndCredential(
641 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
642 ) throws IOException
{
643 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
644 final var profile
= profileAndCredential
.getProfile();
647 var newIdentity
= account
.getIdentityKeyStore()
648 .saveIdentity(recipientId
,
649 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
653 account
.getSessionStore().archiveSessions(recipientId
);
655 } catch (InvalidKeyException ignored
) {
656 logger
.warn("Got invalid identity key in profile for {}",
657 resolveSignalServiceAddress(recipientId
).getIdentifier());
659 return profileAndCredential
;
662 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
663 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
664 if (profileKeyCredential
!= null) {
665 return profileKeyCredential
;
668 ProfileAndCredential profileAndCredential
;
670 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
671 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
672 } catch (IOException e
) {
673 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
677 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
678 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
680 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
681 if (profileKey
!= null) {
682 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
684 profileAndCredential
.getProfile());
685 account
.getProfileStore().storeProfile(recipientId
, profile
);
688 return profileKeyCredential
;
691 private Profile
decryptProfileAndDownloadAvatar(
692 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
694 if (encryptedProfile
.getAvatar() != null) {
695 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
698 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
701 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
702 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
703 if (streamDetails
== null) {
704 return Optional
.absent();
707 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
710 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
711 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
712 if (streamDetails
== null) {
713 return Optional
.absent();
716 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
719 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
720 var g
= getGroup(groupId
);
722 throw new GroupNotFoundException(groupId
);
724 if (!g
.isMember(account
.getSelfRecipientId())) {
725 throw new NotAGroupMemberException(groupId
, g
.getTitle());
730 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
731 var g
= getGroup(groupId
);
733 throw new GroupNotFoundException(groupId
);
735 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
736 throw new NotAGroupMemberException(groupId
, g
.getTitle());
741 public List
<GroupInfo
> getGroups() {
742 return account
.getGroupStore().getGroups();
745 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
746 String messageText
, List
<String
> attachments
, GroupId groupId
747 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
748 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
749 if (attachments
!= null) {
750 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
753 return sendGroupMessage(messageBuilder
, groupId
);
756 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
757 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
758 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
759 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
760 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
762 resolveSignalServiceAddress(targetAuthorRecipientId
),
763 targetSentTimestamp
);
764 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
766 return sendGroupMessage(messageBuilder
, groupId
);
769 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
770 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
771 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
772 final var g
= getGroupForSending(groupId
);
774 GroupUtils
.setGroupContext(messageBuilder
, g
);
775 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
777 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
780 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(
781 GroupId groupId
, Set
<String
> groupAdmins
782 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, InvalidNumberException
, LastGroupAdminException
{
783 var group
= getGroupForUpdating(groupId
);
784 if (group
instanceof GroupInfoV1
) {
785 return quitGroupV1((GroupInfoV1
) group
);
788 final var newAdmins
= getSignalServiceAddresses(groupAdmins
);
790 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
791 } catch (ConflictException e
) {
792 // Detected conflicting update, refreshing group and trying again
793 group
= getGroup(groupId
, true);
794 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
798 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV1(final GroupInfoV1 groupInfoV1
) throws IOException
{
799 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
800 .withId(groupInfoV1
.getGroupId().serialize())
803 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
804 groupInfoV1
.removeMember(account
.getSelfRecipientId());
805 account
.getGroupStore().updateGroup(groupInfoV1
);
806 return sendMessage(messageBuilder
, groupInfoV1
.getMembersWithout(account
.getSelfRecipientId()));
809 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV2(
810 final GroupInfoV2 groupInfoV2
, final Set
<RecipientId
> newAdmins
811 ) throws LastGroupAdminException
, IOException
{
812 final var currentAdmins
= groupInfoV2
.getAdminMembers();
813 newAdmins
.removeAll(currentAdmins
);
814 newAdmins
.retainAll(groupInfoV2
.getMembers());
815 if (currentAdmins
.contains(getSelfRecipientId())
816 && currentAdmins
.size() == 1
817 && groupInfoV2
.getMembers().size() > 1
818 && newAdmins
.size() == 0) {
819 // Last admin can't leave the group, unless she's also the last member
820 throw new LastGroupAdminException(groupInfoV2
.getGroupId(), groupInfoV2
.getTitle());
822 final var groupGroupChangePair
= groupV2Helper
.leaveGroup(groupInfoV2
, newAdmins
);
823 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
824 var messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
825 account
.getGroupStore().updateGroup(groupInfoV2
);
826 return sendMessage(messageBuilder
, groupInfoV2
.getMembersWithout(account
.getSelfRecipientId()));
829 public void deleteGroup(GroupId groupId
) throws IOException
{
830 account
.getGroupStore().deleteGroup(groupId
);
831 avatarStore
.deleteGroupAvatar(groupId
);
834 public Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
835 String name
, List
<String
> members
, File avatarFile
836 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
837 return createGroup(name
, members
== null ?
null : getSignalServiceAddresses(members
), avatarFile
);
840 private Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
841 String name
, Set
<RecipientId
> members
, File avatarFile
842 ) throws IOException
, AttachmentInvalidException
{
843 final var selfRecipientId
= account
.getSelfRecipientId();
844 if (members
!= null && members
.contains(selfRecipientId
)) {
845 members
= new HashSet
<>(members
);
846 members
.remove(selfRecipientId
);
849 var gv2Pair
= groupV2Helper
.createGroup(name
== null ?
"" : name
,
850 members
== null ? Set
.of() : members
,
853 SignalServiceDataMessage
.Builder messageBuilder
;
854 if (gv2Pair
== null) {
855 // Failed to create v2 group, creating v1 group instead
856 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
857 gv1
.addMembers(List
.of(selfRecipientId
));
858 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
859 return new Pair
<>(gv1
.getGroupId(), result
.second());
862 final var gv2
= gv2Pair
.first();
863 final var decryptedGroup
= gv2Pair
.second();
865 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
866 if (avatarFile
!= null) {
867 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
868 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
870 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
871 account
.getGroupStore().updateGroup(gv2
);
873 final var result
= sendMessage(messageBuilder
, gv2
.getMembersIncludingPendingWithout(selfRecipientId
));
874 return new Pair
<>(gv2
.getGroupId(), result
.second());
877 public Pair
<Long
, List
<SendMessageResult
>> updateGroup(
881 List
<String
> members
,
882 List
<String
> removeMembers
,
884 List
<String
> removeAdmins
,
885 boolean resetGroupLink
,
886 GroupLinkState groupLinkState
,
887 GroupPermission addMemberPermission
,
888 GroupPermission editDetailsPermission
,
890 Integer expirationTimer
891 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
892 return updateGroup(groupId
,
895 members
== null ?
null : getSignalServiceAddresses(members
),
896 removeMembers
== null ?
null : getSignalServiceAddresses(removeMembers
),
897 admins
== null ?
null : getSignalServiceAddresses(admins
),
898 removeAdmins
== null ?
null : getSignalServiceAddresses(removeAdmins
),
902 editDetailsPermission
,
907 private Pair
<Long
, List
<SendMessageResult
>> updateGroup(
908 final GroupId groupId
,
910 final String description
,
911 final Set
<RecipientId
> members
,
912 final Set
<RecipientId
> removeMembers
,
913 final Set
<RecipientId
> admins
,
914 final Set
<RecipientId
> removeAdmins
,
915 final boolean resetGroupLink
,
916 final GroupLinkState groupLinkState
,
917 final GroupPermission addMemberPermission
,
918 final GroupPermission editDetailsPermission
,
919 final File avatarFile
,
920 final Integer expirationTimer
921 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
922 var group
= getGroupForUpdating(groupId
);
924 if (group
instanceof GroupInfoV2
) {
926 return updateGroupV2((GroupInfoV2
) group
,
936 editDetailsPermission
,
939 } catch (ConflictException e
) {
940 // Detected conflicting update, refreshing group and trying again
941 group
= getGroup(groupId
, true);
942 return updateGroupV2((GroupInfoV2
) group
,
952 editDetailsPermission
,
958 final var gv1
= (GroupInfoV1
) group
;
959 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
960 if (expirationTimer
!= null) {
961 setExpirationTimer(gv1
, expirationTimer
);
966 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV1(
967 final GroupInfoV1 gv1
, final String name
, final Set
<RecipientId
> members
, final File avatarFile
968 ) throws IOException
, AttachmentInvalidException
{
969 updateGroupV1Details(gv1
, name
, members
, avatarFile
);
970 var messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
972 account
.getGroupStore().updateGroup(gv1
);
974 return sendMessage(messageBuilder
, gv1
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
977 private void updateGroupV1Details(
978 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
979 ) throws IOException
{
984 if (members
!= null) {
985 final var newMemberAddresses
= members
.stream()
986 .filter(member
-> !g
.isMember(member
))
987 .map(this::resolveSignalServiceAddress
)
988 .collect(Collectors
.toList());
989 final var newE164Members
= new HashSet
<String
>();
990 for (var member
: newMemberAddresses
) {
991 if (!member
.getNumber().isPresent()) {
994 newE164Members
.add(member
.getNumber().get());
997 final var registeredUsers
= getRegisteredUsers(newE164Members
);
998 if (registeredUsers
.size() != newE164Members
.size()) {
999 // Some of the new members are not registered on Signal
1000 newE164Members
.removeAll(registeredUsers
.keySet());
1001 throw new IOException("Failed to add members "
1002 + String
.join(", ", newE164Members
)
1003 + " to group: Not registered on Signal");
1006 g
.addMembers(members
);
1009 if (avatarFile
!= null) {
1010 avatarStore
.storeGroupAvatar(g
.getGroupId(),
1011 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
1015 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV2(
1016 final GroupInfoV2 group
,
1018 final String description
,
1019 final Set
<RecipientId
> members
,
1020 final Set
<RecipientId
> removeMembers
,
1021 final Set
<RecipientId
> admins
,
1022 final Set
<RecipientId
> removeAdmins
,
1023 final boolean resetGroupLink
,
1024 final GroupLinkState groupLinkState
,
1025 final GroupPermission addMemberPermission
,
1026 final GroupPermission editDetailsPermission
,
1027 final File avatarFile
,
1028 Integer expirationTimer
1029 ) throws IOException
{
1030 Pair
<Long
, List
<SendMessageResult
>> result
= null;
1031 if (group
.isPendingMember(account
.getSelfRecipientId())) {
1032 var groupGroupChangePair
= groupV2Helper
.acceptInvite(group
);
1033 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1036 if (members
!= null) {
1037 final var newMembers
= new HashSet
<>(members
);
1038 newMembers
.removeAll(group
.getMembers());
1039 if (newMembers
.size() > 0) {
1040 var groupGroupChangePair
= groupV2Helper
.addMembers(group
, newMembers
);
1041 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1045 if (removeMembers
!= null) {
1046 var existingRemoveMembers
= new HashSet
<>(removeMembers
);
1047 existingRemoveMembers
.retainAll(group
.getMembers());
1048 existingRemoveMembers
.remove(getSelfRecipientId());// self can be removed with sendQuitGroupMessage
1049 if (existingRemoveMembers
.size() > 0) {
1050 var groupGroupChangePair
= groupV2Helper
.removeMembers(group
, existingRemoveMembers
);
1051 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1054 var pendingRemoveMembers
= new HashSet
<>(removeMembers
);
1055 pendingRemoveMembers
.retainAll(group
.getPendingMembers());
1056 if (pendingRemoveMembers
.size() > 0) {
1057 var groupGroupChangePair
= groupV2Helper
.revokeInvitedMembers(group
, pendingRemoveMembers
);
1058 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1062 if (admins
!= null) {
1063 final var newAdmins
= new HashSet
<>(admins
);
1064 newAdmins
.retainAll(group
.getMembers());
1065 newAdmins
.removeAll(group
.getAdminMembers());
1066 if (newAdmins
.size() > 0) {
1067 for (var admin
: newAdmins
) {
1068 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, true);
1069 result
= sendUpdateGroupV2Message(group
,
1070 groupGroupChangePair
.first(),
1071 groupGroupChangePair
.second());
1076 if (removeAdmins
!= null) {
1077 final var existingRemoveAdmins
= new HashSet
<>(removeAdmins
);
1078 existingRemoveAdmins
.retainAll(group
.getAdminMembers());
1079 if (existingRemoveAdmins
.size() > 0) {
1080 for (var admin
: existingRemoveAdmins
) {
1081 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, false);
1082 result
= sendUpdateGroupV2Message(group
,
1083 groupGroupChangePair
.first(),
1084 groupGroupChangePair
.second());
1089 if (resetGroupLink
) {
1090 var groupGroupChangePair
= groupV2Helper
.resetGroupLinkPassword(group
);
1091 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1094 if (groupLinkState
!= null) {
1095 var groupGroupChangePair
= groupV2Helper
.setGroupLinkState(group
, groupLinkState
);
1096 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1099 if (addMemberPermission
!= null) {
1100 var groupGroupChangePair
= groupV2Helper
.setAddMemberPermission(group
, addMemberPermission
);
1101 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1104 if (editDetailsPermission
!= null) {
1105 var groupGroupChangePair
= groupV2Helper
.setEditDetailsPermission(group
, editDetailsPermission
);
1106 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1109 if (expirationTimer
!= null) {
1110 var groupGroupChangePair
= groupV2Helper
.setMessageExpirationTimer(group
, expirationTimer
);
1111 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1114 if (name
!= null || description
!= null || avatarFile
!= null) {
1115 var groupGroupChangePair
= groupV2Helper
.updateGroup(group
, name
, description
, avatarFile
);
1116 if (avatarFile
!= null) {
1117 avatarStore
.storeGroupAvatar(group
.getGroupId(),
1118 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
1120 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1126 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
1127 GroupInviteLinkUrl inviteLinkUrl
1128 ) throws IOException
, GroupLinkNotActiveException
{
1129 final var groupJoinInfo
= groupV2Helper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
1130 inviteLinkUrl
.getPassword());
1131 final var groupChange
= groupV2Helper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
1132 inviteLinkUrl
.getPassword(),
1134 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
1135 groupJoinInfo
.getRevision() + 1,
1136 groupChange
.toByteArray());
1138 if (group
.getGroup() == null) {
1139 // Only requested member, can't send update to group members
1140 return new Pair
<>(group
.getGroupId(), List
.of());
1143 final var result
= sendUpdateGroupV2Message(group
, group
.getGroup(), groupChange
);
1145 return new Pair
<>(group
.getGroupId(), result
.second());
1148 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupV2Message(
1149 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
1150 ) throws IOException
{
1151 final var selfRecipientId
= account
.getSelfRecipientId();
1152 final var members
= group
.getMembersIncludingPendingWithout(selfRecipientId
);
1153 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
1154 members
.addAll(group
.getMembersIncludingPendingWithout(selfRecipientId
));
1156 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
1157 account
.getGroupStore().updateGroup(group
);
1158 return sendMessage(messageBuilder
, members
);
1161 private static int currentTimeDays() {
1162 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
1165 private GroupsV2AuthorizationString
getGroupAuthForToday(
1166 final GroupSecretParams groupSecretParams
1167 ) throws IOException
{
1168 final var today
= currentTimeDays();
1169 // Returns credentials for the next 7 days
1170 final var credentials
= groupsV2Api
.getCredentials(today
);
1171 // TODO cache credentials until they expire
1172 var authCredentialResponse
= credentials
.get(today
);
1174 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
1177 authCredentialResponse
);
1178 } catch (VerificationFailedException e
) {
1179 throw new IOException(e
);
1183 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
1184 GroupIdV1 groupId
, SignalServiceAddress recipient
1185 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
1187 var group
= getGroupForSending(groupId
);
1188 if (!(group
instanceof GroupInfoV1
)) {
1189 throw new RuntimeException("Received an invalid group request for a v2 group!");
1191 g
= (GroupInfoV1
) group
;
1193 final var recipientId
= resolveRecipient(recipient
);
1194 if (!g
.isMember(recipientId
)) {
1195 throw new NotAGroupMemberException(groupId
, g
.name
);
1198 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
1200 // Send group message only to the recipient who requested it
1201 return sendMessage(messageBuilder
, Set
.of(recipientId
));
1204 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
1205 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
1206 .withId(g
.getGroupId().serialize())
1208 .withMembers(g
.getMembers()
1210 .map(this::resolveSignalServiceAddress
)
1211 .collect(Collectors
.toList()));
1214 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
1215 if (attachment
.isPresent()) {
1216 group
.withAvatar(attachment
.get());
1218 } catch (IOException e
) {
1219 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
1222 return SignalServiceDataMessage
.newBuilder()
1223 .asGroupMessage(group
.build())
1224 .withExpiration(g
.getMessageExpirationTime());
1227 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
1228 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
1229 .withRevision(g
.getGroup().getRevision())
1230 .withSignedGroupChange(signedGroupChange
);
1231 return SignalServiceDataMessage
.newBuilder()
1232 .asGroupMessage(group
.build())
1233 .withExpiration(g
.getMessageExpirationTime());
1236 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
1237 GroupIdV1 groupId
, SignalServiceAddress recipient
1238 ) throws IOException
{
1239 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
1241 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
1243 // Send group info request message to the recipient who sent us a message with this groupId
1244 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1248 SignalServiceAddress remoteAddress
, long messageId
1249 ) throws IOException
, UntrustedIdentityException
{
1250 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1252 System
.currentTimeMillis());
1254 createMessageSender().sendReceipt(remoteAddress
,
1255 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1259 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1260 String messageText
, List
<String
> attachments
, List
<String
> recipients
1261 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1262 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1263 if (attachments
!= null) {
1264 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1266 // Upload attachments here, so we only upload once even for multiple recipients
1267 var messageSender
= createMessageSender();
1268 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1269 for (var attachment
: attachmentStreams
) {
1270 if (attachment
.isStream()) {
1271 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1272 } else if (attachment
.isPointer()) {
1273 attachmentPointers
.add(attachment
.asPointer());
1277 messageBuilder
.withAttachments(attachmentPointers
);
1279 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1282 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1283 String messageText
, List
<String
> attachments
1284 ) throws IOException
, AttachmentInvalidException
{
1285 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1286 if (attachments
!= null) {
1287 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1289 return sendSelfMessage(messageBuilder
);
1292 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1293 long targetSentTimestamp
, List
<String
> recipients
1294 ) throws IOException
, InvalidNumberException
{
1295 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1296 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1297 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1300 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1301 long targetSentTimestamp
, GroupId groupId
1302 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1303 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1304 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1305 return sendGroupMessage(messageBuilder
, groupId
);
1308 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1309 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1310 ) throws IOException
, InvalidNumberException
{
1311 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1312 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1314 resolveSignalServiceAddress(targetAuthorRecipientId
),
1315 targetSentTimestamp
);
1316 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1317 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1320 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1321 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1323 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1325 return sendMessage(messageBuilder
, signalServiceAddresses
);
1326 } catch (Exception e
) {
1327 for (var address
: signalServiceAddresses
) {
1328 handleEndSession(address
);
1334 void renewSession(RecipientId recipientId
) throws IOException
{
1335 account
.getSessionStore().archiveSessions(recipientId
);
1336 if (!recipientId
.equals(getSelfRecipientId())) {
1337 sendNullMessage(recipientId
);
1341 public String
getContactName(String number
) throws InvalidNumberException
{
1342 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1343 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1346 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1347 if (!account
.isMasterDevice()) {
1348 throw new NotMasterDeviceException();
1350 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1351 var contact
= account
.getContactStore().getContact(recipientId
);
1352 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1353 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1356 public void setContactBlocked(
1357 String number
, boolean blocked
1358 ) throws InvalidNumberException
, NotMasterDeviceException
{
1359 if (!account
.isMasterDevice()) {
1360 throw new NotMasterDeviceException();
1362 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1365 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1366 var contact
= account
.getContactStore().getContact(recipientId
);
1367 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1368 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1371 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1372 var group
= getGroup(groupId
);
1373 if (group
== null) {
1374 throw new GroupNotFoundException(groupId
);
1377 group
.setBlocked(blocked
);
1378 account
.getGroupStore().updateGroup(group
);
1381 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1382 var contact
= account
.getContactStore().getContact(recipientId
);
1383 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1386 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1387 account
.getContactStore()
1388 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1391 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1392 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1393 sendMessage(messageBuilder
, Set
.of(recipientId
));
1397 * Change the expiration timer for a contact
1399 public void setExpirationTimer(
1400 String number
, int messageExpirationTimer
1401 ) throws IOException
, InvalidNumberException
{
1402 var recipientId
= canonicalizeAndResolveRecipient(number
);
1403 setExpirationTimer(recipientId
, messageExpirationTimer
);
1404 sendExpirationTimerUpdate(recipientId
);
1408 * Change the expiration timer for a group
1410 private void setExpirationTimer(
1411 GroupInfoV1 groupInfoV1
, int messageExpirationTimer
1412 ) throws NotAGroupMemberException
, GroupNotFoundException
, IOException
{
1413 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1414 account
.getGroupStore().updateGroup(groupInfoV1
);
1415 sendExpirationTimerUpdate(groupInfoV1
.getGroupId());
1418 private void sendExpirationTimerUpdate(GroupIdV1 groupId
) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1419 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1420 sendGroupMessage(messageBuilder
, groupId
);
1424 * Upload the sticker pack from path.
1426 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1427 * @return if successful, returns the URL to install the sticker pack in the signal app
1429 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1430 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1432 var messageSender
= createMessageSender();
1434 var packKey
= KeyUtils
.createStickerUploadKey();
1435 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1437 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1438 account
.getStickerStore().updateSticker(sticker
);
1441 return new URI("https",
1444 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1445 Hex
.toStringCondensed(packKey
),
1446 StandardCharsets
.UTF_8
)).toString();
1447 } catch (URISyntaxException e
) {
1448 throw new AssertionError(e
);
1452 public void requestAllSyncData() throws IOException
{
1453 requestSyncGroups();
1454 requestSyncContacts();
1455 requestSyncBlocked();
1456 requestSyncConfiguration();
1460 private void requestSyncGroups() throws IOException
{
1461 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1462 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1464 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1466 sendSyncMessage(message
);
1467 } catch (UntrustedIdentityException e
) {
1468 throw new AssertionError(e
);
1472 private void requestSyncContacts() throws IOException
{
1473 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1474 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1476 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1478 sendSyncMessage(message
);
1479 } catch (UntrustedIdentityException e
) {
1480 throw new AssertionError(e
);
1484 private void requestSyncBlocked() throws IOException
{
1485 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1486 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1488 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1490 sendSyncMessage(message
);
1491 } catch (UntrustedIdentityException e
) {
1492 throw new AssertionError(e
);
1496 private void requestSyncConfiguration() throws IOException
{
1497 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1498 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1500 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1502 sendSyncMessage(message
);
1503 } catch (UntrustedIdentityException e
) {
1504 throw new AssertionError(e
);
1508 private void requestSyncKeys() throws IOException
{
1509 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1510 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1512 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1514 sendSyncMessage(message
);
1515 } catch (UntrustedIdentityException e
) {
1516 throw new AssertionError(e
);
1520 private byte[] getSenderCertificate() {
1523 if (account
.isPhoneNumberShared()) {
1524 certificate
= accountManager
.getSenderCertificate();
1526 certificate
= accountManager
.getSenderCertificateForPhoneNumberPrivacy();
1528 } catch (IOException e
) {
1529 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1532 // TODO cache for a day
1536 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1537 var messageSender
= createMessageSender();
1538 messageSender
.sendSyncMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1541 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1542 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1543 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1545 for (var number
: numbers
) {
1546 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1547 if (resolvedAddress
.getUuid().isPresent()) {
1548 signalServiceAddresses
.add(resolvedAddress
);
1550 addressesMissingUuid
.add(resolvedAddress
);
1554 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1555 .map(a
-> a
.getNumber().get())
1556 .collect(Collectors
.toSet());
1557 Map
<String
, UUID
> registeredUsers
;
1559 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1560 } catch (IOException e
) {
1561 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1562 registeredUsers
= Map
.of();
1565 for (var address
: addressesMissingUuid
) {
1566 final var number
= address
.getNumber().get();
1567 if (registeredUsers
.containsKey(number
)) {
1568 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1569 registeredUsers
.get(number
),
1571 signalServiceAddresses
.add(newAddress
);
1573 signalServiceAddresses
.add(address
);
1577 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1580 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1581 final var address
= resolveSignalServiceAddress(recipientId
);
1582 if (!address
.getNumber().isPresent()) {
1585 final var number
= address
.getNumber().get();
1586 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1587 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1590 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1592 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1594 serviceEnvironmentConfig
.getCdsMrenclave());
1595 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1596 throw new IOException(e
);
1600 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1601 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1602 ) throws IOException
{
1603 final var timestamp
= System
.currentTimeMillis();
1604 messageBuilder
.withTimestamp(timestamp
);
1605 getOrCreateMessagePipe();
1606 getOrCreateUnidentifiedMessagePipe();
1607 SignalServiceDataMessage message
= null;
1609 message
= messageBuilder
.build();
1610 if (message
.getGroupContext().isPresent()) {
1612 var messageSender
= createMessageSender();
1613 final var isRecipientUpdate
= false;
1614 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1615 final var addresses
= recipientIdList
.stream()
1616 .map(this::resolveSignalServiceAddress
)
1617 .collect(Collectors
.toList());
1618 var result
= messageSender
.sendDataMessage(addresses
,
1619 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1621 ContentHint
.DEFAULT
,
1624 for (var r
: result
) {
1625 if (r
.getIdentityFailure() != null) {
1626 final var recipientId
= resolveRecipient(r
.getAddress());
1627 final var newIdentity
= account
.getIdentityKeyStore()
1628 .saveIdentity(recipientId
, r
.getIdentityFailure().getIdentityKey(), new Date());
1630 account
.getSessionStore().archiveSessions(recipientId
);
1635 return new Pair
<>(timestamp
, result
);
1636 } catch (UntrustedIdentityException e
) {
1637 return new Pair
<>(timestamp
, List
.of());
1640 // Send to all individually, so sync messages are sent correctly
1641 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1642 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1643 for (var recipientId
: recipientIds
) {
1644 final var contact
= account
.getContactStore().getContact(recipientId
);
1645 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1646 messageBuilder
.withExpiration(expirationTime
);
1647 message
= messageBuilder
.build();
1648 results
.add(sendMessage(recipientId
, message
));
1650 return new Pair
<>(timestamp
, results
);
1653 if (message
!= null && message
.isEndSession()) {
1654 for (var recipient
: recipientIds
) {
1655 handleEndSession(recipient
);
1661 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1662 SignalServiceDataMessage
.Builder messageBuilder
1663 ) throws IOException
{
1664 final var timestamp
= System
.currentTimeMillis();
1665 messageBuilder
.withTimestamp(timestamp
);
1666 getOrCreateMessagePipe();
1667 getOrCreateUnidentifiedMessagePipe();
1668 final var recipientId
= account
.getSelfRecipientId();
1670 final var contact
= account
.getContactStore().getContact(recipientId
);
1671 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1672 messageBuilder
.withExpiration(expirationTime
);
1674 var message
= messageBuilder
.build();
1675 final var result
= sendSelfMessage(message
);
1676 return new Pair
<>(timestamp
, result
);
1679 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1680 var messageSender
= createMessageSender();
1682 var recipientId
= account
.getSelfRecipientId();
1684 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipientId
);
1685 var recipient
= resolveSignalServiceAddress(recipientId
);
1686 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1687 message
.getTimestamp(),
1689 message
.getExpiresInSeconds(),
1690 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1692 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1695 var startTime
= System
.currentTimeMillis();
1696 messageSender
.sendSyncMessage(syncMessage
, unidentifiedAccess
);
1697 return SendMessageResult
.success(recipient
,
1698 unidentifiedAccess
.isPresent(),
1700 System
.currentTimeMillis() - startTime
);
1701 } catch (UntrustedIdentityException e
) {
1702 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1706 private SendMessageResult
sendMessage(
1707 RecipientId recipientId
, SignalServiceDataMessage message
1708 ) throws IOException
{
1709 var messageSender
= createMessageSender();
1711 final var address
= resolveSignalServiceAddress(recipientId
);
1714 return messageSender
.sendDataMessage(address
,
1715 unidentifiedAccessHelper
.getAccessFor(recipientId
),
1716 ContentHint
.DEFAULT
,
1718 } catch (UnregisteredUserException e
) {
1719 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1720 return messageSender
.sendDataMessage(resolveSignalServiceAddress(newRecipientId
),
1721 unidentifiedAccessHelper
.getAccessFor(newRecipientId
),
1722 ContentHint
.DEFAULT
,
1725 } catch (UntrustedIdentityException e
) {
1726 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1730 private SendMessageResult
sendNullMessage(RecipientId recipientId
) throws IOException
{
1731 var messageSender
= createMessageSender();
1733 final var address
= resolveSignalServiceAddress(recipientId
);
1736 return messageSender
.sendNullMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
));
1737 } catch (UnregisteredUserException e
) {
1738 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1739 final var newAddress
= resolveSignalServiceAddress(newRecipientId
);
1740 return messageSender
.sendNullMessage(newAddress
, unidentifiedAccessHelper
.getAccessFor(newRecipientId
));
1742 } catch (UntrustedIdentityException e
) {
1743 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1747 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, ProtocolUntrustedIdentityException
{
1748 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1749 account
.getSignalProtocolStore(),
1751 certificateValidator
);
1752 return cipher
.decrypt(envelope
);
1755 private void handleEndSession(RecipientId recipientId
) {
1756 account
.getSessionStore().deleteAllSessions(recipientId
);
1759 private List
<HandleAction
> handleSignalServiceDataMessage(
1760 SignalServiceDataMessage message
,
1762 SignalServiceAddress source
,
1763 SignalServiceAddress destination
,
1764 boolean ignoreAttachments
1766 var actions
= new ArrayList
<HandleAction
>();
1767 if (message
.getGroupContext().isPresent()) {
1768 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1769 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1770 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1771 var group
= getGroup(groupId
);
1772 if (group
== null || group
instanceof GroupInfoV1
) {
1773 var groupV1
= (GroupInfoV1
) group
;
1774 switch (groupInfo
.getType()) {
1776 if (groupV1
== null) {
1777 groupV1
= new GroupInfoV1(groupId
);
1780 if (groupInfo
.getAvatar().isPresent()) {
1781 var avatar
= groupInfo
.getAvatar().get();
1782 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1785 if (groupInfo
.getName().isPresent()) {
1786 groupV1
.name
= groupInfo
.getName().get();
1789 if (groupInfo
.getMembers().isPresent()) {
1790 groupV1
.addMembers(groupInfo
.getMembers()
1793 .map(this::resolveRecipient
)
1794 .collect(Collectors
.toSet()));
1797 account
.getGroupStore().updateGroup(groupV1
);
1801 if (groupV1
== null && !isSync
) {
1802 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1806 if (groupV1
!= null) {
1807 groupV1
.removeMember(resolveRecipient(source
));
1808 account
.getGroupStore().updateGroup(groupV1
);
1813 if (groupV1
!= null && !isSync
) {
1814 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1819 // Received a group v1 message for a v2 group
1822 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1823 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1824 final var groupMasterKey
= groupContext
.getMasterKey();
1826 getOrMigrateGroup(groupMasterKey
,
1827 groupContext
.getRevision(),
1828 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1832 final var conversationPartnerAddress
= isSync ? destination
: source
;
1833 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1834 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1836 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1837 if (message
.getGroupContext().isPresent()) {
1838 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1839 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1840 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1841 if (group
!= null) {
1842 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1843 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1844 account
.getGroupStore().updateGroup(group
);
1847 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1848 // disappearing message timer already stored in the DecryptedGroup
1850 } else if (conversationPartnerAddress
!= null) {
1851 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1854 if (!ignoreAttachments
) {
1855 if (message
.getAttachments().isPresent()) {
1856 for (var attachment
: message
.getAttachments().get()) {
1857 downloadAttachment(attachment
);
1860 if (message
.getSharedContacts().isPresent()) {
1861 for (var contact
: message
.getSharedContacts().get()) {
1862 if (contact
.getAvatar().isPresent()) {
1863 downloadAttachment(contact
.getAvatar().get().getAttachment());
1868 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1869 final ProfileKey profileKey
;
1871 profileKey
= new ProfileKey(message
.getProfileKey().get());
1872 } catch (InvalidInputException e
) {
1873 throw new AssertionError(e
);
1875 if (source
.matches(account
.getSelfAddress())) {
1876 this.account
.setProfileKey(profileKey
);
1878 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1880 if (message
.getPreviews().isPresent()) {
1881 final var previews
= message
.getPreviews().get();
1882 for (var preview
: previews
) {
1883 if (preview
.getImage().isPresent()) {
1884 downloadAttachment(preview
.getImage().get());
1888 if (message
.getQuote().isPresent()) {
1889 final var quote
= message
.getQuote().get();
1891 for (var quotedAttachment
: quote
.getAttachments()) {
1892 final var thumbnail
= quotedAttachment
.getThumbnail();
1893 if (thumbnail
!= null) {
1894 downloadAttachment(thumbnail
);
1898 if (message
.getSticker().isPresent()) {
1899 final var messageSticker
= message
.getSticker().get();
1900 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1901 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1902 if (sticker
== null) {
1903 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1904 account
.getStickerStore().updateSticker(sticker
);
1910 private GroupInfoV2
getOrMigrateGroup(
1911 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1913 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1915 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1916 var groupInfo
= getGroup(groupId
);
1917 final GroupInfoV2 groupInfoV2
;
1918 if (groupInfo
instanceof GroupInfoV1
) {
1919 // Received a v2 group message for a v1 group, we need to locally migrate the group
1920 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1921 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1922 logger
.info("Locally migrated group {} to group v2, id: {}",
1923 groupInfo
.getGroupId().toBase64(),
1924 groupInfoV2
.getGroupId().toBase64());
1925 } else if (groupInfo
instanceof GroupInfoV2
) {
1926 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1928 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1931 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1932 DecryptedGroup group
= null;
1933 if (signedGroupChange
!= null
1934 && groupInfoV2
.getGroup() != null
1935 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1936 group
= groupV2Helper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(),
1940 if (group
== null) {
1941 group
= groupV2Helper
.getDecryptedGroup(groupSecretParams
);
1943 if (group
!= null) {
1944 storeProfileKeysFromMembers(group
);
1945 final var avatar
= group
.getAvatar();
1946 if (avatar
!= null && !avatar
.isEmpty()) {
1947 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1950 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1951 account
.getGroupStore().updateGroup(groupInfoV2
);
1957 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1958 for (var member
: group
.getMembersList()) {
1959 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
1960 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
1962 account
.getProfileStore()
1963 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
1964 } catch (InvalidInputException ignored
) {
1969 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1970 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1971 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1972 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1973 if (actions
!= null) {
1974 queuedActions
.addAll(actions
);
1977 for (var action
: queuedActions
) {
1979 action
.execute(this);
1980 } catch (Throwable e
) {
1981 logger
.warn("Message action failed.", e
);
1986 private List
<HandleAction
> retryFailedReceivedMessage(
1987 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1989 var envelope
= cachedMessage
.loadEnvelope();
1990 if (envelope
== null) {
1993 SignalServiceContent content
= null;
1994 List
<HandleAction
> actions
= null;
1995 if (!envelope
.isReceipt()) {
1997 content
= decryptMessage(envelope
);
1998 } catch (ProtocolUntrustedIdentityException e
) {
1999 if (!envelope
.hasSource()) {
2000 final var identifier
= e
.getSender();
2001 final var recipientId
= resolveRecipient(identifier
);
2003 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
2004 } catch (IOException ioException
) {
2005 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
2009 } catch (Exception er
) {
2010 // All other errors are not recoverable, so delete the cached message
2011 cachedMessage
.delete();
2014 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
2016 handler
.handleMessage(envelope
, content
, null);
2017 cachedMessage
.delete();
2021 public void receiveMessages(
2024 boolean returnOnTimeout
,
2025 boolean ignoreAttachments
,
2026 ReceiveMessageHandler handler
2027 ) throws IOException
{
2028 retryFailedReceivedMessages(handler
, ignoreAttachments
);
2030 Set
<HandleAction
> queuedActions
= null;
2032 final var messagePipe
= getOrCreateMessagePipe();
2034 var hasCaughtUpWithOldMessages
= false;
2037 SignalServiceEnvelope envelope
;
2038 SignalServiceContent content
= null;
2039 Exception exception
= null;
2040 final CachedMessage
[] cachedMessage
= {null};
2041 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
2042 logger
.debug("Checking for new message from server");
2044 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
2045 final var recipientId
= envelope1
.hasSource()
2046 ?
resolveRecipient(envelope1
.getSourceIdentifier())
2048 // store message on disk, before acknowledging receipt to the server
2049 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
2051 logger
.debug("New message received from server");
2052 if (result
.isPresent()) {
2053 envelope
= result
.get();
2055 // Received indicator that server queue is empty
2056 hasCaughtUpWithOldMessages
= true;
2058 if (queuedActions
!= null) {
2059 for (var action
: queuedActions
) {
2061 action
.execute(this);
2062 } catch (Throwable e
) {
2063 logger
.warn("Message action failed.", e
);
2066 queuedActions
.clear();
2067 queuedActions
= null;
2070 // Continue to wait another timeout for new messages
2073 } catch (TimeoutException e
) {
2074 if (returnOnTimeout
) return;
2078 if (envelope
.hasSource()) {
2079 // Store uuid if we don't have it already
2080 // address/uuid in envelope is sent by server
2081 resolveRecipientTrusted(envelope
.getSourceAddress());
2083 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
2084 if (!envelope
.isReceipt()) {
2086 content
= decryptMessage(envelope
);
2087 } catch (Exception e
) {
2090 if (!envelope
.hasSource() && content
!= null) {
2091 // Store uuid if we don't have it already
2092 // address/uuid is validated by unidentified sender certificate
2093 resolveRecipientTrusted(content
.getSender());
2095 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
2096 if (exception
instanceof ProtocolInvalidMessageException
) {
2097 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
2098 logger
.debug("Received invalid message, queuing renew session action.");
2099 actions
.add(new RenewSessionAction(sender
));
2101 if (hasCaughtUpWithOldMessages
) {
2102 for (var action
: actions
) {
2104 action
.execute(this);
2105 } catch (Throwable e
) {
2106 logger
.warn("Message action failed.", e
);
2110 if (queuedActions
== null) {
2111 queuedActions
= new HashSet
<>();
2113 queuedActions
.addAll(actions
);
2116 if (isMessageBlocked(envelope
, content
)) {
2117 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
2118 } else if (notAGroupMember
) {
2119 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
2121 handler
.handleMessage(envelope
, content
, exception
);
2123 if (cachedMessage
[0] != null) {
2124 if (exception
instanceof ProtocolUntrustedIdentityException
) {
2125 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
2126 final var recipientId
= resolveRecipient(identifier
);
2127 queuedActions
.add(new RetrieveProfileAction(recipientId
));
2128 if (!envelope
.hasSource()) {
2130 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
2131 } catch (IOException ioException
) {
2132 logger
.warn("Failed to move cached message to recipient folder: {}",
2133 ioException
.getMessage());
2137 cachedMessage
[0].delete();
2143 private boolean isMessageBlocked(
2144 SignalServiceEnvelope envelope
, SignalServiceContent content
2146 SignalServiceAddress source
;
2147 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2148 source
= envelope
.getSourceAddress();
2149 } else if (content
!= null) {
2150 source
= content
.getSender();
2154 final var recipientId
= resolveRecipient(source
);
2155 if (isContactBlocked(recipientId
)) {
2159 if (content
!= null && content
.getDataMessage().isPresent()) {
2160 var message
= content
.getDataMessage().get();
2161 if (message
.getGroupContext().isPresent()) {
2162 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2163 var group
= getGroup(groupId
);
2164 if (group
!= null && group
.isBlocked()) {
2172 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
2173 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
2174 return isContactBlocked(recipientId
);
2177 private boolean isContactBlocked(final RecipientId recipientId
) {
2178 var sourceContact
= account
.getContactStore().getContact(recipientId
);
2179 return sourceContact
!= null && sourceContact
.isBlocked();
2182 private boolean isNotAGroupMember(
2183 SignalServiceEnvelope envelope
, SignalServiceContent content
2185 SignalServiceAddress source
;
2186 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2187 source
= envelope
.getSourceAddress();
2188 } else if (content
!= null) {
2189 source
= content
.getSender();
2194 if (content
!= null && content
.getDataMessage().isPresent()) {
2195 var message
= content
.getDataMessage().get();
2196 if (message
.getGroupContext().isPresent()) {
2197 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
2198 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
2199 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
2203 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2204 var group
= getGroup(groupId
);
2205 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
2213 private List
<HandleAction
> handleMessage(
2214 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
2216 var actions
= new ArrayList
<HandleAction
>();
2217 if (content
!= null) {
2218 final SignalServiceAddress sender
;
2219 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2220 sender
= envelope
.getSourceAddress();
2222 sender
= content
.getSender();
2225 if (content
.getDataMessage().isPresent()) {
2226 var message
= content
.getDataMessage().get();
2228 if (content
.isNeedsReceipt()) {
2229 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
2232 actions
.addAll(handleSignalServiceDataMessage(message
,
2235 account
.getSelfAddress(),
2236 ignoreAttachments
));
2238 if (content
.getSyncMessage().isPresent()) {
2239 account
.setMultiDevice(true);
2240 var syncMessage
= content
.getSyncMessage().get();
2241 if (syncMessage
.getSent().isPresent()) {
2242 var message
= syncMessage
.getSent().get();
2243 final var destination
= message
.getDestination().orNull();
2244 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
2248 ignoreAttachments
));
2250 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
2251 var rm
= syncMessage
.getRequest().get();
2252 if (rm
.isContactsRequest()) {
2253 actions
.add(SendSyncContactsAction
.create());
2255 if (rm
.isGroupsRequest()) {
2256 actions
.add(SendSyncGroupsAction
.create());
2258 if (rm
.isBlockedListRequest()) {
2259 actions
.add(SendSyncBlockedListAction
.create());
2261 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2263 if (syncMessage
.getGroups().isPresent()) {
2264 File tmpFile
= null;
2266 tmpFile
= IOUtils
.createTempFile();
2267 final var groupsMessage
= syncMessage
.getGroups().get();
2268 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2269 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2274 } catch (IOException e
) {
2275 logger
.warn("Sync groups contained invalid group, ignoring: {}", e
.getMessage());
2281 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2282 if (syncGroup
!= null) {
2283 if (g
.getName().isPresent()) {
2284 syncGroup
.name
= g
.getName().get();
2286 syncGroup
.addMembers(g
.getMembers()
2288 .map(this::resolveRecipient
)
2289 .collect(Collectors
.toSet()));
2290 if (!g
.isActive()) {
2291 syncGroup
.removeMember(account
.getSelfRecipientId());
2293 // Add ourself to the member set as it's marked as active
2294 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2296 syncGroup
.blocked
= g
.isBlocked();
2297 if (g
.getColor().isPresent()) {
2298 syncGroup
.color
= g
.getColor().get();
2301 if (g
.getAvatar().isPresent()) {
2302 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2304 syncGroup
.archived
= g
.isArchived();
2305 account
.getGroupStore().updateGroup(syncGroup
);
2309 } catch (Exception e
) {
2310 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2314 if (tmpFile
!= null) {
2316 Files
.delete(tmpFile
.toPath());
2317 } catch (IOException e
) {
2318 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2325 if (syncMessage
.getBlockedList().isPresent()) {
2326 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2327 for (var address
: blockedListMessage
.getAddresses()) {
2328 setContactBlocked(resolveRecipient(address
), true);
2330 for (var groupId
: blockedListMessage
.getGroupIds()
2332 .map(GroupId
::unknownVersion
)
2333 .collect(Collectors
.toSet())) {
2335 setGroupBlocked(groupId
, true);
2336 } catch (GroupNotFoundException e
) {
2337 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2338 groupId
.toBase64());
2342 if (syncMessage
.getContacts().isPresent()) {
2343 File tmpFile
= null;
2345 tmpFile
= IOUtils
.createTempFile();
2346 final var contactsMessage
= syncMessage
.getContacts().get();
2347 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2348 .asPointer(), tmpFile
)) {
2349 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2354 } catch (IOException e
) {
2355 logger
.warn("Sync contacts contained invalid contact, ignoring: {}",
2362 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2363 account
.setProfileKey(c
.getProfileKey().get());
2365 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2366 var contact
= account
.getContactStore().getContact(recipientId
);
2367 final var builder
= contact
== null
2368 ? Contact
.newBuilder()
2369 : Contact
.newBuilder(contact
);
2370 if (c
.getName().isPresent()) {
2371 builder
.withName(c
.getName().get());
2373 if (c
.getColor().isPresent()) {
2374 builder
.withColor(c
.getColor().get());
2376 if (c
.getProfileKey().isPresent()) {
2377 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2379 if (c
.getVerified().isPresent()) {
2380 final var verifiedMessage
= c
.getVerified().get();
2381 account
.getIdentityKeyStore()
2382 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2383 verifiedMessage
.getIdentityKey(),
2384 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2386 if (c
.getExpirationTimer().isPresent()) {
2387 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2389 builder
.withBlocked(c
.isBlocked());
2390 builder
.withArchived(c
.isArchived());
2391 account
.getContactStore().storeContact(recipientId
, builder
.build());
2393 if (c
.getAvatar().isPresent()) {
2394 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2398 } catch (Exception e
) {
2399 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2403 if (tmpFile
!= null) {
2405 Files
.delete(tmpFile
.toPath());
2406 } catch (IOException e
) {
2407 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2414 if (syncMessage
.getVerified().isPresent()) {
2415 final var verifiedMessage
= syncMessage
.getVerified().get();
2416 account
.getIdentityKeyStore()
2417 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2418 verifiedMessage
.getIdentityKey(),
2419 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2421 if (syncMessage
.getStickerPackOperations().isPresent()) {
2422 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2423 for (var m
: stickerPackOperationMessages
) {
2424 if (!m
.getPackId().isPresent()) {
2427 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2428 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2429 if (sticker
== null) {
2430 if (!m
.getPackKey().isPresent()) {
2433 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2435 sticker
.setInstalled(!m
.getType().isPresent()
2436 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2437 account
.getStickerStore().updateSticker(sticker
);
2440 if (syncMessage
.getFetchType().isPresent()) {
2441 switch (syncMessage
.getFetchType().get()) {
2443 getRecipientProfile(account
.getSelfRecipientId(), true);
2444 case STORAGE_MANIFEST
:
2448 if (syncMessage
.getKeys().isPresent()) {
2449 final var keysMessage
= syncMessage
.getKeys().get();
2450 if (keysMessage
.getStorageService().isPresent()) {
2451 final var storageKey
= keysMessage
.getStorageService().get();
2452 account
.setStorageKey(storageKey
);
2455 if (syncMessage
.getConfiguration().isPresent()) {
2463 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2465 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2466 } catch (IOException e
) {
2467 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2471 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2473 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2474 } catch (IOException e
) {
2475 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2479 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2481 avatarStore
.storeGroupAvatar(groupId
,
2482 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2483 } catch (IOException e
) {
2484 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2488 private void downloadProfileAvatar(
2489 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2492 avatarStore
.storeProfileAvatar(address
,
2493 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2494 } catch (Throwable e
) {
2495 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2499 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2500 return attachmentStore
.getAttachmentFile(attachmentId
);
2503 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2504 if (!attachment
.isPointer()) {
2505 logger
.warn("Invalid state, can't store an attachment stream.");
2508 var pointer
= attachment
.asPointer();
2509 if (pointer
.getPreview().isPresent()) {
2510 final var preview
= pointer
.getPreview().get();
2512 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2513 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2514 } catch (IOException e
) {
2515 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2520 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2521 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2522 } catch (IOException e
) {
2523 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2527 private void retrieveGroupV2Avatar(
2528 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2529 ) throws IOException
{
2530 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2532 var tmpFile
= IOUtils
.createTempFile();
2533 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2535 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2536 var encryptedData
= IOUtils
.readFully(input
);
2538 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2539 outputStream
.write(decryptedData
);
2542 Files
.delete(tmpFile
.toPath());
2543 } catch (IOException e
) {
2544 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2551 private void retrieveProfileAvatar(
2552 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2553 ) throws IOException
{
2554 var tmpFile
= IOUtils
.createTempFile();
2555 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2558 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2559 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2560 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2563 Files
.delete(tmpFile
.toPath());
2564 } catch (IOException e
) {
2565 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2572 private void retrieveAttachment(
2573 final SignalServiceAttachment attachment
, final OutputStream outputStream
2574 ) throws IOException
{
2575 if (attachment
.isPointer()) {
2576 var pointer
= attachment
.asPointer();
2577 retrieveAttachmentPointer(pointer
, outputStream
);
2579 var stream
= attachment
.asStream();
2580 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2584 private void retrieveAttachmentPointer(
2585 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2586 ) throws IOException
{
2587 var tmpFile
= IOUtils
.createTempFile();
2588 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2589 IOUtils
.copyStream(input
, outputStream
);
2590 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2591 throw new IOException(e
);
2594 Files
.delete(tmpFile
.toPath());
2595 } catch (IOException e
) {
2596 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2603 private InputStream
retrieveAttachmentAsStream(
2604 SignalServiceAttachmentPointer pointer
, File tmpFile
2605 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2606 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2609 void sendGroups() throws IOException
, UntrustedIdentityException
{
2610 var groupsFile
= IOUtils
.createTempFile();
2613 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2614 var out
= new DeviceGroupsOutputStream(fos
);
2615 for (var record : getGroups()) {
2616 if (record instanceof GroupInfoV1
) {
2617 var groupInfo
= (GroupInfoV1
) record;
2618 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2619 Optional
.fromNullable(groupInfo
.name
),
2620 groupInfo
.getMembers()
2622 .map(this::resolveSignalServiceAddress
)
2623 .collect(Collectors
.toList()),
2624 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2625 groupInfo
.isMember(account
.getSelfRecipientId()),
2626 Optional
.of(groupInfo
.messageExpirationTime
),
2627 Optional
.fromNullable(groupInfo
.color
),
2630 groupInfo
.archived
));
2635 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2636 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2637 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2638 .withStream(groupsFileStream
)
2639 .withContentType("application/octet-stream")
2640 .withLength(groupsFile
.length())
2643 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2648 Files
.delete(groupsFile
.toPath());
2649 } catch (IOException e
) {
2650 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2655 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2656 var contactsFile
= IOUtils
.createTempFile();
2659 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2660 var out
= new DeviceContactsOutputStream(fos
);
2661 for (var contactPair
: account
.getContactStore().getContacts()) {
2662 final var recipientId
= contactPair
.first();
2663 final var contact
= contactPair
.second();
2664 final var address
= resolveSignalServiceAddress(recipientId
);
2666 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2667 VerifiedMessage verifiedMessage
= null;
2668 if (currentIdentity
!= null) {
2669 verifiedMessage
= new VerifiedMessage(address
,
2670 currentIdentity
.getIdentityKey(),
2671 currentIdentity
.getTrustLevel().toVerifiedState(),
2672 currentIdentity
.getDateAdded().getTime());
2675 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2676 out
.write(new DeviceContact(address
,
2677 Optional
.fromNullable(contact
.getName()),
2678 createContactAvatarAttachment(address
),
2679 Optional
.fromNullable(contact
.getColor()),
2680 Optional
.fromNullable(verifiedMessage
),
2681 Optional
.fromNullable(profileKey
),
2682 contact
.isBlocked(),
2683 Optional
.of(contact
.getMessageExpirationTime()),
2685 contact
.isArchived()));
2688 if (account
.getProfileKey() != null) {
2689 // Send our own profile key as well
2690 out
.write(new DeviceContact(account
.getSelfAddress(),
2695 Optional
.of(account
.getProfileKey()),
2703 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2704 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2705 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2706 .withStream(contactsFileStream
)
2707 .withContentType("application/octet-stream")
2708 .withLength(contactsFile
.length())
2711 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2716 Files
.delete(contactsFile
.toPath());
2717 } catch (IOException e
) {
2718 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2723 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2724 var addresses
= new ArrayList
<SignalServiceAddress
>();
2725 for (var record : account
.getContactStore().getContacts()) {
2726 if (record.second().isBlocked()) {
2727 addresses
.add(resolveSignalServiceAddress(record.first()));
2730 var groupIds
= new ArrayList
<byte[]>();
2731 for (var record : getGroups()) {
2732 if (record.isBlocked()) {
2733 groupIds
.add(record.getGroupId().serialize());
2736 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2739 private void sendVerifiedMessage(
2740 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2741 ) throws IOException
, UntrustedIdentityException
{
2742 var verifiedMessage
= new VerifiedMessage(destination
,
2744 trustLevel
.toVerifiedState(),
2745 System
.currentTimeMillis());
2746 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2749 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2750 return account
.getContactStore().getContacts();
2753 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2754 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2755 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2756 if (recipient
== null) {
2760 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2761 return recipient
.getContact().getName();
2764 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2765 return recipient
.getProfile().getDisplayName();
2771 public GroupInfo
getGroup(GroupId groupId
) {
2772 return getGroup(groupId
, false);
2775 public GroupInfo
getGroup(GroupId groupId
, boolean forceUpdate
) {
2776 final var group
= account
.getGroupStore().getGroup(groupId
);
2777 if (group
instanceof GroupInfoV2
&& (forceUpdate
|| ((GroupInfoV2
) group
).getGroup() == null)) {
2778 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2779 ((GroupInfoV2
) group
).setGroup(groupV2Helper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2780 account
.getGroupStore().updateGroup(group
);
2785 public List
<IdentityInfo
> getIdentities() {
2786 return account
.getIdentityKeyStore().getIdentities();
2789 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2790 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2791 return identity
== null ? List
.of() : List
.of(identity
);
2795 * Trust this the identity with this fingerprint
2797 * @param name username of the identity
2798 * @param fingerprint Fingerprint
2800 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2801 var recipientId
= canonicalizeAndResolveRecipient(name
);
2802 return trustIdentity(recipientId
,
2803 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2804 TrustLevel
.TRUSTED_VERIFIED
);
2808 * Trust this the identity with this safety number
2810 * @param name username of the identity
2811 * @param safetyNumber Safety number
2813 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2814 var recipientId
= canonicalizeAndResolveRecipient(name
);
2815 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2816 return trustIdentity(recipientId
,
2817 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2818 TrustLevel
.TRUSTED_VERIFIED
);
2822 * Trust all keys of this identity without verification
2824 * @param name username of the identity
2826 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2827 var recipientId
= canonicalizeAndResolveRecipient(name
);
2828 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2831 private boolean trustIdentity(
2832 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2834 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2835 if (identity
== null) {
2839 if (!verifier
.apply(identity
.getIdentityKey())) {
2843 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2845 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2846 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2847 } catch (IOException
| UntrustedIdentityException e
) {
2848 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2854 public String
computeSafetyNumber(
2855 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2857 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2858 account
.getSelfAddress(),
2859 getIdentityKeyPair().getPublicKey(),
2865 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2866 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2868 return resolveSignalServiceAddress(address
);
2872 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2873 if (address
.matches(account
.getSelfAddress())) {
2874 return account
.getSelfAddress();
2877 return account
.getRecipientStore().resolveServiceAddress(address
);
2880 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2881 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2884 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2885 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2887 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2889 return resolveRecipient(canonicalizedNumber
);
2892 private RecipientId
resolveRecipient(final String identifier
) {
2893 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2895 return resolveRecipient(address
);
2898 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2899 return account
.getRecipientStore().resolveRecipient(address
);
2902 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2903 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2907 public void close() throws IOException
{
2911 void close(boolean closeAccount
) throws IOException
{
2912 executor
.shutdown();
2914 if (messagePipe
!= null) {
2915 messagePipe
.shutdown();
2919 if (unidentifiedMessagePipe
!= null) {
2920 unidentifiedMessagePipe
.shutdown();
2921 unidentifiedMessagePipe
= null;
2924 if (closeAccount
&& account
!= null) {
2930 public interface ReceiveMessageHandler
{
2932 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);