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 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
369 } catch (UntrustedIdentityException ignored
) {
373 public void unregister() throws IOException
{
374 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
375 // If this is the master device, other users can't send messages to this number anymore.
376 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
377 accountManager
.setGcmId(Optional
.absent());
379 account
.setRegistered(false);
383 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
384 List
<DeviceInfo
> devices
= accountManager
.getDevices();
385 account
.setMultiDevice(devices
.size() > 1);
390 public void removeLinkedDevices(int deviceId
) throws IOException
{
391 accountManager
.removeDevice(deviceId
);
392 List
<DeviceInfo
> devices
= accountManager
.getDevices();
393 account
.setMultiDevice(devices
.size() > 1);
397 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
398 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
400 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
403 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
404 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
405 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
407 accountManager
.addDevice(deviceIdentifier
,
410 Optional
.of(account
.getProfileKey().serialize()),
412 account
.setMultiDevice(true);
416 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
417 if (pin
.isPresent()) {
418 final MasterKey masterKey
= account
.getPinMasterKey() != null
419 ? account
.getPinMasterKey()
420 : KeyUtils
.createMasterKey();
422 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
424 account
.setRegistrationLockPin(pin
.get());
425 account
.setPinMasterKey(masterKey
);
427 // Remove legacy registration lock
428 accountManager
.removeRegistrationLockV1();
431 pinHelper
.removeRegistrationLockPin();
433 account
.setRegistrationLockPin(null);
434 account
.setPinMasterKey(null);
439 void refreshPreKeys() throws IOException
{
440 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
441 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
442 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
444 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
447 private List
<PreKeyRecord
> generatePreKeys() {
448 final int offset
= account
.getPreKeyIdOffset();
450 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
451 account
.addPreKeys(records
);
457 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
458 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
460 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
461 account
.addSignedPreKey(record);
467 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
468 if (messagePipe
== null) {
469 messagePipe
= messageReceiver
.createMessagePipe();
474 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
475 if (unidentifiedMessagePipe
== null) {
476 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
478 return unidentifiedMessagePipe
;
481 private SignalServiceMessageSender
createMessageSender() {
482 final ExecutorService executor
= null;
483 return new SignalServiceMessageSender(serviceConfiguration
,
485 account
.getUsername(),
486 account
.getPassword(),
487 account
.getDeviceId(),
488 account
.getSignalProtocolStore(),
490 account
.isMultiDevice(),
491 Optional
.fromNullable(messagePipe
),
492 Optional
.fromNullable(unidentifiedMessagePipe
),
494 clientZkProfileOperations
,
496 ServiceConfig
.MAX_ENVELOPE_SIZE
);
499 private SignalProfile
getRecipientProfile(
500 SignalServiceAddress address
502 return getRecipientProfile(address
, false);
505 private SignalProfile
getRecipientProfile(
506 SignalServiceAddress address
, boolean force
508 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
509 if (profileEntry
== null) {
512 long now
= new Date().getTime();
513 // Profiles are cached for 24h before retrieving them again
514 if (!profileEntry
.isRequestPending() && (
516 || profileEntry
.getProfile() == null
517 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
519 profileEntry
.setRequestPending(true);
520 final SignalServiceProfile encryptedProfile
;
522 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
524 } catch (IOException e
) {
525 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
528 profileEntry
.setRequestPending(false);
531 final ProfileKey profileKey
= profileEntry
.getProfileKey();
532 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
533 account
.getProfileStore()
534 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
537 return profileEntry
.getProfile();
540 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
541 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
542 if (profileEntry
== null) {
545 if (profileEntry
.getProfileKeyCredential() == null) {
546 ProfileAndCredential profileAndCredential
;
548 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
549 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
550 } catch (IOException e
) {
551 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
555 long now
= new Date().getTime();
556 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
557 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
558 profileEntry
.getProfileKey(),
559 profileAndCredential
.getProfile());
560 account
.getProfileStore()
561 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
562 return profileKeyCredential
;
564 return profileEntry
.getProfileKeyCredential();
567 private SignalProfile
decryptProfileAndDownloadAvatar(
568 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
570 if (encryptedProfile
.getAvatar() != null) {
571 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
574 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
577 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
578 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
579 if (streamDetails
== null) {
580 return Optional
.absent();
583 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
586 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
587 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
588 if (streamDetails
== null) {
589 return Optional
.absent();
592 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
595 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
596 GroupInfo g
= getGroup(groupId
);
598 throw new GroupNotFoundException(groupId
);
600 if (!g
.isMember(account
.getSelfAddress())) {
601 throw new NotAGroupMemberException(groupId
, g
.getTitle());
606 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
607 GroupInfo g
= getGroup(groupId
);
609 throw new GroupNotFoundException(groupId
);
611 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
612 throw new NotAGroupMemberException(groupId
, g
.getTitle());
617 public List
<GroupInfo
> getGroups() {
618 return account
.getGroupStore().getGroups();
621 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
622 String messageText
, List
<String
> attachments
, GroupId groupId
623 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
624 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
625 .withBody(messageText
);
626 if (attachments
!= null) {
627 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
630 return sendGroupMessage(messageBuilder
, groupId
);
633 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
634 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
635 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
636 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
638 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
639 targetSentTimestamp
);
640 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
641 .withReaction(reaction
);
643 return sendGroupMessage(messageBuilder
, groupId
);
646 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
647 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
648 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
649 final GroupInfo g
= getGroupForSending(groupId
);
651 GroupUtils
.setGroupContext(messageBuilder
, g
);
652 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
654 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
657 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
658 SignalServiceDataMessage
.Builder messageBuilder
;
660 final GroupInfo g
= getGroupForUpdating(groupId
);
661 if (g
instanceof GroupInfoV1
) {
662 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
663 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
664 .withId(groupId
.serialize())
666 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
667 groupInfoV1
.removeMember(account
.getSelfAddress());
668 account
.getGroupStore().updateGroup(groupInfoV1
);
670 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
671 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
672 groupInfoV2
.setGroup(groupGroupChangePair
.first());
673 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
674 account
.getGroupStore().updateGroup(groupInfoV2
);
677 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
680 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
681 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
682 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
683 return sendUpdateGroupMessage(groupId
,
685 members
== null ?
null : getSignalServiceAddresses(members
),
689 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
690 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
691 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
693 SignalServiceDataMessage
.Builder messageBuilder
;
694 if (groupId
== null) {
696 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
697 members
== null ? List
.of() : members
,
700 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
701 gv1
.addMembers(List
.of(account
.getSelfAddress()));
702 updateGroupV1(gv1
, name
, members
, avatarFile
);
703 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
706 if (avatarFile
!= null) {
707 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
708 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
710 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
714 GroupInfo group
= getGroupForUpdating(groupId
);
715 if (group
instanceof GroupInfoV2
) {
716 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
718 Pair
<Long
, List
<SendMessageResult
>> result
= null;
719 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
720 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
721 result
= sendUpdateGroupMessage(groupInfoV2
,
722 groupGroupChangePair
.first(),
723 groupGroupChangePair
.second());
726 if (members
!= null) {
727 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
728 newMembers
.removeAll(group
.getMembers()
730 .map(this::resolveSignalServiceAddress
)
731 .collect(Collectors
.toSet()));
732 if (newMembers
.size() > 0) {
733 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
735 result
= sendUpdateGroupMessage(groupInfoV2
,
736 groupGroupChangePair
.first(),
737 groupGroupChangePair
.second());
740 if (result
== null || name
!= null || avatarFile
!= null) {
741 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
744 if (avatarFile
!= null) {
745 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
746 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
748 result
= sendUpdateGroupMessage(groupInfoV2
,
749 groupGroupChangePair
.first(),
750 groupGroupChangePair
.second());
753 return new Pair
<>(group
.getGroupId(), result
.second());
755 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
756 updateGroupV1(gv1
, name
, members
, avatarFile
);
757 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
762 account
.getGroupStore().updateGroup(g
);
764 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
765 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
766 return new Pair
<>(g
.getGroupId(), result
.second());
769 private void updateGroupV1(
772 final Collection
<SignalServiceAddress
> members
,
773 final File avatarFile
774 ) throws IOException
{
779 if (members
!= null) {
780 final Set
<String
> newE164Members
= new HashSet
<>();
781 for (SignalServiceAddress member
: members
) {
782 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
785 newE164Members
.add(member
.getNumber().get());
788 final Map
<String
, UUID
> registeredUsers
= getRegisteredUsers(newE164Members
);
789 if (registeredUsers
.size() != newE164Members
.size()) {
790 // Some of the new members are not registered on Signal
791 newE164Members
.removeAll(registeredUsers
.keySet());
792 throw new IOException("Failed to add members "
793 + String
.join(", ", newE164Members
)
794 + " to group: Not registered on Signal");
797 g
.addMembers(members
);
800 if (avatarFile
!= null) {
801 avatarStore
.storeGroupAvatar(g
.getGroupId(),
802 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
806 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
807 GroupInviteLinkUrl inviteLinkUrl
808 ) throws IOException
, GroupLinkNotActiveException
{
809 return sendJoinGroupMessage(inviteLinkUrl
);
812 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
813 GroupInviteLinkUrl inviteLinkUrl
814 ) throws IOException
, GroupLinkNotActiveException
{
815 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
816 inviteLinkUrl
.getPassword());
817 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
818 inviteLinkUrl
.getPassword(),
820 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
821 groupJoinInfo
.getRevision() + 1,
822 groupChange
.toByteArray());
824 if (group
.getGroup() == null) {
825 // Only requested member, can't send update to group members
826 return new Pair
<>(group
.getGroupId(), List
.of());
829 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
831 return new Pair
<>(group
.getGroupId(), result
.second());
834 private static int currentTimeDays() {
835 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
838 private GroupsV2AuthorizationString
getGroupAuthForToday(
839 final GroupSecretParams groupSecretParams
840 ) throws IOException
{
841 final int today
= currentTimeDays();
842 // Returns credentials for the next 7 days
843 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
844 // TODO cache credentials until they expire
845 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
847 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
850 authCredentialResponse
);
851 } catch (VerificationFailedException e
) {
852 throw new IOException(e
);
856 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
857 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
858 ) throws IOException
{
859 group
.setGroup(newDecryptedGroup
);
860 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
861 groupChange
.toByteArray());
862 account
.getGroupStore().updateGroup(group
);
863 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
866 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
867 GroupIdV1 groupId
, SignalServiceAddress recipient
868 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
870 GroupInfo group
= getGroupForSending(groupId
);
871 if (!(group
instanceof GroupInfoV1
)) {
872 throw new RuntimeException("Received an invalid group request for a v2 group!");
874 g
= (GroupInfoV1
) group
;
876 if (!g
.isMember(recipient
)) {
877 throw new NotAGroupMemberException(groupId
, g
.name
);
880 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
882 // Send group message only to the recipient who requested it
883 return sendMessage(messageBuilder
, List
.of(recipient
));
886 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
887 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
888 .withId(g
.getGroupId().serialize())
890 .withMembers(new ArrayList
<>(g
.getMembers()));
893 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
894 if (attachment
.isPresent()) {
895 group
.withAvatar(attachment
.get());
897 } catch (IOException e
) {
898 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
901 return SignalServiceDataMessage
.newBuilder()
902 .asGroupMessage(group
.build())
903 .withExpiration(g
.getMessageExpirationTime());
906 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
907 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
908 .withRevision(g
.getGroup().getRevision())
909 .withSignedGroupChange(signedGroupChange
);
910 return SignalServiceDataMessage
.newBuilder()
911 .asGroupMessage(group
.build())
912 .withExpiration(g
.getMessageExpirationTime());
915 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
916 GroupIdV1 groupId
, SignalServiceAddress recipient
917 ) throws IOException
{
918 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
919 .withId(groupId
.serialize());
921 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
922 .asGroupMessage(group
.build());
924 // Send group info request message to the recipient who sent us a message with this groupId
925 return sendMessage(messageBuilder
, List
.of(recipient
));
929 SignalServiceAddress remoteAddress
, long messageId
930 ) throws IOException
, UntrustedIdentityException
{
931 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
933 System
.currentTimeMillis());
935 createMessageSender().sendReceipt(remoteAddress
,
936 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
940 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
941 String messageText
, List
<String
> attachments
, List
<String
> recipients
942 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
943 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
944 .withBody(messageText
);
945 if (attachments
!= null) {
946 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
948 // Upload attachments here, so we only upload once even for multiple recipients
949 SignalServiceMessageSender messageSender
= createMessageSender();
950 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
951 for (SignalServiceAttachment attachment
: attachmentStreams
) {
952 if (attachment
.isStream()) {
953 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
954 } else if (attachment
.isPointer()) {
955 attachmentPointers
.add(attachment
.asPointer());
959 messageBuilder
.withAttachments(attachmentPointers
);
961 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
964 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
965 String messageText
, List
<String
> attachments
966 ) throws IOException
, AttachmentInvalidException
{
967 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
968 .withBody(messageText
);
969 if (attachments
!= null) {
970 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
972 return sendSelfMessage(messageBuilder
);
975 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
976 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
977 ) throws IOException
, InvalidNumberException
{
978 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
980 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
981 targetSentTimestamp
);
982 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
983 .withReaction(reaction
);
984 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
987 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
988 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
990 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
992 return sendMessage(messageBuilder
, signalServiceAddresses
);
993 } catch (Exception e
) {
994 for (SignalServiceAddress address
: signalServiceAddresses
) {
995 handleEndSession(address
);
1002 public String
getContactName(String number
) throws InvalidNumberException
{
1003 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1004 if (contact
== null) {
1007 return contact
.name
;
1011 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1012 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1013 ContactInfo contact
= account
.getContactStore().getContact(address
);
1014 if (contact
== null) {
1015 contact
= new ContactInfo(address
);
1017 contact
.name
= name
;
1018 account
.getContactStore().updateContact(contact
);
1022 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1023 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1026 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1027 ContactInfo contact
= account
.getContactStore().getContact(address
);
1028 if (contact
== null) {
1029 contact
= new ContactInfo(address
);
1031 contact
.blocked
= blocked
;
1032 account
.getContactStore().updateContact(contact
);
1036 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1037 GroupInfo group
= getGroup(groupId
);
1038 if (group
== null) {
1039 throw new GroupNotFoundException(groupId
);
1042 group
.setBlocked(blocked
);
1043 account
.getGroupStore().updateGroup(group
);
1048 * Change the expiration timer for a contact
1050 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1051 ContactInfo contact
= account
.getContactStore().getContact(address
);
1052 contact
.messageExpirationTime
= messageExpirationTimer
;
1053 account
.getContactStore().updateContact(contact
);
1054 sendExpirationTimerUpdate(address
);
1058 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1059 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1060 .asExpirationUpdate();
1061 sendMessage(messageBuilder
, List
.of(address
));
1065 * Change the expiration timer for a contact
1067 public void setExpirationTimer(
1068 String number
, int messageExpirationTimer
1069 ) throws IOException
, InvalidNumberException
{
1070 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1071 setExpirationTimer(address
, messageExpirationTimer
);
1075 * Change the expiration timer for a group
1077 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1078 GroupInfo g
= getGroup(groupId
);
1079 if (g
instanceof GroupInfoV1
) {
1080 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1081 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1082 account
.getGroupStore().updateGroup(groupInfoV1
);
1084 throw new RuntimeException("TODO Not implemented!");
1089 * Upload the sticker pack from path.
1091 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1092 * @return if successful, returns the URL to install the sticker pack in the signal app
1094 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1095 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1097 SignalServiceMessageSender messageSender
= createMessageSender();
1099 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1100 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1102 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1103 account
.getStickerStore().updateSticker(sticker
);
1107 return new URI("https",
1110 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1111 Hex
.toStringCondensed(packKey
),
1112 StandardCharsets
.UTF_8
)).toString();
1113 } catch (URISyntaxException e
) {
1114 throw new AssertionError(e
);
1118 void requestSyncGroups() throws IOException
{
1119 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1120 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1122 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1124 sendSyncMessage(message
);
1125 } catch (UntrustedIdentityException e
) {
1126 throw new AssertionError(e
);
1130 void requestSyncContacts() throws IOException
{
1131 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1132 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1134 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1136 sendSyncMessage(message
);
1137 } catch (UntrustedIdentityException e
) {
1138 throw new AssertionError(e
);
1142 void requestSyncBlocked() throws IOException
{
1143 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1144 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1146 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1148 sendSyncMessage(message
);
1149 } catch (UntrustedIdentityException e
) {
1150 throw new AssertionError(e
);
1154 void requestSyncConfiguration() throws IOException
{
1155 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1156 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1158 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1160 sendSyncMessage(message
);
1161 } catch (UntrustedIdentityException e
) {
1162 throw new AssertionError(e
);
1166 private byte[] getSenderCertificate() {
1167 // TODO support UUID capable sender certificates
1168 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1171 certificate
= accountManager
.getSenderCertificate();
1172 } catch (IOException e
) {
1173 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1176 // TODO cache for a day
1180 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1181 SignalServiceMessageSender messageSender
= createMessageSender();
1183 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1184 } catch (UntrustedIdentityException e
) {
1185 account
.getSignalProtocolStore()
1186 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1188 TrustLevel
.UNTRUSTED
);
1193 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1194 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1195 final Set
<SignalServiceAddress
> addressesMissingUuid
= new HashSet
<>();
1197 for (String number
: numbers
) {
1198 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1199 if (resolvedAddress
.getUuid().isPresent()) {
1200 signalServiceAddresses
.add(resolvedAddress
);
1202 addressesMissingUuid
.add(resolvedAddress
);
1206 final Set
<String
> numbersMissingUuid
= addressesMissingUuid
.stream()
1207 .map(a
-> a
.getNumber().get())
1208 .collect(Collectors
.toSet());
1209 Map
<String
, UUID
> registeredUsers
;
1211 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1212 } catch (IOException e
) {
1213 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1214 registeredUsers
= Map
.of();
1217 for (SignalServiceAddress address
: addressesMissingUuid
) {
1218 final String number
= address
.getNumber().get();
1219 if (registeredUsers
.containsKey(number
)) {
1220 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1221 registeredUsers
.get(number
),
1223 signalServiceAddresses
.add(newAddress
);
1225 signalServiceAddresses
.add(address
);
1229 return signalServiceAddresses
;
1232 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1234 return accountManager
.getRegisteredUsers(getIasKeyStore(), numbersMissingUuid
, CDS_MRENCLAVE
);
1235 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException e
) {
1236 throw new IOException(e
);
1240 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1241 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1242 ) throws IOException
{
1243 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1244 final long timestamp
= System
.currentTimeMillis();
1245 messageBuilder
.withTimestamp(timestamp
);
1246 getOrCreateMessagePipe();
1247 getOrCreateUnidentifiedMessagePipe();
1248 SignalServiceDataMessage message
= null;
1250 message
= messageBuilder
.build();
1251 if (message
.getGroupContext().isPresent()) {
1253 SignalServiceMessageSender messageSender
= createMessageSender();
1254 final boolean isRecipientUpdate
= false;
1255 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1256 unidentifiedAccessHelper
.getAccessFor(recipients
),
1259 for (SendMessageResult r
: result
) {
1260 if (r
.getIdentityFailure() != null) {
1261 account
.getSignalProtocolStore()
1262 .saveIdentity(r
.getAddress(),
1263 r
.getIdentityFailure().getIdentityKey(),
1264 TrustLevel
.UNTRUSTED
);
1267 return new Pair
<>(timestamp
, result
);
1268 } catch (UntrustedIdentityException e
) {
1269 account
.getSignalProtocolStore()
1270 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1272 TrustLevel
.UNTRUSTED
);
1273 return new Pair
<>(timestamp
, List
.of());
1276 // Send to all individually, so sync messages are sent correctly
1277 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1278 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1279 for (SignalServiceAddress address
: recipients
) {
1280 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1281 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1282 messageBuilder
.withExpiration(expirationTime
);
1283 message
= messageBuilder
.build();
1284 results
.add(sendMessage(address
, message
));
1286 return new Pair
<>(timestamp
, results
);
1289 if (message
!= null && message
.isEndSession()) {
1290 for (SignalServiceAddress recipient
: recipients
) {
1291 handleEndSession(recipient
);
1298 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1299 SignalServiceDataMessage
.Builder messageBuilder
1300 ) throws IOException
{
1301 final long timestamp
= System
.currentTimeMillis();
1302 messageBuilder
.withTimestamp(timestamp
);
1303 getOrCreateMessagePipe();
1304 getOrCreateUnidentifiedMessagePipe();
1306 final SignalServiceAddress address
= getSelfAddress();
1308 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1309 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1310 messageBuilder
.withExpiration(expirationTime
);
1312 SignalServiceDataMessage message
= messageBuilder
.build();
1313 final SendMessageResult result
= sendSelfMessage(message
);
1314 return new Pair
<>(timestamp
, result
);
1320 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1321 SignalServiceMessageSender messageSender
= createMessageSender();
1323 SignalServiceAddress recipient
= account
.getSelfAddress();
1325 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1326 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1327 message
.getTimestamp(),
1329 message
.getExpiresInSeconds(),
1330 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1332 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1335 long startTime
= System
.currentTimeMillis();
1336 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1337 return SendMessageResult
.success(recipient
,
1338 unidentifiedAccess
.isPresent(),
1340 System
.currentTimeMillis() - startTime
);
1341 } catch (UntrustedIdentityException e
) {
1342 account
.getSignalProtocolStore()
1343 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1345 TrustLevel
.UNTRUSTED
);
1346 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1350 private SendMessageResult
sendMessage(
1351 SignalServiceAddress address
, SignalServiceDataMessage message
1352 ) throws IOException
{
1353 SignalServiceMessageSender messageSender
= createMessageSender();
1356 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1357 } catch (UntrustedIdentityException e
) {
1358 account
.getSignalProtocolStore()
1359 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1361 TrustLevel
.UNTRUSTED
);
1362 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1366 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1367 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1368 account
.getSignalProtocolStore(),
1369 certificateValidator
);
1371 return cipher
.decrypt(envelope
);
1372 } catch (ProtocolUntrustedIdentityException e
) {
1373 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1374 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1376 account
.getSignalProtocolStore()
1377 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1378 identityException
.getUntrustedIdentity(),
1379 TrustLevel
.UNTRUSTED
);
1380 throw identityException
;
1382 throw new AssertionError(e
);
1386 private void handleEndSession(SignalServiceAddress source
) {
1387 account
.getSignalProtocolStore().deleteAllSessions(source
);
1390 private List
<HandleAction
> handleSignalServiceDataMessage(
1391 SignalServiceDataMessage message
,
1393 SignalServiceAddress source
,
1394 SignalServiceAddress destination
,
1395 boolean ignoreAttachments
1397 List
<HandleAction
> actions
= new ArrayList
<>();
1398 if (message
.getGroupContext().isPresent()) {
1399 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1400 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1401 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1402 GroupInfo group
= getGroup(groupId
);
1403 if (group
== null || group
instanceof GroupInfoV1
) {
1404 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1405 switch (groupInfo
.getType()) {
1407 if (groupV1
== null) {
1408 groupV1
= new GroupInfoV1(groupId
);
1411 if (groupInfo
.getAvatar().isPresent()) {
1412 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1413 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1416 if (groupInfo
.getName().isPresent()) {
1417 groupV1
.name
= groupInfo
.getName().get();
1420 if (groupInfo
.getMembers().isPresent()) {
1421 groupV1
.addMembers(groupInfo
.getMembers()
1424 .map(this::resolveSignalServiceAddress
)
1425 .collect(Collectors
.toSet()));
1428 account
.getGroupStore().updateGroup(groupV1
);
1432 if (groupV1
== null && !isSync
) {
1433 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1437 if (groupV1
!= null) {
1438 groupV1
.removeMember(source
);
1439 account
.getGroupStore().updateGroup(groupV1
);
1444 if (groupV1
!= null && !isSync
) {
1445 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1450 // Received a group v1 message for a v2 group
1453 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1454 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1455 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1457 getOrMigrateGroup(groupMasterKey
,
1458 groupContext
.getRevision(),
1459 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1463 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1464 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1465 handleEndSession(conversationPartnerAddress
);
1467 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1468 if (message
.getGroupContext().isPresent()) {
1469 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1470 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1471 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1472 if (group
!= null) {
1473 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1474 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1475 account
.getGroupStore().updateGroup(group
);
1478 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1479 // disappearing message timer already stored in the DecryptedGroup
1481 } else if (conversationPartnerAddress
!= null) {
1482 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1483 if (contact
== null) {
1484 contact
= new ContactInfo(conversationPartnerAddress
);
1486 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1487 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1488 account
.getContactStore().updateContact(contact
);
1492 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1493 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1494 downloadAttachment(attachment
);
1497 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1498 final ProfileKey profileKey
;
1500 profileKey
= new ProfileKey(message
.getProfileKey().get());
1501 } catch (InvalidInputException e
) {
1502 throw new AssertionError(e
);
1504 if (source
.matches(account
.getSelfAddress())) {
1505 this.account
.setProfileKey(profileKey
);
1507 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1509 if (message
.getPreviews().isPresent()) {
1510 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1511 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1512 if (preview
.getImage().isPresent()) {
1513 downloadAttachment(preview
.getImage().get());
1517 if (message
.getQuote().isPresent()) {
1518 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1520 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1521 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1522 if (thumbnail
!= null) {
1523 downloadAttachment(thumbnail
);
1527 if (message
.getSticker().isPresent()) {
1528 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1529 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1530 if (sticker
== null) {
1531 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1532 account
.getStickerStore().updateSticker(sticker
);
1538 private GroupInfoV2
getOrMigrateGroup(
1539 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1541 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1543 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1544 GroupInfo groupInfo
= getGroup(groupId
);
1545 final GroupInfoV2 groupInfoV2
;
1546 if (groupInfo
instanceof GroupInfoV1
) {
1547 // Received a v2 group message for a v1 group, we need to locally migrate the group
1548 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1549 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1550 logger
.info("Locally migrated group {} to group v2, id: {}",
1551 groupInfo
.getGroupId().toBase64(),
1552 groupInfoV2
.getGroupId().toBase64());
1553 } else if (groupInfo
instanceof GroupInfoV2
) {
1554 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1556 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1559 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1560 DecryptedGroup group
= null;
1561 if (signedGroupChange
!= null
1562 && groupInfoV2
.getGroup() != null
1563 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1564 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1566 if (group
== null) {
1567 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1569 if (group
!= null) {
1570 storeProfileKeysFromMembers(group
);
1571 final String avatar
= group
.getAvatar();
1572 if (avatar
!= null && !avatar
.isEmpty()) {
1573 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1576 groupInfoV2
.setGroup(group
);
1577 account
.getGroupStore().updateGroup(groupInfoV2
);
1583 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1584 for (DecryptedMember member
: group
.getMembersList()) {
1585 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1586 member
.getUuid().toByteArray()), null));
1588 account
.getProfileStore()
1589 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1590 } catch (InvalidInputException ignored
) {
1595 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1596 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1597 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1601 private void retryFailedReceivedMessage(
1602 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1604 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1605 if (envelope
== null) {
1608 SignalServiceContent content
= null;
1609 if (!envelope
.isReceipt()) {
1611 content
= decryptMessage(envelope
);
1612 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1614 } catch (Exception er
) {
1615 // All other errors are not recoverable, so delete the cached message
1616 cachedMessage
.delete();
1619 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1620 for (HandleAction action
: actions
) {
1622 action
.execute(this);
1623 } catch (Throwable e
) {
1624 logger
.warn("Message action failed.", e
);
1629 handler
.handleMessage(envelope
, content
, null);
1630 cachedMessage
.delete();
1633 public void receiveMessages(
1636 boolean returnOnTimeout
,
1637 boolean ignoreAttachments
,
1638 ReceiveMessageHandler handler
1639 ) throws IOException
{
1640 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1642 Set
<HandleAction
> queuedActions
= null;
1644 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1646 boolean hasCaughtUpWithOldMessages
= false;
1649 SignalServiceEnvelope envelope
;
1650 SignalServiceContent content
= null;
1651 Exception exception
= null;
1652 final CachedMessage
[] cachedMessage
= {null};
1654 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1655 // store message on disk, before acknowledging receipt to the server
1656 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1658 if (result
.isPresent()) {
1659 envelope
= result
.get();
1661 // Received indicator that server queue is empty
1662 hasCaughtUpWithOldMessages
= true;
1664 if (queuedActions
!= null) {
1665 for (HandleAction action
: queuedActions
) {
1667 action
.execute(this);
1668 } catch (Throwable e
) {
1669 logger
.warn("Message action failed.", e
);
1673 queuedActions
.clear();
1674 queuedActions
= null;
1677 // Continue to wait another timeout for new messages
1680 } catch (TimeoutException e
) {
1681 if (returnOnTimeout
) return;
1683 } catch (InvalidVersionException e
) {
1684 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1688 if (envelope
.hasSource()) {
1689 // Store uuid if we don't have it already
1690 SignalServiceAddress source
= envelope
.getSourceAddress();
1691 resolveSignalServiceAddress(source
);
1693 if (!envelope
.isReceipt()) {
1695 content
= decryptMessage(envelope
);
1696 } catch (Exception e
) {
1699 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1700 if (hasCaughtUpWithOldMessages
) {
1701 for (HandleAction action
: actions
) {
1703 action
.execute(this);
1704 } catch (Throwable e
) {
1705 logger
.warn("Message action failed.", e
);
1709 if (queuedActions
== null) {
1710 queuedActions
= new HashSet
<>();
1712 queuedActions
.addAll(actions
);
1716 if (isMessageBlocked(envelope
, content
)) {
1717 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1718 } else if (isNotAGroupMember(envelope
, content
)) {
1719 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1721 handler
.handleMessage(envelope
, content
, exception
);
1723 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1724 if (cachedMessage
[0] != null) {
1725 cachedMessage
[0].delete();
1731 private boolean isMessageBlocked(
1732 SignalServiceEnvelope envelope
, SignalServiceContent content
1734 SignalServiceAddress source
;
1735 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1736 source
= envelope
.getSourceAddress();
1737 } else if (content
!= null) {
1738 source
= content
.getSender();
1742 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1743 if (sourceContact
!= null && sourceContact
.blocked
) {
1747 if (content
!= null && content
.getDataMessage().isPresent()) {
1748 SignalServiceDataMessage message
= content
.getDataMessage().get();
1749 if (message
.getGroupContext().isPresent()) {
1750 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1751 GroupInfo group
= getGroup(groupId
);
1752 if (group
!= null && group
.isBlocked()) {
1760 private boolean isNotAGroupMember(
1761 SignalServiceEnvelope envelope
, SignalServiceContent content
1763 SignalServiceAddress source
;
1764 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1765 source
= envelope
.getSourceAddress();
1766 } else if (content
!= null) {
1767 source
= content
.getSender();
1772 if (content
!= null && content
.getDataMessage().isPresent()) {
1773 SignalServiceDataMessage message
= content
.getDataMessage().get();
1774 if (message
.getGroupContext().isPresent()) {
1775 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1776 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1777 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1781 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1782 GroupInfo group
= getGroup(groupId
);
1783 if (group
!= null && !group
.isMember(source
)) {
1791 private List
<HandleAction
> handleMessage(
1792 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1794 List
<HandleAction
> actions
= new ArrayList
<>();
1795 if (content
!= null) {
1796 final SignalServiceAddress sender
;
1797 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1798 sender
= envelope
.getSourceAddress();
1800 sender
= content
.getSender();
1802 // Store uuid if we don't have it already
1803 resolveSignalServiceAddress(sender
);
1805 if (content
.getDataMessage().isPresent()) {
1806 SignalServiceDataMessage message
= content
.getDataMessage().get();
1808 if (content
.isNeedsReceipt()) {
1809 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1812 actions
.addAll(handleSignalServiceDataMessage(message
,
1815 account
.getSelfAddress(),
1816 ignoreAttachments
));
1818 if (content
.getSyncMessage().isPresent()) {
1819 account
.setMultiDevice(true);
1820 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1821 if (syncMessage
.getSent().isPresent()) {
1822 SentTranscriptMessage message
= syncMessage
.getSent().get();
1823 final SignalServiceAddress destination
= message
.getDestination().orNull();
1824 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1828 ignoreAttachments
));
1830 if (syncMessage
.getRequest().isPresent()) {
1831 RequestMessage rm
= syncMessage
.getRequest().get();
1832 if (rm
.isContactsRequest()) {
1833 actions
.add(SendSyncContactsAction
.create());
1835 if (rm
.isGroupsRequest()) {
1836 actions
.add(SendSyncGroupsAction
.create());
1838 if (rm
.isBlockedListRequest()) {
1839 actions
.add(SendSyncBlockedListAction
.create());
1841 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1843 if (syncMessage
.getGroups().isPresent()) {
1844 File tmpFile
= null;
1846 tmpFile
= IOUtils
.createTempFile();
1847 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1848 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1850 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1852 while ((g
= s
.read()) != null) {
1853 GroupInfoV1 syncGroup
= account
.getGroupStore()
1854 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1855 if (syncGroup
!= null) {
1856 if (g
.getName().isPresent()) {
1857 syncGroup
.name
= g
.getName().get();
1859 syncGroup
.addMembers(g
.getMembers()
1861 .map(this::resolveSignalServiceAddress
)
1862 .collect(Collectors
.toSet()));
1863 if (!g
.isActive()) {
1864 syncGroup
.removeMember(account
.getSelfAddress());
1866 // Add ourself to the member set as it's marked as active
1867 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1869 syncGroup
.blocked
= g
.isBlocked();
1870 if (g
.getColor().isPresent()) {
1871 syncGroup
.color
= g
.getColor().get();
1874 if (g
.getAvatar().isPresent()) {
1875 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1877 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1878 syncGroup
.archived
= g
.isArchived();
1879 account
.getGroupStore().updateGroup(syncGroup
);
1883 } catch (Exception e
) {
1884 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1888 if (tmpFile
!= null) {
1890 Files
.delete(tmpFile
.toPath());
1891 } catch (IOException e
) {
1892 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1899 if (syncMessage
.getBlockedList().isPresent()) {
1900 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1901 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1902 setContactBlocked(resolveSignalServiceAddress(address
), true);
1904 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1906 .map(GroupId
::unknownVersion
)
1907 .collect(Collectors
.toSet())) {
1909 setGroupBlocked(groupId
, true);
1910 } catch (GroupNotFoundException e
) {
1911 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1912 groupId
.toBase64());
1916 if (syncMessage
.getContacts().isPresent()) {
1917 File tmpFile
= null;
1919 tmpFile
= IOUtils
.createTempFile();
1920 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1921 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1922 .asPointer(), tmpFile
)) {
1923 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1924 if (contactsMessage
.isComplete()) {
1925 account
.getContactStore().clear();
1928 while ((c
= s
.read()) != null) {
1929 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1930 account
.setProfileKey(c
.getProfileKey().get());
1932 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1933 ContactInfo contact
= account
.getContactStore().getContact(address
);
1934 if (contact
== null) {
1935 contact
= new ContactInfo(address
);
1937 if (c
.getName().isPresent()) {
1938 contact
.name
= c
.getName().get();
1940 if (c
.getColor().isPresent()) {
1941 contact
.color
= c
.getColor().get();
1943 if (c
.getProfileKey().isPresent()) {
1944 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1946 if (c
.getVerified().isPresent()) {
1947 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1948 account
.getSignalProtocolStore()
1949 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1950 verifiedMessage
.getIdentityKey(),
1951 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1953 if (c
.getExpirationTimer().isPresent()) {
1954 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1956 contact
.blocked
= c
.isBlocked();
1957 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1958 contact
.archived
= c
.isArchived();
1959 account
.getContactStore().updateContact(contact
);
1961 if (c
.getAvatar().isPresent()) {
1962 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
1966 } catch (Exception e
) {
1967 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1971 if (tmpFile
!= null) {
1973 Files
.delete(tmpFile
.toPath());
1974 } catch (IOException e
) {
1975 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1982 if (syncMessage
.getVerified().isPresent()) {
1983 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1984 account
.getSignalProtocolStore()
1985 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
1986 verifiedMessage
.getIdentityKey(),
1987 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1989 if (syncMessage
.getStickerPackOperations().isPresent()) {
1990 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
1992 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
1993 if (!m
.getPackId().isPresent()) {
1996 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
1997 if (sticker
== null) {
1998 if (!m
.getPackKey().isPresent()) {
2001 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2003 sticker
.setInstalled(!m
.getType().isPresent()
2004 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2005 account
.getStickerStore().updateSticker(sticker
);
2008 if (syncMessage
.getFetchType().isPresent()) {
2009 switch (syncMessage
.getFetchType().get()) {
2011 getRecipientProfile(getSelfAddress(), true);
2012 case STORAGE_MANIFEST
:
2016 if (syncMessage
.getConfiguration().isPresent()) {
2024 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2026 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2027 } catch (IOException e
) {
2028 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2032 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2034 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2035 } catch (IOException e
) {
2036 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2040 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2042 avatarStore
.storeGroupAvatar(groupId
,
2043 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2044 } catch (IOException e
) {
2045 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2049 private void downloadProfileAvatar(
2050 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2053 avatarStore
.storeProfileAvatar(address
,
2054 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2055 } catch (Throwable e
) {
2056 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2060 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2061 return attachmentStore
.getAttachmentFile(attachmentId
);
2064 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2065 if (!attachment
.isPointer()) {
2066 logger
.warn("Invalid state, can't store an attachment stream.");
2069 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2070 if (pointer
.getPreview().isPresent()) {
2071 final byte[] preview
= pointer
.getPreview().get();
2073 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2074 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2075 } catch (IOException e
) {
2076 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2081 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2082 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2083 } catch (IOException e
) {
2084 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2088 private void retrieveGroupV2Avatar(
2089 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2090 ) throws IOException
{
2091 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2093 File tmpFile
= IOUtils
.createTempFile();
2094 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2096 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2097 byte[] encryptedData
= IOUtils
.readFully(input
);
2099 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2100 outputStream
.write(decryptedData
);
2103 Files
.delete(tmpFile
.toPath());
2104 } catch (IOException e
) {
2105 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2112 private void retrieveProfileAvatar(
2113 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2114 ) throws IOException
{
2115 File tmpFile
= IOUtils
.createTempFile();
2116 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2119 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2120 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2121 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2124 Files
.delete(tmpFile
.toPath());
2125 } catch (IOException e
) {
2126 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2133 private void retrieveAttachment(
2134 final SignalServiceAttachment attachment
, final OutputStream outputStream
2135 ) throws IOException
{
2136 if (attachment
.isPointer()) {
2137 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2138 retrieveAttachmentPointer(pointer
, outputStream
);
2140 SignalServiceAttachmentStream stream
= attachment
.asStream();
2141 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2145 private void retrieveAttachmentPointer(
2146 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2147 ) throws IOException
{
2148 File tmpFile
= IOUtils
.createTempFile();
2149 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2150 IOUtils
.copyStream(input
, outputStream
);
2151 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2152 throw new IOException(e
);
2155 Files
.delete(tmpFile
.toPath());
2156 } catch (IOException e
) {
2157 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2164 private InputStream
retrieveAttachmentAsStream(
2165 SignalServiceAttachmentPointer pointer
, File tmpFile
2166 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2167 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2170 void sendGroups() throws IOException
, UntrustedIdentityException
{
2171 File groupsFile
= IOUtils
.createTempFile();
2174 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2175 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2176 for (GroupInfo
record : getGroups()) {
2177 if (record instanceof GroupInfoV1
) {
2178 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2179 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2180 Optional
.fromNullable(groupInfo
.name
),
2181 new ArrayList
<>(groupInfo
.getMembers()),
2182 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2183 groupInfo
.isMember(account
.getSelfAddress()),
2184 Optional
.of(groupInfo
.messageExpirationTime
),
2185 Optional
.fromNullable(groupInfo
.color
),
2187 Optional
.fromNullable(groupInfo
.inboxPosition
),
2188 groupInfo
.archived
));
2193 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2194 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2195 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2196 .withStream(groupsFileStream
)
2197 .withContentType("application/octet-stream")
2198 .withLength(groupsFile
.length())
2201 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2206 Files
.delete(groupsFile
.toPath());
2207 } catch (IOException e
) {
2208 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2213 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2214 File contactsFile
= IOUtils
.createTempFile();
2217 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2218 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2219 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2220 VerifiedMessage verifiedMessage
= null;
2221 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2222 if (currentIdentity
!= null) {
2223 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2224 currentIdentity
.getIdentityKey(),
2225 currentIdentity
.getTrustLevel().toVerifiedState(),
2226 currentIdentity
.getDateAdded().getTime());
2229 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2230 out
.write(new DeviceContact(record.getAddress(),
2231 Optional
.fromNullable(record.name
),
2232 createContactAvatarAttachment(record.getAddress()),
2233 Optional
.fromNullable(record.color
),
2234 Optional
.fromNullable(verifiedMessage
),
2235 Optional
.fromNullable(profileKey
),
2237 Optional
.of(record.messageExpirationTime
),
2238 Optional
.fromNullable(record.inboxPosition
),
2242 if (account
.getProfileKey() != null) {
2243 // Send our own profile key as well
2244 out
.write(new DeviceContact(account
.getSelfAddress(),
2249 Optional
.of(account
.getProfileKey()),
2257 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2258 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2259 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2260 .withStream(contactsFileStream
)
2261 .withContentType("application/octet-stream")
2262 .withLength(contactsFile
.length())
2265 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2270 Files
.delete(contactsFile
.toPath());
2271 } catch (IOException e
) {
2272 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2277 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2278 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2279 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2280 if (record.blocked
) {
2281 addresses
.add(record.getAddress());
2284 List
<byte[]> groupIds
= new ArrayList
<>();
2285 for (GroupInfo
record : getGroups()) {
2286 if (record.isBlocked()) {
2287 groupIds
.add(record.getGroupId().serialize());
2290 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2293 private void sendVerifiedMessage(
2294 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2295 ) throws IOException
, UntrustedIdentityException
{
2296 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2298 trustLevel
.toVerifiedState(),
2299 System
.currentTimeMillis());
2300 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2303 public List
<ContactInfo
> getContacts() {
2304 return account
.getContactStore().getContacts();
2307 public ContactInfo
getContact(String number
) {
2308 return account
.getContactStore().getContact(Utils
.getSignalServiceAddressFromIdentifier(number
));
2311 public GroupInfo
getGroup(GroupId groupId
) {
2312 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2313 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2314 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2315 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2316 account
.getGroupStore().updateGroup(group
);
2321 public List
<IdentityInfo
> getIdentities() {
2322 return account
.getSignalProtocolStore().getIdentities();
2325 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2326 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2330 * Trust this the identity with this fingerprint
2332 * @param name username of the identity
2333 * @param fingerprint Fingerprint
2335 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2336 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2337 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2341 for (IdentityInfo id
: ids
) {
2342 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2346 account
.getSignalProtocolStore()
2347 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2349 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2350 } catch (IOException
| UntrustedIdentityException e
) {
2351 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2360 * Trust this the identity with this safety number
2362 * @param name username of the identity
2363 * @param safetyNumber Safety number
2365 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2366 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2367 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2371 for (IdentityInfo id
: ids
) {
2372 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2376 account
.getSignalProtocolStore()
2377 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2379 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2380 } catch (IOException
| UntrustedIdentityException e
) {
2381 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2390 * Trust all keys of this identity without verification
2392 * @param name username of the identity
2394 public boolean trustIdentityAllKeys(String name
) {
2395 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2396 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2400 for (IdentityInfo id
: ids
) {
2401 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2402 account
.getSignalProtocolStore()
2403 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2405 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2406 } catch (IOException
| UntrustedIdentityException e
) {
2407 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2415 public String
computeSafetyNumber(
2416 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2418 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2419 account
.getSelfAddress(),
2420 getIdentityKeyPair().getPublicKey(),
2425 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2426 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2428 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2429 return resolveSignalServiceAddress(canonicalizedNumber
);
2432 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2433 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2435 return resolveSignalServiceAddress(address
);
2438 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2439 if (address
.matches(account
.getSelfAddress())) {
2440 return account
.getSelfAddress();
2443 return account
.getRecipientStore().resolveServiceAddress(address
);
2447 public void close() throws IOException
{
2451 void close(boolean closeAccount
) throws IOException
{
2452 if (messagePipe
!= null) {
2453 messagePipe
.shutdown();
2457 if (unidentifiedMessagePipe
!= null) {
2458 unidentifiedMessagePipe
.shutdown();
2459 unidentifiedMessagePipe
= null;
2462 if (closeAccount
&& account
!= null) {
2468 public interface ReceiveMessageHandler
{
2470 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);