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 Map
<String
, UUID
> contactDetails
= getRegisteredUsers(numbers
);
330 Set
<String
> registeredUsers
= contactDetails
.keySet();
332 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
335 public void updateAccountAttributes() throws IOException
{
336 accountManager
.setAccountAttributes(account
.getSignalingKey(),
337 account
.getSignalProtocolStore().getLocalRegistrationId(),
339 // set legacy pin only if no KBS master key is set
340 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
341 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
342 account
.getSelfUnidentifiedAccessKey(),
343 account
.isUnrestrictedUnidentifiedAccess(),
345 account
.isDiscoverableByPhoneNumber());
349 * @param avatar if avatar is null the image from the local avatar store is used (if present),
350 * if it's Optional.absent(), the avatar will be removed
352 public void setProfile(String name
, Optional
<File
> avatar
) throws IOException
{
353 try (final StreamDetails streamDetails
= avatar
== null
354 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
355 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
356 accountManager
.setVersionedProfile(account
.getUuid(), account
.getProfileKey(), name
, streamDetails
);
359 if (avatar
!= null) {
360 if (avatar
.isPresent()) {
361 avatarStore
.storeProfileAvatar(getSelfAddress(),
362 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
364 avatarStore
.deleteProfileAvatar(getSelfAddress());
369 public void unregister() throws IOException
{
370 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
371 // If this is the master device, other users can't send messages to this number anymore.
372 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
373 accountManager
.setGcmId(Optional
.absent());
375 account
.setRegistered(false);
379 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
380 List
<DeviceInfo
> devices
= accountManager
.getDevices();
381 account
.setMultiDevice(devices
.size() > 1);
386 public void removeLinkedDevices(int deviceId
) throws IOException
{
387 accountManager
.removeDevice(deviceId
);
388 List
<DeviceInfo
> devices
= accountManager
.getDevices();
389 account
.setMultiDevice(devices
.size() > 1);
393 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
394 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
396 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
399 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
400 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
401 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
403 accountManager
.addDevice(deviceIdentifier
,
406 Optional
.of(account
.getProfileKey().serialize()),
408 account
.setMultiDevice(true);
412 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
413 if (pin
.isPresent()) {
414 final MasterKey masterKey
= account
.getPinMasterKey() != null
415 ? account
.getPinMasterKey()
416 : KeyUtils
.createMasterKey();
418 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
420 account
.setRegistrationLockPin(pin
.get());
421 account
.setPinMasterKey(masterKey
);
423 // Remove legacy registration lock
424 accountManager
.removeRegistrationLockV1();
427 pinHelper
.removeRegistrationLockPin();
429 account
.setRegistrationLockPin(null);
430 account
.setPinMasterKey(null);
435 void refreshPreKeys() throws IOException
{
436 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
437 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
438 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
440 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
443 private List
<PreKeyRecord
> generatePreKeys() {
444 final int offset
= account
.getPreKeyIdOffset();
446 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
447 account
.addPreKeys(records
);
453 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
454 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
456 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
457 account
.addSignedPreKey(record);
463 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
464 if (messagePipe
== null) {
465 messagePipe
= messageReceiver
.createMessagePipe();
470 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
471 if (unidentifiedMessagePipe
== null) {
472 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
474 return unidentifiedMessagePipe
;
477 private SignalServiceMessageSender
createMessageSender() {
478 final ExecutorService executor
= null;
479 return new SignalServiceMessageSender(serviceConfiguration
,
481 account
.getUsername(),
482 account
.getPassword(),
483 account
.getDeviceId(),
484 account
.getSignalProtocolStore(),
486 account
.isMultiDevice(),
487 Optional
.fromNullable(messagePipe
),
488 Optional
.fromNullable(unidentifiedMessagePipe
),
490 clientZkProfileOperations
,
492 ServiceConfig
.MAX_ENVELOPE_SIZE
);
495 private SignalProfile
getRecipientProfile(
496 SignalServiceAddress address
498 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
499 if (profileEntry
== null) {
502 long now
= new Date().getTime();
503 // Profiles are cached for 24h before retrieving them again
504 if (!profileEntry
.isRequestPending() && (
505 profileEntry
.getProfile() == null || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
507 profileEntry
.setRequestPending(true);
508 final SignalServiceProfile encryptedProfile
;
510 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
512 } catch (IOException e
) {
513 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
516 profileEntry
.setRequestPending(false);
519 final ProfileKey profileKey
= profileEntry
.getProfileKey();
520 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
521 account
.getProfileStore()
522 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
525 return profileEntry
.getProfile();
528 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
529 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
530 if (profileEntry
== null) {
533 if (profileEntry
.getProfileKeyCredential() == null) {
534 ProfileAndCredential profileAndCredential
;
536 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
537 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
538 } catch (IOException e
) {
539 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
543 long now
= new Date().getTime();
544 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
545 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
546 profileEntry
.getProfileKey(),
547 profileAndCredential
.getProfile());
548 account
.getProfileStore()
549 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
550 return profileKeyCredential
;
552 return profileEntry
.getProfileKeyCredential();
555 private SignalProfile
decryptProfileAndDownloadAvatar(
556 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
558 if (encryptedProfile
.getAvatar() != null) {
559 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
562 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
565 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
566 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
567 if (streamDetails
== null) {
568 return Optional
.absent();
571 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
574 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
575 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
576 if (streamDetails
== null) {
577 return Optional
.absent();
580 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
583 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
584 GroupInfo g
= getGroup(groupId
);
586 throw new GroupNotFoundException(groupId
);
588 if (!g
.isMember(account
.getSelfAddress())) {
589 throw new NotAGroupMemberException(groupId
, g
.getTitle());
594 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
595 GroupInfo g
= getGroup(groupId
);
597 throw new GroupNotFoundException(groupId
);
599 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
600 throw new NotAGroupMemberException(groupId
, g
.getTitle());
605 public List
<GroupInfo
> getGroups() {
606 return account
.getGroupStore().getGroups();
609 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
610 String messageText
, List
<String
> attachments
, GroupId groupId
611 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
612 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
613 .withBody(messageText
);
614 if (attachments
!= null) {
615 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
618 return sendGroupMessage(messageBuilder
, groupId
);
621 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
622 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
623 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
624 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
626 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
627 targetSentTimestamp
);
628 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
629 .withReaction(reaction
);
631 return sendGroupMessage(messageBuilder
, groupId
);
634 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
635 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
636 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
637 final GroupInfo g
= getGroupForSending(groupId
);
639 GroupUtils
.setGroupContext(messageBuilder
, g
);
640 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
642 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
645 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
646 SignalServiceDataMessage
.Builder messageBuilder
;
648 final GroupInfo g
= getGroupForUpdating(groupId
);
649 if (g
instanceof GroupInfoV1
) {
650 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
651 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
652 .withId(groupId
.serialize())
654 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
655 groupInfoV1
.removeMember(account
.getSelfAddress());
656 account
.getGroupStore().updateGroup(groupInfoV1
);
658 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
659 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
660 groupInfoV2
.setGroup(groupGroupChangePair
.first());
661 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
662 account
.getGroupStore().updateGroup(groupInfoV2
);
665 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
668 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
669 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
670 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
671 return sendUpdateGroupMessage(groupId
,
673 members
== null ?
null : getSignalServiceAddresses(members
),
677 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
678 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
679 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
681 SignalServiceDataMessage
.Builder messageBuilder
;
682 if (groupId
== null) {
684 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
685 members
== null ? List
.of() : members
,
688 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
689 gv1
.addMembers(List
.of(account
.getSelfAddress()));
690 updateGroupV1(gv1
, name
, members
, avatarFile
);
691 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
694 if (avatarFile
!= null) {
695 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
696 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
698 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
702 GroupInfo group
= getGroupForUpdating(groupId
);
703 if (group
instanceof GroupInfoV2
) {
704 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
706 Pair
<Long
, List
<SendMessageResult
>> result
= null;
707 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
708 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
709 result
= sendUpdateGroupMessage(groupInfoV2
,
710 groupGroupChangePair
.first(),
711 groupGroupChangePair
.second());
714 if (members
!= null) {
715 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
716 newMembers
.removeAll(group
.getMembers()
718 .map(this::resolveSignalServiceAddress
)
719 .collect(Collectors
.toSet()));
720 if (newMembers
.size() > 0) {
721 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
723 result
= sendUpdateGroupMessage(groupInfoV2
,
724 groupGroupChangePair
.first(),
725 groupGroupChangePair
.second());
728 if (result
== null || name
!= null || avatarFile
!= null) {
729 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
732 if (avatarFile
!= null) {
733 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
734 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
736 result
= sendUpdateGroupMessage(groupInfoV2
,
737 groupGroupChangePair
.first(),
738 groupGroupChangePair
.second());
741 return new Pair
<>(group
.getGroupId(), result
.second());
743 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
744 updateGroupV1(gv1
, name
, members
, avatarFile
);
745 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
750 account
.getGroupStore().updateGroup(g
);
752 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
753 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
754 return new Pair
<>(g
.getGroupId(), result
.second());
757 private void updateGroupV1(
760 final Collection
<SignalServiceAddress
> members
,
761 final File avatarFile
762 ) throws IOException
{
767 if (members
!= null) {
768 final Set
<String
> newE164Members
= new HashSet
<>();
769 for (SignalServiceAddress member
: members
) {
770 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
773 newE164Members
.add(member
.getNumber().get());
776 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newE164Members
);
777 if (contacts
.size() != newE164Members
.size()) {
778 // Some of the new members are not registered on Signal
779 for (ContactTokenDetails contact
: contacts
) {
780 newE164Members
.remove(contact
.getNumber());
782 throw new IOException("Failed to add members "
783 + String
.join(", ", newE164Members
)
784 + " to group: Not registered on Signal");
787 g
.addMembers(members
);
790 if (avatarFile
!= null) {
791 avatarStore
.storeGroupAvatar(g
.getGroupId(),
792 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
796 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
797 GroupInviteLinkUrl inviteLinkUrl
798 ) throws IOException
, GroupLinkNotActiveException
{
799 return sendJoinGroupMessage(inviteLinkUrl
);
802 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
803 GroupInviteLinkUrl inviteLinkUrl
804 ) throws IOException
, GroupLinkNotActiveException
{
805 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
806 inviteLinkUrl
.getPassword());
807 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
808 inviteLinkUrl
.getPassword(),
810 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
811 groupJoinInfo
.getRevision() + 1,
812 groupChange
.toByteArray());
814 if (group
.getGroup() == null) {
815 // Only requested member, can't send update to group members
816 return new Pair
<>(group
.getGroupId(), List
.of());
819 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
821 return new Pair
<>(group
.getGroupId(), result
.second());
824 private static int currentTimeDays() {
825 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
828 private GroupsV2AuthorizationString
getGroupAuthForToday(
829 final GroupSecretParams groupSecretParams
830 ) throws IOException
{
831 final int today
= currentTimeDays();
832 // Returns credentials for the next 7 days
833 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
834 // TODO cache credentials until they expire
835 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
837 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
840 authCredentialResponse
);
841 } catch (VerificationFailedException e
) {
842 throw new IOException(e
);
846 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
847 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
848 ) throws IOException
{
849 group
.setGroup(newDecryptedGroup
);
850 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
851 groupChange
.toByteArray());
852 account
.getGroupStore().updateGroup(group
);
853 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
856 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
857 GroupIdV1 groupId
, SignalServiceAddress recipient
858 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
860 GroupInfo group
= getGroupForSending(groupId
);
861 if (!(group
instanceof GroupInfoV1
)) {
862 throw new RuntimeException("Received an invalid group request for a v2 group!");
864 g
= (GroupInfoV1
) group
;
866 if (!g
.isMember(recipient
)) {
867 throw new NotAGroupMemberException(groupId
, g
.name
);
870 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
872 // Send group message only to the recipient who requested it
873 return sendMessage(messageBuilder
, List
.of(recipient
));
876 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
877 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
878 .withId(g
.getGroupId().serialize())
880 .withMembers(new ArrayList
<>(g
.getMembers()));
883 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
884 if (attachment
.isPresent()) {
885 group
.withAvatar(attachment
.get());
887 } catch (IOException e
) {
888 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
891 return SignalServiceDataMessage
.newBuilder()
892 .asGroupMessage(group
.build())
893 .withExpiration(g
.getMessageExpirationTime());
896 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
897 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
898 .withRevision(g
.getGroup().getRevision())
899 .withSignedGroupChange(signedGroupChange
);
900 return SignalServiceDataMessage
.newBuilder()
901 .asGroupMessage(group
.build())
902 .withExpiration(g
.getMessageExpirationTime());
905 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
906 GroupIdV1 groupId
, SignalServiceAddress recipient
907 ) throws IOException
{
908 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
909 .withId(groupId
.serialize());
911 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
912 .asGroupMessage(group
.build());
914 // Send group info request message to the recipient who sent us a message with this groupId
915 return sendMessage(messageBuilder
, List
.of(recipient
));
919 SignalServiceAddress remoteAddress
, long messageId
920 ) throws IOException
, UntrustedIdentityException
{
921 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
923 System
.currentTimeMillis());
925 createMessageSender().sendReceipt(remoteAddress
,
926 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
930 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
931 String messageText
, List
<String
> attachments
, List
<String
> recipients
932 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
933 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
934 .withBody(messageText
);
935 if (attachments
!= null) {
936 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
938 // Upload attachments here, so we only upload once even for multiple recipients
939 SignalServiceMessageSender messageSender
= createMessageSender();
940 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
941 for (SignalServiceAttachment attachment
: attachmentStreams
) {
942 if (attachment
.isStream()) {
943 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
944 } else if (attachment
.isPointer()) {
945 attachmentPointers
.add(attachment
.asPointer());
949 messageBuilder
.withAttachments(attachmentPointers
);
951 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
954 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
955 String messageText
, List
<String
> attachments
956 ) throws IOException
, AttachmentInvalidException
{
957 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
958 .withBody(messageText
);
959 if (attachments
!= null) {
960 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
962 return sendSelfMessage(messageBuilder
);
965 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
966 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
967 ) throws IOException
, InvalidNumberException
{
968 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
970 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
971 targetSentTimestamp
);
972 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
973 .withReaction(reaction
);
974 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
977 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
978 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
980 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
982 return sendMessage(messageBuilder
, signalServiceAddresses
);
983 } catch (Exception e
) {
984 for (SignalServiceAddress address
: signalServiceAddresses
) {
985 handleEndSession(address
);
992 public String
getContactName(String number
) throws InvalidNumberException
{
993 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
994 if (contact
== null) {
1001 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1002 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1003 ContactInfo contact
= account
.getContactStore().getContact(address
);
1004 if (contact
== null) {
1005 contact
= new ContactInfo(address
);
1007 contact
.name
= name
;
1008 account
.getContactStore().updateContact(contact
);
1012 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1013 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1016 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1017 ContactInfo contact
= account
.getContactStore().getContact(address
);
1018 if (contact
== null) {
1019 contact
= new ContactInfo(address
);
1021 contact
.blocked
= blocked
;
1022 account
.getContactStore().updateContact(contact
);
1026 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1027 GroupInfo group
= getGroup(groupId
);
1028 if (group
== null) {
1029 throw new GroupNotFoundException(groupId
);
1032 group
.setBlocked(blocked
);
1033 account
.getGroupStore().updateGroup(group
);
1038 * Change the expiration timer for a contact
1040 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1041 ContactInfo contact
= account
.getContactStore().getContact(address
);
1042 contact
.messageExpirationTime
= messageExpirationTimer
;
1043 account
.getContactStore().updateContact(contact
);
1044 sendExpirationTimerUpdate(address
);
1048 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1049 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1050 .asExpirationUpdate();
1051 sendMessage(messageBuilder
, List
.of(address
));
1055 * Change the expiration timer for a contact
1057 public void setExpirationTimer(
1058 String number
, int messageExpirationTimer
1059 ) throws IOException
, InvalidNumberException
{
1060 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1061 setExpirationTimer(address
, messageExpirationTimer
);
1065 * Change the expiration timer for a group
1067 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1068 GroupInfo g
= getGroup(groupId
);
1069 if (g
instanceof GroupInfoV1
) {
1070 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1071 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1072 account
.getGroupStore().updateGroup(groupInfoV1
);
1074 throw new RuntimeException("TODO Not implemented!");
1079 * Upload the sticker pack from path.
1081 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1082 * @return if successful, returns the URL to install the sticker pack in the signal app
1084 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1085 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1087 SignalServiceMessageSender messageSender
= createMessageSender();
1089 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1090 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1092 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1093 account
.getStickerStore().updateSticker(sticker
);
1097 return new URI("https",
1100 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1101 Hex
.toStringCondensed(packKey
),
1102 StandardCharsets
.UTF_8
)).toString();
1103 } catch (URISyntaxException e
) {
1104 throw new AssertionError(e
);
1108 void requestSyncGroups() throws IOException
{
1109 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1110 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1112 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1114 sendSyncMessage(message
);
1115 } catch (UntrustedIdentityException e
) {
1116 throw new AssertionError(e
);
1120 void requestSyncContacts() throws IOException
{
1121 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1122 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1124 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1126 sendSyncMessage(message
);
1127 } catch (UntrustedIdentityException e
) {
1128 throw new AssertionError(e
);
1132 void requestSyncBlocked() throws IOException
{
1133 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1134 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1136 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1138 sendSyncMessage(message
);
1139 } catch (UntrustedIdentityException e
) {
1140 throw new AssertionError(e
);
1144 void requestSyncConfiguration() throws IOException
{
1145 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1146 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1148 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1150 sendSyncMessage(message
);
1151 } catch (UntrustedIdentityException e
) {
1152 throw new AssertionError(e
);
1156 private byte[] getSenderCertificate() {
1157 // TODO support UUID capable sender certificates
1158 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1161 certificate
= accountManager
.getSenderCertificate();
1162 } catch (IOException e
) {
1163 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1166 // TODO cache for a day
1170 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1171 SignalServiceMessageSender messageSender
= createMessageSender();
1173 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1174 } catch (UntrustedIdentityException e
) {
1175 account
.getSignalProtocolStore()
1176 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1178 TrustLevel
.UNTRUSTED
);
1183 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1184 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1185 final Set
<SignalServiceAddress
> addressesMissingUuid
= new HashSet
<>();
1187 for (String number
: numbers
) {
1188 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1189 if (resolvedAddress
.getUuid().isPresent()) {
1190 signalServiceAddresses
.add(resolvedAddress
);
1192 addressesMissingUuid
.add(resolvedAddress
);
1196 final Set
<String
> numbersMissingUuid
= addressesMissingUuid
.stream()
1197 .map(a
-> a
.getNumber().get())
1198 .collect(Collectors
.toSet());
1199 Map
<String
, UUID
> registeredUsers
;
1201 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1202 } catch (IOException e
) {
1203 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1204 registeredUsers
= Map
.of();
1207 for (SignalServiceAddress address
: addressesMissingUuid
) {
1208 final String number
= address
.getNumber().get();
1209 if (registeredUsers
.containsKey(number
)) {
1210 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1211 registeredUsers
.get(number
),
1213 signalServiceAddresses
.add(newAddress
);
1215 signalServiceAddresses
.add(address
);
1219 return signalServiceAddresses
;
1222 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1224 return accountManager
.getRegisteredUsers(getIasKeyStore(), numbersMissingUuid
, CDS_MRENCLAVE
);
1225 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException e
) {
1226 throw new IOException(e
);
1230 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1231 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1232 ) throws IOException
{
1233 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1234 final long timestamp
= System
.currentTimeMillis();
1235 messageBuilder
.withTimestamp(timestamp
);
1236 getOrCreateMessagePipe();
1237 getOrCreateUnidentifiedMessagePipe();
1238 SignalServiceDataMessage message
= null;
1240 message
= messageBuilder
.build();
1241 if (message
.getGroupContext().isPresent()) {
1243 SignalServiceMessageSender messageSender
= createMessageSender();
1244 final boolean isRecipientUpdate
= false;
1245 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1246 unidentifiedAccessHelper
.getAccessFor(recipients
),
1249 for (SendMessageResult r
: result
) {
1250 if (r
.getIdentityFailure() != null) {
1251 account
.getSignalProtocolStore()
1252 .saveIdentity(r
.getAddress(),
1253 r
.getIdentityFailure().getIdentityKey(),
1254 TrustLevel
.UNTRUSTED
);
1257 return new Pair
<>(timestamp
, result
);
1258 } catch (UntrustedIdentityException e
) {
1259 account
.getSignalProtocolStore()
1260 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1262 TrustLevel
.UNTRUSTED
);
1263 return new Pair
<>(timestamp
, List
.of());
1266 // Send to all individually, so sync messages are sent correctly
1267 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1268 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1269 for (SignalServiceAddress address
: recipients
) {
1270 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1271 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1272 messageBuilder
.withExpiration(expirationTime
);
1273 message
= messageBuilder
.build();
1274 results
.add(sendMessage(address
, message
));
1276 return new Pair
<>(timestamp
, results
);
1279 if (message
!= null && message
.isEndSession()) {
1280 for (SignalServiceAddress recipient
: recipients
) {
1281 handleEndSession(recipient
);
1288 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1289 SignalServiceDataMessage
.Builder messageBuilder
1290 ) throws IOException
{
1291 final long timestamp
= System
.currentTimeMillis();
1292 messageBuilder
.withTimestamp(timestamp
);
1293 getOrCreateMessagePipe();
1294 getOrCreateUnidentifiedMessagePipe();
1296 final SignalServiceAddress address
= getSelfAddress();
1298 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1299 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1300 messageBuilder
.withExpiration(expirationTime
);
1302 SignalServiceDataMessage message
= messageBuilder
.build();
1303 final SendMessageResult result
= sendSelfMessage(message
);
1304 return new Pair
<>(timestamp
, result
);
1310 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1311 SignalServiceMessageSender messageSender
= createMessageSender();
1313 SignalServiceAddress recipient
= account
.getSelfAddress();
1315 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1316 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1317 message
.getTimestamp(),
1319 message
.getExpiresInSeconds(),
1320 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1322 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1325 long startTime
= System
.currentTimeMillis();
1326 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1327 return SendMessageResult
.success(recipient
,
1328 unidentifiedAccess
.isPresent(),
1330 System
.currentTimeMillis() - startTime
);
1331 } catch (UntrustedIdentityException e
) {
1332 account
.getSignalProtocolStore()
1333 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1335 TrustLevel
.UNTRUSTED
);
1336 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1340 private SendMessageResult
sendMessage(
1341 SignalServiceAddress address
, SignalServiceDataMessage message
1342 ) throws IOException
{
1343 SignalServiceMessageSender messageSender
= createMessageSender();
1346 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1347 } catch (UntrustedIdentityException e
) {
1348 account
.getSignalProtocolStore()
1349 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1351 TrustLevel
.UNTRUSTED
);
1352 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1356 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1357 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1358 account
.getSignalProtocolStore(),
1359 certificateValidator
);
1361 return cipher
.decrypt(envelope
);
1362 } catch (ProtocolUntrustedIdentityException e
) {
1363 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1364 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1366 account
.getSignalProtocolStore()
1367 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1368 identityException
.getUntrustedIdentity(),
1369 TrustLevel
.UNTRUSTED
);
1370 throw identityException
;
1372 throw new AssertionError(e
);
1376 private void handleEndSession(SignalServiceAddress source
) {
1377 account
.getSignalProtocolStore().deleteAllSessions(source
);
1380 private List
<HandleAction
> handleSignalServiceDataMessage(
1381 SignalServiceDataMessage message
,
1383 SignalServiceAddress source
,
1384 SignalServiceAddress destination
,
1385 boolean ignoreAttachments
1387 List
<HandleAction
> actions
= new ArrayList
<>();
1388 if (message
.getGroupContext().isPresent()) {
1389 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1390 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1391 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1392 GroupInfo group
= getGroup(groupId
);
1393 if (group
== null || group
instanceof GroupInfoV1
) {
1394 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1395 switch (groupInfo
.getType()) {
1397 if (groupV1
== null) {
1398 groupV1
= new GroupInfoV1(groupId
);
1401 if (groupInfo
.getAvatar().isPresent()) {
1402 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1403 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1406 if (groupInfo
.getName().isPresent()) {
1407 groupV1
.name
= groupInfo
.getName().get();
1410 if (groupInfo
.getMembers().isPresent()) {
1411 groupV1
.addMembers(groupInfo
.getMembers()
1414 .map(this::resolveSignalServiceAddress
)
1415 .collect(Collectors
.toSet()));
1418 account
.getGroupStore().updateGroup(groupV1
);
1422 if (groupV1
== null && !isSync
) {
1423 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1427 if (groupV1
!= null) {
1428 groupV1
.removeMember(source
);
1429 account
.getGroupStore().updateGroup(groupV1
);
1434 if (groupV1
!= null && !isSync
) {
1435 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1440 // Received a group v1 message for a v2 group
1443 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1444 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1445 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1447 getOrMigrateGroup(groupMasterKey
,
1448 groupContext
.getRevision(),
1449 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1453 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1454 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1455 handleEndSession(conversationPartnerAddress
);
1457 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1458 if (message
.getGroupContext().isPresent()) {
1459 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1460 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1461 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1462 if (group
!= null) {
1463 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1464 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1465 account
.getGroupStore().updateGroup(group
);
1468 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1469 // disappearing message timer already stored in the DecryptedGroup
1471 } else if (conversationPartnerAddress
!= null) {
1472 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1473 if (contact
== null) {
1474 contact
= new ContactInfo(conversationPartnerAddress
);
1476 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1477 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1478 account
.getContactStore().updateContact(contact
);
1482 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1483 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1484 downloadAttachment(attachment
);
1487 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1488 final ProfileKey profileKey
;
1490 profileKey
= new ProfileKey(message
.getProfileKey().get());
1491 } catch (InvalidInputException e
) {
1492 throw new AssertionError(e
);
1494 if (source
.matches(account
.getSelfAddress())) {
1495 this.account
.setProfileKey(profileKey
);
1497 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1499 if (message
.getPreviews().isPresent()) {
1500 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1501 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1502 if (preview
.getImage().isPresent()) {
1503 downloadAttachment(preview
.getImage().get());
1507 if (message
.getQuote().isPresent()) {
1508 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1510 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1511 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1512 if (thumbnail
!= null) {
1513 downloadAttachment(thumbnail
);
1517 if (message
.getSticker().isPresent()) {
1518 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1519 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1520 if (sticker
== null) {
1521 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1522 account
.getStickerStore().updateSticker(sticker
);
1528 private GroupInfoV2
getOrMigrateGroup(
1529 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1531 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1533 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1534 GroupInfo groupInfo
= getGroup(groupId
);
1535 final GroupInfoV2 groupInfoV2
;
1536 if (groupInfo
instanceof GroupInfoV1
) {
1537 // Received a v2 group message for a v1 group, we need to locally migrate the group
1538 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1539 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1540 logger
.info("Locally migrated group {} to group v2, id: {}",
1541 groupInfo
.getGroupId().toBase64(),
1542 groupInfoV2
.getGroupId().toBase64());
1543 } else if (groupInfo
instanceof GroupInfoV2
) {
1544 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1546 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1549 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1550 DecryptedGroup group
= null;
1551 if (signedGroupChange
!= null
1552 && groupInfoV2
.getGroup() != null
1553 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1554 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1556 if (group
== null) {
1557 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1559 if (group
!= null) {
1560 storeProfileKeysFromMembers(group
);
1561 final String avatar
= group
.getAvatar();
1562 if (avatar
!= null && !avatar
.isEmpty()) {
1563 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1566 groupInfoV2
.setGroup(group
);
1567 account
.getGroupStore().updateGroup(groupInfoV2
);
1573 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1574 for (DecryptedMember member
: group
.getMembersList()) {
1575 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1576 member
.getUuid().toByteArray()), null));
1578 account
.getProfileStore()
1579 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1580 } catch (InvalidInputException ignored
) {
1585 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1586 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1587 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1591 private void retryFailedReceivedMessage(
1592 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1594 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1595 if (envelope
== null) {
1598 SignalServiceContent content
= null;
1599 if (!envelope
.isReceipt()) {
1601 content
= decryptMessage(envelope
);
1602 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1604 } catch (Exception er
) {
1605 // All other errors are not recoverable, so delete the cached message
1606 cachedMessage
.delete();
1609 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1610 for (HandleAction action
: actions
) {
1612 action
.execute(this);
1613 } catch (Throwable e
) {
1614 logger
.warn("Message action failed.", e
);
1619 handler
.handleMessage(envelope
, content
, null);
1620 cachedMessage
.delete();
1623 public void receiveMessages(
1626 boolean returnOnTimeout
,
1627 boolean ignoreAttachments
,
1628 ReceiveMessageHandler handler
1629 ) throws IOException
{
1630 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1632 Set
<HandleAction
> queuedActions
= null;
1634 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1636 boolean hasCaughtUpWithOldMessages
= false;
1639 SignalServiceEnvelope envelope
;
1640 SignalServiceContent content
= null;
1641 Exception exception
= null;
1642 final CachedMessage
[] cachedMessage
= {null};
1644 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1645 // store message on disk, before acknowledging receipt to the server
1646 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1648 if (result
.isPresent()) {
1649 envelope
= result
.get();
1651 // Received indicator that server queue is empty
1652 hasCaughtUpWithOldMessages
= true;
1654 if (queuedActions
!= null) {
1655 for (HandleAction action
: queuedActions
) {
1657 action
.execute(this);
1658 } catch (Throwable e
) {
1659 logger
.warn("Message action failed.", e
);
1663 queuedActions
.clear();
1664 queuedActions
= null;
1667 // Continue to wait another timeout for new messages
1670 } catch (TimeoutException e
) {
1671 if (returnOnTimeout
) return;
1673 } catch (InvalidVersionException e
) {
1674 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1678 if (envelope
.hasSource()) {
1679 // Store uuid if we don't have it already
1680 SignalServiceAddress source
= envelope
.getSourceAddress();
1681 resolveSignalServiceAddress(source
);
1683 if (!envelope
.isReceipt()) {
1685 content
= decryptMessage(envelope
);
1686 } catch (Exception e
) {
1689 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1690 if (hasCaughtUpWithOldMessages
) {
1691 for (HandleAction action
: actions
) {
1693 action
.execute(this);
1694 } catch (Throwable e
) {
1695 logger
.warn("Message action failed.", e
);
1699 if (queuedActions
== null) {
1700 queuedActions
= new HashSet
<>();
1702 queuedActions
.addAll(actions
);
1706 if (isMessageBlocked(envelope
, content
)) {
1707 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1708 } else if (isNotAGroupMember(envelope
, content
)) {
1709 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1711 handler
.handleMessage(envelope
, content
, exception
);
1713 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1714 if (cachedMessage
[0] != null) {
1715 cachedMessage
[0].delete();
1721 private boolean isMessageBlocked(
1722 SignalServiceEnvelope envelope
, SignalServiceContent content
1724 SignalServiceAddress source
;
1725 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1726 source
= envelope
.getSourceAddress();
1727 } else if (content
!= null) {
1728 source
= content
.getSender();
1732 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1733 if (sourceContact
!= null && sourceContact
.blocked
) {
1737 if (content
!= null && content
.getDataMessage().isPresent()) {
1738 SignalServiceDataMessage message
= content
.getDataMessage().get();
1739 if (message
.getGroupContext().isPresent()) {
1740 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1741 GroupInfo group
= getGroup(groupId
);
1742 if (group
!= null && group
.isBlocked()) {
1750 private boolean isNotAGroupMember(
1751 SignalServiceEnvelope envelope
, SignalServiceContent content
1753 SignalServiceAddress source
;
1754 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1755 source
= envelope
.getSourceAddress();
1756 } else if (content
!= null) {
1757 source
= content
.getSender();
1762 if (content
!= null && content
.getDataMessage().isPresent()) {
1763 SignalServiceDataMessage message
= content
.getDataMessage().get();
1764 if (message
.getGroupContext().isPresent()) {
1765 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1766 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1767 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1771 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1772 GroupInfo group
= getGroup(groupId
);
1773 if (group
!= null && !group
.isMember(source
)) {
1781 private List
<HandleAction
> handleMessage(
1782 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1784 List
<HandleAction
> actions
= new ArrayList
<>();
1785 if (content
!= null) {
1786 final SignalServiceAddress sender
;
1787 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1788 sender
= envelope
.getSourceAddress();
1790 sender
= content
.getSender();
1792 // Store uuid if we don't have it already
1793 resolveSignalServiceAddress(sender
);
1795 if (content
.getDataMessage().isPresent()) {
1796 SignalServiceDataMessage message
= content
.getDataMessage().get();
1798 if (content
.isNeedsReceipt()) {
1799 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1802 actions
.addAll(handleSignalServiceDataMessage(message
,
1805 account
.getSelfAddress(),
1806 ignoreAttachments
));
1808 if (content
.getSyncMessage().isPresent()) {
1809 account
.setMultiDevice(true);
1810 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1811 if (syncMessage
.getSent().isPresent()) {
1812 SentTranscriptMessage message
= syncMessage
.getSent().get();
1813 final SignalServiceAddress destination
= message
.getDestination().orNull();
1814 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1818 ignoreAttachments
));
1820 if (syncMessage
.getRequest().isPresent()) {
1821 RequestMessage rm
= syncMessage
.getRequest().get();
1822 if (rm
.isContactsRequest()) {
1823 actions
.add(SendSyncContactsAction
.create());
1825 if (rm
.isGroupsRequest()) {
1826 actions
.add(SendSyncGroupsAction
.create());
1828 if (rm
.isBlockedListRequest()) {
1829 actions
.add(SendSyncBlockedListAction
.create());
1831 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1833 if (syncMessage
.getGroups().isPresent()) {
1834 File tmpFile
= null;
1836 tmpFile
= IOUtils
.createTempFile();
1837 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1838 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1840 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1842 while ((g
= s
.read()) != null) {
1843 GroupInfoV1 syncGroup
= account
.getGroupStore()
1844 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1845 if (syncGroup
!= null) {
1846 if (g
.getName().isPresent()) {
1847 syncGroup
.name
= g
.getName().get();
1849 syncGroup
.addMembers(g
.getMembers()
1851 .map(this::resolveSignalServiceAddress
)
1852 .collect(Collectors
.toSet()));
1853 if (!g
.isActive()) {
1854 syncGroup
.removeMember(account
.getSelfAddress());
1856 // Add ourself to the member set as it's marked as active
1857 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1859 syncGroup
.blocked
= g
.isBlocked();
1860 if (g
.getColor().isPresent()) {
1861 syncGroup
.color
= g
.getColor().get();
1864 if (g
.getAvatar().isPresent()) {
1865 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1867 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1868 syncGroup
.archived
= g
.isArchived();
1869 account
.getGroupStore().updateGroup(syncGroup
);
1873 } catch (Exception e
) {
1874 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1878 if (tmpFile
!= null) {
1880 Files
.delete(tmpFile
.toPath());
1881 } catch (IOException e
) {
1882 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1889 if (syncMessage
.getBlockedList().isPresent()) {
1890 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1891 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1892 setContactBlocked(resolveSignalServiceAddress(address
), true);
1894 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1896 .map(GroupId
::unknownVersion
)
1897 .collect(Collectors
.toSet())) {
1899 setGroupBlocked(groupId
, true);
1900 } catch (GroupNotFoundException e
) {
1901 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1902 groupId
.toBase64());
1906 if (syncMessage
.getContacts().isPresent()) {
1907 File tmpFile
= null;
1909 tmpFile
= IOUtils
.createTempFile();
1910 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1911 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1912 .asPointer(), tmpFile
)) {
1913 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1914 if (contactsMessage
.isComplete()) {
1915 account
.getContactStore().clear();
1918 while ((c
= s
.read()) != null) {
1919 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1920 account
.setProfileKey(c
.getProfileKey().get());
1922 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1923 ContactInfo contact
= account
.getContactStore().getContact(address
);
1924 if (contact
== null) {
1925 contact
= new ContactInfo(address
);
1927 if (c
.getName().isPresent()) {
1928 contact
.name
= c
.getName().get();
1930 if (c
.getColor().isPresent()) {
1931 contact
.color
= c
.getColor().get();
1933 if (c
.getProfileKey().isPresent()) {
1934 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1936 if (c
.getVerified().isPresent()) {
1937 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1938 account
.getSignalProtocolStore()
1939 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1940 verifiedMessage
.getIdentityKey(),
1941 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1943 if (c
.getExpirationTimer().isPresent()) {
1944 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1946 contact
.blocked
= c
.isBlocked();
1947 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1948 contact
.archived
= c
.isArchived();
1949 account
.getContactStore().updateContact(contact
);
1951 if (c
.getAvatar().isPresent()) {
1952 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
1956 } catch (Exception e
) {
1957 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1961 if (tmpFile
!= null) {
1963 Files
.delete(tmpFile
.toPath());
1964 } catch (IOException e
) {
1965 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1972 if (syncMessage
.getVerified().isPresent()) {
1973 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1974 account
.getSignalProtocolStore()
1975 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
1976 verifiedMessage
.getIdentityKey(),
1977 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1979 if (syncMessage
.getStickerPackOperations().isPresent()) {
1980 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
1982 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
1983 if (!m
.getPackId().isPresent()) {
1986 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
1987 if (sticker
== null) {
1988 if (!m
.getPackKey().isPresent()) {
1991 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
1993 sticker
.setInstalled(!m
.getType().isPresent()
1994 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
1995 account
.getStickerStore().updateSticker(sticker
);
1998 if (syncMessage
.getConfiguration().isPresent()) {
2006 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2008 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2009 } catch (IOException e
) {
2010 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2014 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2016 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2017 } catch (IOException e
) {
2018 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2022 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2024 avatarStore
.storeGroupAvatar(groupId
,
2025 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2026 } catch (IOException e
) {
2027 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2031 private void downloadProfileAvatar(
2032 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2035 avatarStore
.storeProfileAvatar(address
,
2036 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2037 } catch (Throwable e
) {
2038 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2042 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2043 return attachmentStore
.getAttachmentFile(attachmentId
);
2046 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2047 if (!attachment
.isPointer()) {
2048 logger
.warn("Invalid state, can't store an attachment stream.");
2051 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2052 if (pointer
.getPreview().isPresent()) {
2053 final byte[] preview
= pointer
.getPreview().get();
2055 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2056 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2057 } catch (IOException e
) {
2058 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2063 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2064 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2065 } catch (IOException e
) {
2066 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2070 private void retrieveGroupV2Avatar(
2071 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2072 ) throws IOException
{
2073 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2075 File tmpFile
= IOUtils
.createTempFile();
2076 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2078 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2079 byte[] encryptedData
= IOUtils
.readFully(input
);
2081 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2082 outputStream
.write(decryptedData
);
2085 Files
.delete(tmpFile
.toPath());
2086 } catch (IOException e
) {
2087 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2094 private void retrieveProfileAvatar(
2095 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2096 ) throws IOException
{
2097 File tmpFile
= IOUtils
.createTempFile();
2098 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2101 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2102 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2103 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2106 Files
.delete(tmpFile
.toPath());
2107 } catch (IOException e
) {
2108 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2115 private void retrieveAttachment(
2116 final SignalServiceAttachment attachment
, final OutputStream outputStream
2117 ) throws IOException
{
2118 if (attachment
.isPointer()) {
2119 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2120 retrieveAttachmentPointer(pointer
, outputStream
);
2122 SignalServiceAttachmentStream stream
= attachment
.asStream();
2123 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2127 private void retrieveAttachmentPointer(
2128 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2129 ) throws IOException
{
2130 File tmpFile
= IOUtils
.createTempFile();
2131 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2132 IOUtils
.copyStream(input
, outputStream
);
2133 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2134 throw new IOException(e
);
2137 Files
.delete(tmpFile
.toPath());
2138 } catch (IOException e
) {
2139 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2146 private InputStream
retrieveAttachmentAsStream(
2147 SignalServiceAttachmentPointer pointer
, File tmpFile
2148 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2149 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2152 void sendGroups() throws IOException
, UntrustedIdentityException
{
2153 File groupsFile
= IOUtils
.createTempFile();
2156 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2157 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2158 for (GroupInfo
record : getGroups()) {
2159 if (record instanceof GroupInfoV1
) {
2160 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2161 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2162 Optional
.fromNullable(groupInfo
.name
),
2163 new ArrayList
<>(groupInfo
.getMembers()),
2164 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2165 groupInfo
.isMember(account
.getSelfAddress()),
2166 Optional
.of(groupInfo
.messageExpirationTime
),
2167 Optional
.fromNullable(groupInfo
.color
),
2169 Optional
.fromNullable(groupInfo
.inboxPosition
),
2170 groupInfo
.archived
));
2175 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2176 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2177 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2178 .withStream(groupsFileStream
)
2179 .withContentType("application/octet-stream")
2180 .withLength(groupsFile
.length())
2183 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2188 Files
.delete(groupsFile
.toPath());
2189 } catch (IOException e
) {
2190 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2195 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2196 File contactsFile
= IOUtils
.createTempFile();
2199 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2200 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2201 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2202 VerifiedMessage verifiedMessage
= null;
2203 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2204 if (currentIdentity
!= null) {
2205 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2206 currentIdentity
.getIdentityKey(),
2207 currentIdentity
.getTrustLevel().toVerifiedState(),
2208 currentIdentity
.getDateAdded().getTime());
2211 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2212 out
.write(new DeviceContact(record.getAddress(),
2213 Optional
.fromNullable(record.name
),
2214 createContactAvatarAttachment(record.getAddress()),
2215 Optional
.fromNullable(record.color
),
2216 Optional
.fromNullable(verifiedMessage
),
2217 Optional
.fromNullable(profileKey
),
2219 Optional
.of(record.messageExpirationTime
),
2220 Optional
.fromNullable(record.inboxPosition
),
2224 if (account
.getProfileKey() != null) {
2225 // Send our own profile key as well
2226 out
.write(new DeviceContact(account
.getSelfAddress(),
2231 Optional
.of(account
.getProfileKey()),
2239 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2240 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2241 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2242 .withStream(contactsFileStream
)
2243 .withContentType("application/octet-stream")
2244 .withLength(contactsFile
.length())
2247 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2252 Files
.delete(contactsFile
.toPath());
2253 } catch (IOException e
) {
2254 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2259 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2260 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2261 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2262 if (record.blocked
) {
2263 addresses
.add(record.getAddress());
2266 List
<byte[]> groupIds
= new ArrayList
<>();
2267 for (GroupInfo
record : getGroups()) {
2268 if (record.isBlocked()) {
2269 groupIds
.add(record.getGroupId().serialize());
2272 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2275 private void sendVerifiedMessage(
2276 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2277 ) throws IOException
, UntrustedIdentityException
{
2278 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2280 trustLevel
.toVerifiedState(),
2281 System
.currentTimeMillis());
2282 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2285 public List
<ContactInfo
> getContacts() {
2286 return account
.getContactStore().getContacts();
2289 public ContactInfo
getContact(String number
) {
2290 return account
.getContactStore().getContact(Utils
.getSignalServiceAddressFromIdentifier(number
));
2293 public GroupInfo
getGroup(GroupId groupId
) {
2294 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2295 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2296 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2297 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2298 account
.getGroupStore().updateGroup(group
);
2303 public List
<IdentityInfo
> getIdentities() {
2304 return account
.getSignalProtocolStore().getIdentities();
2307 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2308 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2312 * Trust this the identity with this fingerprint
2314 * @param name username of the identity
2315 * @param fingerprint Fingerprint
2317 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2318 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2319 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2323 for (IdentityInfo id
: ids
) {
2324 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2328 account
.getSignalProtocolStore()
2329 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2331 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2332 } catch (IOException
| UntrustedIdentityException e
) {
2333 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2342 * Trust this the identity with this safety number
2344 * @param name username of the identity
2345 * @param safetyNumber Safety number
2347 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2348 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2349 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2353 for (IdentityInfo id
: ids
) {
2354 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2358 account
.getSignalProtocolStore()
2359 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2361 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2362 } catch (IOException
| UntrustedIdentityException e
) {
2363 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2372 * Trust all keys of this identity without verification
2374 * @param name username of the identity
2376 public boolean trustIdentityAllKeys(String name
) {
2377 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2378 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2382 for (IdentityInfo id
: ids
) {
2383 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2384 account
.getSignalProtocolStore()
2385 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2387 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2388 } catch (IOException
| UntrustedIdentityException e
) {
2389 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2397 public String
computeSafetyNumber(
2398 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2400 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2401 account
.getSelfAddress(),
2402 getIdentityKeyPair().getPublicKey(),
2407 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2408 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2410 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2411 return resolveSignalServiceAddress(canonicalizedNumber
);
2414 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2415 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2417 return resolveSignalServiceAddress(address
);
2420 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2421 if (address
.matches(account
.getSelfAddress())) {
2422 return account
.getSelfAddress();
2425 return account
.getRecipientStore().resolveServiceAddress(address
);
2429 public void close() throws IOException
{
2433 void close(boolean closeAccount
) throws IOException
{
2434 if (messagePipe
!= null) {
2435 messagePipe
.shutdown();
2439 if (unidentifiedMessagePipe
!= null) {
2440 unidentifiedMessagePipe
.shutdown();
2441 unidentifiedMessagePipe
= null;
2444 if (closeAccount
&& account
!= null) {
2450 public interface ReceiveMessageHandler
{
2452 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);