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
;
141 import java
.io
.Closeable
;
143 import java
.io
.FileInputStream
;
144 import java
.io
.FileOutputStream
;
145 import java
.io
.IOException
;
146 import java
.io
.InputStream
;
147 import java
.io
.OutputStream
;
149 import java
.net
.URISyntaxException
;
150 import java
.net
.URLEncoder
;
151 import java
.nio
.charset
.StandardCharsets
;
152 import java
.nio
.file
.Files
;
153 import java
.security
.SignatureException
;
154 import java
.util
.ArrayList
;
155 import java
.util
.Arrays
;
156 import java
.util
.Collection
;
157 import java
.util
.Date
;
158 import java
.util
.HashMap
;
159 import java
.util
.HashSet
;
160 import java
.util
.List
;
161 import java
.util
.Map
;
162 import java
.util
.Set
;
163 import java
.util
.UUID
;
164 import java
.util
.concurrent
.ExecutorService
;
165 import java
.util
.concurrent
.TimeUnit
;
166 import java
.util
.concurrent
.TimeoutException
;
167 import java
.util
.stream
.Collectors
;
169 import static org
.asamk
.signal
.manager
.ServiceConfig
.CDS_MRENCLAVE
;
170 import static org
.asamk
.signal
.manager
.ServiceConfig
.capabilities
;
171 import static org
.asamk
.signal
.manager
.ServiceConfig
.getIasKeyStore
;
173 public class Manager
implements Closeable
{
175 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
177 private final CertificateValidator certificateValidator
= new CertificateValidator(ServiceConfig
.getUnidentifiedSenderTrustRoot());
179 private final SignalServiceConfiguration serviceConfiguration
;
180 private final String userAgent
;
182 private SignalAccount account
;
183 private final SignalServiceAccountManager accountManager
;
184 private final GroupsV2Api groupsV2Api
;
185 private final GroupsV2Operations groupsV2Operations
;
186 private final SignalServiceMessageReceiver messageReceiver
;
187 private final ClientZkProfileOperations clientZkProfileOperations
;
189 private SignalServiceMessagePipe messagePipe
= null;
190 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
192 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
193 private final ProfileHelper profileHelper
;
194 private final GroupHelper groupHelper
;
195 private final PinHelper pinHelper
;
196 private final AvatarStore avatarStore
;
197 private final AttachmentStore attachmentStore
;
200 SignalAccount account
,
201 PathConfig pathConfig
,
202 SignalServiceConfiguration serviceConfiguration
,
205 this.account
= account
;
206 this.serviceConfiguration
= serviceConfiguration
;
207 this.userAgent
= userAgent
;
208 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
209 serviceConfiguration
)) : null;
210 final SleepTimer timer
= new UptimeSleepTimer();
211 this.accountManager
= new SignalServiceAccountManager(serviceConfiguration
,
212 new DynamicCredentialsProvider(account
.getUuid(),
213 account
.getUsername(),
214 account
.getPassword(),
215 account
.getSignalingKey(),
216 account
.getDeviceId()),
220 this.groupsV2Api
= accountManager
.getGroupsV2Api();
221 final KeyBackupService keyBackupService
= ServiceConfig
.createKeyBackupService(accountManager
);
222 this.pinHelper
= new PinHelper(keyBackupService
);
223 this.clientZkProfileOperations
= capabilities
.isGv2() ? ClientZkOperations
.create(serviceConfiguration
)
224 .getProfileOperations() : null;
225 this.messageReceiver
= new SignalServiceMessageReceiver(serviceConfiguration
,
227 account
.getUsername(),
228 account
.getPassword(),
229 account
.getDeviceId(),
230 account
.getSignalingKey(),
234 clientZkProfileOperations
);
236 this.account
.setResolver(this::resolveSignalServiceAddress
);
238 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
239 account
.getProfileStore()::getProfileKey
,
240 this::getRecipientProfile
,
241 this::getSenderCertificate
);
242 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
243 unidentifiedAccessHelper
::getAccessFor
,
244 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
245 () -> messageReceiver
);
246 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
247 this::getRecipientProfile
,
248 account
::getSelfAddress
,
251 this::getGroupAuthForToday
);
252 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
253 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
256 public String
getUsername() {
257 return account
.getUsername();
260 public SignalServiceAddress
getSelfAddress() {
261 return account
.getSelfAddress();
264 private IdentityKeyPair
getIdentityKeyPair() {
265 return account
.getSignalProtocolStore().getIdentityKeyPair();
268 public int getDeviceId() {
269 return account
.getDeviceId();
272 public static Manager
init(
273 String username
, File settingsPath
, SignalServiceConfiguration serviceConfiguration
, String userAgent
274 ) throws IOException
, NotRegisteredException
{
275 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
277 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
278 throw new NotRegisteredException();
281 SignalAccount account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
283 if (!account
.isRegistered()) {
284 throw new NotRegisteredException();
287 return new Manager(account
, pathConfig
, serviceConfiguration
, userAgent
);
290 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
291 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
292 final File dataPath
= pathConfig
.getDataPath();
293 final File
[] files
= dataPath
.listFiles();
299 return Arrays
.stream(files
)
300 .filter(File
::isFile
)
302 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
303 .collect(Collectors
.toList());
306 public void checkAccountState() throws IOException
{
307 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
311 if (account
.getUuid() == null) {
312 account
.setUuid(accountManager
.getOwnUuid());
315 updateAccountAttributes();
319 * This is used for checking a set of phone numbers for registration on Signal
321 * @param numbers The set of phone number in question
322 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
323 * @throws IOException if its unable to get the contacts to check if they're registered
325 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
326 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
327 Map
<String
, UUID
> contactDetails
= getRegisteredUsers(numbers
);
329 Set
<String
> registeredUsers
= contactDetails
.keySet();
331 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
334 public void updateAccountAttributes() throws IOException
{
335 accountManager
.setAccountAttributes(account
.getSignalingKey(),
336 account
.getSignalProtocolStore().getLocalRegistrationId(),
338 // set legacy pin only if no KBS master key is set
339 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
340 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
341 account
.getSelfUnidentifiedAccessKey(),
342 account
.isUnrestrictedUnidentifiedAccess(),
344 account
.isDiscoverableByPhoneNumber());
348 * @param avatar if avatar is null the image from the local avatar store is used (if present),
349 * if it's Optional.absent(), the avatar will be removed
351 public void setProfile(String name
, Optional
<File
> avatar
) throws IOException
{
352 try (final StreamDetails streamDetails
= avatar
== null
353 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
354 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
355 accountManager
.setVersionedProfile(account
.getUuid(), account
.getProfileKey(), name
, streamDetails
);
358 if (avatar
!= null) {
359 if (avatar
.isPresent()) {
360 avatarStore
.storeProfileAvatar(getSelfAddress(),
361 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
363 avatarStore
.deleteProfileAvatar(getSelfAddress());
368 public void unregister() throws IOException
{
369 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
370 // If this is the master device, other users can't send messages to this number anymore.
371 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
372 accountManager
.setGcmId(Optional
.absent());
374 account
.setRegistered(false);
378 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
379 List
<DeviceInfo
> devices
= accountManager
.getDevices();
380 account
.setMultiDevice(devices
.size() > 1);
385 public void removeLinkedDevices(int deviceId
) throws IOException
{
386 accountManager
.removeDevice(deviceId
);
387 List
<DeviceInfo
> devices
= accountManager
.getDevices();
388 account
.setMultiDevice(devices
.size() > 1);
392 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
393 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
395 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
398 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
399 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
400 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
402 accountManager
.addDevice(deviceIdentifier
,
405 Optional
.of(account
.getProfileKey().serialize()),
407 account
.setMultiDevice(true);
411 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
412 if (pin
.isPresent()) {
413 final MasterKey masterKey
= account
.getPinMasterKey() != null
414 ? account
.getPinMasterKey()
415 : KeyUtils
.createMasterKey();
417 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
419 account
.setRegistrationLockPin(pin
.get());
420 account
.setPinMasterKey(masterKey
);
422 // Remove legacy registration lock
423 accountManager
.removeRegistrationLockV1();
426 pinHelper
.removeRegistrationLockPin();
428 account
.setRegistrationLockPin(null);
429 account
.setPinMasterKey(null);
434 void refreshPreKeys() throws IOException
{
435 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
436 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
437 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
439 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
442 private List
<PreKeyRecord
> generatePreKeys() {
443 final int offset
= account
.getPreKeyIdOffset();
445 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
446 account
.addPreKeys(records
);
452 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
453 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
455 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
456 account
.addSignedPreKey(record);
462 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
463 if (messagePipe
== null) {
464 messagePipe
= messageReceiver
.createMessagePipe();
469 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
470 if (unidentifiedMessagePipe
== null) {
471 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
473 return unidentifiedMessagePipe
;
476 private SignalServiceMessageSender
createMessageSender() {
477 final ExecutorService executor
= null;
478 return new SignalServiceMessageSender(serviceConfiguration
,
480 account
.getUsername(),
481 account
.getPassword(),
482 account
.getDeviceId(),
483 account
.getSignalProtocolStore(),
485 account
.isMultiDevice(),
486 Optional
.fromNullable(messagePipe
),
487 Optional
.fromNullable(unidentifiedMessagePipe
),
489 clientZkProfileOperations
,
491 ServiceConfig
.MAX_ENVELOPE_SIZE
);
494 private SignalProfile
getRecipientProfile(
495 SignalServiceAddress address
497 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
498 if (profileEntry
== null) {
501 long now
= new Date().getTime();
502 // Profiles are cached for 24h before retrieving them again
503 if (!profileEntry
.isRequestPending() && (
504 profileEntry
.getProfile() == null || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
506 profileEntry
.setRequestPending(true);
507 final SignalServiceProfile encryptedProfile
;
509 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
511 } catch (IOException e
) {
512 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
515 profileEntry
.setRequestPending(false);
518 final ProfileKey profileKey
= profileEntry
.getProfileKey();
519 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
520 account
.getProfileStore()
521 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
524 return profileEntry
.getProfile();
527 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
528 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
529 if (profileEntry
== null) {
532 if (profileEntry
.getProfileKeyCredential() == null) {
533 ProfileAndCredential profileAndCredential
;
535 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
536 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
537 } catch (IOException e
) {
538 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
542 long now
= new Date().getTime();
543 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
544 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
545 profileEntry
.getProfileKey(),
546 profileAndCredential
.getProfile());
547 account
.getProfileStore()
548 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
549 return profileKeyCredential
;
551 return profileEntry
.getProfileKeyCredential();
554 private SignalProfile
decryptProfileAndDownloadAvatar(
555 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
557 if (encryptedProfile
.getAvatar() != null) {
558 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
561 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
564 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
565 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
566 if (streamDetails
== null) {
567 return Optional
.absent();
570 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
573 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
574 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
575 if (streamDetails
== null) {
576 return Optional
.absent();
579 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
582 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
583 GroupInfo g
= getGroup(groupId
);
585 throw new GroupNotFoundException(groupId
);
587 if (!g
.isMember(account
.getSelfAddress())) {
588 throw new NotAGroupMemberException(groupId
, g
.getTitle());
593 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
594 GroupInfo g
= getGroup(groupId
);
596 throw new GroupNotFoundException(groupId
);
598 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
599 throw new NotAGroupMemberException(groupId
, g
.getTitle());
604 public List
<GroupInfo
> getGroups() {
605 return account
.getGroupStore().getGroups();
608 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
609 String messageText
, List
<String
> attachments
, GroupId groupId
610 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
611 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
612 .withBody(messageText
);
613 if (attachments
!= null) {
614 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
617 return sendGroupMessage(messageBuilder
, groupId
);
620 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
621 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
622 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
623 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
625 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
626 targetSentTimestamp
);
627 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
628 .withReaction(reaction
);
630 return sendGroupMessage(messageBuilder
, groupId
);
633 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
634 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
635 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
636 final GroupInfo g
= getGroupForSending(groupId
);
638 GroupUtils
.setGroupContext(messageBuilder
, g
);
639 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
641 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
644 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
645 SignalServiceDataMessage
.Builder messageBuilder
;
647 final GroupInfo g
= getGroupForUpdating(groupId
);
648 if (g
instanceof GroupInfoV1
) {
649 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
650 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
651 .withId(groupId
.serialize())
653 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
654 groupInfoV1
.removeMember(account
.getSelfAddress());
655 account
.getGroupStore().updateGroup(groupInfoV1
);
657 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
658 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
659 groupInfoV2
.setGroup(groupGroupChangePair
.first());
660 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
661 account
.getGroupStore().updateGroup(groupInfoV2
);
664 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
667 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
668 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
669 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
670 return sendUpdateGroupMessage(groupId
,
672 members
== null ?
null : getSignalServiceAddresses(members
),
676 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
677 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
678 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
680 SignalServiceDataMessage
.Builder messageBuilder
;
681 if (groupId
== null) {
683 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
684 members
== null ? List
.of() : members
,
687 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
688 gv1
.addMembers(List
.of(account
.getSelfAddress()));
689 updateGroupV1(gv1
, name
, members
, avatarFile
);
690 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
693 if (avatarFile
!= null) {
694 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
695 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
697 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
701 GroupInfo group
= getGroupForUpdating(groupId
);
702 if (group
instanceof GroupInfoV2
) {
703 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
705 Pair
<Long
, List
<SendMessageResult
>> result
= null;
706 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
707 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
708 result
= sendUpdateGroupMessage(groupInfoV2
,
709 groupGroupChangePair
.first(),
710 groupGroupChangePair
.second());
713 if (members
!= null) {
714 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
715 newMembers
.removeAll(group
.getMembers()
717 .map(this::resolveSignalServiceAddress
)
718 .collect(Collectors
.toSet()));
719 if (newMembers
.size() > 0) {
720 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
722 result
= sendUpdateGroupMessage(groupInfoV2
,
723 groupGroupChangePair
.first(),
724 groupGroupChangePair
.second());
727 if (result
== null || name
!= null || avatarFile
!= null) {
728 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
731 if (avatarFile
!= null) {
732 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
733 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
735 result
= sendUpdateGroupMessage(groupInfoV2
,
736 groupGroupChangePair
.first(),
737 groupGroupChangePair
.second());
740 return new Pair
<>(group
.getGroupId(), result
.second());
742 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
743 updateGroupV1(gv1
, name
, members
, avatarFile
);
744 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
749 account
.getGroupStore().updateGroup(g
);
751 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
752 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
753 return new Pair
<>(g
.getGroupId(), result
.second());
756 private void updateGroupV1(
759 final Collection
<SignalServiceAddress
> members
,
760 final File avatarFile
761 ) throws IOException
{
766 if (members
!= null) {
767 final Set
<String
> newE164Members
= new HashSet
<>();
768 for (SignalServiceAddress member
: members
) {
769 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
772 newE164Members
.add(member
.getNumber().get());
775 final Map
<String
, UUID
> registeredUsers
= getRegisteredUsers(newE164Members
);
776 if (registeredUsers
.size() != newE164Members
.size()) {
777 // Some of the new members are not registered on Signal
778 newE164Members
.removeAll(registeredUsers
.keySet());
779 throw new IOException("Failed to add members "
780 + String
.join(", ", newE164Members
)
781 + " to group: Not registered on Signal");
784 g
.addMembers(members
);
787 if (avatarFile
!= null) {
788 avatarStore
.storeGroupAvatar(g
.getGroupId(),
789 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
793 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
794 GroupInviteLinkUrl inviteLinkUrl
795 ) throws IOException
, GroupLinkNotActiveException
{
796 return sendJoinGroupMessage(inviteLinkUrl
);
799 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
800 GroupInviteLinkUrl inviteLinkUrl
801 ) throws IOException
, GroupLinkNotActiveException
{
802 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
803 inviteLinkUrl
.getPassword());
804 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
805 inviteLinkUrl
.getPassword(),
807 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
808 groupJoinInfo
.getRevision() + 1,
809 groupChange
.toByteArray());
811 if (group
.getGroup() == null) {
812 // Only requested member, can't send update to group members
813 return new Pair
<>(group
.getGroupId(), List
.of());
816 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
818 return new Pair
<>(group
.getGroupId(), result
.second());
821 private static int currentTimeDays() {
822 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
825 private GroupsV2AuthorizationString
getGroupAuthForToday(
826 final GroupSecretParams groupSecretParams
827 ) throws IOException
{
828 final int today
= currentTimeDays();
829 // Returns credentials for the next 7 days
830 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
831 // TODO cache credentials until they expire
832 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
834 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
837 authCredentialResponse
);
838 } catch (VerificationFailedException e
) {
839 throw new IOException(e
);
843 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
844 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
845 ) throws IOException
{
846 group
.setGroup(newDecryptedGroup
);
847 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
848 groupChange
.toByteArray());
849 account
.getGroupStore().updateGroup(group
);
850 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
853 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
854 GroupIdV1 groupId
, SignalServiceAddress recipient
855 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
857 GroupInfo group
= getGroupForSending(groupId
);
858 if (!(group
instanceof GroupInfoV1
)) {
859 throw new RuntimeException("Received an invalid group request for a v2 group!");
861 g
= (GroupInfoV1
) group
;
863 if (!g
.isMember(recipient
)) {
864 throw new NotAGroupMemberException(groupId
, g
.name
);
867 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
869 // Send group message only to the recipient who requested it
870 return sendMessage(messageBuilder
, List
.of(recipient
));
873 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
874 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
875 .withId(g
.getGroupId().serialize())
877 .withMembers(new ArrayList
<>(g
.getMembers()));
880 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
881 if (attachment
.isPresent()) {
882 group
.withAvatar(attachment
.get());
884 } catch (IOException e
) {
885 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
888 return SignalServiceDataMessage
.newBuilder()
889 .asGroupMessage(group
.build())
890 .withExpiration(g
.getMessageExpirationTime());
893 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
894 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
895 .withRevision(g
.getGroup().getRevision())
896 .withSignedGroupChange(signedGroupChange
);
897 return SignalServiceDataMessage
.newBuilder()
898 .asGroupMessage(group
.build())
899 .withExpiration(g
.getMessageExpirationTime());
902 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
903 GroupIdV1 groupId
, SignalServiceAddress recipient
904 ) throws IOException
{
905 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
906 .withId(groupId
.serialize());
908 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
909 .asGroupMessage(group
.build());
911 // Send group info request message to the recipient who sent us a message with this groupId
912 return sendMessage(messageBuilder
, List
.of(recipient
));
916 SignalServiceAddress remoteAddress
, long messageId
917 ) throws IOException
, UntrustedIdentityException
{
918 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
920 System
.currentTimeMillis());
922 createMessageSender().sendReceipt(remoteAddress
,
923 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
927 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
928 String messageText
, List
<String
> attachments
, List
<String
> recipients
929 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
930 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
931 .withBody(messageText
);
932 if (attachments
!= null) {
933 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
935 // Upload attachments here, so we only upload once even for multiple recipients
936 SignalServiceMessageSender messageSender
= createMessageSender();
937 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
938 for (SignalServiceAttachment attachment
: attachmentStreams
) {
939 if (attachment
.isStream()) {
940 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
941 } else if (attachment
.isPointer()) {
942 attachmentPointers
.add(attachment
.asPointer());
946 messageBuilder
.withAttachments(attachmentPointers
);
948 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
951 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
952 String messageText
, List
<String
> attachments
953 ) throws IOException
, AttachmentInvalidException
{
954 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
955 .withBody(messageText
);
956 if (attachments
!= null) {
957 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
959 return sendSelfMessage(messageBuilder
);
962 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
963 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
964 ) throws IOException
, InvalidNumberException
{
965 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
967 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
968 targetSentTimestamp
);
969 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
970 .withReaction(reaction
);
971 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
974 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
975 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
977 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
979 return sendMessage(messageBuilder
, signalServiceAddresses
);
980 } catch (Exception e
) {
981 for (SignalServiceAddress address
: signalServiceAddresses
) {
982 handleEndSession(address
);
989 public String
getContactName(String number
) throws InvalidNumberException
{
990 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
991 if (contact
== null) {
998 public void setContactName(String number
, String name
) throws InvalidNumberException
{
999 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1000 ContactInfo contact
= account
.getContactStore().getContact(address
);
1001 if (contact
== null) {
1002 contact
= new ContactInfo(address
);
1004 contact
.name
= name
;
1005 account
.getContactStore().updateContact(contact
);
1009 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1010 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1013 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1014 ContactInfo contact
= account
.getContactStore().getContact(address
);
1015 if (contact
== null) {
1016 contact
= new ContactInfo(address
);
1018 contact
.blocked
= blocked
;
1019 account
.getContactStore().updateContact(contact
);
1023 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1024 GroupInfo group
= getGroup(groupId
);
1025 if (group
== null) {
1026 throw new GroupNotFoundException(groupId
);
1029 group
.setBlocked(blocked
);
1030 account
.getGroupStore().updateGroup(group
);
1035 * Change the expiration timer for a contact
1037 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1038 ContactInfo contact
= account
.getContactStore().getContact(address
);
1039 contact
.messageExpirationTime
= messageExpirationTimer
;
1040 account
.getContactStore().updateContact(contact
);
1041 sendExpirationTimerUpdate(address
);
1045 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1046 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1047 .asExpirationUpdate();
1048 sendMessage(messageBuilder
, List
.of(address
));
1052 * Change the expiration timer for a contact
1054 public void setExpirationTimer(
1055 String number
, int messageExpirationTimer
1056 ) throws IOException
, InvalidNumberException
{
1057 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1058 setExpirationTimer(address
, messageExpirationTimer
);
1062 * Change the expiration timer for a group
1064 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1065 GroupInfo g
= getGroup(groupId
);
1066 if (g
instanceof GroupInfoV1
) {
1067 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1068 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1069 account
.getGroupStore().updateGroup(groupInfoV1
);
1071 throw new RuntimeException("TODO Not implemented!");
1076 * Upload the sticker pack from path.
1078 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1079 * @return if successful, returns the URL to install the sticker pack in the signal app
1081 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1082 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1084 SignalServiceMessageSender messageSender
= createMessageSender();
1086 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1087 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1089 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1090 account
.getStickerStore().updateSticker(sticker
);
1094 return new URI("https",
1097 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1098 Hex
.toStringCondensed(packKey
),
1099 StandardCharsets
.UTF_8
)).toString();
1100 } catch (URISyntaxException e
) {
1101 throw new AssertionError(e
);
1105 void requestSyncGroups() throws IOException
{
1106 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1107 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1109 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1111 sendSyncMessage(message
);
1112 } catch (UntrustedIdentityException e
) {
1113 throw new AssertionError(e
);
1117 void requestSyncContacts() throws IOException
{
1118 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1119 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1121 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1123 sendSyncMessage(message
);
1124 } catch (UntrustedIdentityException e
) {
1125 throw new AssertionError(e
);
1129 void requestSyncBlocked() throws IOException
{
1130 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1131 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1133 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1135 sendSyncMessage(message
);
1136 } catch (UntrustedIdentityException e
) {
1137 throw new AssertionError(e
);
1141 void requestSyncConfiguration() throws IOException
{
1142 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1143 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1145 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1147 sendSyncMessage(message
);
1148 } catch (UntrustedIdentityException e
) {
1149 throw new AssertionError(e
);
1153 private byte[] getSenderCertificate() {
1154 // TODO support UUID capable sender certificates
1155 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1158 certificate
= accountManager
.getSenderCertificate();
1159 } catch (IOException e
) {
1160 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1163 // TODO cache for a day
1167 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1168 SignalServiceMessageSender messageSender
= createMessageSender();
1170 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1171 } catch (UntrustedIdentityException e
) {
1172 account
.getSignalProtocolStore()
1173 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1175 TrustLevel
.UNTRUSTED
);
1180 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1181 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1182 final Set
<SignalServiceAddress
> addressesMissingUuid
= new HashSet
<>();
1184 for (String number
: numbers
) {
1185 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1186 if (resolvedAddress
.getUuid().isPresent()) {
1187 signalServiceAddresses
.add(resolvedAddress
);
1189 addressesMissingUuid
.add(resolvedAddress
);
1193 final Set
<String
> numbersMissingUuid
= addressesMissingUuid
.stream()
1194 .map(a
-> a
.getNumber().get())
1195 .collect(Collectors
.toSet());
1196 Map
<String
, UUID
> registeredUsers
;
1198 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1199 } catch (IOException e
) {
1200 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1201 registeredUsers
= Map
.of();
1204 for (SignalServiceAddress address
: addressesMissingUuid
) {
1205 final String number
= address
.getNumber().get();
1206 if (registeredUsers
.containsKey(number
)) {
1207 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1208 registeredUsers
.get(number
),
1210 signalServiceAddresses
.add(newAddress
);
1212 signalServiceAddresses
.add(address
);
1216 return signalServiceAddresses
;
1219 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1221 return accountManager
.getRegisteredUsers(getIasKeyStore(), numbersMissingUuid
, CDS_MRENCLAVE
);
1222 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException e
) {
1223 throw new IOException(e
);
1227 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1228 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1229 ) throws IOException
{
1230 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1231 final long timestamp
= System
.currentTimeMillis();
1232 messageBuilder
.withTimestamp(timestamp
);
1233 getOrCreateMessagePipe();
1234 getOrCreateUnidentifiedMessagePipe();
1235 SignalServiceDataMessage message
= null;
1237 message
= messageBuilder
.build();
1238 if (message
.getGroupContext().isPresent()) {
1240 SignalServiceMessageSender messageSender
= createMessageSender();
1241 final boolean isRecipientUpdate
= false;
1242 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1243 unidentifiedAccessHelper
.getAccessFor(recipients
),
1246 for (SendMessageResult r
: result
) {
1247 if (r
.getIdentityFailure() != null) {
1248 account
.getSignalProtocolStore()
1249 .saveIdentity(r
.getAddress(),
1250 r
.getIdentityFailure().getIdentityKey(),
1251 TrustLevel
.UNTRUSTED
);
1254 return new Pair
<>(timestamp
, result
);
1255 } catch (UntrustedIdentityException e
) {
1256 account
.getSignalProtocolStore()
1257 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1259 TrustLevel
.UNTRUSTED
);
1260 return new Pair
<>(timestamp
, List
.of());
1263 // Send to all individually, so sync messages are sent correctly
1264 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1265 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1266 for (SignalServiceAddress address
: recipients
) {
1267 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1268 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1269 messageBuilder
.withExpiration(expirationTime
);
1270 message
= messageBuilder
.build();
1271 results
.add(sendMessage(address
, message
));
1273 return new Pair
<>(timestamp
, results
);
1276 if (message
!= null && message
.isEndSession()) {
1277 for (SignalServiceAddress recipient
: recipients
) {
1278 handleEndSession(recipient
);
1285 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1286 SignalServiceDataMessage
.Builder messageBuilder
1287 ) throws IOException
{
1288 final long timestamp
= System
.currentTimeMillis();
1289 messageBuilder
.withTimestamp(timestamp
);
1290 getOrCreateMessagePipe();
1291 getOrCreateUnidentifiedMessagePipe();
1293 final SignalServiceAddress address
= getSelfAddress();
1295 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1296 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1297 messageBuilder
.withExpiration(expirationTime
);
1299 SignalServiceDataMessage message
= messageBuilder
.build();
1300 final SendMessageResult result
= sendSelfMessage(message
);
1301 return new Pair
<>(timestamp
, result
);
1307 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1308 SignalServiceMessageSender messageSender
= createMessageSender();
1310 SignalServiceAddress recipient
= account
.getSelfAddress();
1312 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1313 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1314 message
.getTimestamp(),
1316 message
.getExpiresInSeconds(),
1317 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1319 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1322 long startTime
= System
.currentTimeMillis();
1323 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1324 return SendMessageResult
.success(recipient
,
1325 unidentifiedAccess
.isPresent(),
1327 System
.currentTimeMillis() - startTime
);
1328 } catch (UntrustedIdentityException e
) {
1329 account
.getSignalProtocolStore()
1330 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1332 TrustLevel
.UNTRUSTED
);
1333 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1337 private SendMessageResult
sendMessage(
1338 SignalServiceAddress address
, SignalServiceDataMessage message
1339 ) throws IOException
{
1340 SignalServiceMessageSender messageSender
= createMessageSender();
1343 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1344 } catch (UntrustedIdentityException e
) {
1345 account
.getSignalProtocolStore()
1346 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1348 TrustLevel
.UNTRUSTED
);
1349 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1353 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1354 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1355 account
.getSignalProtocolStore(),
1356 certificateValidator
);
1358 return cipher
.decrypt(envelope
);
1359 } catch (ProtocolUntrustedIdentityException e
) {
1360 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1361 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1363 account
.getSignalProtocolStore()
1364 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1365 identityException
.getUntrustedIdentity(),
1366 TrustLevel
.UNTRUSTED
);
1367 throw identityException
;
1369 throw new AssertionError(e
);
1373 private void handleEndSession(SignalServiceAddress source
) {
1374 account
.getSignalProtocolStore().deleteAllSessions(source
);
1377 private List
<HandleAction
> handleSignalServiceDataMessage(
1378 SignalServiceDataMessage message
,
1380 SignalServiceAddress source
,
1381 SignalServiceAddress destination
,
1382 boolean ignoreAttachments
1384 List
<HandleAction
> actions
= new ArrayList
<>();
1385 if (message
.getGroupContext().isPresent()) {
1386 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1387 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1388 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1389 GroupInfo group
= getGroup(groupId
);
1390 if (group
== null || group
instanceof GroupInfoV1
) {
1391 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1392 switch (groupInfo
.getType()) {
1394 if (groupV1
== null) {
1395 groupV1
= new GroupInfoV1(groupId
);
1398 if (groupInfo
.getAvatar().isPresent()) {
1399 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1400 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1403 if (groupInfo
.getName().isPresent()) {
1404 groupV1
.name
= groupInfo
.getName().get();
1407 if (groupInfo
.getMembers().isPresent()) {
1408 groupV1
.addMembers(groupInfo
.getMembers()
1411 .map(this::resolveSignalServiceAddress
)
1412 .collect(Collectors
.toSet()));
1415 account
.getGroupStore().updateGroup(groupV1
);
1419 if (groupV1
== null && !isSync
) {
1420 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1424 if (groupV1
!= null) {
1425 groupV1
.removeMember(source
);
1426 account
.getGroupStore().updateGroup(groupV1
);
1431 if (groupV1
!= null && !isSync
) {
1432 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1437 // Received a group v1 message for a v2 group
1440 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1441 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1442 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1444 getOrMigrateGroup(groupMasterKey
,
1445 groupContext
.getRevision(),
1446 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1450 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1451 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1452 handleEndSession(conversationPartnerAddress
);
1454 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1455 if (message
.getGroupContext().isPresent()) {
1456 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1457 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1458 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1459 if (group
!= null) {
1460 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1461 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1462 account
.getGroupStore().updateGroup(group
);
1465 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1466 // disappearing message timer already stored in the DecryptedGroup
1468 } else if (conversationPartnerAddress
!= null) {
1469 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1470 if (contact
== null) {
1471 contact
= new ContactInfo(conversationPartnerAddress
);
1473 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1474 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1475 account
.getContactStore().updateContact(contact
);
1479 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1480 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1481 downloadAttachment(attachment
);
1484 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1485 final ProfileKey profileKey
;
1487 profileKey
= new ProfileKey(message
.getProfileKey().get());
1488 } catch (InvalidInputException e
) {
1489 throw new AssertionError(e
);
1491 if (source
.matches(account
.getSelfAddress())) {
1492 this.account
.setProfileKey(profileKey
);
1494 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1496 if (message
.getPreviews().isPresent()) {
1497 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1498 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1499 if (preview
.getImage().isPresent()) {
1500 downloadAttachment(preview
.getImage().get());
1504 if (message
.getQuote().isPresent()) {
1505 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1507 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1508 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1509 if (thumbnail
!= null) {
1510 downloadAttachment(thumbnail
);
1514 if (message
.getSticker().isPresent()) {
1515 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1516 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1517 if (sticker
== null) {
1518 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1519 account
.getStickerStore().updateSticker(sticker
);
1525 private GroupInfoV2
getOrMigrateGroup(
1526 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1528 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1530 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1531 GroupInfo groupInfo
= getGroup(groupId
);
1532 final GroupInfoV2 groupInfoV2
;
1533 if (groupInfo
instanceof GroupInfoV1
) {
1534 // Received a v2 group message for a v1 group, we need to locally migrate the group
1535 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1536 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1537 logger
.info("Locally migrated group {} to group v2, id: {}",
1538 groupInfo
.getGroupId().toBase64(),
1539 groupInfoV2
.getGroupId().toBase64());
1540 } else if (groupInfo
instanceof GroupInfoV2
) {
1541 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1543 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1546 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1547 DecryptedGroup group
= null;
1548 if (signedGroupChange
!= null
1549 && groupInfoV2
.getGroup() != null
1550 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1551 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1553 if (group
== null) {
1554 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1556 if (group
!= null) {
1557 storeProfileKeysFromMembers(group
);
1558 final String avatar
= group
.getAvatar();
1559 if (avatar
!= null && !avatar
.isEmpty()) {
1560 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1563 groupInfoV2
.setGroup(group
);
1564 account
.getGroupStore().updateGroup(groupInfoV2
);
1570 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1571 for (DecryptedMember member
: group
.getMembersList()) {
1572 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1573 member
.getUuid().toByteArray()), null));
1575 account
.getProfileStore()
1576 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1577 } catch (InvalidInputException ignored
) {
1582 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1583 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1584 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1588 private void retryFailedReceivedMessage(
1589 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1591 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1592 if (envelope
== null) {
1595 SignalServiceContent content
= null;
1596 if (!envelope
.isReceipt()) {
1598 content
= decryptMessage(envelope
);
1599 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1601 } catch (Exception er
) {
1602 // All other errors are not recoverable, so delete the cached message
1603 cachedMessage
.delete();
1606 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1607 for (HandleAction action
: actions
) {
1609 action
.execute(this);
1610 } catch (Throwable e
) {
1611 logger
.warn("Message action failed.", e
);
1616 handler
.handleMessage(envelope
, content
, null);
1617 cachedMessage
.delete();
1620 public void receiveMessages(
1623 boolean returnOnTimeout
,
1624 boolean ignoreAttachments
,
1625 ReceiveMessageHandler handler
1626 ) throws IOException
{
1627 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1629 Set
<HandleAction
> queuedActions
= null;
1631 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1633 boolean hasCaughtUpWithOldMessages
= false;
1636 SignalServiceEnvelope envelope
;
1637 SignalServiceContent content
= null;
1638 Exception exception
= null;
1639 final CachedMessage
[] cachedMessage
= {null};
1641 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1642 // store message on disk, before acknowledging receipt to the server
1643 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1645 if (result
.isPresent()) {
1646 envelope
= result
.get();
1648 // Received indicator that server queue is empty
1649 hasCaughtUpWithOldMessages
= true;
1651 if (queuedActions
!= null) {
1652 for (HandleAction action
: queuedActions
) {
1654 action
.execute(this);
1655 } catch (Throwable e
) {
1656 logger
.warn("Message action failed.", e
);
1660 queuedActions
.clear();
1661 queuedActions
= null;
1664 // Continue to wait another timeout for new messages
1667 } catch (TimeoutException e
) {
1668 if (returnOnTimeout
) return;
1670 } catch (InvalidVersionException e
) {
1671 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1675 if (envelope
.hasSource()) {
1676 // Store uuid if we don't have it already
1677 SignalServiceAddress source
= envelope
.getSourceAddress();
1678 resolveSignalServiceAddress(source
);
1680 if (!envelope
.isReceipt()) {
1682 content
= decryptMessage(envelope
);
1683 } catch (Exception e
) {
1686 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1687 if (hasCaughtUpWithOldMessages
) {
1688 for (HandleAction action
: actions
) {
1690 action
.execute(this);
1691 } catch (Throwable e
) {
1692 logger
.warn("Message action failed.", e
);
1696 if (queuedActions
== null) {
1697 queuedActions
= new HashSet
<>();
1699 queuedActions
.addAll(actions
);
1703 if (isMessageBlocked(envelope
, content
)) {
1704 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1705 } else if (isNotAGroupMember(envelope
, content
)) {
1706 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1708 handler
.handleMessage(envelope
, content
, exception
);
1710 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1711 if (cachedMessage
[0] != null) {
1712 cachedMessage
[0].delete();
1718 private boolean isMessageBlocked(
1719 SignalServiceEnvelope envelope
, SignalServiceContent content
1721 SignalServiceAddress source
;
1722 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1723 source
= envelope
.getSourceAddress();
1724 } else if (content
!= null) {
1725 source
= content
.getSender();
1729 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1730 if (sourceContact
!= null && sourceContact
.blocked
) {
1734 if (content
!= null && content
.getDataMessage().isPresent()) {
1735 SignalServiceDataMessage message
= content
.getDataMessage().get();
1736 if (message
.getGroupContext().isPresent()) {
1737 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1738 GroupInfo group
= getGroup(groupId
);
1739 if (group
!= null && group
.isBlocked()) {
1747 private boolean isNotAGroupMember(
1748 SignalServiceEnvelope envelope
, SignalServiceContent content
1750 SignalServiceAddress source
;
1751 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1752 source
= envelope
.getSourceAddress();
1753 } else if (content
!= null) {
1754 source
= content
.getSender();
1759 if (content
!= null && content
.getDataMessage().isPresent()) {
1760 SignalServiceDataMessage message
= content
.getDataMessage().get();
1761 if (message
.getGroupContext().isPresent()) {
1762 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1763 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1764 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1768 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1769 GroupInfo group
= getGroup(groupId
);
1770 if (group
!= null && !group
.isMember(source
)) {
1778 private List
<HandleAction
> handleMessage(
1779 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1781 List
<HandleAction
> actions
= new ArrayList
<>();
1782 if (content
!= null) {
1783 final SignalServiceAddress sender
;
1784 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1785 sender
= envelope
.getSourceAddress();
1787 sender
= content
.getSender();
1789 // Store uuid if we don't have it already
1790 resolveSignalServiceAddress(sender
);
1792 if (content
.getDataMessage().isPresent()) {
1793 SignalServiceDataMessage message
= content
.getDataMessage().get();
1795 if (content
.isNeedsReceipt()) {
1796 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1799 actions
.addAll(handleSignalServiceDataMessage(message
,
1802 account
.getSelfAddress(),
1803 ignoreAttachments
));
1805 if (content
.getSyncMessage().isPresent()) {
1806 account
.setMultiDevice(true);
1807 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1808 if (syncMessage
.getSent().isPresent()) {
1809 SentTranscriptMessage message
= syncMessage
.getSent().get();
1810 final SignalServiceAddress destination
= message
.getDestination().orNull();
1811 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1815 ignoreAttachments
));
1817 if (syncMessage
.getRequest().isPresent()) {
1818 RequestMessage rm
= syncMessage
.getRequest().get();
1819 if (rm
.isContactsRequest()) {
1820 actions
.add(SendSyncContactsAction
.create());
1822 if (rm
.isGroupsRequest()) {
1823 actions
.add(SendSyncGroupsAction
.create());
1825 if (rm
.isBlockedListRequest()) {
1826 actions
.add(SendSyncBlockedListAction
.create());
1828 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1830 if (syncMessage
.getGroups().isPresent()) {
1831 File tmpFile
= null;
1833 tmpFile
= IOUtils
.createTempFile();
1834 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1835 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1837 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1839 while ((g
= s
.read()) != null) {
1840 GroupInfoV1 syncGroup
= account
.getGroupStore()
1841 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1842 if (syncGroup
!= null) {
1843 if (g
.getName().isPresent()) {
1844 syncGroup
.name
= g
.getName().get();
1846 syncGroup
.addMembers(g
.getMembers()
1848 .map(this::resolveSignalServiceAddress
)
1849 .collect(Collectors
.toSet()));
1850 if (!g
.isActive()) {
1851 syncGroup
.removeMember(account
.getSelfAddress());
1853 // Add ourself to the member set as it's marked as active
1854 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1856 syncGroup
.blocked
= g
.isBlocked();
1857 if (g
.getColor().isPresent()) {
1858 syncGroup
.color
= g
.getColor().get();
1861 if (g
.getAvatar().isPresent()) {
1862 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1864 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1865 syncGroup
.archived
= g
.isArchived();
1866 account
.getGroupStore().updateGroup(syncGroup
);
1870 } catch (Exception e
) {
1871 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1875 if (tmpFile
!= null) {
1877 Files
.delete(tmpFile
.toPath());
1878 } catch (IOException e
) {
1879 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1886 if (syncMessage
.getBlockedList().isPresent()) {
1887 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1888 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1889 setContactBlocked(resolveSignalServiceAddress(address
), true);
1891 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1893 .map(GroupId
::unknownVersion
)
1894 .collect(Collectors
.toSet())) {
1896 setGroupBlocked(groupId
, true);
1897 } catch (GroupNotFoundException e
) {
1898 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1899 groupId
.toBase64());
1903 if (syncMessage
.getContacts().isPresent()) {
1904 File tmpFile
= null;
1906 tmpFile
= IOUtils
.createTempFile();
1907 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1908 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1909 .asPointer(), tmpFile
)) {
1910 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1911 if (contactsMessage
.isComplete()) {
1912 account
.getContactStore().clear();
1915 while ((c
= s
.read()) != null) {
1916 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1917 account
.setProfileKey(c
.getProfileKey().get());
1919 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1920 ContactInfo contact
= account
.getContactStore().getContact(address
);
1921 if (contact
== null) {
1922 contact
= new ContactInfo(address
);
1924 if (c
.getName().isPresent()) {
1925 contact
.name
= c
.getName().get();
1927 if (c
.getColor().isPresent()) {
1928 contact
.color
= c
.getColor().get();
1930 if (c
.getProfileKey().isPresent()) {
1931 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1933 if (c
.getVerified().isPresent()) {
1934 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1935 account
.getSignalProtocolStore()
1936 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1937 verifiedMessage
.getIdentityKey(),
1938 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1940 if (c
.getExpirationTimer().isPresent()) {
1941 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1943 contact
.blocked
= c
.isBlocked();
1944 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1945 contact
.archived
= c
.isArchived();
1946 account
.getContactStore().updateContact(contact
);
1948 if (c
.getAvatar().isPresent()) {
1949 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
1953 } catch (Exception e
) {
1954 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1958 if (tmpFile
!= null) {
1960 Files
.delete(tmpFile
.toPath());
1961 } catch (IOException e
) {
1962 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1969 if (syncMessage
.getVerified().isPresent()) {
1970 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1971 account
.getSignalProtocolStore()
1972 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
1973 verifiedMessage
.getIdentityKey(),
1974 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1976 if (syncMessage
.getStickerPackOperations().isPresent()) {
1977 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
1979 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
1980 if (!m
.getPackId().isPresent()) {
1983 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
1984 if (sticker
== null) {
1985 if (!m
.getPackKey().isPresent()) {
1988 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
1990 sticker
.setInstalled(!m
.getType().isPresent()
1991 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
1992 account
.getStickerStore().updateSticker(sticker
);
1995 if (syncMessage
.getConfiguration().isPresent()) {
2003 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2005 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2006 } catch (IOException e
) {
2007 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2011 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2013 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2014 } catch (IOException e
) {
2015 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2019 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2021 avatarStore
.storeGroupAvatar(groupId
,
2022 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2023 } catch (IOException e
) {
2024 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2028 private void downloadProfileAvatar(
2029 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2032 avatarStore
.storeProfileAvatar(address
,
2033 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2034 } catch (Throwable e
) {
2035 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2039 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2040 return attachmentStore
.getAttachmentFile(attachmentId
);
2043 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2044 if (!attachment
.isPointer()) {
2045 logger
.warn("Invalid state, can't store an attachment stream.");
2048 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2049 if (pointer
.getPreview().isPresent()) {
2050 final byte[] preview
= pointer
.getPreview().get();
2052 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2053 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2054 } catch (IOException e
) {
2055 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2060 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2061 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2062 } catch (IOException e
) {
2063 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2067 private void retrieveGroupV2Avatar(
2068 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2069 ) throws IOException
{
2070 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2072 File tmpFile
= IOUtils
.createTempFile();
2073 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2075 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2076 byte[] encryptedData
= IOUtils
.readFully(input
);
2078 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2079 outputStream
.write(decryptedData
);
2082 Files
.delete(tmpFile
.toPath());
2083 } catch (IOException e
) {
2084 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2091 private void retrieveProfileAvatar(
2092 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2093 ) throws IOException
{
2094 File tmpFile
= IOUtils
.createTempFile();
2095 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2098 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2099 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2100 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2103 Files
.delete(tmpFile
.toPath());
2104 } catch (IOException e
) {
2105 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2112 private void retrieveAttachment(
2113 final SignalServiceAttachment attachment
, final OutputStream outputStream
2114 ) throws IOException
{
2115 if (attachment
.isPointer()) {
2116 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2117 retrieveAttachmentPointer(pointer
, outputStream
);
2119 SignalServiceAttachmentStream stream
= attachment
.asStream();
2120 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2124 private void retrieveAttachmentPointer(
2125 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2126 ) throws IOException
{
2127 File tmpFile
= IOUtils
.createTempFile();
2128 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2129 IOUtils
.copyStream(input
, outputStream
);
2130 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2131 throw new IOException(e
);
2134 Files
.delete(tmpFile
.toPath());
2135 } catch (IOException e
) {
2136 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2143 private InputStream
retrieveAttachmentAsStream(
2144 SignalServiceAttachmentPointer pointer
, File tmpFile
2145 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2146 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2149 void sendGroups() throws IOException
, UntrustedIdentityException
{
2150 File groupsFile
= IOUtils
.createTempFile();
2153 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2154 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2155 for (GroupInfo
record : getGroups()) {
2156 if (record instanceof GroupInfoV1
) {
2157 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2158 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2159 Optional
.fromNullable(groupInfo
.name
),
2160 new ArrayList
<>(groupInfo
.getMembers()),
2161 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2162 groupInfo
.isMember(account
.getSelfAddress()),
2163 Optional
.of(groupInfo
.messageExpirationTime
),
2164 Optional
.fromNullable(groupInfo
.color
),
2166 Optional
.fromNullable(groupInfo
.inboxPosition
),
2167 groupInfo
.archived
));
2172 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2173 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2174 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2175 .withStream(groupsFileStream
)
2176 .withContentType("application/octet-stream")
2177 .withLength(groupsFile
.length())
2180 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2185 Files
.delete(groupsFile
.toPath());
2186 } catch (IOException e
) {
2187 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2192 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2193 File contactsFile
= IOUtils
.createTempFile();
2196 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2197 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2198 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2199 VerifiedMessage verifiedMessage
= null;
2200 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2201 if (currentIdentity
!= null) {
2202 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2203 currentIdentity
.getIdentityKey(),
2204 currentIdentity
.getTrustLevel().toVerifiedState(),
2205 currentIdentity
.getDateAdded().getTime());
2208 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2209 out
.write(new DeviceContact(record.getAddress(),
2210 Optional
.fromNullable(record.name
),
2211 createContactAvatarAttachment(record.getAddress()),
2212 Optional
.fromNullable(record.color
),
2213 Optional
.fromNullable(verifiedMessage
),
2214 Optional
.fromNullable(profileKey
),
2216 Optional
.of(record.messageExpirationTime
),
2217 Optional
.fromNullable(record.inboxPosition
),
2221 if (account
.getProfileKey() != null) {
2222 // Send our own profile key as well
2223 out
.write(new DeviceContact(account
.getSelfAddress(),
2228 Optional
.of(account
.getProfileKey()),
2236 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2237 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2238 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2239 .withStream(contactsFileStream
)
2240 .withContentType("application/octet-stream")
2241 .withLength(contactsFile
.length())
2244 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2249 Files
.delete(contactsFile
.toPath());
2250 } catch (IOException e
) {
2251 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2256 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2257 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2258 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2259 if (record.blocked
) {
2260 addresses
.add(record.getAddress());
2263 List
<byte[]> groupIds
= new ArrayList
<>();
2264 for (GroupInfo
record : getGroups()) {
2265 if (record.isBlocked()) {
2266 groupIds
.add(record.getGroupId().serialize());
2269 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2272 private void sendVerifiedMessage(
2273 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2274 ) throws IOException
, UntrustedIdentityException
{
2275 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2277 trustLevel
.toVerifiedState(),
2278 System
.currentTimeMillis());
2279 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2282 public List
<ContactInfo
> getContacts() {
2283 return account
.getContactStore().getContacts();
2286 public ContactInfo
getContact(String number
) {
2287 return account
.getContactStore().getContact(Utils
.getSignalServiceAddressFromIdentifier(number
));
2290 public GroupInfo
getGroup(GroupId groupId
) {
2291 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2292 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2293 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2294 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2295 account
.getGroupStore().updateGroup(group
);
2300 public List
<IdentityInfo
> getIdentities() {
2301 return account
.getSignalProtocolStore().getIdentities();
2304 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2305 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2309 * Trust this the identity with this fingerprint
2311 * @param name username of the identity
2312 * @param fingerprint Fingerprint
2314 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2315 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2316 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2320 for (IdentityInfo id
: ids
) {
2321 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2325 account
.getSignalProtocolStore()
2326 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2328 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2329 } catch (IOException
| UntrustedIdentityException e
) {
2330 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2339 * Trust this the identity with this safety number
2341 * @param name username of the identity
2342 * @param safetyNumber Safety number
2344 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2345 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2346 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2350 for (IdentityInfo id
: ids
) {
2351 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2355 account
.getSignalProtocolStore()
2356 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2358 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2359 } catch (IOException
| UntrustedIdentityException e
) {
2360 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2369 * Trust all keys of this identity without verification
2371 * @param name username of the identity
2373 public boolean trustIdentityAllKeys(String name
) {
2374 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2375 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2379 for (IdentityInfo id
: ids
) {
2380 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2381 account
.getSignalProtocolStore()
2382 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2384 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2385 } catch (IOException
| UntrustedIdentityException e
) {
2386 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2394 public String
computeSafetyNumber(
2395 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2397 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2398 account
.getSelfAddress(),
2399 getIdentityKeyPair().getPublicKey(),
2404 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2405 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2407 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2408 return resolveSignalServiceAddress(canonicalizedNumber
);
2411 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2412 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2414 return resolveSignalServiceAddress(address
);
2417 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2418 if (address
.matches(account
.getSelfAddress())) {
2419 return account
.getSelfAddress();
2422 return account
.getRecipientStore().resolveServiceAddress(address
);
2426 public void close() throws IOException
{
2430 void close(boolean closeAccount
) throws IOException
{
2431 if (messagePipe
!= null) {
2432 messagePipe
.shutdown();
2436 if (unidentifiedMessagePipe
!= null) {
2437 unidentifiedMessagePipe
.shutdown();
2438 unidentifiedMessagePipe
= null;
2441 if (closeAccount
&& account
!= null) {
2447 public interface ReceiveMessageHandler
{
2449 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);