2 Copyright (C) 2015-2021 AsamK and contributors
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.signal
.manager
.groups
.GroupId
;
20 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
21 import org
.asamk
.signal
.manager
.groups
.GroupIdV2
;
22 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
23 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
24 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
25 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
26 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
27 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
28 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
29 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
30 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
31 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactInfo
;
32 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
33 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
34 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
35 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
36 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfile
;
37 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfileEntry
;
38 import org
.asamk
.signal
.manager
.storage
.protocol
.IdentityInfo
;
39 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
40 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
41 import org
.asamk
.signal
.manager
.util
.IOUtils
;
42 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
43 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
44 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
45 import org
.asamk
.signal
.manager
.util
.Utils
;
46 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
47 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
48 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
49 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
50 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
51 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
52 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
53 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
54 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
56 import org
.signal
.libsignal
.metadata
.SelfSendException
;
57 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
58 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
59 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
60 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroupJoinInfo
;
61 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedMember
;
62 import org
.signal
.zkgroup
.InvalidInputException
;
63 import org
.signal
.zkgroup
.VerificationFailedException
;
64 import org
.signal
.zkgroup
.auth
.AuthCredentialResponse
;
65 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
66 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
67 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
68 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
69 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
70 import org
.slf4j
.Logger
;
71 import org
.slf4j
.LoggerFactory
;
72 import org
.whispersystems
.libsignal
.IdentityKey
;
73 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
74 import org
.whispersystems
.libsignal
.InvalidKeyException
;
75 import org
.whispersystems
.libsignal
.InvalidMessageException
;
76 import org
.whispersystems
.libsignal
.InvalidVersionException
;
77 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
78 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
79 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
80 import org
.whispersystems
.libsignal
.util
.Pair
;
81 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
82 import org
.whispersystems
.signalservice
.api
.KeyBackupService
;
83 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
84 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
85 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
86 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
87 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
88 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
89 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
90 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
91 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
92 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
93 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
94 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
95 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
96 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
106 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
107 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceStickerManifestUpload
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
121 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
122 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
123 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
124 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
125 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
126 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
127 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
128 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
129 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
130 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
131 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
132 import org
.whispersystems
.signalservice
.internal
.configuration
.SignalServiceConfiguration
;
133 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
134 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
135 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
136 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
137 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
138 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
139 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
140 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
142 import java
.io
.Closeable
;
144 import java
.io
.FileInputStream
;
145 import java
.io
.FileOutputStream
;
146 import java
.io
.IOException
;
147 import java
.io
.InputStream
;
148 import java
.io
.OutputStream
;
150 import java
.net
.URISyntaxException
;
151 import java
.net
.URLEncoder
;
152 import java
.nio
.charset
.StandardCharsets
;
153 import java
.nio
.file
.Files
;
154 import java
.security
.SignatureException
;
155 import java
.util
.ArrayList
;
156 import java
.util
.Arrays
;
157 import java
.util
.Collection
;
158 import java
.util
.Date
;
159 import java
.util
.HashMap
;
160 import java
.util
.HashSet
;
161 import java
.util
.List
;
162 import java
.util
.Map
;
163 import java
.util
.Set
;
164 import java
.util
.UUID
;
165 import java
.util
.concurrent
.ExecutorService
;
166 import java
.util
.concurrent
.TimeUnit
;
167 import java
.util
.concurrent
.TimeoutException
;
168 import java
.util
.stream
.Collectors
;
170 import static org
.asamk
.signal
.manager
.ServiceConfig
.CDS_MRENCLAVE
;
171 import static org
.asamk
.signal
.manager
.ServiceConfig
.capabilities
;
172 import static org
.asamk
.signal
.manager
.ServiceConfig
.getIasKeyStore
;
174 public class Manager
implements Closeable
{
176 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
178 private final CertificateValidator certificateValidator
= new CertificateValidator(ServiceConfig
.getUnidentifiedSenderTrustRoot());
180 private final SignalServiceConfiguration serviceConfiguration
;
181 private final String userAgent
;
183 private SignalAccount account
;
184 private final SignalServiceAccountManager accountManager
;
185 private final GroupsV2Api groupsV2Api
;
186 private final GroupsV2Operations groupsV2Operations
;
187 private final SignalServiceMessageReceiver messageReceiver
;
188 private final ClientZkProfileOperations clientZkProfileOperations
;
190 private SignalServiceMessagePipe messagePipe
= null;
191 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
193 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
194 private final ProfileHelper profileHelper
;
195 private final GroupHelper groupHelper
;
196 private final PinHelper pinHelper
;
197 private final AvatarStore avatarStore
;
198 private final AttachmentStore attachmentStore
;
201 SignalAccount account
,
202 PathConfig pathConfig
,
203 SignalServiceConfiguration serviceConfiguration
,
206 this.account
= account
;
207 this.serviceConfiguration
= serviceConfiguration
;
208 this.userAgent
= userAgent
;
209 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
210 serviceConfiguration
)) : null;
211 final SleepTimer timer
= new UptimeSleepTimer();
212 this.accountManager
= new SignalServiceAccountManager(serviceConfiguration
,
213 new DynamicCredentialsProvider(account
.getUuid(),
214 account
.getUsername(),
215 account
.getPassword(),
216 account
.getSignalingKey(),
217 account
.getDeviceId()),
221 this.groupsV2Api
= accountManager
.getGroupsV2Api();
222 final KeyBackupService keyBackupService
= ServiceConfig
.createKeyBackupService(accountManager
);
223 this.pinHelper
= new PinHelper(keyBackupService
);
224 this.clientZkProfileOperations
= capabilities
.isGv2() ? ClientZkOperations
.create(serviceConfiguration
)
225 .getProfileOperations() : null;
226 this.messageReceiver
= new SignalServiceMessageReceiver(serviceConfiguration
,
228 account
.getUsername(),
229 account
.getPassword(),
230 account
.getDeviceId(),
231 account
.getSignalingKey(),
235 clientZkProfileOperations
);
237 this.account
.setResolver(this::resolveSignalServiceAddress
);
239 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
240 account
.getProfileStore()::getProfileKey
,
241 this::getRecipientProfile
,
242 this::getSenderCertificate
);
243 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
244 unidentifiedAccessHelper
::getAccessFor
,
245 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
246 () -> messageReceiver
);
247 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
248 this::getRecipientProfile
,
249 account
::getSelfAddress
,
252 this::getGroupAuthForToday
);
253 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
254 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
257 public String
getUsername() {
258 return account
.getUsername();
261 public SignalServiceAddress
getSelfAddress() {
262 return account
.getSelfAddress();
265 private IdentityKeyPair
getIdentityKeyPair() {
266 return account
.getSignalProtocolStore().getIdentityKeyPair();
269 public int getDeviceId() {
270 return account
.getDeviceId();
273 public static Manager
init(
274 String username
, File settingsPath
, SignalServiceConfiguration serviceConfiguration
, String userAgent
275 ) throws IOException
, NotRegisteredException
{
276 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
278 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
279 throw new NotRegisteredException();
282 SignalAccount account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
284 if (!account
.isRegistered()) {
285 throw new NotRegisteredException();
288 return new Manager(account
, pathConfig
, serviceConfiguration
, userAgent
);
291 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
292 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
293 final File dataPath
= pathConfig
.getDataPath();
294 final File
[] files
= dataPath
.listFiles();
300 return Arrays
.stream(files
)
301 .filter(File
::isFile
)
303 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
304 .collect(Collectors
.toList());
307 public void checkAccountState() throws IOException
{
308 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
312 if (account
.getUuid() == null) {
313 account
.setUuid(accountManager
.getOwnUuid());
316 updateAccountAttributes();
320 * This is used for checking a set of phone numbers for registration on Signal
322 * @param numbers The set of phone number in question
323 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
324 * @throws IOException if its unable to get the contacts to check if they're registered
326 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
327 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
328 Map
<String
, UUID
> contactDetails
= getRegisteredUsers(numbers
);
330 Set
<String
> registeredUsers
= contactDetails
.keySet();
332 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
335 public void updateAccountAttributes() throws IOException
{
336 accountManager
.setAccountAttributes(account
.getSignalingKey(),
337 account
.getSignalProtocolStore().getLocalRegistrationId(),
339 // set legacy pin only if no KBS master key is set
340 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
341 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
342 account
.getSelfUnidentifiedAccessKey(),
343 account
.isUnrestrictedUnidentifiedAccess(),
345 account
.isDiscoverableByPhoneNumber());
349 * @param avatar if avatar is null the image from the local avatar store is used (if present),
350 * if it's Optional.absent(), the avatar will be removed
352 public void setProfile(String name
, Optional
<File
> avatar
) throws IOException
{
353 try (final StreamDetails streamDetails
= avatar
== null
354 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
355 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
356 accountManager
.setVersionedProfile(account
.getUuid(), account
.getProfileKey(), name
, streamDetails
);
359 if (avatar
!= null) {
360 if (avatar
.isPresent()) {
361 avatarStore
.storeProfileAvatar(getSelfAddress(),
362 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
364 avatarStore
.deleteProfileAvatar(getSelfAddress());
369 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
370 } catch (UntrustedIdentityException ignored
) {
374 public void unregister() throws IOException
{
375 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
376 // If this is the master device, other users can't send messages to this number anymore.
377 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
378 accountManager
.setGcmId(Optional
.absent());
380 account
.setRegistered(false);
384 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
385 List
<DeviceInfo
> devices
= accountManager
.getDevices();
386 account
.setMultiDevice(devices
.size() > 1);
391 public void removeLinkedDevices(int deviceId
) throws IOException
{
392 accountManager
.removeDevice(deviceId
);
393 List
<DeviceInfo
> devices
= accountManager
.getDevices();
394 account
.setMultiDevice(devices
.size() > 1);
398 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
399 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
401 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
404 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
405 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
406 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
408 accountManager
.addDevice(deviceIdentifier
,
411 Optional
.of(account
.getProfileKey().serialize()),
413 account
.setMultiDevice(true);
417 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
418 if (!account
.isMasterDevice()) {
419 throw new RuntimeException("Only master device can set a PIN");
421 if (pin
.isPresent()) {
422 final MasterKey masterKey
= account
.getPinMasterKey() != null
423 ? account
.getPinMasterKey()
424 : KeyUtils
.createMasterKey();
426 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
428 account
.setRegistrationLockPin(pin
.get());
429 account
.setPinMasterKey(masterKey
);
431 // Remove legacy registration lock
432 accountManager
.removeRegistrationLockV1();
435 pinHelper
.removeRegistrationLockPin();
437 account
.setRegistrationLockPin(null);
438 account
.setPinMasterKey(null);
443 void refreshPreKeys() throws IOException
{
444 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
445 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
446 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
448 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
451 private List
<PreKeyRecord
> generatePreKeys() {
452 final int offset
= account
.getPreKeyIdOffset();
454 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
455 account
.addPreKeys(records
);
461 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
462 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
464 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
465 account
.addSignedPreKey(record);
471 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
472 if (messagePipe
== null) {
473 messagePipe
= messageReceiver
.createMessagePipe();
478 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
479 if (unidentifiedMessagePipe
== null) {
480 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
482 return unidentifiedMessagePipe
;
485 private SignalServiceMessageSender
createMessageSender() {
486 final ExecutorService executor
= null;
487 return new SignalServiceMessageSender(serviceConfiguration
,
489 account
.getUsername(),
490 account
.getPassword(),
491 account
.getDeviceId(),
492 account
.getSignalProtocolStore(),
494 account
.isMultiDevice(),
495 Optional
.fromNullable(messagePipe
),
496 Optional
.fromNullable(unidentifiedMessagePipe
),
498 clientZkProfileOperations
,
500 ServiceConfig
.MAX_ENVELOPE_SIZE
);
503 private SignalProfile
getRecipientProfile(
504 SignalServiceAddress address
506 return getRecipientProfile(address
, false);
509 private SignalProfile
getRecipientProfile(
510 SignalServiceAddress address
, boolean force
512 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
513 if (profileEntry
== null) {
516 long now
= new Date().getTime();
517 // Profiles are cached for 24h before retrieving them again
518 if (!profileEntry
.isRequestPending() && (
520 || profileEntry
.getProfile() == null
521 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
523 profileEntry
.setRequestPending(true);
524 final SignalServiceProfile encryptedProfile
;
526 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
528 } catch (IOException e
) {
529 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
532 profileEntry
.setRequestPending(false);
535 final ProfileKey profileKey
= profileEntry
.getProfileKey();
536 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
537 account
.getProfileStore()
538 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
541 return profileEntry
.getProfile();
544 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
545 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
546 if (profileEntry
== null) {
549 if (profileEntry
.getProfileKeyCredential() == null) {
550 ProfileAndCredential profileAndCredential
;
552 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
553 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
554 } catch (IOException e
) {
555 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
559 long now
= new Date().getTime();
560 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
561 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
562 profileEntry
.getProfileKey(),
563 profileAndCredential
.getProfile());
564 account
.getProfileStore()
565 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
566 return profileKeyCredential
;
568 return profileEntry
.getProfileKeyCredential();
571 private SignalProfile
decryptProfileAndDownloadAvatar(
572 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
574 if (encryptedProfile
.getAvatar() != null) {
575 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
578 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
581 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
582 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
583 if (streamDetails
== null) {
584 return Optional
.absent();
587 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
590 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
591 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
592 if (streamDetails
== null) {
593 return Optional
.absent();
596 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
599 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
600 GroupInfo g
= getGroup(groupId
);
602 throw new GroupNotFoundException(groupId
);
604 if (!g
.isMember(account
.getSelfAddress())) {
605 throw new NotAGroupMemberException(groupId
, g
.getTitle());
610 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
611 GroupInfo g
= getGroup(groupId
);
613 throw new GroupNotFoundException(groupId
);
615 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
616 throw new NotAGroupMemberException(groupId
, g
.getTitle());
621 public List
<GroupInfo
> getGroups() {
622 return account
.getGroupStore().getGroups();
625 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
626 String messageText
, List
<String
> attachments
, GroupId groupId
627 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
628 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
629 .withBody(messageText
);
630 if (attachments
!= null) {
631 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
634 return sendGroupMessage(messageBuilder
, groupId
);
637 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
638 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
639 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
640 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
642 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
643 targetSentTimestamp
);
644 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
645 .withReaction(reaction
);
647 return sendGroupMessage(messageBuilder
, groupId
);
650 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
651 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
652 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
653 final GroupInfo g
= getGroupForSending(groupId
);
655 GroupUtils
.setGroupContext(messageBuilder
, g
);
656 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
658 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
661 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
662 SignalServiceDataMessage
.Builder messageBuilder
;
664 final GroupInfo g
= getGroupForUpdating(groupId
);
665 if (g
instanceof GroupInfoV1
) {
666 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
667 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
668 .withId(groupId
.serialize())
670 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
671 groupInfoV1
.removeMember(account
.getSelfAddress());
672 account
.getGroupStore().updateGroup(groupInfoV1
);
674 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
675 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
676 groupInfoV2
.setGroup(groupGroupChangePair
.first());
677 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
678 account
.getGroupStore().updateGroup(groupInfoV2
);
681 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
684 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
685 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
686 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
687 return sendUpdateGroupMessage(groupId
,
689 members
== null ?
null : getSignalServiceAddresses(members
),
693 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
694 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
695 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
697 SignalServiceDataMessage
.Builder messageBuilder
;
698 if (groupId
== null) {
700 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
701 members
== null ? List
.of() : members
,
704 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
705 gv1
.addMembers(List
.of(account
.getSelfAddress()));
706 updateGroupV1(gv1
, name
, members
, avatarFile
);
707 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
710 if (avatarFile
!= null) {
711 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
712 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
714 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
718 GroupInfo group
= getGroupForUpdating(groupId
);
719 if (group
instanceof GroupInfoV2
) {
720 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
722 Pair
<Long
, List
<SendMessageResult
>> result
= null;
723 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
724 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
725 result
= sendUpdateGroupMessage(groupInfoV2
,
726 groupGroupChangePair
.first(),
727 groupGroupChangePair
.second());
730 if (members
!= null) {
731 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
732 newMembers
.removeAll(group
.getMembers()
734 .map(this::resolveSignalServiceAddress
)
735 .collect(Collectors
.toSet()));
736 if (newMembers
.size() > 0) {
737 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
739 result
= sendUpdateGroupMessage(groupInfoV2
,
740 groupGroupChangePair
.first(),
741 groupGroupChangePair
.second());
744 if (result
== null || name
!= null || avatarFile
!= null) {
745 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
748 if (avatarFile
!= null) {
749 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
750 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
752 result
= sendUpdateGroupMessage(groupInfoV2
,
753 groupGroupChangePair
.first(),
754 groupGroupChangePair
.second());
757 return new Pair
<>(group
.getGroupId(), result
.second());
759 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
760 updateGroupV1(gv1
, name
, members
, avatarFile
);
761 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
766 account
.getGroupStore().updateGroup(g
);
768 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
769 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
770 return new Pair
<>(g
.getGroupId(), result
.second());
773 private void updateGroupV1(
776 final Collection
<SignalServiceAddress
> members
,
777 final File avatarFile
778 ) throws IOException
{
783 if (members
!= null) {
784 final Set
<String
> newE164Members
= new HashSet
<>();
785 for (SignalServiceAddress member
: members
) {
786 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
789 newE164Members
.add(member
.getNumber().get());
792 final Map
<String
, UUID
> registeredUsers
= getRegisteredUsers(newE164Members
);
793 if (registeredUsers
.size() != newE164Members
.size()) {
794 // Some of the new members are not registered on Signal
795 newE164Members
.removeAll(registeredUsers
.keySet());
796 throw new IOException("Failed to add members "
797 + String
.join(", ", newE164Members
)
798 + " to group: Not registered on Signal");
801 g
.addMembers(members
);
804 if (avatarFile
!= null) {
805 avatarStore
.storeGroupAvatar(g
.getGroupId(),
806 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
810 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
811 GroupInviteLinkUrl inviteLinkUrl
812 ) throws IOException
, GroupLinkNotActiveException
{
813 return sendJoinGroupMessage(inviteLinkUrl
);
816 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
817 GroupInviteLinkUrl inviteLinkUrl
818 ) throws IOException
, GroupLinkNotActiveException
{
819 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
820 inviteLinkUrl
.getPassword());
821 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
822 inviteLinkUrl
.getPassword(),
824 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
825 groupJoinInfo
.getRevision() + 1,
826 groupChange
.toByteArray());
828 if (group
.getGroup() == null) {
829 // Only requested member, can't send update to group members
830 return new Pair
<>(group
.getGroupId(), List
.of());
833 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
835 return new Pair
<>(group
.getGroupId(), result
.second());
838 private static int currentTimeDays() {
839 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
842 private GroupsV2AuthorizationString
getGroupAuthForToday(
843 final GroupSecretParams groupSecretParams
844 ) throws IOException
{
845 final int today
= currentTimeDays();
846 // Returns credentials for the next 7 days
847 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
848 // TODO cache credentials until they expire
849 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
851 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
854 authCredentialResponse
);
855 } catch (VerificationFailedException e
) {
856 throw new IOException(e
);
860 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
861 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
862 ) throws IOException
{
863 group
.setGroup(newDecryptedGroup
);
864 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
865 groupChange
.toByteArray());
866 account
.getGroupStore().updateGroup(group
);
867 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
870 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
871 GroupIdV1 groupId
, SignalServiceAddress recipient
872 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
874 GroupInfo group
= getGroupForSending(groupId
);
875 if (!(group
instanceof GroupInfoV1
)) {
876 throw new RuntimeException("Received an invalid group request for a v2 group!");
878 g
= (GroupInfoV1
) group
;
880 if (!g
.isMember(recipient
)) {
881 throw new NotAGroupMemberException(groupId
, g
.name
);
884 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
886 // Send group message only to the recipient who requested it
887 return sendMessage(messageBuilder
, List
.of(recipient
));
890 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
891 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
892 .withId(g
.getGroupId().serialize())
894 .withMembers(new ArrayList
<>(g
.getMembers()));
897 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
898 if (attachment
.isPresent()) {
899 group
.withAvatar(attachment
.get());
901 } catch (IOException e
) {
902 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
905 return SignalServiceDataMessage
.newBuilder()
906 .asGroupMessage(group
.build())
907 .withExpiration(g
.getMessageExpirationTime());
910 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
911 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
912 .withRevision(g
.getGroup().getRevision())
913 .withSignedGroupChange(signedGroupChange
);
914 return SignalServiceDataMessage
.newBuilder()
915 .asGroupMessage(group
.build())
916 .withExpiration(g
.getMessageExpirationTime());
919 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
920 GroupIdV1 groupId
, SignalServiceAddress recipient
921 ) throws IOException
{
922 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
923 .withId(groupId
.serialize());
925 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
926 .asGroupMessage(group
.build());
928 // Send group info request message to the recipient who sent us a message with this groupId
929 return sendMessage(messageBuilder
, List
.of(recipient
));
933 SignalServiceAddress remoteAddress
, long messageId
934 ) throws IOException
, UntrustedIdentityException
{
935 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
937 System
.currentTimeMillis());
939 createMessageSender().sendReceipt(remoteAddress
,
940 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
944 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
945 String messageText
, List
<String
> attachments
, List
<String
> recipients
946 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
947 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
948 .withBody(messageText
);
949 if (attachments
!= null) {
950 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
952 // Upload attachments here, so we only upload once even for multiple recipients
953 SignalServiceMessageSender messageSender
= createMessageSender();
954 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
955 for (SignalServiceAttachment attachment
: attachmentStreams
) {
956 if (attachment
.isStream()) {
957 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
958 } else if (attachment
.isPointer()) {
959 attachmentPointers
.add(attachment
.asPointer());
963 messageBuilder
.withAttachments(attachmentPointers
);
965 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
968 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
969 String messageText
, List
<String
> attachments
970 ) throws IOException
, AttachmentInvalidException
{
971 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
972 .withBody(messageText
);
973 if (attachments
!= null) {
974 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
976 return sendSelfMessage(messageBuilder
);
979 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
980 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
981 ) throws IOException
, InvalidNumberException
{
982 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
984 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
985 targetSentTimestamp
);
986 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
987 .withReaction(reaction
);
988 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
991 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
992 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
994 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
996 return sendMessage(messageBuilder
, signalServiceAddresses
);
997 } catch (Exception e
) {
998 for (SignalServiceAddress address
: signalServiceAddresses
) {
999 handleEndSession(address
);
1006 public String
getContactName(String number
) throws InvalidNumberException
{
1007 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1008 if (contact
== null) {
1011 return contact
.name
;
1015 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1016 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1017 ContactInfo contact
= account
.getContactStore().getContact(address
);
1018 if (contact
== null) {
1019 contact
= new ContactInfo(address
);
1021 contact
.name
= name
;
1022 account
.getContactStore().updateContact(contact
);
1026 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1027 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1030 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1031 ContactInfo contact
= account
.getContactStore().getContact(address
);
1032 if (contact
== null) {
1033 contact
= new ContactInfo(address
);
1035 contact
.blocked
= blocked
;
1036 account
.getContactStore().updateContact(contact
);
1040 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1041 GroupInfo group
= getGroup(groupId
);
1042 if (group
== null) {
1043 throw new GroupNotFoundException(groupId
);
1046 group
.setBlocked(blocked
);
1047 account
.getGroupStore().updateGroup(group
);
1052 * Change the expiration timer for a contact
1054 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1055 ContactInfo contact
= account
.getContactStore().getContact(address
);
1056 contact
.messageExpirationTime
= messageExpirationTimer
;
1057 account
.getContactStore().updateContact(contact
);
1058 sendExpirationTimerUpdate(address
);
1062 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1063 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1064 .asExpirationUpdate();
1065 sendMessage(messageBuilder
, List
.of(address
));
1069 * Change the expiration timer for a contact
1071 public void setExpirationTimer(
1072 String number
, int messageExpirationTimer
1073 ) throws IOException
, InvalidNumberException
{
1074 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1075 setExpirationTimer(address
, messageExpirationTimer
);
1079 * Change the expiration timer for a group
1081 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1082 GroupInfo g
= getGroup(groupId
);
1083 if (g
instanceof GroupInfoV1
) {
1084 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1085 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1086 account
.getGroupStore().updateGroup(groupInfoV1
);
1088 throw new RuntimeException("TODO Not implemented!");
1093 * Upload the sticker pack from path.
1095 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1096 * @return if successful, returns the URL to install the sticker pack in the signal app
1098 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1099 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1101 SignalServiceMessageSender messageSender
= createMessageSender();
1103 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1104 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1106 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1107 account
.getStickerStore().updateSticker(sticker
);
1111 return new URI("https",
1114 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1115 Hex
.toStringCondensed(packKey
),
1116 StandardCharsets
.UTF_8
)).toString();
1117 } catch (URISyntaxException e
) {
1118 throw new AssertionError(e
);
1122 void requestSyncGroups() throws IOException
{
1123 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1124 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1126 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1128 sendSyncMessage(message
);
1129 } catch (UntrustedIdentityException e
) {
1130 throw new AssertionError(e
);
1134 void requestSyncContacts() throws IOException
{
1135 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1136 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1138 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1140 sendSyncMessage(message
);
1141 } catch (UntrustedIdentityException e
) {
1142 throw new AssertionError(e
);
1146 void requestSyncBlocked() throws IOException
{
1147 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1148 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1150 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1152 sendSyncMessage(message
);
1153 } catch (UntrustedIdentityException e
) {
1154 throw new AssertionError(e
);
1158 void requestSyncConfiguration() throws IOException
{
1159 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1160 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1162 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1164 sendSyncMessage(message
);
1165 } catch (UntrustedIdentityException e
) {
1166 throw new AssertionError(e
);
1170 private byte[] getSenderCertificate() {
1171 // TODO support UUID capable sender certificates
1172 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1175 certificate
= accountManager
.getSenderCertificate();
1176 } catch (IOException e
) {
1177 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1180 // TODO cache for a day
1184 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1185 SignalServiceMessageSender messageSender
= createMessageSender();
1187 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1188 } catch (UntrustedIdentityException e
) {
1189 account
.getSignalProtocolStore()
1190 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1192 TrustLevel
.UNTRUSTED
);
1197 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1198 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1199 final Set
<SignalServiceAddress
> addressesMissingUuid
= new HashSet
<>();
1201 for (String number
: numbers
) {
1202 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1203 if (resolvedAddress
.getUuid().isPresent()) {
1204 signalServiceAddresses
.add(resolvedAddress
);
1206 addressesMissingUuid
.add(resolvedAddress
);
1210 final Set
<String
> numbersMissingUuid
= addressesMissingUuid
.stream()
1211 .map(a
-> a
.getNumber().get())
1212 .collect(Collectors
.toSet());
1213 Map
<String
, UUID
> registeredUsers
;
1215 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1216 } catch (IOException e
) {
1217 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1218 registeredUsers
= Map
.of();
1221 for (SignalServiceAddress address
: addressesMissingUuid
) {
1222 final String number
= address
.getNumber().get();
1223 if (registeredUsers
.containsKey(number
)) {
1224 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1225 registeredUsers
.get(number
),
1227 signalServiceAddresses
.add(newAddress
);
1229 signalServiceAddresses
.add(address
);
1233 return signalServiceAddresses
;
1236 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1238 return accountManager
.getRegisteredUsers(getIasKeyStore(), numbersMissingUuid
, CDS_MRENCLAVE
);
1239 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException e
) {
1240 throw new IOException(e
);
1244 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1245 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1246 ) throws IOException
{
1247 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1248 final long timestamp
= System
.currentTimeMillis();
1249 messageBuilder
.withTimestamp(timestamp
);
1250 getOrCreateMessagePipe();
1251 getOrCreateUnidentifiedMessagePipe();
1252 SignalServiceDataMessage message
= null;
1254 message
= messageBuilder
.build();
1255 if (message
.getGroupContext().isPresent()) {
1257 SignalServiceMessageSender messageSender
= createMessageSender();
1258 final boolean isRecipientUpdate
= false;
1259 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1260 unidentifiedAccessHelper
.getAccessFor(recipients
),
1263 for (SendMessageResult r
: result
) {
1264 if (r
.getIdentityFailure() != null) {
1265 account
.getSignalProtocolStore()
1266 .saveIdentity(r
.getAddress(),
1267 r
.getIdentityFailure().getIdentityKey(),
1268 TrustLevel
.UNTRUSTED
);
1271 return new Pair
<>(timestamp
, result
);
1272 } catch (UntrustedIdentityException e
) {
1273 account
.getSignalProtocolStore()
1274 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1276 TrustLevel
.UNTRUSTED
);
1277 return new Pair
<>(timestamp
, List
.of());
1280 // Send to all individually, so sync messages are sent correctly
1281 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1282 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1283 for (SignalServiceAddress address
: recipients
) {
1284 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1285 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1286 messageBuilder
.withExpiration(expirationTime
);
1287 message
= messageBuilder
.build();
1288 results
.add(sendMessage(address
, message
));
1290 return new Pair
<>(timestamp
, results
);
1293 if (message
!= null && message
.isEndSession()) {
1294 for (SignalServiceAddress recipient
: recipients
) {
1295 handleEndSession(recipient
);
1302 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1303 SignalServiceDataMessage
.Builder messageBuilder
1304 ) throws IOException
{
1305 final long timestamp
= System
.currentTimeMillis();
1306 messageBuilder
.withTimestamp(timestamp
);
1307 getOrCreateMessagePipe();
1308 getOrCreateUnidentifiedMessagePipe();
1310 final SignalServiceAddress address
= getSelfAddress();
1312 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1313 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1314 messageBuilder
.withExpiration(expirationTime
);
1316 SignalServiceDataMessage message
= messageBuilder
.build();
1317 final SendMessageResult result
= sendSelfMessage(message
);
1318 return new Pair
<>(timestamp
, result
);
1324 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1325 SignalServiceMessageSender messageSender
= createMessageSender();
1327 SignalServiceAddress recipient
= account
.getSelfAddress();
1329 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1330 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1331 message
.getTimestamp(),
1333 message
.getExpiresInSeconds(),
1334 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1336 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1339 long startTime
= System
.currentTimeMillis();
1340 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1341 return SendMessageResult
.success(recipient
,
1342 unidentifiedAccess
.isPresent(),
1344 System
.currentTimeMillis() - startTime
);
1345 } catch (UntrustedIdentityException e
) {
1346 account
.getSignalProtocolStore()
1347 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1349 TrustLevel
.UNTRUSTED
);
1350 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1354 private SendMessageResult
sendMessage(
1355 SignalServiceAddress address
, SignalServiceDataMessage message
1356 ) throws IOException
{
1357 SignalServiceMessageSender messageSender
= createMessageSender();
1360 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1361 } catch (UntrustedIdentityException e
) {
1362 account
.getSignalProtocolStore()
1363 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1365 TrustLevel
.UNTRUSTED
);
1366 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1370 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1371 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1372 account
.getSignalProtocolStore(),
1373 certificateValidator
);
1375 return cipher
.decrypt(envelope
);
1376 } catch (ProtocolUntrustedIdentityException e
) {
1377 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1378 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1380 account
.getSignalProtocolStore()
1381 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1382 identityException
.getUntrustedIdentity(),
1383 TrustLevel
.UNTRUSTED
);
1384 throw identityException
;
1386 throw new AssertionError(e
);
1390 private void handleEndSession(SignalServiceAddress source
) {
1391 account
.getSignalProtocolStore().deleteAllSessions(source
);
1394 private List
<HandleAction
> handleSignalServiceDataMessage(
1395 SignalServiceDataMessage message
,
1397 SignalServiceAddress source
,
1398 SignalServiceAddress destination
,
1399 boolean ignoreAttachments
1401 List
<HandleAction
> actions
= new ArrayList
<>();
1402 if (message
.getGroupContext().isPresent()) {
1403 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1404 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1405 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1406 GroupInfo group
= getGroup(groupId
);
1407 if (group
== null || group
instanceof GroupInfoV1
) {
1408 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1409 switch (groupInfo
.getType()) {
1411 if (groupV1
== null) {
1412 groupV1
= new GroupInfoV1(groupId
);
1415 if (groupInfo
.getAvatar().isPresent()) {
1416 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1417 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1420 if (groupInfo
.getName().isPresent()) {
1421 groupV1
.name
= groupInfo
.getName().get();
1424 if (groupInfo
.getMembers().isPresent()) {
1425 groupV1
.addMembers(groupInfo
.getMembers()
1428 .map(this::resolveSignalServiceAddress
)
1429 .collect(Collectors
.toSet()));
1432 account
.getGroupStore().updateGroup(groupV1
);
1436 if (groupV1
== null && !isSync
) {
1437 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1441 if (groupV1
!= null) {
1442 groupV1
.removeMember(source
);
1443 account
.getGroupStore().updateGroup(groupV1
);
1448 if (groupV1
!= null && !isSync
) {
1449 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1454 // Received a group v1 message for a v2 group
1457 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1458 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1459 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1461 getOrMigrateGroup(groupMasterKey
,
1462 groupContext
.getRevision(),
1463 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1467 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1468 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1469 handleEndSession(conversationPartnerAddress
);
1471 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1472 if (message
.getGroupContext().isPresent()) {
1473 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1474 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1475 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1476 if (group
!= null) {
1477 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1478 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1479 account
.getGroupStore().updateGroup(group
);
1482 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1483 // disappearing message timer already stored in the DecryptedGroup
1485 } else if (conversationPartnerAddress
!= null) {
1486 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1487 if (contact
== null) {
1488 contact
= new ContactInfo(conversationPartnerAddress
);
1490 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1491 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1492 account
.getContactStore().updateContact(contact
);
1496 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1497 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1498 downloadAttachment(attachment
);
1501 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1502 final ProfileKey profileKey
;
1504 profileKey
= new ProfileKey(message
.getProfileKey().get());
1505 } catch (InvalidInputException e
) {
1506 throw new AssertionError(e
);
1508 if (source
.matches(account
.getSelfAddress())) {
1509 this.account
.setProfileKey(profileKey
);
1511 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1513 if (message
.getPreviews().isPresent()) {
1514 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1515 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1516 if (preview
.getImage().isPresent()) {
1517 downloadAttachment(preview
.getImage().get());
1521 if (message
.getQuote().isPresent()) {
1522 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1524 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1525 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1526 if (thumbnail
!= null) {
1527 downloadAttachment(thumbnail
);
1531 if (message
.getSticker().isPresent()) {
1532 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1533 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1534 if (sticker
== null) {
1535 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1536 account
.getStickerStore().updateSticker(sticker
);
1542 private GroupInfoV2
getOrMigrateGroup(
1543 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1545 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1547 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1548 GroupInfo groupInfo
= getGroup(groupId
);
1549 final GroupInfoV2 groupInfoV2
;
1550 if (groupInfo
instanceof GroupInfoV1
) {
1551 // Received a v2 group message for a v1 group, we need to locally migrate the group
1552 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1553 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1554 logger
.info("Locally migrated group {} to group v2, id: {}",
1555 groupInfo
.getGroupId().toBase64(),
1556 groupInfoV2
.getGroupId().toBase64());
1557 } else if (groupInfo
instanceof GroupInfoV2
) {
1558 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1560 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1563 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1564 DecryptedGroup group
= null;
1565 if (signedGroupChange
!= null
1566 && groupInfoV2
.getGroup() != null
1567 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1568 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1570 if (group
== null) {
1571 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1573 if (group
!= null) {
1574 storeProfileKeysFromMembers(group
);
1575 final String avatar
= group
.getAvatar();
1576 if (avatar
!= null && !avatar
.isEmpty()) {
1577 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1580 groupInfoV2
.setGroup(group
);
1581 account
.getGroupStore().updateGroup(groupInfoV2
);
1587 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1588 for (DecryptedMember member
: group
.getMembersList()) {
1589 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1590 member
.getUuid().toByteArray()), null));
1592 account
.getProfileStore()
1593 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1594 } catch (InvalidInputException ignored
) {
1599 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1600 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1601 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1605 private void retryFailedReceivedMessage(
1606 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1608 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1609 if (envelope
== null) {
1612 SignalServiceContent content
= null;
1613 if (!envelope
.isReceipt()) {
1615 content
= decryptMessage(envelope
);
1616 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1618 } catch (Exception er
) {
1619 // All other errors are not recoverable, so delete the cached message
1620 cachedMessage
.delete();
1623 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1624 for (HandleAction action
: actions
) {
1626 action
.execute(this);
1627 } catch (Throwable e
) {
1628 logger
.warn("Message action failed.", e
);
1633 handler
.handleMessage(envelope
, content
, null);
1634 cachedMessage
.delete();
1637 public void receiveMessages(
1640 boolean returnOnTimeout
,
1641 boolean ignoreAttachments
,
1642 ReceiveMessageHandler handler
1643 ) throws IOException
{
1644 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1646 Set
<HandleAction
> queuedActions
= null;
1648 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1650 boolean hasCaughtUpWithOldMessages
= false;
1653 SignalServiceEnvelope envelope
;
1654 SignalServiceContent content
= null;
1655 Exception exception
= null;
1656 final CachedMessage
[] cachedMessage
= {null};
1658 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1659 // store message on disk, before acknowledging receipt to the server
1660 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1662 if (result
.isPresent()) {
1663 envelope
= result
.get();
1665 // Received indicator that server queue is empty
1666 hasCaughtUpWithOldMessages
= true;
1668 if (queuedActions
!= null) {
1669 for (HandleAction action
: queuedActions
) {
1671 action
.execute(this);
1672 } catch (Throwable e
) {
1673 logger
.warn("Message action failed.", e
);
1677 queuedActions
.clear();
1678 queuedActions
= null;
1681 // Continue to wait another timeout for new messages
1684 } catch (TimeoutException e
) {
1685 if (returnOnTimeout
) return;
1687 } catch (InvalidVersionException e
) {
1688 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1692 if (envelope
.hasSource()) {
1693 // Store uuid if we don't have it already
1694 SignalServiceAddress source
= envelope
.getSourceAddress();
1695 resolveSignalServiceAddress(source
);
1697 if (!envelope
.isReceipt()) {
1699 content
= decryptMessage(envelope
);
1700 } catch (Exception e
) {
1703 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1704 if (hasCaughtUpWithOldMessages
) {
1705 for (HandleAction action
: actions
) {
1707 action
.execute(this);
1708 } catch (Throwable e
) {
1709 logger
.warn("Message action failed.", e
);
1713 if (queuedActions
== null) {
1714 queuedActions
= new HashSet
<>();
1716 queuedActions
.addAll(actions
);
1720 if (isMessageBlocked(envelope
, content
)) {
1721 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1722 } else if (isNotAGroupMember(envelope
, content
)) {
1723 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1725 handler
.handleMessage(envelope
, content
, exception
);
1727 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1728 if (cachedMessage
[0] != null) {
1729 cachedMessage
[0].delete();
1735 private boolean isMessageBlocked(
1736 SignalServiceEnvelope envelope
, SignalServiceContent content
1738 SignalServiceAddress source
;
1739 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1740 source
= envelope
.getSourceAddress();
1741 } else if (content
!= null) {
1742 source
= content
.getSender();
1746 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1747 if (sourceContact
!= null && sourceContact
.blocked
) {
1751 if (content
!= null && content
.getDataMessage().isPresent()) {
1752 SignalServiceDataMessage message
= content
.getDataMessage().get();
1753 if (message
.getGroupContext().isPresent()) {
1754 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1755 GroupInfo group
= getGroup(groupId
);
1756 if (group
!= null && group
.isBlocked()) {
1764 private boolean isNotAGroupMember(
1765 SignalServiceEnvelope envelope
, SignalServiceContent content
1767 SignalServiceAddress source
;
1768 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1769 source
= envelope
.getSourceAddress();
1770 } else if (content
!= null) {
1771 source
= content
.getSender();
1776 if (content
!= null && content
.getDataMessage().isPresent()) {
1777 SignalServiceDataMessage message
= content
.getDataMessage().get();
1778 if (message
.getGroupContext().isPresent()) {
1779 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1780 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1781 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1785 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1786 GroupInfo group
= getGroup(groupId
);
1787 if (group
!= null && !group
.isMember(source
)) {
1795 private List
<HandleAction
> handleMessage(
1796 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1798 List
<HandleAction
> actions
= new ArrayList
<>();
1799 if (content
!= null) {
1800 final SignalServiceAddress sender
;
1801 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1802 sender
= envelope
.getSourceAddress();
1804 sender
= content
.getSender();
1806 // Store uuid if we don't have it already
1807 resolveSignalServiceAddress(sender
);
1809 if (content
.getDataMessage().isPresent()) {
1810 SignalServiceDataMessage message
= content
.getDataMessage().get();
1812 if (content
.isNeedsReceipt()) {
1813 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1816 actions
.addAll(handleSignalServiceDataMessage(message
,
1819 account
.getSelfAddress(),
1820 ignoreAttachments
));
1822 if (content
.getSyncMessage().isPresent()) {
1823 account
.setMultiDevice(true);
1824 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1825 if (syncMessage
.getSent().isPresent()) {
1826 SentTranscriptMessage message
= syncMessage
.getSent().get();
1827 final SignalServiceAddress destination
= message
.getDestination().orNull();
1828 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1832 ignoreAttachments
));
1834 if (syncMessage
.getRequest().isPresent()) {
1835 RequestMessage rm
= syncMessage
.getRequest().get();
1836 if (rm
.isContactsRequest()) {
1837 actions
.add(SendSyncContactsAction
.create());
1839 if (rm
.isGroupsRequest()) {
1840 actions
.add(SendSyncGroupsAction
.create());
1842 if (rm
.isBlockedListRequest()) {
1843 actions
.add(SendSyncBlockedListAction
.create());
1845 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1847 if (syncMessage
.getGroups().isPresent()) {
1848 File tmpFile
= null;
1850 tmpFile
= IOUtils
.createTempFile();
1851 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1852 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1854 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1856 while ((g
= s
.read()) != null) {
1857 GroupInfoV1 syncGroup
= account
.getGroupStore()
1858 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1859 if (syncGroup
!= null) {
1860 if (g
.getName().isPresent()) {
1861 syncGroup
.name
= g
.getName().get();
1863 syncGroup
.addMembers(g
.getMembers()
1865 .map(this::resolveSignalServiceAddress
)
1866 .collect(Collectors
.toSet()));
1867 if (!g
.isActive()) {
1868 syncGroup
.removeMember(account
.getSelfAddress());
1870 // Add ourself to the member set as it's marked as active
1871 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1873 syncGroup
.blocked
= g
.isBlocked();
1874 if (g
.getColor().isPresent()) {
1875 syncGroup
.color
= g
.getColor().get();
1878 if (g
.getAvatar().isPresent()) {
1879 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1881 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1882 syncGroup
.archived
= g
.isArchived();
1883 account
.getGroupStore().updateGroup(syncGroup
);
1887 } catch (Exception e
) {
1888 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1892 if (tmpFile
!= null) {
1894 Files
.delete(tmpFile
.toPath());
1895 } catch (IOException e
) {
1896 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1903 if (syncMessage
.getBlockedList().isPresent()) {
1904 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1905 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1906 setContactBlocked(resolveSignalServiceAddress(address
), true);
1908 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1910 .map(GroupId
::unknownVersion
)
1911 .collect(Collectors
.toSet())) {
1913 setGroupBlocked(groupId
, true);
1914 } catch (GroupNotFoundException e
) {
1915 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1916 groupId
.toBase64());
1920 if (syncMessage
.getContacts().isPresent()) {
1921 File tmpFile
= null;
1923 tmpFile
= IOUtils
.createTempFile();
1924 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1925 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1926 .asPointer(), tmpFile
)) {
1927 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1928 if (contactsMessage
.isComplete()) {
1929 account
.getContactStore().clear();
1932 while ((c
= s
.read()) != null) {
1933 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1934 account
.setProfileKey(c
.getProfileKey().get());
1936 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1937 ContactInfo contact
= account
.getContactStore().getContact(address
);
1938 if (contact
== null) {
1939 contact
= new ContactInfo(address
);
1941 if (c
.getName().isPresent()) {
1942 contact
.name
= c
.getName().get();
1944 if (c
.getColor().isPresent()) {
1945 contact
.color
= c
.getColor().get();
1947 if (c
.getProfileKey().isPresent()) {
1948 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1950 if (c
.getVerified().isPresent()) {
1951 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1952 account
.getSignalProtocolStore()
1953 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1954 verifiedMessage
.getIdentityKey(),
1955 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1957 if (c
.getExpirationTimer().isPresent()) {
1958 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1960 contact
.blocked
= c
.isBlocked();
1961 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1962 contact
.archived
= c
.isArchived();
1963 account
.getContactStore().updateContact(contact
);
1965 if (c
.getAvatar().isPresent()) {
1966 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
1970 } catch (Exception e
) {
1971 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1975 if (tmpFile
!= null) {
1977 Files
.delete(tmpFile
.toPath());
1978 } catch (IOException e
) {
1979 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1986 if (syncMessage
.getVerified().isPresent()) {
1987 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1988 account
.getSignalProtocolStore()
1989 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
1990 verifiedMessage
.getIdentityKey(),
1991 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1993 if (syncMessage
.getStickerPackOperations().isPresent()) {
1994 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
1996 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
1997 if (!m
.getPackId().isPresent()) {
2000 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2001 if (sticker
== null) {
2002 if (!m
.getPackKey().isPresent()) {
2005 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2007 sticker
.setInstalled(!m
.getType().isPresent()
2008 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2009 account
.getStickerStore().updateSticker(sticker
);
2012 if (syncMessage
.getFetchType().isPresent()) {
2013 switch (syncMessage
.getFetchType().get()) {
2015 getRecipientProfile(getSelfAddress(), true);
2016 case STORAGE_MANIFEST
:
2020 if (syncMessage
.getConfiguration().isPresent()) {
2028 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2030 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2031 } catch (IOException e
) {
2032 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2036 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2038 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2039 } catch (IOException e
) {
2040 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2044 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2046 avatarStore
.storeGroupAvatar(groupId
,
2047 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2048 } catch (IOException e
) {
2049 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2053 private void downloadProfileAvatar(
2054 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2057 avatarStore
.storeProfileAvatar(address
,
2058 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2059 } catch (Throwable e
) {
2060 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2064 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2065 return attachmentStore
.getAttachmentFile(attachmentId
);
2068 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2069 if (!attachment
.isPointer()) {
2070 logger
.warn("Invalid state, can't store an attachment stream.");
2073 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2074 if (pointer
.getPreview().isPresent()) {
2075 final byte[] preview
= pointer
.getPreview().get();
2077 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2078 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2079 } catch (IOException e
) {
2080 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2085 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2086 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2087 } catch (IOException e
) {
2088 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2092 private void retrieveGroupV2Avatar(
2093 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2094 ) throws IOException
{
2095 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2097 File tmpFile
= IOUtils
.createTempFile();
2098 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2100 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2101 byte[] encryptedData
= IOUtils
.readFully(input
);
2103 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2104 outputStream
.write(decryptedData
);
2107 Files
.delete(tmpFile
.toPath());
2108 } catch (IOException e
) {
2109 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2116 private void retrieveProfileAvatar(
2117 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2118 ) throws IOException
{
2119 File tmpFile
= IOUtils
.createTempFile();
2120 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2123 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2124 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2125 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2128 Files
.delete(tmpFile
.toPath());
2129 } catch (IOException e
) {
2130 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2137 private void retrieveAttachment(
2138 final SignalServiceAttachment attachment
, final OutputStream outputStream
2139 ) throws IOException
{
2140 if (attachment
.isPointer()) {
2141 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2142 retrieveAttachmentPointer(pointer
, outputStream
);
2144 SignalServiceAttachmentStream stream
= attachment
.asStream();
2145 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2149 private void retrieveAttachmentPointer(
2150 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2151 ) throws IOException
{
2152 File tmpFile
= IOUtils
.createTempFile();
2153 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2154 IOUtils
.copyStream(input
, outputStream
);
2155 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2156 throw new IOException(e
);
2159 Files
.delete(tmpFile
.toPath());
2160 } catch (IOException e
) {
2161 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2168 private InputStream
retrieveAttachmentAsStream(
2169 SignalServiceAttachmentPointer pointer
, File tmpFile
2170 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2171 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2174 void sendGroups() throws IOException
, UntrustedIdentityException
{
2175 File groupsFile
= IOUtils
.createTempFile();
2178 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2179 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2180 for (GroupInfo
record : getGroups()) {
2181 if (record instanceof GroupInfoV1
) {
2182 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2183 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2184 Optional
.fromNullable(groupInfo
.name
),
2185 new ArrayList
<>(groupInfo
.getMembers()),
2186 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2187 groupInfo
.isMember(account
.getSelfAddress()),
2188 Optional
.of(groupInfo
.messageExpirationTime
),
2189 Optional
.fromNullable(groupInfo
.color
),
2191 Optional
.fromNullable(groupInfo
.inboxPosition
),
2192 groupInfo
.archived
));
2197 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2198 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2199 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2200 .withStream(groupsFileStream
)
2201 .withContentType("application/octet-stream")
2202 .withLength(groupsFile
.length())
2205 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2210 Files
.delete(groupsFile
.toPath());
2211 } catch (IOException e
) {
2212 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2217 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2218 File contactsFile
= IOUtils
.createTempFile();
2221 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2222 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2223 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2224 VerifiedMessage verifiedMessage
= null;
2225 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2226 if (currentIdentity
!= null) {
2227 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2228 currentIdentity
.getIdentityKey(),
2229 currentIdentity
.getTrustLevel().toVerifiedState(),
2230 currentIdentity
.getDateAdded().getTime());
2233 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2234 out
.write(new DeviceContact(record.getAddress(),
2235 Optional
.fromNullable(record.name
),
2236 createContactAvatarAttachment(record.getAddress()),
2237 Optional
.fromNullable(record.color
),
2238 Optional
.fromNullable(verifiedMessage
),
2239 Optional
.fromNullable(profileKey
),
2241 Optional
.of(record.messageExpirationTime
),
2242 Optional
.fromNullable(record.inboxPosition
),
2246 if (account
.getProfileKey() != null) {
2247 // Send our own profile key as well
2248 out
.write(new DeviceContact(account
.getSelfAddress(),
2253 Optional
.of(account
.getProfileKey()),
2261 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2262 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2263 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2264 .withStream(contactsFileStream
)
2265 .withContentType("application/octet-stream")
2266 .withLength(contactsFile
.length())
2269 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2274 Files
.delete(contactsFile
.toPath());
2275 } catch (IOException e
) {
2276 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2281 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2282 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2283 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2284 if (record.blocked
) {
2285 addresses
.add(record.getAddress());
2288 List
<byte[]> groupIds
= new ArrayList
<>();
2289 for (GroupInfo
record : getGroups()) {
2290 if (record.isBlocked()) {
2291 groupIds
.add(record.getGroupId().serialize());
2294 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2297 private void sendVerifiedMessage(
2298 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2299 ) throws IOException
, UntrustedIdentityException
{
2300 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2302 trustLevel
.toVerifiedState(),
2303 System
.currentTimeMillis());
2304 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2307 public List
<ContactInfo
> getContacts() {
2308 return account
.getContactStore().getContacts();
2311 public String
getContactOrProfileName(String number
) {
2312 final SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2314 final ContactInfo contact
= account
.getContactStore().getContact(address
);
2315 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2316 return contact
.name
;
2319 final SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2320 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2321 return profileEntry
.getProfile().getName();
2327 public GroupInfo
getGroup(GroupId groupId
) {
2328 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2329 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2330 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2331 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2332 account
.getGroupStore().updateGroup(group
);
2337 public List
<IdentityInfo
> getIdentities() {
2338 return account
.getSignalProtocolStore().getIdentities();
2341 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2342 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2346 * Trust this the identity with this fingerprint
2348 * @param name username of the identity
2349 * @param fingerprint Fingerprint
2351 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2352 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2353 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2357 for (IdentityInfo id
: ids
) {
2358 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2362 account
.getSignalProtocolStore()
2363 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2365 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2366 } catch (IOException
| UntrustedIdentityException e
) {
2367 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2376 * Trust this the identity with this safety number
2378 * @param name username of the identity
2379 * @param safetyNumber Safety number
2381 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2382 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2383 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2387 for (IdentityInfo id
: ids
) {
2388 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2392 account
.getSignalProtocolStore()
2393 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2395 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2396 } catch (IOException
| UntrustedIdentityException e
) {
2397 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2406 * Trust all keys of this identity without verification
2408 * @param name username of the identity
2410 public boolean trustIdentityAllKeys(String name
) {
2411 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2412 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2416 for (IdentityInfo id
: ids
) {
2417 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2418 account
.getSignalProtocolStore()
2419 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2421 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2422 } catch (IOException
| UntrustedIdentityException e
) {
2423 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2431 public String
computeSafetyNumber(
2432 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2434 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2435 account
.getSelfAddress(),
2436 getIdentityKeyPair().getPublicKey(),
2441 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2442 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2444 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2445 return resolveSignalServiceAddress(canonicalizedNumber
);
2448 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2449 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2451 return resolveSignalServiceAddress(address
);
2454 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2455 if (address
.matches(account
.getSelfAddress())) {
2456 return account
.getSelfAddress();
2459 return account
.getRecipientStore().resolveServiceAddress(address
);
2463 public void close() throws IOException
{
2467 void close(boolean closeAccount
) throws IOException
{
2468 if (messagePipe
!= null) {
2469 messagePipe
.shutdown();
2473 if (unidentifiedMessagePipe
!= null) {
2474 unidentifiedMessagePipe
.shutdown();
2475 unidentifiedMessagePipe
= null;
2478 if (closeAccount
&& account
!= null) {
2484 public interface ReceiveMessageHandler
{
2486 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);