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
.config
.ServiceConfig
;
20 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
21 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
22 import org
.asamk
.signal
.manager
.groups
.GroupId
;
23 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
24 import org
.asamk
.signal
.manager
.groups
.GroupIdV2
;
25 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
26 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
27 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
28 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
29 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
30 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
31 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
32 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
33 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
34 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactInfo
;
35 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
36 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
37 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
38 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
39 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfile
;
40 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfileEntry
;
41 import org
.asamk
.signal
.manager
.storage
.protocol
.IdentityInfo
;
42 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
43 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
44 import org
.asamk
.signal
.manager
.util
.IOUtils
;
45 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
46 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
47 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
48 import org
.asamk
.signal
.manager
.util
.Utils
;
49 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
50 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
51 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
52 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
53 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
54 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
56 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
57 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
58 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
59 import org
.signal
.libsignal
.metadata
.SelfSendException
;
60 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
61 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
62 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
63 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroupJoinInfo
;
64 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedMember
;
65 import org
.signal
.zkgroup
.InvalidInputException
;
66 import org
.signal
.zkgroup
.VerificationFailedException
;
67 import org
.signal
.zkgroup
.auth
.AuthCredentialResponse
;
68 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
69 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
70 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
71 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
72 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
73 import org
.slf4j
.Logger
;
74 import org
.slf4j
.LoggerFactory
;
75 import org
.whispersystems
.libsignal
.IdentityKey
;
76 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
77 import org
.whispersystems
.libsignal
.InvalidKeyException
;
78 import org
.whispersystems
.libsignal
.InvalidMessageException
;
79 import org
.whispersystems
.libsignal
.InvalidVersionException
;
80 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
81 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
82 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
83 import org
.whispersystems
.libsignal
.util
.Pair
;
84 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
85 import org
.whispersystems
.signalservice
.api
.KeyBackupService
;
86 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
87 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
88 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
89 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
90 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
91 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
92 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
93 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
94 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
95 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
96 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
97 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
98 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
106 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
107 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
108 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
109 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
110 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceStickerManifestUpload
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.KeysMessage
;
121 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
122 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
123 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
124 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
125 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
126 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
127 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
128 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
129 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
130 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
131 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
132 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
133 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
134 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
135 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
136 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
137 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
138 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
139 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
140 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
141 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
142 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
143 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
144 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
146 import java
.io
.Closeable
;
148 import java
.io
.FileInputStream
;
149 import java
.io
.FileOutputStream
;
150 import java
.io
.IOException
;
151 import java
.io
.InputStream
;
152 import java
.io
.OutputStream
;
154 import java
.net
.URISyntaxException
;
155 import java
.net
.URLEncoder
;
156 import java
.nio
.charset
.StandardCharsets
;
157 import java
.nio
.file
.Files
;
158 import java
.security
.SignatureException
;
159 import java
.util
.ArrayList
;
160 import java
.util
.Arrays
;
161 import java
.util
.Collection
;
162 import java
.util
.Date
;
163 import java
.util
.HashMap
;
164 import java
.util
.HashSet
;
165 import java
.util
.List
;
166 import java
.util
.Map
;
167 import java
.util
.Set
;
168 import java
.util
.UUID
;
169 import java
.util
.concurrent
.ExecutorService
;
170 import java
.util
.concurrent
.TimeUnit
;
171 import java
.util
.concurrent
.TimeoutException
;
172 import java
.util
.stream
.Collectors
;
174 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
176 public class Manager
implements Closeable
{
178 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
180 private final CertificateValidator certificateValidator
;
182 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
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 ServiceEnvironmentConfig serviceEnvironmentConfig
,
208 this.account
= account
;
209 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
210 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
211 this.userAgent
= userAgent
;
212 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
213 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
214 final SleepTimer timer
= new UptimeSleepTimer();
215 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
216 new DynamicCredentialsProvider(account
.getUuid(),
217 account
.getUsername(),
218 account
.getPassword(),
219 account
.getSignalingKey(),
220 account
.getDeviceId()),
223 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
225 this.groupsV2Api
= accountManager
.getGroupsV2Api();
226 final KeyBackupService keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
227 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
228 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
229 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
232 this.pinHelper
= new PinHelper(keyBackupService
);
233 this.clientZkProfileOperations
= capabilities
.isGv2()
234 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
235 .getProfileOperations()
237 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
239 account
.getUsername(),
240 account
.getPassword(),
241 account
.getDeviceId(),
242 account
.getSignalingKey(),
246 clientZkProfileOperations
,
247 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
249 this.account
.setResolver(this::resolveSignalServiceAddress
);
251 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
252 account
.getProfileStore()::getProfileKey
,
253 this::getRecipientProfile
,
254 this::getSenderCertificate
);
255 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
256 unidentifiedAccessHelper
::getAccessFor
,
257 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
258 () -> messageReceiver
);
259 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
260 this::getRecipientProfile
,
261 account
::getSelfAddress
,
264 this::getGroupAuthForToday
);
265 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
266 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
269 public String
getUsername() {
270 return account
.getUsername();
273 public SignalServiceAddress
getSelfAddress() {
274 return account
.getSelfAddress();
277 private IdentityKeyPair
getIdentityKeyPair() {
278 return account
.getSignalProtocolStore().getIdentityKeyPair();
281 public int getDeviceId() {
282 return account
.getDeviceId();
285 public static Manager
init(
286 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
287 ) throws IOException
, NotRegisteredException
{
288 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
290 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
291 throw new NotRegisteredException();
294 SignalAccount account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
296 if (!account
.isRegistered()) {
297 throw new NotRegisteredException();
300 final ServiceEnvironmentConfig serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(
304 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
307 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
308 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
309 final File dataPath
= pathConfig
.getDataPath();
310 final File
[] files
= dataPath
.listFiles();
316 return Arrays
.stream(files
)
317 .filter(File
::isFile
)
319 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
320 .collect(Collectors
.toList());
323 public void checkAccountState() throws IOException
{
324 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
328 if (account
.getUuid() == null) {
329 account
.setUuid(accountManager
.getOwnUuid());
332 updateAccountAttributes();
336 * This is used for checking a set of phone numbers for registration on Signal
338 * @param numbers The set of phone number in question
339 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
340 * @throws IOException if its unable to get the contacts to check if they're registered
342 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
343 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
344 Map
<String
, UUID
> contactDetails
= getRegisteredUsers(numbers
);
346 Set
<String
> registeredUsers
= contactDetails
.keySet();
348 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
351 public void updateAccountAttributes() throws IOException
{
352 accountManager
.setAccountAttributes(account
.getSignalingKey(),
353 account
.getSignalProtocolStore().getLocalRegistrationId(),
355 // set legacy pin only if no KBS master key is set
356 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
357 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
358 account
.getSelfUnidentifiedAccessKey(),
359 account
.isUnrestrictedUnidentifiedAccess(),
361 account
.isDiscoverableByPhoneNumber());
365 * @param avatar if avatar is null the image from the local avatar store is used (if present),
366 * if it's Optional.absent(), the avatar will be removed
368 public void setProfile(String name
, Optional
<File
> avatar
) throws IOException
{
371 String aboutEmoji
= null;
373 try (final StreamDetails streamDetails
= avatar
== null
374 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
375 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
376 accountManager
.setVersionedProfile(account
.getUuid(),
377 account
.getProfileKey(),
384 if (avatar
!= null) {
385 if (avatar
.isPresent()) {
386 avatarStore
.storeProfileAvatar(getSelfAddress(),
387 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
389 avatarStore
.deleteProfileAvatar(getSelfAddress());
394 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
395 } catch (UntrustedIdentityException ignored
) {
399 public void unregister() throws IOException
{
400 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
401 // If this is the master device, other users can't send messages to this number anymore.
402 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
403 accountManager
.setGcmId(Optional
.absent());
404 accountManager
.deleteAccount();
406 account
.setRegistered(false);
410 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
411 List
<DeviceInfo
> devices
= accountManager
.getDevices();
412 account
.setMultiDevice(devices
.size() > 1);
417 public void removeLinkedDevices(int deviceId
) throws IOException
{
418 accountManager
.removeDevice(deviceId
);
419 List
<DeviceInfo
> devices
= accountManager
.getDevices();
420 account
.setMultiDevice(devices
.size() > 1);
424 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
425 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
427 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
430 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
431 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
432 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
434 accountManager
.addDevice(deviceIdentifier
,
437 Optional
.of(account
.getProfileKey().serialize()),
439 account
.setMultiDevice(true);
443 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
444 if (!account
.isMasterDevice()) {
445 throw new RuntimeException("Only master device can set a PIN");
447 if (pin
.isPresent()) {
448 final MasterKey masterKey
= account
.getPinMasterKey() != null
449 ? account
.getPinMasterKey()
450 : KeyUtils
.createMasterKey();
452 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
454 account
.setRegistrationLockPin(pin
.get());
455 account
.setPinMasterKey(masterKey
);
457 // Remove legacy registration lock
458 accountManager
.removeRegistrationLockV1();
461 pinHelper
.removeRegistrationLockPin();
463 account
.setRegistrationLockPin(null);
464 account
.setPinMasterKey(null);
469 void refreshPreKeys() throws IOException
{
470 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
471 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
472 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
474 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
477 private List
<PreKeyRecord
> generatePreKeys() {
478 final int offset
= account
.getPreKeyIdOffset();
480 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
481 account
.addPreKeys(records
);
487 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
488 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
490 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
491 account
.addSignedPreKey(record);
497 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
498 if (messagePipe
== null) {
499 messagePipe
= messageReceiver
.createMessagePipe();
504 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
505 if (unidentifiedMessagePipe
== null) {
506 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
508 return unidentifiedMessagePipe
;
511 private SignalServiceMessageSender
createMessageSender() {
512 final ExecutorService executor
= null;
513 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
515 account
.getUsername(),
516 account
.getPassword(),
517 account
.getDeviceId(),
518 account
.getSignalProtocolStore(),
520 account
.isMultiDevice(),
521 Optional
.fromNullable(messagePipe
),
522 Optional
.fromNullable(unidentifiedMessagePipe
),
524 clientZkProfileOperations
,
526 ServiceConfig
.MAX_ENVELOPE_SIZE
,
527 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
530 private SignalProfile
getRecipientProfile(
531 SignalServiceAddress address
533 return getRecipientProfile(address
, false);
536 private SignalProfile
getRecipientProfile(
537 SignalServiceAddress address
, boolean force
539 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
540 if (profileEntry
== null) {
543 long now
= new Date().getTime();
544 // Profiles are cached for 24h before retrieving them again
545 if (!profileEntry
.isRequestPending() && (
547 || profileEntry
.getProfile() == null
548 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
550 profileEntry
.setRequestPending(true);
551 final SignalServiceProfile encryptedProfile
;
553 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
555 } catch (IOException e
) {
556 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
559 profileEntry
.setRequestPending(false);
562 final ProfileKey profileKey
= profileEntry
.getProfileKey();
563 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
564 account
.getProfileStore()
565 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
568 return profileEntry
.getProfile();
571 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
572 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
573 if (profileEntry
== null) {
576 if (profileEntry
.getProfileKeyCredential() == null) {
577 ProfileAndCredential profileAndCredential
;
579 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
580 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
581 } catch (IOException e
) {
582 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
586 long now
= new Date().getTime();
587 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
588 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
589 profileEntry
.getProfileKey(),
590 profileAndCredential
.getProfile());
591 account
.getProfileStore()
592 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
593 return profileKeyCredential
;
595 return profileEntry
.getProfileKeyCredential();
598 private SignalProfile
decryptProfileAndDownloadAvatar(
599 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
601 if (encryptedProfile
.getAvatar() != null) {
602 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
605 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
608 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
609 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
610 if (streamDetails
== null) {
611 return Optional
.absent();
614 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
617 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
618 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
619 if (streamDetails
== null) {
620 return Optional
.absent();
623 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
626 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
627 GroupInfo g
= getGroup(groupId
);
629 throw new GroupNotFoundException(groupId
);
631 if (!g
.isMember(account
.getSelfAddress())) {
632 throw new NotAGroupMemberException(groupId
, g
.getTitle());
637 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
638 GroupInfo g
= getGroup(groupId
);
640 throw new GroupNotFoundException(groupId
);
642 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
643 throw new NotAGroupMemberException(groupId
, g
.getTitle());
648 public List
<GroupInfo
> getGroups() {
649 return account
.getGroupStore().getGroups();
652 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
653 String messageText
, List
<String
> attachments
, GroupId groupId
654 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
655 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
656 .withBody(messageText
);
657 if (attachments
!= null) {
658 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
661 return sendGroupMessage(messageBuilder
, groupId
);
664 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
665 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
666 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
667 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
669 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
670 targetSentTimestamp
);
671 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
672 .withReaction(reaction
);
674 return sendGroupMessage(messageBuilder
, groupId
);
677 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
678 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
679 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
680 final GroupInfo g
= getGroupForSending(groupId
);
682 GroupUtils
.setGroupContext(messageBuilder
, g
);
683 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
685 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
688 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
689 SignalServiceDataMessage
.Builder messageBuilder
;
691 final GroupInfo g
= getGroupForUpdating(groupId
);
692 if (g
instanceof GroupInfoV1
) {
693 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
694 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
695 .withId(groupId
.serialize())
697 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
698 groupInfoV1
.removeMember(account
.getSelfAddress());
699 account
.getGroupStore().updateGroup(groupInfoV1
);
701 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
702 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
703 groupInfoV2
.setGroup(groupGroupChangePair
.first());
704 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
705 account
.getGroupStore().updateGroup(groupInfoV2
);
708 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
711 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
712 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
713 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
714 return sendUpdateGroupMessage(groupId
,
716 members
== null ?
null : getSignalServiceAddresses(members
),
720 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
721 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
722 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
724 SignalServiceDataMessage
.Builder messageBuilder
;
725 if (groupId
== null) {
727 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
728 members
== null ? List
.of() : members
,
731 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
732 gv1
.addMembers(List
.of(account
.getSelfAddress()));
733 updateGroupV1(gv1
, name
, members
, avatarFile
);
734 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
737 if (avatarFile
!= null) {
738 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
739 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
741 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
745 GroupInfo group
= getGroupForUpdating(groupId
);
746 if (group
instanceof GroupInfoV2
) {
747 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
749 Pair
<Long
, List
<SendMessageResult
>> result
= null;
750 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
751 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
752 result
= sendUpdateGroupMessage(groupInfoV2
,
753 groupGroupChangePair
.first(),
754 groupGroupChangePair
.second());
757 if (members
!= null) {
758 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
759 newMembers
.removeAll(group
.getMembers()
761 .map(this::resolveSignalServiceAddress
)
762 .collect(Collectors
.toSet()));
763 if (newMembers
.size() > 0) {
764 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
766 result
= sendUpdateGroupMessage(groupInfoV2
,
767 groupGroupChangePair
.first(),
768 groupGroupChangePair
.second());
771 if (result
== null || name
!= null || avatarFile
!= null) {
772 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
775 if (avatarFile
!= null) {
776 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
777 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
779 result
= sendUpdateGroupMessage(groupInfoV2
,
780 groupGroupChangePair
.first(),
781 groupGroupChangePair
.second());
784 return new Pair
<>(group
.getGroupId(), result
.second());
786 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
787 updateGroupV1(gv1
, name
, members
, avatarFile
);
788 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
793 account
.getGroupStore().updateGroup(g
);
795 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
796 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
797 return new Pair
<>(g
.getGroupId(), result
.second());
800 private void updateGroupV1(
803 final Collection
<SignalServiceAddress
> members
,
804 final File avatarFile
805 ) throws IOException
{
810 if (members
!= null) {
811 final Set
<String
> newE164Members
= new HashSet
<>();
812 for (SignalServiceAddress member
: members
) {
813 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
816 newE164Members
.add(member
.getNumber().get());
819 final Map
<String
, UUID
> registeredUsers
= getRegisteredUsers(newE164Members
);
820 if (registeredUsers
.size() != newE164Members
.size()) {
821 // Some of the new members are not registered on Signal
822 newE164Members
.removeAll(registeredUsers
.keySet());
823 throw new IOException("Failed to add members "
824 + String
.join(", ", newE164Members
)
825 + " to group: Not registered on Signal");
828 g
.addMembers(members
);
831 if (avatarFile
!= null) {
832 avatarStore
.storeGroupAvatar(g
.getGroupId(),
833 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
837 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
838 GroupInviteLinkUrl inviteLinkUrl
839 ) throws IOException
, GroupLinkNotActiveException
{
840 return sendJoinGroupMessage(inviteLinkUrl
);
843 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
844 GroupInviteLinkUrl inviteLinkUrl
845 ) throws IOException
, GroupLinkNotActiveException
{
846 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
847 inviteLinkUrl
.getPassword());
848 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
849 inviteLinkUrl
.getPassword(),
851 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
852 groupJoinInfo
.getRevision() + 1,
853 groupChange
.toByteArray());
855 if (group
.getGroup() == null) {
856 // Only requested member, can't send update to group members
857 return new Pair
<>(group
.getGroupId(), List
.of());
860 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
862 return new Pair
<>(group
.getGroupId(), result
.second());
865 private static int currentTimeDays() {
866 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
869 private GroupsV2AuthorizationString
getGroupAuthForToday(
870 final GroupSecretParams groupSecretParams
871 ) throws IOException
{
872 final int today
= currentTimeDays();
873 // Returns credentials for the next 7 days
874 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
875 // TODO cache credentials until they expire
876 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
878 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
881 authCredentialResponse
);
882 } catch (VerificationFailedException e
) {
883 throw new IOException(e
);
887 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
888 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
889 ) throws IOException
{
890 group
.setGroup(newDecryptedGroup
);
891 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
892 groupChange
.toByteArray());
893 account
.getGroupStore().updateGroup(group
);
894 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
897 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
898 GroupIdV1 groupId
, SignalServiceAddress recipient
899 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
901 GroupInfo group
= getGroupForSending(groupId
);
902 if (!(group
instanceof GroupInfoV1
)) {
903 throw new RuntimeException("Received an invalid group request for a v2 group!");
905 g
= (GroupInfoV1
) group
;
907 if (!g
.isMember(recipient
)) {
908 throw new NotAGroupMemberException(groupId
, g
.name
);
911 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
913 // Send group message only to the recipient who requested it
914 return sendMessage(messageBuilder
, List
.of(recipient
));
917 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
918 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
919 .withId(g
.getGroupId().serialize())
921 .withMembers(new ArrayList
<>(g
.getMembers()));
924 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
925 if (attachment
.isPresent()) {
926 group
.withAvatar(attachment
.get());
928 } catch (IOException e
) {
929 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
932 return SignalServiceDataMessage
.newBuilder()
933 .asGroupMessage(group
.build())
934 .withExpiration(g
.getMessageExpirationTime());
937 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
938 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
939 .withRevision(g
.getGroup().getRevision())
940 .withSignedGroupChange(signedGroupChange
);
941 return SignalServiceDataMessage
.newBuilder()
942 .asGroupMessage(group
.build())
943 .withExpiration(g
.getMessageExpirationTime());
946 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
947 GroupIdV1 groupId
, SignalServiceAddress recipient
948 ) throws IOException
{
949 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
950 .withId(groupId
.serialize());
952 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
953 .asGroupMessage(group
.build());
955 // Send group info request message to the recipient who sent us a message with this groupId
956 return sendMessage(messageBuilder
, List
.of(recipient
));
960 SignalServiceAddress remoteAddress
, long messageId
961 ) throws IOException
, UntrustedIdentityException
{
962 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
964 System
.currentTimeMillis());
966 createMessageSender().sendReceipt(remoteAddress
,
967 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
971 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
972 String messageText
, List
<String
> attachments
, List
<String
> recipients
973 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
974 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
975 .withBody(messageText
);
976 if (attachments
!= null) {
977 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
979 // Upload attachments here, so we only upload once even for multiple recipients
980 SignalServiceMessageSender messageSender
= createMessageSender();
981 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
982 for (SignalServiceAttachment attachment
: attachmentStreams
) {
983 if (attachment
.isStream()) {
984 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
985 } else if (attachment
.isPointer()) {
986 attachmentPointers
.add(attachment
.asPointer());
990 messageBuilder
.withAttachments(attachmentPointers
);
992 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
995 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
996 String messageText
, List
<String
> attachments
997 ) throws IOException
, AttachmentInvalidException
{
998 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
999 .withBody(messageText
);
1000 if (attachments
!= null) {
1001 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1003 return sendSelfMessage(messageBuilder
);
1006 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1007 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1008 ) throws IOException
, InvalidNumberException
{
1009 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1011 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1012 targetSentTimestamp
);
1013 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1014 .withReaction(reaction
);
1015 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1018 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1019 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1021 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1023 return sendMessage(messageBuilder
, signalServiceAddresses
);
1024 } catch (Exception e
) {
1025 for (SignalServiceAddress address
: signalServiceAddresses
) {
1026 handleEndSession(address
);
1033 public String
getContactName(String number
) throws InvalidNumberException
{
1034 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1035 if (contact
== null) {
1038 return contact
.name
;
1042 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1043 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1044 ContactInfo contact
= account
.getContactStore().getContact(address
);
1045 if (contact
== null) {
1046 contact
= new ContactInfo(address
);
1048 contact
.name
= name
;
1049 account
.getContactStore().updateContact(contact
);
1053 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1054 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1057 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1058 ContactInfo contact
= account
.getContactStore().getContact(address
);
1059 if (contact
== null) {
1060 contact
= new ContactInfo(address
);
1062 contact
.blocked
= blocked
;
1063 account
.getContactStore().updateContact(contact
);
1067 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1068 GroupInfo group
= getGroup(groupId
);
1069 if (group
== null) {
1070 throw new GroupNotFoundException(groupId
);
1073 group
.setBlocked(blocked
);
1074 account
.getGroupStore().updateGroup(group
);
1079 * Change the expiration timer for a contact
1081 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1082 ContactInfo contact
= account
.getContactStore().getContact(address
);
1083 contact
.messageExpirationTime
= messageExpirationTimer
;
1084 account
.getContactStore().updateContact(contact
);
1085 sendExpirationTimerUpdate(address
);
1089 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1090 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1091 .asExpirationUpdate();
1092 sendMessage(messageBuilder
, List
.of(address
));
1096 * Change the expiration timer for a contact
1098 public void setExpirationTimer(
1099 String number
, int messageExpirationTimer
1100 ) throws IOException
, InvalidNumberException
{
1101 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1102 setExpirationTimer(address
, messageExpirationTimer
);
1106 * Change the expiration timer for a group
1108 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1109 GroupInfo g
= getGroup(groupId
);
1110 if (g
instanceof GroupInfoV1
) {
1111 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1112 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1113 account
.getGroupStore().updateGroup(groupInfoV1
);
1115 throw new RuntimeException("TODO Not implemented!");
1120 * Upload the sticker pack from path.
1122 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1123 * @return if successful, returns the URL to install the sticker pack in the signal app
1125 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1126 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1128 SignalServiceMessageSender messageSender
= createMessageSender();
1130 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1131 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1133 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1134 account
.getStickerStore().updateSticker(sticker
);
1138 return new URI("https",
1141 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1142 Hex
.toStringCondensed(packKey
),
1143 StandardCharsets
.UTF_8
)).toString();
1144 } catch (URISyntaxException e
) {
1145 throw new AssertionError(e
);
1149 void requestSyncGroups() throws IOException
{
1150 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1151 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1153 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1155 sendSyncMessage(message
);
1156 } catch (UntrustedIdentityException e
) {
1157 throw new AssertionError(e
);
1161 void requestSyncContacts() throws IOException
{
1162 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1163 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1165 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1167 sendSyncMessage(message
);
1168 } catch (UntrustedIdentityException e
) {
1169 throw new AssertionError(e
);
1173 void requestSyncBlocked() throws IOException
{
1174 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1175 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1177 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1179 sendSyncMessage(message
);
1180 } catch (UntrustedIdentityException e
) {
1181 throw new AssertionError(e
);
1185 void requestSyncConfiguration() throws IOException
{
1186 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1187 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1189 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1191 sendSyncMessage(message
);
1192 } catch (UntrustedIdentityException e
) {
1193 throw new AssertionError(e
);
1197 void requestSyncKeys() throws IOException
{
1198 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1199 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1201 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1203 sendSyncMessage(message
);
1204 } catch (UntrustedIdentityException e
) {
1205 throw new AssertionError(e
);
1209 private byte[] getSenderCertificate() {
1210 // TODO support UUID capable sender certificates
1211 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1214 certificate
= accountManager
.getSenderCertificate();
1215 } catch (IOException e
) {
1216 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1219 // TODO cache for a day
1223 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1224 SignalServiceMessageSender messageSender
= createMessageSender();
1226 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1227 } catch (UntrustedIdentityException e
) {
1228 account
.getSignalProtocolStore()
1229 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1231 TrustLevel
.UNTRUSTED
);
1236 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1237 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1238 final Set
<SignalServiceAddress
> addressesMissingUuid
= new HashSet
<>();
1240 for (String number
: numbers
) {
1241 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1242 if (resolvedAddress
.getUuid().isPresent()) {
1243 signalServiceAddresses
.add(resolvedAddress
);
1245 addressesMissingUuid
.add(resolvedAddress
);
1249 final Set
<String
> numbersMissingUuid
= addressesMissingUuid
.stream()
1250 .map(a
-> a
.getNumber().get())
1251 .collect(Collectors
.toSet());
1252 Map
<String
, UUID
> registeredUsers
;
1254 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1255 } catch (IOException e
) {
1256 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1257 registeredUsers
= Map
.of();
1260 for (SignalServiceAddress address
: addressesMissingUuid
) {
1261 final String number
= address
.getNumber().get();
1262 if (registeredUsers
.containsKey(number
)) {
1263 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1264 registeredUsers
.get(number
),
1266 signalServiceAddresses
.add(newAddress
);
1268 signalServiceAddresses
.add(address
);
1272 return signalServiceAddresses
;
1275 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1277 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1279 serviceEnvironmentConfig
.getCdsMrenclave());
1280 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1281 throw new IOException(e
);
1285 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1286 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1287 ) throws IOException
{
1288 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1289 final long timestamp
= System
.currentTimeMillis();
1290 messageBuilder
.withTimestamp(timestamp
);
1291 getOrCreateMessagePipe();
1292 getOrCreateUnidentifiedMessagePipe();
1293 SignalServiceDataMessage message
= null;
1295 message
= messageBuilder
.build();
1296 if (message
.getGroupContext().isPresent()) {
1298 SignalServiceMessageSender messageSender
= createMessageSender();
1299 final boolean isRecipientUpdate
= false;
1300 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1301 unidentifiedAccessHelper
.getAccessFor(recipients
),
1304 for (SendMessageResult r
: result
) {
1305 if (r
.getIdentityFailure() != null) {
1306 account
.getSignalProtocolStore()
1307 .saveIdentity(r
.getAddress(),
1308 r
.getIdentityFailure().getIdentityKey(),
1309 TrustLevel
.UNTRUSTED
);
1312 return new Pair
<>(timestamp
, result
);
1313 } catch (UntrustedIdentityException e
) {
1314 account
.getSignalProtocolStore()
1315 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1317 TrustLevel
.UNTRUSTED
);
1318 return new Pair
<>(timestamp
, List
.of());
1321 // Send to all individually, so sync messages are sent correctly
1322 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1323 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1324 for (SignalServiceAddress address
: recipients
) {
1325 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1326 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1327 messageBuilder
.withExpiration(expirationTime
);
1328 message
= messageBuilder
.build();
1329 results
.add(sendMessage(address
, message
));
1331 return new Pair
<>(timestamp
, results
);
1334 if (message
!= null && message
.isEndSession()) {
1335 for (SignalServiceAddress recipient
: recipients
) {
1336 handleEndSession(recipient
);
1343 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1344 SignalServiceDataMessage
.Builder messageBuilder
1345 ) throws IOException
{
1346 final long timestamp
= System
.currentTimeMillis();
1347 messageBuilder
.withTimestamp(timestamp
);
1348 getOrCreateMessagePipe();
1349 getOrCreateUnidentifiedMessagePipe();
1351 final SignalServiceAddress address
= getSelfAddress();
1353 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1354 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1355 messageBuilder
.withExpiration(expirationTime
);
1357 SignalServiceDataMessage message
= messageBuilder
.build();
1358 final SendMessageResult result
= sendSelfMessage(message
);
1359 return new Pair
<>(timestamp
, result
);
1365 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1366 SignalServiceMessageSender messageSender
= createMessageSender();
1368 SignalServiceAddress recipient
= account
.getSelfAddress();
1370 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1371 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1372 message
.getTimestamp(),
1374 message
.getExpiresInSeconds(),
1375 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1377 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1380 long startTime
= System
.currentTimeMillis();
1381 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1382 return SendMessageResult
.success(recipient
,
1383 unidentifiedAccess
.isPresent(),
1385 System
.currentTimeMillis() - startTime
);
1386 } catch (UntrustedIdentityException e
) {
1387 account
.getSignalProtocolStore()
1388 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1390 TrustLevel
.UNTRUSTED
);
1391 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1395 private SendMessageResult
sendMessage(
1396 SignalServiceAddress address
, SignalServiceDataMessage message
1397 ) throws IOException
{
1398 SignalServiceMessageSender messageSender
= createMessageSender();
1401 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1402 } catch (UntrustedIdentityException e
) {
1403 account
.getSignalProtocolStore()
1404 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1406 TrustLevel
.UNTRUSTED
);
1407 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1411 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1412 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1413 account
.getSignalProtocolStore(),
1414 certificateValidator
);
1416 return cipher
.decrypt(envelope
);
1417 } catch (ProtocolUntrustedIdentityException e
) {
1418 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1419 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1421 final IdentityKey untrustedIdentity
= identityException
.getUntrustedIdentity();
1422 if (untrustedIdentity
!= null) {
1423 account
.getSignalProtocolStore()
1424 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1426 TrustLevel
.UNTRUSTED
);
1428 throw identityException
;
1430 throw new AssertionError(e
);
1434 private void handleEndSession(SignalServiceAddress source
) {
1435 account
.getSignalProtocolStore().deleteAllSessions(source
);
1438 private List
<HandleAction
> handleSignalServiceDataMessage(
1439 SignalServiceDataMessage message
,
1441 SignalServiceAddress source
,
1442 SignalServiceAddress destination
,
1443 boolean ignoreAttachments
1445 List
<HandleAction
> actions
= new ArrayList
<>();
1446 if (message
.getGroupContext().isPresent()) {
1447 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1448 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1449 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1450 GroupInfo group
= getGroup(groupId
);
1451 if (group
== null || group
instanceof GroupInfoV1
) {
1452 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1453 switch (groupInfo
.getType()) {
1455 if (groupV1
== null) {
1456 groupV1
= new GroupInfoV1(groupId
);
1459 if (groupInfo
.getAvatar().isPresent()) {
1460 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1461 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1464 if (groupInfo
.getName().isPresent()) {
1465 groupV1
.name
= groupInfo
.getName().get();
1468 if (groupInfo
.getMembers().isPresent()) {
1469 groupV1
.addMembers(groupInfo
.getMembers()
1472 .map(this::resolveSignalServiceAddress
)
1473 .collect(Collectors
.toSet()));
1476 account
.getGroupStore().updateGroup(groupV1
);
1480 if (groupV1
== null && !isSync
) {
1481 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1485 if (groupV1
!= null) {
1486 groupV1
.removeMember(source
);
1487 account
.getGroupStore().updateGroup(groupV1
);
1492 if (groupV1
!= null && !isSync
) {
1493 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1498 // Received a group v1 message for a v2 group
1501 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1502 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1503 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1505 getOrMigrateGroup(groupMasterKey
,
1506 groupContext
.getRevision(),
1507 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1511 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1512 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1513 handleEndSession(conversationPartnerAddress
);
1515 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1516 if (message
.getGroupContext().isPresent()) {
1517 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1518 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1519 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1520 if (group
!= null) {
1521 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1522 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1523 account
.getGroupStore().updateGroup(group
);
1526 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1527 // disappearing message timer already stored in the DecryptedGroup
1529 } else if (conversationPartnerAddress
!= null) {
1530 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1531 if (contact
== null) {
1532 contact
= new ContactInfo(conversationPartnerAddress
);
1534 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1535 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1536 account
.getContactStore().updateContact(contact
);
1540 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1541 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1542 downloadAttachment(attachment
);
1545 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1546 final ProfileKey profileKey
;
1548 profileKey
= new ProfileKey(message
.getProfileKey().get());
1549 } catch (InvalidInputException e
) {
1550 throw new AssertionError(e
);
1552 if (source
.matches(account
.getSelfAddress())) {
1553 this.account
.setProfileKey(profileKey
);
1555 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1557 if (message
.getPreviews().isPresent()) {
1558 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1559 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1560 if (preview
.getImage().isPresent()) {
1561 downloadAttachment(preview
.getImage().get());
1565 if (message
.getQuote().isPresent()) {
1566 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1568 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1569 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1570 if (thumbnail
!= null) {
1571 downloadAttachment(thumbnail
);
1575 if (message
.getSticker().isPresent()) {
1576 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1577 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1578 if (sticker
== null) {
1579 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1580 account
.getStickerStore().updateSticker(sticker
);
1586 private GroupInfoV2
getOrMigrateGroup(
1587 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1589 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1591 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1592 GroupInfo groupInfo
= getGroup(groupId
);
1593 final GroupInfoV2 groupInfoV2
;
1594 if (groupInfo
instanceof GroupInfoV1
) {
1595 // Received a v2 group message for a v1 group, we need to locally migrate the group
1596 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1597 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1598 logger
.info("Locally migrated group {} to group v2, id: {}",
1599 groupInfo
.getGroupId().toBase64(),
1600 groupInfoV2
.getGroupId().toBase64());
1601 } else if (groupInfo
instanceof GroupInfoV2
) {
1602 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1604 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1607 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1608 DecryptedGroup group
= null;
1609 if (signedGroupChange
!= null
1610 && groupInfoV2
.getGroup() != null
1611 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1612 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1614 if (group
== null) {
1615 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1617 if (group
!= null) {
1618 storeProfileKeysFromMembers(group
);
1619 final String avatar
= group
.getAvatar();
1620 if (avatar
!= null && !avatar
.isEmpty()) {
1621 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1624 groupInfoV2
.setGroup(group
);
1625 account
.getGroupStore().updateGroup(groupInfoV2
);
1631 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1632 for (DecryptedMember member
: group
.getMembersList()) {
1633 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1634 member
.getUuid().toByteArray()), null));
1636 account
.getProfileStore()
1637 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1638 } catch (InvalidInputException ignored
) {
1643 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1644 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1645 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1649 private void retryFailedReceivedMessage(
1650 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1652 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1653 if (envelope
== null) {
1656 SignalServiceContent content
= null;
1657 if (!envelope
.isReceipt()) {
1659 content
= decryptMessage(envelope
);
1660 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1662 } catch (Exception er
) {
1663 // All other errors are not recoverable, so delete the cached message
1664 cachedMessage
.delete();
1667 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1668 for (HandleAction action
: actions
) {
1670 action
.execute(this);
1671 } catch (Throwable e
) {
1672 logger
.warn("Message action failed.", e
);
1677 handler
.handleMessage(envelope
, content
, null);
1678 cachedMessage
.delete();
1681 public void receiveMessages(
1684 boolean returnOnTimeout
,
1685 boolean ignoreAttachments
,
1686 ReceiveMessageHandler handler
1687 ) throws IOException
{
1688 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1690 Set
<HandleAction
> queuedActions
= null;
1692 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1694 boolean hasCaughtUpWithOldMessages
= false;
1697 SignalServiceEnvelope envelope
;
1698 SignalServiceContent content
= null;
1699 Exception exception
= null;
1700 final CachedMessage
[] cachedMessage
= {null};
1702 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1703 // store message on disk, before acknowledging receipt to the server
1704 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1706 if (result
.isPresent()) {
1707 envelope
= result
.get();
1709 // Received indicator that server queue is empty
1710 hasCaughtUpWithOldMessages
= true;
1712 if (queuedActions
!= null) {
1713 for (HandleAction action
: queuedActions
) {
1715 action
.execute(this);
1716 } catch (Throwable e
) {
1717 logger
.warn("Message action failed.", e
);
1721 queuedActions
.clear();
1722 queuedActions
= null;
1725 // Continue to wait another timeout for new messages
1728 } catch (TimeoutException e
) {
1729 if (returnOnTimeout
) return;
1731 } catch (InvalidVersionException e
) {
1732 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1736 if (envelope
.hasSource()) {
1737 // Store uuid if we don't have it already
1738 SignalServiceAddress source
= envelope
.getSourceAddress();
1739 resolveSignalServiceAddress(source
);
1741 if (!envelope
.isReceipt()) {
1743 content
= decryptMessage(envelope
);
1744 } catch (Exception e
) {
1747 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1748 if (hasCaughtUpWithOldMessages
) {
1749 for (HandleAction action
: actions
) {
1751 action
.execute(this);
1752 } catch (Throwable e
) {
1753 logger
.warn("Message action failed.", e
);
1757 if (queuedActions
== null) {
1758 queuedActions
= new HashSet
<>();
1760 queuedActions
.addAll(actions
);
1764 if (isMessageBlocked(envelope
, content
)) {
1765 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1766 } else if (isNotAGroupMember(envelope
, content
)) {
1767 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1769 handler
.handleMessage(envelope
, content
, exception
);
1771 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1772 if (cachedMessage
[0] != null) {
1773 cachedMessage
[0].delete();
1779 private boolean isMessageBlocked(
1780 SignalServiceEnvelope envelope
, SignalServiceContent content
1782 SignalServiceAddress source
;
1783 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1784 source
= envelope
.getSourceAddress();
1785 } else if (content
!= null) {
1786 source
= content
.getSender();
1790 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1791 if (sourceContact
!= null && sourceContact
.blocked
) {
1795 if (content
!= null && content
.getDataMessage().isPresent()) {
1796 SignalServiceDataMessage message
= content
.getDataMessage().get();
1797 if (message
.getGroupContext().isPresent()) {
1798 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1799 GroupInfo group
= getGroup(groupId
);
1800 if (group
!= null && group
.isBlocked()) {
1808 private boolean isNotAGroupMember(
1809 SignalServiceEnvelope envelope
, SignalServiceContent content
1811 SignalServiceAddress source
;
1812 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1813 source
= envelope
.getSourceAddress();
1814 } else if (content
!= null) {
1815 source
= content
.getSender();
1820 if (content
!= null && content
.getDataMessage().isPresent()) {
1821 SignalServiceDataMessage message
= content
.getDataMessage().get();
1822 if (message
.getGroupContext().isPresent()) {
1823 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1824 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1825 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1829 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1830 GroupInfo group
= getGroup(groupId
);
1831 if (group
!= null && !group
.isMember(source
)) {
1839 private List
<HandleAction
> handleMessage(
1840 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1842 List
<HandleAction
> actions
= new ArrayList
<>();
1843 if (content
!= null) {
1844 final SignalServiceAddress sender
;
1845 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1846 sender
= envelope
.getSourceAddress();
1848 sender
= content
.getSender();
1850 // Store uuid if we don't have it already
1851 resolveSignalServiceAddress(sender
);
1853 if (content
.getDataMessage().isPresent()) {
1854 SignalServiceDataMessage message
= content
.getDataMessage().get();
1856 if (content
.isNeedsReceipt()) {
1857 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1860 actions
.addAll(handleSignalServiceDataMessage(message
,
1863 account
.getSelfAddress(),
1864 ignoreAttachments
));
1866 if (content
.getSyncMessage().isPresent()) {
1867 account
.setMultiDevice(true);
1868 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1869 if (syncMessage
.getSent().isPresent()) {
1870 SentTranscriptMessage message
= syncMessage
.getSent().get();
1871 final SignalServiceAddress destination
= message
.getDestination().orNull();
1872 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1876 ignoreAttachments
));
1878 if (syncMessage
.getRequest().isPresent()) {
1879 RequestMessage rm
= syncMessage
.getRequest().get();
1880 if (rm
.isContactsRequest()) {
1881 actions
.add(SendSyncContactsAction
.create());
1883 if (rm
.isGroupsRequest()) {
1884 actions
.add(SendSyncGroupsAction
.create());
1886 if (rm
.isBlockedListRequest()) {
1887 actions
.add(SendSyncBlockedListAction
.create());
1889 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1891 if (syncMessage
.getGroups().isPresent()) {
1892 File tmpFile
= null;
1894 tmpFile
= IOUtils
.createTempFile();
1895 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1896 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1898 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1900 while ((g
= s
.read()) != null) {
1901 GroupInfoV1 syncGroup
= account
.getGroupStore()
1902 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1903 if (syncGroup
!= null) {
1904 if (g
.getName().isPresent()) {
1905 syncGroup
.name
= g
.getName().get();
1907 syncGroup
.addMembers(g
.getMembers()
1909 .map(this::resolveSignalServiceAddress
)
1910 .collect(Collectors
.toSet()));
1911 if (!g
.isActive()) {
1912 syncGroup
.removeMember(account
.getSelfAddress());
1914 // Add ourself to the member set as it's marked as active
1915 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1917 syncGroup
.blocked
= g
.isBlocked();
1918 if (g
.getColor().isPresent()) {
1919 syncGroup
.color
= g
.getColor().get();
1922 if (g
.getAvatar().isPresent()) {
1923 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1925 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1926 syncGroup
.archived
= g
.isArchived();
1927 account
.getGroupStore().updateGroup(syncGroup
);
1931 } catch (Exception e
) {
1932 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1936 if (tmpFile
!= null) {
1938 Files
.delete(tmpFile
.toPath());
1939 } catch (IOException e
) {
1940 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1947 if (syncMessage
.getBlockedList().isPresent()) {
1948 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1949 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1950 setContactBlocked(resolveSignalServiceAddress(address
), true);
1952 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1954 .map(GroupId
::unknownVersion
)
1955 .collect(Collectors
.toSet())) {
1957 setGroupBlocked(groupId
, true);
1958 } catch (GroupNotFoundException e
) {
1959 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1960 groupId
.toBase64());
1964 if (syncMessage
.getContacts().isPresent()) {
1965 File tmpFile
= null;
1967 tmpFile
= IOUtils
.createTempFile();
1968 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1969 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1970 .asPointer(), tmpFile
)) {
1971 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1972 if (contactsMessage
.isComplete()) {
1973 account
.getContactStore().clear();
1976 while ((c
= s
.read()) != null) {
1977 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1978 account
.setProfileKey(c
.getProfileKey().get());
1980 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1981 ContactInfo contact
= account
.getContactStore().getContact(address
);
1982 if (contact
== null) {
1983 contact
= new ContactInfo(address
);
1985 if (c
.getName().isPresent()) {
1986 contact
.name
= c
.getName().get();
1988 if (c
.getColor().isPresent()) {
1989 contact
.color
= c
.getColor().get();
1991 if (c
.getProfileKey().isPresent()) {
1992 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1994 if (c
.getVerified().isPresent()) {
1995 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1996 account
.getSignalProtocolStore()
1997 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
1998 verifiedMessage
.getIdentityKey(),
1999 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2001 if (c
.getExpirationTimer().isPresent()) {
2002 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
2004 contact
.blocked
= c
.isBlocked();
2005 contact
.inboxPosition
= c
.getInboxPosition().orNull();
2006 contact
.archived
= c
.isArchived();
2007 account
.getContactStore().updateContact(contact
);
2009 if (c
.getAvatar().isPresent()) {
2010 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2014 } catch (Exception e
) {
2015 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2019 if (tmpFile
!= null) {
2021 Files
.delete(tmpFile
.toPath());
2022 } catch (IOException e
) {
2023 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2030 if (syncMessage
.getVerified().isPresent()) {
2031 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
2032 account
.getSignalProtocolStore()
2033 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2034 verifiedMessage
.getIdentityKey(),
2035 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2037 if (syncMessage
.getStickerPackOperations().isPresent()) {
2038 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
2040 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
2041 if (!m
.getPackId().isPresent()) {
2044 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2045 if (sticker
== null) {
2046 if (!m
.getPackKey().isPresent()) {
2049 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2051 sticker
.setInstalled(!m
.getType().isPresent()
2052 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2053 account
.getStickerStore().updateSticker(sticker
);
2056 if (syncMessage
.getFetchType().isPresent()) {
2057 switch (syncMessage
.getFetchType().get()) {
2059 getRecipientProfile(getSelfAddress(), true);
2060 case STORAGE_MANIFEST
:
2064 if (syncMessage
.getKeys().isPresent()) {
2065 final KeysMessage keysMessage
= syncMessage
.getKeys().get();
2066 if (keysMessage
.getStorageService().isPresent()) {
2067 final StorageKey storageKey
= keysMessage
.getStorageService().get();
2068 account
.setStorageKey(storageKey
);
2071 if (syncMessage
.getConfiguration().isPresent()) {
2079 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2081 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2082 } catch (IOException e
) {
2083 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2087 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2089 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2090 } catch (IOException e
) {
2091 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2095 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2097 avatarStore
.storeGroupAvatar(groupId
,
2098 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2099 } catch (IOException e
) {
2100 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2104 private void downloadProfileAvatar(
2105 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2108 avatarStore
.storeProfileAvatar(address
,
2109 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2110 } catch (Throwable e
) {
2111 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2115 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2116 return attachmentStore
.getAttachmentFile(attachmentId
);
2119 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2120 if (!attachment
.isPointer()) {
2121 logger
.warn("Invalid state, can't store an attachment stream.");
2124 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2125 if (pointer
.getPreview().isPresent()) {
2126 final byte[] preview
= pointer
.getPreview().get();
2128 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2129 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2130 } catch (IOException e
) {
2131 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2136 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2137 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2138 } catch (IOException e
) {
2139 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2143 private void retrieveGroupV2Avatar(
2144 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2145 ) throws IOException
{
2146 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2148 File tmpFile
= IOUtils
.createTempFile();
2149 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2151 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2152 byte[] encryptedData
= IOUtils
.readFully(input
);
2154 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2155 outputStream
.write(decryptedData
);
2158 Files
.delete(tmpFile
.toPath());
2159 } catch (IOException e
) {
2160 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2167 private void retrieveProfileAvatar(
2168 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2169 ) throws IOException
{
2170 File tmpFile
= IOUtils
.createTempFile();
2171 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2174 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2175 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2176 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2179 Files
.delete(tmpFile
.toPath());
2180 } catch (IOException e
) {
2181 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2188 private void retrieveAttachment(
2189 final SignalServiceAttachment attachment
, final OutputStream outputStream
2190 ) throws IOException
{
2191 if (attachment
.isPointer()) {
2192 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2193 retrieveAttachmentPointer(pointer
, outputStream
);
2195 SignalServiceAttachmentStream stream
= attachment
.asStream();
2196 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2200 private void retrieveAttachmentPointer(
2201 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2202 ) throws IOException
{
2203 File tmpFile
= IOUtils
.createTempFile();
2204 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2205 IOUtils
.copyStream(input
, outputStream
);
2206 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2207 throw new IOException(e
);
2210 Files
.delete(tmpFile
.toPath());
2211 } catch (IOException e
) {
2212 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2219 private InputStream
retrieveAttachmentAsStream(
2220 SignalServiceAttachmentPointer pointer
, File tmpFile
2221 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2222 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2225 void sendGroups() throws IOException
, UntrustedIdentityException
{
2226 File groupsFile
= IOUtils
.createTempFile();
2229 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2230 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2231 for (GroupInfo
record : getGroups()) {
2232 if (record instanceof GroupInfoV1
) {
2233 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2234 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2235 Optional
.fromNullable(groupInfo
.name
),
2236 new ArrayList
<>(groupInfo
.getMembers()),
2237 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2238 groupInfo
.isMember(account
.getSelfAddress()),
2239 Optional
.of(groupInfo
.messageExpirationTime
),
2240 Optional
.fromNullable(groupInfo
.color
),
2242 Optional
.fromNullable(groupInfo
.inboxPosition
),
2243 groupInfo
.archived
));
2248 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2249 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2250 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2251 .withStream(groupsFileStream
)
2252 .withContentType("application/octet-stream")
2253 .withLength(groupsFile
.length())
2256 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2261 Files
.delete(groupsFile
.toPath());
2262 } catch (IOException e
) {
2263 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2268 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2269 File contactsFile
= IOUtils
.createTempFile();
2272 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2273 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2274 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2275 VerifiedMessage verifiedMessage
= null;
2276 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2277 if (currentIdentity
!= null) {
2278 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2279 currentIdentity
.getIdentityKey(),
2280 currentIdentity
.getTrustLevel().toVerifiedState(),
2281 currentIdentity
.getDateAdded().getTime());
2284 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2285 out
.write(new DeviceContact(record.getAddress(),
2286 Optional
.fromNullable(record.name
),
2287 createContactAvatarAttachment(record.getAddress()),
2288 Optional
.fromNullable(record.color
),
2289 Optional
.fromNullable(verifiedMessage
),
2290 Optional
.fromNullable(profileKey
),
2292 Optional
.of(record.messageExpirationTime
),
2293 Optional
.fromNullable(record.inboxPosition
),
2297 if (account
.getProfileKey() != null) {
2298 // Send our own profile key as well
2299 out
.write(new DeviceContact(account
.getSelfAddress(),
2304 Optional
.of(account
.getProfileKey()),
2312 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2313 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2314 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2315 .withStream(contactsFileStream
)
2316 .withContentType("application/octet-stream")
2317 .withLength(contactsFile
.length())
2320 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2325 Files
.delete(contactsFile
.toPath());
2326 } catch (IOException e
) {
2327 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2332 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2333 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2334 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2335 if (record.blocked
) {
2336 addresses
.add(record.getAddress());
2339 List
<byte[]> groupIds
= new ArrayList
<>();
2340 for (GroupInfo
record : getGroups()) {
2341 if (record.isBlocked()) {
2342 groupIds
.add(record.getGroupId().serialize());
2345 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2348 private void sendVerifiedMessage(
2349 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2350 ) throws IOException
, UntrustedIdentityException
{
2351 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2353 trustLevel
.toVerifiedState(),
2354 System
.currentTimeMillis());
2355 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2358 public List
<ContactInfo
> getContacts() {
2359 return account
.getContactStore().getContacts();
2362 public String
getContactOrProfileName(String number
) {
2363 final SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2365 final ContactInfo contact
= account
.getContactStore().getContact(address
);
2366 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2367 return contact
.name
;
2370 final SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2371 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2372 return profileEntry
.getProfile().getName();
2378 public GroupInfo
getGroup(GroupId groupId
) {
2379 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2380 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2381 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2382 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2383 account
.getGroupStore().updateGroup(group
);
2388 public List
<IdentityInfo
> getIdentities() {
2389 return account
.getSignalProtocolStore().getIdentities();
2392 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2393 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2397 * Trust this the identity with this fingerprint
2399 * @param name username of the identity
2400 * @param fingerprint Fingerprint
2402 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2403 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2404 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2408 for (IdentityInfo id
: ids
) {
2409 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2413 account
.getSignalProtocolStore()
2414 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2416 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2417 } catch (IOException
| UntrustedIdentityException e
) {
2418 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2427 * Trust this the identity with this safety number
2429 * @param name username of the identity
2430 * @param safetyNumber Safety number
2432 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2433 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2434 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2438 for (IdentityInfo id
: ids
) {
2439 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2443 account
.getSignalProtocolStore()
2444 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2446 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2447 } catch (IOException
| UntrustedIdentityException e
) {
2448 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2457 * Trust all keys of this identity without verification
2459 * @param name username of the identity
2461 public boolean trustIdentityAllKeys(String name
) {
2462 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2463 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2467 for (IdentityInfo id
: ids
) {
2468 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2469 account
.getSignalProtocolStore()
2470 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2472 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2473 } catch (IOException
| UntrustedIdentityException e
) {
2474 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2482 public String
computeSafetyNumber(
2483 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2485 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2486 account
.getSelfAddress(),
2487 getIdentityKeyPair().getPublicKey(),
2492 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2493 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2495 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2496 return resolveSignalServiceAddress(canonicalizedNumber
);
2499 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2500 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2502 return resolveSignalServiceAddress(address
);
2505 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2506 if (address
.matches(account
.getSelfAddress())) {
2507 return account
.getSelfAddress();
2510 return account
.getRecipientStore().resolveServiceAddress(address
);
2514 public void close() throws IOException
{
2518 void close(boolean closeAccount
) throws IOException
{
2519 if (messagePipe
!= null) {
2520 messagePipe
.shutdown();
2524 if (unidentifiedMessagePipe
!= null) {
2525 unidentifiedMessagePipe
.shutdown();
2526 unidentifiedMessagePipe
= null;
2529 if (closeAccount
&& account
!= null) {
2535 public interface ReceiveMessageHandler
{
2537 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);