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 com
.fasterxml
.jackson
.databind
.ObjectMapper
;
21 import org
.asamk
.signal
.manager
.groups
.GroupId
;
22 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
23 import org
.asamk
.signal
.manager
.groups
.GroupIdV2
;
24 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
25 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
26 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
27 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
28 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
29 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
30 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
31 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
32 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
33 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactInfo
;
34 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
35 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
36 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
37 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
38 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfile
;
39 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfileEntry
;
40 import org
.asamk
.signal
.manager
.storage
.protocol
.IdentityInfo
;
41 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
42 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
43 import org
.asamk
.signal
.manager
.util
.IOUtils
;
44 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
45 import org
.asamk
.signal
.manager
.util
.Utils
;
46 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
47 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
48 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
49 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
50 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
51 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
52 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
53 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
54 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
56 import org
.signal
.libsignal
.metadata
.SelfSendException
;
57 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
58 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
59 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
60 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroupJoinInfo
;
61 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedMember
;
62 import org
.signal
.zkgroup
.InvalidInputException
;
63 import org
.signal
.zkgroup
.VerificationFailedException
;
64 import org
.signal
.zkgroup
.auth
.AuthCredentialResponse
;
65 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
66 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
67 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
68 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
69 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
70 import org
.slf4j
.Logger
;
71 import org
.slf4j
.LoggerFactory
;
72 import org
.whispersystems
.libsignal
.IdentityKey
;
73 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
74 import org
.whispersystems
.libsignal
.InvalidKeyException
;
75 import org
.whispersystems
.libsignal
.InvalidMessageException
;
76 import org
.whispersystems
.libsignal
.InvalidVersionException
;
77 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
78 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
79 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
80 import org
.whispersystems
.libsignal
.util
.Pair
;
81 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
82 import org
.whispersystems
.signalservice
.api
.KeyBackupService
;
83 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
84 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
85 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
86 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
87 import org
.whispersystems
.signalservice
.api
.crypto
.InvalidCiphertextException
;
88 import org
.whispersystems
.signalservice
.api
.crypto
.ProfileCipher
;
89 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
90 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
91 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
92 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
93 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
94 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
95 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
96 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
97 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
106 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
107 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
108 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
109 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceStickerManifestUpload
;
110 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceStickerManifestUpload
.StickerInfo
;
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
.RequestMessage
;
121 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
122 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
123 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
124 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
125 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
126 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
127 import org
.whispersystems
.signalservice
.api
.push
.ContactTokenDetails
;
128 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
129 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
130 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
131 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
132 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
133 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
134 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
135 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
136 import org
.whispersystems
.signalservice
.internal
.configuration
.SignalServiceConfiguration
;
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
.util
.Base64
;
146 import java
.io
.Closeable
;
148 import java
.io
.FileInputStream
;
149 import java
.io
.FileNotFoundException
;
150 import java
.io
.FileOutputStream
;
151 import java
.io
.IOException
;
152 import java
.io
.InputStream
;
153 import java
.io
.OutputStream
;
155 import java
.net
.URISyntaxException
;
156 import java
.net
.URLEncoder
;
157 import java
.nio
.charset
.StandardCharsets
;
158 import java
.nio
.file
.Files
;
159 import java
.security
.SignatureException
;
160 import java
.util
.ArrayList
;
161 import java
.util
.Arrays
;
162 import java
.util
.Collection
;
163 import java
.util
.Date
;
164 import java
.util
.HashMap
;
165 import java
.util
.HashSet
;
166 import java
.util
.List
;
167 import java
.util
.Map
;
168 import java
.util
.Set
;
169 import java
.util
.UUID
;
170 import java
.util
.concurrent
.ExecutorService
;
171 import java
.util
.concurrent
.TimeUnit
;
172 import java
.util
.concurrent
.TimeoutException
;
173 import java
.util
.stream
.Collectors
;
174 import java
.util
.zip
.ZipEntry
;
175 import java
.util
.zip
.ZipFile
;
177 import static org
.asamk
.signal
.manager
.ServiceConfig
.CDS_MRENCLAVE
;
178 import static org
.asamk
.signal
.manager
.ServiceConfig
.capabilities
;
179 import static org
.asamk
.signal
.manager
.ServiceConfig
.getIasKeyStore
;
181 public class Manager
implements Closeable
{
183 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
185 private final CertificateValidator certificateValidator
= new CertificateValidator(ServiceConfig
.getUnidentifiedSenderTrustRoot());
187 private final SignalServiceConfiguration serviceConfiguration
;
188 private final String userAgent
;
190 private SignalAccount account
;
191 private final PathConfig pathConfig
;
192 private final SignalServiceAccountManager accountManager
;
193 private final GroupsV2Api groupsV2Api
;
194 private final GroupsV2Operations groupsV2Operations
;
195 private final SignalServiceMessageReceiver messageReceiver
;
196 private final ClientZkProfileOperations clientZkProfileOperations
;
198 private SignalServiceMessagePipe messagePipe
= null;
199 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
201 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
202 private final ProfileHelper profileHelper
;
203 private final GroupHelper groupHelper
;
204 private final PinHelper pinHelper
;
205 private final AvatarStore avatarStore
;
208 SignalAccount account
,
209 PathConfig pathConfig
,
210 SignalServiceConfiguration serviceConfiguration
,
213 this.account
= account
;
214 this.pathConfig
= pathConfig
;
215 this.serviceConfiguration
= serviceConfiguration
;
216 this.userAgent
= userAgent
;
217 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
218 serviceConfiguration
)) : null;
219 final SleepTimer timer
= new UptimeSleepTimer();
220 this.accountManager
= new SignalServiceAccountManager(serviceConfiguration
,
221 new DynamicCredentialsProvider(account
.getUuid(),
222 account
.getUsername(),
223 account
.getPassword(),
224 account
.getSignalingKey(),
225 account
.getDeviceId()),
229 this.groupsV2Api
= accountManager
.getGroupsV2Api();
230 final KeyBackupService keyBackupService
= ServiceConfig
.createKeyBackupService(accountManager
);
231 this.pinHelper
= new PinHelper(keyBackupService
);
232 this.clientZkProfileOperations
= capabilities
.isGv2() ? ClientZkOperations
.create(serviceConfiguration
)
233 .getProfileOperations() : null;
234 this.messageReceiver
= new SignalServiceMessageReceiver(serviceConfiguration
,
236 account
.getUsername(),
237 account
.getPassword(),
238 account
.getDeviceId(),
239 account
.getSignalingKey(),
243 clientZkProfileOperations
);
245 this.account
.setResolver(this::resolveSignalServiceAddress
);
247 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
248 account
.getProfileStore()::getProfileKey
,
249 this::getRecipientProfile
,
250 this::getSenderCertificate
);
251 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
252 unidentifiedAccessHelper
::getAccessFor
,
253 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
254 () -> messageReceiver
);
255 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
256 this::getRecipientProfile
,
257 account
::getSelfAddress
,
260 this::getGroupAuthForToday
);
261 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
264 public String
getUsername() {
265 return account
.getUsername();
268 public SignalServiceAddress
getSelfAddress() {
269 return account
.getSelfAddress();
272 private IdentityKeyPair
getIdentityKeyPair() {
273 return account
.getSignalProtocolStore().getIdentityKeyPair();
276 public int getDeviceId() {
277 return account
.getDeviceId();
280 public static Manager
init(
281 String username
, File settingsPath
, SignalServiceConfiguration serviceConfiguration
, String userAgent
282 ) throws IOException
, NotRegisteredException
{
283 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
285 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
286 throw new NotRegisteredException();
289 SignalAccount account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
291 if (!account
.isRegistered()) {
292 throw new NotRegisteredException();
295 return new Manager(account
, pathConfig
, serviceConfiguration
, userAgent
);
298 public void checkAccountState() throws IOException
{
299 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
303 if (account
.getUuid() == null) {
304 account
.setUuid(accountManager
.getOwnUuid());
307 updateAccountAttributes();
311 * This is used for checking a set of phone numbers for registration on Signal
313 * @param numbers The set of phone number in question
314 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
315 * @throws IOException if its unable to get the contacts to check if they're registered
317 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
318 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
319 List
<ContactTokenDetails
> contactDetails
= this.accountManager
.getContacts(numbers
);
321 Set
<String
> registeredUsers
= contactDetails
.stream()
322 .map(ContactTokenDetails
::getNumber
)
323 .collect(Collectors
.toSet());
325 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
328 public void updateAccountAttributes() throws IOException
{
329 accountManager
.setAccountAttributes(account
.getSignalingKey(),
330 account
.getSignalProtocolStore().getLocalRegistrationId(),
332 // set legacy pin only if no KBS master key is set
333 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
334 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
335 account
.getSelfUnidentifiedAccessKey(),
336 account
.isUnrestrictedUnidentifiedAccess(),
338 account
.isDiscoverableByPhoneNumber());
342 * @param avatar if avatar is null the image from the local avatar store is used (if present),
343 * if it's Optional.absent(), the avatar will be removed
345 public void setProfile(String name
, Optional
<File
> avatar
) throws IOException
{
346 try (final StreamDetails streamDetails
= avatar
== null
347 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
348 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
349 accountManager
.setVersionedProfile(account
.getUuid(), account
.getProfileKey(), name
, streamDetails
);
352 if (avatar
!= null) {
353 if (avatar
.isPresent()) {
354 avatarStore
.storeProfileAvatar(getSelfAddress(),
355 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
357 avatarStore
.deleteProfileAvatar(getSelfAddress());
362 public void unregister() throws IOException
{
363 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
364 // If this is the master device, other users can't send messages to this number anymore.
365 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
366 accountManager
.setGcmId(Optional
.absent());
368 account
.setRegistered(false);
372 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
373 List
<DeviceInfo
> devices
= accountManager
.getDevices();
374 account
.setMultiDevice(devices
.size() > 1);
379 public void removeLinkedDevices(int deviceId
) throws IOException
{
380 accountManager
.removeDevice(deviceId
);
381 List
<DeviceInfo
> devices
= accountManager
.getDevices();
382 account
.setMultiDevice(devices
.size() > 1);
386 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
387 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
389 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
392 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
393 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
394 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
396 accountManager
.addDevice(deviceIdentifier
,
399 Optional
.of(account
.getProfileKey().serialize()),
401 account
.setMultiDevice(true);
405 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
406 if (pin
.isPresent()) {
407 final MasterKey masterKey
= account
.getPinMasterKey() != null
408 ? account
.getPinMasterKey()
409 : KeyUtils
.createMasterKey();
411 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
413 account
.setRegistrationLockPin(pin
.get());
414 account
.setPinMasterKey(masterKey
);
416 // Remove legacy registration lock
417 accountManager
.removeRegistrationLockV1();
420 pinHelper
.removeRegistrationLockPin();
422 account
.setRegistrationLockPin(null);
423 account
.setPinMasterKey(null);
428 void refreshPreKeys() throws IOException
{
429 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
430 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
431 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
433 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
436 private List
<PreKeyRecord
> generatePreKeys() {
437 final int offset
= account
.getPreKeyIdOffset();
439 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
440 account
.addPreKeys(records
);
446 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
447 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
449 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
450 account
.addSignedPreKey(record);
456 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
457 if (messagePipe
== null) {
458 messagePipe
= messageReceiver
.createMessagePipe();
463 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
464 if (unidentifiedMessagePipe
== null) {
465 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
467 return unidentifiedMessagePipe
;
470 private SignalServiceMessageSender
createMessageSender() {
471 final ExecutorService executor
= null;
472 return new SignalServiceMessageSender(serviceConfiguration
,
474 account
.getUsername(),
475 account
.getPassword(),
476 account
.getDeviceId(),
477 account
.getSignalProtocolStore(),
479 account
.isMultiDevice(),
480 Optional
.fromNullable(messagePipe
),
481 Optional
.fromNullable(unidentifiedMessagePipe
),
483 clientZkProfileOperations
,
485 ServiceConfig
.MAX_ENVELOPE_SIZE
);
488 private SignalProfile
getRecipientProfile(
489 SignalServiceAddress address
491 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
492 if (profileEntry
== null) {
495 long now
= new Date().getTime();
496 // Profiles are cache for 24h before retrieving them again
497 if (!profileEntry
.isRequestPending() && (
498 profileEntry
.getProfile() == null || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
500 ProfileKey profileKey
= profileEntry
.getProfileKey();
501 profileEntry
.setRequestPending(true);
502 SignalProfile profile
;
504 profile
= retrieveRecipientProfile(address
, profileKey
);
505 } catch (IOException e
) {
506 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
507 profileEntry
.setRequestPending(false);
510 profileEntry
.setRequestPending(false);
511 account
.getProfileStore()
512 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
515 return profileEntry
.getProfile();
518 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
519 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
520 if (profileEntry
== null) {
523 if (profileEntry
.getProfileKeyCredential() == null) {
524 ProfileAndCredential profileAndCredential
;
526 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
527 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
528 } catch (IOException e
) {
529 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
533 long now
= new Date().getTime();
534 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
535 final SignalProfile profile
= decryptProfile(address
,
536 profileEntry
.getProfileKey(),
537 profileAndCredential
.getProfile());
538 account
.getProfileStore()
539 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
540 return profileKeyCredential
;
542 return profileEntry
.getProfileKeyCredential();
545 private SignalProfile
retrieveRecipientProfile(
546 SignalServiceAddress address
, ProfileKey profileKey
547 ) throws IOException
{
548 final SignalServiceProfile encryptedProfile
= profileHelper
.retrieveProfileSync(address
,
549 SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
551 return decryptProfile(address
, profileKey
, encryptedProfile
);
554 private SignalProfile
decryptProfile(
555 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
557 if (encryptedProfile
.getAvatar() != null) {
559 retrieveProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
560 } catch (Throwable e
) {
561 logger
.warn("Failed to retrieve profile avatar, ignoring: {}", e
.getMessage());
565 ProfileCipher profileCipher
= new ProfileCipher(profileKey
);
569 name
= encryptedProfile
.getName() == null
571 : new String(profileCipher
.decryptName(Base64
.decode(encryptedProfile
.getName())));
572 } catch (IOException e
) {
575 String unidentifiedAccess
;
577 unidentifiedAccess
= encryptedProfile
.getUnidentifiedAccess() == null
578 || !profileCipher
.verifyUnidentifiedAccess(Base64
.decode(encryptedProfile
.getUnidentifiedAccess()))
580 : encryptedProfile
.getUnidentifiedAccess();
581 } catch (IOException e
) {
582 unidentifiedAccess
= null;
584 return new SignalProfile(encryptedProfile
.getIdentityKey(),
587 encryptedProfile
.isUnrestrictedUnidentifiedAccess(),
588 encryptedProfile
.getCapabilities());
589 } catch (InvalidCiphertextException e
) {
594 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
595 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
596 if (streamDetails
== null) {
597 return Optional
.absent();
600 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
603 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
604 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
605 if (streamDetails
== null) {
606 return Optional
.absent();
609 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
612 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
613 GroupInfo g
= getGroup(groupId
);
615 throw new GroupNotFoundException(groupId
);
617 if (!g
.isMember(account
.getSelfAddress())) {
618 throw new NotAGroupMemberException(groupId
, g
.getTitle());
623 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
624 GroupInfo g
= getGroup(groupId
);
626 throw new GroupNotFoundException(groupId
);
628 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
629 throw new NotAGroupMemberException(groupId
, g
.getTitle());
634 public List
<GroupInfo
> getGroups() {
635 return account
.getGroupStore().getGroups();
638 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
639 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
640 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
641 final GroupInfo g
= getGroupForSending(groupId
);
643 GroupUtils
.setGroupContext(messageBuilder
, g
);
644 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
646 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
649 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
650 String messageText
, List
<String
> attachments
, GroupId groupId
651 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
652 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
653 .withBody(messageText
);
654 if (attachments
!= null) {
655 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
658 return sendGroupMessage(messageBuilder
, groupId
);
661 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
662 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
663 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
664 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
666 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
667 targetSentTimestamp
);
668 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
669 .withReaction(reaction
);
671 return sendGroupMessage(messageBuilder
, groupId
);
674 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
676 SignalServiceDataMessage
.Builder messageBuilder
;
678 final GroupInfo g
= getGroupForUpdating(groupId
);
679 if (g
instanceof GroupInfoV1
) {
680 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
681 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
682 .withId(groupId
.serialize())
684 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
685 groupInfoV1
.removeMember(account
.getSelfAddress());
686 account
.getGroupStore().updateGroup(groupInfoV1
);
688 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
689 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
690 groupInfoV2
.setGroup(groupGroupChangePair
.first());
691 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
692 account
.getGroupStore().updateGroup(groupInfoV2
);
695 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
698 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
699 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
700 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
702 SignalServiceDataMessage
.Builder messageBuilder
;
703 if (groupId
== null) {
705 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
706 members
== null ? List
.of() : members
,
709 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
710 gv1
.addMembers(List
.of(account
.getSelfAddress()));
711 updateGroupV1(gv1
, name
, members
, avatarFile
);
712 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
715 if (avatarFile
!= null) {
716 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
717 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
719 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
723 GroupInfo group
= getGroupForUpdating(groupId
);
724 if (group
instanceof GroupInfoV2
) {
725 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
727 Pair
<Long
, List
<SendMessageResult
>> result
= null;
728 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
729 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
730 result
= sendUpdateGroupMessage(groupInfoV2
,
731 groupGroupChangePair
.first(),
732 groupGroupChangePair
.second());
735 if (members
!= null) {
736 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
737 newMembers
.removeAll(group
.getMembers()
739 .map(this::resolveSignalServiceAddress
)
740 .collect(Collectors
.toSet()));
741 if (newMembers
.size() > 0) {
742 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
744 result
= sendUpdateGroupMessage(groupInfoV2
,
745 groupGroupChangePair
.first(),
746 groupGroupChangePair
.second());
749 if (result
== null || name
!= null || avatarFile
!= null) {
750 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
753 if (avatarFile
!= null) {
754 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
755 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
757 result
= sendUpdateGroupMessage(groupInfoV2
,
758 groupGroupChangePair
.first(),
759 groupGroupChangePair
.second());
762 return new Pair
<>(group
.getGroupId(), result
.second());
764 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
765 updateGroupV1(gv1
, name
, members
, avatarFile
);
766 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
771 account
.getGroupStore().updateGroup(g
);
773 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
774 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
775 return new Pair
<>(g
.getGroupId(), result
.second());
778 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
779 GroupInviteLinkUrl inviteLinkUrl
780 ) throws IOException
, GroupLinkNotActiveException
{
781 return sendJoinGroupMessage(inviteLinkUrl
);
784 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
785 GroupInviteLinkUrl inviteLinkUrl
786 ) throws IOException
, GroupLinkNotActiveException
{
787 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
788 inviteLinkUrl
.getPassword());
789 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
790 inviteLinkUrl
.getPassword(),
792 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
793 groupJoinInfo
.getRevision() + 1,
794 groupChange
.toByteArray());
796 if (group
.getGroup() == null) {
797 // Only requested member, can't send update to group members
798 return new Pair
<>(group
.getGroupId(), List
.of());
801 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
803 return new Pair
<>(group
.getGroupId(), result
.second());
806 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
807 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
808 ) throws IOException
{
809 group
.setGroup(newDecryptedGroup
);
810 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
811 groupChange
.toByteArray());
812 account
.getGroupStore().updateGroup(group
);
813 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
816 private void updateGroupV1(
819 final Collection
<SignalServiceAddress
> members
,
820 final File avatarFile
821 ) throws IOException
{
826 if (members
!= null) {
827 final Set
<String
> newE164Members
= new HashSet
<>();
828 for (SignalServiceAddress member
: members
) {
829 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
832 newE164Members
.add(member
.getNumber().get());
835 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newE164Members
);
836 if (contacts
.size() != newE164Members
.size()) {
837 // Some of the new members are not registered on Signal
838 for (ContactTokenDetails contact
: contacts
) {
839 newE164Members
.remove(contact
.getNumber());
841 throw new IOException("Failed to add members "
842 + String
.join(", ", newE164Members
)
843 + " to group: Not registered on Signal");
846 g
.addMembers(members
);
849 if (avatarFile
!= null) {
850 avatarStore
.storeGroupAvatar(g
.getGroupId(),
851 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
855 Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
856 GroupIdV1 groupId
, SignalServiceAddress recipient
857 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
859 GroupInfo group
= getGroupForSending(groupId
);
860 if (!(group
instanceof GroupInfoV1
)) {
861 throw new RuntimeException("Received an invalid group request for a v2 group!");
863 g
= (GroupInfoV1
) group
;
865 if (!g
.isMember(recipient
)) {
866 throw new NotAGroupMemberException(groupId
, g
.name
);
869 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
871 // Send group message only to the recipient who requested it
872 return sendMessage(messageBuilder
, List
.of(recipient
));
875 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
876 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
877 .withId(g
.getGroupId().serialize())
879 .withMembers(new ArrayList
<>(g
.getMembers()));
882 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
883 if (attachment
.isPresent()) {
884 group
.withAvatar(attachment
.get());
886 } catch (IOException e
) {
887 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
890 return SignalServiceDataMessage
.newBuilder()
891 .asGroupMessage(group
.build())
892 .withExpiration(g
.getMessageExpirationTime());
895 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
896 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
897 .withRevision(g
.getGroup().getRevision())
898 .withSignedGroupChange(signedGroupChange
);
899 return SignalServiceDataMessage
.newBuilder()
900 .asGroupMessage(group
.build())
901 .withExpiration(g
.getMessageExpirationTime());
904 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
905 GroupIdV1 groupId
, SignalServiceAddress recipient
906 ) throws IOException
{
907 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
908 .withId(groupId
.serialize());
910 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
911 .asGroupMessage(group
.build());
913 // Send group info request message to the recipient who sent us a message with this groupId
914 return sendMessage(messageBuilder
, List
.of(recipient
));
918 SignalServiceAddress remoteAddress
, long messageId
919 ) throws IOException
, UntrustedIdentityException
{
920 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
922 System
.currentTimeMillis());
924 createMessageSender().sendReceipt(remoteAddress
,
925 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
929 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
930 String messageText
, List
<String
> attachments
, List
<String
> recipients
931 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
932 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
933 .withBody(messageText
);
934 if (attachments
!= null) {
935 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
937 // Upload attachments here, so we only upload once even for multiple recipients
938 SignalServiceMessageSender messageSender
= createMessageSender();
939 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
940 for (SignalServiceAttachment attachment
: attachmentStreams
) {
941 if (attachment
.isStream()) {
942 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
943 } else if (attachment
.isPointer()) {
944 attachmentPointers
.add(attachment
.asPointer());
948 messageBuilder
.withAttachments(attachmentPointers
);
950 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
953 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
954 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
955 ) throws IOException
, InvalidNumberException
{
956 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
958 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
959 targetSentTimestamp
);
960 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
961 .withReaction(reaction
);
962 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
965 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
966 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
968 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
970 return sendMessage(messageBuilder
, signalServiceAddresses
);
971 } catch (Exception e
) {
972 for (SignalServiceAddress address
: signalServiceAddresses
) {
973 handleEndSession(address
);
980 public String
getContactName(String number
) throws InvalidNumberException
{
981 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
982 if (contact
== null) {
989 public void setContactName(String number
, String name
) throws InvalidNumberException
{
990 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
991 ContactInfo contact
= account
.getContactStore().getContact(address
);
992 if (contact
== null) {
993 contact
= new ContactInfo(address
);
996 account
.getContactStore().updateContact(contact
);
1000 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1001 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1004 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1005 ContactInfo contact
= account
.getContactStore().getContact(address
);
1006 if (contact
== null) {
1007 contact
= new ContactInfo(address
);
1009 contact
.blocked
= blocked
;
1010 account
.getContactStore().updateContact(contact
);
1014 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1015 GroupInfo group
= getGroup(groupId
);
1016 if (group
== null) {
1017 throw new GroupNotFoundException(groupId
);
1020 group
.setBlocked(blocked
);
1021 account
.getGroupStore().updateGroup(group
);
1025 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
1026 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
1027 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
1028 return sendUpdateGroupMessage(groupId
,
1030 members
== null ?
null : getSignalServiceAddresses(members
),
1035 * Change the expiration timer for a contact
1037 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1038 ContactInfo contact
= account
.getContactStore().getContact(address
);
1039 contact
.messageExpirationTime
= messageExpirationTimer
;
1040 account
.getContactStore().updateContact(contact
);
1041 sendExpirationTimerUpdate(address
);
1045 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1046 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1047 .asExpirationUpdate();
1048 sendMessage(messageBuilder
, List
.of(address
));
1052 * Change the expiration timer for a contact
1054 public void setExpirationTimer(
1055 String number
, int messageExpirationTimer
1056 ) throws IOException
, InvalidNumberException
{
1057 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1058 setExpirationTimer(address
, messageExpirationTimer
);
1062 * Change the expiration timer for a group
1064 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1065 GroupInfo g
= getGroup(groupId
);
1066 if (g
instanceof GroupInfoV1
) {
1067 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1068 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1069 account
.getGroupStore().updateGroup(groupInfoV1
);
1071 throw new RuntimeException("TODO Not implemented!");
1076 * Upload the sticker pack from path.
1078 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1079 * @return if successful, returns the URL to install the sticker pack in the signal app
1081 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1082 SignalServiceStickerManifestUpload manifest
= getSignalServiceStickerManifestUpload(path
);
1084 SignalServiceMessageSender messageSender
= createMessageSender();
1086 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1087 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1089 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1090 account
.getStickerStore().updateSticker(sticker
);
1094 return new URI("https",
1097 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1098 Hex
.toStringCondensed(packKey
),
1099 StandardCharsets
.UTF_8
)).toString();
1100 } catch (URISyntaxException e
) {
1101 throw new AssertionError(e
);
1105 private SignalServiceStickerManifestUpload
getSignalServiceStickerManifestUpload(
1107 ) throws IOException
, StickerPackInvalidException
{
1109 String rootPath
= null;
1111 if (file
.getName().endsWith(".zip")) {
1112 zip
= new ZipFile(file
);
1113 } else if (file
.getName().equals("manifest.json")) {
1114 rootPath
= file
.getParent();
1116 throw new StickerPackInvalidException("Could not find manifest.json");
1119 JsonStickerPack pack
= parseStickerPack(rootPath
, zip
);
1121 if (pack
.stickers
== null) {
1122 throw new StickerPackInvalidException("Must set a 'stickers' field.");
1125 if (pack
.stickers
.isEmpty()) {
1126 throw new StickerPackInvalidException("Must include stickers.");
1129 List
<StickerInfo
> stickers
= new ArrayList
<>(pack
.stickers
.size());
1130 for (JsonStickerPack
.JsonSticker sticker
: pack
.stickers
) {
1131 if (sticker
.file
== null) {
1132 throw new StickerPackInvalidException("Must set a 'file' field on each sticker.");
1135 Pair
<InputStream
, Long
> data
;
1137 data
= getInputStreamAndLength(rootPath
, zip
, sticker
.file
);
1138 } catch (IOException ignored
) {
1139 throw new StickerPackInvalidException("Could not find find " + sticker
.file
);
1142 String contentType
= Utils
.getFileMimeType(new File(sticker
.file
), null);
1143 StickerInfo stickerInfo
= new StickerInfo(data
.first(),
1145 Optional
.fromNullable(sticker
.emoji
).or(""),
1147 stickers
.add(stickerInfo
);
1150 StickerInfo cover
= null;
1151 if (pack
.cover
!= null) {
1152 if (pack
.cover
.file
== null) {
1153 throw new StickerPackInvalidException("Must set a 'file' field on the cover.");
1156 Pair
<InputStream
, Long
> data
;
1158 data
= getInputStreamAndLength(rootPath
, zip
, pack
.cover
.file
);
1159 } catch (IOException ignored
) {
1160 throw new StickerPackInvalidException("Could not find find " + pack
.cover
.file
);
1163 String contentType
= Utils
.getFileMimeType(new File(pack
.cover
.file
), null);
1164 cover
= new StickerInfo(data
.first(),
1166 Optional
.fromNullable(pack
.cover
.emoji
).or(""),
1170 return new SignalServiceStickerManifestUpload(pack
.title
, pack
.author
, cover
, stickers
);
1173 private static JsonStickerPack
parseStickerPack(String rootPath
, ZipFile zip
) throws IOException
{
1174 InputStream inputStream
;
1176 inputStream
= zip
.getInputStream(zip
.getEntry("manifest.json"));
1178 inputStream
= new FileInputStream((new File(rootPath
, "manifest.json")));
1180 return new ObjectMapper().readValue(inputStream
, JsonStickerPack
.class);
1183 private static Pair
<InputStream
, Long
> getInputStreamAndLength(
1184 final String rootPath
, final ZipFile zip
, final String subfile
1185 ) throws IOException
{
1187 final ZipEntry entry
= zip
.getEntry(subfile
);
1188 return new Pair
<>(zip
.getInputStream(entry
), entry
.getSize());
1190 final File file
= new File(rootPath
, subfile
);
1191 return new Pair
<>(new FileInputStream(file
), file
.length());
1195 void requestSyncGroups() throws IOException
{
1196 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1197 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1199 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1201 sendSyncMessage(message
);
1202 } catch (UntrustedIdentityException e
) {
1203 e
.printStackTrace();
1207 void requestSyncContacts() throws IOException
{
1208 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1209 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1211 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1213 sendSyncMessage(message
);
1214 } catch (UntrustedIdentityException e
) {
1215 e
.printStackTrace();
1219 void requestSyncBlocked() throws IOException
{
1220 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1221 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1223 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1225 sendSyncMessage(message
);
1226 } catch (UntrustedIdentityException e
) {
1227 e
.printStackTrace();
1231 void requestSyncConfiguration() throws IOException
{
1232 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1233 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1235 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1237 sendSyncMessage(message
);
1238 } catch (UntrustedIdentityException e
) {
1239 e
.printStackTrace();
1243 private byte[] getSenderCertificate() {
1244 // TODO support UUID capable sender certificates
1245 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1248 certificate
= accountManager
.getSenderCertificate();
1249 } catch (IOException e
) {
1250 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1253 // TODO cache for a day
1257 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1258 SignalServiceMessageSender messageSender
= createMessageSender();
1260 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1261 } catch (UntrustedIdentityException e
) {
1262 account
.getSignalProtocolStore()
1263 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1265 TrustLevel
.UNTRUSTED
);
1270 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1271 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1272 final Set
<SignalServiceAddress
> missingUuids
= new HashSet
<>();
1274 for (String number
: numbers
) {
1275 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1276 if (resolvedAddress
.getUuid().isPresent()) {
1277 signalServiceAddresses
.add(resolvedAddress
);
1279 missingUuids
.add(resolvedAddress
);
1283 Map
<String
, UUID
> registeredUsers
;
1285 registeredUsers
= accountManager
.getRegisteredUsers(getIasKeyStore(),
1286 missingUuids
.stream().map(a
-> a
.getNumber().get()).collect(Collectors
.toSet()),
1288 } catch (IOException
| Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException e
) {
1289 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1290 registeredUsers
= new HashMap
<>();
1293 for (SignalServiceAddress address
: missingUuids
) {
1294 final String number
= address
.getNumber().get();
1295 if (registeredUsers
.containsKey(number
)) {
1296 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1297 registeredUsers
.get(number
),
1299 signalServiceAddresses
.add(newAddress
);
1301 signalServiceAddresses
.add(address
);
1305 return signalServiceAddresses
;
1308 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1309 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1310 ) throws IOException
{
1311 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1312 final long timestamp
= System
.currentTimeMillis();
1313 messageBuilder
.withTimestamp(timestamp
);
1314 getOrCreateMessagePipe();
1315 getOrCreateUnidentifiedMessagePipe();
1316 SignalServiceDataMessage message
= null;
1318 message
= messageBuilder
.build();
1319 if (message
.getGroupContext().isPresent()) {
1321 SignalServiceMessageSender messageSender
= createMessageSender();
1322 final boolean isRecipientUpdate
= false;
1323 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1324 unidentifiedAccessHelper
.getAccessFor(recipients
),
1327 for (SendMessageResult r
: result
) {
1328 if (r
.getIdentityFailure() != null) {
1329 account
.getSignalProtocolStore()
1330 .saveIdentity(r
.getAddress(),
1331 r
.getIdentityFailure().getIdentityKey(),
1332 TrustLevel
.UNTRUSTED
);
1335 return new Pair
<>(timestamp
, result
);
1336 } catch (UntrustedIdentityException e
) {
1337 account
.getSignalProtocolStore()
1338 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1340 TrustLevel
.UNTRUSTED
);
1341 return new Pair
<>(timestamp
, List
.of());
1344 // Send to all individually, so sync messages are sent correctly
1345 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1346 for (SignalServiceAddress address
: recipients
) {
1347 ContactInfo contact
= account
.getContactStore().getContact(address
);
1348 if (contact
!= null) {
1349 messageBuilder
.withExpiration(contact
.messageExpirationTime
);
1350 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1352 messageBuilder
.withExpiration(0);
1353 messageBuilder
.withProfileKey(null);
1355 message
= messageBuilder
.build();
1356 if (address
.matches(account
.getSelfAddress())) {
1357 results
.add(sendSelfMessage(message
));
1359 results
.add(sendMessage(address
, message
));
1362 return new Pair
<>(timestamp
, results
);
1365 if (message
!= null && message
.isEndSession()) {
1366 for (SignalServiceAddress recipient
: recipients
) {
1367 handleEndSession(recipient
);
1374 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1375 SignalServiceMessageSender messageSender
= createMessageSender();
1377 SignalServiceAddress recipient
= account
.getSelfAddress();
1379 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1380 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1381 message
.getTimestamp(),
1383 message
.getExpiresInSeconds(),
1384 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1386 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1389 long startTime
= System
.currentTimeMillis();
1390 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1391 return SendMessageResult
.success(recipient
,
1392 unidentifiedAccess
.isPresent(),
1394 System
.currentTimeMillis() - startTime
);
1395 } catch (UntrustedIdentityException e
) {
1396 account
.getSignalProtocolStore()
1397 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1399 TrustLevel
.UNTRUSTED
);
1400 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1404 private SendMessageResult
sendMessage(
1405 SignalServiceAddress address
, SignalServiceDataMessage message
1406 ) throws IOException
{
1407 SignalServiceMessageSender messageSender
= createMessageSender();
1410 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1411 } catch (UntrustedIdentityException e
) {
1412 account
.getSignalProtocolStore()
1413 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1415 TrustLevel
.UNTRUSTED
);
1416 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1420 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1421 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1422 account
.getSignalProtocolStore(),
1423 certificateValidator
);
1425 return cipher
.decrypt(envelope
);
1426 } catch (ProtocolUntrustedIdentityException e
) {
1427 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1428 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1430 account
.getSignalProtocolStore()
1431 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1432 identityException
.getUntrustedIdentity(),
1433 TrustLevel
.UNTRUSTED
);
1434 throw identityException
;
1436 throw new AssertionError(e
);
1440 private void handleEndSession(SignalServiceAddress source
) {
1441 account
.getSignalProtocolStore().deleteAllSessions(source
);
1444 private static int currentTimeDays() {
1445 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
1448 private GroupsV2AuthorizationString
getGroupAuthForToday(
1449 final GroupSecretParams groupSecretParams
1450 ) throws IOException
{
1451 final int today
= currentTimeDays();
1452 // Returns credentials for the next 7 days
1453 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
1454 // TODO cache credentials until they expire
1455 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
1457 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
1460 authCredentialResponse
);
1461 } catch (VerificationFailedException e
) {
1462 throw new IOException(e
);
1466 private List
<HandleAction
> handleSignalServiceDataMessage(
1467 SignalServiceDataMessage message
,
1469 SignalServiceAddress source
,
1470 SignalServiceAddress destination
,
1471 boolean ignoreAttachments
1473 List
<HandleAction
> actions
= new ArrayList
<>();
1474 if (message
.getGroupContext().isPresent()) {
1475 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1476 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1477 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1478 GroupInfo group
= getGroup(groupId
);
1479 if (group
== null || group
instanceof GroupInfoV1
) {
1480 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1481 switch (groupInfo
.getType()) {
1483 if (groupV1
== null) {
1484 groupV1
= new GroupInfoV1(groupId
);
1487 if (groupInfo
.getAvatar().isPresent()) {
1488 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1489 if (avatar
.isPointer()) {
1491 retrieveGroupAvatarAttachment(avatar
.asPointer(), groupV1
.getGroupId());
1492 } catch (IOException e
) {
1493 logger
.warn("Failed to retrieve avatar for group {}, ignoring: {}",
1500 if (groupInfo
.getName().isPresent()) {
1501 groupV1
.name
= groupInfo
.getName().get();
1504 if (groupInfo
.getMembers().isPresent()) {
1505 groupV1
.addMembers(groupInfo
.getMembers()
1508 .map(this::resolveSignalServiceAddress
)
1509 .collect(Collectors
.toSet()));
1512 account
.getGroupStore().updateGroup(groupV1
);
1516 if (groupV1
== null && !isSync
) {
1517 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1521 if (groupV1
!= null) {
1522 groupV1
.removeMember(source
);
1523 account
.getGroupStore().updateGroup(groupV1
);
1528 if (groupV1
!= null && !isSync
) {
1529 actions
.add(new SendGroupUpdateAction(source
, groupV1
.getGroupId()));
1534 // Received a group v1 message for a v2 group
1537 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1538 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1539 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1541 getOrMigrateGroup(groupMasterKey
,
1542 groupContext
.getRevision(),
1543 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1547 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1548 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1549 handleEndSession(conversationPartnerAddress
);
1551 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1552 if (message
.getGroupContext().isPresent()) {
1553 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1554 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1555 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1556 if (group
!= null) {
1557 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1558 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1559 account
.getGroupStore().updateGroup(group
);
1562 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1563 // disappearing message timer already stored in the DecryptedGroup
1565 } else if (conversationPartnerAddress
!= null) {
1566 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1567 if (contact
== null) {
1568 contact
= new ContactInfo(conversationPartnerAddress
);
1570 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1571 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1572 account
.getContactStore().updateContact(contact
);
1576 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1577 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1578 if (attachment
.isPointer()) {
1580 retrieveAttachment(attachment
.asPointer());
1581 } catch (IOException e
) {
1582 logger
.warn("Failed to retrieve attachment ({}), ignoring: {}",
1583 attachment
.asPointer().getRemoteId(),
1589 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1590 final ProfileKey profileKey
;
1592 profileKey
= new ProfileKey(message
.getProfileKey().get());
1593 } catch (InvalidInputException e
) {
1594 throw new AssertionError(e
);
1596 if (source
.matches(account
.getSelfAddress())) {
1597 this.account
.setProfileKey(profileKey
);
1599 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1601 if (message
.getPreviews().isPresent()) {
1602 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1603 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1604 if (preview
.getImage().isPresent() && preview
.getImage().get().isPointer()) {
1605 SignalServiceAttachmentPointer attachment
= preview
.getImage().get().asPointer();
1607 retrieveAttachment(attachment
);
1608 } catch (IOException e
) {
1609 logger
.warn("Failed to retrieve preview image ({}), ignoring: {}",
1610 attachment
.getRemoteId(),
1616 if (message
.getQuote().isPresent()) {
1617 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1619 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1620 final SignalServiceAttachment attachment
= quotedAttachment
.getThumbnail();
1621 if (attachment
!= null && attachment
.isPointer()) {
1623 retrieveAttachment(attachment
.asPointer());
1624 } catch (IOException e
) {
1625 logger
.warn("Failed to retrieve quote attachment thumbnail ({}), ignoring: {}",
1626 attachment
.asPointer().getRemoteId(),
1632 if (message
.getSticker().isPresent()) {
1633 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1634 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1635 if (sticker
== null) {
1636 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1637 account
.getStickerStore().updateSticker(sticker
);
1643 private GroupInfoV2
getOrMigrateGroup(
1644 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1646 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1648 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1649 GroupInfo groupInfo
= getGroup(groupId
);
1650 final GroupInfoV2 groupInfoV2
;
1651 if (groupInfo
instanceof GroupInfoV1
) {
1652 // Received a v2 group message for a v1 group, we need to locally migrate the group
1653 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1654 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1655 logger
.info("Locally migrated group {} to group v2, id: {}",
1656 groupInfo
.getGroupId().toBase64(),
1657 groupInfoV2
.getGroupId().toBase64());
1658 } else if (groupInfo
instanceof GroupInfoV2
) {
1659 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1661 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1664 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1665 DecryptedGroup group
= null;
1666 if (signedGroupChange
!= null
1667 && groupInfoV2
.getGroup() != null
1668 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1669 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1671 if (group
== null) {
1672 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1674 if (group
!= null) {
1675 storeProfileKeysFromMembers(group
);
1676 final String avatar
= group
.getAvatar();
1677 if (avatar
!= null && !avatar
.isEmpty()) {
1679 retrieveGroupAvatar(groupId
, groupSecretParams
, avatar
);
1680 } catch (IOException e
) {
1681 logger
.warn("Failed to download group avatar, ignoring: {}", e
.getMessage());
1685 groupInfoV2
.setGroup(group
);
1686 account
.getGroupStore().updateGroup(groupInfoV2
);
1692 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1693 for (DecryptedMember member
: group
.getMembersList()) {
1694 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1695 member
.getUuid().toByteArray()), null));
1697 account
.getProfileStore()
1698 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1699 } catch (InvalidInputException ignored
) {
1704 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1705 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1706 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1710 private void retryFailedReceivedMessage(
1711 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1713 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1714 if (envelope
== null) {
1717 SignalServiceContent content
= null;
1718 if (!envelope
.isReceipt()) {
1720 content
= decryptMessage(envelope
);
1721 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1723 } catch (Exception er
) {
1724 // All other errors are not recoverable, so delete the cached message
1725 cachedMessage
.delete();
1728 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1729 for (HandleAction action
: actions
) {
1731 action
.execute(this);
1732 } catch (Throwable e
) {
1733 e
.printStackTrace();
1738 handler
.handleMessage(envelope
, content
, null);
1739 cachedMessage
.delete();
1742 public void receiveMessages(
1745 boolean returnOnTimeout
,
1746 boolean ignoreAttachments
,
1747 ReceiveMessageHandler handler
1748 ) throws IOException
{
1749 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1751 Set
<HandleAction
> queuedActions
= null;
1753 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1755 boolean hasCaughtUpWithOldMessages
= false;
1758 SignalServiceEnvelope envelope
;
1759 SignalServiceContent content
= null;
1760 Exception exception
= null;
1761 final CachedMessage
[] cachedMessage
= {null};
1763 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1764 // store message on disk, before acknowledging receipt to the server
1765 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1767 if (result
.isPresent()) {
1768 envelope
= result
.get();
1770 // Received indicator that server queue is empty
1771 hasCaughtUpWithOldMessages
= true;
1773 if (queuedActions
!= null) {
1774 for (HandleAction action
: queuedActions
) {
1776 action
.execute(this);
1777 } catch (Throwable e
) {
1778 e
.printStackTrace();
1782 queuedActions
.clear();
1783 queuedActions
= null;
1786 // Continue to wait another timeout for new messages
1789 } catch (TimeoutException e
) {
1790 if (returnOnTimeout
) return;
1792 } catch (InvalidVersionException e
) {
1793 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1797 if (envelope
.hasSource()) {
1798 // Store uuid if we don't have it already
1799 SignalServiceAddress source
= envelope
.getSourceAddress();
1800 resolveSignalServiceAddress(source
);
1802 if (!envelope
.isReceipt()) {
1804 content
= decryptMessage(envelope
);
1805 } catch (Exception e
) {
1808 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1809 if (hasCaughtUpWithOldMessages
) {
1810 for (HandleAction action
: actions
) {
1812 action
.execute(this);
1813 } catch (Throwable e
) {
1814 e
.printStackTrace();
1818 if (queuedActions
== null) {
1819 queuedActions
= new HashSet
<>();
1821 queuedActions
.addAll(actions
);
1825 if (isMessageBlocked(envelope
, content
)) {
1826 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1827 } else if (isNotAGroupMember(envelope
, content
)) {
1828 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1830 handler
.handleMessage(envelope
, content
, exception
);
1832 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1833 if (cachedMessage
[0] != null) {
1834 cachedMessage
[0].delete();
1840 private boolean isMessageBlocked(
1841 SignalServiceEnvelope envelope
, SignalServiceContent content
1843 SignalServiceAddress source
;
1844 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1845 source
= envelope
.getSourceAddress();
1846 } else if (content
!= null) {
1847 source
= content
.getSender();
1851 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1852 if (sourceContact
!= null && sourceContact
.blocked
) {
1856 if (content
!= null && content
.getDataMessage().isPresent()) {
1857 SignalServiceDataMessage message
= content
.getDataMessage().get();
1858 if (message
.getGroupContext().isPresent()) {
1859 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1860 GroupInfo group
= getGroup(groupId
);
1861 if (group
!= null && group
.isBlocked()) {
1869 private boolean isNotAGroupMember(
1870 SignalServiceEnvelope envelope
, SignalServiceContent content
1872 SignalServiceAddress source
;
1873 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1874 source
= envelope
.getSourceAddress();
1875 } else if (content
!= null) {
1876 source
= content
.getSender();
1881 if (content
!= null && content
.getDataMessage().isPresent()) {
1882 SignalServiceDataMessage message
= content
.getDataMessage().get();
1883 if (message
.getGroupContext().isPresent()) {
1884 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1885 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1886 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1890 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1891 GroupInfo group
= getGroup(groupId
);
1892 if (group
!= null && !group
.isMember(source
)) {
1900 private List
<HandleAction
> handleMessage(
1901 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1903 List
<HandleAction
> actions
= new ArrayList
<>();
1904 if (content
!= null) {
1905 final SignalServiceAddress sender
;
1906 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1907 sender
= envelope
.getSourceAddress();
1909 sender
= content
.getSender();
1911 // Store uuid if we don't have it already
1912 resolveSignalServiceAddress(sender
);
1914 if (content
.getDataMessage().isPresent()) {
1915 SignalServiceDataMessage message
= content
.getDataMessage().get();
1917 if (content
.isNeedsReceipt()) {
1918 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1921 actions
.addAll(handleSignalServiceDataMessage(message
,
1924 account
.getSelfAddress(),
1925 ignoreAttachments
));
1927 if (content
.getSyncMessage().isPresent()) {
1928 account
.setMultiDevice(true);
1929 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1930 if (syncMessage
.getSent().isPresent()) {
1931 SentTranscriptMessage message
= syncMessage
.getSent().get();
1932 final SignalServiceAddress destination
= message
.getDestination().orNull();
1933 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1937 ignoreAttachments
));
1939 if (syncMessage
.getRequest().isPresent()) {
1940 RequestMessage rm
= syncMessage
.getRequest().get();
1941 if (rm
.isContactsRequest()) {
1942 actions
.add(SendSyncContactsAction
.create());
1944 if (rm
.isGroupsRequest()) {
1945 actions
.add(SendSyncGroupsAction
.create());
1947 if (rm
.isBlockedListRequest()) {
1948 actions
.add(SendSyncBlockedListAction
.create());
1950 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1952 if (syncMessage
.getGroups().isPresent()) {
1953 File tmpFile
= null;
1955 tmpFile
= IOUtils
.createTempFile();
1956 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups()
1958 .asPointer(), tmpFile
)) {
1959 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1961 while ((g
= s
.read()) != null) {
1962 GroupInfoV1 syncGroup
= account
.getGroupStore()
1963 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1964 if (syncGroup
!= null) {
1965 if (g
.getName().isPresent()) {
1966 syncGroup
.name
= g
.getName().get();
1968 syncGroup
.addMembers(g
.getMembers()
1970 .map(this::resolveSignalServiceAddress
)
1971 .collect(Collectors
.toSet()));
1972 if (!g
.isActive()) {
1973 syncGroup
.removeMember(account
.getSelfAddress());
1975 // Add ourself to the member set as it's marked as active
1976 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1978 syncGroup
.blocked
= g
.isBlocked();
1979 if (g
.getColor().isPresent()) {
1980 syncGroup
.color
= g
.getColor().get();
1983 if (g
.getAvatar().isPresent()) {
1984 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.getGroupId());
1986 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1987 syncGroup
.archived
= g
.isArchived();
1988 account
.getGroupStore().updateGroup(syncGroup
);
1992 } catch (Exception e
) {
1993 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1996 e
.printStackTrace();
1998 if (tmpFile
!= null) {
2000 Files
.delete(tmpFile
.toPath());
2001 } catch (IOException e
) {
2002 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2009 if (syncMessage
.getBlockedList().isPresent()) {
2010 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
2011 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
2012 setContactBlocked(resolveSignalServiceAddress(address
), true);
2014 for (GroupId groupId
: blockedListMessage
.getGroupIds()
2016 .map(GroupId
::unknownVersion
)
2017 .collect(Collectors
.toSet())) {
2019 setGroupBlocked(groupId
, true);
2020 } catch (GroupNotFoundException e
) {
2021 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2022 groupId
.toBase64());
2026 if (syncMessage
.getContacts().isPresent()) {
2027 File tmpFile
= null;
2029 tmpFile
= IOUtils
.createTempFile();
2030 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
2031 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2032 .asPointer(), tmpFile
)) {
2033 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
2034 if (contactsMessage
.isComplete()) {
2035 account
.getContactStore().clear();
2038 while ((c
= s
.read()) != null) {
2039 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2040 account
.setProfileKey(c
.getProfileKey().get());
2042 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
2043 ContactInfo contact
= account
.getContactStore().getContact(address
);
2044 if (contact
== null) {
2045 contact
= new ContactInfo(address
);
2047 if (c
.getName().isPresent()) {
2048 contact
.name
= c
.getName().get();
2050 if (c
.getColor().isPresent()) {
2051 contact
.color
= c
.getColor().get();
2053 if (c
.getProfileKey().isPresent()) {
2054 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
2056 if (c
.getVerified().isPresent()) {
2057 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
2058 account
.getSignalProtocolStore()
2059 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
2060 verifiedMessage
.getIdentityKey(),
2061 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2063 if (c
.getExpirationTimer().isPresent()) {
2064 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
2066 contact
.blocked
= c
.isBlocked();
2067 contact
.inboxPosition
= c
.getInboxPosition().orNull();
2068 contact
.archived
= c
.isArchived();
2069 account
.getContactStore().updateContact(contact
);
2071 if (c
.getAvatar().isPresent()) {
2072 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.getAddress());
2076 } catch (Exception e
) {
2077 e
.printStackTrace();
2079 if (tmpFile
!= null) {
2081 Files
.delete(tmpFile
.toPath());
2082 } catch (IOException e
) {
2083 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2090 if (syncMessage
.getVerified().isPresent()) {
2091 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
2092 account
.getSignalProtocolStore()
2093 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2094 verifiedMessage
.getIdentityKey(),
2095 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2097 if (syncMessage
.getStickerPackOperations().isPresent()) {
2098 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
2100 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
2101 if (!m
.getPackId().isPresent()) {
2104 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2105 if (sticker
== null) {
2106 if (!m
.getPackKey().isPresent()) {
2109 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2111 sticker
.setInstalled(!m
.getType().isPresent()
2112 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2113 account
.getStickerStore().updateSticker(sticker
);
2116 if (syncMessage
.getConfiguration().isPresent()) {
2124 private void retrieveContactAvatarAttachment(
2125 SignalServiceAttachment attachment
, SignalServiceAddress address
2126 ) throws IOException
{
2127 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(attachment
, outputStream
));
2130 private void retrieveGroupAvatarAttachment(
2131 SignalServiceAttachment attachment
, GroupId groupId
2132 ) throws IOException
{
2133 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(attachment
, outputStream
));
2136 private void retrieveGroupAvatar(
2137 GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
2138 ) throws IOException
{
2139 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2141 File tmpFile
= IOUtils
.createTempFile();
2142 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2144 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2145 byte[] encryptedData
= IOUtils
.readFully(input
);
2147 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2148 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> outputStream
.write(decryptedData
));
2151 Files
.delete(tmpFile
.toPath());
2152 } catch (IOException e
) {
2153 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2160 private void retrieveProfileAvatar(
2161 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2162 ) throws IOException
{
2163 File tmpFile
= IOUtils
.createTempFile();
2164 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2167 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2168 avatarStore
.storeProfileAvatar(address
, outputStream
-> {
2169 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2170 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2174 Files
.delete(tmpFile
.toPath());
2175 } catch (IOException e
) {
2176 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2183 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2184 return new File(pathConfig
.getAttachmentsPath(), attachmentId
.toString());
2187 private void retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
{
2188 IOUtils
.createPrivateDirectories(pathConfig
.getAttachmentsPath());
2189 retrieveAttachment(pointer
, getAttachmentFile(pointer
.getRemoteId()));
2192 private void retrieveAttachment(
2193 SignalServiceAttachmentPointer pointer
, File outputFile
2194 ) throws IOException
{
2195 if (pointer
.getPreview().isPresent()) {
2196 File previewFile
= new File(outputFile
+ ".preview");
2197 try (OutputStream output
= new FileOutputStream(previewFile
)) {
2198 byte[] preview
= pointer
.getPreview().get();
2199 output
.write(preview
, 0, preview
.length
);
2200 } catch (FileNotFoundException e
) {
2201 logger
.warn("Failed to retrieve attachment preview, ignoring: {}", e
.getMessage());
2205 try (OutputStream output
= new FileOutputStream(outputFile
)) {
2206 retrieveAttachment(pointer
, output
);
2210 private void retrieveAttachment(
2211 final SignalServiceAttachment attachment
, final OutputStream outputStream
2212 ) throws IOException
{
2213 if (attachment
.isPointer()) {
2214 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2215 retrieveAttachment(pointer
, outputStream
);
2217 SignalServiceAttachmentStream stream
= attachment
.asStream();
2218 AttachmentUtils
.retrieveAttachment(stream
, outputStream
);
2222 private void retrieveAttachment(
2223 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2224 ) throws IOException
{
2225 File tmpFile
= IOUtils
.createTempFile();
2226 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
,
2228 ServiceConfig
.MAX_ATTACHMENT_SIZE
)) {
2229 IOUtils
.copyStream(input
, outputStream
);
2230 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2231 throw new IOException(e
);
2234 Files
.delete(tmpFile
.toPath());
2235 } catch (IOException e
) {
2236 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2243 private InputStream
retrieveAttachmentAsStream(
2244 SignalServiceAttachmentPointer pointer
, File tmpFile
2245 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2246 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2249 void sendGroups() throws IOException
, UntrustedIdentityException
{
2250 File groupsFile
= IOUtils
.createTempFile();
2253 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2254 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2255 for (GroupInfo
record : getGroups()) {
2256 if (record instanceof GroupInfoV1
) {
2257 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2258 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2259 Optional
.fromNullable(groupInfo
.name
),
2260 new ArrayList
<>(groupInfo
.getMembers()),
2261 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2262 groupInfo
.isMember(account
.getSelfAddress()),
2263 Optional
.of(groupInfo
.messageExpirationTime
),
2264 Optional
.fromNullable(groupInfo
.color
),
2266 Optional
.fromNullable(groupInfo
.inboxPosition
),
2267 groupInfo
.archived
));
2272 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2273 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2274 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2275 .withStream(groupsFileStream
)
2276 .withContentType("application/octet-stream")
2277 .withLength(groupsFile
.length())
2280 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2285 Files
.delete(groupsFile
.toPath());
2286 } catch (IOException e
) {
2287 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2292 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2293 File contactsFile
= IOUtils
.createTempFile();
2296 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2297 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2298 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2299 VerifiedMessage verifiedMessage
= null;
2300 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2301 if (currentIdentity
!= null) {
2302 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2303 currentIdentity
.getIdentityKey(),
2304 currentIdentity
.getTrustLevel().toVerifiedState(),
2305 currentIdentity
.getDateAdded().getTime());
2308 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2309 out
.write(new DeviceContact(record.getAddress(),
2310 Optional
.fromNullable(record.name
),
2311 createContactAvatarAttachment(record.getAddress()),
2312 Optional
.fromNullable(record.color
),
2313 Optional
.fromNullable(verifiedMessage
),
2314 Optional
.fromNullable(profileKey
),
2316 Optional
.of(record.messageExpirationTime
),
2317 Optional
.fromNullable(record.inboxPosition
),
2321 if (account
.getProfileKey() != null) {
2322 // Send our own profile key as well
2323 out
.write(new DeviceContact(account
.getSelfAddress(),
2328 Optional
.of(account
.getProfileKey()),
2336 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2337 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2338 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2339 .withStream(contactsFileStream
)
2340 .withContentType("application/octet-stream")
2341 .withLength(contactsFile
.length())
2344 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2349 Files
.delete(contactsFile
.toPath());
2350 } catch (IOException e
) {
2351 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2356 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2357 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2358 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2359 if (record.blocked
) {
2360 addresses
.add(record.getAddress());
2363 List
<byte[]> groupIds
= new ArrayList
<>();
2364 for (GroupInfo
record : getGroups()) {
2365 if (record.isBlocked()) {
2366 groupIds
.add(record.getGroupId().serialize());
2369 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2372 private void sendVerifiedMessage(
2373 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2374 ) throws IOException
, UntrustedIdentityException
{
2375 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2377 trustLevel
.toVerifiedState(),
2378 System
.currentTimeMillis());
2379 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2382 public List
<ContactInfo
> getContacts() {
2383 return account
.getContactStore().getContacts();
2386 public ContactInfo
getContact(String number
) {
2387 return account
.getContactStore().getContact(Utils
.getSignalServiceAddressFromIdentifier(number
));
2390 public GroupInfo
getGroup(GroupId groupId
) {
2391 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2392 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2393 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2394 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2395 account
.getGroupStore().updateGroup(group
);
2400 public List
<IdentityInfo
> getIdentities() {
2401 return account
.getSignalProtocolStore().getIdentities();
2404 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2405 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2409 * Trust this the identity with this fingerprint
2411 * @param name username of the identity
2412 * @param fingerprint Fingerprint
2414 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2415 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2416 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2420 for (IdentityInfo id
: ids
) {
2421 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2425 account
.getSignalProtocolStore()
2426 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2428 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2429 } catch (IOException
| UntrustedIdentityException e
) {
2430 e
.printStackTrace();
2439 * Trust this the identity with this safety number
2441 * @param name username of the identity
2442 * @param safetyNumber Safety number
2444 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2445 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2446 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2450 for (IdentityInfo id
: ids
) {
2451 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2455 account
.getSignalProtocolStore()
2456 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2458 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2459 } catch (IOException
| UntrustedIdentityException e
) {
2460 e
.printStackTrace();
2469 * Trust all keys of this identity without verification
2471 * @param name username of the identity
2473 public boolean trustIdentityAllKeys(String name
) {
2474 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2475 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2479 for (IdentityInfo id
: ids
) {
2480 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2481 account
.getSignalProtocolStore()
2482 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2484 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2485 } catch (IOException
| UntrustedIdentityException e
) {
2486 e
.printStackTrace();
2494 public String
computeSafetyNumber(
2495 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2497 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2498 account
.getSelfAddress(),
2499 getIdentityKeyPair().getPublicKey(),
2504 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2505 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2507 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2508 return resolveSignalServiceAddress(canonicalizedNumber
);
2511 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2512 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2514 return resolveSignalServiceAddress(address
);
2517 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2518 if (address
.matches(account
.getSelfAddress())) {
2519 return account
.getSelfAddress();
2522 return account
.getRecipientStore().resolveServiceAddress(address
);
2526 public void close() throws IOException
{
2530 void close(boolean closeAccount
) throws IOException
{
2531 if (messagePipe
!= null) {
2532 messagePipe
.shutdown();
2536 if (unidentifiedMessagePipe
!= null) {
2537 unidentifiedMessagePipe
.shutdown();
2538 unidentifiedMessagePipe
= null;
2541 if (closeAccount
&& account
!= null) {
2547 public interface ReceiveMessageHandler
{
2549 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);