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
.ContactTokenDetails
;
125 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
126 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
127 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
128 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
129 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
130 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
131 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
132 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
133 import org
.whispersystems
.signalservice
.internal
.configuration
.SignalServiceConfiguration
;
134 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
135 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
136 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
137 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
138 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
139 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
140 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
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 List
<ContactTokenDetails
> contactDetails
= this.accountManager
.getContacts(numbers
);
330 Set
<String
> registeredUsers
= contactDetails
.stream()
331 .map(ContactTokenDetails
::getNumber
)
332 .collect(Collectors
.toSet());
334 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
337 public void updateAccountAttributes() throws IOException
{
338 accountManager
.setAccountAttributes(account
.getSignalingKey(),
339 account
.getSignalProtocolStore().getLocalRegistrationId(),
341 // set legacy pin only if no KBS master key is set
342 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
343 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
344 account
.getSelfUnidentifiedAccessKey(),
345 account
.isUnrestrictedUnidentifiedAccess(),
347 account
.isDiscoverableByPhoneNumber());
351 * @param avatar if avatar is null the image from the local avatar store is used (if present),
352 * if it's Optional.absent(), the avatar will be removed
354 public void setProfile(String name
, Optional
<File
> avatar
) throws IOException
{
355 try (final StreamDetails streamDetails
= avatar
== null
356 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
357 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
358 accountManager
.setVersionedProfile(account
.getUuid(), account
.getProfileKey(), name
, streamDetails
);
361 if (avatar
!= null) {
362 if (avatar
.isPresent()) {
363 avatarStore
.storeProfileAvatar(getSelfAddress(),
364 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
366 avatarStore
.deleteProfileAvatar(getSelfAddress());
371 public void unregister() throws IOException
{
372 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
373 // If this is the master device, other users can't send messages to this number anymore.
374 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
375 accountManager
.setGcmId(Optional
.absent());
377 account
.setRegistered(false);
381 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
382 List
<DeviceInfo
> devices
= accountManager
.getDevices();
383 account
.setMultiDevice(devices
.size() > 1);
388 public void removeLinkedDevices(int deviceId
) throws IOException
{
389 accountManager
.removeDevice(deviceId
);
390 List
<DeviceInfo
> devices
= accountManager
.getDevices();
391 account
.setMultiDevice(devices
.size() > 1);
395 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
396 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
398 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
401 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
402 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
403 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
405 accountManager
.addDevice(deviceIdentifier
,
408 Optional
.of(account
.getProfileKey().serialize()),
410 account
.setMultiDevice(true);
414 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
415 if (pin
.isPresent()) {
416 final MasterKey masterKey
= account
.getPinMasterKey() != null
417 ? account
.getPinMasterKey()
418 : KeyUtils
.createMasterKey();
420 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
422 account
.setRegistrationLockPin(pin
.get());
423 account
.setPinMasterKey(masterKey
);
425 // Remove legacy registration lock
426 accountManager
.removeRegistrationLockV1();
429 pinHelper
.removeRegistrationLockPin();
431 account
.setRegistrationLockPin(null);
432 account
.setPinMasterKey(null);
437 void refreshPreKeys() throws IOException
{
438 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
439 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
440 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
442 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
445 private List
<PreKeyRecord
> generatePreKeys() {
446 final int offset
= account
.getPreKeyIdOffset();
448 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
449 account
.addPreKeys(records
);
455 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
456 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
458 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
459 account
.addSignedPreKey(record);
465 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
466 if (messagePipe
== null) {
467 messagePipe
= messageReceiver
.createMessagePipe();
472 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
473 if (unidentifiedMessagePipe
== null) {
474 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
476 return unidentifiedMessagePipe
;
479 private SignalServiceMessageSender
createMessageSender() {
480 final ExecutorService executor
= null;
481 return new SignalServiceMessageSender(serviceConfiguration
,
483 account
.getUsername(),
484 account
.getPassword(),
485 account
.getDeviceId(),
486 account
.getSignalProtocolStore(),
488 account
.isMultiDevice(),
489 Optional
.fromNullable(messagePipe
),
490 Optional
.fromNullable(unidentifiedMessagePipe
),
492 clientZkProfileOperations
,
494 ServiceConfig
.MAX_ENVELOPE_SIZE
);
497 private SignalProfile
getRecipientProfile(
498 SignalServiceAddress address
500 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
501 if (profileEntry
== null) {
504 long now
= new Date().getTime();
505 // Profiles are cached for 24h before retrieving them again
506 if (!profileEntry
.isRequestPending() && (
507 profileEntry
.getProfile() == null || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
509 profileEntry
.setRequestPending(true);
510 final SignalServiceProfile encryptedProfile
;
512 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
514 } catch (IOException e
) {
515 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
518 profileEntry
.setRequestPending(false);
521 final ProfileKey profileKey
= profileEntry
.getProfileKey();
522 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
523 account
.getProfileStore()
524 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
527 return profileEntry
.getProfile();
530 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
531 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
532 if (profileEntry
== null) {
535 if (profileEntry
.getProfileKeyCredential() == null) {
536 ProfileAndCredential profileAndCredential
;
538 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
539 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
540 } catch (IOException e
) {
541 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
545 long now
= new Date().getTime();
546 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
547 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
548 profileEntry
.getProfileKey(),
549 profileAndCredential
.getProfile());
550 account
.getProfileStore()
551 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
552 return profileKeyCredential
;
554 return profileEntry
.getProfileKeyCredential();
557 private SignalProfile
decryptProfileAndDownloadAvatar(
558 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
560 if (encryptedProfile
.getAvatar() != null) {
561 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
564 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
567 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
568 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
569 if (streamDetails
== null) {
570 return Optional
.absent();
573 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
576 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
577 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
578 if (streamDetails
== null) {
579 return Optional
.absent();
582 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
585 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
586 GroupInfo g
= getGroup(groupId
);
588 throw new GroupNotFoundException(groupId
);
590 if (!g
.isMember(account
.getSelfAddress())) {
591 throw new NotAGroupMemberException(groupId
, g
.getTitle());
596 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
597 GroupInfo g
= getGroup(groupId
);
599 throw new GroupNotFoundException(groupId
);
601 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
602 throw new NotAGroupMemberException(groupId
, g
.getTitle());
607 public List
<GroupInfo
> getGroups() {
608 return account
.getGroupStore().getGroups();
611 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
612 String messageText
, List
<String
> attachments
, GroupId groupId
613 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
614 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
615 .withBody(messageText
);
616 if (attachments
!= null) {
617 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
620 return sendGroupMessage(messageBuilder
, groupId
);
623 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
624 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
625 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
626 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
628 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
629 targetSentTimestamp
);
630 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
631 .withReaction(reaction
);
633 return sendGroupMessage(messageBuilder
, groupId
);
636 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
637 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
638 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
639 final GroupInfo g
= getGroupForSending(groupId
);
641 GroupUtils
.setGroupContext(messageBuilder
, g
);
642 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
644 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
647 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
648 SignalServiceDataMessage
.Builder messageBuilder
;
650 final GroupInfo g
= getGroupForUpdating(groupId
);
651 if (g
instanceof GroupInfoV1
) {
652 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
653 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
654 .withId(groupId
.serialize())
656 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
657 groupInfoV1
.removeMember(account
.getSelfAddress());
658 account
.getGroupStore().updateGroup(groupInfoV1
);
660 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
661 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
662 groupInfoV2
.setGroup(groupGroupChangePair
.first());
663 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
664 account
.getGroupStore().updateGroup(groupInfoV2
);
667 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
670 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
671 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
672 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
673 return sendUpdateGroupMessage(groupId
,
675 members
== null ?
null : getSignalServiceAddresses(members
),
679 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
680 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
681 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
683 SignalServiceDataMessage
.Builder messageBuilder
;
684 if (groupId
== null) {
686 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
687 members
== null ? List
.of() : members
,
690 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
691 gv1
.addMembers(List
.of(account
.getSelfAddress()));
692 updateGroupV1(gv1
, name
, members
, avatarFile
);
693 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
696 if (avatarFile
!= null) {
697 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
698 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
700 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
704 GroupInfo group
= getGroupForUpdating(groupId
);
705 if (group
instanceof GroupInfoV2
) {
706 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
708 Pair
<Long
, List
<SendMessageResult
>> result
= null;
709 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
710 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
711 result
= sendUpdateGroupMessage(groupInfoV2
,
712 groupGroupChangePair
.first(),
713 groupGroupChangePair
.second());
716 if (members
!= null) {
717 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
718 newMembers
.removeAll(group
.getMembers()
720 .map(this::resolveSignalServiceAddress
)
721 .collect(Collectors
.toSet()));
722 if (newMembers
.size() > 0) {
723 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
725 result
= sendUpdateGroupMessage(groupInfoV2
,
726 groupGroupChangePair
.first(),
727 groupGroupChangePair
.second());
730 if (result
== null || name
!= null || avatarFile
!= null) {
731 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
734 if (avatarFile
!= null) {
735 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
736 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
738 result
= sendUpdateGroupMessage(groupInfoV2
,
739 groupGroupChangePair
.first(),
740 groupGroupChangePair
.second());
743 return new Pair
<>(group
.getGroupId(), result
.second());
745 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
746 updateGroupV1(gv1
, name
, members
, avatarFile
);
747 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
752 account
.getGroupStore().updateGroup(g
);
754 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
755 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
756 return new Pair
<>(g
.getGroupId(), result
.second());
759 private void updateGroupV1(
762 final Collection
<SignalServiceAddress
> members
,
763 final File avatarFile
764 ) throws IOException
{
769 if (members
!= null) {
770 final Set
<String
> newE164Members
= new HashSet
<>();
771 for (SignalServiceAddress member
: members
) {
772 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
775 newE164Members
.add(member
.getNumber().get());
778 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newE164Members
);
779 if (contacts
.size() != newE164Members
.size()) {
780 // Some of the new members are not registered on Signal
781 for (ContactTokenDetails contact
: contacts
) {
782 newE164Members
.remove(contact
.getNumber());
784 throw new IOException("Failed to add members "
785 + String
.join(", ", newE164Members
)
786 + " to group: Not registered on Signal");
789 g
.addMembers(members
);
792 if (avatarFile
!= null) {
793 avatarStore
.storeGroupAvatar(g
.getGroupId(),
794 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
798 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
799 GroupInviteLinkUrl inviteLinkUrl
800 ) throws IOException
, GroupLinkNotActiveException
{
801 return sendJoinGroupMessage(inviteLinkUrl
);
804 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
805 GroupInviteLinkUrl inviteLinkUrl
806 ) throws IOException
, GroupLinkNotActiveException
{
807 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
808 inviteLinkUrl
.getPassword());
809 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
810 inviteLinkUrl
.getPassword(),
812 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
813 groupJoinInfo
.getRevision() + 1,
814 groupChange
.toByteArray());
816 if (group
.getGroup() == null) {
817 // Only requested member, can't send update to group members
818 return new Pair
<>(group
.getGroupId(), List
.of());
821 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
823 return new Pair
<>(group
.getGroupId(), result
.second());
826 private static int currentTimeDays() {
827 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
830 private GroupsV2AuthorizationString
getGroupAuthForToday(
831 final GroupSecretParams groupSecretParams
832 ) throws IOException
{
833 final int today
= currentTimeDays();
834 // Returns credentials for the next 7 days
835 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
836 // TODO cache credentials until they expire
837 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
839 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
842 authCredentialResponse
);
843 } catch (VerificationFailedException e
) {
844 throw new IOException(e
);
848 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
849 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
850 ) throws IOException
{
851 group
.setGroup(newDecryptedGroup
);
852 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
853 groupChange
.toByteArray());
854 account
.getGroupStore().updateGroup(group
);
855 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
858 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
859 GroupIdV1 groupId
, SignalServiceAddress recipient
860 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
862 GroupInfo group
= getGroupForSending(groupId
);
863 if (!(group
instanceof GroupInfoV1
)) {
864 throw new RuntimeException("Received an invalid group request for a v2 group!");
866 g
= (GroupInfoV1
) group
;
868 if (!g
.isMember(recipient
)) {
869 throw new NotAGroupMemberException(groupId
, g
.name
);
872 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
874 // Send group message only to the recipient who requested it
875 return sendMessage(messageBuilder
, List
.of(recipient
));
878 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
879 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
880 .withId(g
.getGroupId().serialize())
882 .withMembers(new ArrayList
<>(g
.getMembers()));
885 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
886 if (attachment
.isPresent()) {
887 group
.withAvatar(attachment
.get());
889 } catch (IOException e
) {
890 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
893 return SignalServiceDataMessage
.newBuilder()
894 .asGroupMessage(group
.build())
895 .withExpiration(g
.getMessageExpirationTime());
898 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
899 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
900 .withRevision(g
.getGroup().getRevision())
901 .withSignedGroupChange(signedGroupChange
);
902 return SignalServiceDataMessage
.newBuilder()
903 .asGroupMessage(group
.build())
904 .withExpiration(g
.getMessageExpirationTime());
907 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
908 GroupIdV1 groupId
, SignalServiceAddress recipient
909 ) throws IOException
{
910 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
911 .withId(groupId
.serialize());
913 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
914 .asGroupMessage(group
.build());
916 // Send group info request message to the recipient who sent us a message with this groupId
917 return sendMessage(messageBuilder
, List
.of(recipient
));
921 SignalServiceAddress remoteAddress
, long messageId
922 ) throws IOException
, UntrustedIdentityException
{
923 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
925 System
.currentTimeMillis());
927 createMessageSender().sendReceipt(remoteAddress
,
928 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
932 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
933 String messageText
, List
<String
> attachments
, List
<String
> recipients
934 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
935 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
936 .withBody(messageText
);
937 if (attachments
!= null) {
938 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
940 // Upload attachments here, so we only upload once even for multiple recipients
941 SignalServiceMessageSender messageSender
= createMessageSender();
942 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
943 for (SignalServiceAttachment attachment
: attachmentStreams
) {
944 if (attachment
.isStream()) {
945 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
946 } else if (attachment
.isPointer()) {
947 attachmentPointers
.add(attachment
.asPointer());
951 messageBuilder
.withAttachments(attachmentPointers
);
953 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
956 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
957 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
958 ) throws IOException
, InvalidNumberException
{
959 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
961 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
962 targetSentTimestamp
);
963 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
964 .withReaction(reaction
);
965 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
968 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
969 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
971 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
973 return sendMessage(messageBuilder
, signalServiceAddresses
);
974 } catch (Exception e
) {
975 for (SignalServiceAddress address
: signalServiceAddresses
) {
976 handleEndSession(address
);
983 public String
getContactName(String number
) throws InvalidNumberException
{
984 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
985 if (contact
== null) {
992 public void setContactName(String number
, String name
) throws InvalidNumberException
{
993 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
994 ContactInfo contact
= account
.getContactStore().getContact(address
);
995 if (contact
== null) {
996 contact
= new ContactInfo(address
);
999 account
.getContactStore().updateContact(contact
);
1003 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1004 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1007 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1008 ContactInfo contact
= account
.getContactStore().getContact(address
);
1009 if (contact
== null) {
1010 contact
= new ContactInfo(address
);
1012 contact
.blocked
= blocked
;
1013 account
.getContactStore().updateContact(contact
);
1017 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1018 GroupInfo group
= getGroup(groupId
);
1019 if (group
== null) {
1020 throw new GroupNotFoundException(groupId
);
1023 group
.setBlocked(blocked
);
1024 account
.getGroupStore().updateGroup(group
);
1029 * Change the expiration timer for a contact
1031 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1032 ContactInfo contact
= account
.getContactStore().getContact(address
);
1033 contact
.messageExpirationTime
= messageExpirationTimer
;
1034 account
.getContactStore().updateContact(contact
);
1035 sendExpirationTimerUpdate(address
);
1039 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1040 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1041 .asExpirationUpdate();
1042 sendMessage(messageBuilder
, List
.of(address
));
1046 * Change the expiration timer for a contact
1048 public void setExpirationTimer(
1049 String number
, int messageExpirationTimer
1050 ) throws IOException
, InvalidNumberException
{
1051 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1052 setExpirationTimer(address
, messageExpirationTimer
);
1056 * Change the expiration timer for a group
1058 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1059 GroupInfo g
= getGroup(groupId
);
1060 if (g
instanceof GroupInfoV1
) {
1061 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1062 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1063 account
.getGroupStore().updateGroup(groupInfoV1
);
1065 throw new RuntimeException("TODO Not implemented!");
1070 * Upload the sticker pack from path.
1072 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1073 * @return if successful, returns the URL to install the sticker pack in the signal app
1075 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1076 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1078 SignalServiceMessageSender messageSender
= createMessageSender();
1080 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1081 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1083 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1084 account
.getStickerStore().updateSticker(sticker
);
1088 return new URI("https",
1091 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1092 Hex
.toStringCondensed(packKey
),
1093 StandardCharsets
.UTF_8
)).toString();
1094 } catch (URISyntaxException e
) {
1095 throw new AssertionError(e
);
1099 void requestSyncGroups() throws IOException
{
1100 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1101 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1103 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1105 sendSyncMessage(message
);
1106 } catch (UntrustedIdentityException e
) {
1107 throw new AssertionError(e
);
1111 void requestSyncContacts() throws IOException
{
1112 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1113 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1115 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1117 sendSyncMessage(message
);
1118 } catch (UntrustedIdentityException e
) {
1119 throw new AssertionError(e
);
1123 void requestSyncBlocked() throws IOException
{
1124 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1125 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1127 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1129 sendSyncMessage(message
);
1130 } catch (UntrustedIdentityException e
) {
1131 throw new AssertionError(e
);
1135 void requestSyncConfiguration() throws IOException
{
1136 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1137 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1139 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1141 sendSyncMessage(message
);
1142 } catch (UntrustedIdentityException e
) {
1143 throw new AssertionError(e
);
1147 private byte[] getSenderCertificate() {
1148 // TODO support UUID capable sender certificates
1149 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1152 certificate
= accountManager
.getSenderCertificate();
1153 } catch (IOException e
) {
1154 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1157 // TODO cache for a day
1161 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1162 SignalServiceMessageSender messageSender
= createMessageSender();
1164 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1165 } catch (UntrustedIdentityException e
) {
1166 account
.getSignalProtocolStore()
1167 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1169 TrustLevel
.UNTRUSTED
);
1174 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1175 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1176 final Set
<SignalServiceAddress
> missingUuids
= new HashSet
<>();
1178 for (String number
: numbers
) {
1179 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1180 if (resolvedAddress
.getUuid().isPresent()) {
1181 signalServiceAddresses
.add(resolvedAddress
);
1183 missingUuids
.add(resolvedAddress
);
1187 Map
<String
, UUID
> registeredUsers
;
1189 registeredUsers
= accountManager
.getRegisteredUsers(getIasKeyStore(),
1190 missingUuids
.stream().map(a
-> a
.getNumber().get()).collect(Collectors
.toSet()),
1192 } catch (IOException
| Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException e
) {
1193 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1194 registeredUsers
= new HashMap
<>();
1197 for (SignalServiceAddress address
: missingUuids
) {
1198 final String number
= address
.getNumber().get();
1199 if (registeredUsers
.containsKey(number
)) {
1200 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1201 registeredUsers
.get(number
),
1203 signalServiceAddresses
.add(newAddress
);
1205 signalServiceAddresses
.add(address
);
1209 return signalServiceAddresses
;
1212 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1213 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1214 ) throws IOException
{
1215 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1216 final long timestamp
= System
.currentTimeMillis();
1217 messageBuilder
.withTimestamp(timestamp
);
1218 getOrCreateMessagePipe();
1219 getOrCreateUnidentifiedMessagePipe();
1220 SignalServiceDataMessage message
= null;
1222 message
= messageBuilder
.build();
1223 if (message
.getGroupContext().isPresent()) {
1225 SignalServiceMessageSender messageSender
= createMessageSender();
1226 final boolean isRecipientUpdate
= false;
1227 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1228 unidentifiedAccessHelper
.getAccessFor(recipients
),
1231 for (SendMessageResult r
: result
) {
1232 if (r
.getIdentityFailure() != null) {
1233 account
.getSignalProtocolStore()
1234 .saveIdentity(r
.getAddress(),
1235 r
.getIdentityFailure().getIdentityKey(),
1236 TrustLevel
.UNTRUSTED
);
1239 return new Pair
<>(timestamp
, result
);
1240 } catch (UntrustedIdentityException e
) {
1241 account
.getSignalProtocolStore()
1242 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1244 TrustLevel
.UNTRUSTED
);
1245 return new Pair
<>(timestamp
, List
.of());
1248 // Send to all individually, so sync messages are sent correctly
1249 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1250 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1251 for (SignalServiceAddress address
: recipients
) {
1252 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1253 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1254 messageBuilder
.withExpiration(expirationTime
);
1255 message
= messageBuilder
.build();
1256 if (address
.matches(account
.getSelfAddress())) {
1257 results
.add(sendSelfMessage(message
));
1259 results
.add(sendMessage(address
, message
));
1262 return new Pair
<>(timestamp
, results
);
1265 if (message
!= null && message
.isEndSession()) {
1266 for (SignalServiceAddress recipient
: recipients
) {
1267 handleEndSession(recipient
);
1274 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1275 SignalServiceMessageSender messageSender
= createMessageSender();
1277 SignalServiceAddress recipient
= account
.getSelfAddress();
1279 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1280 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1281 message
.getTimestamp(),
1283 message
.getExpiresInSeconds(),
1284 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1286 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1289 long startTime
= System
.currentTimeMillis();
1290 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1291 return SendMessageResult
.success(recipient
,
1292 unidentifiedAccess
.isPresent(),
1294 System
.currentTimeMillis() - startTime
);
1295 } catch (UntrustedIdentityException e
) {
1296 account
.getSignalProtocolStore()
1297 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1299 TrustLevel
.UNTRUSTED
);
1300 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1304 private SendMessageResult
sendMessage(
1305 SignalServiceAddress address
, SignalServiceDataMessage message
1306 ) throws IOException
{
1307 SignalServiceMessageSender messageSender
= createMessageSender();
1310 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1311 } catch (UntrustedIdentityException e
) {
1312 account
.getSignalProtocolStore()
1313 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1315 TrustLevel
.UNTRUSTED
);
1316 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1320 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1321 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1322 account
.getSignalProtocolStore(),
1323 certificateValidator
);
1325 return cipher
.decrypt(envelope
);
1326 } catch (ProtocolUntrustedIdentityException e
) {
1327 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1328 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1330 account
.getSignalProtocolStore()
1331 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1332 identityException
.getUntrustedIdentity(),
1333 TrustLevel
.UNTRUSTED
);
1334 throw identityException
;
1336 throw new AssertionError(e
);
1340 private void handleEndSession(SignalServiceAddress source
) {
1341 account
.getSignalProtocolStore().deleteAllSessions(source
);
1344 private List
<HandleAction
> handleSignalServiceDataMessage(
1345 SignalServiceDataMessage message
,
1347 SignalServiceAddress source
,
1348 SignalServiceAddress destination
,
1349 boolean ignoreAttachments
1351 List
<HandleAction
> actions
= new ArrayList
<>();
1352 if (message
.getGroupContext().isPresent()) {
1353 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1354 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1355 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1356 GroupInfo group
= getGroup(groupId
);
1357 if (group
== null || group
instanceof GroupInfoV1
) {
1358 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1359 switch (groupInfo
.getType()) {
1361 if (groupV1
== null) {
1362 groupV1
= new GroupInfoV1(groupId
);
1365 if (groupInfo
.getAvatar().isPresent()) {
1366 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1367 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1370 if (groupInfo
.getName().isPresent()) {
1371 groupV1
.name
= groupInfo
.getName().get();
1374 if (groupInfo
.getMembers().isPresent()) {
1375 groupV1
.addMembers(groupInfo
.getMembers()
1378 .map(this::resolveSignalServiceAddress
)
1379 .collect(Collectors
.toSet()));
1382 account
.getGroupStore().updateGroup(groupV1
);
1386 if (groupV1
== null && !isSync
) {
1387 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1391 if (groupV1
!= null) {
1392 groupV1
.removeMember(source
);
1393 account
.getGroupStore().updateGroup(groupV1
);
1398 if (groupV1
!= null && !isSync
) {
1399 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1404 // Received a group v1 message for a v2 group
1407 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1408 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1409 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1411 getOrMigrateGroup(groupMasterKey
,
1412 groupContext
.getRevision(),
1413 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1417 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1418 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1419 handleEndSession(conversationPartnerAddress
);
1421 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1422 if (message
.getGroupContext().isPresent()) {
1423 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1424 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1425 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1426 if (group
!= null) {
1427 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1428 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1429 account
.getGroupStore().updateGroup(group
);
1432 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1433 // disappearing message timer already stored in the DecryptedGroup
1435 } else if (conversationPartnerAddress
!= null) {
1436 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1437 if (contact
== null) {
1438 contact
= new ContactInfo(conversationPartnerAddress
);
1440 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1441 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1442 account
.getContactStore().updateContact(contact
);
1446 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1447 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1448 downloadAttachment(attachment
);
1451 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1452 final ProfileKey profileKey
;
1454 profileKey
= new ProfileKey(message
.getProfileKey().get());
1455 } catch (InvalidInputException e
) {
1456 throw new AssertionError(e
);
1458 if (source
.matches(account
.getSelfAddress())) {
1459 this.account
.setProfileKey(profileKey
);
1461 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1463 if (message
.getPreviews().isPresent()) {
1464 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1465 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1466 if (preview
.getImage().isPresent()) {
1467 downloadAttachment(preview
.getImage().get());
1471 if (message
.getQuote().isPresent()) {
1472 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1474 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1475 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1476 if (thumbnail
!= null) {
1477 downloadAttachment(thumbnail
);
1481 if (message
.getSticker().isPresent()) {
1482 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1483 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1484 if (sticker
== null) {
1485 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1486 account
.getStickerStore().updateSticker(sticker
);
1492 private GroupInfoV2
getOrMigrateGroup(
1493 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1495 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1497 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1498 GroupInfo groupInfo
= getGroup(groupId
);
1499 final GroupInfoV2 groupInfoV2
;
1500 if (groupInfo
instanceof GroupInfoV1
) {
1501 // Received a v2 group message for a v1 group, we need to locally migrate the group
1502 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1503 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1504 logger
.info("Locally migrated group {} to group v2, id: {}",
1505 groupInfo
.getGroupId().toBase64(),
1506 groupInfoV2
.getGroupId().toBase64());
1507 } else if (groupInfo
instanceof GroupInfoV2
) {
1508 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1510 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1513 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1514 DecryptedGroup group
= null;
1515 if (signedGroupChange
!= null
1516 && groupInfoV2
.getGroup() != null
1517 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1518 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1520 if (group
== null) {
1521 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1523 if (group
!= null) {
1524 storeProfileKeysFromMembers(group
);
1525 final String avatar
= group
.getAvatar();
1526 if (avatar
!= null && !avatar
.isEmpty()) {
1527 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1530 groupInfoV2
.setGroup(group
);
1531 account
.getGroupStore().updateGroup(groupInfoV2
);
1537 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1538 for (DecryptedMember member
: group
.getMembersList()) {
1539 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1540 member
.getUuid().toByteArray()), null));
1542 account
.getProfileStore()
1543 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1544 } catch (InvalidInputException ignored
) {
1549 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1550 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1551 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1555 private void retryFailedReceivedMessage(
1556 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1558 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1559 if (envelope
== null) {
1562 SignalServiceContent content
= null;
1563 if (!envelope
.isReceipt()) {
1565 content
= decryptMessage(envelope
);
1566 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1568 } catch (Exception er
) {
1569 // All other errors are not recoverable, so delete the cached message
1570 cachedMessage
.delete();
1573 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1574 for (HandleAction action
: actions
) {
1576 action
.execute(this);
1577 } catch (Throwable e
) {
1578 logger
.warn("Message action failed.", e
);
1583 handler
.handleMessage(envelope
, content
, null);
1584 cachedMessage
.delete();
1587 public void receiveMessages(
1590 boolean returnOnTimeout
,
1591 boolean ignoreAttachments
,
1592 ReceiveMessageHandler handler
1593 ) throws IOException
{
1594 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1596 Set
<HandleAction
> queuedActions
= null;
1598 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1600 boolean hasCaughtUpWithOldMessages
= false;
1603 SignalServiceEnvelope envelope
;
1604 SignalServiceContent content
= null;
1605 Exception exception
= null;
1606 final CachedMessage
[] cachedMessage
= {null};
1608 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1609 // store message on disk, before acknowledging receipt to the server
1610 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1612 if (result
.isPresent()) {
1613 envelope
= result
.get();
1615 // Received indicator that server queue is empty
1616 hasCaughtUpWithOldMessages
= true;
1618 if (queuedActions
!= null) {
1619 for (HandleAction action
: queuedActions
) {
1621 action
.execute(this);
1622 } catch (Throwable e
) {
1623 logger
.warn("Message action failed.", e
);
1627 queuedActions
.clear();
1628 queuedActions
= null;
1631 // Continue to wait another timeout for new messages
1634 } catch (TimeoutException e
) {
1635 if (returnOnTimeout
) return;
1637 } catch (InvalidVersionException e
) {
1638 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1642 if (envelope
.hasSource()) {
1643 // Store uuid if we don't have it already
1644 SignalServiceAddress source
= envelope
.getSourceAddress();
1645 resolveSignalServiceAddress(source
);
1647 if (!envelope
.isReceipt()) {
1649 content
= decryptMessage(envelope
);
1650 } catch (Exception e
) {
1653 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1654 if (hasCaughtUpWithOldMessages
) {
1655 for (HandleAction action
: actions
) {
1657 action
.execute(this);
1658 } catch (Throwable e
) {
1659 logger
.warn("Message action failed.", e
);
1663 if (queuedActions
== null) {
1664 queuedActions
= new HashSet
<>();
1666 queuedActions
.addAll(actions
);
1670 if (isMessageBlocked(envelope
, content
)) {
1671 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1672 } else if (isNotAGroupMember(envelope
, content
)) {
1673 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1675 handler
.handleMessage(envelope
, content
, exception
);
1677 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1678 if (cachedMessage
[0] != null) {
1679 cachedMessage
[0].delete();
1685 private boolean isMessageBlocked(
1686 SignalServiceEnvelope envelope
, SignalServiceContent content
1688 SignalServiceAddress source
;
1689 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1690 source
= envelope
.getSourceAddress();
1691 } else if (content
!= null) {
1692 source
= content
.getSender();
1696 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1697 if (sourceContact
!= null && sourceContact
.blocked
) {
1701 if (content
!= null && content
.getDataMessage().isPresent()) {
1702 SignalServiceDataMessage message
= content
.getDataMessage().get();
1703 if (message
.getGroupContext().isPresent()) {
1704 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1705 GroupInfo group
= getGroup(groupId
);
1706 if (group
!= null && group
.isBlocked()) {
1714 private boolean isNotAGroupMember(
1715 SignalServiceEnvelope envelope
, SignalServiceContent content
1717 SignalServiceAddress source
;
1718 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1719 source
= envelope
.getSourceAddress();
1720 } else if (content
!= null) {
1721 source
= content
.getSender();
1726 if (content
!= null && content
.getDataMessage().isPresent()) {
1727 SignalServiceDataMessage message
= content
.getDataMessage().get();
1728 if (message
.getGroupContext().isPresent()) {
1729 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1730 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1731 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1735 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1736 GroupInfo group
= getGroup(groupId
);
1737 if (group
!= null && !group
.isMember(source
)) {
1745 private List
<HandleAction
> handleMessage(
1746 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1748 List
<HandleAction
> actions
= new ArrayList
<>();
1749 if (content
!= null) {
1750 final SignalServiceAddress sender
;
1751 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1752 sender
= envelope
.getSourceAddress();
1754 sender
= content
.getSender();
1756 // Store uuid if we don't have it already
1757 resolveSignalServiceAddress(sender
);
1759 if (content
.getDataMessage().isPresent()) {
1760 SignalServiceDataMessage message
= content
.getDataMessage().get();
1762 if (content
.isNeedsReceipt()) {
1763 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1766 actions
.addAll(handleSignalServiceDataMessage(message
,
1769 account
.getSelfAddress(),
1770 ignoreAttachments
));
1772 if (content
.getSyncMessage().isPresent()) {
1773 account
.setMultiDevice(true);
1774 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1775 if (syncMessage
.getSent().isPresent()) {
1776 SentTranscriptMessage message
= syncMessage
.getSent().get();
1777 final SignalServiceAddress destination
= message
.getDestination().orNull();
1778 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1782 ignoreAttachments
));
1784 if (syncMessage
.getRequest().isPresent()) {
1785 RequestMessage rm
= syncMessage
.getRequest().get();
1786 if (rm
.isContactsRequest()) {
1787 actions
.add(SendSyncContactsAction
.create());
1789 if (rm
.isGroupsRequest()) {
1790 actions
.add(SendSyncGroupsAction
.create());
1792 if (rm
.isBlockedListRequest()) {
1793 actions
.add(SendSyncBlockedListAction
.create());
1795 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1797 if (syncMessage
.getGroups().isPresent()) {
1798 File tmpFile
= null;
1800 tmpFile
= IOUtils
.createTempFile();
1801 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1802 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1804 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1806 while ((g
= s
.read()) != null) {
1807 GroupInfoV1 syncGroup
= account
.getGroupStore()
1808 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1809 if (syncGroup
!= null) {
1810 if (g
.getName().isPresent()) {
1811 syncGroup
.name
= g
.getName().get();
1813 syncGroup
.addMembers(g
.getMembers()
1815 .map(this::resolveSignalServiceAddress
)
1816 .collect(Collectors
.toSet()));
1817 if (!g
.isActive()) {
1818 syncGroup
.removeMember(account
.getSelfAddress());
1820 // Add ourself to the member set as it's marked as active
1821 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1823 syncGroup
.blocked
= g
.isBlocked();
1824 if (g
.getColor().isPresent()) {
1825 syncGroup
.color
= g
.getColor().get();
1828 if (g
.getAvatar().isPresent()) {
1829 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1831 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1832 syncGroup
.archived
= g
.isArchived();
1833 account
.getGroupStore().updateGroup(syncGroup
);
1837 } catch (Exception e
) {
1838 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1842 if (tmpFile
!= null) {
1844 Files
.delete(tmpFile
.toPath());
1845 } catch (IOException e
) {
1846 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1853 if (syncMessage
.getBlockedList().isPresent()) {
1854 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1855 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1856 setContactBlocked(resolveSignalServiceAddress(address
), true);
1858 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1860 .map(GroupId
::unknownVersion
)
1861 .collect(Collectors
.toSet())) {
1863 setGroupBlocked(groupId
, true);
1864 } catch (GroupNotFoundException e
) {
1865 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1866 groupId
.toBase64());
1870 if (syncMessage
.getContacts().isPresent()) {
1871 File tmpFile
= null;
1873 tmpFile
= IOUtils
.createTempFile();
1874 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1875 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1876 .asPointer(), tmpFile
)) {
1877 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1878 if (contactsMessage
.isComplete()) {
1879 account
.getContactStore().clear();
1882 while ((c
= s
.read()) != null) {
1883 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1884 account
.setProfileKey(c
.getProfileKey().get());
1886 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1887 ContactInfo contact
= account
.getContactStore().getContact(address
);
1888 if (contact
== null) {
1889 contact
= new ContactInfo(address
);
1891 if (c
.getName().isPresent()) {
1892 contact
.name
= c
.getName().get();
1894 if (c
.getColor().isPresent()) {
1895 contact
.color
= c
.getColor().get();
1897 if (c
.getProfileKey().isPresent()) {
1898 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1900 if (c
.getVerified().isPresent()) {
1901 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1902 account
.getSignalProtocolStore()
1903 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1904 verifiedMessage
.getIdentityKey(),
1905 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1907 if (c
.getExpirationTimer().isPresent()) {
1908 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1910 contact
.blocked
= c
.isBlocked();
1911 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1912 contact
.archived
= c
.isArchived();
1913 account
.getContactStore().updateContact(contact
);
1915 if (c
.getAvatar().isPresent()) {
1916 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
1920 } catch (Exception e
) {
1921 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1925 if (tmpFile
!= null) {
1927 Files
.delete(tmpFile
.toPath());
1928 } catch (IOException e
) {
1929 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1936 if (syncMessage
.getVerified().isPresent()) {
1937 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1938 account
.getSignalProtocolStore()
1939 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
1940 verifiedMessage
.getIdentityKey(),
1941 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1943 if (syncMessage
.getStickerPackOperations().isPresent()) {
1944 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
1946 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
1947 if (!m
.getPackId().isPresent()) {
1950 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
1951 if (sticker
== null) {
1952 if (!m
.getPackKey().isPresent()) {
1955 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
1957 sticker
.setInstalled(!m
.getType().isPresent()
1958 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
1959 account
.getStickerStore().updateSticker(sticker
);
1962 if (syncMessage
.getConfiguration().isPresent()) {
1970 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
1972 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
1973 } catch (IOException e
) {
1974 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
1978 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
1980 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
1981 } catch (IOException e
) {
1982 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
1986 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
1988 avatarStore
.storeGroupAvatar(groupId
,
1989 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
1990 } catch (IOException e
) {
1991 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
1995 private void downloadProfileAvatar(
1996 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
1999 avatarStore
.storeProfileAvatar(address
,
2000 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2001 } catch (Throwable e
) {
2002 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2006 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2007 return attachmentStore
.getAttachmentFile(attachmentId
);
2010 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2011 if (!attachment
.isPointer()) {
2012 logger
.warn("Invalid state, can't store an attachment stream.");
2015 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2016 if (pointer
.getPreview().isPresent()) {
2017 final byte[] preview
= pointer
.getPreview().get();
2019 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2020 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2021 } catch (IOException e
) {
2022 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2027 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2028 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2029 } catch (IOException e
) {
2030 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2034 private void retrieveGroupV2Avatar(
2035 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2036 ) throws IOException
{
2037 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2039 File tmpFile
= IOUtils
.createTempFile();
2040 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2042 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2043 byte[] encryptedData
= IOUtils
.readFully(input
);
2045 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2046 outputStream
.write(decryptedData
);
2049 Files
.delete(tmpFile
.toPath());
2050 } catch (IOException e
) {
2051 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2058 private void retrieveProfileAvatar(
2059 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2060 ) throws IOException
{
2061 File tmpFile
= IOUtils
.createTempFile();
2062 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2065 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2066 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2067 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2070 Files
.delete(tmpFile
.toPath());
2071 } catch (IOException e
) {
2072 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2079 private void retrieveAttachment(
2080 final SignalServiceAttachment attachment
, final OutputStream outputStream
2081 ) throws IOException
{
2082 if (attachment
.isPointer()) {
2083 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2084 retrieveAttachmentPointer(pointer
, outputStream
);
2086 SignalServiceAttachmentStream stream
= attachment
.asStream();
2087 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2091 private void retrieveAttachmentPointer(
2092 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2093 ) throws IOException
{
2094 File tmpFile
= IOUtils
.createTempFile();
2095 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2096 IOUtils
.copyStream(input
, outputStream
);
2097 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2098 throw new IOException(e
);
2101 Files
.delete(tmpFile
.toPath());
2102 } catch (IOException e
) {
2103 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2110 private InputStream
retrieveAttachmentAsStream(
2111 SignalServiceAttachmentPointer pointer
, File tmpFile
2112 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2113 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2116 void sendGroups() throws IOException
, UntrustedIdentityException
{
2117 File groupsFile
= IOUtils
.createTempFile();
2120 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2121 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2122 for (GroupInfo
record : getGroups()) {
2123 if (record instanceof GroupInfoV1
) {
2124 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2125 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2126 Optional
.fromNullable(groupInfo
.name
),
2127 new ArrayList
<>(groupInfo
.getMembers()),
2128 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2129 groupInfo
.isMember(account
.getSelfAddress()),
2130 Optional
.of(groupInfo
.messageExpirationTime
),
2131 Optional
.fromNullable(groupInfo
.color
),
2133 Optional
.fromNullable(groupInfo
.inboxPosition
),
2134 groupInfo
.archived
));
2139 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2140 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2141 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2142 .withStream(groupsFileStream
)
2143 .withContentType("application/octet-stream")
2144 .withLength(groupsFile
.length())
2147 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2152 Files
.delete(groupsFile
.toPath());
2153 } catch (IOException e
) {
2154 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2159 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2160 File contactsFile
= IOUtils
.createTempFile();
2163 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2164 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2165 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2166 VerifiedMessage verifiedMessage
= null;
2167 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2168 if (currentIdentity
!= null) {
2169 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2170 currentIdentity
.getIdentityKey(),
2171 currentIdentity
.getTrustLevel().toVerifiedState(),
2172 currentIdentity
.getDateAdded().getTime());
2175 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2176 out
.write(new DeviceContact(record.getAddress(),
2177 Optional
.fromNullable(record.name
),
2178 createContactAvatarAttachment(record.getAddress()),
2179 Optional
.fromNullable(record.color
),
2180 Optional
.fromNullable(verifiedMessage
),
2181 Optional
.fromNullable(profileKey
),
2183 Optional
.of(record.messageExpirationTime
),
2184 Optional
.fromNullable(record.inboxPosition
),
2188 if (account
.getProfileKey() != null) {
2189 // Send our own profile key as well
2190 out
.write(new DeviceContact(account
.getSelfAddress(),
2195 Optional
.of(account
.getProfileKey()),
2203 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2204 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2205 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2206 .withStream(contactsFileStream
)
2207 .withContentType("application/octet-stream")
2208 .withLength(contactsFile
.length())
2211 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2216 Files
.delete(contactsFile
.toPath());
2217 } catch (IOException e
) {
2218 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2223 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2224 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2225 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2226 if (record.blocked
) {
2227 addresses
.add(record.getAddress());
2230 List
<byte[]> groupIds
= new ArrayList
<>();
2231 for (GroupInfo
record : getGroups()) {
2232 if (record.isBlocked()) {
2233 groupIds
.add(record.getGroupId().serialize());
2236 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2239 private void sendVerifiedMessage(
2240 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2241 ) throws IOException
, UntrustedIdentityException
{
2242 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2244 trustLevel
.toVerifiedState(),
2245 System
.currentTimeMillis());
2246 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2249 public List
<ContactInfo
> getContacts() {
2250 return account
.getContactStore().getContacts();
2253 public ContactInfo
getContact(String number
) {
2254 return account
.getContactStore().getContact(Utils
.getSignalServiceAddressFromIdentifier(number
));
2257 public GroupInfo
getGroup(GroupId groupId
) {
2258 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2259 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2260 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2261 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2262 account
.getGroupStore().updateGroup(group
);
2267 public List
<IdentityInfo
> getIdentities() {
2268 return account
.getSignalProtocolStore().getIdentities();
2271 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2272 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2276 * Trust this the identity with this fingerprint
2278 * @param name username of the identity
2279 * @param fingerprint Fingerprint
2281 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2282 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2283 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2287 for (IdentityInfo id
: ids
) {
2288 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2292 account
.getSignalProtocolStore()
2293 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2295 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2296 } catch (IOException
| UntrustedIdentityException e
) {
2297 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2306 * Trust this the identity with this safety number
2308 * @param name username of the identity
2309 * @param safetyNumber Safety number
2311 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2312 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2313 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2317 for (IdentityInfo id
: ids
) {
2318 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2322 account
.getSignalProtocolStore()
2323 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2325 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2326 } catch (IOException
| UntrustedIdentityException e
) {
2327 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2336 * Trust all keys of this identity without verification
2338 * @param name username of the identity
2340 public boolean trustIdentityAllKeys(String name
) {
2341 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2342 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2346 for (IdentityInfo id
: ids
) {
2347 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2348 account
.getSignalProtocolStore()
2349 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2351 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2352 } catch (IOException
| UntrustedIdentityException e
) {
2353 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2361 public String
computeSafetyNumber(
2362 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2364 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2365 account
.getSelfAddress(),
2366 getIdentityKeyPair().getPublicKey(),
2371 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2372 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2374 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2375 return resolveSignalServiceAddress(canonicalizedNumber
);
2378 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2379 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2381 return resolveSignalServiceAddress(address
);
2384 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2385 if (address
.matches(account
.getSelfAddress())) {
2386 return account
.getSelfAddress();
2389 return account
.getRecipientStore().resolveServiceAddress(address
);
2393 public void close() throws IOException
{
2397 void close(boolean closeAccount
) throws IOException
{
2398 if (messagePipe
!= null) {
2399 messagePipe
.shutdown();
2403 if (unidentifiedMessagePipe
!= null) {
2404 unidentifiedMessagePipe
.shutdown();
2405 unidentifiedMessagePipe
= null;
2408 if (closeAccount
&& account
!= null) {
2414 public interface ReceiveMessageHandler
{
2416 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);