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
.RequestMessage
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
121 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
122 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
123 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
124 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
125 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
126 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
127 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
128 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
129 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
130 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
131 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
132 import org
.whispersystems
.signalservice
.internal
.configuration
.SignalServiceConfiguration
;
133 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
134 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
135 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
136 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
137 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
138 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
139 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
140 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
142 import java
.io
.Closeable
;
144 import java
.io
.FileInputStream
;
145 import java
.io
.FileOutputStream
;
146 import java
.io
.IOException
;
147 import java
.io
.InputStream
;
148 import java
.io
.OutputStream
;
150 import java
.net
.URISyntaxException
;
151 import java
.net
.URLEncoder
;
152 import java
.nio
.charset
.StandardCharsets
;
153 import java
.nio
.file
.Files
;
154 import java
.security
.SignatureException
;
155 import java
.util
.ArrayList
;
156 import java
.util
.Arrays
;
157 import java
.util
.Collection
;
158 import java
.util
.Date
;
159 import java
.util
.HashMap
;
160 import java
.util
.HashSet
;
161 import java
.util
.List
;
162 import java
.util
.Map
;
163 import java
.util
.Set
;
164 import java
.util
.UUID
;
165 import java
.util
.concurrent
.ExecutorService
;
166 import java
.util
.concurrent
.TimeUnit
;
167 import java
.util
.concurrent
.TimeoutException
;
168 import java
.util
.stream
.Collectors
;
170 import static org
.asamk
.signal
.manager
.ServiceConfig
.CDS_MRENCLAVE
;
171 import static org
.asamk
.signal
.manager
.ServiceConfig
.capabilities
;
172 import static org
.asamk
.signal
.manager
.ServiceConfig
.getIasKeyStore
;
174 public class Manager
implements Closeable
{
176 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
178 private final CertificateValidator certificateValidator
= new CertificateValidator(ServiceConfig
.getUnidentifiedSenderTrustRoot());
180 private final SignalServiceConfiguration serviceConfiguration
;
181 private final String userAgent
;
183 private SignalAccount account
;
184 private final SignalServiceAccountManager accountManager
;
185 private final GroupsV2Api groupsV2Api
;
186 private final GroupsV2Operations groupsV2Operations
;
187 private final SignalServiceMessageReceiver messageReceiver
;
188 private final ClientZkProfileOperations clientZkProfileOperations
;
190 private SignalServiceMessagePipe messagePipe
= null;
191 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
193 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
194 private final ProfileHelper profileHelper
;
195 private final GroupHelper groupHelper
;
196 private final PinHelper pinHelper
;
197 private final AvatarStore avatarStore
;
198 private final AttachmentStore attachmentStore
;
201 SignalAccount account
,
202 PathConfig pathConfig
,
203 SignalServiceConfiguration serviceConfiguration
,
206 this.account
= account
;
207 this.serviceConfiguration
= serviceConfiguration
;
208 this.userAgent
= userAgent
;
209 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
210 serviceConfiguration
)) : null;
211 final SleepTimer timer
= new UptimeSleepTimer();
212 this.accountManager
= new SignalServiceAccountManager(serviceConfiguration
,
213 new DynamicCredentialsProvider(account
.getUuid(),
214 account
.getUsername(),
215 account
.getPassword(),
216 account
.getSignalingKey(),
217 account
.getDeviceId()),
221 this.groupsV2Api
= accountManager
.getGroupsV2Api();
222 final KeyBackupService keyBackupService
= ServiceConfig
.createKeyBackupService(accountManager
);
223 this.pinHelper
= new PinHelper(keyBackupService
);
224 this.clientZkProfileOperations
= capabilities
.isGv2() ? ClientZkOperations
.create(serviceConfiguration
)
225 .getProfileOperations() : null;
226 this.messageReceiver
= new SignalServiceMessageReceiver(serviceConfiguration
,
228 account
.getUsername(),
229 account
.getPassword(),
230 account
.getDeviceId(),
231 account
.getSignalingKey(),
235 clientZkProfileOperations
);
237 this.account
.setResolver(this::resolveSignalServiceAddress
);
239 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
240 account
.getProfileStore()::getProfileKey
,
241 this::getRecipientProfile
,
242 this::getSenderCertificate
);
243 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
244 unidentifiedAccessHelper
::getAccessFor
,
245 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
246 () -> messageReceiver
);
247 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
248 this::getRecipientProfile
,
249 account
::getSelfAddress
,
252 this::getGroupAuthForToday
);
253 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
254 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
257 public String
getUsername() {
258 return account
.getUsername();
261 public SignalServiceAddress
getSelfAddress() {
262 return account
.getSelfAddress();
265 private IdentityKeyPair
getIdentityKeyPair() {
266 return account
.getSignalProtocolStore().getIdentityKeyPair();
269 public int getDeviceId() {
270 return account
.getDeviceId();
273 public static Manager
init(
274 String username
, File settingsPath
, SignalServiceConfiguration serviceConfiguration
, String userAgent
275 ) throws IOException
, NotRegisteredException
{
276 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
278 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
279 throw new NotRegisteredException();
282 SignalAccount account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
284 if (!account
.isRegistered()) {
285 throw new NotRegisteredException();
288 return new Manager(account
, pathConfig
, serviceConfiguration
, userAgent
);
291 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
292 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
293 final File dataPath
= pathConfig
.getDataPath();
294 final File
[] files
= dataPath
.listFiles();
300 return Arrays
.stream(files
)
301 .filter(File
::isFile
)
303 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
304 .collect(Collectors
.toList());
307 public void checkAccountState() throws IOException
{
308 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
312 if (account
.getUuid() == null) {
313 account
.setUuid(accountManager
.getOwnUuid());
316 updateAccountAttributes();
320 * This is used for checking a set of phone numbers for registration on Signal
322 * @param numbers The set of phone number in question
323 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
324 * @throws IOException if its unable to get the contacts to check if they're registered
326 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
327 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
328 Map
<String
, UUID
> contactDetails
= getRegisteredUsers(numbers
);
330 Set
<String
> registeredUsers
= contactDetails
.keySet();
332 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
335 public void updateAccountAttributes() throws IOException
{
336 accountManager
.setAccountAttributes(account
.getSignalingKey(),
337 account
.getSignalProtocolStore().getLocalRegistrationId(),
339 // set legacy pin only if no KBS master key is set
340 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
341 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
342 account
.getSelfUnidentifiedAccessKey(),
343 account
.isUnrestrictedUnidentifiedAccess(),
345 account
.isDiscoverableByPhoneNumber());
349 * @param avatar if avatar is null the image from the local avatar store is used (if present),
350 * if it's Optional.absent(), the avatar will be removed
352 public void setProfile(String name
, Optional
<File
> avatar
) throws IOException
{
353 try (final StreamDetails streamDetails
= avatar
== null
354 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
355 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
356 accountManager
.setVersionedProfile(account
.getUuid(), account
.getProfileKey(), name
, streamDetails
);
359 if (avatar
!= null) {
360 if (avatar
.isPresent()) {
361 avatarStore
.storeProfileAvatar(getSelfAddress(),
362 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
364 avatarStore
.deleteProfileAvatar(getSelfAddress());
369 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
370 } catch (UntrustedIdentityException ignored
) {
374 public void unregister() throws IOException
{
375 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
376 // If this is the master device, other users can't send messages to this number anymore.
377 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
378 accountManager
.setGcmId(Optional
.absent());
380 account
.setRegistered(false);
384 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
385 List
<DeviceInfo
> devices
= accountManager
.getDevices();
386 account
.setMultiDevice(devices
.size() > 1);
391 public void removeLinkedDevices(int deviceId
) throws IOException
{
392 accountManager
.removeDevice(deviceId
);
393 List
<DeviceInfo
> devices
= accountManager
.getDevices();
394 account
.setMultiDevice(devices
.size() > 1);
398 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
399 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
401 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
404 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
405 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
406 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
408 accountManager
.addDevice(deviceIdentifier
,
411 Optional
.of(account
.getProfileKey().serialize()),
413 account
.setMultiDevice(true);
417 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
418 if (pin
.isPresent()) {
419 final MasterKey masterKey
= account
.getPinMasterKey() != null
420 ? account
.getPinMasterKey()
421 : KeyUtils
.createMasterKey();
423 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
425 account
.setRegistrationLockPin(pin
.get());
426 account
.setPinMasterKey(masterKey
);
428 // Remove legacy registration lock
429 accountManager
.removeRegistrationLockV1();
432 pinHelper
.removeRegistrationLockPin();
434 account
.setRegistrationLockPin(null);
435 account
.setPinMasterKey(null);
440 void refreshPreKeys() throws IOException
{
441 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
442 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
443 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
445 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
448 private List
<PreKeyRecord
> generatePreKeys() {
449 final int offset
= account
.getPreKeyIdOffset();
451 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
452 account
.addPreKeys(records
);
458 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
459 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
461 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
462 account
.addSignedPreKey(record);
468 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
469 if (messagePipe
== null) {
470 messagePipe
= messageReceiver
.createMessagePipe();
475 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
476 if (unidentifiedMessagePipe
== null) {
477 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
479 return unidentifiedMessagePipe
;
482 private SignalServiceMessageSender
createMessageSender() {
483 final ExecutorService executor
= null;
484 return new SignalServiceMessageSender(serviceConfiguration
,
486 account
.getUsername(),
487 account
.getPassword(),
488 account
.getDeviceId(),
489 account
.getSignalProtocolStore(),
491 account
.isMultiDevice(),
492 Optional
.fromNullable(messagePipe
),
493 Optional
.fromNullable(unidentifiedMessagePipe
),
495 clientZkProfileOperations
,
497 ServiceConfig
.MAX_ENVELOPE_SIZE
);
500 private SignalProfile
getRecipientProfile(
501 SignalServiceAddress address
503 return getRecipientProfile(address
, false);
506 private SignalProfile
getRecipientProfile(
507 SignalServiceAddress address
, boolean force
509 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
510 if (profileEntry
== null) {
513 long now
= new Date().getTime();
514 // Profiles are cached for 24h before retrieving them again
515 if (!profileEntry
.isRequestPending() && (
517 || profileEntry
.getProfile() == null
518 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
520 profileEntry
.setRequestPending(true);
521 final SignalServiceProfile encryptedProfile
;
523 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
525 } catch (IOException e
) {
526 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
529 profileEntry
.setRequestPending(false);
532 final ProfileKey profileKey
= profileEntry
.getProfileKey();
533 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
534 account
.getProfileStore()
535 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
538 return profileEntry
.getProfile();
541 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
542 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
543 if (profileEntry
== null) {
546 if (profileEntry
.getProfileKeyCredential() == null) {
547 ProfileAndCredential profileAndCredential
;
549 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
550 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
551 } catch (IOException e
) {
552 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
556 long now
= new Date().getTime();
557 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
558 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
559 profileEntry
.getProfileKey(),
560 profileAndCredential
.getProfile());
561 account
.getProfileStore()
562 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
563 return profileKeyCredential
;
565 return profileEntry
.getProfileKeyCredential();
568 private SignalProfile
decryptProfileAndDownloadAvatar(
569 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
571 if (encryptedProfile
.getAvatar() != null) {
572 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
575 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
578 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
579 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
580 if (streamDetails
== null) {
581 return Optional
.absent();
584 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
587 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
588 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
589 if (streamDetails
== null) {
590 return Optional
.absent();
593 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
596 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
597 GroupInfo g
= getGroup(groupId
);
599 throw new GroupNotFoundException(groupId
);
601 if (!g
.isMember(account
.getSelfAddress())) {
602 throw new NotAGroupMemberException(groupId
, g
.getTitle());
607 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
608 GroupInfo g
= getGroup(groupId
);
610 throw new GroupNotFoundException(groupId
);
612 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
613 throw new NotAGroupMemberException(groupId
, g
.getTitle());
618 public List
<GroupInfo
> getGroups() {
619 return account
.getGroupStore().getGroups();
622 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
623 String messageText
, List
<String
> attachments
, GroupId groupId
624 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
625 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
626 .withBody(messageText
);
627 if (attachments
!= null) {
628 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
631 return sendGroupMessage(messageBuilder
, groupId
);
634 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
635 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
636 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
637 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
639 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
640 targetSentTimestamp
);
641 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
642 .withReaction(reaction
);
644 return sendGroupMessage(messageBuilder
, groupId
);
647 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
648 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
649 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
650 final GroupInfo g
= getGroupForSending(groupId
);
652 GroupUtils
.setGroupContext(messageBuilder
, g
);
653 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
655 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
658 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
659 SignalServiceDataMessage
.Builder messageBuilder
;
661 final GroupInfo g
= getGroupForUpdating(groupId
);
662 if (g
instanceof GroupInfoV1
) {
663 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
664 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
665 .withId(groupId
.serialize())
667 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
668 groupInfoV1
.removeMember(account
.getSelfAddress());
669 account
.getGroupStore().updateGroup(groupInfoV1
);
671 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
672 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
673 groupInfoV2
.setGroup(groupGroupChangePair
.first());
674 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
675 account
.getGroupStore().updateGroup(groupInfoV2
);
678 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
681 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
682 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
683 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
684 return sendUpdateGroupMessage(groupId
,
686 members
== null ?
null : getSignalServiceAddresses(members
),
690 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
691 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
692 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
694 SignalServiceDataMessage
.Builder messageBuilder
;
695 if (groupId
== null) {
697 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
698 members
== null ? List
.of() : members
,
701 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
702 gv1
.addMembers(List
.of(account
.getSelfAddress()));
703 updateGroupV1(gv1
, name
, members
, avatarFile
);
704 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
707 if (avatarFile
!= null) {
708 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
709 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
711 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
715 GroupInfo group
= getGroupForUpdating(groupId
);
716 if (group
instanceof GroupInfoV2
) {
717 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
719 Pair
<Long
, List
<SendMessageResult
>> result
= null;
720 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
721 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
722 result
= sendUpdateGroupMessage(groupInfoV2
,
723 groupGroupChangePair
.first(),
724 groupGroupChangePair
.second());
727 if (members
!= null) {
728 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
729 newMembers
.removeAll(group
.getMembers()
731 .map(this::resolveSignalServiceAddress
)
732 .collect(Collectors
.toSet()));
733 if (newMembers
.size() > 0) {
734 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
736 result
= sendUpdateGroupMessage(groupInfoV2
,
737 groupGroupChangePair
.first(),
738 groupGroupChangePair
.second());
741 if (result
== null || name
!= null || avatarFile
!= null) {
742 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
745 if (avatarFile
!= null) {
746 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
747 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
749 result
= sendUpdateGroupMessage(groupInfoV2
,
750 groupGroupChangePair
.first(),
751 groupGroupChangePair
.second());
754 return new Pair
<>(group
.getGroupId(), result
.second());
756 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
757 updateGroupV1(gv1
, name
, members
, avatarFile
);
758 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
763 account
.getGroupStore().updateGroup(g
);
765 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
766 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
767 return new Pair
<>(g
.getGroupId(), result
.second());
770 private void updateGroupV1(
773 final Collection
<SignalServiceAddress
> members
,
774 final File avatarFile
775 ) throws IOException
{
780 if (members
!= null) {
781 final Set
<String
> newE164Members
= new HashSet
<>();
782 for (SignalServiceAddress member
: members
) {
783 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
786 newE164Members
.add(member
.getNumber().get());
789 final Map
<String
, UUID
> registeredUsers
= getRegisteredUsers(newE164Members
);
790 if (registeredUsers
.size() != newE164Members
.size()) {
791 // Some of the new members are not registered on Signal
792 newE164Members
.removeAll(registeredUsers
.keySet());
793 throw new IOException("Failed to add members "
794 + String
.join(", ", newE164Members
)
795 + " to group: Not registered on Signal");
798 g
.addMembers(members
);
801 if (avatarFile
!= null) {
802 avatarStore
.storeGroupAvatar(g
.getGroupId(),
803 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
807 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
808 GroupInviteLinkUrl inviteLinkUrl
809 ) throws IOException
, GroupLinkNotActiveException
{
810 return sendJoinGroupMessage(inviteLinkUrl
);
813 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
814 GroupInviteLinkUrl inviteLinkUrl
815 ) throws IOException
, GroupLinkNotActiveException
{
816 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
817 inviteLinkUrl
.getPassword());
818 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
819 inviteLinkUrl
.getPassword(),
821 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
822 groupJoinInfo
.getRevision() + 1,
823 groupChange
.toByteArray());
825 if (group
.getGroup() == null) {
826 // Only requested member, can't send update to group members
827 return new Pair
<>(group
.getGroupId(), List
.of());
830 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
832 return new Pair
<>(group
.getGroupId(), result
.second());
835 private static int currentTimeDays() {
836 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
839 private GroupsV2AuthorizationString
getGroupAuthForToday(
840 final GroupSecretParams groupSecretParams
841 ) throws IOException
{
842 final int today
= currentTimeDays();
843 // Returns credentials for the next 7 days
844 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
845 // TODO cache credentials until they expire
846 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
848 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
851 authCredentialResponse
);
852 } catch (VerificationFailedException e
) {
853 throw new IOException(e
);
857 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
858 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
859 ) throws IOException
{
860 group
.setGroup(newDecryptedGroup
);
861 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
862 groupChange
.toByteArray());
863 account
.getGroupStore().updateGroup(group
);
864 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
867 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
868 GroupIdV1 groupId
, SignalServiceAddress recipient
869 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
871 GroupInfo group
= getGroupForSending(groupId
);
872 if (!(group
instanceof GroupInfoV1
)) {
873 throw new RuntimeException("Received an invalid group request for a v2 group!");
875 g
= (GroupInfoV1
) group
;
877 if (!g
.isMember(recipient
)) {
878 throw new NotAGroupMemberException(groupId
, g
.name
);
881 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
883 // Send group message only to the recipient who requested it
884 return sendMessage(messageBuilder
, List
.of(recipient
));
887 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
888 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
889 .withId(g
.getGroupId().serialize())
891 .withMembers(new ArrayList
<>(g
.getMembers()));
894 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
895 if (attachment
.isPresent()) {
896 group
.withAvatar(attachment
.get());
898 } catch (IOException e
) {
899 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
902 return SignalServiceDataMessage
.newBuilder()
903 .asGroupMessage(group
.build())
904 .withExpiration(g
.getMessageExpirationTime());
907 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
908 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
909 .withRevision(g
.getGroup().getRevision())
910 .withSignedGroupChange(signedGroupChange
);
911 return SignalServiceDataMessage
.newBuilder()
912 .asGroupMessage(group
.build())
913 .withExpiration(g
.getMessageExpirationTime());
916 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
917 GroupIdV1 groupId
, SignalServiceAddress recipient
918 ) throws IOException
{
919 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
920 .withId(groupId
.serialize());
922 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
923 .asGroupMessage(group
.build());
925 // Send group info request message to the recipient who sent us a message with this groupId
926 return sendMessage(messageBuilder
, List
.of(recipient
));
930 SignalServiceAddress remoteAddress
, long messageId
931 ) throws IOException
, UntrustedIdentityException
{
932 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
934 System
.currentTimeMillis());
936 createMessageSender().sendReceipt(remoteAddress
,
937 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
941 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
942 String messageText
, List
<String
> attachments
, List
<String
> recipients
943 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
944 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
945 .withBody(messageText
);
946 if (attachments
!= null) {
947 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
949 // Upload attachments here, so we only upload once even for multiple recipients
950 SignalServiceMessageSender messageSender
= createMessageSender();
951 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
952 for (SignalServiceAttachment attachment
: attachmentStreams
) {
953 if (attachment
.isStream()) {
954 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
955 } else if (attachment
.isPointer()) {
956 attachmentPointers
.add(attachment
.asPointer());
960 messageBuilder
.withAttachments(attachmentPointers
);
962 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
965 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
966 String messageText
, List
<String
> attachments
967 ) throws IOException
, AttachmentInvalidException
{
968 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
969 .withBody(messageText
);
970 if (attachments
!= null) {
971 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
973 return sendSelfMessage(messageBuilder
);
976 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
977 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
978 ) throws IOException
, InvalidNumberException
{
979 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
981 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
982 targetSentTimestamp
);
983 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
984 .withReaction(reaction
);
985 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
988 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
989 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
991 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
993 return sendMessage(messageBuilder
, signalServiceAddresses
);
994 } catch (Exception e
) {
995 for (SignalServiceAddress address
: signalServiceAddresses
) {
996 handleEndSession(address
);
1003 public String
getContactName(String number
) throws InvalidNumberException
{
1004 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1005 if (contact
== null) {
1008 return contact
.name
;
1012 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1013 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1014 ContactInfo contact
= account
.getContactStore().getContact(address
);
1015 if (contact
== null) {
1016 contact
= new ContactInfo(address
);
1018 contact
.name
= name
;
1019 account
.getContactStore().updateContact(contact
);
1023 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1024 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1027 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1028 ContactInfo contact
= account
.getContactStore().getContact(address
);
1029 if (contact
== null) {
1030 contact
= new ContactInfo(address
);
1032 contact
.blocked
= blocked
;
1033 account
.getContactStore().updateContact(contact
);
1037 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1038 GroupInfo group
= getGroup(groupId
);
1039 if (group
== null) {
1040 throw new GroupNotFoundException(groupId
);
1043 group
.setBlocked(blocked
);
1044 account
.getGroupStore().updateGroup(group
);
1049 * Change the expiration timer for a contact
1051 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1052 ContactInfo contact
= account
.getContactStore().getContact(address
);
1053 contact
.messageExpirationTime
= messageExpirationTimer
;
1054 account
.getContactStore().updateContact(contact
);
1055 sendExpirationTimerUpdate(address
);
1059 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1060 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1061 .asExpirationUpdate();
1062 sendMessage(messageBuilder
, List
.of(address
));
1066 * Change the expiration timer for a contact
1068 public void setExpirationTimer(
1069 String number
, int messageExpirationTimer
1070 ) throws IOException
, InvalidNumberException
{
1071 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1072 setExpirationTimer(address
, messageExpirationTimer
);
1076 * Change the expiration timer for a group
1078 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1079 GroupInfo g
= getGroup(groupId
);
1080 if (g
instanceof GroupInfoV1
) {
1081 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1082 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1083 account
.getGroupStore().updateGroup(groupInfoV1
);
1085 throw new RuntimeException("TODO Not implemented!");
1090 * Upload the sticker pack from path.
1092 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1093 * @return if successful, returns the URL to install the sticker pack in the signal app
1095 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1096 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1098 SignalServiceMessageSender messageSender
= createMessageSender();
1100 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1101 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1103 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1104 account
.getStickerStore().updateSticker(sticker
);
1108 return new URI("https",
1111 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1112 Hex
.toStringCondensed(packKey
),
1113 StandardCharsets
.UTF_8
)).toString();
1114 } catch (URISyntaxException e
) {
1115 throw new AssertionError(e
);
1119 void requestSyncGroups() throws IOException
{
1120 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1121 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1123 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1125 sendSyncMessage(message
);
1126 } catch (UntrustedIdentityException e
) {
1127 throw new AssertionError(e
);
1131 void requestSyncContacts() throws IOException
{
1132 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1133 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1135 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1137 sendSyncMessage(message
);
1138 } catch (UntrustedIdentityException e
) {
1139 throw new AssertionError(e
);
1143 void requestSyncBlocked() throws IOException
{
1144 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1145 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1147 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1149 sendSyncMessage(message
);
1150 } catch (UntrustedIdentityException e
) {
1151 throw new AssertionError(e
);
1155 void requestSyncConfiguration() throws IOException
{
1156 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1157 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1159 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1161 sendSyncMessage(message
);
1162 } catch (UntrustedIdentityException e
) {
1163 throw new AssertionError(e
);
1167 private byte[] getSenderCertificate() {
1168 // TODO support UUID capable sender certificates
1169 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1172 certificate
= accountManager
.getSenderCertificate();
1173 } catch (IOException e
) {
1174 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1177 // TODO cache for a day
1181 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1182 SignalServiceMessageSender messageSender
= createMessageSender();
1184 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1185 } catch (UntrustedIdentityException e
) {
1186 account
.getSignalProtocolStore()
1187 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1189 TrustLevel
.UNTRUSTED
);
1194 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1195 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1196 final Set
<SignalServiceAddress
> addressesMissingUuid
= new HashSet
<>();
1198 for (String number
: numbers
) {
1199 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1200 if (resolvedAddress
.getUuid().isPresent()) {
1201 signalServiceAddresses
.add(resolvedAddress
);
1203 addressesMissingUuid
.add(resolvedAddress
);
1207 final Set
<String
> numbersMissingUuid
= addressesMissingUuid
.stream()
1208 .map(a
-> a
.getNumber().get())
1209 .collect(Collectors
.toSet());
1210 Map
<String
, UUID
> registeredUsers
;
1212 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1213 } catch (IOException e
) {
1214 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1215 registeredUsers
= Map
.of();
1218 for (SignalServiceAddress address
: addressesMissingUuid
) {
1219 final String number
= address
.getNumber().get();
1220 if (registeredUsers
.containsKey(number
)) {
1221 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1222 registeredUsers
.get(number
),
1224 signalServiceAddresses
.add(newAddress
);
1226 signalServiceAddresses
.add(address
);
1230 return signalServiceAddresses
;
1233 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1235 return accountManager
.getRegisteredUsers(getIasKeyStore(), numbersMissingUuid
, CDS_MRENCLAVE
);
1236 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException e
) {
1237 throw new IOException(e
);
1241 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1242 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1243 ) throws IOException
{
1244 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1245 final long timestamp
= System
.currentTimeMillis();
1246 messageBuilder
.withTimestamp(timestamp
);
1247 getOrCreateMessagePipe();
1248 getOrCreateUnidentifiedMessagePipe();
1249 SignalServiceDataMessage message
= null;
1251 message
= messageBuilder
.build();
1252 if (message
.getGroupContext().isPresent()) {
1254 SignalServiceMessageSender messageSender
= createMessageSender();
1255 final boolean isRecipientUpdate
= false;
1256 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1257 unidentifiedAccessHelper
.getAccessFor(recipients
),
1260 for (SendMessageResult r
: result
) {
1261 if (r
.getIdentityFailure() != null) {
1262 account
.getSignalProtocolStore()
1263 .saveIdentity(r
.getAddress(),
1264 r
.getIdentityFailure().getIdentityKey(),
1265 TrustLevel
.UNTRUSTED
);
1268 return new Pair
<>(timestamp
, result
);
1269 } catch (UntrustedIdentityException e
) {
1270 account
.getSignalProtocolStore()
1271 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1273 TrustLevel
.UNTRUSTED
);
1274 return new Pair
<>(timestamp
, List
.of());
1277 // Send to all individually, so sync messages are sent correctly
1278 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1279 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1280 for (SignalServiceAddress address
: recipients
) {
1281 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1282 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1283 messageBuilder
.withExpiration(expirationTime
);
1284 message
= messageBuilder
.build();
1285 results
.add(sendMessage(address
, message
));
1287 return new Pair
<>(timestamp
, results
);
1290 if (message
!= null && message
.isEndSession()) {
1291 for (SignalServiceAddress recipient
: recipients
) {
1292 handleEndSession(recipient
);
1299 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1300 SignalServiceDataMessage
.Builder messageBuilder
1301 ) throws IOException
{
1302 final long timestamp
= System
.currentTimeMillis();
1303 messageBuilder
.withTimestamp(timestamp
);
1304 getOrCreateMessagePipe();
1305 getOrCreateUnidentifiedMessagePipe();
1307 final SignalServiceAddress address
= getSelfAddress();
1309 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1310 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1311 messageBuilder
.withExpiration(expirationTime
);
1313 SignalServiceDataMessage message
= messageBuilder
.build();
1314 final SendMessageResult result
= sendSelfMessage(message
);
1315 return new Pair
<>(timestamp
, result
);
1321 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1322 SignalServiceMessageSender messageSender
= createMessageSender();
1324 SignalServiceAddress recipient
= account
.getSelfAddress();
1326 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1327 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1328 message
.getTimestamp(),
1330 message
.getExpiresInSeconds(),
1331 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1333 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1336 long startTime
= System
.currentTimeMillis();
1337 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1338 return SendMessageResult
.success(recipient
,
1339 unidentifiedAccess
.isPresent(),
1341 System
.currentTimeMillis() - startTime
);
1342 } catch (UntrustedIdentityException e
) {
1343 account
.getSignalProtocolStore()
1344 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1346 TrustLevel
.UNTRUSTED
);
1347 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1351 private SendMessageResult
sendMessage(
1352 SignalServiceAddress address
, SignalServiceDataMessage message
1353 ) throws IOException
{
1354 SignalServiceMessageSender messageSender
= createMessageSender();
1357 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1358 } catch (UntrustedIdentityException e
) {
1359 account
.getSignalProtocolStore()
1360 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1362 TrustLevel
.UNTRUSTED
);
1363 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1367 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1368 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1369 account
.getSignalProtocolStore(),
1370 certificateValidator
);
1372 return cipher
.decrypt(envelope
);
1373 } catch (ProtocolUntrustedIdentityException e
) {
1374 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1375 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1377 account
.getSignalProtocolStore()
1378 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1379 identityException
.getUntrustedIdentity(),
1380 TrustLevel
.UNTRUSTED
);
1381 throw identityException
;
1383 throw new AssertionError(e
);
1387 private void handleEndSession(SignalServiceAddress source
) {
1388 account
.getSignalProtocolStore().deleteAllSessions(source
);
1391 private List
<HandleAction
> handleSignalServiceDataMessage(
1392 SignalServiceDataMessage message
,
1394 SignalServiceAddress source
,
1395 SignalServiceAddress destination
,
1396 boolean ignoreAttachments
1398 List
<HandleAction
> actions
= new ArrayList
<>();
1399 if (message
.getGroupContext().isPresent()) {
1400 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1401 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1402 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1403 GroupInfo group
= getGroup(groupId
);
1404 if (group
== null || group
instanceof GroupInfoV1
) {
1405 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1406 switch (groupInfo
.getType()) {
1408 if (groupV1
== null) {
1409 groupV1
= new GroupInfoV1(groupId
);
1412 if (groupInfo
.getAvatar().isPresent()) {
1413 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1414 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1417 if (groupInfo
.getName().isPresent()) {
1418 groupV1
.name
= groupInfo
.getName().get();
1421 if (groupInfo
.getMembers().isPresent()) {
1422 groupV1
.addMembers(groupInfo
.getMembers()
1425 .map(this::resolveSignalServiceAddress
)
1426 .collect(Collectors
.toSet()));
1429 account
.getGroupStore().updateGroup(groupV1
);
1433 if (groupV1
== null && !isSync
) {
1434 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1438 if (groupV1
!= null) {
1439 groupV1
.removeMember(source
);
1440 account
.getGroupStore().updateGroup(groupV1
);
1445 if (groupV1
!= null && !isSync
) {
1446 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1451 // Received a group v1 message for a v2 group
1454 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1455 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1456 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1458 getOrMigrateGroup(groupMasterKey
,
1459 groupContext
.getRevision(),
1460 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1464 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1465 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1466 handleEndSession(conversationPartnerAddress
);
1468 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1469 if (message
.getGroupContext().isPresent()) {
1470 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1471 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1472 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1473 if (group
!= null) {
1474 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1475 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1476 account
.getGroupStore().updateGroup(group
);
1479 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1480 // disappearing message timer already stored in the DecryptedGroup
1482 } else if (conversationPartnerAddress
!= null) {
1483 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1484 if (contact
== null) {
1485 contact
= new ContactInfo(conversationPartnerAddress
);
1487 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1488 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1489 account
.getContactStore().updateContact(contact
);
1493 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1494 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1495 downloadAttachment(attachment
);
1498 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1499 final ProfileKey profileKey
;
1501 profileKey
= new ProfileKey(message
.getProfileKey().get());
1502 } catch (InvalidInputException e
) {
1503 throw new AssertionError(e
);
1505 if (source
.matches(account
.getSelfAddress())) {
1506 this.account
.setProfileKey(profileKey
);
1508 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1510 if (message
.getPreviews().isPresent()) {
1511 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1512 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1513 if (preview
.getImage().isPresent()) {
1514 downloadAttachment(preview
.getImage().get());
1518 if (message
.getQuote().isPresent()) {
1519 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1521 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1522 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1523 if (thumbnail
!= null) {
1524 downloadAttachment(thumbnail
);
1528 if (message
.getSticker().isPresent()) {
1529 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1530 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1531 if (sticker
== null) {
1532 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1533 account
.getStickerStore().updateSticker(sticker
);
1539 private GroupInfoV2
getOrMigrateGroup(
1540 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1542 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1544 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1545 GroupInfo groupInfo
= getGroup(groupId
);
1546 final GroupInfoV2 groupInfoV2
;
1547 if (groupInfo
instanceof GroupInfoV1
) {
1548 // Received a v2 group message for a v1 group, we need to locally migrate the group
1549 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1550 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1551 logger
.info("Locally migrated group {} to group v2, id: {}",
1552 groupInfo
.getGroupId().toBase64(),
1553 groupInfoV2
.getGroupId().toBase64());
1554 } else if (groupInfo
instanceof GroupInfoV2
) {
1555 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1557 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1560 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1561 DecryptedGroup group
= null;
1562 if (signedGroupChange
!= null
1563 && groupInfoV2
.getGroup() != null
1564 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1565 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1567 if (group
== null) {
1568 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1570 if (group
!= null) {
1571 storeProfileKeysFromMembers(group
);
1572 final String avatar
= group
.getAvatar();
1573 if (avatar
!= null && !avatar
.isEmpty()) {
1574 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1577 groupInfoV2
.setGroup(group
);
1578 account
.getGroupStore().updateGroup(groupInfoV2
);
1584 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1585 for (DecryptedMember member
: group
.getMembersList()) {
1586 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1587 member
.getUuid().toByteArray()), null));
1589 account
.getProfileStore()
1590 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1591 } catch (InvalidInputException ignored
) {
1596 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1597 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1598 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1602 private void retryFailedReceivedMessage(
1603 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1605 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1606 if (envelope
== null) {
1609 SignalServiceContent content
= null;
1610 if (!envelope
.isReceipt()) {
1612 content
= decryptMessage(envelope
);
1613 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1615 } catch (Exception er
) {
1616 // All other errors are not recoverable, so delete the cached message
1617 cachedMessage
.delete();
1620 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1621 for (HandleAction action
: actions
) {
1623 action
.execute(this);
1624 } catch (Throwable e
) {
1625 logger
.warn("Message action failed.", e
);
1630 handler
.handleMessage(envelope
, content
, null);
1631 cachedMessage
.delete();
1634 public void receiveMessages(
1637 boolean returnOnTimeout
,
1638 boolean ignoreAttachments
,
1639 ReceiveMessageHandler handler
1640 ) throws IOException
{
1641 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1643 Set
<HandleAction
> queuedActions
= null;
1645 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1647 boolean hasCaughtUpWithOldMessages
= false;
1650 SignalServiceEnvelope envelope
;
1651 SignalServiceContent content
= null;
1652 Exception exception
= null;
1653 final CachedMessage
[] cachedMessage
= {null};
1655 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1656 // store message on disk, before acknowledging receipt to the server
1657 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1659 if (result
.isPresent()) {
1660 envelope
= result
.get();
1662 // Received indicator that server queue is empty
1663 hasCaughtUpWithOldMessages
= true;
1665 if (queuedActions
!= null) {
1666 for (HandleAction action
: queuedActions
) {
1668 action
.execute(this);
1669 } catch (Throwable e
) {
1670 logger
.warn("Message action failed.", e
);
1674 queuedActions
.clear();
1675 queuedActions
= null;
1678 // Continue to wait another timeout for new messages
1681 } catch (TimeoutException e
) {
1682 if (returnOnTimeout
) return;
1684 } catch (InvalidVersionException e
) {
1685 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1689 if (envelope
.hasSource()) {
1690 // Store uuid if we don't have it already
1691 SignalServiceAddress source
= envelope
.getSourceAddress();
1692 resolveSignalServiceAddress(source
);
1694 if (!envelope
.isReceipt()) {
1696 content
= decryptMessage(envelope
);
1697 } catch (Exception e
) {
1700 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1701 if (hasCaughtUpWithOldMessages
) {
1702 for (HandleAction action
: actions
) {
1704 action
.execute(this);
1705 } catch (Throwable e
) {
1706 logger
.warn("Message action failed.", e
);
1710 if (queuedActions
== null) {
1711 queuedActions
= new HashSet
<>();
1713 queuedActions
.addAll(actions
);
1717 if (isMessageBlocked(envelope
, content
)) {
1718 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1719 } else if (isNotAGroupMember(envelope
, content
)) {
1720 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1722 handler
.handleMessage(envelope
, content
, exception
);
1724 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1725 if (cachedMessage
[0] != null) {
1726 cachedMessage
[0].delete();
1732 private boolean isMessageBlocked(
1733 SignalServiceEnvelope envelope
, SignalServiceContent content
1735 SignalServiceAddress source
;
1736 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1737 source
= envelope
.getSourceAddress();
1738 } else if (content
!= null) {
1739 source
= content
.getSender();
1743 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1744 if (sourceContact
!= null && sourceContact
.blocked
) {
1748 if (content
!= null && content
.getDataMessage().isPresent()) {
1749 SignalServiceDataMessage message
= content
.getDataMessage().get();
1750 if (message
.getGroupContext().isPresent()) {
1751 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1752 GroupInfo group
= getGroup(groupId
);
1753 if (group
!= null && group
.isBlocked()) {
1761 private boolean isNotAGroupMember(
1762 SignalServiceEnvelope envelope
, SignalServiceContent content
1764 SignalServiceAddress source
;
1765 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1766 source
= envelope
.getSourceAddress();
1767 } else if (content
!= null) {
1768 source
= content
.getSender();
1773 if (content
!= null && content
.getDataMessage().isPresent()) {
1774 SignalServiceDataMessage message
= content
.getDataMessage().get();
1775 if (message
.getGroupContext().isPresent()) {
1776 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1777 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1778 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1782 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1783 GroupInfo group
= getGroup(groupId
);
1784 if (group
!= null && !group
.isMember(source
)) {
1792 private List
<HandleAction
> handleMessage(
1793 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1795 List
<HandleAction
> actions
= new ArrayList
<>();
1796 if (content
!= null) {
1797 final SignalServiceAddress sender
;
1798 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1799 sender
= envelope
.getSourceAddress();
1801 sender
= content
.getSender();
1803 // Store uuid if we don't have it already
1804 resolveSignalServiceAddress(sender
);
1806 if (content
.getDataMessage().isPresent()) {
1807 SignalServiceDataMessage message
= content
.getDataMessage().get();
1809 if (content
.isNeedsReceipt()) {
1810 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1813 actions
.addAll(handleSignalServiceDataMessage(message
,
1816 account
.getSelfAddress(),
1817 ignoreAttachments
));
1819 if (content
.getSyncMessage().isPresent()) {
1820 account
.setMultiDevice(true);
1821 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1822 if (syncMessage
.getSent().isPresent()) {
1823 SentTranscriptMessage message
= syncMessage
.getSent().get();
1824 final SignalServiceAddress destination
= message
.getDestination().orNull();
1825 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1829 ignoreAttachments
));
1831 if (syncMessage
.getRequest().isPresent()) {
1832 RequestMessage rm
= syncMessage
.getRequest().get();
1833 if (rm
.isContactsRequest()) {
1834 actions
.add(SendSyncContactsAction
.create());
1836 if (rm
.isGroupsRequest()) {
1837 actions
.add(SendSyncGroupsAction
.create());
1839 if (rm
.isBlockedListRequest()) {
1840 actions
.add(SendSyncBlockedListAction
.create());
1842 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1844 if (syncMessage
.getGroups().isPresent()) {
1845 File tmpFile
= null;
1847 tmpFile
= IOUtils
.createTempFile();
1848 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1849 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1851 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1853 while ((g
= s
.read()) != null) {
1854 GroupInfoV1 syncGroup
= account
.getGroupStore()
1855 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1856 if (syncGroup
!= null) {
1857 if (g
.getName().isPresent()) {
1858 syncGroup
.name
= g
.getName().get();
1860 syncGroup
.addMembers(g
.getMembers()
1862 .map(this::resolveSignalServiceAddress
)
1863 .collect(Collectors
.toSet()));
1864 if (!g
.isActive()) {
1865 syncGroup
.removeMember(account
.getSelfAddress());
1867 // Add ourself to the member set as it's marked as active
1868 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1870 syncGroup
.blocked
= g
.isBlocked();
1871 if (g
.getColor().isPresent()) {
1872 syncGroup
.color
= g
.getColor().get();
1875 if (g
.getAvatar().isPresent()) {
1876 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1878 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1879 syncGroup
.archived
= g
.isArchived();
1880 account
.getGroupStore().updateGroup(syncGroup
);
1884 } catch (Exception e
) {
1885 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1889 if (tmpFile
!= null) {
1891 Files
.delete(tmpFile
.toPath());
1892 } catch (IOException e
) {
1893 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1900 if (syncMessage
.getBlockedList().isPresent()) {
1901 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1902 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1903 setContactBlocked(resolveSignalServiceAddress(address
), true);
1905 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1907 .map(GroupId
::unknownVersion
)
1908 .collect(Collectors
.toSet())) {
1910 setGroupBlocked(groupId
, true);
1911 } catch (GroupNotFoundException e
) {
1912 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1913 groupId
.toBase64());
1917 if (syncMessage
.getContacts().isPresent()) {
1918 File tmpFile
= null;
1920 tmpFile
= IOUtils
.createTempFile();
1921 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1922 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1923 .asPointer(), tmpFile
)) {
1924 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1925 if (contactsMessage
.isComplete()) {
1926 account
.getContactStore().clear();
1929 while ((c
= s
.read()) != null) {
1930 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1931 account
.setProfileKey(c
.getProfileKey().get());
1933 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1934 ContactInfo contact
= account
.getContactStore().getContact(address
);
1935 if (contact
== null) {
1936 contact
= new ContactInfo(address
);
1938 if (c
.getName().isPresent()) {
1939 contact
.name
= c
.getName().get();
1941 if (c
.getColor().isPresent()) {
1942 contact
.color
= c
.getColor().get();
1944 if (c
.getProfileKey().isPresent()) {
1945 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1947 if (c
.getVerified().isPresent()) {
1948 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1949 account
.getSignalProtocolStore()
1950 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1951 verifiedMessage
.getIdentityKey(),
1952 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1954 if (c
.getExpirationTimer().isPresent()) {
1955 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1957 contact
.blocked
= c
.isBlocked();
1958 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1959 contact
.archived
= c
.isArchived();
1960 account
.getContactStore().updateContact(contact
);
1962 if (c
.getAvatar().isPresent()) {
1963 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
1967 } catch (Exception e
) {
1968 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1972 if (tmpFile
!= null) {
1974 Files
.delete(tmpFile
.toPath());
1975 } catch (IOException e
) {
1976 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1983 if (syncMessage
.getVerified().isPresent()) {
1984 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1985 account
.getSignalProtocolStore()
1986 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
1987 verifiedMessage
.getIdentityKey(),
1988 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1990 if (syncMessage
.getStickerPackOperations().isPresent()) {
1991 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
1993 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
1994 if (!m
.getPackId().isPresent()) {
1997 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
1998 if (sticker
== null) {
1999 if (!m
.getPackKey().isPresent()) {
2002 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2004 sticker
.setInstalled(!m
.getType().isPresent()
2005 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2006 account
.getStickerStore().updateSticker(sticker
);
2009 if (syncMessage
.getFetchType().isPresent()) {
2010 switch (syncMessage
.getFetchType().get()) {
2012 getRecipientProfile(getSelfAddress(), true);
2013 case STORAGE_MANIFEST
:
2017 if (syncMessage
.getConfiguration().isPresent()) {
2025 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2027 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2028 } catch (IOException e
) {
2029 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2033 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2035 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2036 } catch (IOException e
) {
2037 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2041 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2043 avatarStore
.storeGroupAvatar(groupId
,
2044 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2045 } catch (IOException e
) {
2046 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2050 private void downloadProfileAvatar(
2051 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2054 avatarStore
.storeProfileAvatar(address
,
2055 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2056 } catch (Throwable e
) {
2057 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2061 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2062 return attachmentStore
.getAttachmentFile(attachmentId
);
2065 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2066 if (!attachment
.isPointer()) {
2067 logger
.warn("Invalid state, can't store an attachment stream.");
2070 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2071 if (pointer
.getPreview().isPresent()) {
2072 final byte[] preview
= pointer
.getPreview().get();
2074 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2075 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2076 } catch (IOException e
) {
2077 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2082 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2083 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2084 } catch (IOException e
) {
2085 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2089 private void retrieveGroupV2Avatar(
2090 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2091 ) throws IOException
{
2092 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2094 File tmpFile
= IOUtils
.createTempFile();
2095 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2097 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2098 byte[] encryptedData
= IOUtils
.readFully(input
);
2100 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2101 outputStream
.write(decryptedData
);
2104 Files
.delete(tmpFile
.toPath());
2105 } catch (IOException e
) {
2106 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2113 private void retrieveProfileAvatar(
2114 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2115 ) throws IOException
{
2116 File tmpFile
= IOUtils
.createTempFile();
2117 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2120 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2121 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2122 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2125 Files
.delete(tmpFile
.toPath());
2126 } catch (IOException e
) {
2127 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2134 private void retrieveAttachment(
2135 final SignalServiceAttachment attachment
, final OutputStream outputStream
2136 ) throws IOException
{
2137 if (attachment
.isPointer()) {
2138 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2139 retrieveAttachmentPointer(pointer
, outputStream
);
2141 SignalServiceAttachmentStream stream
= attachment
.asStream();
2142 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2146 private void retrieveAttachmentPointer(
2147 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2148 ) throws IOException
{
2149 File tmpFile
= IOUtils
.createTempFile();
2150 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2151 IOUtils
.copyStream(input
, outputStream
);
2152 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2153 throw new IOException(e
);
2156 Files
.delete(tmpFile
.toPath());
2157 } catch (IOException e
) {
2158 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2165 private InputStream
retrieveAttachmentAsStream(
2166 SignalServiceAttachmentPointer pointer
, File tmpFile
2167 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2168 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2171 void sendGroups() throws IOException
, UntrustedIdentityException
{
2172 File groupsFile
= IOUtils
.createTempFile();
2175 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2176 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2177 for (GroupInfo
record : getGroups()) {
2178 if (record instanceof GroupInfoV1
) {
2179 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2180 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2181 Optional
.fromNullable(groupInfo
.name
),
2182 new ArrayList
<>(groupInfo
.getMembers()),
2183 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2184 groupInfo
.isMember(account
.getSelfAddress()),
2185 Optional
.of(groupInfo
.messageExpirationTime
),
2186 Optional
.fromNullable(groupInfo
.color
),
2188 Optional
.fromNullable(groupInfo
.inboxPosition
),
2189 groupInfo
.archived
));
2194 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2195 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2196 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2197 .withStream(groupsFileStream
)
2198 .withContentType("application/octet-stream")
2199 .withLength(groupsFile
.length())
2202 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2207 Files
.delete(groupsFile
.toPath());
2208 } catch (IOException e
) {
2209 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2214 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2215 File contactsFile
= IOUtils
.createTempFile();
2218 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2219 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2220 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2221 VerifiedMessage verifiedMessage
= null;
2222 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2223 if (currentIdentity
!= null) {
2224 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2225 currentIdentity
.getIdentityKey(),
2226 currentIdentity
.getTrustLevel().toVerifiedState(),
2227 currentIdentity
.getDateAdded().getTime());
2230 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2231 out
.write(new DeviceContact(record.getAddress(),
2232 Optional
.fromNullable(record.name
),
2233 createContactAvatarAttachment(record.getAddress()),
2234 Optional
.fromNullable(record.color
),
2235 Optional
.fromNullable(verifiedMessage
),
2236 Optional
.fromNullable(profileKey
),
2238 Optional
.of(record.messageExpirationTime
),
2239 Optional
.fromNullable(record.inboxPosition
),
2243 if (account
.getProfileKey() != null) {
2244 // Send our own profile key as well
2245 out
.write(new DeviceContact(account
.getSelfAddress(),
2250 Optional
.of(account
.getProfileKey()),
2258 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2259 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2260 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2261 .withStream(contactsFileStream
)
2262 .withContentType("application/octet-stream")
2263 .withLength(contactsFile
.length())
2266 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2271 Files
.delete(contactsFile
.toPath());
2272 } catch (IOException e
) {
2273 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2278 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2279 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2280 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2281 if (record.blocked
) {
2282 addresses
.add(record.getAddress());
2285 List
<byte[]> groupIds
= new ArrayList
<>();
2286 for (GroupInfo
record : getGroups()) {
2287 if (record.isBlocked()) {
2288 groupIds
.add(record.getGroupId().serialize());
2291 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2294 private void sendVerifiedMessage(
2295 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2296 ) throws IOException
, UntrustedIdentityException
{
2297 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2299 trustLevel
.toVerifiedState(),
2300 System
.currentTimeMillis());
2301 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2304 public List
<ContactInfo
> getContacts() {
2305 return account
.getContactStore().getContacts();
2308 public String
getContactOrProfileName(String number
) {
2309 final SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2311 final ContactInfo contact
= account
.getContactStore().getContact(address
);
2312 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2313 return contact
.name
;
2316 final SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2317 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2318 return profileEntry
.getProfile().getName();
2324 public GroupInfo
getGroup(GroupId groupId
) {
2325 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2326 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2327 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2328 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2329 account
.getGroupStore().updateGroup(group
);
2334 public List
<IdentityInfo
> getIdentities() {
2335 return account
.getSignalProtocolStore().getIdentities();
2338 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2339 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2343 * Trust this the identity with this fingerprint
2345 * @param name username of the identity
2346 * @param fingerprint Fingerprint
2348 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2349 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2350 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2354 for (IdentityInfo id
: ids
) {
2355 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2359 account
.getSignalProtocolStore()
2360 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2362 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2363 } catch (IOException
| UntrustedIdentityException e
) {
2364 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2373 * Trust this the identity with this safety number
2375 * @param name username of the identity
2376 * @param safetyNumber Safety number
2378 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2379 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2380 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2384 for (IdentityInfo id
: ids
) {
2385 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2389 account
.getSignalProtocolStore()
2390 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2392 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2393 } catch (IOException
| UntrustedIdentityException e
) {
2394 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2403 * Trust all keys of this identity without verification
2405 * @param name username of the identity
2407 public boolean trustIdentityAllKeys(String name
) {
2408 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2409 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2413 for (IdentityInfo id
: ids
) {
2414 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2415 account
.getSignalProtocolStore()
2416 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2418 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2419 } catch (IOException
| UntrustedIdentityException e
) {
2420 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2428 public String
computeSafetyNumber(
2429 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2431 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2432 account
.getSelfAddress(),
2433 getIdentityKeyPair().getPublicKey(),
2438 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2439 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2441 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2442 return resolveSignalServiceAddress(canonicalizedNumber
);
2445 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2446 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2448 return resolveSignalServiceAddress(address
);
2451 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2452 if (address
.matches(account
.getSelfAddress())) {
2453 return account
.getSelfAddress();
2456 return account
.getRecipientStore().resolveServiceAddress(address
);
2460 public void close() throws IOException
{
2464 void close(boolean closeAccount
) throws IOException
{
2465 if (messagePipe
!= null) {
2466 messagePipe
.shutdown();
2470 if (unidentifiedMessagePipe
!= null) {
2471 unidentifiedMessagePipe
.shutdown();
2472 unidentifiedMessagePipe
= null;
2475 if (closeAccount
&& account
!= null) {
2481 public interface ReceiveMessageHandler
{
2483 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);