2 Copyright (C) 2015-2021 AsamK and contributors
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.signal
.manager
.api
.Device
;
20 import org
.asamk
.signal
.manager
.api
.TypingAction
;
21 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
22 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
23 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
24 import org
.asamk
.signal
.manager
.groups
.GroupId
;
25 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
26 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
27 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
28 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
29 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
30 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
31 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
32 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
33 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
34 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
35 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
36 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
37 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
38 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
39 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
40 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
41 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
42 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
43 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
44 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
45 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
46 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
47 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
48 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
49 import org
.asamk
.signal
.manager
.util
.IOUtils
;
50 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
51 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
52 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
53 import org
.asamk
.signal
.manager
.util
.Utils
;
54 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
55 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
56 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
57 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
58 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
59 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
60 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
61 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
62 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
63 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
64 import org
.signal
.libsignal
.metadata
.SelfSendException
;
65 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
66 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
67 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
68 import org
.signal
.zkgroup
.InvalidInputException
;
69 import org
.signal
.zkgroup
.VerificationFailedException
;
70 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
71 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
72 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
73 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
74 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
75 import org
.slf4j
.Logger
;
76 import org
.slf4j
.LoggerFactory
;
77 import org
.whispersystems
.libsignal
.IdentityKey
;
78 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
79 import org
.whispersystems
.libsignal
.InvalidKeyException
;
80 import org
.whispersystems
.libsignal
.InvalidMessageException
;
81 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
82 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
83 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
84 import org
.whispersystems
.libsignal
.util
.Pair
;
85 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
86 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
87 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
88 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
89 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
90 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
91 import org
.whispersystems
.signalservice
.api
.crypto
.ContentHint
;
92 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
93 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
94 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
95 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
96 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
97 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
98 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
106 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
107 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
108 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
109 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
110 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
121 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
122 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
123 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
124 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
125 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
126 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
127 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.ConflictException
;
128 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
129 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
130 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
131 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
132 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
133 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
134 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
135 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
136 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
137 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
138 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
139 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
140 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
141 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
142 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
143 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
145 import java
.io
.Closeable
;
147 import java
.io
.FileInputStream
;
148 import java
.io
.FileOutputStream
;
149 import java
.io
.IOException
;
150 import java
.io
.InputStream
;
151 import java
.io
.OutputStream
;
153 import java
.net
.URISyntaxException
;
154 import java
.net
.URLEncoder
;
155 import java
.nio
.charset
.StandardCharsets
;
156 import java
.nio
.file
.Files
;
157 import java
.security
.SignatureException
;
158 import java
.util
.ArrayList
;
159 import java
.util
.Arrays
;
160 import java
.util
.Base64
;
161 import java
.util
.Collection
;
162 import java
.util
.Date
;
163 import java
.util
.HashSet
;
164 import java
.util
.List
;
165 import java
.util
.Map
;
166 import java
.util
.Set
;
167 import java
.util
.UUID
;
168 import java
.util
.concurrent
.ExecutorService
;
169 import java
.util
.concurrent
.Executors
;
170 import java
.util
.concurrent
.TimeUnit
;
171 import java
.util
.concurrent
.TimeoutException
;
172 import java
.util
.concurrent
.locks
.ReentrantLock
;
173 import java
.util
.function
.Function
;
174 import java
.util
.stream
.Collectors
;
176 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
178 public class Manager
implements Closeable
{
180 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
182 private final CertificateValidator certificateValidator
;
184 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
185 private final String userAgent
;
187 private SignalAccount account
;
188 private final SignalServiceAccountManager accountManager
;
189 private final GroupsV2Api groupsV2Api
;
190 private final GroupsV2Operations groupsV2Operations
;
191 private final SignalServiceMessageReceiver messageReceiver
;
192 private final ClientZkProfileOperations clientZkProfileOperations
;
194 private final ExecutorService executor
= Executors
.newCachedThreadPool();
196 private SignalServiceMessagePipe messagePipe
= null;
197 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
199 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
200 private final ProfileHelper profileHelper
;
201 private final GroupV2Helper groupV2Helper
;
202 private final PinHelper pinHelper
;
203 private final AvatarStore avatarStore
;
204 private final AttachmentStore attachmentStore
;
205 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
206 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
209 public Lock
acquire() {
211 return LEGACY_LOCK
::unlock
;
216 SignalAccount account
,
217 PathConfig pathConfig
,
218 ServiceEnvironmentConfig serviceEnvironmentConfig
,
221 this.account
= account
;
222 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
223 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
224 this.userAgent
= userAgent
;
225 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
226 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
227 final SleepTimer timer
= new UptimeSleepTimer();
228 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
229 new DynamicCredentialsProvider(account
.getUuid(),
230 account
.getUsername(),
231 account
.getPassword(),
232 account
.getDeviceId()),
235 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
237 this.groupsV2Api
= accountManager
.getGroupsV2Api();
238 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
239 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
240 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
241 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
244 this.pinHelper
= new PinHelper(keyBackupService
);
245 this.clientZkProfileOperations
= capabilities
.isGv2()
246 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
247 .getProfileOperations()
249 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
251 account
.getUsername(),
252 account
.getPassword(),
253 account
.getDeviceId(),
257 clientZkProfileOperations
,
258 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
260 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
261 account
.getProfileStore()::getProfileKey
,
262 this::getRecipientProfile
,
263 this::getSenderCertificate
);
264 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
265 unidentifiedAccessHelper
::getAccessFor
,
266 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
267 () -> messageReceiver
,
268 this::resolveSignalServiceAddress
);
269 this.groupV2Helper
= new GroupV2Helper(this::getRecipientProfileKeyCredential
,
270 this::getRecipientProfile
,
271 account
::getSelfRecipientId
,
274 this::getGroupAuthForToday
,
275 this::resolveSignalServiceAddress
);
276 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
277 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
280 public String
getUsername() {
281 return account
.getUsername();
284 public SignalServiceAddress
getSelfAddress() {
285 return account
.getSelfAddress();
288 public RecipientId
getSelfRecipientId() {
289 return account
.getSelfRecipientId();
292 private IdentityKeyPair
getIdentityKeyPair() {
293 return account
.getIdentityKeyPair();
296 public int getDeviceId() {
297 return account
.getDeviceId();
300 public static Manager
init(
301 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
302 ) throws IOException
, NotRegisteredException
{
303 var pathConfig
= PathConfig
.createDefault(settingsPath
);
305 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
306 throw new NotRegisteredException();
309 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true);
311 if (!account
.isRegistered()) {
312 throw new NotRegisteredException();
315 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
317 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
320 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
321 var pathConfig
= PathConfig
.createDefault(settingsPath
);
322 final var dataPath
= pathConfig
.getDataPath();
323 final var files
= dataPath
.listFiles();
329 return Arrays
.stream(files
)
330 .filter(File
::isFile
)
332 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
333 .collect(Collectors
.toList());
336 public void checkAccountState() throws IOException
{
337 if (account
.getLastReceiveTimestamp() == 0) {
338 logger
.warn("The Signal protocol expects that incoming messages are regularly received.");
340 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
341 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
344 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
348 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
351 if (account
.getUuid() == null) {
352 account
.setUuid(accountManager
.getOwnUuid());
354 updateAccountAttributes();
358 * This is used for checking a set of phone numbers for registration on Signal
360 * @param numbers The set of phone number in question
361 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
362 * @throws IOException if its unable to get the contacts to check if they're registered
364 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
365 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
366 var contactDetails
= getRegisteredUsers(numbers
);
368 var registeredUsers
= contactDetails
.keySet();
370 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
373 public void updateAccountAttributes() throws IOException
{
374 accountManager
.setAccountAttributes(account
.getEncryptedDeviceName(),
376 account
.getLocalRegistrationId(),
378 // set legacy pin only if no KBS master key is set
379 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
380 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
381 account
.getSelfUnidentifiedAccessKey(),
382 account
.isUnrestrictedUnidentifiedAccess(),
384 account
.isDiscoverableByPhoneNumber());
388 * @param givenName if null, the previous givenName will be kept
389 * @param familyName if null, the previous familyName will be kept
390 * @param about if null, the previous about text will be kept
391 * @param aboutEmoji if null, the previous about emoji will be kept
392 * @param avatar if avatar is null the image from the local avatar store is used (if present),
394 public void setProfile(
395 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
396 ) throws IOException
{
397 var profile
= getRecipientProfile(account
.getSelfRecipientId());
398 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
399 if (givenName
!= null) {
400 builder
.withGivenName(givenName
);
402 if (familyName
!= null) {
403 builder
.withFamilyName(familyName
);
406 builder
.withAbout(about
);
408 if (aboutEmoji
!= null) {
409 builder
.withAboutEmoji(aboutEmoji
);
411 var newProfile
= builder
.build();
413 try (final var streamDetails
= avatar
== null
414 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
415 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
416 accountManager
.setVersionedProfile(account
.getUuid(),
417 account
.getProfileKey(),
418 newProfile
.getInternalServiceName(),
419 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
420 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
425 if (avatar
!= null) {
426 if (avatar
.isPresent()) {
427 avatarStore
.storeProfileAvatar(getSelfAddress(),
428 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
430 avatarStore
.deleteProfileAvatar(getSelfAddress());
433 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
436 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
437 } catch (UntrustedIdentityException ignored
) {
441 public void unregister() throws IOException
{
442 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
443 // If this is the master device, other users can't send messages to this number anymore.
444 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
445 accountManager
.setGcmId(Optional
.absent());
447 account
.setRegistered(false);
450 public void deleteAccount() throws IOException
{
451 accountManager
.deleteAccount();
453 account
.setRegistered(false);
456 public List
<Device
> getLinkedDevices() throws IOException
{
457 var devices
= accountManager
.getDevices();
458 account
.setMultiDevice(devices
.size() > 1);
459 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
460 return devices
.stream().map(d
-> {
461 String deviceName
= d
.getName();
462 if (deviceName
!= null) {
464 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
465 } catch (IOException e
) {
466 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
469 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
470 }).collect(Collectors
.toList());
473 public void removeLinkedDevices(int deviceId
) throws IOException
{
474 accountManager
.removeDevice(deviceId
);
475 var devices
= accountManager
.getDevices();
476 account
.setMultiDevice(devices
.size() > 1);
479 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
480 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
482 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
485 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
486 var identityKeyPair
= getIdentityKeyPair();
487 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
489 accountManager
.addDevice(deviceIdentifier
,
492 Optional
.of(account
.getProfileKey().serialize()),
494 account
.setMultiDevice(true);
497 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
498 if (!account
.isMasterDevice()) {
499 throw new RuntimeException("Only master device can set a PIN");
501 if (pin
.isPresent()) {
502 final var masterKey
= account
.getPinMasterKey() != null
503 ? account
.getPinMasterKey()
504 : KeyUtils
.createMasterKey();
506 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
508 account
.setRegistrationLockPin(pin
.get(), masterKey
);
510 // Remove legacy registration lock
511 accountManager
.removeRegistrationLockV1();
514 pinHelper
.removeRegistrationLockPin();
516 account
.setRegistrationLockPin(null, null);
520 void refreshPreKeys() throws IOException
{
521 var oneTimePreKeys
= generatePreKeys();
522 final var identityKeyPair
= getIdentityKeyPair();
523 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
525 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
528 private List
<PreKeyRecord
> generatePreKeys() {
529 final var offset
= account
.getPreKeyIdOffset();
531 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
532 account
.addPreKeys(records
);
537 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
538 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
540 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
541 account
.addSignedPreKey(record);
546 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
547 if (messagePipe
== null) {
548 messagePipe
= messageReceiver
.createMessagePipe();
553 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
554 if (unidentifiedMessagePipe
== null) {
555 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
557 return unidentifiedMessagePipe
;
560 private SignalServiceMessageSender
createMessageSender() {
561 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
563 account
.getUsername(),
564 account
.getPassword(),
565 account
.getDeviceId(),
566 account
.getSignalProtocolStore(),
569 account
.isMultiDevice(),
570 Optional
.fromNullable(messagePipe
),
571 Optional
.fromNullable(unidentifiedMessagePipe
),
573 clientZkProfileOperations
,
575 ServiceConfig
.MAX_ENVELOPE_SIZE
,
576 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
579 public Profile
getRecipientProfile(
580 RecipientId recipientId
582 return getRecipientProfile(recipientId
, false);
585 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
587 Profile
getRecipientProfile(
588 RecipientId recipientId
, boolean force
590 var profile
= account
.getProfileStore().getProfile(recipientId
);
592 var now
= System
.currentTimeMillis();
593 // Profiles are cached for 24h before retrieving them again, unless forced
594 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
598 synchronized (pendingProfileRequest
) {
599 if (pendingProfileRequest
.contains(recipientId
)) {
602 pendingProfileRequest
.add(recipientId
);
604 final SignalServiceProfile encryptedProfile
;
606 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
608 synchronized (pendingProfileRequest
) {
609 pendingProfileRequest
.remove(recipientId
);
612 if (encryptedProfile
== null) {
616 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
617 if (profileKey
== null) {
618 profile
= new Profile(System
.currentTimeMillis(),
623 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
624 ProfileUtils
.getCapabilities(encryptedProfile
));
626 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
628 account
.getProfileStore().storeProfile(recipientId
, profile
);
633 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
635 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
636 } catch (IOException e
) {
637 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
642 private ProfileAndCredential
retrieveProfileAndCredential(
643 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
644 ) throws IOException
{
645 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
646 final var profile
= profileAndCredential
.getProfile();
649 var newIdentity
= account
.getIdentityKeyStore()
650 .saveIdentity(recipientId
,
651 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
655 account
.getSessionStore().archiveSessions(recipientId
);
657 } catch (InvalidKeyException ignored
) {
658 logger
.warn("Got invalid identity key in profile for {}",
659 resolveSignalServiceAddress(recipientId
).getIdentifier());
661 return profileAndCredential
;
664 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
665 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
666 if (profileKeyCredential
!= null) {
667 return profileKeyCredential
;
670 ProfileAndCredential profileAndCredential
;
672 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
673 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
674 } catch (IOException e
) {
675 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
679 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
680 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
682 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
683 if (profileKey
!= null) {
684 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
686 profileAndCredential
.getProfile());
687 account
.getProfileStore().storeProfile(recipientId
, profile
);
690 return profileKeyCredential
;
693 private Profile
decryptProfileAndDownloadAvatar(
694 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
696 if (encryptedProfile
.getAvatar() != null) {
697 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
700 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
703 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
704 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
705 if (streamDetails
== null) {
706 return Optional
.absent();
709 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
712 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
713 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
714 if (streamDetails
== null) {
715 return Optional
.absent();
718 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
721 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
722 var g
= getGroup(groupId
);
724 throw new GroupNotFoundException(groupId
);
726 if (!g
.isMember(account
.getSelfRecipientId())) {
727 throw new NotAGroupMemberException(groupId
, g
.getTitle());
732 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
733 var g
= getGroup(groupId
);
735 throw new GroupNotFoundException(groupId
);
737 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
738 throw new NotAGroupMemberException(groupId
, g
.getTitle());
743 public List
<GroupInfo
> getGroups() {
744 return account
.getGroupStore().getGroups();
747 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
748 String messageText
, List
<String
> attachments
, GroupId groupId
749 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
750 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
751 if (attachments
!= null) {
752 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
755 return sendGroupMessage(messageBuilder
, groupId
);
758 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
759 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
760 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
761 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
762 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
764 resolveSignalServiceAddress(targetAuthorRecipientId
),
765 targetSentTimestamp
);
766 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
768 return sendGroupMessage(messageBuilder
, groupId
);
771 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
772 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
773 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
774 final var g
= getGroupForSending(groupId
);
776 GroupUtils
.setGroupContext(messageBuilder
, g
);
777 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
779 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
782 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(
783 GroupId groupId
, Set
<String
> groupAdmins
784 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, InvalidNumberException
, LastGroupAdminException
{
785 var group
= getGroupForUpdating(groupId
);
786 if (group
instanceof GroupInfoV1
) {
787 return quitGroupV1((GroupInfoV1
) group
);
790 final var newAdmins
= getSignalServiceAddresses(groupAdmins
);
792 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
793 } catch (ConflictException e
) {
794 // Detected conflicting update, refreshing group and trying again
795 group
= getGroup(groupId
, true);
796 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
800 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV1(final GroupInfoV1 groupInfoV1
) throws IOException
{
801 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
802 .withId(groupInfoV1
.getGroupId().serialize())
805 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
806 groupInfoV1
.removeMember(account
.getSelfRecipientId());
807 account
.getGroupStore().updateGroup(groupInfoV1
);
808 return sendMessage(messageBuilder
, groupInfoV1
.getMembersWithout(account
.getSelfRecipientId()));
811 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV2(
812 final GroupInfoV2 groupInfoV2
, final Set
<RecipientId
> newAdmins
813 ) throws LastGroupAdminException
, IOException
{
814 final var currentAdmins
= groupInfoV2
.getAdminMembers();
815 newAdmins
.removeAll(currentAdmins
);
816 newAdmins
.retainAll(groupInfoV2
.getMembers());
817 if (currentAdmins
.contains(getSelfRecipientId())
818 && currentAdmins
.size() == 1
819 && groupInfoV2
.getMembers().size() > 1
820 && newAdmins
.size() == 0) {
821 // Last admin can't leave the group, unless she's also the last member
822 throw new LastGroupAdminException(groupInfoV2
.getGroupId(), groupInfoV2
.getTitle());
824 final var groupGroupChangePair
= groupV2Helper
.leaveGroup(groupInfoV2
, newAdmins
);
825 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
826 var messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
827 account
.getGroupStore().updateGroup(groupInfoV2
);
828 return sendMessage(messageBuilder
, groupInfoV2
.getMembersWithout(account
.getSelfRecipientId()));
831 public void deleteGroup(GroupId groupId
) throws IOException
{
832 account
.getGroupStore().deleteGroup(groupId
);
833 avatarStore
.deleteGroupAvatar(groupId
);
836 public Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
837 String name
, List
<String
> members
, File avatarFile
838 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
839 return createGroup(name
, members
== null ?
null : getSignalServiceAddresses(members
), avatarFile
);
842 private Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
843 String name
, Set
<RecipientId
> members
, File avatarFile
844 ) throws IOException
, AttachmentInvalidException
{
845 final var selfRecipientId
= account
.getSelfRecipientId();
846 if (members
!= null && members
.contains(selfRecipientId
)) {
847 members
= new HashSet
<>(members
);
848 members
.remove(selfRecipientId
);
851 var gv2Pair
= groupV2Helper
.createGroup(name
== null ?
"" : name
,
852 members
== null ? Set
.of() : members
,
855 SignalServiceDataMessage
.Builder messageBuilder
;
856 if (gv2Pair
== null) {
857 // Failed to create v2 group, creating v1 group instead
858 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
859 gv1
.addMembers(List
.of(selfRecipientId
));
860 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
861 return new Pair
<>(gv1
.getGroupId(), result
.second());
864 final var gv2
= gv2Pair
.first();
865 final var decryptedGroup
= gv2Pair
.second();
867 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
868 if (avatarFile
!= null) {
869 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
870 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
872 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
873 account
.getGroupStore().updateGroup(gv2
);
875 final var result
= sendMessage(messageBuilder
, gv2
.getMembersIncludingPendingWithout(selfRecipientId
));
876 return new Pair
<>(gv2
.getGroupId(), result
.second());
879 public Pair
<Long
, List
<SendMessageResult
>> updateGroup(
883 List
<String
> members
,
884 List
<String
> removeMembers
,
886 List
<String
> removeAdmins
,
887 boolean resetGroupLink
,
888 GroupLinkState groupLinkState
,
889 GroupPermission addMemberPermission
,
890 GroupPermission editDetailsPermission
,
892 Integer expirationTimer
893 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
894 return updateGroup(groupId
,
897 members
== null ?
null : getSignalServiceAddresses(members
),
898 removeMembers
== null ?
null : getSignalServiceAddresses(removeMembers
),
899 admins
== null ?
null : getSignalServiceAddresses(admins
),
900 removeAdmins
== null ?
null : getSignalServiceAddresses(removeAdmins
),
904 editDetailsPermission
,
909 private Pair
<Long
, List
<SendMessageResult
>> updateGroup(
910 final GroupId groupId
,
912 final String description
,
913 final Set
<RecipientId
> members
,
914 final Set
<RecipientId
> removeMembers
,
915 final Set
<RecipientId
> admins
,
916 final Set
<RecipientId
> removeAdmins
,
917 final boolean resetGroupLink
,
918 final GroupLinkState groupLinkState
,
919 final GroupPermission addMemberPermission
,
920 final GroupPermission editDetailsPermission
,
921 final File avatarFile
,
922 final Integer expirationTimer
923 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
924 var group
= getGroupForUpdating(groupId
);
926 if (group
instanceof GroupInfoV2
) {
928 return updateGroupV2((GroupInfoV2
) group
,
938 editDetailsPermission
,
941 } catch (ConflictException e
) {
942 // Detected conflicting update, refreshing group and trying again
943 group
= getGroup(groupId
, true);
944 return updateGroupV2((GroupInfoV2
) group
,
954 editDetailsPermission
,
960 final var gv1
= (GroupInfoV1
) group
;
961 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
962 if (expirationTimer
!= null) {
963 setExpirationTimer(gv1
, expirationTimer
);
968 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV1(
969 final GroupInfoV1 gv1
, final String name
, final Set
<RecipientId
> members
, final File avatarFile
970 ) throws IOException
, AttachmentInvalidException
{
971 updateGroupV1Details(gv1
, name
, members
, avatarFile
);
972 var messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
974 account
.getGroupStore().updateGroup(gv1
);
976 return sendMessage(messageBuilder
, gv1
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
979 private void updateGroupV1Details(
980 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
981 ) throws IOException
{
986 if (members
!= null) {
987 final var newMemberAddresses
= members
.stream()
988 .filter(member
-> !g
.isMember(member
))
989 .map(this::resolveSignalServiceAddress
)
990 .collect(Collectors
.toList());
991 final var newE164Members
= new HashSet
<String
>();
992 for (var member
: newMemberAddresses
) {
993 if (!member
.getNumber().isPresent()) {
996 newE164Members
.add(member
.getNumber().get());
999 final var registeredUsers
= getRegisteredUsers(newE164Members
);
1000 if (registeredUsers
.size() != newE164Members
.size()) {
1001 // Some of the new members are not registered on Signal
1002 newE164Members
.removeAll(registeredUsers
.keySet());
1003 throw new IOException("Failed to add members "
1004 + String
.join(", ", newE164Members
)
1005 + " to group: Not registered on Signal");
1008 g
.addMembers(members
);
1011 if (avatarFile
!= null) {
1012 avatarStore
.storeGroupAvatar(g
.getGroupId(),
1013 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
1017 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV2(
1018 final GroupInfoV2 group
,
1020 final String description
,
1021 final Set
<RecipientId
> members
,
1022 final Set
<RecipientId
> removeMembers
,
1023 final Set
<RecipientId
> admins
,
1024 final Set
<RecipientId
> removeAdmins
,
1025 final boolean resetGroupLink
,
1026 final GroupLinkState groupLinkState
,
1027 final GroupPermission addMemberPermission
,
1028 final GroupPermission editDetailsPermission
,
1029 final File avatarFile
,
1030 Integer expirationTimer
1031 ) throws IOException
{
1032 Pair
<Long
, List
<SendMessageResult
>> result
= null;
1033 if (group
.isPendingMember(account
.getSelfRecipientId())) {
1034 var groupGroupChangePair
= groupV2Helper
.acceptInvite(group
);
1035 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1038 if (members
!= null) {
1039 final var newMembers
= new HashSet
<>(members
);
1040 newMembers
.removeAll(group
.getMembers());
1041 if (newMembers
.size() > 0) {
1042 var groupGroupChangePair
= groupV2Helper
.addMembers(group
, newMembers
);
1043 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1047 if (removeMembers
!= null) {
1048 var existingRemoveMembers
= new HashSet
<>(removeMembers
);
1049 existingRemoveMembers
.retainAll(group
.getMembers());
1050 existingRemoveMembers
.remove(getSelfRecipientId());// self can be removed with sendQuitGroupMessage
1051 if (existingRemoveMembers
.size() > 0) {
1052 var groupGroupChangePair
= groupV2Helper
.removeMembers(group
, existingRemoveMembers
);
1053 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1056 var pendingRemoveMembers
= new HashSet
<>(removeMembers
);
1057 pendingRemoveMembers
.retainAll(group
.getPendingMembers());
1058 if (pendingRemoveMembers
.size() > 0) {
1059 var groupGroupChangePair
= groupV2Helper
.revokeInvitedMembers(group
, pendingRemoveMembers
);
1060 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1064 if (admins
!= null) {
1065 final var newAdmins
= new HashSet
<>(admins
);
1066 newAdmins
.retainAll(group
.getMembers());
1067 newAdmins
.removeAll(group
.getAdminMembers());
1068 if (newAdmins
.size() > 0) {
1069 for (var admin
: newAdmins
) {
1070 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, true);
1071 result
= sendUpdateGroupV2Message(group
,
1072 groupGroupChangePair
.first(),
1073 groupGroupChangePair
.second());
1078 if (removeAdmins
!= null) {
1079 final var existingRemoveAdmins
= new HashSet
<>(removeAdmins
);
1080 existingRemoveAdmins
.retainAll(group
.getAdminMembers());
1081 if (existingRemoveAdmins
.size() > 0) {
1082 for (var admin
: existingRemoveAdmins
) {
1083 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, false);
1084 result
= sendUpdateGroupV2Message(group
,
1085 groupGroupChangePair
.first(),
1086 groupGroupChangePair
.second());
1091 if (resetGroupLink
) {
1092 var groupGroupChangePair
= groupV2Helper
.resetGroupLinkPassword(group
);
1093 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1096 if (groupLinkState
!= null) {
1097 var groupGroupChangePair
= groupV2Helper
.setGroupLinkState(group
, groupLinkState
);
1098 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1101 if (addMemberPermission
!= null) {
1102 var groupGroupChangePair
= groupV2Helper
.setAddMemberPermission(group
, addMemberPermission
);
1103 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1106 if (editDetailsPermission
!= null) {
1107 var groupGroupChangePair
= groupV2Helper
.setEditDetailsPermission(group
, editDetailsPermission
);
1108 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1111 if (expirationTimer
!= null) {
1112 var groupGroupChangePair
= groupV2Helper
.setMessageExpirationTimer(group
, expirationTimer
);
1113 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1116 if (name
!= null || description
!= null || avatarFile
!= null) {
1117 var groupGroupChangePair
= groupV2Helper
.updateGroup(group
, name
, description
, avatarFile
);
1118 if (avatarFile
!= null) {
1119 avatarStore
.storeGroupAvatar(group
.getGroupId(),
1120 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
1122 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1128 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
1129 GroupInviteLinkUrl inviteLinkUrl
1130 ) throws IOException
, GroupLinkNotActiveException
{
1131 final var groupJoinInfo
= groupV2Helper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
1132 inviteLinkUrl
.getPassword());
1133 final var groupChange
= groupV2Helper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
1134 inviteLinkUrl
.getPassword(),
1136 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
1137 groupJoinInfo
.getRevision() + 1,
1138 groupChange
.toByteArray());
1140 if (group
.getGroup() == null) {
1141 // Only requested member, can't send update to group members
1142 return new Pair
<>(group
.getGroupId(), List
.of());
1145 final var result
= sendUpdateGroupV2Message(group
, group
.getGroup(), groupChange
);
1147 return new Pair
<>(group
.getGroupId(), result
.second());
1150 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupV2Message(
1151 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
1152 ) throws IOException
{
1153 final var selfRecipientId
= account
.getSelfRecipientId();
1154 final var members
= group
.getMembersIncludingPendingWithout(selfRecipientId
);
1155 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
1156 members
.addAll(group
.getMembersIncludingPendingWithout(selfRecipientId
));
1158 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
1159 account
.getGroupStore().updateGroup(group
);
1160 return sendMessage(messageBuilder
, members
);
1163 private static int currentTimeDays() {
1164 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
1167 private GroupsV2AuthorizationString
getGroupAuthForToday(
1168 final GroupSecretParams groupSecretParams
1169 ) throws IOException
{
1170 final var today
= currentTimeDays();
1171 // Returns credentials for the next 7 days
1172 final var credentials
= groupsV2Api
.getCredentials(today
);
1173 // TODO cache credentials until they expire
1174 var authCredentialResponse
= credentials
.get(today
);
1176 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
1179 authCredentialResponse
);
1180 } catch (VerificationFailedException e
) {
1181 throw new IOException(e
);
1185 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
1186 GroupIdV1 groupId
, SignalServiceAddress recipient
1187 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
1189 var group
= getGroupForSending(groupId
);
1190 if (!(group
instanceof GroupInfoV1
)) {
1191 throw new RuntimeException("Received an invalid group request for a v2 group!");
1193 g
= (GroupInfoV1
) group
;
1195 final var recipientId
= resolveRecipient(recipient
);
1196 if (!g
.isMember(recipientId
)) {
1197 throw new NotAGroupMemberException(groupId
, g
.name
);
1200 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
1202 // Send group message only to the recipient who requested it
1203 return sendMessage(messageBuilder
, Set
.of(recipientId
));
1206 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
1207 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
1208 .withId(g
.getGroupId().serialize())
1210 .withMembers(g
.getMembers()
1212 .map(this::resolveSignalServiceAddress
)
1213 .collect(Collectors
.toList()));
1216 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
1217 if (attachment
.isPresent()) {
1218 group
.withAvatar(attachment
.get());
1220 } catch (IOException e
) {
1221 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
1224 return SignalServiceDataMessage
.newBuilder()
1225 .asGroupMessage(group
.build())
1226 .withExpiration(g
.getMessageExpirationTime());
1229 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
1230 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
1231 .withRevision(g
.getGroup().getRevision())
1232 .withSignedGroupChange(signedGroupChange
);
1233 return SignalServiceDataMessage
.newBuilder()
1234 .asGroupMessage(group
.build())
1235 .withExpiration(g
.getMessageExpirationTime());
1238 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
1239 GroupIdV1 groupId
, SignalServiceAddress recipient
1240 ) throws IOException
{
1241 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
1243 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
1245 // Send group info request message to the recipient who sent us a message with this groupId
1246 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1250 SignalServiceAddress remoteAddress
, long messageId
1251 ) throws IOException
, UntrustedIdentityException
{
1252 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1254 System
.currentTimeMillis());
1256 createMessageSender().sendReceipt(remoteAddress
,
1257 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1261 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1262 String messageText
, List
<String
> attachments
, List
<String
> recipients
1263 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1264 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1265 if (attachments
!= null) {
1266 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1268 // Upload attachments here, so we only upload once even for multiple recipients
1269 var messageSender
= createMessageSender();
1270 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1271 for (var attachment
: attachmentStreams
) {
1272 if (attachment
.isStream()) {
1273 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1274 } else if (attachment
.isPointer()) {
1275 attachmentPointers
.add(attachment
.asPointer());
1279 messageBuilder
.withAttachments(attachmentPointers
);
1281 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1284 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1285 String messageText
, List
<String
> attachments
1286 ) throws IOException
, AttachmentInvalidException
{
1287 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1288 if (attachments
!= null) {
1289 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1291 return sendSelfMessage(messageBuilder
);
1294 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1295 long targetSentTimestamp
, List
<String
> recipients
1296 ) throws IOException
, InvalidNumberException
{
1297 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1298 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1299 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1302 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1303 long targetSentTimestamp
, GroupId groupId
1304 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1305 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1306 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1307 return sendGroupMessage(messageBuilder
, groupId
);
1310 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1311 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1312 ) throws IOException
, InvalidNumberException
{
1313 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1314 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1316 resolveSignalServiceAddress(targetAuthorRecipientId
),
1317 targetSentTimestamp
);
1318 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1319 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1322 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1323 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1325 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1327 return sendMessage(messageBuilder
, signalServiceAddresses
);
1328 } catch (Exception e
) {
1329 for (var address
: signalServiceAddresses
) {
1330 handleEndSession(address
);
1336 void renewSession(RecipientId recipientId
) throws IOException
{
1337 account
.getSessionStore().archiveSessions(recipientId
);
1338 if (!recipientId
.equals(getSelfRecipientId())) {
1339 sendNullMessage(recipientId
);
1343 public String
getContactName(String number
) throws InvalidNumberException
{
1344 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1345 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1348 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1349 if (!account
.isMasterDevice()) {
1350 throw new NotMasterDeviceException();
1352 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1353 var contact
= account
.getContactStore().getContact(recipientId
);
1354 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1355 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1358 public void setContactBlocked(
1359 String number
, boolean blocked
1360 ) throws InvalidNumberException
, NotMasterDeviceException
{
1361 if (!account
.isMasterDevice()) {
1362 throw new NotMasterDeviceException();
1364 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1367 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1368 var contact
= account
.getContactStore().getContact(recipientId
);
1369 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1370 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1373 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1374 var group
= getGroup(groupId
);
1375 if (group
== null) {
1376 throw new GroupNotFoundException(groupId
);
1379 group
.setBlocked(blocked
);
1380 account
.getGroupStore().updateGroup(group
);
1383 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1384 var contact
= account
.getContactStore().getContact(recipientId
);
1385 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1388 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1389 account
.getContactStore()
1390 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1393 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1394 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1395 sendMessage(messageBuilder
, Set
.of(recipientId
));
1399 * Change the expiration timer for a contact
1401 public void setExpirationTimer(
1402 String number
, int messageExpirationTimer
1403 ) throws IOException
, InvalidNumberException
{
1404 var recipientId
= canonicalizeAndResolveRecipient(number
);
1405 setExpirationTimer(recipientId
, messageExpirationTimer
);
1406 sendExpirationTimerUpdate(recipientId
);
1410 * Change the expiration timer for a group
1412 private void setExpirationTimer(
1413 GroupInfoV1 groupInfoV1
, int messageExpirationTimer
1414 ) throws NotAGroupMemberException
, GroupNotFoundException
, IOException
{
1415 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1416 account
.getGroupStore().updateGroup(groupInfoV1
);
1417 sendExpirationTimerUpdate(groupInfoV1
.getGroupId());
1420 private void sendExpirationTimerUpdate(GroupIdV1 groupId
) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1421 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1422 sendGroupMessage(messageBuilder
, groupId
);
1426 * Upload the sticker pack from path.
1428 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1429 * @return if successful, returns the URL to install the sticker pack in the signal app
1431 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1432 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1434 var messageSender
= createMessageSender();
1436 var packKey
= KeyUtils
.createStickerUploadKey();
1437 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1439 var sticker
= new Sticker(StickerPackId
.deserialize(Hex
.fromStringCondensed(packId
)), packKey
);
1440 account
.getStickerStore().updateSticker(sticker
);
1443 return new URI("https",
1446 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1447 Hex
.toStringCondensed(packKey
),
1448 StandardCharsets
.UTF_8
)).toString();
1449 } catch (URISyntaxException e
) {
1450 throw new AssertionError(e
);
1454 public void requestAllSyncData() throws IOException
{
1455 requestSyncGroups();
1456 requestSyncContacts();
1457 requestSyncBlocked();
1458 requestSyncConfiguration();
1462 private void requestSyncGroups() throws IOException
{
1463 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1464 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1466 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1468 sendSyncMessage(message
);
1469 } catch (UntrustedIdentityException e
) {
1470 throw new AssertionError(e
);
1474 private void requestSyncContacts() throws IOException
{
1475 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1476 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1478 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1480 sendSyncMessage(message
);
1481 } catch (UntrustedIdentityException e
) {
1482 throw new AssertionError(e
);
1486 private void requestSyncBlocked() throws IOException
{
1487 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1488 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1490 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1492 sendSyncMessage(message
);
1493 } catch (UntrustedIdentityException e
) {
1494 throw new AssertionError(e
);
1498 private void requestSyncConfiguration() throws IOException
{
1499 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1500 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1502 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1504 sendSyncMessage(message
);
1505 } catch (UntrustedIdentityException e
) {
1506 throw new AssertionError(e
);
1510 private void requestSyncKeys() throws IOException
{
1511 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1512 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1514 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1516 sendSyncMessage(message
);
1517 } catch (UntrustedIdentityException e
) {
1518 throw new AssertionError(e
);
1522 private byte[] getSenderCertificate() {
1525 if (account
.isPhoneNumberShared()) {
1526 certificate
= accountManager
.getSenderCertificate();
1528 certificate
= accountManager
.getSenderCertificateForPhoneNumberPrivacy();
1530 } catch (IOException e
) {
1531 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1534 // TODO cache for a day
1538 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1539 var messageSender
= createMessageSender();
1540 messageSender
.sendSyncMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1543 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1544 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1545 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1547 for (var number
: numbers
) {
1548 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1549 if (resolvedAddress
.getUuid().isPresent()) {
1550 signalServiceAddresses
.add(resolvedAddress
);
1552 addressesMissingUuid
.add(resolvedAddress
);
1556 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1557 .map(a
-> a
.getNumber().get())
1558 .collect(Collectors
.toSet());
1559 Map
<String
, UUID
> registeredUsers
;
1561 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1562 } catch (IOException e
) {
1563 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1564 registeredUsers
= Map
.of();
1567 for (var address
: addressesMissingUuid
) {
1568 final var number
= address
.getNumber().get();
1569 if (registeredUsers
.containsKey(number
)) {
1570 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1571 registeredUsers
.get(number
),
1573 signalServiceAddresses
.add(newAddress
);
1575 signalServiceAddresses
.add(address
);
1579 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1582 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1583 final var address
= resolveSignalServiceAddress(recipientId
);
1584 if (!address
.getNumber().isPresent()) {
1587 final var number
= address
.getNumber().get();
1588 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1589 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1592 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1594 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1596 serviceEnvironmentConfig
.getCdsMrenclave());
1597 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1598 throw new IOException(e
);
1602 public void sendTypingMessage(
1603 TypingAction action
, Set
<String
> recipients
1604 ) throws IOException
, UntrustedIdentityException
, InvalidNumberException
{
1605 sendTypingMessageInternal(action
, getSignalServiceAddresses(recipients
));
1608 private void sendTypingMessageInternal(
1609 TypingAction action
, Set
<RecipientId
> recipientIds
1610 ) throws IOException
, UntrustedIdentityException
{
1611 final var timestamp
= System
.currentTimeMillis();
1612 var message
= new SignalServiceTypingMessage(action
.toSignalService(), timestamp
, Optional
.absent());
1613 var messageSender
= createMessageSender();
1614 for (var recipientId
: recipientIds
) {
1615 final var address
= resolveSignalServiceAddress(recipientId
);
1616 messageSender
.sendTyping(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
), message
);
1620 public void sendGroupTypingMessage(
1621 TypingAction action
, GroupId groupId
1622 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1623 final var timestamp
= System
.currentTimeMillis();
1624 final var g
= getGroupForSending(groupId
);
1625 final var message
= new SignalServiceTypingMessage(action
.toSignalService(),
1627 Optional
.of(groupId
.serialize()));
1628 final var messageSender
= createMessageSender();
1629 final var recipientIdList
= new ArrayList
<>(g
.getMembersWithout(account
.getSelfRecipientId()));
1630 final var addresses
= recipientIdList
.stream()
1631 .map(this::resolveSignalServiceAddress
)
1632 .collect(Collectors
.toList());
1633 messageSender
.sendTyping(addresses
, unidentifiedAccessHelper
.getAccessFor(recipientIdList
), message
, null);
1636 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1637 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1638 ) throws IOException
{
1639 final var timestamp
= System
.currentTimeMillis();
1640 messageBuilder
.withTimestamp(timestamp
);
1641 getOrCreateMessagePipe();
1642 getOrCreateUnidentifiedMessagePipe();
1643 SignalServiceDataMessage message
= null;
1645 message
= messageBuilder
.build();
1646 if (message
.getGroupContext().isPresent()) {
1648 var messageSender
= createMessageSender();
1649 final var isRecipientUpdate
= false;
1650 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1651 final var addresses
= recipientIdList
.stream()
1652 .map(this::resolveSignalServiceAddress
)
1653 .collect(Collectors
.toList());
1654 var result
= messageSender
.sendDataMessage(addresses
,
1655 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1657 ContentHint
.DEFAULT
,
1660 for (var r
: result
) {
1661 if (r
.getIdentityFailure() != null) {
1662 final var recipientId
= resolveRecipient(r
.getAddress());
1663 final var newIdentity
= account
.getIdentityKeyStore()
1664 .saveIdentity(recipientId
, r
.getIdentityFailure().getIdentityKey(), new Date());
1666 account
.getSessionStore().archiveSessions(recipientId
);
1671 return new Pair
<>(timestamp
, result
);
1672 } catch (UntrustedIdentityException e
) {
1673 return new Pair
<>(timestamp
, List
.of());
1676 // Send to all individually, so sync messages are sent correctly
1677 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1678 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1679 for (var recipientId
: recipientIds
) {
1680 final var contact
= account
.getContactStore().getContact(recipientId
);
1681 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1682 messageBuilder
.withExpiration(expirationTime
);
1683 message
= messageBuilder
.build();
1684 results
.add(sendMessage(recipientId
, message
));
1686 return new Pair
<>(timestamp
, results
);
1689 if (message
!= null && message
.isEndSession()) {
1690 for (var recipient
: recipientIds
) {
1691 handleEndSession(recipient
);
1697 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1698 SignalServiceDataMessage
.Builder messageBuilder
1699 ) throws IOException
{
1700 final var timestamp
= System
.currentTimeMillis();
1701 messageBuilder
.withTimestamp(timestamp
);
1702 getOrCreateMessagePipe();
1703 getOrCreateUnidentifiedMessagePipe();
1704 final var recipientId
= account
.getSelfRecipientId();
1706 final var contact
= account
.getContactStore().getContact(recipientId
);
1707 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1708 messageBuilder
.withExpiration(expirationTime
);
1710 var message
= messageBuilder
.build();
1711 final var result
= sendSelfMessage(message
);
1712 return new Pair
<>(timestamp
, result
);
1715 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1716 var messageSender
= createMessageSender();
1718 var recipientId
= account
.getSelfRecipientId();
1720 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipientId
);
1721 var recipient
= resolveSignalServiceAddress(recipientId
);
1722 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1723 message
.getTimestamp(),
1725 message
.getExpiresInSeconds(),
1726 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1728 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1731 var startTime
= System
.currentTimeMillis();
1732 messageSender
.sendSyncMessage(syncMessage
, unidentifiedAccess
);
1733 return SendMessageResult
.success(recipient
,
1734 unidentifiedAccess
.isPresent(),
1736 System
.currentTimeMillis() - startTime
);
1737 } catch (UntrustedIdentityException e
) {
1738 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1742 private SendMessageResult
sendMessage(
1743 RecipientId recipientId
, SignalServiceDataMessage message
1744 ) throws IOException
{
1745 var messageSender
= createMessageSender();
1747 final var address
= resolveSignalServiceAddress(recipientId
);
1750 return messageSender
.sendDataMessage(address
,
1751 unidentifiedAccessHelper
.getAccessFor(recipientId
),
1752 ContentHint
.DEFAULT
,
1754 } catch (UnregisteredUserException e
) {
1755 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1756 return messageSender
.sendDataMessage(resolveSignalServiceAddress(newRecipientId
),
1757 unidentifiedAccessHelper
.getAccessFor(newRecipientId
),
1758 ContentHint
.DEFAULT
,
1761 } catch (UntrustedIdentityException e
) {
1762 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1766 private SendMessageResult
sendNullMessage(RecipientId recipientId
) throws IOException
{
1767 var messageSender
= createMessageSender();
1769 final var address
= resolveSignalServiceAddress(recipientId
);
1772 return messageSender
.sendNullMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
));
1773 } catch (UnregisteredUserException e
) {
1774 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1775 final var newAddress
= resolveSignalServiceAddress(newRecipientId
);
1776 return messageSender
.sendNullMessage(newAddress
, unidentifiedAccessHelper
.getAccessFor(newRecipientId
));
1778 } catch (UntrustedIdentityException e
) {
1779 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1783 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, ProtocolUntrustedIdentityException
{
1784 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1785 account
.getSignalProtocolStore(),
1787 certificateValidator
);
1788 return cipher
.decrypt(envelope
);
1791 private void handleEndSession(RecipientId recipientId
) {
1792 account
.getSessionStore().deleteAllSessions(recipientId
);
1795 private List
<HandleAction
> handleSignalServiceDataMessage(
1796 SignalServiceDataMessage message
,
1798 SignalServiceAddress source
,
1799 SignalServiceAddress destination
,
1800 boolean ignoreAttachments
1802 var actions
= new ArrayList
<HandleAction
>();
1803 if (message
.getGroupContext().isPresent()) {
1804 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1805 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1806 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1807 var group
= getGroup(groupId
);
1808 if (group
== null || group
instanceof GroupInfoV1
) {
1809 var groupV1
= (GroupInfoV1
) group
;
1810 switch (groupInfo
.getType()) {
1812 if (groupV1
== null) {
1813 groupV1
= new GroupInfoV1(groupId
);
1816 if (groupInfo
.getAvatar().isPresent()) {
1817 var avatar
= groupInfo
.getAvatar().get();
1818 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1821 if (groupInfo
.getName().isPresent()) {
1822 groupV1
.name
= groupInfo
.getName().get();
1825 if (groupInfo
.getMembers().isPresent()) {
1826 groupV1
.addMembers(groupInfo
.getMembers()
1829 .map(this::resolveRecipient
)
1830 .collect(Collectors
.toSet()));
1833 account
.getGroupStore().updateGroup(groupV1
);
1837 if (groupV1
== null && !isSync
) {
1838 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1842 if (groupV1
!= null) {
1843 groupV1
.removeMember(resolveRecipient(source
));
1844 account
.getGroupStore().updateGroup(groupV1
);
1849 if (groupV1
!= null && !isSync
) {
1850 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1855 // Received a group v1 message for a v2 group
1858 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1859 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1860 final var groupMasterKey
= groupContext
.getMasterKey();
1862 getOrMigrateGroup(groupMasterKey
,
1863 groupContext
.getRevision(),
1864 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1868 final var conversationPartnerAddress
= isSync ? destination
: source
;
1869 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1870 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1872 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1873 if (message
.getGroupContext().isPresent()) {
1874 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1875 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1876 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1877 if (group
!= null) {
1878 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1879 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1880 account
.getGroupStore().updateGroup(group
);
1883 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1884 // disappearing message timer already stored in the DecryptedGroup
1886 } else if (conversationPartnerAddress
!= null) {
1887 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1890 if (!ignoreAttachments
) {
1891 if (message
.getAttachments().isPresent()) {
1892 for (var attachment
: message
.getAttachments().get()) {
1893 downloadAttachment(attachment
);
1896 if (message
.getSharedContacts().isPresent()) {
1897 for (var contact
: message
.getSharedContacts().get()) {
1898 if (contact
.getAvatar().isPresent()) {
1899 downloadAttachment(contact
.getAvatar().get().getAttachment());
1904 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1905 final ProfileKey profileKey
;
1907 profileKey
= new ProfileKey(message
.getProfileKey().get());
1908 } catch (InvalidInputException e
) {
1909 throw new AssertionError(e
);
1911 if (source
.matches(account
.getSelfAddress())) {
1912 this.account
.setProfileKey(profileKey
);
1914 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1916 if (message
.getPreviews().isPresent()) {
1917 final var previews
= message
.getPreviews().get();
1918 for (var preview
: previews
) {
1919 if (preview
.getImage().isPresent()) {
1920 downloadAttachment(preview
.getImage().get());
1924 if (message
.getQuote().isPresent()) {
1925 final var quote
= message
.getQuote().get();
1927 for (var quotedAttachment
: quote
.getAttachments()) {
1928 final var thumbnail
= quotedAttachment
.getThumbnail();
1929 if (thumbnail
!= null) {
1930 downloadAttachment(thumbnail
);
1934 if (message
.getSticker().isPresent()) {
1935 final var messageSticker
= message
.getSticker().get();
1936 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1937 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1938 if (sticker
== null) {
1939 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1940 account
.getStickerStore().updateSticker(sticker
);
1946 private GroupInfoV2
getOrMigrateGroup(
1947 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1949 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1951 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1952 var groupInfo
= getGroup(groupId
);
1953 final GroupInfoV2 groupInfoV2
;
1954 if (groupInfo
instanceof GroupInfoV1
) {
1955 // Received a v2 group message for a v1 group, we need to locally migrate the group
1956 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1957 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1958 logger
.info("Locally migrated group {} to group v2, id: {}",
1959 groupInfo
.getGroupId().toBase64(),
1960 groupInfoV2
.getGroupId().toBase64());
1961 } else if (groupInfo
instanceof GroupInfoV2
) {
1962 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1964 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1967 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1968 DecryptedGroup group
= null;
1969 if (signedGroupChange
!= null
1970 && groupInfoV2
.getGroup() != null
1971 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1972 group
= groupV2Helper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(),
1976 if (group
== null) {
1977 group
= groupV2Helper
.getDecryptedGroup(groupSecretParams
);
1979 if (group
!= null) {
1980 storeProfileKeysFromMembers(group
);
1981 final var avatar
= group
.getAvatar();
1982 if (avatar
!= null && !avatar
.isEmpty()) {
1983 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1986 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
1987 account
.getGroupStore().updateGroup(groupInfoV2
);
1993 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1994 for (var member
: group
.getMembersList()) {
1995 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
1996 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
1998 account
.getProfileStore()
1999 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
2000 } catch (InvalidInputException ignored
) {
2005 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
2006 Set
<HandleAction
> queuedActions
= new HashSet
<>();
2007 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
2008 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
2009 if (actions
!= null) {
2010 queuedActions
.addAll(actions
);
2013 for (var action
: queuedActions
) {
2015 action
.execute(this);
2016 } catch (Throwable e
) {
2017 logger
.warn("Message action failed.", e
);
2022 private List
<HandleAction
> retryFailedReceivedMessage(
2023 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
2025 var envelope
= cachedMessage
.loadEnvelope();
2026 if (envelope
== null) {
2029 SignalServiceContent content
= null;
2030 List
<HandleAction
> actions
= null;
2031 if (!envelope
.isReceipt()) {
2033 content
= decryptMessage(envelope
);
2034 } catch (ProtocolUntrustedIdentityException e
) {
2035 if (!envelope
.hasSource()) {
2036 final var identifier
= e
.getSender();
2037 final var recipientId
= resolveRecipient(identifier
);
2039 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
2040 } catch (IOException ioException
) {
2041 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
2045 } catch (Exception er
) {
2046 // All other errors are not recoverable, so delete the cached message
2047 cachedMessage
.delete();
2050 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
2052 handler
.handleMessage(envelope
, content
, null);
2053 cachedMessage
.delete();
2057 public void receiveMessages(
2060 boolean returnOnTimeout
,
2061 boolean ignoreAttachments
,
2062 ReceiveMessageHandler handler
2063 ) throws IOException
{
2064 retryFailedReceivedMessages(handler
, ignoreAttachments
);
2066 Set
<HandleAction
> queuedActions
= null;
2068 final var messagePipe
= getOrCreateMessagePipe();
2070 var hasCaughtUpWithOldMessages
= false;
2073 SignalServiceEnvelope envelope
;
2074 SignalServiceContent content
= null;
2075 Exception exception
= null;
2076 final CachedMessage
[] cachedMessage
= {null};
2077 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
2078 logger
.debug("Checking for new message from server");
2080 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
2081 final var recipientId
= envelope1
.hasSource()
2082 ?
resolveRecipient(envelope1
.getSourceIdentifier())
2084 // store message on disk, before acknowledging receipt to the server
2085 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
2087 logger
.debug("New message received from server");
2088 if (result
.isPresent()) {
2089 envelope
= result
.get();
2091 // Received indicator that server queue is empty
2092 hasCaughtUpWithOldMessages
= true;
2094 if (queuedActions
!= null) {
2095 for (var action
: queuedActions
) {
2097 action
.execute(this);
2098 } catch (Throwable e
) {
2099 logger
.warn("Message action failed.", e
);
2102 queuedActions
.clear();
2103 queuedActions
= null;
2106 // Continue to wait another timeout for new messages
2109 } catch (TimeoutException e
) {
2110 if (returnOnTimeout
) return;
2114 if (envelope
.hasSource()) {
2115 // Store uuid if we don't have it already
2116 // address/uuid in envelope is sent by server
2117 resolveRecipientTrusted(envelope
.getSourceAddress());
2119 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
2120 if (!envelope
.isReceipt()) {
2122 content
= decryptMessage(envelope
);
2123 } catch (Exception e
) {
2126 if (!envelope
.hasSource() && content
!= null) {
2127 // Store uuid if we don't have it already
2128 // address/uuid is validated by unidentified sender certificate
2129 resolveRecipientTrusted(content
.getSender());
2131 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
2132 if (exception
instanceof ProtocolInvalidMessageException
) {
2133 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
2134 logger
.debug("Received invalid message, queuing renew session action.");
2135 actions
.add(new RenewSessionAction(sender
));
2137 if (hasCaughtUpWithOldMessages
) {
2138 for (var action
: actions
) {
2140 action
.execute(this);
2141 } catch (Throwable e
) {
2142 logger
.warn("Message action failed.", e
);
2146 if (queuedActions
== null) {
2147 queuedActions
= new HashSet
<>();
2149 queuedActions
.addAll(actions
);
2152 if (isMessageBlocked(envelope
, content
)) {
2153 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
2154 } else if (notAGroupMember
) {
2155 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
2157 handler
.handleMessage(envelope
, content
, exception
);
2159 if (cachedMessage
[0] != null) {
2160 if (exception
instanceof ProtocolUntrustedIdentityException
) {
2161 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
2162 final var recipientId
= resolveRecipient(identifier
);
2163 queuedActions
.add(new RetrieveProfileAction(recipientId
));
2164 if (!envelope
.hasSource()) {
2166 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
2167 } catch (IOException ioException
) {
2168 logger
.warn("Failed to move cached message to recipient folder: {}",
2169 ioException
.getMessage());
2173 cachedMessage
[0].delete();
2179 private boolean isMessageBlocked(
2180 SignalServiceEnvelope envelope
, SignalServiceContent content
2182 SignalServiceAddress source
;
2183 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2184 source
= envelope
.getSourceAddress();
2185 } else if (content
!= null) {
2186 source
= content
.getSender();
2190 final var recipientId
= resolveRecipient(source
);
2191 if (isContactBlocked(recipientId
)) {
2195 if (content
!= null && content
.getDataMessage().isPresent()) {
2196 var message
= content
.getDataMessage().get();
2197 if (message
.getGroupContext().isPresent()) {
2198 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2199 var group
= getGroup(groupId
);
2200 if (group
!= null && group
.isBlocked()) {
2208 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
2209 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
2210 return isContactBlocked(recipientId
);
2213 private boolean isContactBlocked(final RecipientId recipientId
) {
2214 var sourceContact
= account
.getContactStore().getContact(recipientId
);
2215 return sourceContact
!= null && sourceContact
.isBlocked();
2218 private boolean isNotAGroupMember(
2219 SignalServiceEnvelope envelope
, SignalServiceContent content
2221 SignalServiceAddress source
;
2222 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2223 source
= envelope
.getSourceAddress();
2224 } else if (content
!= null) {
2225 source
= content
.getSender();
2230 if (content
!= null && content
.getDataMessage().isPresent()) {
2231 var message
= content
.getDataMessage().get();
2232 if (message
.getGroupContext().isPresent()) {
2233 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
2234 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
2235 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
2239 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2240 var group
= getGroup(groupId
);
2241 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
2249 private List
<HandleAction
> handleMessage(
2250 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
2252 var actions
= new ArrayList
<HandleAction
>();
2253 if (content
!= null) {
2254 final SignalServiceAddress sender
;
2255 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2256 sender
= envelope
.getSourceAddress();
2258 sender
= content
.getSender();
2261 if (content
.getDataMessage().isPresent()) {
2262 var message
= content
.getDataMessage().get();
2264 if (content
.isNeedsReceipt()) {
2265 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
2268 actions
.addAll(handleSignalServiceDataMessage(message
,
2271 account
.getSelfAddress(),
2272 ignoreAttachments
));
2274 if (content
.getSyncMessage().isPresent()) {
2275 account
.setMultiDevice(true);
2276 var syncMessage
= content
.getSyncMessage().get();
2277 if (syncMessage
.getSent().isPresent()) {
2278 var message
= syncMessage
.getSent().get();
2279 final var destination
= message
.getDestination().orNull();
2280 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
2284 ignoreAttachments
));
2286 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
2287 var rm
= syncMessage
.getRequest().get();
2288 if (rm
.isContactsRequest()) {
2289 actions
.add(SendSyncContactsAction
.create());
2291 if (rm
.isGroupsRequest()) {
2292 actions
.add(SendSyncGroupsAction
.create());
2294 if (rm
.isBlockedListRequest()) {
2295 actions
.add(SendSyncBlockedListAction
.create());
2297 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2299 if (syncMessage
.getGroups().isPresent()) {
2300 File tmpFile
= null;
2302 tmpFile
= IOUtils
.createTempFile();
2303 final var groupsMessage
= syncMessage
.getGroups().get();
2304 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2305 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2310 } catch (IOException e
) {
2311 logger
.warn("Sync groups contained invalid group, ignoring: {}", e
.getMessage());
2317 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2318 if (syncGroup
!= null) {
2319 if (g
.getName().isPresent()) {
2320 syncGroup
.name
= g
.getName().get();
2322 syncGroup
.addMembers(g
.getMembers()
2324 .map(this::resolveRecipient
)
2325 .collect(Collectors
.toSet()));
2326 if (!g
.isActive()) {
2327 syncGroup
.removeMember(account
.getSelfRecipientId());
2329 // Add ourself to the member set as it's marked as active
2330 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2332 syncGroup
.blocked
= g
.isBlocked();
2333 if (g
.getColor().isPresent()) {
2334 syncGroup
.color
= g
.getColor().get();
2337 if (g
.getAvatar().isPresent()) {
2338 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2340 syncGroup
.archived
= g
.isArchived();
2341 account
.getGroupStore().updateGroup(syncGroup
);
2345 } catch (Exception e
) {
2346 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2350 if (tmpFile
!= null) {
2352 Files
.delete(tmpFile
.toPath());
2353 } catch (IOException e
) {
2354 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2361 if (syncMessage
.getBlockedList().isPresent()) {
2362 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2363 for (var address
: blockedListMessage
.getAddresses()) {
2364 setContactBlocked(resolveRecipient(address
), true);
2366 for (var groupId
: blockedListMessage
.getGroupIds()
2368 .map(GroupId
::unknownVersion
)
2369 .collect(Collectors
.toSet())) {
2371 setGroupBlocked(groupId
, true);
2372 } catch (GroupNotFoundException e
) {
2373 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2374 groupId
.toBase64());
2378 if (syncMessage
.getContacts().isPresent()) {
2379 File tmpFile
= null;
2381 tmpFile
= IOUtils
.createTempFile();
2382 final var contactsMessage
= syncMessage
.getContacts().get();
2383 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2384 .asPointer(), tmpFile
)) {
2385 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2390 } catch (IOException e
) {
2391 logger
.warn("Sync contacts contained invalid contact, ignoring: {}",
2398 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2399 account
.setProfileKey(c
.getProfileKey().get());
2401 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2402 var contact
= account
.getContactStore().getContact(recipientId
);
2403 final var builder
= contact
== null
2404 ? Contact
.newBuilder()
2405 : Contact
.newBuilder(contact
);
2406 if (c
.getName().isPresent()) {
2407 builder
.withName(c
.getName().get());
2409 if (c
.getColor().isPresent()) {
2410 builder
.withColor(c
.getColor().get());
2412 if (c
.getProfileKey().isPresent()) {
2413 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2415 if (c
.getVerified().isPresent()) {
2416 final var verifiedMessage
= c
.getVerified().get();
2417 account
.getIdentityKeyStore()
2418 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2419 verifiedMessage
.getIdentityKey(),
2420 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2422 if (c
.getExpirationTimer().isPresent()) {
2423 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2425 builder
.withBlocked(c
.isBlocked());
2426 builder
.withArchived(c
.isArchived());
2427 account
.getContactStore().storeContact(recipientId
, builder
.build());
2429 if (c
.getAvatar().isPresent()) {
2430 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2434 } catch (Exception e
) {
2435 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2439 if (tmpFile
!= null) {
2441 Files
.delete(tmpFile
.toPath());
2442 } catch (IOException e
) {
2443 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2450 if (syncMessage
.getVerified().isPresent()) {
2451 final var verifiedMessage
= syncMessage
.getVerified().get();
2452 account
.getIdentityKeyStore()
2453 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2454 verifiedMessage
.getIdentityKey(),
2455 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2457 if (syncMessage
.getStickerPackOperations().isPresent()) {
2458 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2459 for (var m
: stickerPackOperationMessages
) {
2460 if (!m
.getPackId().isPresent()) {
2463 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2464 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2465 if (sticker
== null) {
2466 if (!m
.getPackKey().isPresent()) {
2469 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2471 sticker
.setInstalled(!m
.getType().isPresent()
2472 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2473 account
.getStickerStore().updateSticker(sticker
);
2476 if (syncMessage
.getFetchType().isPresent()) {
2477 switch (syncMessage
.getFetchType().get()) {
2479 getRecipientProfile(account
.getSelfRecipientId(), true);
2480 case STORAGE_MANIFEST
:
2484 if (syncMessage
.getKeys().isPresent()) {
2485 final var keysMessage
= syncMessage
.getKeys().get();
2486 if (keysMessage
.getStorageService().isPresent()) {
2487 final var storageKey
= keysMessage
.getStorageService().get();
2488 account
.setStorageKey(storageKey
);
2491 if (syncMessage
.getConfiguration().isPresent()) {
2499 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2501 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2502 } catch (IOException e
) {
2503 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2507 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2509 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2510 } catch (IOException e
) {
2511 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2515 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2517 avatarStore
.storeGroupAvatar(groupId
,
2518 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2519 } catch (IOException e
) {
2520 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2524 private void downloadProfileAvatar(
2525 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2528 avatarStore
.storeProfileAvatar(address
,
2529 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2530 } catch (Throwable e
) {
2531 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2535 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2536 return attachmentStore
.getAttachmentFile(attachmentId
);
2539 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2540 if (!attachment
.isPointer()) {
2541 logger
.warn("Invalid state, can't store an attachment stream.");
2544 var pointer
= attachment
.asPointer();
2545 if (pointer
.getPreview().isPresent()) {
2546 final var preview
= pointer
.getPreview().get();
2548 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2549 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2550 } catch (IOException e
) {
2551 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2556 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2557 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2558 } catch (IOException e
) {
2559 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2563 private void retrieveGroupV2Avatar(
2564 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2565 ) throws IOException
{
2566 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2568 var tmpFile
= IOUtils
.createTempFile();
2569 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2571 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2572 var encryptedData
= IOUtils
.readFully(input
);
2574 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2575 outputStream
.write(decryptedData
);
2578 Files
.delete(tmpFile
.toPath());
2579 } catch (IOException e
) {
2580 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2587 private void retrieveProfileAvatar(
2588 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2589 ) throws IOException
{
2590 var tmpFile
= IOUtils
.createTempFile();
2591 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2594 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2595 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2596 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2599 Files
.delete(tmpFile
.toPath());
2600 } catch (IOException e
) {
2601 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2608 private void retrieveAttachment(
2609 final SignalServiceAttachment attachment
, final OutputStream outputStream
2610 ) throws IOException
{
2611 if (attachment
.isPointer()) {
2612 var pointer
= attachment
.asPointer();
2613 retrieveAttachmentPointer(pointer
, outputStream
);
2615 var stream
= attachment
.asStream();
2616 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2620 private void retrieveAttachmentPointer(
2621 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2622 ) throws IOException
{
2623 var tmpFile
= IOUtils
.createTempFile();
2624 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2625 IOUtils
.copyStream(input
, outputStream
);
2626 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2627 throw new IOException(e
);
2630 Files
.delete(tmpFile
.toPath());
2631 } catch (IOException e
) {
2632 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2639 private InputStream
retrieveAttachmentAsStream(
2640 SignalServiceAttachmentPointer pointer
, File tmpFile
2641 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2642 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2645 void sendGroups() throws IOException
, UntrustedIdentityException
{
2646 var groupsFile
= IOUtils
.createTempFile();
2649 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2650 var out
= new DeviceGroupsOutputStream(fos
);
2651 for (var record : getGroups()) {
2652 if (record instanceof GroupInfoV1
) {
2653 var groupInfo
= (GroupInfoV1
) record;
2654 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2655 Optional
.fromNullable(groupInfo
.name
),
2656 groupInfo
.getMembers()
2658 .map(this::resolveSignalServiceAddress
)
2659 .collect(Collectors
.toList()),
2660 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2661 groupInfo
.isMember(account
.getSelfRecipientId()),
2662 Optional
.of(groupInfo
.messageExpirationTime
),
2663 Optional
.fromNullable(groupInfo
.color
),
2666 groupInfo
.archived
));
2671 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2672 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2673 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2674 .withStream(groupsFileStream
)
2675 .withContentType("application/octet-stream")
2676 .withLength(groupsFile
.length())
2679 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2684 Files
.delete(groupsFile
.toPath());
2685 } catch (IOException e
) {
2686 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2691 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2692 var contactsFile
= IOUtils
.createTempFile();
2695 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2696 var out
= new DeviceContactsOutputStream(fos
);
2697 for (var contactPair
: account
.getContactStore().getContacts()) {
2698 final var recipientId
= contactPair
.first();
2699 final var contact
= contactPair
.second();
2700 final var address
= resolveSignalServiceAddress(recipientId
);
2702 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2703 VerifiedMessage verifiedMessage
= null;
2704 if (currentIdentity
!= null) {
2705 verifiedMessage
= new VerifiedMessage(address
,
2706 currentIdentity
.getIdentityKey(),
2707 currentIdentity
.getTrustLevel().toVerifiedState(),
2708 currentIdentity
.getDateAdded().getTime());
2711 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2712 out
.write(new DeviceContact(address
,
2713 Optional
.fromNullable(contact
.getName()),
2714 createContactAvatarAttachment(address
),
2715 Optional
.fromNullable(contact
.getColor()),
2716 Optional
.fromNullable(verifiedMessage
),
2717 Optional
.fromNullable(profileKey
),
2718 contact
.isBlocked(),
2719 Optional
.of(contact
.getMessageExpirationTime()),
2721 contact
.isArchived()));
2724 if (account
.getProfileKey() != null) {
2725 // Send our own profile key as well
2726 out
.write(new DeviceContact(account
.getSelfAddress(),
2731 Optional
.of(account
.getProfileKey()),
2739 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2740 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2741 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2742 .withStream(contactsFileStream
)
2743 .withContentType("application/octet-stream")
2744 .withLength(contactsFile
.length())
2747 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2752 Files
.delete(contactsFile
.toPath());
2753 } catch (IOException e
) {
2754 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2759 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2760 var addresses
= new ArrayList
<SignalServiceAddress
>();
2761 for (var record : account
.getContactStore().getContacts()) {
2762 if (record.second().isBlocked()) {
2763 addresses
.add(resolveSignalServiceAddress(record.first()));
2766 var groupIds
= new ArrayList
<byte[]>();
2767 for (var record : getGroups()) {
2768 if (record.isBlocked()) {
2769 groupIds
.add(record.getGroupId().serialize());
2772 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2775 private void sendVerifiedMessage(
2776 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2777 ) throws IOException
, UntrustedIdentityException
{
2778 var verifiedMessage
= new VerifiedMessage(destination
,
2780 trustLevel
.toVerifiedState(),
2781 System
.currentTimeMillis());
2782 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2785 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2786 return account
.getContactStore().getContacts();
2789 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2790 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2791 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2792 if (recipient
== null) {
2796 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2797 return recipient
.getContact().getName();
2800 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2801 return recipient
.getProfile().getDisplayName();
2807 public GroupInfo
getGroup(GroupId groupId
) {
2808 return getGroup(groupId
, false);
2811 public GroupInfo
getGroup(GroupId groupId
, boolean forceUpdate
) {
2812 final var group
= account
.getGroupStore().getGroup(groupId
);
2813 if (group
instanceof GroupInfoV2
&& (forceUpdate
|| ((GroupInfoV2
) group
).getGroup() == null)) {
2814 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2815 ((GroupInfoV2
) group
).setGroup(groupV2Helper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2816 account
.getGroupStore().updateGroup(group
);
2821 public List
<IdentityInfo
> getIdentities() {
2822 return account
.getIdentityKeyStore().getIdentities();
2825 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2826 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2827 return identity
== null ? List
.of() : List
.of(identity
);
2831 * Trust this the identity with this fingerprint
2833 * @param name username of the identity
2834 * @param fingerprint Fingerprint
2836 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2837 var recipientId
= canonicalizeAndResolveRecipient(name
);
2838 return trustIdentity(recipientId
,
2839 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2840 TrustLevel
.TRUSTED_VERIFIED
);
2844 * Trust this the identity with this safety number
2846 * @param name username of the identity
2847 * @param safetyNumber Safety number
2849 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2850 var recipientId
= canonicalizeAndResolveRecipient(name
);
2851 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2852 return trustIdentity(recipientId
,
2853 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2854 TrustLevel
.TRUSTED_VERIFIED
);
2858 * Trust all keys of this identity without verification
2860 * @param name username of the identity
2862 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2863 var recipientId
= canonicalizeAndResolveRecipient(name
);
2864 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2867 private boolean trustIdentity(
2868 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2870 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2871 if (identity
== null) {
2875 if (!verifier
.apply(identity
.getIdentityKey())) {
2879 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2881 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2882 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2883 } catch (IOException
| UntrustedIdentityException e
) {
2884 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2890 public String
computeSafetyNumber(
2891 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2893 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2894 account
.getSelfAddress(),
2895 getIdentityKeyPair().getPublicKey(),
2901 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2902 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2904 return resolveSignalServiceAddress(address
);
2908 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2909 if (address
.matches(account
.getSelfAddress())) {
2910 return account
.getSelfAddress();
2913 return account
.getRecipientStore().resolveServiceAddress(address
);
2916 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2917 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2920 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2921 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2923 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2925 return resolveRecipient(canonicalizedNumber
);
2928 private RecipientId
resolveRecipient(final String identifier
) {
2929 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2931 return resolveRecipient(address
);
2934 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2935 return account
.getRecipientStore().resolveRecipient(address
);
2938 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2939 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2943 public void close() throws IOException
{
2947 void close(boolean closeAccount
) throws IOException
{
2948 executor
.shutdown();
2950 if (messagePipe
!= null) {
2951 messagePipe
.shutdown();
2955 if (unidentifiedMessagePipe
!= null) {
2956 unidentifiedMessagePipe
.shutdown();
2957 unidentifiedMessagePipe
= null;
2960 if (closeAccount
&& account
!= null) {
2966 public interface ReceiveMessageHandler
{
2968 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);