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
.KeysMessage
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
121 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
122 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
123 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
124 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
125 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
126 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
127 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
128 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
129 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
130 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
131 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
132 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
133 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
134 import org
.whispersystems
.signalservice
.internal
.configuration
.SignalServiceConfiguration
;
135 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
136 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
137 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
138 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
139 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
140 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
141 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
142 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
144 import java
.io
.Closeable
;
146 import java
.io
.FileInputStream
;
147 import java
.io
.FileOutputStream
;
148 import java
.io
.IOException
;
149 import java
.io
.InputStream
;
150 import java
.io
.OutputStream
;
152 import java
.net
.URISyntaxException
;
153 import java
.net
.URLEncoder
;
154 import java
.nio
.charset
.StandardCharsets
;
155 import java
.nio
.file
.Files
;
156 import java
.security
.SignatureException
;
157 import java
.util
.ArrayList
;
158 import java
.util
.Arrays
;
159 import java
.util
.Collection
;
160 import java
.util
.Date
;
161 import java
.util
.HashMap
;
162 import java
.util
.HashSet
;
163 import java
.util
.List
;
164 import java
.util
.Map
;
165 import java
.util
.Set
;
166 import java
.util
.UUID
;
167 import java
.util
.concurrent
.ExecutorService
;
168 import java
.util
.concurrent
.TimeUnit
;
169 import java
.util
.concurrent
.TimeoutException
;
170 import java
.util
.stream
.Collectors
;
172 import static org
.asamk
.signal
.manager
.ServiceConfig
.CDS_MRENCLAVE
;
173 import static org
.asamk
.signal
.manager
.ServiceConfig
.capabilities
;
174 import static org
.asamk
.signal
.manager
.ServiceConfig
.getIasKeyStore
;
176 public class Manager
implements Closeable
{
178 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
180 private final CertificateValidator certificateValidator
= new CertificateValidator(ServiceConfig
.getUnidentifiedSenderTrustRoot());
182 private final SignalServiceConfiguration serviceConfiguration
;
183 private final String userAgent
;
185 private SignalAccount account
;
186 private final SignalServiceAccountManager accountManager
;
187 private final GroupsV2Api groupsV2Api
;
188 private final GroupsV2Operations groupsV2Operations
;
189 private final SignalServiceMessageReceiver messageReceiver
;
190 private final ClientZkProfileOperations clientZkProfileOperations
;
192 private SignalServiceMessagePipe messagePipe
= null;
193 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
195 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
196 private final ProfileHelper profileHelper
;
197 private final GroupHelper groupHelper
;
198 private final PinHelper pinHelper
;
199 private final AvatarStore avatarStore
;
200 private final AttachmentStore attachmentStore
;
203 SignalAccount account
,
204 PathConfig pathConfig
,
205 SignalServiceConfiguration serviceConfiguration
,
208 this.account
= account
;
209 this.serviceConfiguration
= serviceConfiguration
;
210 this.userAgent
= userAgent
;
211 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
212 serviceConfiguration
)) : null;
213 final SleepTimer timer
= new UptimeSleepTimer();
214 this.accountManager
= new SignalServiceAccountManager(serviceConfiguration
,
215 new DynamicCredentialsProvider(account
.getUuid(),
216 account
.getUsername(),
217 account
.getPassword(),
218 account
.getSignalingKey(),
219 account
.getDeviceId()),
222 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
224 this.groupsV2Api
= accountManager
.getGroupsV2Api();
225 final KeyBackupService keyBackupService
= ServiceConfig
.createKeyBackupService(accountManager
);
226 this.pinHelper
= new PinHelper(keyBackupService
);
227 this.clientZkProfileOperations
= capabilities
.isGv2() ? ClientZkOperations
.create(serviceConfiguration
)
228 .getProfileOperations() : null;
229 this.messageReceiver
= new SignalServiceMessageReceiver(serviceConfiguration
,
231 account
.getUsername(),
232 account
.getPassword(),
233 account
.getDeviceId(),
234 account
.getSignalingKey(),
238 clientZkProfileOperations
,
239 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
241 this.account
.setResolver(this::resolveSignalServiceAddress
);
243 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
244 account
.getProfileStore()::getProfileKey
,
245 this::getRecipientProfile
,
246 this::getSenderCertificate
);
247 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
248 unidentifiedAccessHelper
::getAccessFor
,
249 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
250 () -> messageReceiver
);
251 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
252 this::getRecipientProfile
,
253 account
::getSelfAddress
,
256 this::getGroupAuthForToday
);
257 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
258 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
261 public String
getUsername() {
262 return account
.getUsername();
265 public SignalServiceAddress
getSelfAddress() {
266 return account
.getSelfAddress();
269 private IdentityKeyPair
getIdentityKeyPair() {
270 return account
.getSignalProtocolStore().getIdentityKeyPair();
273 public int getDeviceId() {
274 return account
.getDeviceId();
277 public static Manager
init(
278 String username
, File settingsPath
, SignalServiceConfiguration serviceConfiguration
, String userAgent
279 ) throws IOException
, NotRegisteredException
{
280 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
282 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
283 throw new NotRegisteredException();
286 SignalAccount account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
288 if (!account
.isRegistered()) {
289 throw new NotRegisteredException();
292 return new Manager(account
, pathConfig
, serviceConfiguration
, userAgent
);
295 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
296 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
297 final File dataPath
= pathConfig
.getDataPath();
298 final File
[] files
= dataPath
.listFiles();
304 return Arrays
.stream(files
)
305 .filter(File
::isFile
)
307 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
308 .collect(Collectors
.toList());
311 public void checkAccountState() throws IOException
{
312 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
316 if (account
.getUuid() == null) {
317 account
.setUuid(accountManager
.getOwnUuid());
320 updateAccountAttributes();
324 * This is used for checking a set of phone numbers for registration on Signal
326 * @param numbers The set of phone number in question
327 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
328 * @throws IOException if its unable to get the contacts to check if they're registered
330 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
331 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
332 Map
<String
, UUID
> contactDetails
= getRegisteredUsers(numbers
);
334 Set
<String
> registeredUsers
= contactDetails
.keySet();
336 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
339 public void updateAccountAttributes() throws IOException
{
340 accountManager
.setAccountAttributes(account
.getSignalingKey(),
341 account
.getSignalProtocolStore().getLocalRegistrationId(),
343 // set legacy pin only if no KBS master key is set
344 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
345 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
346 account
.getSelfUnidentifiedAccessKey(),
347 account
.isUnrestrictedUnidentifiedAccess(),
349 account
.isDiscoverableByPhoneNumber());
353 * @param avatar if avatar is null the image from the local avatar store is used (if present),
354 * if it's Optional.absent(), the avatar will be removed
356 public void setProfile(String name
, Optional
<File
> avatar
) throws IOException
{
359 String aboutEmoji
= null;
361 try (final StreamDetails streamDetails
= avatar
== null
362 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
363 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
364 accountManager
.setVersionedProfile(account
.getUuid(),
365 account
.getProfileKey(),
372 if (avatar
!= null) {
373 if (avatar
.isPresent()) {
374 avatarStore
.storeProfileAvatar(getSelfAddress(),
375 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
377 avatarStore
.deleteProfileAvatar(getSelfAddress());
382 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
383 } catch (UntrustedIdentityException ignored
) {
387 public void unregister() throws IOException
{
388 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
389 // If this is the master device, other users can't send messages to this number anymore.
390 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
391 accountManager
.setGcmId(Optional
.absent());
392 accountManager
.deleteAccount();
394 account
.setRegistered(false);
398 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
399 List
<DeviceInfo
> devices
= accountManager
.getDevices();
400 account
.setMultiDevice(devices
.size() > 1);
405 public void removeLinkedDevices(int deviceId
) throws IOException
{
406 accountManager
.removeDevice(deviceId
);
407 List
<DeviceInfo
> devices
= accountManager
.getDevices();
408 account
.setMultiDevice(devices
.size() > 1);
412 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
413 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
415 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
418 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
419 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
420 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
422 accountManager
.addDevice(deviceIdentifier
,
425 Optional
.of(account
.getProfileKey().serialize()),
427 account
.setMultiDevice(true);
431 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
432 if (!account
.isMasterDevice()) {
433 throw new RuntimeException("Only master device can set a PIN");
435 if (pin
.isPresent()) {
436 final MasterKey masterKey
= account
.getPinMasterKey() != null
437 ? account
.getPinMasterKey()
438 : KeyUtils
.createMasterKey();
440 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
442 account
.setRegistrationLockPin(pin
.get());
443 account
.setPinMasterKey(masterKey
);
445 // Remove legacy registration lock
446 accountManager
.removeRegistrationLockV1();
449 pinHelper
.removeRegistrationLockPin();
451 account
.setRegistrationLockPin(null);
452 account
.setPinMasterKey(null);
457 void refreshPreKeys() throws IOException
{
458 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
459 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
460 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
462 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
465 private List
<PreKeyRecord
> generatePreKeys() {
466 final int offset
= account
.getPreKeyIdOffset();
468 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
469 account
.addPreKeys(records
);
475 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
476 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
478 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
479 account
.addSignedPreKey(record);
485 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
486 if (messagePipe
== null) {
487 messagePipe
= messageReceiver
.createMessagePipe();
492 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
493 if (unidentifiedMessagePipe
== null) {
494 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
496 return unidentifiedMessagePipe
;
499 private SignalServiceMessageSender
createMessageSender() {
500 final ExecutorService executor
= null;
501 return new SignalServiceMessageSender(serviceConfiguration
,
503 account
.getUsername(),
504 account
.getPassword(),
505 account
.getDeviceId(),
506 account
.getSignalProtocolStore(),
508 account
.isMultiDevice(),
509 Optional
.fromNullable(messagePipe
),
510 Optional
.fromNullable(unidentifiedMessagePipe
),
512 clientZkProfileOperations
,
514 ServiceConfig
.MAX_ENVELOPE_SIZE
,
515 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
518 private SignalProfile
getRecipientProfile(
519 SignalServiceAddress address
521 return getRecipientProfile(address
, false);
524 private SignalProfile
getRecipientProfile(
525 SignalServiceAddress address
, boolean force
527 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
528 if (profileEntry
== null) {
531 long now
= new Date().getTime();
532 // Profiles are cached for 24h before retrieving them again
533 if (!profileEntry
.isRequestPending() && (
535 || profileEntry
.getProfile() == null
536 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
538 profileEntry
.setRequestPending(true);
539 final SignalServiceProfile encryptedProfile
;
541 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
543 } catch (IOException e
) {
544 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
547 profileEntry
.setRequestPending(false);
550 final ProfileKey profileKey
= profileEntry
.getProfileKey();
551 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
552 account
.getProfileStore()
553 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
556 return profileEntry
.getProfile();
559 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
560 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
561 if (profileEntry
== null) {
564 if (profileEntry
.getProfileKeyCredential() == null) {
565 ProfileAndCredential profileAndCredential
;
567 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
568 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
569 } catch (IOException e
) {
570 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
574 long now
= new Date().getTime();
575 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
576 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
577 profileEntry
.getProfileKey(),
578 profileAndCredential
.getProfile());
579 account
.getProfileStore()
580 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
581 return profileKeyCredential
;
583 return profileEntry
.getProfileKeyCredential();
586 private SignalProfile
decryptProfileAndDownloadAvatar(
587 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
589 if (encryptedProfile
.getAvatar() != null) {
590 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
593 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
596 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
597 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
598 if (streamDetails
== null) {
599 return Optional
.absent();
602 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
605 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
606 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
607 if (streamDetails
== null) {
608 return Optional
.absent();
611 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
614 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
615 GroupInfo g
= getGroup(groupId
);
617 throw new GroupNotFoundException(groupId
);
619 if (!g
.isMember(account
.getSelfAddress())) {
620 throw new NotAGroupMemberException(groupId
, g
.getTitle());
625 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
626 GroupInfo g
= getGroup(groupId
);
628 throw new GroupNotFoundException(groupId
);
630 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
631 throw new NotAGroupMemberException(groupId
, g
.getTitle());
636 public List
<GroupInfo
> getGroups() {
637 return account
.getGroupStore().getGroups();
640 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
641 String messageText
, List
<String
> attachments
, GroupId groupId
642 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
643 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
644 .withBody(messageText
);
645 if (attachments
!= null) {
646 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
649 return sendGroupMessage(messageBuilder
, groupId
);
652 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
653 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
654 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
655 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
657 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
658 targetSentTimestamp
);
659 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
660 .withReaction(reaction
);
662 return sendGroupMessage(messageBuilder
, groupId
);
665 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
666 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
667 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
668 final GroupInfo g
= getGroupForSending(groupId
);
670 GroupUtils
.setGroupContext(messageBuilder
, g
);
671 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
673 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
676 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
677 SignalServiceDataMessage
.Builder messageBuilder
;
679 final GroupInfo g
= getGroupForUpdating(groupId
);
680 if (g
instanceof GroupInfoV1
) {
681 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
682 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
683 .withId(groupId
.serialize())
685 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
686 groupInfoV1
.removeMember(account
.getSelfAddress());
687 account
.getGroupStore().updateGroup(groupInfoV1
);
689 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
690 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
691 groupInfoV2
.setGroup(groupGroupChangePair
.first());
692 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
693 account
.getGroupStore().updateGroup(groupInfoV2
);
696 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
699 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
700 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
701 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
702 return sendUpdateGroupMessage(groupId
,
704 members
== null ?
null : getSignalServiceAddresses(members
),
708 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
709 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
710 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
712 SignalServiceDataMessage
.Builder messageBuilder
;
713 if (groupId
== null) {
715 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
716 members
== null ? List
.of() : members
,
719 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
720 gv1
.addMembers(List
.of(account
.getSelfAddress()));
721 updateGroupV1(gv1
, name
, members
, avatarFile
);
722 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
725 if (avatarFile
!= null) {
726 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
727 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
729 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
733 GroupInfo group
= getGroupForUpdating(groupId
);
734 if (group
instanceof GroupInfoV2
) {
735 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
737 Pair
<Long
, List
<SendMessageResult
>> result
= null;
738 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
739 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
740 result
= sendUpdateGroupMessage(groupInfoV2
,
741 groupGroupChangePair
.first(),
742 groupGroupChangePair
.second());
745 if (members
!= null) {
746 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
747 newMembers
.removeAll(group
.getMembers()
749 .map(this::resolveSignalServiceAddress
)
750 .collect(Collectors
.toSet()));
751 if (newMembers
.size() > 0) {
752 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
754 result
= sendUpdateGroupMessage(groupInfoV2
,
755 groupGroupChangePair
.first(),
756 groupGroupChangePair
.second());
759 if (result
== null || name
!= null || avatarFile
!= null) {
760 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
763 if (avatarFile
!= null) {
764 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
765 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
767 result
= sendUpdateGroupMessage(groupInfoV2
,
768 groupGroupChangePair
.first(),
769 groupGroupChangePair
.second());
772 return new Pair
<>(group
.getGroupId(), result
.second());
774 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
775 updateGroupV1(gv1
, name
, members
, avatarFile
);
776 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
781 account
.getGroupStore().updateGroup(g
);
783 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
784 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
785 return new Pair
<>(g
.getGroupId(), result
.second());
788 private void updateGroupV1(
791 final Collection
<SignalServiceAddress
> members
,
792 final File avatarFile
793 ) throws IOException
{
798 if (members
!= null) {
799 final Set
<String
> newE164Members
= new HashSet
<>();
800 for (SignalServiceAddress member
: members
) {
801 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
804 newE164Members
.add(member
.getNumber().get());
807 final Map
<String
, UUID
> registeredUsers
= getRegisteredUsers(newE164Members
);
808 if (registeredUsers
.size() != newE164Members
.size()) {
809 // Some of the new members are not registered on Signal
810 newE164Members
.removeAll(registeredUsers
.keySet());
811 throw new IOException("Failed to add members "
812 + String
.join(", ", newE164Members
)
813 + " to group: Not registered on Signal");
816 g
.addMembers(members
);
819 if (avatarFile
!= null) {
820 avatarStore
.storeGroupAvatar(g
.getGroupId(),
821 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
825 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
826 GroupInviteLinkUrl inviteLinkUrl
827 ) throws IOException
, GroupLinkNotActiveException
{
828 return sendJoinGroupMessage(inviteLinkUrl
);
831 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
832 GroupInviteLinkUrl inviteLinkUrl
833 ) throws IOException
, GroupLinkNotActiveException
{
834 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
835 inviteLinkUrl
.getPassword());
836 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
837 inviteLinkUrl
.getPassword(),
839 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
840 groupJoinInfo
.getRevision() + 1,
841 groupChange
.toByteArray());
843 if (group
.getGroup() == null) {
844 // Only requested member, can't send update to group members
845 return new Pair
<>(group
.getGroupId(), List
.of());
848 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
850 return new Pair
<>(group
.getGroupId(), result
.second());
853 private static int currentTimeDays() {
854 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
857 private GroupsV2AuthorizationString
getGroupAuthForToday(
858 final GroupSecretParams groupSecretParams
859 ) throws IOException
{
860 final int today
= currentTimeDays();
861 // Returns credentials for the next 7 days
862 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
863 // TODO cache credentials until they expire
864 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
866 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
869 authCredentialResponse
);
870 } catch (VerificationFailedException e
) {
871 throw new IOException(e
);
875 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
876 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
877 ) throws IOException
{
878 group
.setGroup(newDecryptedGroup
);
879 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
880 groupChange
.toByteArray());
881 account
.getGroupStore().updateGroup(group
);
882 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
885 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
886 GroupIdV1 groupId
, SignalServiceAddress recipient
887 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
889 GroupInfo group
= getGroupForSending(groupId
);
890 if (!(group
instanceof GroupInfoV1
)) {
891 throw new RuntimeException("Received an invalid group request for a v2 group!");
893 g
= (GroupInfoV1
) group
;
895 if (!g
.isMember(recipient
)) {
896 throw new NotAGroupMemberException(groupId
, g
.name
);
899 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
901 // Send group message only to the recipient who requested it
902 return sendMessage(messageBuilder
, List
.of(recipient
));
905 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
906 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
907 .withId(g
.getGroupId().serialize())
909 .withMembers(new ArrayList
<>(g
.getMembers()));
912 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
913 if (attachment
.isPresent()) {
914 group
.withAvatar(attachment
.get());
916 } catch (IOException e
) {
917 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
920 return SignalServiceDataMessage
.newBuilder()
921 .asGroupMessage(group
.build())
922 .withExpiration(g
.getMessageExpirationTime());
925 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
926 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
927 .withRevision(g
.getGroup().getRevision())
928 .withSignedGroupChange(signedGroupChange
);
929 return SignalServiceDataMessage
.newBuilder()
930 .asGroupMessage(group
.build())
931 .withExpiration(g
.getMessageExpirationTime());
934 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
935 GroupIdV1 groupId
, SignalServiceAddress recipient
936 ) throws IOException
{
937 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
938 .withId(groupId
.serialize());
940 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
941 .asGroupMessage(group
.build());
943 // Send group info request message to the recipient who sent us a message with this groupId
944 return sendMessage(messageBuilder
, List
.of(recipient
));
948 SignalServiceAddress remoteAddress
, long messageId
949 ) throws IOException
, UntrustedIdentityException
{
950 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
952 System
.currentTimeMillis());
954 createMessageSender().sendReceipt(remoteAddress
,
955 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
959 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
960 String messageText
, List
<String
> attachments
, List
<String
> recipients
961 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
962 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
963 .withBody(messageText
);
964 if (attachments
!= null) {
965 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
967 // Upload attachments here, so we only upload once even for multiple recipients
968 SignalServiceMessageSender messageSender
= createMessageSender();
969 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
970 for (SignalServiceAttachment attachment
: attachmentStreams
) {
971 if (attachment
.isStream()) {
972 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
973 } else if (attachment
.isPointer()) {
974 attachmentPointers
.add(attachment
.asPointer());
978 messageBuilder
.withAttachments(attachmentPointers
);
980 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
983 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
984 String messageText
, List
<String
> attachments
985 ) throws IOException
, AttachmentInvalidException
{
986 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
987 .withBody(messageText
);
988 if (attachments
!= null) {
989 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
991 return sendSelfMessage(messageBuilder
);
994 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
995 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
996 ) throws IOException
, InvalidNumberException
{
997 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
999 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1000 targetSentTimestamp
);
1001 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1002 .withReaction(reaction
);
1003 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1006 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1007 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1009 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1011 return sendMessage(messageBuilder
, signalServiceAddresses
);
1012 } catch (Exception e
) {
1013 for (SignalServiceAddress address
: signalServiceAddresses
) {
1014 handleEndSession(address
);
1021 public String
getContactName(String number
) throws InvalidNumberException
{
1022 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1023 if (contact
== null) {
1026 return contact
.name
;
1030 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1031 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1032 ContactInfo contact
= account
.getContactStore().getContact(address
);
1033 if (contact
== null) {
1034 contact
= new ContactInfo(address
);
1036 contact
.name
= name
;
1037 account
.getContactStore().updateContact(contact
);
1041 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1042 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1045 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1046 ContactInfo contact
= account
.getContactStore().getContact(address
);
1047 if (contact
== null) {
1048 contact
= new ContactInfo(address
);
1050 contact
.blocked
= blocked
;
1051 account
.getContactStore().updateContact(contact
);
1055 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1056 GroupInfo group
= getGroup(groupId
);
1057 if (group
== null) {
1058 throw new GroupNotFoundException(groupId
);
1061 group
.setBlocked(blocked
);
1062 account
.getGroupStore().updateGroup(group
);
1067 * Change the expiration timer for a contact
1069 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1070 ContactInfo contact
= account
.getContactStore().getContact(address
);
1071 contact
.messageExpirationTime
= messageExpirationTimer
;
1072 account
.getContactStore().updateContact(contact
);
1073 sendExpirationTimerUpdate(address
);
1077 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1078 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1079 .asExpirationUpdate();
1080 sendMessage(messageBuilder
, List
.of(address
));
1084 * Change the expiration timer for a contact
1086 public void setExpirationTimer(
1087 String number
, int messageExpirationTimer
1088 ) throws IOException
, InvalidNumberException
{
1089 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1090 setExpirationTimer(address
, messageExpirationTimer
);
1094 * Change the expiration timer for a group
1096 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1097 GroupInfo g
= getGroup(groupId
);
1098 if (g
instanceof GroupInfoV1
) {
1099 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1100 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1101 account
.getGroupStore().updateGroup(groupInfoV1
);
1103 throw new RuntimeException("TODO Not implemented!");
1108 * Upload the sticker pack from path.
1110 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1111 * @return if successful, returns the URL to install the sticker pack in the signal app
1113 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1114 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1116 SignalServiceMessageSender messageSender
= createMessageSender();
1118 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1119 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1121 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1122 account
.getStickerStore().updateSticker(sticker
);
1126 return new URI("https",
1129 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1130 Hex
.toStringCondensed(packKey
),
1131 StandardCharsets
.UTF_8
)).toString();
1132 } catch (URISyntaxException e
) {
1133 throw new AssertionError(e
);
1137 void requestSyncGroups() throws IOException
{
1138 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1139 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1141 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1143 sendSyncMessage(message
);
1144 } catch (UntrustedIdentityException e
) {
1145 throw new AssertionError(e
);
1149 void requestSyncContacts() throws IOException
{
1150 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1151 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1153 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1155 sendSyncMessage(message
);
1156 } catch (UntrustedIdentityException e
) {
1157 throw new AssertionError(e
);
1161 void requestSyncBlocked() throws IOException
{
1162 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1163 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1165 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1167 sendSyncMessage(message
);
1168 } catch (UntrustedIdentityException e
) {
1169 throw new AssertionError(e
);
1173 void requestSyncConfiguration() throws IOException
{
1174 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1175 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1177 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1179 sendSyncMessage(message
);
1180 } catch (UntrustedIdentityException e
) {
1181 throw new AssertionError(e
);
1185 void requestSyncKeys() throws IOException
{
1186 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1187 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1189 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1191 sendSyncMessage(message
);
1192 } catch (UntrustedIdentityException e
) {
1193 throw new AssertionError(e
);
1197 private byte[] getSenderCertificate() {
1198 // TODO support UUID capable sender certificates
1199 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1202 certificate
= accountManager
.getSenderCertificate();
1203 } catch (IOException e
) {
1204 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1207 // TODO cache for a day
1211 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1212 SignalServiceMessageSender messageSender
= createMessageSender();
1214 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1215 } catch (UntrustedIdentityException e
) {
1216 account
.getSignalProtocolStore()
1217 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1219 TrustLevel
.UNTRUSTED
);
1224 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1225 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1226 final Set
<SignalServiceAddress
> addressesMissingUuid
= new HashSet
<>();
1228 for (String number
: numbers
) {
1229 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1230 if (resolvedAddress
.getUuid().isPresent()) {
1231 signalServiceAddresses
.add(resolvedAddress
);
1233 addressesMissingUuid
.add(resolvedAddress
);
1237 final Set
<String
> numbersMissingUuid
= addressesMissingUuid
.stream()
1238 .map(a
-> a
.getNumber().get())
1239 .collect(Collectors
.toSet());
1240 Map
<String
, UUID
> registeredUsers
;
1242 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1243 } catch (IOException e
) {
1244 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1245 registeredUsers
= Map
.of();
1248 for (SignalServiceAddress address
: addressesMissingUuid
) {
1249 final String number
= address
.getNumber().get();
1250 if (registeredUsers
.containsKey(number
)) {
1251 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1252 registeredUsers
.get(number
),
1254 signalServiceAddresses
.add(newAddress
);
1256 signalServiceAddresses
.add(address
);
1260 return signalServiceAddresses
;
1263 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1265 return accountManager
.getRegisteredUsers(getIasKeyStore(), numbersMissingUuid
, CDS_MRENCLAVE
);
1266 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1267 throw new IOException(e
);
1271 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1272 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1273 ) throws IOException
{
1274 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1275 final long timestamp
= System
.currentTimeMillis();
1276 messageBuilder
.withTimestamp(timestamp
);
1277 getOrCreateMessagePipe();
1278 getOrCreateUnidentifiedMessagePipe();
1279 SignalServiceDataMessage message
= null;
1281 message
= messageBuilder
.build();
1282 if (message
.getGroupContext().isPresent()) {
1284 SignalServiceMessageSender messageSender
= createMessageSender();
1285 final boolean isRecipientUpdate
= false;
1286 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1287 unidentifiedAccessHelper
.getAccessFor(recipients
),
1290 for (SendMessageResult r
: result
) {
1291 if (r
.getIdentityFailure() != null) {
1292 account
.getSignalProtocolStore()
1293 .saveIdentity(r
.getAddress(),
1294 r
.getIdentityFailure().getIdentityKey(),
1295 TrustLevel
.UNTRUSTED
);
1298 return new Pair
<>(timestamp
, result
);
1299 } catch (UntrustedIdentityException e
) {
1300 account
.getSignalProtocolStore()
1301 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1303 TrustLevel
.UNTRUSTED
);
1304 return new Pair
<>(timestamp
, List
.of());
1307 // Send to all individually, so sync messages are sent correctly
1308 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1309 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1310 for (SignalServiceAddress address
: recipients
) {
1311 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1312 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1313 messageBuilder
.withExpiration(expirationTime
);
1314 message
= messageBuilder
.build();
1315 results
.add(sendMessage(address
, message
));
1317 return new Pair
<>(timestamp
, results
);
1320 if (message
!= null && message
.isEndSession()) {
1321 for (SignalServiceAddress recipient
: recipients
) {
1322 handleEndSession(recipient
);
1329 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1330 SignalServiceDataMessage
.Builder messageBuilder
1331 ) throws IOException
{
1332 final long timestamp
= System
.currentTimeMillis();
1333 messageBuilder
.withTimestamp(timestamp
);
1334 getOrCreateMessagePipe();
1335 getOrCreateUnidentifiedMessagePipe();
1337 final SignalServiceAddress address
= getSelfAddress();
1339 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1340 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1341 messageBuilder
.withExpiration(expirationTime
);
1343 SignalServiceDataMessage message
= messageBuilder
.build();
1344 final SendMessageResult result
= sendSelfMessage(message
);
1345 return new Pair
<>(timestamp
, result
);
1351 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1352 SignalServiceMessageSender messageSender
= createMessageSender();
1354 SignalServiceAddress recipient
= account
.getSelfAddress();
1356 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1357 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1358 message
.getTimestamp(),
1360 message
.getExpiresInSeconds(),
1361 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1363 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1366 long startTime
= System
.currentTimeMillis();
1367 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1368 return SendMessageResult
.success(recipient
,
1369 unidentifiedAccess
.isPresent(),
1371 System
.currentTimeMillis() - startTime
);
1372 } catch (UntrustedIdentityException e
) {
1373 account
.getSignalProtocolStore()
1374 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1376 TrustLevel
.UNTRUSTED
);
1377 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1381 private SendMessageResult
sendMessage(
1382 SignalServiceAddress address
, SignalServiceDataMessage message
1383 ) throws IOException
{
1384 SignalServiceMessageSender messageSender
= createMessageSender();
1387 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1388 } catch (UntrustedIdentityException e
) {
1389 account
.getSignalProtocolStore()
1390 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1392 TrustLevel
.UNTRUSTED
);
1393 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1397 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1398 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1399 account
.getSignalProtocolStore(),
1400 certificateValidator
);
1402 return cipher
.decrypt(envelope
);
1403 } catch (ProtocolUntrustedIdentityException e
) {
1404 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1405 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1407 final IdentityKey untrustedIdentity
= identityException
.getUntrustedIdentity();
1408 if (untrustedIdentity
!= null) {
1409 account
.getSignalProtocolStore()
1410 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1412 TrustLevel
.UNTRUSTED
);
1414 throw identityException
;
1416 throw new AssertionError(e
);
1420 private void handleEndSession(SignalServiceAddress source
) {
1421 account
.getSignalProtocolStore().deleteAllSessions(source
);
1424 private List
<HandleAction
> handleSignalServiceDataMessage(
1425 SignalServiceDataMessage message
,
1427 SignalServiceAddress source
,
1428 SignalServiceAddress destination
,
1429 boolean ignoreAttachments
1431 List
<HandleAction
> actions
= new ArrayList
<>();
1432 if (message
.getGroupContext().isPresent()) {
1433 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1434 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1435 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1436 GroupInfo group
= getGroup(groupId
);
1437 if (group
== null || group
instanceof GroupInfoV1
) {
1438 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1439 switch (groupInfo
.getType()) {
1441 if (groupV1
== null) {
1442 groupV1
= new GroupInfoV1(groupId
);
1445 if (groupInfo
.getAvatar().isPresent()) {
1446 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1447 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1450 if (groupInfo
.getName().isPresent()) {
1451 groupV1
.name
= groupInfo
.getName().get();
1454 if (groupInfo
.getMembers().isPresent()) {
1455 groupV1
.addMembers(groupInfo
.getMembers()
1458 .map(this::resolveSignalServiceAddress
)
1459 .collect(Collectors
.toSet()));
1462 account
.getGroupStore().updateGroup(groupV1
);
1466 if (groupV1
== null && !isSync
) {
1467 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1471 if (groupV1
!= null) {
1472 groupV1
.removeMember(source
);
1473 account
.getGroupStore().updateGroup(groupV1
);
1478 if (groupV1
!= null && !isSync
) {
1479 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1484 // Received a group v1 message for a v2 group
1487 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1488 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1489 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1491 getOrMigrateGroup(groupMasterKey
,
1492 groupContext
.getRevision(),
1493 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1497 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1498 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1499 handleEndSession(conversationPartnerAddress
);
1501 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1502 if (message
.getGroupContext().isPresent()) {
1503 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1504 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1505 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1506 if (group
!= null) {
1507 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1508 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1509 account
.getGroupStore().updateGroup(group
);
1512 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1513 // disappearing message timer already stored in the DecryptedGroup
1515 } else if (conversationPartnerAddress
!= null) {
1516 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1517 if (contact
== null) {
1518 contact
= new ContactInfo(conversationPartnerAddress
);
1520 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1521 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1522 account
.getContactStore().updateContact(contact
);
1526 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1527 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1528 downloadAttachment(attachment
);
1531 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1532 final ProfileKey profileKey
;
1534 profileKey
= new ProfileKey(message
.getProfileKey().get());
1535 } catch (InvalidInputException e
) {
1536 throw new AssertionError(e
);
1538 if (source
.matches(account
.getSelfAddress())) {
1539 this.account
.setProfileKey(profileKey
);
1541 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1543 if (message
.getPreviews().isPresent()) {
1544 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1545 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1546 if (preview
.getImage().isPresent()) {
1547 downloadAttachment(preview
.getImage().get());
1551 if (message
.getQuote().isPresent()) {
1552 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1554 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1555 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1556 if (thumbnail
!= null) {
1557 downloadAttachment(thumbnail
);
1561 if (message
.getSticker().isPresent()) {
1562 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1563 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1564 if (sticker
== null) {
1565 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1566 account
.getStickerStore().updateSticker(sticker
);
1572 private GroupInfoV2
getOrMigrateGroup(
1573 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1575 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1577 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1578 GroupInfo groupInfo
= getGroup(groupId
);
1579 final GroupInfoV2 groupInfoV2
;
1580 if (groupInfo
instanceof GroupInfoV1
) {
1581 // Received a v2 group message for a v1 group, we need to locally migrate the group
1582 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1583 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1584 logger
.info("Locally migrated group {} to group v2, id: {}",
1585 groupInfo
.getGroupId().toBase64(),
1586 groupInfoV2
.getGroupId().toBase64());
1587 } else if (groupInfo
instanceof GroupInfoV2
) {
1588 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1590 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1593 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1594 DecryptedGroup group
= null;
1595 if (signedGroupChange
!= null
1596 && groupInfoV2
.getGroup() != null
1597 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1598 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1600 if (group
== null) {
1601 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1603 if (group
!= null) {
1604 storeProfileKeysFromMembers(group
);
1605 final String avatar
= group
.getAvatar();
1606 if (avatar
!= null && !avatar
.isEmpty()) {
1607 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1610 groupInfoV2
.setGroup(group
);
1611 account
.getGroupStore().updateGroup(groupInfoV2
);
1617 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1618 for (DecryptedMember member
: group
.getMembersList()) {
1619 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1620 member
.getUuid().toByteArray()), null));
1622 account
.getProfileStore()
1623 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1624 } catch (InvalidInputException ignored
) {
1629 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1630 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1631 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1635 private void retryFailedReceivedMessage(
1636 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1638 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1639 if (envelope
== null) {
1642 SignalServiceContent content
= null;
1643 if (!envelope
.isReceipt()) {
1645 content
= decryptMessage(envelope
);
1646 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1648 } catch (Exception er
) {
1649 // All other errors are not recoverable, so delete the cached message
1650 cachedMessage
.delete();
1653 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1654 for (HandleAction action
: actions
) {
1656 action
.execute(this);
1657 } catch (Throwable e
) {
1658 logger
.warn("Message action failed.", e
);
1663 handler
.handleMessage(envelope
, content
, null);
1664 cachedMessage
.delete();
1667 public void receiveMessages(
1670 boolean returnOnTimeout
,
1671 boolean ignoreAttachments
,
1672 ReceiveMessageHandler handler
1673 ) throws IOException
{
1674 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1676 Set
<HandleAction
> queuedActions
= null;
1678 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1680 boolean hasCaughtUpWithOldMessages
= false;
1683 SignalServiceEnvelope envelope
;
1684 SignalServiceContent content
= null;
1685 Exception exception
= null;
1686 final CachedMessage
[] cachedMessage
= {null};
1688 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1689 // store message on disk, before acknowledging receipt to the server
1690 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1692 if (result
.isPresent()) {
1693 envelope
= result
.get();
1695 // Received indicator that server queue is empty
1696 hasCaughtUpWithOldMessages
= true;
1698 if (queuedActions
!= null) {
1699 for (HandleAction action
: queuedActions
) {
1701 action
.execute(this);
1702 } catch (Throwable e
) {
1703 logger
.warn("Message action failed.", e
);
1707 queuedActions
.clear();
1708 queuedActions
= null;
1711 // Continue to wait another timeout for new messages
1714 } catch (TimeoutException e
) {
1715 if (returnOnTimeout
) return;
1717 } catch (InvalidVersionException e
) {
1718 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1722 if (envelope
.hasSource()) {
1723 // Store uuid if we don't have it already
1724 SignalServiceAddress source
= envelope
.getSourceAddress();
1725 resolveSignalServiceAddress(source
);
1727 if (!envelope
.isReceipt()) {
1729 content
= decryptMessage(envelope
);
1730 } catch (Exception e
) {
1733 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1734 if (hasCaughtUpWithOldMessages
) {
1735 for (HandleAction action
: actions
) {
1737 action
.execute(this);
1738 } catch (Throwable e
) {
1739 logger
.warn("Message action failed.", e
);
1743 if (queuedActions
== null) {
1744 queuedActions
= new HashSet
<>();
1746 queuedActions
.addAll(actions
);
1750 if (isMessageBlocked(envelope
, content
)) {
1751 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1752 } else if (isNotAGroupMember(envelope
, content
)) {
1753 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1755 handler
.handleMessage(envelope
, content
, exception
);
1757 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1758 if (cachedMessage
[0] != null) {
1759 cachedMessage
[0].delete();
1765 private boolean isMessageBlocked(
1766 SignalServiceEnvelope envelope
, SignalServiceContent content
1768 SignalServiceAddress source
;
1769 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1770 source
= envelope
.getSourceAddress();
1771 } else if (content
!= null) {
1772 source
= content
.getSender();
1776 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1777 if (sourceContact
!= null && sourceContact
.blocked
) {
1781 if (content
!= null && content
.getDataMessage().isPresent()) {
1782 SignalServiceDataMessage message
= content
.getDataMessage().get();
1783 if (message
.getGroupContext().isPresent()) {
1784 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1785 GroupInfo group
= getGroup(groupId
);
1786 if (group
!= null && group
.isBlocked()) {
1794 private boolean isNotAGroupMember(
1795 SignalServiceEnvelope envelope
, SignalServiceContent content
1797 SignalServiceAddress source
;
1798 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1799 source
= envelope
.getSourceAddress();
1800 } else if (content
!= null) {
1801 source
= content
.getSender();
1806 if (content
!= null && content
.getDataMessage().isPresent()) {
1807 SignalServiceDataMessage message
= content
.getDataMessage().get();
1808 if (message
.getGroupContext().isPresent()) {
1809 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1810 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1811 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1815 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1816 GroupInfo group
= getGroup(groupId
);
1817 if (group
!= null && !group
.isMember(source
)) {
1825 private List
<HandleAction
> handleMessage(
1826 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1828 List
<HandleAction
> actions
= new ArrayList
<>();
1829 if (content
!= null) {
1830 final SignalServiceAddress sender
;
1831 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1832 sender
= envelope
.getSourceAddress();
1834 sender
= content
.getSender();
1836 // Store uuid if we don't have it already
1837 resolveSignalServiceAddress(sender
);
1839 if (content
.getDataMessage().isPresent()) {
1840 SignalServiceDataMessage message
= content
.getDataMessage().get();
1842 if (content
.isNeedsReceipt()) {
1843 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1846 actions
.addAll(handleSignalServiceDataMessage(message
,
1849 account
.getSelfAddress(),
1850 ignoreAttachments
));
1852 if (content
.getSyncMessage().isPresent()) {
1853 account
.setMultiDevice(true);
1854 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1855 if (syncMessage
.getSent().isPresent()) {
1856 SentTranscriptMessage message
= syncMessage
.getSent().get();
1857 final SignalServiceAddress destination
= message
.getDestination().orNull();
1858 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1862 ignoreAttachments
));
1864 if (syncMessage
.getRequest().isPresent()) {
1865 RequestMessage rm
= syncMessage
.getRequest().get();
1866 if (rm
.isContactsRequest()) {
1867 actions
.add(SendSyncContactsAction
.create());
1869 if (rm
.isGroupsRequest()) {
1870 actions
.add(SendSyncGroupsAction
.create());
1872 if (rm
.isBlockedListRequest()) {
1873 actions
.add(SendSyncBlockedListAction
.create());
1875 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1877 if (syncMessage
.getGroups().isPresent()) {
1878 File tmpFile
= null;
1880 tmpFile
= IOUtils
.createTempFile();
1881 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1882 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1884 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1886 while ((g
= s
.read()) != null) {
1887 GroupInfoV1 syncGroup
= account
.getGroupStore()
1888 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1889 if (syncGroup
!= null) {
1890 if (g
.getName().isPresent()) {
1891 syncGroup
.name
= g
.getName().get();
1893 syncGroup
.addMembers(g
.getMembers()
1895 .map(this::resolveSignalServiceAddress
)
1896 .collect(Collectors
.toSet()));
1897 if (!g
.isActive()) {
1898 syncGroup
.removeMember(account
.getSelfAddress());
1900 // Add ourself to the member set as it's marked as active
1901 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1903 syncGroup
.blocked
= g
.isBlocked();
1904 if (g
.getColor().isPresent()) {
1905 syncGroup
.color
= g
.getColor().get();
1908 if (g
.getAvatar().isPresent()) {
1909 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1911 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1912 syncGroup
.archived
= g
.isArchived();
1913 account
.getGroupStore().updateGroup(syncGroup
);
1917 } catch (Exception e
) {
1918 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1922 if (tmpFile
!= null) {
1924 Files
.delete(tmpFile
.toPath());
1925 } catch (IOException e
) {
1926 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1933 if (syncMessage
.getBlockedList().isPresent()) {
1934 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1935 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1936 setContactBlocked(resolveSignalServiceAddress(address
), true);
1938 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1940 .map(GroupId
::unknownVersion
)
1941 .collect(Collectors
.toSet())) {
1943 setGroupBlocked(groupId
, true);
1944 } catch (GroupNotFoundException e
) {
1945 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1946 groupId
.toBase64());
1950 if (syncMessage
.getContacts().isPresent()) {
1951 File tmpFile
= null;
1953 tmpFile
= IOUtils
.createTempFile();
1954 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1955 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1956 .asPointer(), tmpFile
)) {
1957 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1958 if (contactsMessage
.isComplete()) {
1959 account
.getContactStore().clear();
1962 while ((c
= s
.read()) != null) {
1963 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1964 account
.setProfileKey(c
.getProfileKey().get());
1966 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1967 ContactInfo contact
= account
.getContactStore().getContact(address
);
1968 if (contact
== null) {
1969 contact
= new ContactInfo(address
);
1971 if (c
.getName().isPresent()) {
1972 contact
.name
= c
.getName().get();
1974 if (c
.getColor().isPresent()) {
1975 contact
.color
= c
.getColor().get();
1977 if (c
.getProfileKey().isPresent()) {
1978 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1980 if (c
.getVerified().isPresent()) {
1981 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1982 account
.getSignalProtocolStore()
1983 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1984 verifiedMessage
.getIdentityKey(),
1985 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1987 if (c
.getExpirationTimer().isPresent()) {
1988 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1990 contact
.blocked
= c
.isBlocked();
1991 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1992 contact
.archived
= c
.isArchived();
1993 account
.getContactStore().updateContact(contact
);
1995 if (c
.getAvatar().isPresent()) {
1996 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2000 } catch (Exception e
) {
2001 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2005 if (tmpFile
!= null) {
2007 Files
.delete(tmpFile
.toPath());
2008 } catch (IOException e
) {
2009 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2016 if (syncMessage
.getVerified().isPresent()) {
2017 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
2018 account
.getSignalProtocolStore()
2019 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2020 verifiedMessage
.getIdentityKey(),
2021 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2023 if (syncMessage
.getStickerPackOperations().isPresent()) {
2024 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
2026 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
2027 if (!m
.getPackId().isPresent()) {
2030 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2031 if (sticker
== null) {
2032 if (!m
.getPackKey().isPresent()) {
2035 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2037 sticker
.setInstalled(!m
.getType().isPresent()
2038 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2039 account
.getStickerStore().updateSticker(sticker
);
2042 if (syncMessage
.getFetchType().isPresent()) {
2043 switch (syncMessage
.getFetchType().get()) {
2045 getRecipientProfile(getSelfAddress(), true);
2046 case STORAGE_MANIFEST
:
2050 if (syncMessage
.getKeys().isPresent()) {
2051 final KeysMessage keysMessage
= syncMessage
.getKeys().get();
2052 if (keysMessage
.getStorageService().isPresent()) {
2053 final StorageKey storageKey
= keysMessage
.getStorageService().get();
2054 account
.setStorageKey(storageKey
);
2057 if (syncMessage
.getConfiguration().isPresent()) {
2065 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2067 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2068 } catch (IOException e
) {
2069 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2073 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2075 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2076 } catch (IOException e
) {
2077 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2081 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2083 avatarStore
.storeGroupAvatar(groupId
,
2084 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2085 } catch (IOException e
) {
2086 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2090 private void downloadProfileAvatar(
2091 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2094 avatarStore
.storeProfileAvatar(address
,
2095 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2096 } catch (Throwable e
) {
2097 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2101 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2102 return attachmentStore
.getAttachmentFile(attachmentId
);
2105 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2106 if (!attachment
.isPointer()) {
2107 logger
.warn("Invalid state, can't store an attachment stream.");
2110 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2111 if (pointer
.getPreview().isPresent()) {
2112 final byte[] preview
= pointer
.getPreview().get();
2114 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2115 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2116 } catch (IOException e
) {
2117 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2122 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2123 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2124 } catch (IOException e
) {
2125 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2129 private void retrieveGroupV2Avatar(
2130 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2131 ) throws IOException
{
2132 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2134 File tmpFile
= IOUtils
.createTempFile();
2135 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2137 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2138 byte[] encryptedData
= IOUtils
.readFully(input
);
2140 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2141 outputStream
.write(decryptedData
);
2144 Files
.delete(tmpFile
.toPath());
2145 } catch (IOException e
) {
2146 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2153 private void retrieveProfileAvatar(
2154 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2155 ) throws IOException
{
2156 File tmpFile
= IOUtils
.createTempFile();
2157 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2160 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2161 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2162 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2165 Files
.delete(tmpFile
.toPath());
2166 } catch (IOException e
) {
2167 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2174 private void retrieveAttachment(
2175 final SignalServiceAttachment attachment
, final OutputStream outputStream
2176 ) throws IOException
{
2177 if (attachment
.isPointer()) {
2178 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2179 retrieveAttachmentPointer(pointer
, outputStream
);
2181 SignalServiceAttachmentStream stream
= attachment
.asStream();
2182 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2186 private void retrieveAttachmentPointer(
2187 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2188 ) throws IOException
{
2189 File tmpFile
= IOUtils
.createTempFile();
2190 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2191 IOUtils
.copyStream(input
, outputStream
);
2192 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2193 throw new IOException(e
);
2196 Files
.delete(tmpFile
.toPath());
2197 } catch (IOException e
) {
2198 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2205 private InputStream
retrieveAttachmentAsStream(
2206 SignalServiceAttachmentPointer pointer
, File tmpFile
2207 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2208 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2211 void sendGroups() throws IOException
, UntrustedIdentityException
{
2212 File groupsFile
= IOUtils
.createTempFile();
2215 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2216 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2217 for (GroupInfo
record : getGroups()) {
2218 if (record instanceof GroupInfoV1
) {
2219 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2220 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2221 Optional
.fromNullable(groupInfo
.name
),
2222 new ArrayList
<>(groupInfo
.getMembers()),
2223 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2224 groupInfo
.isMember(account
.getSelfAddress()),
2225 Optional
.of(groupInfo
.messageExpirationTime
),
2226 Optional
.fromNullable(groupInfo
.color
),
2228 Optional
.fromNullable(groupInfo
.inboxPosition
),
2229 groupInfo
.archived
));
2234 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2235 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2236 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2237 .withStream(groupsFileStream
)
2238 .withContentType("application/octet-stream")
2239 .withLength(groupsFile
.length())
2242 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2247 Files
.delete(groupsFile
.toPath());
2248 } catch (IOException e
) {
2249 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2254 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2255 File contactsFile
= IOUtils
.createTempFile();
2258 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2259 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2260 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2261 VerifiedMessage verifiedMessage
= null;
2262 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2263 if (currentIdentity
!= null) {
2264 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2265 currentIdentity
.getIdentityKey(),
2266 currentIdentity
.getTrustLevel().toVerifiedState(),
2267 currentIdentity
.getDateAdded().getTime());
2270 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2271 out
.write(new DeviceContact(record.getAddress(),
2272 Optional
.fromNullable(record.name
),
2273 createContactAvatarAttachment(record.getAddress()),
2274 Optional
.fromNullable(record.color
),
2275 Optional
.fromNullable(verifiedMessage
),
2276 Optional
.fromNullable(profileKey
),
2278 Optional
.of(record.messageExpirationTime
),
2279 Optional
.fromNullable(record.inboxPosition
),
2283 if (account
.getProfileKey() != null) {
2284 // Send our own profile key as well
2285 out
.write(new DeviceContact(account
.getSelfAddress(),
2290 Optional
.of(account
.getProfileKey()),
2298 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2299 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2300 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2301 .withStream(contactsFileStream
)
2302 .withContentType("application/octet-stream")
2303 .withLength(contactsFile
.length())
2306 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2311 Files
.delete(contactsFile
.toPath());
2312 } catch (IOException e
) {
2313 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2318 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2319 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2320 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2321 if (record.blocked
) {
2322 addresses
.add(record.getAddress());
2325 List
<byte[]> groupIds
= new ArrayList
<>();
2326 for (GroupInfo
record : getGroups()) {
2327 if (record.isBlocked()) {
2328 groupIds
.add(record.getGroupId().serialize());
2331 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2334 private void sendVerifiedMessage(
2335 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2336 ) throws IOException
, UntrustedIdentityException
{
2337 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2339 trustLevel
.toVerifiedState(),
2340 System
.currentTimeMillis());
2341 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2344 public List
<ContactInfo
> getContacts() {
2345 return account
.getContactStore().getContacts();
2348 public String
getContactOrProfileName(String number
) {
2349 final SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2351 final ContactInfo contact
= account
.getContactStore().getContact(address
);
2352 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2353 return contact
.name
;
2356 final SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2357 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2358 return profileEntry
.getProfile().getName();
2364 public GroupInfo
getGroup(GroupId groupId
) {
2365 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2366 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2367 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2368 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2369 account
.getGroupStore().updateGroup(group
);
2374 public List
<IdentityInfo
> getIdentities() {
2375 return account
.getSignalProtocolStore().getIdentities();
2378 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2379 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2383 * Trust this the identity with this fingerprint
2385 * @param name username of the identity
2386 * @param fingerprint Fingerprint
2388 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2389 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2390 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2394 for (IdentityInfo id
: ids
) {
2395 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2399 account
.getSignalProtocolStore()
2400 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2402 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2403 } catch (IOException
| UntrustedIdentityException e
) {
2404 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2413 * Trust this the identity with this safety number
2415 * @param name username of the identity
2416 * @param safetyNumber Safety number
2418 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2419 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2420 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2424 for (IdentityInfo id
: ids
) {
2425 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2429 account
.getSignalProtocolStore()
2430 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2432 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2433 } catch (IOException
| UntrustedIdentityException e
) {
2434 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2443 * Trust all keys of this identity without verification
2445 * @param name username of the identity
2447 public boolean trustIdentityAllKeys(String name
) {
2448 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2449 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2453 for (IdentityInfo id
: ids
) {
2454 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2455 account
.getSignalProtocolStore()
2456 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2458 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2459 } catch (IOException
| UntrustedIdentityException e
) {
2460 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2468 public String
computeSafetyNumber(
2469 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2471 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2472 account
.getSelfAddress(),
2473 getIdentityKeyPair().getPublicKey(),
2478 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2479 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2481 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2482 return resolveSignalServiceAddress(canonicalizedNumber
);
2485 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2486 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2488 return resolveSignalServiceAddress(address
);
2491 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2492 if (address
.matches(account
.getSelfAddress())) {
2493 return account
.getSelfAddress();
2496 return account
.getRecipientStore().resolveServiceAddress(address
);
2500 public void close() throws IOException
{
2504 void close(boolean closeAccount
) throws IOException
{
2505 if (messagePipe
!= null) {
2506 messagePipe
.shutdown();
2510 if (unidentifiedMessagePipe
!= null) {
2511 unidentifiedMessagePipe
.shutdown();
2512 unidentifiedMessagePipe
= null;
2515 if (closeAccount
&& account
!= null) {
2521 public interface ReceiveMessageHandler
{
2523 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);