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
, SendMessageResult
> sendSelfMessage(
957 String messageText
, List
<String
> attachments
958 ) throws IOException
, AttachmentInvalidException
{
959 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
960 .withBody(messageText
);
961 if (attachments
!= null) {
962 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
964 return sendSelfMessage(messageBuilder
);
967 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
968 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
969 ) throws IOException
, InvalidNumberException
{
970 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
972 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
973 targetSentTimestamp
);
974 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
975 .withReaction(reaction
);
976 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
979 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
980 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
982 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
984 return sendMessage(messageBuilder
, signalServiceAddresses
);
985 } catch (Exception e
) {
986 for (SignalServiceAddress address
: signalServiceAddresses
) {
987 handleEndSession(address
);
994 public String
getContactName(String number
) throws InvalidNumberException
{
995 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
996 if (contact
== null) {
1003 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1004 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1005 ContactInfo contact
= account
.getContactStore().getContact(address
);
1006 if (contact
== null) {
1007 contact
= new ContactInfo(address
);
1009 contact
.name
= name
;
1010 account
.getContactStore().updateContact(contact
);
1014 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1015 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1018 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1019 ContactInfo contact
= account
.getContactStore().getContact(address
);
1020 if (contact
== null) {
1021 contact
= new ContactInfo(address
);
1023 contact
.blocked
= blocked
;
1024 account
.getContactStore().updateContact(contact
);
1028 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1029 GroupInfo group
= getGroup(groupId
);
1030 if (group
== null) {
1031 throw new GroupNotFoundException(groupId
);
1034 group
.setBlocked(blocked
);
1035 account
.getGroupStore().updateGroup(group
);
1040 * Change the expiration timer for a contact
1042 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1043 ContactInfo contact
= account
.getContactStore().getContact(address
);
1044 contact
.messageExpirationTime
= messageExpirationTimer
;
1045 account
.getContactStore().updateContact(contact
);
1046 sendExpirationTimerUpdate(address
);
1050 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1051 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1052 .asExpirationUpdate();
1053 sendMessage(messageBuilder
, List
.of(address
));
1057 * Change the expiration timer for a contact
1059 public void setExpirationTimer(
1060 String number
, int messageExpirationTimer
1061 ) throws IOException
, InvalidNumberException
{
1062 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1063 setExpirationTimer(address
, messageExpirationTimer
);
1067 * Change the expiration timer for a group
1069 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1070 GroupInfo g
= getGroup(groupId
);
1071 if (g
instanceof GroupInfoV1
) {
1072 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1073 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1074 account
.getGroupStore().updateGroup(groupInfoV1
);
1076 throw new RuntimeException("TODO Not implemented!");
1081 * Upload the sticker pack from path.
1083 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1084 * @return if successful, returns the URL to install the sticker pack in the signal app
1086 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1087 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1089 SignalServiceMessageSender messageSender
= createMessageSender();
1091 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1092 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1094 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1095 account
.getStickerStore().updateSticker(sticker
);
1099 return new URI("https",
1102 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1103 Hex
.toStringCondensed(packKey
),
1104 StandardCharsets
.UTF_8
)).toString();
1105 } catch (URISyntaxException e
) {
1106 throw new AssertionError(e
);
1110 void requestSyncGroups() throws IOException
{
1111 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1112 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1114 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1116 sendSyncMessage(message
);
1117 } catch (UntrustedIdentityException e
) {
1118 throw new AssertionError(e
);
1122 void requestSyncContacts() throws IOException
{
1123 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1124 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1126 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1128 sendSyncMessage(message
);
1129 } catch (UntrustedIdentityException e
) {
1130 throw new AssertionError(e
);
1134 void requestSyncBlocked() throws IOException
{
1135 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1136 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1138 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1140 sendSyncMessage(message
);
1141 } catch (UntrustedIdentityException e
) {
1142 throw new AssertionError(e
);
1146 void requestSyncConfiguration() throws IOException
{
1147 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1148 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1150 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1152 sendSyncMessage(message
);
1153 } catch (UntrustedIdentityException e
) {
1154 throw new AssertionError(e
);
1158 private byte[] getSenderCertificate() {
1159 // TODO support UUID capable sender certificates
1160 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1163 certificate
= accountManager
.getSenderCertificate();
1164 } catch (IOException e
) {
1165 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1168 // TODO cache for a day
1172 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1173 SignalServiceMessageSender messageSender
= createMessageSender();
1175 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1176 } catch (UntrustedIdentityException e
) {
1177 account
.getSignalProtocolStore()
1178 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1180 TrustLevel
.UNTRUSTED
);
1185 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1186 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1187 final Set
<SignalServiceAddress
> missingUuids
= new HashSet
<>();
1189 for (String number
: numbers
) {
1190 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1191 if (resolvedAddress
.getUuid().isPresent()) {
1192 signalServiceAddresses
.add(resolvedAddress
);
1194 missingUuids
.add(resolvedAddress
);
1198 Map
<String
, UUID
> registeredUsers
;
1200 registeredUsers
= accountManager
.getRegisteredUsers(getIasKeyStore(),
1201 missingUuids
.stream().map(a
-> a
.getNumber().get()).collect(Collectors
.toSet()),
1203 } catch (IOException
| Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException e
) {
1204 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1205 registeredUsers
= new HashMap
<>();
1208 for (SignalServiceAddress address
: missingUuids
) {
1209 final String number
= address
.getNumber().get();
1210 if (registeredUsers
.containsKey(number
)) {
1211 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1212 registeredUsers
.get(number
),
1214 signalServiceAddresses
.add(newAddress
);
1216 signalServiceAddresses
.add(address
);
1220 return signalServiceAddresses
;
1223 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1224 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1225 ) throws IOException
{
1226 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1227 final long timestamp
= System
.currentTimeMillis();
1228 messageBuilder
.withTimestamp(timestamp
);
1229 getOrCreateMessagePipe();
1230 getOrCreateUnidentifiedMessagePipe();
1231 SignalServiceDataMessage message
= null;
1233 message
= messageBuilder
.build();
1234 if (message
.getGroupContext().isPresent()) {
1236 SignalServiceMessageSender messageSender
= createMessageSender();
1237 final boolean isRecipientUpdate
= false;
1238 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1239 unidentifiedAccessHelper
.getAccessFor(recipients
),
1242 for (SendMessageResult r
: result
) {
1243 if (r
.getIdentityFailure() != null) {
1244 account
.getSignalProtocolStore()
1245 .saveIdentity(r
.getAddress(),
1246 r
.getIdentityFailure().getIdentityKey(),
1247 TrustLevel
.UNTRUSTED
);
1250 return new Pair
<>(timestamp
, result
);
1251 } catch (UntrustedIdentityException e
) {
1252 account
.getSignalProtocolStore()
1253 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1255 TrustLevel
.UNTRUSTED
);
1256 return new Pair
<>(timestamp
, List
.of());
1259 // Send to all individually, so sync messages are sent correctly
1260 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1261 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1262 for (SignalServiceAddress address
: recipients
) {
1263 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1264 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1265 messageBuilder
.withExpiration(expirationTime
);
1266 message
= messageBuilder
.build();
1267 results
.add(sendMessage(address
, message
));
1269 return new Pair
<>(timestamp
, results
);
1272 if (message
!= null && message
.isEndSession()) {
1273 for (SignalServiceAddress recipient
: recipients
) {
1274 handleEndSession(recipient
);
1281 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1282 SignalServiceDataMessage
.Builder messageBuilder
1283 ) throws IOException
{
1284 final long timestamp
= System
.currentTimeMillis();
1285 messageBuilder
.withTimestamp(timestamp
);
1286 getOrCreateMessagePipe();
1287 getOrCreateUnidentifiedMessagePipe();
1289 final SignalServiceAddress address
= getSelfAddress();
1291 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1292 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1293 messageBuilder
.withExpiration(expirationTime
);
1295 SignalServiceDataMessage message
= messageBuilder
.build();
1296 final SendMessageResult result
= sendSelfMessage(message
);
1297 return new Pair
<>(timestamp
, result
);
1303 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1304 SignalServiceMessageSender messageSender
= createMessageSender();
1306 SignalServiceAddress recipient
= account
.getSelfAddress();
1308 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1309 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1310 message
.getTimestamp(),
1312 message
.getExpiresInSeconds(),
1313 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1315 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1318 long startTime
= System
.currentTimeMillis();
1319 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1320 return SendMessageResult
.success(recipient
,
1321 unidentifiedAccess
.isPresent(),
1323 System
.currentTimeMillis() - startTime
);
1324 } catch (UntrustedIdentityException e
) {
1325 account
.getSignalProtocolStore()
1326 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1328 TrustLevel
.UNTRUSTED
);
1329 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1333 private SendMessageResult
sendMessage(
1334 SignalServiceAddress address
, SignalServiceDataMessage message
1335 ) throws IOException
{
1336 SignalServiceMessageSender messageSender
= createMessageSender();
1339 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1340 } catch (UntrustedIdentityException e
) {
1341 account
.getSignalProtocolStore()
1342 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1344 TrustLevel
.UNTRUSTED
);
1345 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1349 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1350 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1351 account
.getSignalProtocolStore(),
1352 certificateValidator
);
1354 return cipher
.decrypt(envelope
);
1355 } catch (ProtocolUntrustedIdentityException e
) {
1356 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1357 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1359 account
.getSignalProtocolStore()
1360 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1361 identityException
.getUntrustedIdentity(),
1362 TrustLevel
.UNTRUSTED
);
1363 throw identityException
;
1365 throw new AssertionError(e
);
1369 private void handleEndSession(SignalServiceAddress source
) {
1370 account
.getSignalProtocolStore().deleteAllSessions(source
);
1373 private List
<HandleAction
> handleSignalServiceDataMessage(
1374 SignalServiceDataMessage message
,
1376 SignalServiceAddress source
,
1377 SignalServiceAddress destination
,
1378 boolean ignoreAttachments
1380 List
<HandleAction
> actions
= new ArrayList
<>();
1381 if (message
.getGroupContext().isPresent()) {
1382 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1383 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1384 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1385 GroupInfo group
= getGroup(groupId
);
1386 if (group
== null || group
instanceof GroupInfoV1
) {
1387 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1388 switch (groupInfo
.getType()) {
1390 if (groupV1
== null) {
1391 groupV1
= new GroupInfoV1(groupId
);
1394 if (groupInfo
.getAvatar().isPresent()) {
1395 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1396 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1399 if (groupInfo
.getName().isPresent()) {
1400 groupV1
.name
= groupInfo
.getName().get();
1403 if (groupInfo
.getMembers().isPresent()) {
1404 groupV1
.addMembers(groupInfo
.getMembers()
1407 .map(this::resolveSignalServiceAddress
)
1408 .collect(Collectors
.toSet()));
1411 account
.getGroupStore().updateGroup(groupV1
);
1415 if (groupV1
== null && !isSync
) {
1416 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1420 if (groupV1
!= null) {
1421 groupV1
.removeMember(source
);
1422 account
.getGroupStore().updateGroup(groupV1
);
1427 if (groupV1
!= null && !isSync
) {
1428 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1433 // Received a group v1 message for a v2 group
1436 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1437 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1438 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1440 getOrMigrateGroup(groupMasterKey
,
1441 groupContext
.getRevision(),
1442 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1446 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1447 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1448 handleEndSession(conversationPartnerAddress
);
1450 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1451 if (message
.getGroupContext().isPresent()) {
1452 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1453 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1454 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1455 if (group
!= null) {
1456 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1457 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1458 account
.getGroupStore().updateGroup(group
);
1461 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1462 // disappearing message timer already stored in the DecryptedGroup
1464 } else if (conversationPartnerAddress
!= null) {
1465 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1466 if (contact
== null) {
1467 contact
= new ContactInfo(conversationPartnerAddress
);
1469 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1470 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1471 account
.getContactStore().updateContact(contact
);
1475 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1476 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1477 downloadAttachment(attachment
);
1480 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1481 final ProfileKey profileKey
;
1483 profileKey
= new ProfileKey(message
.getProfileKey().get());
1484 } catch (InvalidInputException e
) {
1485 throw new AssertionError(e
);
1487 if (source
.matches(account
.getSelfAddress())) {
1488 this.account
.setProfileKey(profileKey
);
1490 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1492 if (message
.getPreviews().isPresent()) {
1493 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1494 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1495 if (preview
.getImage().isPresent()) {
1496 downloadAttachment(preview
.getImage().get());
1500 if (message
.getQuote().isPresent()) {
1501 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1503 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1504 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1505 if (thumbnail
!= null) {
1506 downloadAttachment(thumbnail
);
1510 if (message
.getSticker().isPresent()) {
1511 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1512 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1513 if (sticker
== null) {
1514 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1515 account
.getStickerStore().updateSticker(sticker
);
1521 private GroupInfoV2
getOrMigrateGroup(
1522 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1524 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1526 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1527 GroupInfo groupInfo
= getGroup(groupId
);
1528 final GroupInfoV2 groupInfoV2
;
1529 if (groupInfo
instanceof GroupInfoV1
) {
1530 // Received a v2 group message for a v1 group, we need to locally migrate the group
1531 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1532 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1533 logger
.info("Locally migrated group {} to group v2, id: {}",
1534 groupInfo
.getGroupId().toBase64(),
1535 groupInfoV2
.getGroupId().toBase64());
1536 } else if (groupInfo
instanceof GroupInfoV2
) {
1537 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1539 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1542 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1543 DecryptedGroup group
= null;
1544 if (signedGroupChange
!= null
1545 && groupInfoV2
.getGroup() != null
1546 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1547 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1549 if (group
== null) {
1550 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1552 if (group
!= null) {
1553 storeProfileKeysFromMembers(group
);
1554 final String avatar
= group
.getAvatar();
1555 if (avatar
!= null && !avatar
.isEmpty()) {
1556 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1559 groupInfoV2
.setGroup(group
);
1560 account
.getGroupStore().updateGroup(groupInfoV2
);
1566 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1567 for (DecryptedMember member
: group
.getMembersList()) {
1568 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1569 member
.getUuid().toByteArray()), null));
1571 account
.getProfileStore()
1572 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1573 } catch (InvalidInputException ignored
) {
1578 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1579 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1580 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1584 private void retryFailedReceivedMessage(
1585 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1587 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1588 if (envelope
== null) {
1591 SignalServiceContent content
= null;
1592 if (!envelope
.isReceipt()) {
1594 content
= decryptMessage(envelope
);
1595 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1597 } catch (Exception er
) {
1598 // All other errors are not recoverable, so delete the cached message
1599 cachedMessage
.delete();
1602 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1603 for (HandleAction action
: actions
) {
1605 action
.execute(this);
1606 } catch (Throwable e
) {
1607 logger
.warn("Message action failed.", e
);
1612 handler
.handleMessage(envelope
, content
, null);
1613 cachedMessage
.delete();
1616 public void receiveMessages(
1619 boolean returnOnTimeout
,
1620 boolean ignoreAttachments
,
1621 ReceiveMessageHandler handler
1622 ) throws IOException
{
1623 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1625 Set
<HandleAction
> queuedActions
= null;
1627 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1629 boolean hasCaughtUpWithOldMessages
= false;
1632 SignalServiceEnvelope envelope
;
1633 SignalServiceContent content
= null;
1634 Exception exception
= null;
1635 final CachedMessage
[] cachedMessage
= {null};
1637 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1638 // store message on disk, before acknowledging receipt to the server
1639 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1641 if (result
.isPresent()) {
1642 envelope
= result
.get();
1644 // Received indicator that server queue is empty
1645 hasCaughtUpWithOldMessages
= true;
1647 if (queuedActions
!= null) {
1648 for (HandleAction action
: queuedActions
) {
1650 action
.execute(this);
1651 } catch (Throwable e
) {
1652 logger
.warn("Message action failed.", e
);
1656 queuedActions
.clear();
1657 queuedActions
= null;
1660 // Continue to wait another timeout for new messages
1663 } catch (TimeoutException e
) {
1664 if (returnOnTimeout
) return;
1666 } catch (InvalidVersionException e
) {
1667 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1671 if (envelope
.hasSource()) {
1672 // Store uuid if we don't have it already
1673 SignalServiceAddress source
= envelope
.getSourceAddress();
1674 resolveSignalServiceAddress(source
);
1676 if (!envelope
.isReceipt()) {
1678 content
= decryptMessage(envelope
);
1679 } catch (Exception e
) {
1682 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1683 if (hasCaughtUpWithOldMessages
) {
1684 for (HandleAction action
: actions
) {
1686 action
.execute(this);
1687 } catch (Throwable e
) {
1688 logger
.warn("Message action failed.", e
);
1692 if (queuedActions
== null) {
1693 queuedActions
= new HashSet
<>();
1695 queuedActions
.addAll(actions
);
1699 if (isMessageBlocked(envelope
, content
)) {
1700 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1701 } else if (isNotAGroupMember(envelope
, content
)) {
1702 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1704 handler
.handleMessage(envelope
, content
, exception
);
1706 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1707 if (cachedMessage
[0] != null) {
1708 cachedMessage
[0].delete();
1714 private boolean isMessageBlocked(
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();
1725 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1726 if (sourceContact
!= null && sourceContact
.blocked
) {
1730 if (content
!= null && content
.getDataMessage().isPresent()) {
1731 SignalServiceDataMessage message
= content
.getDataMessage().get();
1732 if (message
.getGroupContext().isPresent()) {
1733 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1734 GroupInfo group
= getGroup(groupId
);
1735 if (group
!= null && group
.isBlocked()) {
1743 private boolean isNotAGroupMember(
1744 SignalServiceEnvelope envelope
, SignalServiceContent content
1746 SignalServiceAddress source
;
1747 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1748 source
= envelope
.getSourceAddress();
1749 } else if (content
!= null) {
1750 source
= content
.getSender();
1755 if (content
!= null && content
.getDataMessage().isPresent()) {
1756 SignalServiceDataMessage message
= content
.getDataMessage().get();
1757 if (message
.getGroupContext().isPresent()) {
1758 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1759 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1760 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1764 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1765 GroupInfo group
= getGroup(groupId
);
1766 if (group
!= null && !group
.isMember(source
)) {
1774 private List
<HandleAction
> handleMessage(
1775 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1777 List
<HandleAction
> actions
= new ArrayList
<>();
1778 if (content
!= null) {
1779 final SignalServiceAddress sender
;
1780 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1781 sender
= envelope
.getSourceAddress();
1783 sender
= content
.getSender();
1785 // Store uuid if we don't have it already
1786 resolveSignalServiceAddress(sender
);
1788 if (content
.getDataMessage().isPresent()) {
1789 SignalServiceDataMessage message
= content
.getDataMessage().get();
1791 if (content
.isNeedsReceipt()) {
1792 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1795 actions
.addAll(handleSignalServiceDataMessage(message
,
1798 account
.getSelfAddress(),
1799 ignoreAttachments
));
1801 if (content
.getSyncMessage().isPresent()) {
1802 account
.setMultiDevice(true);
1803 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1804 if (syncMessage
.getSent().isPresent()) {
1805 SentTranscriptMessage message
= syncMessage
.getSent().get();
1806 final SignalServiceAddress destination
= message
.getDestination().orNull();
1807 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1811 ignoreAttachments
));
1813 if (syncMessage
.getRequest().isPresent()) {
1814 RequestMessage rm
= syncMessage
.getRequest().get();
1815 if (rm
.isContactsRequest()) {
1816 actions
.add(SendSyncContactsAction
.create());
1818 if (rm
.isGroupsRequest()) {
1819 actions
.add(SendSyncGroupsAction
.create());
1821 if (rm
.isBlockedListRequest()) {
1822 actions
.add(SendSyncBlockedListAction
.create());
1824 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1826 if (syncMessage
.getGroups().isPresent()) {
1827 File tmpFile
= null;
1829 tmpFile
= IOUtils
.createTempFile();
1830 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1831 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1833 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1835 while ((g
= s
.read()) != null) {
1836 GroupInfoV1 syncGroup
= account
.getGroupStore()
1837 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1838 if (syncGroup
!= null) {
1839 if (g
.getName().isPresent()) {
1840 syncGroup
.name
= g
.getName().get();
1842 syncGroup
.addMembers(g
.getMembers()
1844 .map(this::resolveSignalServiceAddress
)
1845 .collect(Collectors
.toSet()));
1846 if (!g
.isActive()) {
1847 syncGroup
.removeMember(account
.getSelfAddress());
1849 // Add ourself to the member set as it's marked as active
1850 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1852 syncGroup
.blocked
= g
.isBlocked();
1853 if (g
.getColor().isPresent()) {
1854 syncGroup
.color
= g
.getColor().get();
1857 if (g
.getAvatar().isPresent()) {
1858 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1860 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1861 syncGroup
.archived
= g
.isArchived();
1862 account
.getGroupStore().updateGroup(syncGroup
);
1866 } catch (Exception e
) {
1867 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1871 if (tmpFile
!= null) {
1873 Files
.delete(tmpFile
.toPath());
1874 } catch (IOException e
) {
1875 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1882 if (syncMessage
.getBlockedList().isPresent()) {
1883 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1884 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1885 setContactBlocked(resolveSignalServiceAddress(address
), true);
1887 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1889 .map(GroupId
::unknownVersion
)
1890 .collect(Collectors
.toSet())) {
1892 setGroupBlocked(groupId
, true);
1893 } catch (GroupNotFoundException e
) {
1894 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1895 groupId
.toBase64());
1899 if (syncMessage
.getContacts().isPresent()) {
1900 File tmpFile
= null;
1902 tmpFile
= IOUtils
.createTempFile();
1903 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1904 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1905 .asPointer(), tmpFile
)) {
1906 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1907 if (contactsMessage
.isComplete()) {
1908 account
.getContactStore().clear();
1911 while ((c
= s
.read()) != null) {
1912 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1913 account
.setProfileKey(c
.getProfileKey().get());
1915 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1916 ContactInfo contact
= account
.getContactStore().getContact(address
);
1917 if (contact
== null) {
1918 contact
= new ContactInfo(address
);
1920 if (c
.getName().isPresent()) {
1921 contact
.name
= c
.getName().get();
1923 if (c
.getColor().isPresent()) {
1924 contact
.color
= c
.getColor().get();
1926 if (c
.getProfileKey().isPresent()) {
1927 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1929 if (c
.getVerified().isPresent()) {
1930 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1931 account
.getSignalProtocolStore()
1932 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1933 verifiedMessage
.getIdentityKey(),
1934 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1936 if (c
.getExpirationTimer().isPresent()) {
1937 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1939 contact
.blocked
= c
.isBlocked();
1940 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1941 contact
.archived
= c
.isArchived();
1942 account
.getContactStore().updateContact(contact
);
1944 if (c
.getAvatar().isPresent()) {
1945 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
1949 } catch (Exception e
) {
1950 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1954 if (tmpFile
!= null) {
1956 Files
.delete(tmpFile
.toPath());
1957 } catch (IOException e
) {
1958 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1965 if (syncMessage
.getVerified().isPresent()) {
1966 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1967 account
.getSignalProtocolStore()
1968 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
1969 verifiedMessage
.getIdentityKey(),
1970 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1972 if (syncMessage
.getStickerPackOperations().isPresent()) {
1973 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
1975 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
1976 if (!m
.getPackId().isPresent()) {
1979 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
1980 if (sticker
== null) {
1981 if (!m
.getPackKey().isPresent()) {
1984 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
1986 sticker
.setInstalled(!m
.getType().isPresent()
1987 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
1988 account
.getStickerStore().updateSticker(sticker
);
1991 if (syncMessage
.getConfiguration().isPresent()) {
1999 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2001 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2002 } catch (IOException e
) {
2003 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2007 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2009 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2010 } catch (IOException e
) {
2011 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2015 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2017 avatarStore
.storeGroupAvatar(groupId
,
2018 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2019 } catch (IOException e
) {
2020 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2024 private void downloadProfileAvatar(
2025 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2028 avatarStore
.storeProfileAvatar(address
,
2029 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2030 } catch (Throwable e
) {
2031 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2035 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2036 return attachmentStore
.getAttachmentFile(attachmentId
);
2039 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2040 if (!attachment
.isPointer()) {
2041 logger
.warn("Invalid state, can't store an attachment stream.");
2044 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2045 if (pointer
.getPreview().isPresent()) {
2046 final byte[] preview
= pointer
.getPreview().get();
2048 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2049 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2050 } catch (IOException e
) {
2051 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2056 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2057 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2058 } catch (IOException e
) {
2059 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2063 private void retrieveGroupV2Avatar(
2064 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2065 ) throws IOException
{
2066 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2068 File tmpFile
= IOUtils
.createTempFile();
2069 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2071 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2072 byte[] encryptedData
= IOUtils
.readFully(input
);
2074 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2075 outputStream
.write(decryptedData
);
2078 Files
.delete(tmpFile
.toPath());
2079 } catch (IOException e
) {
2080 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2087 private void retrieveProfileAvatar(
2088 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2089 ) throws IOException
{
2090 File tmpFile
= IOUtils
.createTempFile();
2091 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2094 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2095 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2096 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2099 Files
.delete(tmpFile
.toPath());
2100 } catch (IOException e
) {
2101 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2108 private void retrieveAttachment(
2109 final SignalServiceAttachment attachment
, final OutputStream outputStream
2110 ) throws IOException
{
2111 if (attachment
.isPointer()) {
2112 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2113 retrieveAttachmentPointer(pointer
, outputStream
);
2115 SignalServiceAttachmentStream stream
= attachment
.asStream();
2116 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2120 private void retrieveAttachmentPointer(
2121 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2122 ) throws IOException
{
2123 File tmpFile
= IOUtils
.createTempFile();
2124 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2125 IOUtils
.copyStream(input
, outputStream
);
2126 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2127 throw new IOException(e
);
2130 Files
.delete(tmpFile
.toPath());
2131 } catch (IOException e
) {
2132 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2139 private InputStream
retrieveAttachmentAsStream(
2140 SignalServiceAttachmentPointer pointer
, File tmpFile
2141 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2142 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2145 void sendGroups() throws IOException
, UntrustedIdentityException
{
2146 File groupsFile
= IOUtils
.createTempFile();
2149 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2150 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2151 for (GroupInfo
record : getGroups()) {
2152 if (record instanceof GroupInfoV1
) {
2153 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2154 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2155 Optional
.fromNullable(groupInfo
.name
),
2156 new ArrayList
<>(groupInfo
.getMembers()),
2157 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2158 groupInfo
.isMember(account
.getSelfAddress()),
2159 Optional
.of(groupInfo
.messageExpirationTime
),
2160 Optional
.fromNullable(groupInfo
.color
),
2162 Optional
.fromNullable(groupInfo
.inboxPosition
),
2163 groupInfo
.archived
));
2168 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2169 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2170 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2171 .withStream(groupsFileStream
)
2172 .withContentType("application/octet-stream")
2173 .withLength(groupsFile
.length())
2176 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2181 Files
.delete(groupsFile
.toPath());
2182 } catch (IOException e
) {
2183 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2188 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2189 File contactsFile
= IOUtils
.createTempFile();
2192 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2193 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2194 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2195 VerifiedMessage verifiedMessage
= null;
2196 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2197 if (currentIdentity
!= null) {
2198 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2199 currentIdentity
.getIdentityKey(),
2200 currentIdentity
.getTrustLevel().toVerifiedState(),
2201 currentIdentity
.getDateAdded().getTime());
2204 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2205 out
.write(new DeviceContact(record.getAddress(),
2206 Optional
.fromNullable(record.name
),
2207 createContactAvatarAttachment(record.getAddress()),
2208 Optional
.fromNullable(record.color
),
2209 Optional
.fromNullable(verifiedMessage
),
2210 Optional
.fromNullable(profileKey
),
2212 Optional
.of(record.messageExpirationTime
),
2213 Optional
.fromNullable(record.inboxPosition
),
2217 if (account
.getProfileKey() != null) {
2218 // Send our own profile key as well
2219 out
.write(new DeviceContact(account
.getSelfAddress(),
2224 Optional
.of(account
.getProfileKey()),
2232 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2233 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2234 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2235 .withStream(contactsFileStream
)
2236 .withContentType("application/octet-stream")
2237 .withLength(contactsFile
.length())
2240 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2245 Files
.delete(contactsFile
.toPath());
2246 } catch (IOException e
) {
2247 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2252 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2253 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2254 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2255 if (record.blocked
) {
2256 addresses
.add(record.getAddress());
2259 List
<byte[]> groupIds
= new ArrayList
<>();
2260 for (GroupInfo
record : getGroups()) {
2261 if (record.isBlocked()) {
2262 groupIds
.add(record.getGroupId().serialize());
2265 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2268 private void sendVerifiedMessage(
2269 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2270 ) throws IOException
, UntrustedIdentityException
{
2271 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2273 trustLevel
.toVerifiedState(),
2274 System
.currentTimeMillis());
2275 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2278 public List
<ContactInfo
> getContacts() {
2279 return account
.getContactStore().getContacts();
2282 public ContactInfo
getContact(String number
) {
2283 return account
.getContactStore().getContact(Utils
.getSignalServiceAddressFromIdentifier(number
));
2286 public GroupInfo
getGroup(GroupId groupId
) {
2287 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2288 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2289 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2290 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2291 account
.getGroupStore().updateGroup(group
);
2296 public List
<IdentityInfo
> getIdentities() {
2297 return account
.getSignalProtocolStore().getIdentities();
2300 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2301 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2305 * Trust this the identity with this fingerprint
2307 * @param name username of the identity
2308 * @param fingerprint Fingerprint
2310 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2311 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2312 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2316 for (IdentityInfo id
: ids
) {
2317 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2321 account
.getSignalProtocolStore()
2322 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2324 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2325 } catch (IOException
| UntrustedIdentityException e
) {
2326 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2335 * Trust this the identity with this safety number
2337 * @param name username of the identity
2338 * @param safetyNumber Safety number
2340 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2341 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2342 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2346 for (IdentityInfo id
: ids
) {
2347 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2351 account
.getSignalProtocolStore()
2352 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2354 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2355 } catch (IOException
| UntrustedIdentityException e
) {
2356 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2365 * Trust all keys of this identity without verification
2367 * @param name username of the identity
2369 public boolean trustIdentityAllKeys(String name
) {
2370 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2371 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2375 for (IdentityInfo id
: ids
) {
2376 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2377 account
.getSignalProtocolStore()
2378 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2380 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2381 } catch (IOException
| UntrustedIdentityException e
) {
2382 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2390 public String
computeSafetyNumber(
2391 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2393 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2394 account
.getSelfAddress(),
2395 getIdentityKeyPair().getPublicKey(),
2400 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2401 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2403 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2404 return resolveSignalServiceAddress(canonicalizedNumber
);
2407 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2408 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2410 return resolveSignalServiceAddress(address
);
2413 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2414 if (address
.matches(account
.getSelfAddress())) {
2415 return account
.getSelfAddress();
2418 return account
.getRecipientStore().resolveServiceAddress(address
);
2422 public void close() throws IOException
{
2426 void close(boolean closeAccount
) throws IOException
{
2427 if (messagePipe
!= null) {
2428 messagePipe
.shutdown();
2432 if (unidentifiedMessagePipe
!= null) {
2433 unidentifiedMessagePipe
.shutdown();
2434 unidentifiedMessagePipe
= null;
2437 if (closeAccount
&& account
!= null) {
2443 public interface ReceiveMessageHandler
{
2445 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);