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 void checkAccountState() throws IOException
{
292 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
296 if (account
.getUuid() == null) {
297 account
.setUuid(accountManager
.getOwnUuid());
300 updateAccountAttributes();
304 * This is used for checking a set of phone numbers for registration on Signal
306 * @param numbers The set of phone number in question
307 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
308 * @throws IOException if its unable to get the contacts to check if they're registered
310 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
311 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
312 List
<ContactTokenDetails
> contactDetails
= this.accountManager
.getContacts(numbers
);
314 Set
<String
> registeredUsers
= contactDetails
.stream()
315 .map(ContactTokenDetails
::getNumber
)
316 .collect(Collectors
.toSet());
318 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
321 public void updateAccountAttributes() throws IOException
{
322 accountManager
.setAccountAttributes(account
.getSignalingKey(),
323 account
.getSignalProtocolStore().getLocalRegistrationId(),
325 // set legacy pin only if no KBS master key is set
326 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
327 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
328 account
.getSelfUnidentifiedAccessKey(),
329 account
.isUnrestrictedUnidentifiedAccess(),
331 account
.isDiscoverableByPhoneNumber());
335 * @param avatar if avatar is null the image from the local avatar store is used (if present),
336 * if it's Optional.absent(), the avatar will be removed
338 public void setProfile(String name
, Optional
<File
> avatar
) throws IOException
{
339 try (final StreamDetails streamDetails
= avatar
== null
340 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
341 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
342 accountManager
.setVersionedProfile(account
.getUuid(), account
.getProfileKey(), name
, streamDetails
);
345 if (avatar
!= null) {
346 if (avatar
.isPresent()) {
347 avatarStore
.storeProfileAvatar(getSelfAddress(),
348 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
350 avatarStore
.deleteProfileAvatar(getSelfAddress());
355 public void unregister() throws IOException
{
356 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
357 // If this is the master device, other users can't send messages to this number anymore.
358 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
359 accountManager
.setGcmId(Optional
.absent());
361 account
.setRegistered(false);
365 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
366 List
<DeviceInfo
> devices
= accountManager
.getDevices();
367 account
.setMultiDevice(devices
.size() > 1);
372 public void removeLinkedDevices(int deviceId
) throws IOException
{
373 accountManager
.removeDevice(deviceId
);
374 List
<DeviceInfo
> devices
= accountManager
.getDevices();
375 account
.setMultiDevice(devices
.size() > 1);
379 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
380 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
382 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
385 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
386 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
387 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
389 accountManager
.addDevice(deviceIdentifier
,
392 Optional
.of(account
.getProfileKey().serialize()),
394 account
.setMultiDevice(true);
398 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
399 if (pin
.isPresent()) {
400 final MasterKey masterKey
= account
.getPinMasterKey() != null
401 ? account
.getPinMasterKey()
402 : KeyUtils
.createMasterKey();
404 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
406 account
.setRegistrationLockPin(pin
.get());
407 account
.setPinMasterKey(masterKey
);
409 // Remove legacy registration lock
410 accountManager
.removeRegistrationLockV1();
413 pinHelper
.removeRegistrationLockPin();
415 account
.setRegistrationLockPin(null);
416 account
.setPinMasterKey(null);
421 void refreshPreKeys() throws IOException
{
422 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
423 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
424 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
426 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
429 private List
<PreKeyRecord
> generatePreKeys() {
430 final int offset
= account
.getPreKeyIdOffset();
432 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
433 account
.addPreKeys(records
);
439 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
440 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
442 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
443 account
.addSignedPreKey(record);
449 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
450 if (messagePipe
== null) {
451 messagePipe
= messageReceiver
.createMessagePipe();
456 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
457 if (unidentifiedMessagePipe
== null) {
458 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
460 return unidentifiedMessagePipe
;
463 private SignalServiceMessageSender
createMessageSender() {
464 final ExecutorService executor
= null;
465 return new SignalServiceMessageSender(serviceConfiguration
,
467 account
.getUsername(),
468 account
.getPassword(),
469 account
.getDeviceId(),
470 account
.getSignalProtocolStore(),
472 account
.isMultiDevice(),
473 Optional
.fromNullable(messagePipe
),
474 Optional
.fromNullable(unidentifiedMessagePipe
),
476 clientZkProfileOperations
,
478 ServiceConfig
.MAX_ENVELOPE_SIZE
);
481 private SignalProfile
getRecipientProfile(
482 SignalServiceAddress address
484 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
485 if (profileEntry
== null) {
488 long now
= new Date().getTime();
489 // Profiles are cached for 24h before retrieving them again
490 if (!profileEntry
.isRequestPending() && (
491 profileEntry
.getProfile() == null || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
493 profileEntry
.setRequestPending(true);
494 final SignalServiceProfile encryptedProfile
;
496 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
498 } catch (IOException e
) {
499 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
502 profileEntry
.setRequestPending(false);
505 final ProfileKey profileKey
= profileEntry
.getProfileKey();
506 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
507 account
.getProfileStore()
508 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
511 return profileEntry
.getProfile();
514 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
515 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
516 if (profileEntry
== null) {
519 if (profileEntry
.getProfileKeyCredential() == null) {
520 ProfileAndCredential profileAndCredential
;
522 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
523 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
524 } catch (IOException e
) {
525 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
529 long now
= new Date().getTime();
530 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
531 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
532 profileEntry
.getProfileKey(),
533 profileAndCredential
.getProfile());
534 account
.getProfileStore()
535 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
536 return profileKeyCredential
;
538 return profileEntry
.getProfileKeyCredential();
541 private SignalProfile
decryptProfileAndDownloadAvatar(
542 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
544 if (encryptedProfile
.getAvatar() != null) {
545 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
548 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
551 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
552 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
553 if (streamDetails
== null) {
554 return Optional
.absent();
557 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
560 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
561 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
562 if (streamDetails
== null) {
563 return Optional
.absent();
566 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
569 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
570 GroupInfo g
= getGroup(groupId
);
572 throw new GroupNotFoundException(groupId
);
574 if (!g
.isMember(account
.getSelfAddress())) {
575 throw new NotAGroupMemberException(groupId
, g
.getTitle());
580 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
581 GroupInfo g
= getGroup(groupId
);
583 throw new GroupNotFoundException(groupId
);
585 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
586 throw new NotAGroupMemberException(groupId
, g
.getTitle());
591 public List
<GroupInfo
> getGroups() {
592 return account
.getGroupStore().getGroups();
595 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
596 String messageText
, List
<String
> attachments
, GroupId groupId
597 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
598 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
599 .withBody(messageText
);
600 if (attachments
!= null) {
601 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
604 return sendGroupMessage(messageBuilder
, groupId
);
607 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
608 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
609 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
610 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
612 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
613 targetSentTimestamp
);
614 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
615 .withReaction(reaction
);
617 return sendGroupMessage(messageBuilder
, groupId
);
620 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
621 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
622 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
623 final GroupInfo g
= getGroupForSending(groupId
);
625 GroupUtils
.setGroupContext(messageBuilder
, g
);
626 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
628 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
631 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
632 SignalServiceDataMessage
.Builder messageBuilder
;
634 final GroupInfo g
= getGroupForUpdating(groupId
);
635 if (g
instanceof GroupInfoV1
) {
636 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
637 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
638 .withId(groupId
.serialize())
640 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
641 groupInfoV1
.removeMember(account
.getSelfAddress());
642 account
.getGroupStore().updateGroup(groupInfoV1
);
644 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
645 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
646 groupInfoV2
.setGroup(groupGroupChangePair
.first());
647 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
648 account
.getGroupStore().updateGroup(groupInfoV2
);
651 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
654 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
655 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
656 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
657 return sendUpdateGroupMessage(groupId
,
659 members
== null ?
null : getSignalServiceAddresses(members
),
663 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
664 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
665 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
667 SignalServiceDataMessage
.Builder messageBuilder
;
668 if (groupId
== null) {
670 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
671 members
== null ? List
.of() : members
,
674 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
675 gv1
.addMembers(List
.of(account
.getSelfAddress()));
676 updateGroupV1(gv1
, name
, members
, avatarFile
);
677 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
680 if (avatarFile
!= null) {
681 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
682 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
684 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
688 GroupInfo group
= getGroupForUpdating(groupId
);
689 if (group
instanceof GroupInfoV2
) {
690 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
692 Pair
<Long
, List
<SendMessageResult
>> result
= null;
693 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
694 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
695 result
= sendUpdateGroupMessage(groupInfoV2
,
696 groupGroupChangePair
.first(),
697 groupGroupChangePair
.second());
700 if (members
!= null) {
701 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
702 newMembers
.removeAll(group
.getMembers()
704 .map(this::resolveSignalServiceAddress
)
705 .collect(Collectors
.toSet()));
706 if (newMembers
.size() > 0) {
707 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
709 result
= sendUpdateGroupMessage(groupInfoV2
,
710 groupGroupChangePair
.first(),
711 groupGroupChangePair
.second());
714 if (result
== null || name
!= null || avatarFile
!= null) {
715 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
718 if (avatarFile
!= null) {
719 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
720 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
722 result
= sendUpdateGroupMessage(groupInfoV2
,
723 groupGroupChangePair
.first(),
724 groupGroupChangePair
.second());
727 return new Pair
<>(group
.getGroupId(), result
.second());
729 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
730 updateGroupV1(gv1
, name
, members
, avatarFile
);
731 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
736 account
.getGroupStore().updateGroup(g
);
738 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
739 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
740 return new Pair
<>(g
.getGroupId(), result
.second());
743 private void updateGroupV1(
746 final Collection
<SignalServiceAddress
> members
,
747 final File avatarFile
748 ) throws IOException
{
753 if (members
!= null) {
754 final Set
<String
> newE164Members
= new HashSet
<>();
755 for (SignalServiceAddress member
: members
) {
756 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
759 newE164Members
.add(member
.getNumber().get());
762 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newE164Members
);
763 if (contacts
.size() != newE164Members
.size()) {
764 // Some of the new members are not registered on Signal
765 for (ContactTokenDetails contact
: contacts
) {
766 newE164Members
.remove(contact
.getNumber());
768 throw new IOException("Failed to add members "
769 + String
.join(", ", newE164Members
)
770 + " to group: Not registered on Signal");
773 g
.addMembers(members
);
776 if (avatarFile
!= null) {
777 avatarStore
.storeGroupAvatar(g
.getGroupId(),
778 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
782 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
783 GroupInviteLinkUrl inviteLinkUrl
784 ) throws IOException
, GroupLinkNotActiveException
{
785 return sendJoinGroupMessage(inviteLinkUrl
);
788 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
789 GroupInviteLinkUrl inviteLinkUrl
790 ) throws IOException
, GroupLinkNotActiveException
{
791 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
792 inviteLinkUrl
.getPassword());
793 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
794 inviteLinkUrl
.getPassword(),
796 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
797 groupJoinInfo
.getRevision() + 1,
798 groupChange
.toByteArray());
800 if (group
.getGroup() == null) {
801 // Only requested member, can't send update to group members
802 return new Pair
<>(group
.getGroupId(), List
.of());
805 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
807 return new Pair
<>(group
.getGroupId(), result
.second());
810 private static int currentTimeDays() {
811 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
814 private GroupsV2AuthorizationString
getGroupAuthForToday(
815 final GroupSecretParams groupSecretParams
816 ) throws IOException
{
817 final int today
= currentTimeDays();
818 // Returns credentials for the next 7 days
819 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
820 // TODO cache credentials until they expire
821 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
823 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
826 authCredentialResponse
);
827 } catch (VerificationFailedException e
) {
828 throw new IOException(e
);
832 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
833 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
834 ) throws IOException
{
835 group
.setGroup(newDecryptedGroup
);
836 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
837 groupChange
.toByteArray());
838 account
.getGroupStore().updateGroup(group
);
839 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
842 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
843 GroupIdV1 groupId
, SignalServiceAddress recipient
844 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
846 GroupInfo group
= getGroupForSending(groupId
);
847 if (!(group
instanceof GroupInfoV1
)) {
848 throw new RuntimeException("Received an invalid group request for a v2 group!");
850 g
= (GroupInfoV1
) group
;
852 if (!g
.isMember(recipient
)) {
853 throw new NotAGroupMemberException(groupId
, g
.name
);
856 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
858 // Send group message only to the recipient who requested it
859 return sendMessage(messageBuilder
, List
.of(recipient
));
862 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
863 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
864 .withId(g
.getGroupId().serialize())
866 .withMembers(new ArrayList
<>(g
.getMembers()));
869 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
870 if (attachment
.isPresent()) {
871 group
.withAvatar(attachment
.get());
873 } catch (IOException e
) {
874 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
877 return SignalServiceDataMessage
.newBuilder()
878 .asGroupMessage(group
.build())
879 .withExpiration(g
.getMessageExpirationTime());
882 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
883 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
884 .withRevision(g
.getGroup().getRevision())
885 .withSignedGroupChange(signedGroupChange
);
886 return SignalServiceDataMessage
.newBuilder()
887 .asGroupMessage(group
.build())
888 .withExpiration(g
.getMessageExpirationTime());
891 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
892 GroupIdV1 groupId
, SignalServiceAddress recipient
893 ) throws IOException
{
894 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
895 .withId(groupId
.serialize());
897 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
898 .asGroupMessage(group
.build());
900 // Send group info request message to the recipient who sent us a message with this groupId
901 return sendMessage(messageBuilder
, List
.of(recipient
));
905 SignalServiceAddress remoteAddress
, long messageId
906 ) throws IOException
, UntrustedIdentityException
{
907 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
909 System
.currentTimeMillis());
911 createMessageSender().sendReceipt(remoteAddress
,
912 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
916 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
917 String messageText
, List
<String
> attachments
, List
<String
> recipients
918 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
919 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
920 .withBody(messageText
);
921 if (attachments
!= null) {
922 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
924 // Upload attachments here, so we only upload once even for multiple recipients
925 SignalServiceMessageSender messageSender
= createMessageSender();
926 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
927 for (SignalServiceAttachment attachment
: attachmentStreams
) {
928 if (attachment
.isStream()) {
929 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
930 } else if (attachment
.isPointer()) {
931 attachmentPointers
.add(attachment
.asPointer());
935 messageBuilder
.withAttachments(attachmentPointers
);
937 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
940 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
941 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
942 ) throws IOException
, InvalidNumberException
{
943 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
945 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
946 targetSentTimestamp
);
947 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
948 .withReaction(reaction
);
949 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
952 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
953 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
955 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
957 return sendMessage(messageBuilder
, signalServiceAddresses
);
958 } catch (Exception e
) {
959 for (SignalServiceAddress address
: signalServiceAddresses
) {
960 handleEndSession(address
);
967 public String
getContactName(String number
) throws InvalidNumberException
{
968 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
969 if (contact
== null) {
976 public void setContactName(String number
, String name
) throws InvalidNumberException
{
977 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
978 ContactInfo contact
= account
.getContactStore().getContact(address
);
979 if (contact
== null) {
980 contact
= new ContactInfo(address
);
983 account
.getContactStore().updateContact(contact
);
987 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
988 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
991 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
992 ContactInfo contact
= account
.getContactStore().getContact(address
);
993 if (contact
== null) {
994 contact
= new ContactInfo(address
);
996 contact
.blocked
= blocked
;
997 account
.getContactStore().updateContact(contact
);
1001 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1002 GroupInfo group
= getGroup(groupId
);
1003 if (group
== null) {
1004 throw new GroupNotFoundException(groupId
);
1007 group
.setBlocked(blocked
);
1008 account
.getGroupStore().updateGroup(group
);
1013 * Change the expiration timer for a contact
1015 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1016 ContactInfo contact
= account
.getContactStore().getContact(address
);
1017 contact
.messageExpirationTime
= messageExpirationTimer
;
1018 account
.getContactStore().updateContact(contact
);
1019 sendExpirationTimerUpdate(address
);
1023 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1024 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1025 .asExpirationUpdate();
1026 sendMessage(messageBuilder
, List
.of(address
));
1030 * Change the expiration timer for a contact
1032 public void setExpirationTimer(
1033 String number
, int messageExpirationTimer
1034 ) throws IOException
, InvalidNumberException
{
1035 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1036 setExpirationTimer(address
, messageExpirationTimer
);
1040 * Change the expiration timer for a group
1042 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1043 GroupInfo g
= getGroup(groupId
);
1044 if (g
instanceof GroupInfoV1
) {
1045 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1046 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1047 account
.getGroupStore().updateGroup(groupInfoV1
);
1049 throw new RuntimeException("TODO Not implemented!");
1054 * Upload the sticker pack from path.
1056 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1057 * @return if successful, returns the URL to install the sticker pack in the signal app
1059 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1060 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1062 SignalServiceMessageSender messageSender
= createMessageSender();
1064 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1065 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1067 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1068 account
.getStickerStore().updateSticker(sticker
);
1072 return new URI("https",
1075 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1076 Hex
.toStringCondensed(packKey
),
1077 StandardCharsets
.UTF_8
)).toString();
1078 } catch (URISyntaxException e
) {
1079 throw new AssertionError(e
);
1083 void requestSyncGroups() throws IOException
{
1084 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1085 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1087 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1089 sendSyncMessage(message
);
1090 } catch (UntrustedIdentityException e
) {
1091 throw new AssertionError(e
);
1095 void requestSyncContacts() throws IOException
{
1096 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1097 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1099 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1101 sendSyncMessage(message
);
1102 } catch (UntrustedIdentityException e
) {
1103 throw new AssertionError(e
);
1107 void requestSyncBlocked() throws IOException
{
1108 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1109 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1111 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1113 sendSyncMessage(message
);
1114 } catch (UntrustedIdentityException e
) {
1115 throw new AssertionError(e
);
1119 void requestSyncConfiguration() throws IOException
{
1120 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1121 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1123 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1125 sendSyncMessage(message
);
1126 } catch (UntrustedIdentityException e
) {
1127 throw new AssertionError(e
);
1131 private byte[] getSenderCertificate() {
1132 // TODO support UUID capable sender certificates
1133 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1136 certificate
= accountManager
.getSenderCertificate();
1137 } catch (IOException e
) {
1138 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1141 // TODO cache for a day
1145 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1146 SignalServiceMessageSender messageSender
= createMessageSender();
1148 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1149 } catch (UntrustedIdentityException e
) {
1150 account
.getSignalProtocolStore()
1151 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1153 TrustLevel
.UNTRUSTED
);
1158 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1159 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1160 final Set
<SignalServiceAddress
> missingUuids
= new HashSet
<>();
1162 for (String number
: numbers
) {
1163 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1164 if (resolvedAddress
.getUuid().isPresent()) {
1165 signalServiceAddresses
.add(resolvedAddress
);
1167 missingUuids
.add(resolvedAddress
);
1171 Map
<String
, UUID
> registeredUsers
;
1173 registeredUsers
= accountManager
.getRegisteredUsers(getIasKeyStore(),
1174 missingUuids
.stream().map(a
-> a
.getNumber().get()).collect(Collectors
.toSet()),
1176 } catch (IOException
| Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException e
) {
1177 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1178 registeredUsers
= new HashMap
<>();
1181 for (SignalServiceAddress address
: missingUuids
) {
1182 final String number
= address
.getNumber().get();
1183 if (registeredUsers
.containsKey(number
)) {
1184 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1185 registeredUsers
.get(number
),
1187 signalServiceAddresses
.add(newAddress
);
1189 signalServiceAddresses
.add(address
);
1193 return signalServiceAddresses
;
1196 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1197 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1198 ) throws IOException
{
1199 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1200 final long timestamp
= System
.currentTimeMillis();
1201 messageBuilder
.withTimestamp(timestamp
);
1202 getOrCreateMessagePipe();
1203 getOrCreateUnidentifiedMessagePipe();
1204 SignalServiceDataMessage message
= null;
1206 message
= messageBuilder
.build();
1207 if (message
.getGroupContext().isPresent()) {
1209 SignalServiceMessageSender messageSender
= createMessageSender();
1210 final boolean isRecipientUpdate
= false;
1211 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1212 unidentifiedAccessHelper
.getAccessFor(recipients
),
1215 for (SendMessageResult r
: result
) {
1216 if (r
.getIdentityFailure() != null) {
1217 account
.getSignalProtocolStore()
1218 .saveIdentity(r
.getAddress(),
1219 r
.getIdentityFailure().getIdentityKey(),
1220 TrustLevel
.UNTRUSTED
);
1223 return new Pair
<>(timestamp
, result
);
1224 } catch (UntrustedIdentityException e
) {
1225 account
.getSignalProtocolStore()
1226 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1228 TrustLevel
.UNTRUSTED
);
1229 return new Pair
<>(timestamp
, List
.of());
1232 // Send to all individually, so sync messages are sent correctly
1233 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1234 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1235 for (SignalServiceAddress address
: recipients
) {
1236 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1237 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1238 messageBuilder
.withExpiration(expirationTime
);
1239 message
= messageBuilder
.build();
1240 if (address
.matches(account
.getSelfAddress())) {
1241 results
.add(sendSelfMessage(message
));
1243 results
.add(sendMessage(address
, message
));
1246 return new Pair
<>(timestamp
, results
);
1249 if (message
!= null && message
.isEndSession()) {
1250 for (SignalServiceAddress recipient
: recipients
) {
1251 handleEndSession(recipient
);
1258 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1259 SignalServiceMessageSender messageSender
= createMessageSender();
1261 SignalServiceAddress recipient
= account
.getSelfAddress();
1263 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1264 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1265 message
.getTimestamp(),
1267 message
.getExpiresInSeconds(),
1268 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1270 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1273 long startTime
= System
.currentTimeMillis();
1274 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1275 return SendMessageResult
.success(recipient
,
1276 unidentifiedAccess
.isPresent(),
1278 System
.currentTimeMillis() - startTime
);
1279 } catch (UntrustedIdentityException e
) {
1280 account
.getSignalProtocolStore()
1281 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1283 TrustLevel
.UNTRUSTED
);
1284 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1288 private SendMessageResult
sendMessage(
1289 SignalServiceAddress address
, SignalServiceDataMessage message
1290 ) throws IOException
{
1291 SignalServiceMessageSender messageSender
= createMessageSender();
1294 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1295 } catch (UntrustedIdentityException e
) {
1296 account
.getSignalProtocolStore()
1297 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1299 TrustLevel
.UNTRUSTED
);
1300 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1304 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1305 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1306 account
.getSignalProtocolStore(),
1307 certificateValidator
);
1309 return cipher
.decrypt(envelope
);
1310 } catch (ProtocolUntrustedIdentityException e
) {
1311 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1312 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1314 account
.getSignalProtocolStore()
1315 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1316 identityException
.getUntrustedIdentity(),
1317 TrustLevel
.UNTRUSTED
);
1318 throw identityException
;
1320 throw new AssertionError(e
);
1324 private void handleEndSession(SignalServiceAddress source
) {
1325 account
.getSignalProtocolStore().deleteAllSessions(source
);
1328 private List
<HandleAction
> handleSignalServiceDataMessage(
1329 SignalServiceDataMessage message
,
1331 SignalServiceAddress source
,
1332 SignalServiceAddress destination
,
1333 boolean ignoreAttachments
1335 List
<HandleAction
> actions
= new ArrayList
<>();
1336 if (message
.getGroupContext().isPresent()) {
1337 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1338 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1339 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1340 GroupInfo group
= getGroup(groupId
);
1341 if (group
== null || group
instanceof GroupInfoV1
) {
1342 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1343 switch (groupInfo
.getType()) {
1345 if (groupV1
== null) {
1346 groupV1
= new GroupInfoV1(groupId
);
1349 if (groupInfo
.getAvatar().isPresent()) {
1350 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1351 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1354 if (groupInfo
.getName().isPresent()) {
1355 groupV1
.name
= groupInfo
.getName().get();
1358 if (groupInfo
.getMembers().isPresent()) {
1359 groupV1
.addMembers(groupInfo
.getMembers()
1362 .map(this::resolveSignalServiceAddress
)
1363 .collect(Collectors
.toSet()));
1366 account
.getGroupStore().updateGroup(groupV1
);
1370 if (groupV1
== null && !isSync
) {
1371 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1375 if (groupV1
!= null) {
1376 groupV1
.removeMember(source
);
1377 account
.getGroupStore().updateGroup(groupV1
);
1382 if (groupV1
!= null && !isSync
) {
1383 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1388 // Received a group v1 message for a v2 group
1391 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1392 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1393 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1395 getOrMigrateGroup(groupMasterKey
,
1396 groupContext
.getRevision(),
1397 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1401 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1402 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1403 handleEndSession(conversationPartnerAddress
);
1405 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1406 if (message
.getGroupContext().isPresent()) {
1407 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1408 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1409 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1410 if (group
!= null) {
1411 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1412 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1413 account
.getGroupStore().updateGroup(group
);
1416 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1417 // disappearing message timer already stored in the DecryptedGroup
1419 } else if (conversationPartnerAddress
!= null) {
1420 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1421 if (contact
== null) {
1422 contact
= new ContactInfo(conversationPartnerAddress
);
1424 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1425 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1426 account
.getContactStore().updateContact(contact
);
1430 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1431 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1432 downloadAttachment(attachment
);
1435 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1436 final ProfileKey profileKey
;
1438 profileKey
= new ProfileKey(message
.getProfileKey().get());
1439 } catch (InvalidInputException e
) {
1440 throw new AssertionError(e
);
1442 if (source
.matches(account
.getSelfAddress())) {
1443 this.account
.setProfileKey(profileKey
);
1445 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1447 if (message
.getPreviews().isPresent()) {
1448 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1449 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1450 if (preview
.getImage().isPresent()) {
1451 downloadAttachment(preview
.getImage().get());
1455 if (message
.getQuote().isPresent()) {
1456 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1458 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1459 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1460 if (thumbnail
!= null) {
1461 downloadAttachment(thumbnail
);
1465 if (message
.getSticker().isPresent()) {
1466 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1467 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1468 if (sticker
== null) {
1469 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1470 account
.getStickerStore().updateSticker(sticker
);
1476 private GroupInfoV2
getOrMigrateGroup(
1477 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1479 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1481 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1482 GroupInfo groupInfo
= getGroup(groupId
);
1483 final GroupInfoV2 groupInfoV2
;
1484 if (groupInfo
instanceof GroupInfoV1
) {
1485 // Received a v2 group message for a v1 group, we need to locally migrate the group
1486 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1487 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1488 logger
.info("Locally migrated group {} to group v2, id: {}",
1489 groupInfo
.getGroupId().toBase64(),
1490 groupInfoV2
.getGroupId().toBase64());
1491 } else if (groupInfo
instanceof GroupInfoV2
) {
1492 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1494 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1497 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1498 DecryptedGroup group
= null;
1499 if (signedGroupChange
!= null
1500 && groupInfoV2
.getGroup() != null
1501 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1502 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1504 if (group
== null) {
1505 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1507 if (group
!= null) {
1508 storeProfileKeysFromMembers(group
);
1509 final String avatar
= group
.getAvatar();
1510 if (avatar
!= null && !avatar
.isEmpty()) {
1511 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1514 groupInfoV2
.setGroup(group
);
1515 account
.getGroupStore().updateGroup(groupInfoV2
);
1521 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1522 for (DecryptedMember member
: group
.getMembersList()) {
1523 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1524 member
.getUuid().toByteArray()), null));
1526 account
.getProfileStore()
1527 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1528 } catch (InvalidInputException ignored
) {
1533 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1534 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1535 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1539 private void retryFailedReceivedMessage(
1540 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1542 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1543 if (envelope
== null) {
1546 SignalServiceContent content
= null;
1547 if (!envelope
.isReceipt()) {
1549 content
= decryptMessage(envelope
);
1550 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1552 } catch (Exception er
) {
1553 // All other errors are not recoverable, so delete the cached message
1554 cachedMessage
.delete();
1557 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1558 for (HandleAction action
: actions
) {
1560 action
.execute(this);
1561 } catch (Throwable e
) {
1562 logger
.warn("Message action failed.", e
);
1567 handler
.handleMessage(envelope
, content
, null);
1568 cachedMessage
.delete();
1571 public void receiveMessages(
1574 boolean returnOnTimeout
,
1575 boolean ignoreAttachments
,
1576 ReceiveMessageHandler handler
1577 ) throws IOException
{
1578 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1580 Set
<HandleAction
> queuedActions
= null;
1582 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1584 boolean hasCaughtUpWithOldMessages
= false;
1587 SignalServiceEnvelope envelope
;
1588 SignalServiceContent content
= null;
1589 Exception exception
= null;
1590 final CachedMessage
[] cachedMessage
= {null};
1592 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1593 // store message on disk, before acknowledging receipt to the server
1594 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1596 if (result
.isPresent()) {
1597 envelope
= result
.get();
1599 // Received indicator that server queue is empty
1600 hasCaughtUpWithOldMessages
= true;
1602 if (queuedActions
!= null) {
1603 for (HandleAction action
: queuedActions
) {
1605 action
.execute(this);
1606 } catch (Throwable e
) {
1607 logger
.warn("Message action failed.", e
);
1611 queuedActions
.clear();
1612 queuedActions
= null;
1615 // Continue to wait another timeout for new messages
1618 } catch (TimeoutException e
) {
1619 if (returnOnTimeout
) return;
1621 } catch (InvalidVersionException e
) {
1622 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1626 if (envelope
.hasSource()) {
1627 // Store uuid if we don't have it already
1628 SignalServiceAddress source
= envelope
.getSourceAddress();
1629 resolveSignalServiceAddress(source
);
1631 if (!envelope
.isReceipt()) {
1633 content
= decryptMessage(envelope
);
1634 } catch (Exception e
) {
1637 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1638 if (hasCaughtUpWithOldMessages
) {
1639 for (HandleAction action
: actions
) {
1641 action
.execute(this);
1642 } catch (Throwable e
) {
1643 logger
.warn("Message action failed.", e
);
1647 if (queuedActions
== null) {
1648 queuedActions
= new HashSet
<>();
1650 queuedActions
.addAll(actions
);
1654 if (isMessageBlocked(envelope
, content
)) {
1655 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1656 } else if (isNotAGroupMember(envelope
, content
)) {
1657 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1659 handler
.handleMessage(envelope
, content
, exception
);
1661 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1662 if (cachedMessage
[0] != null) {
1663 cachedMessage
[0].delete();
1669 private boolean isMessageBlocked(
1670 SignalServiceEnvelope envelope
, SignalServiceContent content
1672 SignalServiceAddress source
;
1673 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1674 source
= envelope
.getSourceAddress();
1675 } else if (content
!= null) {
1676 source
= content
.getSender();
1680 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1681 if (sourceContact
!= null && sourceContact
.blocked
) {
1685 if (content
!= null && content
.getDataMessage().isPresent()) {
1686 SignalServiceDataMessage message
= content
.getDataMessage().get();
1687 if (message
.getGroupContext().isPresent()) {
1688 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1689 GroupInfo group
= getGroup(groupId
);
1690 if (group
!= null && group
.isBlocked()) {
1698 private boolean isNotAGroupMember(
1699 SignalServiceEnvelope envelope
, SignalServiceContent content
1701 SignalServiceAddress source
;
1702 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1703 source
= envelope
.getSourceAddress();
1704 } else if (content
!= null) {
1705 source
= content
.getSender();
1710 if (content
!= null && content
.getDataMessage().isPresent()) {
1711 SignalServiceDataMessage message
= content
.getDataMessage().get();
1712 if (message
.getGroupContext().isPresent()) {
1713 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1714 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1715 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1719 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1720 GroupInfo group
= getGroup(groupId
);
1721 if (group
!= null && !group
.isMember(source
)) {
1729 private List
<HandleAction
> handleMessage(
1730 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1732 List
<HandleAction
> actions
= new ArrayList
<>();
1733 if (content
!= null) {
1734 final SignalServiceAddress sender
;
1735 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1736 sender
= envelope
.getSourceAddress();
1738 sender
= content
.getSender();
1740 // Store uuid if we don't have it already
1741 resolveSignalServiceAddress(sender
);
1743 if (content
.getDataMessage().isPresent()) {
1744 SignalServiceDataMessage message
= content
.getDataMessage().get();
1746 if (content
.isNeedsReceipt()) {
1747 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1750 actions
.addAll(handleSignalServiceDataMessage(message
,
1753 account
.getSelfAddress(),
1754 ignoreAttachments
));
1756 if (content
.getSyncMessage().isPresent()) {
1757 account
.setMultiDevice(true);
1758 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1759 if (syncMessage
.getSent().isPresent()) {
1760 SentTranscriptMessage message
= syncMessage
.getSent().get();
1761 final SignalServiceAddress destination
= message
.getDestination().orNull();
1762 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1766 ignoreAttachments
));
1768 if (syncMessage
.getRequest().isPresent()) {
1769 RequestMessage rm
= syncMessage
.getRequest().get();
1770 if (rm
.isContactsRequest()) {
1771 actions
.add(SendSyncContactsAction
.create());
1773 if (rm
.isGroupsRequest()) {
1774 actions
.add(SendSyncGroupsAction
.create());
1776 if (rm
.isBlockedListRequest()) {
1777 actions
.add(SendSyncBlockedListAction
.create());
1779 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1781 if (syncMessage
.getGroups().isPresent()) {
1782 File tmpFile
= null;
1784 tmpFile
= IOUtils
.createTempFile();
1785 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1786 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1788 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1790 while ((g
= s
.read()) != null) {
1791 GroupInfoV1 syncGroup
= account
.getGroupStore()
1792 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1793 if (syncGroup
!= null) {
1794 if (g
.getName().isPresent()) {
1795 syncGroup
.name
= g
.getName().get();
1797 syncGroup
.addMembers(g
.getMembers()
1799 .map(this::resolveSignalServiceAddress
)
1800 .collect(Collectors
.toSet()));
1801 if (!g
.isActive()) {
1802 syncGroup
.removeMember(account
.getSelfAddress());
1804 // Add ourself to the member set as it's marked as active
1805 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1807 syncGroup
.blocked
= g
.isBlocked();
1808 if (g
.getColor().isPresent()) {
1809 syncGroup
.color
= g
.getColor().get();
1812 if (g
.getAvatar().isPresent()) {
1813 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1815 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1816 syncGroup
.archived
= g
.isArchived();
1817 account
.getGroupStore().updateGroup(syncGroup
);
1821 } catch (Exception e
) {
1822 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1826 if (tmpFile
!= null) {
1828 Files
.delete(tmpFile
.toPath());
1829 } catch (IOException e
) {
1830 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1837 if (syncMessage
.getBlockedList().isPresent()) {
1838 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1839 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1840 setContactBlocked(resolveSignalServiceAddress(address
), true);
1842 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1844 .map(GroupId
::unknownVersion
)
1845 .collect(Collectors
.toSet())) {
1847 setGroupBlocked(groupId
, true);
1848 } catch (GroupNotFoundException e
) {
1849 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1850 groupId
.toBase64());
1854 if (syncMessage
.getContacts().isPresent()) {
1855 File tmpFile
= null;
1857 tmpFile
= IOUtils
.createTempFile();
1858 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1859 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1860 .asPointer(), tmpFile
)) {
1861 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1862 if (contactsMessage
.isComplete()) {
1863 account
.getContactStore().clear();
1866 while ((c
= s
.read()) != null) {
1867 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1868 account
.setProfileKey(c
.getProfileKey().get());
1870 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1871 ContactInfo contact
= account
.getContactStore().getContact(address
);
1872 if (contact
== null) {
1873 contact
= new ContactInfo(address
);
1875 if (c
.getName().isPresent()) {
1876 contact
.name
= c
.getName().get();
1878 if (c
.getColor().isPresent()) {
1879 contact
.color
= c
.getColor().get();
1881 if (c
.getProfileKey().isPresent()) {
1882 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1884 if (c
.getVerified().isPresent()) {
1885 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1886 account
.getSignalProtocolStore()
1887 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1888 verifiedMessage
.getIdentityKey(),
1889 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1891 if (c
.getExpirationTimer().isPresent()) {
1892 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1894 contact
.blocked
= c
.isBlocked();
1895 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1896 contact
.archived
= c
.isArchived();
1897 account
.getContactStore().updateContact(contact
);
1899 if (c
.getAvatar().isPresent()) {
1900 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
1904 } catch (Exception e
) {
1905 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1909 if (tmpFile
!= null) {
1911 Files
.delete(tmpFile
.toPath());
1912 } catch (IOException e
) {
1913 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1920 if (syncMessage
.getVerified().isPresent()) {
1921 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1922 account
.getSignalProtocolStore()
1923 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
1924 verifiedMessage
.getIdentityKey(),
1925 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1927 if (syncMessage
.getStickerPackOperations().isPresent()) {
1928 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
1930 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
1931 if (!m
.getPackId().isPresent()) {
1934 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
1935 if (sticker
== null) {
1936 if (!m
.getPackKey().isPresent()) {
1939 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
1941 sticker
.setInstalled(!m
.getType().isPresent()
1942 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
1943 account
.getStickerStore().updateSticker(sticker
);
1946 if (syncMessage
.getConfiguration().isPresent()) {
1954 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
1956 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
1957 } catch (IOException e
) {
1958 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
1962 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
1964 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
1965 } catch (IOException e
) {
1966 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
1970 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
1972 avatarStore
.storeGroupAvatar(groupId
,
1973 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
1974 } catch (IOException e
) {
1975 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
1979 private void downloadProfileAvatar(
1980 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
1983 avatarStore
.storeProfileAvatar(address
,
1984 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
1985 } catch (Throwable e
) {
1986 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
1990 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
1991 return attachmentStore
.getAttachmentFile(attachmentId
);
1994 private void downloadAttachment(final SignalServiceAttachment attachment
) {
1995 if (!attachment
.isPointer()) {
1996 logger
.warn("Invalid state, can't store an attachment stream.");
1999 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2000 if (pointer
.getPreview().isPresent()) {
2001 final byte[] preview
= pointer
.getPreview().get();
2003 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2004 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2005 } catch (IOException e
) {
2006 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2011 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2012 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2013 } catch (IOException e
) {
2014 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2018 private void retrieveGroupV2Avatar(
2019 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2020 ) throws IOException
{
2021 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2023 File tmpFile
= IOUtils
.createTempFile();
2024 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2026 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2027 byte[] encryptedData
= IOUtils
.readFully(input
);
2029 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2030 outputStream
.write(decryptedData
);
2033 Files
.delete(tmpFile
.toPath());
2034 } catch (IOException e
) {
2035 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2042 private void retrieveProfileAvatar(
2043 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2044 ) throws IOException
{
2045 File tmpFile
= IOUtils
.createTempFile();
2046 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2049 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2050 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2051 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2054 Files
.delete(tmpFile
.toPath());
2055 } catch (IOException e
) {
2056 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2063 private void retrieveAttachment(
2064 final SignalServiceAttachment attachment
, final OutputStream outputStream
2065 ) throws IOException
{
2066 if (attachment
.isPointer()) {
2067 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2068 retrieveAttachmentPointer(pointer
, outputStream
);
2070 SignalServiceAttachmentStream stream
= attachment
.asStream();
2071 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2075 private void retrieveAttachmentPointer(
2076 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2077 ) throws IOException
{
2078 File tmpFile
= IOUtils
.createTempFile();
2079 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2080 IOUtils
.copyStream(input
, outputStream
);
2081 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2082 throw new IOException(e
);
2085 Files
.delete(tmpFile
.toPath());
2086 } catch (IOException e
) {
2087 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2094 private InputStream
retrieveAttachmentAsStream(
2095 SignalServiceAttachmentPointer pointer
, File tmpFile
2096 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2097 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2100 void sendGroups() throws IOException
, UntrustedIdentityException
{
2101 File groupsFile
= IOUtils
.createTempFile();
2104 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2105 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2106 for (GroupInfo
record : getGroups()) {
2107 if (record instanceof GroupInfoV1
) {
2108 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2109 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2110 Optional
.fromNullable(groupInfo
.name
),
2111 new ArrayList
<>(groupInfo
.getMembers()),
2112 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2113 groupInfo
.isMember(account
.getSelfAddress()),
2114 Optional
.of(groupInfo
.messageExpirationTime
),
2115 Optional
.fromNullable(groupInfo
.color
),
2117 Optional
.fromNullable(groupInfo
.inboxPosition
),
2118 groupInfo
.archived
));
2123 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2124 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2125 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2126 .withStream(groupsFileStream
)
2127 .withContentType("application/octet-stream")
2128 .withLength(groupsFile
.length())
2131 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2136 Files
.delete(groupsFile
.toPath());
2137 } catch (IOException e
) {
2138 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2143 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2144 File contactsFile
= IOUtils
.createTempFile();
2147 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2148 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2149 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2150 VerifiedMessage verifiedMessage
= null;
2151 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2152 if (currentIdentity
!= null) {
2153 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2154 currentIdentity
.getIdentityKey(),
2155 currentIdentity
.getTrustLevel().toVerifiedState(),
2156 currentIdentity
.getDateAdded().getTime());
2159 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2160 out
.write(new DeviceContact(record.getAddress(),
2161 Optional
.fromNullable(record.name
),
2162 createContactAvatarAttachment(record.getAddress()),
2163 Optional
.fromNullable(record.color
),
2164 Optional
.fromNullable(verifiedMessage
),
2165 Optional
.fromNullable(profileKey
),
2167 Optional
.of(record.messageExpirationTime
),
2168 Optional
.fromNullable(record.inboxPosition
),
2172 if (account
.getProfileKey() != null) {
2173 // Send our own profile key as well
2174 out
.write(new DeviceContact(account
.getSelfAddress(),
2179 Optional
.of(account
.getProfileKey()),
2187 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2188 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2189 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2190 .withStream(contactsFileStream
)
2191 .withContentType("application/octet-stream")
2192 .withLength(contactsFile
.length())
2195 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2200 Files
.delete(contactsFile
.toPath());
2201 } catch (IOException e
) {
2202 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2207 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2208 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2209 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2210 if (record.blocked
) {
2211 addresses
.add(record.getAddress());
2214 List
<byte[]> groupIds
= new ArrayList
<>();
2215 for (GroupInfo
record : getGroups()) {
2216 if (record.isBlocked()) {
2217 groupIds
.add(record.getGroupId().serialize());
2220 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2223 private void sendVerifiedMessage(
2224 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2225 ) throws IOException
, UntrustedIdentityException
{
2226 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2228 trustLevel
.toVerifiedState(),
2229 System
.currentTimeMillis());
2230 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2233 public List
<ContactInfo
> getContacts() {
2234 return account
.getContactStore().getContacts();
2237 public ContactInfo
getContact(String number
) {
2238 return account
.getContactStore().getContact(Utils
.getSignalServiceAddressFromIdentifier(number
));
2241 public GroupInfo
getGroup(GroupId groupId
) {
2242 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2243 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2244 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2245 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2246 account
.getGroupStore().updateGroup(group
);
2251 public List
<IdentityInfo
> getIdentities() {
2252 return account
.getSignalProtocolStore().getIdentities();
2255 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2256 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2260 * Trust this the identity with this fingerprint
2262 * @param name username of the identity
2263 * @param fingerprint Fingerprint
2265 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2266 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2267 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2271 for (IdentityInfo id
: ids
) {
2272 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2276 account
.getSignalProtocolStore()
2277 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2279 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2280 } catch (IOException
| UntrustedIdentityException e
) {
2281 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2290 * Trust this the identity with this safety number
2292 * @param name username of the identity
2293 * @param safetyNumber Safety number
2295 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2296 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2297 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2301 for (IdentityInfo id
: ids
) {
2302 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2306 account
.getSignalProtocolStore()
2307 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2309 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2310 } catch (IOException
| UntrustedIdentityException e
) {
2311 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2320 * Trust all keys of this identity without verification
2322 * @param name username of the identity
2324 public boolean trustIdentityAllKeys(String name
) {
2325 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2326 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2330 for (IdentityInfo id
: ids
) {
2331 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2332 account
.getSignalProtocolStore()
2333 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2335 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2336 } catch (IOException
| UntrustedIdentityException e
) {
2337 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2345 public String
computeSafetyNumber(
2346 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2348 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2349 account
.getSelfAddress(),
2350 getIdentityKeyPair().getPublicKey(),
2355 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2356 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2358 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2359 return resolveSignalServiceAddress(canonicalizedNumber
);
2362 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2363 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2365 return resolveSignalServiceAddress(address
);
2368 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2369 if (address
.matches(account
.getSelfAddress())) {
2370 return account
.getSelfAddress();
2373 return account
.getRecipientStore().resolveServiceAddress(address
);
2377 public void close() throws IOException
{
2381 void close(boolean closeAccount
) throws IOException
{
2382 if (messagePipe
!= null) {
2383 messagePipe
.shutdown();
2387 if (unidentifiedMessagePipe
!= null) {
2388 unidentifiedMessagePipe
.shutdown();
2389 unidentifiedMessagePipe
= null;
2392 if (closeAccount
&& account
!= null) {
2398 public interface ReceiveMessageHandler
{
2400 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);