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
.groups
.GroupId
;
20 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
21 import org
.asamk
.signal
.manager
.groups
.GroupIdV2
;
22 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
23 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
24 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
25 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
26 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
27 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
28 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
29 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
30 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
31 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactInfo
;
32 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
33 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
34 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
35 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
36 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfile
;
37 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfileEntry
;
38 import org
.asamk
.signal
.manager
.storage
.protocol
.IdentityInfo
;
39 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
40 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
41 import org
.asamk
.signal
.manager
.util
.IOUtils
;
42 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
43 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
44 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
45 import org
.asamk
.signal
.manager
.util
.Utils
;
46 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
47 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
48 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
49 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
50 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
51 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
52 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
53 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
54 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
56 import org
.signal
.libsignal
.metadata
.SelfSendException
;
57 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
58 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
59 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
60 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroupJoinInfo
;
61 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedMember
;
62 import org
.signal
.zkgroup
.InvalidInputException
;
63 import org
.signal
.zkgroup
.VerificationFailedException
;
64 import org
.signal
.zkgroup
.auth
.AuthCredentialResponse
;
65 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
66 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
67 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
68 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
69 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
70 import org
.slf4j
.Logger
;
71 import org
.slf4j
.LoggerFactory
;
72 import org
.whispersystems
.libsignal
.IdentityKey
;
73 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
74 import org
.whispersystems
.libsignal
.InvalidKeyException
;
75 import org
.whispersystems
.libsignal
.InvalidMessageException
;
76 import org
.whispersystems
.libsignal
.InvalidVersionException
;
77 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
78 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
79 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
80 import org
.whispersystems
.libsignal
.util
.Pair
;
81 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
82 import org
.whispersystems
.signalservice
.api
.KeyBackupService
;
83 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
84 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
85 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
86 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
87 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
88 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
89 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
90 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
91 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
92 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
93 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
94 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
95 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
96 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
106 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
107 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceStickerManifestUpload
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.KeysMessage
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
121 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
122 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
123 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
124 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
125 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
126 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
127 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
128 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
129 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
130 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
131 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
132 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
133 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
134 import org
.whispersystems
.signalservice
.internal
.configuration
.SignalServiceConfiguration
;
135 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
136 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
137 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
138 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
139 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
140 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
141 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
142 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
144 import java
.io
.Closeable
;
146 import java
.io
.FileInputStream
;
147 import java
.io
.FileOutputStream
;
148 import java
.io
.IOException
;
149 import java
.io
.InputStream
;
150 import java
.io
.OutputStream
;
152 import java
.net
.URISyntaxException
;
153 import java
.net
.URLEncoder
;
154 import java
.nio
.charset
.StandardCharsets
;
155 import java
.nio
.file
.Files
;
156 import java
.security
.SignatureException
;
157 import java
.util
.ArrayList
;
158 import java
.util
.Arrays
;
159 import java
.util
.Collection
;
160 import java
.util
.Date
;
161 import java
.util
.HashMap
;
162 import java
.util
.HashSet
;
163 import java
.util
.List
;
164 import java
.util
.Map
;
165 import java
.util
.Set
;
166 import java
.util
.UUID
;
167 import java
.util
.concurrent
.ExecutorService
;
168 import java
.util
.concurrent
.TimeUnit
;
169 import java
.util
.concurrent
.TimeoutException
;
170 import java
.util
.stream
.Collectors
;
172 import static org
.asamk
.signal
.manager
.ServiceConfig
.CDS_MRENCLAVE
;
173 import static org
.asamk
.signal
.manager
.ServiceConfig
.capabilities
;
174 import static org
.asamk
.signal
.manager
.ServiceConfig
.getIasKeyStore
;
176 public class Manager
implements Closeable
{
178 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
180 private final CertificateValidator certificateValidator
= new CertificateValidator(ServiceConfig
.getUnidentifiedSenderTrustRoot());
182 private final SignalServiceConfiguration serviceConfiguration
;
183 private final String userAgent
;
185 private SignalAccount account
;
186 private final SignalServiceAccountManager accountManager
;
187 private final GroupsV2Api groupsV2Api
;
188 private final GroupsV2Operations groupsV2Operations
;
189 private final SignalServiceMessageReceiver messageReceiver
;
190 private final ClientZkProfileOperations clientZkProfileOperations
;
192 private SignalServiceMessagePipe messagePipe
= null;
193 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
195 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
196 private final ProfileHelper profileHelper
;
197 private final GroupHelper groupHelper
;
198 private final PinHelper pinHelper
;
199 private final AvatarStore avatarStore
;
200 private final AttachmentStore attachmentStore
;
203 SignalAccount account
,
204 PathConfig pathConfig
,
205 SignalServiceConfiguration serviceConfiguration
,
208 this.account
= account
;
209 this.serviceConfiguration
= serviceConfiguration
;
210 this.userAgent
= userAgent
;
211 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
212 serviceConfiguration
)) : null;
213 final SleepTimer timer
= new UptimeSleepTimer();
214 this.accountManager
= new SignalServiceAccountManager(serviceConfiguration
,
215 new DynamicCredentialsProvider(account
.getUuid(),
216 account
.getUsername(),
217 account
.getPassword(),
218 account
.getSignalingKey(),
219 account
.getDeviceId()),
223 this.groupsV2Api
= accountManager
.getGroupsV2Api();
224 final KeyBackupService keyBackupService
= ServiceConfig
.createKeyBackupService(accountManager
);
225 this.pinHelper
= new PinHelper(keyBackupService
);
226 this.clientZkProfileOperations
= capabilities
.isGv2() ? ClientZkOperations
.create(serviceConfiguration
)
227 .getProfileOperations() : null;
228 this.messageReceiver
= new SignalServiceMessageReceiver(serviceConfiguration
,
230 account
.getUsername(),
231 account
.getPassword(),
232 account
.getDeviceId(),
233 account
.getSignalingKey(),
237 clientZkProfileOperations
);
239 this.account
.setResolver(this::resolveSignalServiceAddress
);
241 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
242 account
.getProfileStore()::getProfileKey
,
243 this::getRecipientProfile
,
244 this::getSenderCertificate
);
245 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
246 unidentifiedAccessHelper
::getAccessFor
,
247 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
248 () -> messageReceiver
);
249 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
250 this::getRecipientProfile
,
251 account
::getSelfAddress
,
254 this::getGroupAuthForToday
);
255 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
256 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
259 public String
getUsername() {
260 return account
.getUsername();
263 public SignalServiceAddress
getSelfAddress() {
264 return account
.getSelfAddress();
267 private IdentityKeyPair
getIdentityKeyPair() {
268 return account
.getSignalProtocolStore().getIdentityKeyPair();
271 public int getDeviceId() {
272 return account
.getDeviceId();
275 public static Manager
init(
276 String username
, File settingsPath
, SignalServiceConfiguration serviceConfiguration
, String userAgent
277 ) throws IOException
, NotRegisteredException
{
278 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
280 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
281 throw new NotRegisteredException();
284 SignalAccount account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
286 if (!account
.isRegistered()) {
287 throw new NotRegisteredException();
290 return new Manager(account
, pathConfig
, serviceConfiguration
, userAgent
);
293 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
294 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
295 final File dataPath
= pathConfig
.getDataPath();
296 final File
[] files
= dataPath
.listFiles();
302 return Arrays
.stream(files
)
303 .filter(File
::isFile
)
305 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
306 .collect(Collectors
.toList());
309 public void checkAccountState() throws IOException
{
310 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
314 if (account
.getUuid() == null) {
315 account
.setUuid(accountManager
.getOwnUuid());
318 updateAccountAttributes();
322 * This is used for checking a set of phone numbers for registration on Signal
324 * @param numbers The set of phone number in question
325 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
326 * @throws IOException if its unable to get the contacts to check if they're registered
328 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
329 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
330 Map
<String
, UUID
> contactDetails
= getRegisteredUsers(numbers
);
332 Set
<String
> registeredUsers
= contactDetails
.keySet();
334 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
337 public void updateAccountAttributes() throws IOException
{
338 accountManager
.setAccountAttributes(account
.getSignalingKey(),
339 account
.getSignalProtocolStore().getLocalRegistrationId(),
341 // set legacy pin only if no KBS master key is set
342 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
343 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
344 account
.getSelfUnidentifiedAccessKey(),
345 account
.isUnrestrictedUnidentifiedAccess(),
347 account
.isDiscoverableByPhoneNumber());
351 * @param avatar if avatar is null the image from the local avatar store is used (if present),
352 * if it's Optional.absent(), the avatar will be removed
354 public void setProfile(String name
, Optional
<File
> avatar
) throws IOException
{
355 try (final StreamDetails streamDetails
= avatar
== null
356 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
357 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
358 accountManager
.setVersionedProfile(account
.getUuid(), account
.getProfileKey(), name
, streamDetails
);
361 if (avatar
!= null) {
362 if (avatar
.isPresent()) {
363 avatarStore
.storeProfileAvatar(getSelfAddress(),
364 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
366 avatarStore
.deleteProfileAvatar(getSelfAddress());
371 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
372 } catch (UntrustedIdentityException ignored
) {
376 public void unregister() throws IOException
{
377 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
378 // If this is the master device, other users can't send messages to this number anymore.
379 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
380 accountManager
.setGcmId(Optional
.absent());
382 account
.setRegistered(false);
386 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
387 List
<DeviceInfo
> devices
= accountManager
.getDevices();
388 account
.setMultiDevice(devices
.size() > 1);
393 public void removeLinkedDevices(int deviceId
) throws IOException
{
394 accountManager
.removeDevice(deviceId
);
395 List
<DeviceInfo
> devices
= accountManager
.getDevices();
396 account
.setMultiDevice(devices
.size() > 1);
400 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
401 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
403 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
406 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
407 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
408 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
410 accountManager
.addDevice(deviceIdentifier
,
413 Optional
.of(account
.getProfileKey().serialize()),
415 account
.setMultiDevice(true);
419 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
420 if (!account
.isMasterDevice()) {
421 throw new RuntimeException("Only master device can set a PIN");
423 if (pin
.isPresent()) {
424 final MasterKey masterKey
= account
.getPinMasterKey() != null
425 ? account
.getPinMasterKey()
426 : KeyUtils
.createMasterKey();
428 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
430 account
.setRegistrationLockPin(pin
.get());
431 account
.setPinMasterKey(masterKey
);
433 // Remove legacy registration lock
434 accountManager
.removeRegistrationLockV1();
437 pinHelper
.removeRegistrationLockPin();
439 account
.setRegistrationLockPin(null);
440 account
.setPinMasterKey(null);
445 void refreshPreKeys() throws IOException
{
446 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
447 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
448 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
450 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
453 private List
<PreKeyRecord
> generatePreKeys() {
454 final int offset
= account
.getPreKeyIdOffset();
456 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
457 account
.addPreKeys(records
);
463 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
464 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
466 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
467 account
.addSignedPreKey(record);
473 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
474 if (messagePipe
== null) {
475 messagePipe
= messageReceiver
.createMessagePipe();
480 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
481 if (unidentifiedMessagePipe
== null) {
482 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
484 return unidentifiedMessagePipe
;
487 private SignalServiceMessageSender
createMessageSender() {
488 final ExecutorService executor
= null;
489 return new SignalServiceMessageSender(serviceConfiguration
,
491 account
.getUsername(),
492 account
.getPassword(),
493 account
.getDeviceId(),
494 account
.getSignalProtocolStore(),
496 account
.isMultiDevice(),
497 Optional
.fromNullable(messagePipe
),
498 Optional
.fromNullable(unidentifiedMessagePipe
),
500 clientZkProfileOperations
,
502 ServiceConfig
.MAX_ENVELOPE_SIZE
);
505 private SignalProfile
getRecipientProfile(
506 SignalServiceAddress address
508 return getRecipientProfile(address
, false);
511 private SignalProfile
getRecipientProfile(
512 SignalServiceAddress address
, boolean force
514 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
515 if (profileEntry
== null) {
518 long now
= new Date().getTime();
519 // Profiles are cached for 24h before retrieving them again
520 if (!profileEntry
.isRequestPending() && (
522 || profileEntry
.getProfile() == null
523 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
525 profileEntry
.setRequestPending(true);
526 final SignalServiceProfile encryptedProfile
;
528 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
530 } catch (IOException e
) {
531 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
534 profileEntry
.setRequestPending(false);
537 final ProfileKey profileKey
= profileEntry
.getProfileKey();
538 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
539 account
.getProfileStore()
540 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
543 return profileEntry
.getProfile();
546 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
547 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
548 if (profileEntry
== null) {
551 if (profileEntry
.getProfileKeyCredential() == null) {
552 ProfileAndCredential profileAndCredential
;
554 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
555 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
556 } catch (IOException e
) {
557 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
561 long now
= new Date().getTime();
562 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
563 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
564 profileEntry
.getProfileKey(),
565 profileAndCredential
.getProfile());
566 account
.getProfileStore()
567 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
568 return profileKeyCredential
;
570 return profileEntry
.getProfileKeyCredential();
573 private SignalProfile
decryptProfileAndDownloadAvatar(
574 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
576 if (encryptedProfile
.getAvatar() != null) {
577 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
580 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
583 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
584 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
585 if (streamDetails
== null) {
586 return Optional
.absent();
589 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
592 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
593 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
594 if (streamDetails
== null) {
595 return Optional
.absent();
598 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
601 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
602 GroupInfo g
= getGroup(groupId
);
604 throw new GroupNotFoundException(groupId
);
606 if (!g
.isMember(account
.getSelfAddress())) {
607 throw new NotAGroupMemberException(groupId
, g
.getTitle());
612 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
613 GroupInfo g
= getGroup(groupId
);
615 throw new GroupNotFoundException(groupId
);
617 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
618 throw new NotAGroupMemberException(groupId
, g
.getTitle());
623 public List
<GroupInfo
> getGroups() {
624 return account
.getGroupStore().getGroups();
627 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
628 String messageText
, List
<String
> attachments
, GroupId groupId
629 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
630 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
631 .withBody(messageText
);
632 if (attachments
!= null) {
633 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
636 return sendGroupMessage(messageBuilder
, groupId
);
639 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
640 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
641 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
642 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
644 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
645 targetSentTimestamp
);
646 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
647 .withReaction(reaction
);
649 return sendGroupMessage(messageBuilder
, groupId
);
652 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
653 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
654 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
655 final GroupInfo g
= getGroupForSending(groupId
);
657 GroupUtils
.setGroupContext(messageBuilder
, g
);
658 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
660 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
663 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
664 SignalServiceDataMessage
.Builder messageBuilder
;
666 final GroupInfo g
= getGroupForUpdating(groupId
);
667 if (g
instanceof GroupInfoV1
) {
668 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
669 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
670 .withId(groupId
.serialize())
672 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
673 groupInfoV1
.removeMember(account
.getSelfAddress());
674 account
.getGroupStore().updateGroup(groupInfoV1
);
676 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
677 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
678 groupInfoV2
.setGroup(groupGroupChangePair
.first());
679 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
680 account
.getGroupStore().updateGroup(groupInfoV2
);
683 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
686 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
687 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
688 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
689 return sendUpdateGroupMessage(groupId
,
691 members
== null ?
null : getSignalServiceAddresses(members
),
695 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
696 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
697 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
699 SignalServiceDataMessage
.Builder messageBuilder
;
700 if (groupId
== null) {
702 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
703 members
== null ? List
.of() : members
,
706 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
707 gv1
.addMembers(List
.of(account
.getSelfAddress()));
708 updateGroupV1(gv1
, name
, members
, avatarFile
);
709 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
712 if (avatarFile
!= null) {
713 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
714 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
716 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
720 GroupInfo group
= getGroupForUpdating(groupId
);
721 if (group
instanceof GroupInfoV2
) {
722 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
724 Pair
<Long
, List
<SendMessageResult
>> result
= null;
725 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
726 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
727 result
= sendUpdateGroupMessage(groupInfoV2
,
728 groupGroupChangePair
.first(),
729 groupGroupChangePair
.second());
732 if (members
!= null) {
733 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
734 newMembers
.removeAll(group
.getMembers()
736 .map(this::resolveSignalServiceAddress
)
737 .collect(Collectors
.toSet()));
738 if (newMembers
.size() > 0) {
739 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
741 result
= sendUpdateGroupMessage(groupInfoV2
,
742 groupGroupChangePair
.first(),
743 groupGroupChangePair
.second());
746 if (result
== null || name
!= null || avatarFile
!= null) {
747 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
750 if (avatarFile
!= null) {
751 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
752 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
754 result
= sendUpdateGroupMessage(groupInfoV2
,
755 groupGroupChangePair
.first(),
756 groupGroupChangePair
.second());
759 return new Pair
<>(group
.getGroupId(), result
.second());
761 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
762 updateGroupV1(gv1
, name
, members
, avatarFile
);
763 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
768 account
.getGroupStore().updateGroup(g
);
770 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
771 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
772 return new Pair
<>(g
.getGroupId(), result
.second());
775 private void updateGroupV1(
778 final Collection
<SignalServiceAddress
> members
,
779 final File avatarFile
780 ) throws IOException
{
785 if (members
!= null) {
786 final Set
<String
> newE164Members
= new HashSet
<>();
787 for (SignalServiceAddress member
: members
) {
788 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
791 newE164Members
.add(member
.getNumber().get());
794 final Map
<String
, UUID
> registeredUsers
= getRegisteredUsers(newE164Members
);
795 if (registeredUsers
.size() != newE164Members
.size()) {
796 // Some of the new members are not registered on Signal
797 newE164Members
.removeAll(registeredUsers
.keySet());
798 throw new IOException("Failed to add members "
799 + String
.join(", ", newE164Members
)
800 + " to group: Not registered on Signal");
803 g
.addMembers(members
);
806 if (avatarFile
!= null) {
807 avatarStore
.storeGroupAvatar(g
.getGroupId(),
808 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
812 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
813 GroupInviteLinkUrl inviteLinkUrl
814 ) throws IOException
, GroupLinkNotActiveException
{
815 return sendJoinGroupMessage(inviteLinkUrl
);
818 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
819 GroupInviteLinkUrl inviteLinkUrl
820 ) throws IOException
, GroupLinkNotActiveException
{
821 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
822 inviteLinkUrl
.getPassword());
823 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
824 inviteLinkUrl
.getPassword(),
826 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
827 groupJoinInfo
.getRevision() + 1,
828 groupChange
.toByteArray());
830 if (group
.getGroup() == null) {
831 // Only requested member, can't send update to group members
832 return new Pair
<>(group
.getGroupId(), List
.of());
835 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
837 return new Pair
<>(group
.getGroupId(), result
.second());
840 private static int currentTimeDays() {
841 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
844 private GroupsV2AuthorizationString
getGroupAuthForToday(
845 final GroupSecretParams groupSecretParams
846 ) throws IOException
{
847 final int today
= currentTimeDays();
848 // Returns credentials for the next 7 days
849 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
850 // TODO cache credentials until they expire
851 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
853 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
856 authCredentialResponse
);
857 } catch (VerificationFailedException e
) {
858 throw new IOException(e
);
862 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
863 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
864 ) throws IOException
{
865 group
.setGroup(newDecryptedGroup
);
866 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
867 groupChange
.toByteArray());
868 account
.getGroupStore().updateGroup(group
);
869 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
872 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
873 GroupIdV1 groupId
, SignalServiceAddress recipient
874 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
876 GroupInfo group
= getGroupForSending(groupId
);
877 if (!(group
instanceof GroupInfoV1
)) {
878 throw new RuntimeException("Received an invalid group request for a v2 group!");
880 g
= (GroupInfoV1
) group
;
882 if (!g
.isMember(recipient
)) {
883 throw new NotAGroupMemberException(groupId
, g
.name
);
886 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
888 // Send group message only to the recipient who requested it
889 return sendMessage(messageBuilder
, List
.of(recipient
));
892 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
893 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
894 .withId(g
.getGroupId().serialize())
896 .withMembers(new ArrayList
<>(g
.getMembers()));
899 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
900 if (attachment
.isPresent()) {
901 group
.withAvatar(attachment
.get());
903 } catch (IOException e
) {
904 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
907 return SignalServiceDataMessage
.newBuilder()
908 .asGroupMessage(group
.build())
909 .withExpiration(g
.getMessageExpirationTime());
912 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
913 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
914 .withRevision(g
.getGroup().getRevision())
915 .withSignedGroupChange(signedGroupChange
);
916 return SignalServiceDataMessage
.newBuilder()
917 .asGroupMessage(group
.build())
918 .withExpiration(g
.getMessageExpirationTime());
921 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
922 GroupIdV1 groupId
, SignalServiceAddress recipient
923 ) throws IOException
{
924 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
925 .withId(groupId
.serialize());
927 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
928 .asGroupMessage(group
.build());
930 // Send group info request message to the recipient who sent us a message with this groupId
931 return sendMessage(messageBuilder
, List
.of(recipient
));
935 SignalServiceAddress remoteAddress
, long messageId
936 ) throws IOException
, UntrustedIdentityException
{
937 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
939 System
.currentTimeMillis());
941 createMessageSender().sendReceipt(remoteAddress
,
942 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
946 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
947 String messageText
, List
<String
> attachments
, List
<String
> recipients
948 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
949 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
950 .withBody(messageText
);
951 if (attachments
!= null) {
952 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
954 // Upload attachments here, so we only upload once even for multiple recipients
955 SignalServiceMessageSender messageSender
= createMessageSender();
956 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
957 for (SignalServiceAttachment attachment
: attachmentStreams
) {
958 if (attachment
.isStream()) {
959 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
960 } else if (attachment
.isPointer()) {
961 attachmentPointers
.add(attachment
.asPointer());
965 messageBuilder
.withAttachments(attachmentPointers
);
967 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
970 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
971 String messageText
, List
<String
> attachments
972 ) throws IOException
, AttachmentInvalidException
{
973 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
974 .withBody(messageText
);
975 if (attachments
!= null) {
976 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
978 return sendSelfMessage(messageBuilder
);
981 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
982 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
983 ) throws IOException
, InvalidNumberException
{
984 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
986 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
987 targetSentTimestamp
);
988 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
989 .withReaction(reaction
);
990 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
993 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
994 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
996 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
998 return sendMessage(messageBuilder
, signalServiceAddresses
);
999 } catch (Exception e
) {
1000 for (SignalServiceAddress address
: signalServiceAddresses
) {
1001 handleEndSession(address
);
1008 public String
getContactName(String number
) throws InvalidNumberException
{
1009 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1010 if (contact
== null) {
1013 return contact
.name
;
1017 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1018 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1019 ContactInfo contact
= account
.getContactStore().getContact(address
);
1020 if (contact
== null) {
1021 contact
= new ContactInfo(address
);
1023 contact
.name
= name
;
1024 account
.getContactStore().updateContact(contact
);
1028 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1029 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1032 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1033 ContactInfo contact
= account
.getContactStore().getContact(address
);
1034 if (contact
== null) {
1035 contact
= new ContactInfo(address
);
1037 contact
.blocked
= blocked
;
1038 account
.getContactStore().updateContact(contact
);
1042 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1043 GroupInfo group
= getGroup(groupId
);
1044 if (group
== null) {
1045 throw new GroupNotFoundException(groupId
);
1048 group
.setBlocked(blocked
);
1049 account
.getGroupStore().updateGroup(group
);
1054 * Change the expiration timer for a contact
1056 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1057 ContactInfo contact
= account
.getContactStore().getContact(address
);
1058 contact
.messageExpirationTime
= messageExpirationTimer
;
1059 account
.getContactStore().updateContact(contact
);
1060 sendExpirationTimerUpdate(address
);
1064 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1065 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1066 .asExpirationUpdate();
1067 sendMessage(messageBuilder
, List
.of(address
));
1071 * Change the expiration timer for a contact
1073 public void setExpirationTimer(
1074 String number
, int messageExpirationTimer
1075 ) throws IOException
, InvalidNumberException
{
1076 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1077 setExpirationTimer(address
, messageExpirationTimer
);
1081 * Change the expiration timer for a group
1083 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1084 GroupInfo g
= getGroup(groupId
);
1085 if (g
instanceof GroupInfoV1
) {
1086 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1087 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1088 account
.getGroupStore().updateGroup(groupInfoV1
);
1090 throw new RuntimeException("TODO Not implemented!");
1095 * Upload the sticker pack from path.
1097 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1098 * @return if successful, returns the URL to install the sticker pack in the signal app
1100 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1101 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1103 SignalServiceMessageSender messageSender
= createMessageSender();
1105 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1106 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1108 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1109 account
.getStickerStore().updateSticker(sticker
);
1113 return new URI("https",
1116 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1117 Hex
.toStringCondensed(packKey
),
1118 StandardCharsets
.UTF_8
)).toString();
1119 } catch (URISyntaxException e
) {
1120 throw new AssertionError(e
);
1124 void requestSyncGroups() throws IOException
{
1125 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1126 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1128 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1130 sendSyncMessage(message
);
1131 } catch (UntrustedIdentityException e
) {
1132 throw new AssertionError(e
);
1136 void requestSyncContacts() throws IOException
{
1137 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1138 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1140 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1142 sendSyncMessage(message
);
1143 } catch (UntrustedIdentityException e
) {
1144 throw new AssertionError(e
);
1148 void requestSyncBlocked() throws IOException
{
1149 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1150 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1152 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1154 sendSyncMessage(message
);
1155 } catch (UntrustedIdentityException e
) {
1156 throw new AssertionError(e
);
1160 void requestSyncConfiguration() throws IOException
{
1161 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1162 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1164 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1166 sendSyncMessage(message
);
1167 } catch (UntrustedIdentityException e
) {
1168 throw new AssertionError(e
);
1172 void requestSyncKeys() throws IOException
{
1173 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1174 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1176 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1178 sendSyncMessage(message
);
1179 } catch (UntrustedIdentityException e
) {
1180 throw new AssertionError(e
);
1184 private byte[] getSenderCertificate() {
1185 // TODO support UUID capable sender certificates
1186 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1189 certificate
= accountManager
.getSenderCertificate();
1190 } catch (IOException e
) {
1191 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1194 // TODO cache for a day
1198 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1199 SignalServiceMessageSender messageSender
= createMessageSender();
1201 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1202 } catch (UntrustedIdentityException e
) {
1203 account
.getSignalProtocolStore()
1204 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1206 TrustLevel
.UNTRUSTED
);
1211 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1212 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1213 final Set
<SignalServiceAddress
> addressesMissingUuid
= new HashSet
<>();
1215 for (String number
: numbers
) {
1216 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1217 if (resolvedAddress
.getUuid().isPresent()) {
1218 signalServiceAddresses
.add(resolvedAddress
);
1220 addressesMissingUuid
.add(resolvedAddress
);
1224 final Set
<String
> numbersMissingUuid
= addressesMissingUuid
.stream()
1225 .map(a
-> a
.getNumber().get())
1226 .collect(Collectors
.toSet());
1227 Map
<String
, UUID
> registeredUsers
;
1229 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1230 } catch (IOException e
) {
1231 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1232 registeredUsers
= Map
.of();
1235 for (SignalServiceAddress address
: addressesMissingUuid
) {
1236 final String number
= address
.getNumber().get();
1237 if (registeredUsers
.containsKey(number
)) {
1238 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1239 registeredUsers
.get(number
),
1241 signalServiceAddresses
.add(newAddress
);
1243 signalServiceAddresses
.add(address
);
1247 return signalServiceAddresses
;
1250 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1252 return accountManager
.getRegisteredUsers(getIasKeyStore(), numbersMissingUuid
, CDS_MRENCLAVE
);
1253 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException e
) {
1254 throw new IOException(e
);
1258 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1259 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1260 ) throws IOException
{
1261 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1262 final long timestamp
= System
.currentTimeMillis();
1263 messageBuilder
.withTimestamp(timestamp
);
1264 getOrCreateMessagePipe();
1265 getOrCreateUnidentifiedMessagePipe();
1266 SignalServiceDataMessage message
= null;
1268 message
= messageBuilder
.build();
1269 if (message
.getGroupContext().isPresent()) {
1271 SignalServiceMessageSender messageSender
= createMessageSender();
1272 final boolean isRecipientUpdate
= false;
1273 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1274 unidentifiedAccessHelper
.getAccessFor(recipients
),
1277 for (SendMessageResult r
: result
) {
1278 if (r
.getIdentityFailure() != null) {
1279 account
.getSignalProtocolStore()
1280 .saveIdentity(r
.getAddress(),
1281 r
.getIdentityFailure().getIdentityKey(),
1282 TrustLevel
.UNTRUSTED
);
1285 return new Pair
<>(timestamp
, result
);
1286 } catch (UntrustedIdentityException e
) {
1287 account
.getSignalProtocolStore()
1288 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1290 TrustLevel
.UNTRUSTED
);
1291 return new Pair
<>(timestamp
, List
.of());
1294 // Send to all individually, so sync messages are sent correctly
1295 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1296 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1297 for (SignalServiceAddress address
: recipients
) {
1298 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1299 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1300 messageBuilder
.withExpiration(expirationTime
);
1301 message
= messageBuilder
.build();
1302 results
.add(sendMessage(address
, message
));
1304 return new Pair
<>(timestamp
, results
);
1307 if (message
!= null && message
.isEndSession()) {
1308 for (SignalServiceAddress recipient
: recipients
) {
1309 handleEndSession(recipient
);
1316 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1317 SignalServiceDataMessage
.Builder messageBuilder
1318 ) throws IOException
{
1319 final long timestamp
= System
.currentTimeMillis();
1320 messageBuilder
.withTimestamp(timestamp
);
1321 getOrCreateMessagePipe();
1322 getOrCreateUnidentifiedMessagePipe();
1324 final SignalServiceAddress address
= getSelfAddress();
1326 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1327 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1328 messageBuilder
.withExpiration(expirationTime
);
1330 SignalServiceDataMessage message
= messageBuilder
.build();
1331 final SendMessageResult result
= sendSelfMessage(message
);
1332 return new Pair
<>(timestamp
, result
);
1338 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1339 SignalServiceMessageSender messageSender
= createMessageSender();
1341 SignalServiceAddress recipient
= account
.getSelfAddress();
1343 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1344 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1345 message
.getTimestamp(),
1347 message
.getExpiresInSeconds(),
1348 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1350 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1353 long startTime
= System
.currentTimeMillis();
1354 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1355 return SendMessageResult
.success(recipient
,
1356 unidentifiedAccess
.isPresent(),
1358 System
.currentTimeMillis() - startTime
);
1359 } catch (UntrustedIdentityException e
) {
1360 account
.getSignalProtocolStore()
1361 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1363 TrustLevel
.UNTRUSTED
);
1364 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1368 private SendMessageResult
sendMessage(
1369 SignalServiceAddress address
, SignalServiceDataMessage message
1370 ) throws IOException
{
1371 SignalServiceMessageSender messageSender
= createMessageSender();
1374 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1375 } catch (UntrustedIdentityException e
) {
1376 account
.getSignalProtocolStore()
1377 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1379 TrustLevel
.UNTRUSTED
);
1380 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1384 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1385 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1386 account
.getSignalProtocolStore(),
1387 certificateValidator
);
1389 return cipher
.decrypt(envelope
);
1390 } catch (ProtocolUntrustedIdentityException e
) {
1391 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1392 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1394 account
.getSignalProtocolStore()
1395 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1396 identityException
.getUntrustedIdentity(),
1397 TrustLevel
.UNTRUSTED
);
1398 throw identityException
;
1400 throw new AssertionError(e
);
1404 private void handleEndSession(SignalServiceAddress source
) {
1405 account
.getSignalProtocolStore().deleteAllSessions(source
);
1408 private List
<HandleAction
> handleSignalServiceDataMessage(
1409 SignalServiceDataMessage message
,
1411 SignalServiceAddress source
,
1412 SignalServiceAddress destination
,
1413 boolean ignoreAttachments
1415 List
<HandleAction
> actions
= new ArrayList
<>();
1416 if (message
.getGroupContext().isPresent()) {
1417 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1418 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1419 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1420 GroupInfo group
= getGroup(groupId
);
1421 if (group
== null || group
instanceof GroupInfoV1
) {
1422 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1423 switch (groupInfo
.getType()) {
1425 if (groupV1
== null) {
1426 groupV1
= new GroupInfoV1(groupId
);
1429 if (groupInfo
.getAvatar().isPresent()) {
1430 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1431 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1434 if (groupInfo
.getName().isPresent()) {
1435 groupV1
.name
= groupInfo
.getName().get();
1438 if (groupInfo
.getMembers().isPresent()) {
1439 groupV1
.addMembers(groupInfo
.getMembers()
1442 .map(this::resolveSignalServiceAddress
)
1443 .collect(Collectors
.toSet()));
1446 account
.getGroupStore().updateGroup(groupV1
);
1450 if (groupV1
== null && !isSync
) {
1451 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1455 if (groupV1
!= null) {
1456 groupV1
.removeMember(source
);
1457 account
.getGroupStore().updateGroup(groupV1
);
1462 if (groupV1
!= null && !isSync
) {
1463 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1468 // Received a group v1 message for a v2 group
1471 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1472 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1473 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1475 getOrMigrateGroup(groupMasterKey
,
1476 groupContext
.getRevision(),
1477 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1481 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1482 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1483 handleEndSession(conversationPartnerAddress
);
1485 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1486 if (message
.getGroupContext().isPresent()) {
1487 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1488 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1489 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1490 if (group
!= null) {
1491 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1492 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1493 account
.getGroupStore().updateGroup(group
);
1496 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1497 // disappearing message timer already stored in the DecryptedGroup
1499 } else if (conversationPartnerAddress
!= null) {
1500 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1501 if (contact
== null) {
1502 contact
= new ContactInfo(conversationPartnerAddress
);
1504 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1505 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1506 account
.getContactStore().updateContact(contact
);
1510 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1511 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1512 downloadAttachment(attachment
);
1515 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1516 final ProfileKey profileKey
;
1518 profileKey
= new ProfileKey(message
.getProfileKey().get());
1519 } catch (InvalidInputException e
) {
1520 throw new AssertionError(e
);
1522 if (source
.matches(account
.getSelfAddress())) {
1523 this.account
.setProfileKey(profileKey
);
1525 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1527 if (message
.getPreviews().isPresent()) {
1528 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1529 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1530 if (preview
.getImage().isPresent()) {
1531 downloadAttachment(preview
.getImage().get());
1535 if (message
.getQuote().isPresent()) {
1536 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1538 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1539 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1540 if (thumbnail
!= null) {
1541 downloadAttachment(thumbnail
);
1545 if (message
.getSticker().isPresent()) {
1546 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1547 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1548 if (sticker
== null) {
1549 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1550 account
.getStickerStore().updateSticker(sticker
);
1556 private GroupInfoV2
getOrMigrateGroup(
1557 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1559 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1561 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1562 GroupInfo groupInfo
= getGroup(groupId
);
1563 final GroupInfoV2 groupInfoV2
;
1564 if (groupInfo
instanceof GroupInfoV1
) {
1565 // Received a v2 group message for a v1 group, we need to locally migrate the group
1566 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1567 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1568 logger
.info("Locally migrated group {} to group v2, id: {}",
1569 groupInfo
.getGroupId().toBase64(),
1570 groupInfoV2
.getGroupId().toBase64());
1571 } else if (groupInfo
instanceof GroupInfoV2
) {
1572 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1574 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1577 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1578 DecryptedGroup group
= null;
1579 if (signedGroupChange
!= null
1580 && groupInfoV2
.getGroup() != null
1581 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1582 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1584 if (group
== null) {
1585 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1587 if (group
!= null) {
1588 storeProfileKeysFromMembers(group
);
1589 final String avatar
= group
.getAvatar();
1590 if (avatar
!= null && !avatar
.isEmpty()) {
1591 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1594 groupInfoV2
.setGroup(group
);
1595 account
.getGroupStore().updateGroup(groupInfoV2
);
1601 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1602 for (DecryptedMember member
: group
.getMembersList()) {
1603 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1604 member
.getUuid().toByteArray()), null));
1606 account
.getProfileStore()
1607 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1608 } catch (InvalidInputException ignored
) {
1613 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1614 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1615 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1619 private void retryFailedReceivedMessage(
1620 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1622 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1623 if (envelope
== null) {
1626 SignalServiceContent content
= null;
1627 if (!envelope
.isReceipt()) {
1629 content
= decryptMessage(envelope
);
1630 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1632 } catch (Exception er
) {
1633 // All other errors are not recoverable, so delete the cached message
1634 cachedMessage
.delete();
1637 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1638 for (HandleAction action
: actions
) {
1640 action
.execute(this);
1641 } catch (Throwable e
) {
1642 logger
.warn("Message action failed.", e
);
1647 handler
.handleMessage(envelope
, content
, null);
1648 cachedMessage
.delete();
1651 public void receiveMessages(
1654 boolean returnOnTimeout
,
1655 boolean ignoreAttachments
,
1656 ReceiveMessageHandler handler
1657 ) throws IOException
{
1658 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1660 Set
<HandleAction
> queuedActions
= null;
1662 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1664 boolean hasCaughtUpWithOldMessages
= false;
1667 SignalServiceEnvelope envelope
;
1668 SignalServiceContent content
= null;
1669 Exception exception
= null;
1670 final CachedMessage
[] cachedMessage
= {null};
1672 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1673 // store message on disk, before acknowledging receipt to the server
1674 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1676 if (result
.isPresent()) {
1677 envelope
= result
.get();
1679 // Received indicator that server queue is empty
1680 hasCaughtUpWithOldMessages
= true;
1682 if (queuedActions
!= null) {
1683 for (HandleAction action
: queuedActions
) {
1685 action
.execute(this);
1686 } catch (Throwable e
) {
1687 logger
.warn("Message action failed.", e
);
1691 queuedActions
.clear();
1692 queuedActions
= null;
1695 // Continue to wait another timeout for new messages
1698 } catch (TimeoutException e
) {
1699 if (returnOnTimeout
) return;
1701 } catch (InvalidVersionException e
) {
1702 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1706 if (envelope
.hasSource()) {
1707 // Store uuid if we don't have it already
1708 SignalServiceAddress source
= envelope
.getSourceAddress();
1709 resolveSignalServiceAddress(source
);
1711 if (!envelope
.isReceipt()) {
1713 content
= decryptMessage(envelope
);
1714 } catch (Exception e
) {
1717 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1718 if (hasCaughtUpWithOldMessages
) {
1719 for (HandleAction action
: actions
) {
1721 action
.execute(this);
1722 } catch (Throwable e
) {
1723 logger
.warn("Message action failed.", e
);
1727 if (queuedActions
== null) {
1728 queuedActions
= new HashSet
<>();
1730 queuedActions
.addAll(actions
);
1734 if (isMessageBlocked(envelope
, content
)) {
1735 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1736 } else if (isNotAGroupMember(envelope
, content
)) {
1737 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1739 handler
.handleMessage(envelope
, content
, exception
);
1741 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1742 if (cachedMessage
[0] != null) {
1743 cachedMessage
[0].delete();
1749 private boolean isMessageBlocked(
1750 SignalServiceEnvelope envelope
, SignalServiceContent content
1752 SignalServiceAddress source
;
1753 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1754 source
= envelope
.getSourceAddress();
1755 } else if (content
!= null) {
1756 source
= content
.getSender();
1760 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1761 if (sourceContact
!= null && sourceContact
.blocked
) {
1765 if (content
!= null && content
.getDataMessage().isPresent()) {
1766 SignalServiceDataMessage message
= content
.getDataMessage().get();
1767 if (message
.getGroupContext().isPresent()) {
1768 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1769 GroupInfo group
= getGroup(groupId
);
1770 if (group
!= null && group
.isBlocked()) {
1778 private boolean isNotAGroupMember(
1779 SignalServiceEnvelope envelope
, SignalServiceContent content
1781 SignalServiceAddress source
;
1782 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1783 source
= envelope
.getSourceAddress();
1784 } else if (content
!= null) {
1785 source
= content
.getSender();
1790 if (content
!= null && content
.getDataMessage().isPresent()) {
1791 SignalServiceDataMessage message
= content
.getDataMessage().get();
1792 if (message
.getGroupContext().isPresent()) {
1793 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1794 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1795 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1799 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1800 GroupInfo group
= getGroup(groupId
);
1801 if (group
!= null && !group
.isMember(source
)) {
1809 private List
<HandleAction
> handleMessage(
1810 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1812 List
<HandleAction
> actions
= new ArrayList
<>();
1813 if (content
!= null) {
1814 final SignalServiceAddress sender
;
1815 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1816 sender
= envelope
.getSourceAddress();
1818 sender
= content
.getSender();
1820 // Store uuid if we don't have it already
1821 resolveSignalServiceAddress(sender
);
1823 if (content
.getDataMessage().isPresent()) {
1824 SignalServiceDataMessage message
= content
.getDataMessage().get();
1826 if (content
.isNeedsReceipt()) {
1827 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1830 actions
.addAll(handleSignalServiceDataMessage(message
,
1833 account
.getSelfAddress(),
1834 ignoreAttachments
));
1836 if (content
.getSyncMessage().isPresent()) {
1837 account
.setMultiDevice(true);
1838 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1839 if (syncMessage
.getSent().isPresent()) {
1840 SentTranscriptMessage message
= syncMessage
.getSent().get();
1841 final SignalServiceAddress destination
= message
.getDestination().orNull();
1842 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1846 ignoreAttachments
));
1848 if (syncMessage
.getRequest().isPresent()) {
1849 RequestMessage rm
= syncMessage
.getRequest().get();
1850 if (rm
.isContactsRequest()) {
1851 actions
.add(SendSyncContactsAction
.create());
1853 if (rm
.isGroupsRequest()) {
1854 actions
.add(SendSyncGroupsAction
.create());
1856 if (rm
.isBlockedListRequest()) {
1857 actions
.add(SendSyncBlockedListAction
.create());
1859 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1861 if (syncMessage
.getGroups().isPresent()) {
1862 File tmpFile
= null;
1864 tmpFile
= IOUtils
.createTempFile();
1865 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1866 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1868 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1870 while ((g
= s
.read()) != null) {
1871 GroupInfoV1 syncGroup
= account
.getGroupStore()
1872 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1873 if (syncGroup
!= null) {
1874 if (g
.getName().isPresent()) {
1875 syncGroup
.name
= g
.getName().get();
1877 syncGroup
.addMembers(g
.getMembers()
1879 .map(this::resolveSignalServiceAddress
)
1880 .collect(Collectors
.toSet()));
1881 if (!g
.isActive()) {
1882 syncGroup
.removeMember(account
.getSelfAddress());
1884 // Add ourself to the member set as it's marked as active
1885 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1887 syncGroup
.blocked
= g
.isBlocked();
1888 if (g
.getColor().isPresent()) {
1889 syncGroup
.color
= g
.getColor().get();
1892 if (g
.getAvatar().isPresent()) {
1893 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1895 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1896 syncGroup
.archived
= g
.isArchived();
1897 account
.getGroupStore().updateGroup(syncGroup
);
1901 } catch (Exception e
) {
1902 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1906 if (tmpFile
!= null) {
1908 Files
.delete(tmpFile
.toPath());
1909 } catch (IOException e
) {
1910 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1917 if (syncMessage
.getBlockedList().isPresent()) {
1918 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1919 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1920 setContactBlocked(resolveSignalServiceAddress(address
), true);
1922 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1924 .map(GroupId
::unknownVersion
)
1925 .collect(Collectors
.toSet())) {
1927 setGroupBlocked(groupId
, true);
1928 } catch (GroupNotFoundException e
) {
1929 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1930 groupId
.toBase64());
1934 if (syncMessage
.getContacts().isPresent()) {
1935 File tmpFile
= null;
1937 tmpFile
= IOUtils
.createTempFile();
1938 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1939 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1940 .asPointer(), tmpFile
)) {
1941 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1942 if (contactsMessage
.isComplete()) {
1943 account
.getContactStore().clear();
1946 while ((c
= s
.read()) != null) {
1947 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1948 account
.setProfileKey(c
.getProfileKey().get());
1950 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1951 ContactInfo contact
= account
.getContactStore().getContact(address
);
1952 if (contact
== null) {
1953 contact
= new ContactInfo(address
);
1955 if (c
.getName().isPresent()) {
1956 contact
.name
= c
.getName().get();
1958 if (c
.getColor().isPresent()) {
1959 contact
.color
= c
.getColor().get();
1961 if (c
.getProfileKey().isPresent()) {
1962 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1964 if (c
.getVerified().isPresent()) {
1965 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1966 account
.getSignalProtocolStore()
1967 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1968 verifiedMessage
.getIdentityKey(),
1969 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1971 if (c
.getExpirationTimer().isPresent()) {
1972 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1974 contact
.blocked
= c
.isBlocked();
1975 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1976 contact
.archived
= c
.isArchived();
1977 account
.getContactStore().updateContact(contact
);
1979 if (c
.getAvatar().isPresent()) {
1980 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
1984 } catch (Exception e
) {
1985 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1989 if (tmpFile
!= null) {
1991 Files
.delete(tmpFile
.toPath());
1992 } catch (IOException e
) {
1993 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2000 if (syncMessage
.getVerified().isPresent()) {
2001 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
2002 account
.getSignalProtocolStore()
2003 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2004 verifiedMessage
.getIdentityKey(),
2005 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2007 if (syncMessage
.getStickerPackOperations().isPresent()) {
2008 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
2010 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
2011 if (!m
.getPackId().isPresent()) {
2014 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2015 if (sticker
== null) {
2016 if (!m
.getPackKey().isPresent()) {
2019 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2021 sticker
.setInstalled(!m
.getType().isPresent()
2022 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2023 account
.getStickerStore().updateSticker(sticker
);
2026 if (syncMessage
.getFetchType().isPresent()) {
2027 switch (syncMessage
.getFetchType().get()) {
2029 getRecipientProfile(getSelfAddress(), true);
2030 case STORAGE_MANIFEST
:
2034 if (syncMessage
.getKeys().isPresent()) {
2035 final KeysMessage keysMessage
= syncMessage
.getKeys().get();
2036 if (keysMessage
.getStorageService().isPresent()) {
2037 final StorageKey storageKey
= keysMessage
.getStorageService().get();
2038 account
.setStorageKey(storageKey
);
2041 if (syncMessage
.getConfiguration().isPresent()) {
2049 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2051 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2052 } catch (IOException e
) {
2053 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2057 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2059 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2060 } catch (IOException e
) {
2061 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2065 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2067 avatarStore
.storeGroupAvatar(groupId
,
2068 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2069 } catch (IOException e
) {
2070 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2074 private void downloadProfileAvatar(
2075 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2078 avatarStore
.storeProfileAvatar(address
,
2079 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2080 } catch (Throwable e
) {
2081 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2085 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2086 return attachmentStore
.getAttachmentFile(attachmentId
);
2089 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2090 if (!attachment
.isPointer()) {
2091 logger
.warn("Invalid state, can't store an attachment stream.");
2094 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2095 if (pointer
.getPreview().isPresent()) {
2096 final byte[] preview
= pointer
.getPreview().get();
2098 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2099 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2100 } catch (IOException e
) {
2101 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2106 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2107 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2108 } catch (IOException e
) {
2109 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2113 private void retrieveGroupV2Avatar(
2114 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2115 ) throws IOException
{
2116 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2118 File tmpFile
= IOUtils
.createTempFile();
2119 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2121 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2122 byte[] encryptedData
= IOUtils
.readFully(input
);
2124 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2125 outputStream
.write(decryptedData
);
2128 Files
.delete(tmpFile
.toPath());
2129 } catch (IOException e
) {
2130 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2137 private void retrieveProfileAvatar(
2138 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2139 ) throws IOException
{
2140 File tmpFile
= IOUtils
.createTempFile();
2141 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2144 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2145 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2146 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2149 Files
.delete(tmpFile
.toPath());
2150 } catch (IOException e
) {
2151 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2158 private void retrieveAttachment(
2159 final SignalServiceAttachment attachment
, final OutputStream outputStream
2160 ) throws IOException
{
2161 if (attachment
.isPointer()) {
2162 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2163 retrieveAttachmentPointer(pointer
, outputStream
);
2165 SignalServiceAttachmentStream stream
= attachment
.asStream();
2166 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2170 private void retrieveAttachmentPointer(
2171 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2172 ) throws IOException
{
2173 File tmpFile
= IOUtils
.createTempFile();
2174 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2175 IOUtils
.copyStream(input
, outputStream
);
2176 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2177 throw new IOException(e
);
2180 Files
.delete(tmpFile
.toPath());
2181 } catch (IOException e
) {
2182 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2189 private InputStream
retrieveAttachmentAsStream(
2190 SignalServiceAttachmentPointer pointer
, File tmpFile
2191 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2192 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2195 void sendGroups() throws IOException
, UntrustedIdentityException
{
2196 File groupsFile
= IOUtils
.createTempFile();
2199 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2200 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2201 for (GroupInfo
record : getGroups()) {
2202 if (record instanceof GroupInfoV1
) {
2203 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2204 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2205 Optional
.fromNullable(groupInfo
.name
),
2206 new ArrayList
<>(groupInfo
.getMembers()),
2207 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2208 groupInfo
.isMember(account
.getSelfAddress()),
2209 Optional
.of(groupInfo
.messageExpirationTime
),
2210 Optional
.fromNullable(groupInfo
.color
),
2212 Optional
.fromNullable(groupInfo
.inboxPosition
),
2213 groupInfo
.archived
));
2218 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2219 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2220 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2221 .withStream(groupsFileStream
)
2222 .withContentType("application/octet-stream")
2223 .withLength(groupsFile
.length())
2226 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2231 Files
.delete(groupsFile
.toPath());
2232 } catch (IOException e
) {
2233 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2238 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2239 File contactsFile
= IOUtils
.createTempFile();
2242 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2243 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2244 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2245 VerifiedMessage verifiedMessage
= null;
2246 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2247 if (currentIdentity
!= null) {
2248 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2249 currentIdentity
.getIdentityKey(),
2250 currentIdentity
.getTrustLevel().toVerifiedState(),
2251 currentIdentity
.getDateAdded().getTime());
2254 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2255 out
.write(new DeviceContact(record.getAddress(),
2256 Optional
.fromNullable(record.name
),
2257 createContactAvatarAttachment(record.getAddress()),
2258 Optional
.fromNullable(record.color
),
2259 Optional
.fromNullable(verifiedMessage
),
2260 Optional
.fromNullable(profileKey
),
2262 Optional
.of(record.messageExpirationTime
),
2263 Optional
.fromNullable(record.inboxPosition
),
2267 if (account
.getProfileKey() != null) {
2268 // Send our own profile key as well
2269 out
.write(new DeviceContact(account
.getSelfAddress(),
2274 Optional
.of(account
.getProfileKey()),
2282 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2283 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2284 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2285 .withStream(contactsFileStream
)
2286 .withContentType("application/octet-stream")
2287 .withLength(contactsFile
.length())
2290 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2295 Files
.delete(contactsFile
.toPath());
2296 } catch (IOException e
) {
2297 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2302 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2303 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2304 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2305 if (record.blocked
) {
2306 addresses
.add(record.getAddress());
2309 List
<byte[]> groupIds
= new ArrayList
<>();
2310 for (GroupInfo
record : getGroups()) {
2311 if (record.isBlocked()) {
2312 groupIds
.add(record.getGroupId().serialize());
2315 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2318 private void sendVerifiedMessage(
2319 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2320 ) throws IOException
, UntrustedIdentityException
{
2321 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2323 trustLevel
.toVerifiedState(),
2324 System
.currentTimeMillis());
2325 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2328 public List
<ContactInfo
> getContacts() {
2329 return account
.getContactStore().getContacts();
2332 public String
getContactOrProfileName(String number
) {
2333 final SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2335 final ContactInfo contact
= account
.getContactStore().getContact(address
);
2336 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2337 return contact
.name
;
2340 final SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2341 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2342 return profileEntry
.getProfile().getName();
2348 public GroupInfo
getGroup(GroupId groupId
) {
2349 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2350 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2351 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2352 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2353 account
.getGroupStore().updateGroup(group
);
2358 public List
<IdentityInfo
> getIdentities() {
2359 return account
.getSignalProtocolStore().getIdentities();
2362 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2363 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2367 * Trust this the identity with this fingerprint
2369 * @param name username of the identity
2370 * @param fingerprint Fingerprint
2372 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2373 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2374 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2378 for (IdentityInfo id
: ids
) {
2379 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2383 account
.getSignalProtocolStore()
2384 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2386 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2387 } catch (IOException
| UntrustedIdentityException e
) {
2388 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2397 * Trust this the identity with this safety number
2399 * @param name username of the identity
2400 * @param safetyNumber Safety number
2402 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2403 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2404 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2408 for (IdentityInfo id
: ids
) {
2409 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2413 account
.getSignalProtocolStore()
2414 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2416 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2417 } catch (IOException
| UntrustedIdentityException e
) {
2418 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2427 * Trust all keys of this identity without verification
2429 * @param name username of the identity
2431 public boolean trustIdentityAllKeys(String name
) {
2432 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2433 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2437 for (IdentityInfo id
: ids
) {
2438 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2439 account
.getSignalProtocolStore()
2440 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2442 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2443 } catch (IOException
| UntrustedIdentityException e
) {
2444 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2452 public String
computeSafetyNumber(
2453 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2455 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2456 account
.getSelfAddress(),
2457 getIdentityKeyPair().getPublicKey(),
2462 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2463 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2465 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2466 return resolveSignalServiceAddress(canonicalizedNumber
);
2469 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2470 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2472 return resolveSignalServiceAddress(address
);
2475 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2476 if (address
.matches(account
.getSelfAddress())) {
2477 return account
.getSelfAddress();
2480 return account
.getRecipientStore().resolveServiceAddress(address
);
2484 public void close() throws IOException
{
2488 void close(boolean closeAccount
) throws IOException
{
2489 if (messagePipe
!= null) {
2490 messagePipe
.shutdown();
2494 if (unidentifiedMessagePipe
!= null) {
2495 unidentifiedMessagePipe
.shutdown();
2496 unidentifiedMessagePipe
= null;
2499 if (closeAccount
&& account
!= null) {
2505 public interface ReceiveMessageHandler
{
2507 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);