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 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1346 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1347 for (SignalServiceAddress address
: recipients
) {
1348 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1349 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1350 messageBuilder
.withExpiration(expirationTime
);
1351 message
= messageBuilder
.build();
1352 if (address
.matches(account
.getSelfAddress())) {
1353 results
.add(sendSelfMessage(message
));
1355 results
.add(sendMessage(address
, message
));
1358 return new Pair
<>(timestamp
, results
);
1361 if (message
!= null && message
.isEndSession()) {
1362 for (SignalServiceAddress recipient
: recipients
) {
1363 handleEndSession(recipient
);
1370 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1371 SignalServiceMessageSender messageSender
= createMessageSender();
1373 SignalServiceAddress recipient
= account
.getSelfAddress();
1375 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1376 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1377 message
.getTimestamp(),
1379 message
.getExpiresInSeconds(),
1380 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1382 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1385 long startTime
= System
.currentTimeMillis();
1386 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1387 return SendMessageResult
.success(recipient
,
1388 unidentifiedAccess
.isPresent(),
1390 System
.currentTimeMillis() - startTime
);
1391 } catch (UntrustedIdentityException e
) {
1392 account
.getSignalProtocolStore()
1393 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1395 TrustLevel
.UNTRUSTED
);
1396 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1400 private SendMessageResult
sendMessage(
1401 SignalServiceAddress address
, SignalServiceDataMessage message
1402 ) throws IOException
{
1403 SignalServiceMessageSender messageSender
= createMessageSender();
1406 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1407 } catch (UntrustedIdentityException e
) {
1408 account
.getSignalProtocolStore()
1409 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1411 TrustLevel
.UNTRUSTED
);
1412 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1416 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1417 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1418 account
.getSignalProtocolStore(),
1419 certificateValidator
);
1421 return cipher
.decrypt(envelope
);
1422 } catch (ProtocolUntrustedIdentityException e
) {
1423 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1424 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1426 account
.getSignalProtocolStore()
1427 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1428 identityException
.getUntrustedIdentity(),
1429 TrustLevel
.UNTRUSTED
);
1430 throw identityException
;
1432 throw new AssertionError(e
);
1436 private void handleEndSession(SignalServiceAddress source
) {
1437 account
.getSignalProtocolStore().deleteAllSessions(source
);
1440 private static int currentTimeDays() {
1441 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
1444 private GroupsV2AuthorizationString
getGroupAuthForToday(
1445 final GroupSecretParams groupSecretParams
1446 ) throws IOException
{
1447 final int today
= currentTimeDays();
1448 // Returns credentials for the next 7 days
1449 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
1450 // TODO cache credentials until they expire
1451 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
1453 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
1456 authCredentialResponse
);
1457 } catch (VerificationFailedException e
) {
1458 throw new IOException(e
);
1462 private List
<HandleAction
> handleSignalServiceDataMessage(
1463 SignalServiceDataMessage message
,
1465 SignalServiceAddress source
,
1466 SignalServiceAddress destination
,
1467 boolean ignoreAttachments
1469 List
<HandleAction
> actions
= new ArrayList
<>();
1470 if (message
.getGroupContext().isPresent()) {
1471 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1472 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1473 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1474 GroupInfo group
= getGroup(groupId
);
1475 if (group
== null || group
instanceof GroupInfoV1
) {
1476 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1477 switch (groupInfo
.getType()) {
1479 if (groupV1
== null) {
1480 groupV1
= new GroupInfoV1(groupId
);
1483 if (groupInfo
.getAvatar().isPresent()) {
1484 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1485 if (avatar
.isPointer()) {
1487 retrieveGroupAvatarAttachment(avatar
.asPointer(), groupV1
.getGroupId());
1488 } catch (IOException e
) {
1489 logger
.warn("Failed to retrieve avatar for group {}, ignoring: {}",
1496 if (groupInfo
.getName().isPresent()) {
1497 groupV1
.name
= groupInfo
.getName().get();
1500 if (groupInfo
.getMembers().isPresent()) {
1501 groupV1
.addMembers(groupInfo
.getMembers()
1504 .map(this::resolveSignalServiceAddress
)
1505 .collect(Collectors
.toSet()));
1508 account
.getGroupStore().updateGroup(groupV1
);
1512 if (groupV1
== null && !isSync
) {
1513 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1517 if (groupV1
!= null) {
1518 groupV1
.removeMember(source
);
1519 account
.getGroupStore().updateGroup(groupV1
);
1524 if (groupV1
!= null && !isSync
) {
1525 actions
.add(new SendGroupUpdateAction(source
, groupV1
.getGroupId()));
1530 // Received a group v1 message for a v2 group
1533 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1534 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1535 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1537 getOrMigrateGroup(groupMasterKey
,
1538 groupContext
.getRevision(),
1539 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1543 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1544 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1545 handleEndSession(conversationPartnerAddress
);
1547 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1548 if (message
.getGroupContext().isPresent()) {
1549 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1550 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1551 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1552 if (group
!= null) {
1553 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1554 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1555 account
.getGroupStore().updateGroup(group
);
1558 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1559 // disappearing message timer already stored in the DecryptedGroup
1561 } else if (conversationPartnerAddress
!= null) {
1562 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1563 if (contact
== null) {
1564 contact
= new ContactInfo(conversationPartnerAddress
);
1566 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1567 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1568 account
.getContactStore().updateContact(contact
);
1572 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1573 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1574 if (attachment
.isPointer()) {
1576 retrieveAttachment(attachment
.asPointer());
1577 } catch (IOException e
) {
1578 logger
.warn("Failed to retrieve attachment ({}), ignoring: {}",
1579 attachment
.asPointer().getRemoteId(),
1585 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1586 final ProfileKey profileKey
;
1588 profileKey
= new ProfileKey(message
.getProfileKey().get());
1589 } catch (InvalidInputException e
) {
1590 throw new AssertionError(e
);
1592 if (source
.matches(account
.getSelfAddress())) {
1593 this.account
.setProfileKey(profileKey
);
1595 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1597 if (message
.getPreviews().isPresent()) {
1598 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1599 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1600 if (preview
.getImage().isPresent() && preview
.getImage().get().isPointer()) {
1601 SignalServiceAttachmentPointer attachment
= preview
.getImage().get().asPointer();
1603 retrieveAttachment(attachment
);
1604 } catch (IOException e
) {
1605 logger
.warn("Failed to retrieve preview image ({}), ignoring: {}",
1606 attachment
.getRemoteId(),
1612 if (message
.getQuote().isPresent()) {
1613 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1615 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1616 final SignalServiceAttachment attachment
= quotedAttachment
.getThumbnail();
1617 if (attachment
!= null && attachment
.isPointer()) {
1619 retrieveAttachment(attachment
.asPointer());
1620 } catch (IOException e
) {
1621 logger
.warn("Failed to retrieve quote attachment thumbnail ({}), ignoring: {}",
1622 attachment
.asPointer().getRemoteId(),
1628 if (message
.getSticker().isPresent()) {
1629 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1630 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1631 if (sticker
== null) {
1632 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1633 account
.getStickerStore().updateSticker(sticker
);
1639 private GroupInfoV2
getOrMigrateGroup(
1640 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1642 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1644 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1645 GroupInfo groupInfo
= getGroup(groupId
);
1646 final GroupInfoV2 groupInfoV2
;
1647 if (groupInfo
instanceof GroupInfoV1
) {
1648 // Received a v2 group message for a v1 group, we need to locally migrate the group
1649 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1650 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1651 logger
.info("Locally migrated group {} to group v2, id: {}",
1652 groupInfo
.getGroupId().toBase64(),
1653 groupInfoV2
.getGroupId().toBase64());
1654 } else if (groupInfo
instanceof GroupInfoV2
) {
1655 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1657 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1660 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1661 DecryptedGroup group
= null;
1662 if (signedGroupChange
!= null
1663 && groupInfoV2
.getGroup() != null
1664 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1665 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1667 if (group
== null) {
1668 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1670 if (group
!= null) {
1671 storeProfileKeysFromMembers(group
);
1672 final String avatar
= group
.getAvatar();
1673 if (avatar
!= null && !avatar
.isEmpty()) {
1675 retrieveGroupAvatar(groupId
, groupSecretParams
, avatar
);
1676 } catch (IOException e
) {
1677 logger
.warn("Failed to download group avatar, ignoring: {}", e
.getMessage());
1681 groupInfoV2
.setGroup(group
);
1682 account
.getGroupStore().updateGroup(groupInfoV2
);
1688 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1689 for (DecryptedMember member
: group
.getMembersList()) {
1690 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1691 member
.getUuid().toByteArray()), null));
1693 account
.getProfileStore()
1694 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1695 } catch (InvalidInputException ignored
) {
1700 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1701 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1702 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1706 private void retryFailedReceivedMessage(
1707 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1709 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1710 if (envelope
== null) {
1713 SignalServiceContent content
= null;
1714 if (!envelope
.isReceipt()) {
1716 content
= decryptMessage(envelope
);
1717 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1719 } catch (Exception er
) {
1720 // All other errors are not recoverable, so delete the cached message
1721 cachedMessage
.delete();
1724 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1725 for (HandleAction action
: actions
) {
1727 action
.execute(this);
1728 } catch (Throwable e
) {
1729 e
.printStackTrace();
1734 handler
.handleMessage(envelope
, content
, null);
1735 cachedMessage
.delete();
1738 public void receiveMessages(
1741 boolean returnOnTimeout
,
1742 boolean ignoreAttachments
,
1743 ReceiveMessageHandler handler
1744 ) throws IOException
{
1745 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1747 Set
<HandleAction
> queuedActions
= null;
1749 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1751 boolean hasCaughtUpWithOldMessages
= false;
1754 SignalServiceEnvelope envelope
;
1755 SignalServiceContent content
= null;
1756 Exception exception
= null;
1757 final CachedMessage
[] cachedMessage
= {null};
1759 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1760 // store message on disk, before acknowledging receipt to the server
1761 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1763 if (result
.isPresent()) {
1764 envelope
= result
.get();
1766 // Received indicator that server queue is empty
1767 hasCaughtUpWithOldMessages
= true;
1769 if (queuedActions
!= null) {
1770 for (HandleAction action
: queuedActions
) {
1772 action
.execute(this);
1773 } catch (Throwable e
) {
1774 e
.printStackTrace();
1778 queuedActions
.clear();
1779 queuedActions
= null;
1782 // Continue to wait another timeout for new messages
1785 } catch (TimeoutException e
) {
1786 if (returnOnTimeout
) return;
1788 } catch (InvalidVersionException e
) {
1789 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1793 if (envelope
.hasSource()) {
1794 // Store uuid if we don't have it already
1795 SignalServiceAddress source
= envelope
.getSourceAddress();
1796 resolveSignalServiceAddress(source
);
1798 if (!envelope
.isReceipt()) {
1800 content
= decryptMessage(envelope
);
1801 } catch (Exception e
) {
1804 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1805 if (hasCaughtUpWithOldMessages
) {
1806 for (HandleAction action
: actions
) {
1808 action
.execute(this);
1809 } catch (Throwable e
) {
1810 e
.printStackTrace();
1814 if (queuedActions
== null) {
1815 queuedActions
= new HashSet
<>();
1817 queuedActions
.addAll(actions
);
1821 if (isMessageBlocked(envelope
, content
)) {
1822 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1823 } else if (isNotAGroupMember(envelope
, content
)) {
1824 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1826 handler
.handleMessage(envelope
, content
, exception
);
1828 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1829 if (cachedMessage
[0] != null) {
1830 cachedMessage
[0].delete();
1836 private boolean isMessageBlocked(
1837 SignalServiceEnvelope envelope
, SignalServiceContent content
1839 SignalServiceAddress source
;
1840 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1841 source
= envelope
.getSourceAddress();
1842 } else if (content
!= null) {
1843 source
= content
.getSender();
1847 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1848 if (sourceContact
!= null && sourceContact
.blocked
) {
1852 if (content
!= null && content
.getDataMessage().isPresent()) {
1853 SignalServiceDataMessage message
= content
.getDataMessage().get();
1854 if (message
.getGroupContext().isPresent()) {
1855 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1856 GroupInfo group
= getGroup(groupId
);
1857 if (group
!= null && group
.isBlocked()) {
1865 private boolean isNotAGroupMember(
1866 SignalServiceEnvelope envelope
, SignalServiceContent content
1868 SignalServiceAddress source
;
1869 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1870 source
= envelope
.getSourceAddress();
1871 } else if (content
!= null) {
1872 source
= content
.getSender();
1877 if (content
!= null && content
.getDataMessage().isPresent()) {
1878 SignalServiceDataMessage message
= content
.getDataMessage().get();
1879 if (message
.getGroupContext().isPresent()) {
1880 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1881 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1882 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1886 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1887 GroupInfo group
= getGroup(groupId
);
1888 if (group
!= null && !group
.isMember(source
)) {
1896 private List
<HandleAction
> handleMessage(
1897 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1899 List
<HandleAction
> actions
= new ArrayList
<>();
1900 if (content
!= null) {
1901 final SignalServiceAddress sender
;
1902 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1903 sender
= envelope
.getSourceAddress();
1905 sender
= content
.getSender();
1907 // Store uuid if we don't have it already
1908 resolveSignalServiceAddress(sender
);
1910 if (content
.getDataMessage().isPresent()) {
1911 SignalServiceDataMessage message
= content
.getDataMessage().get();
1913 if (content
.isNeedsReceipt()) {
1914 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1917 actions
.addAll(handleSignalServiceDataMessage(message
,
1920 account
.getSelfAddress(),
1921 ignoreAttachments
));
1923 if (content
.getSyncMessage().isPresent()) {
1924 account
.setMultiDevice(true);
1925 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1926 if (syncMessage
.getSent().isPresent()) {
1927 SentTranscriptMessage message
= syncMessage
.getSent().get();
1928 final SignalServiceAddress destination
= message
.getDestination().orNull();
1929 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1933 ignoreAttachments
));
1935 if (syncMessage
.getRequest().isPresent()) {
1936 RequestMessage rm
= syncMessage
.getRequest().get();
1937 if (rm
.isContactsRequest()) {
1938 actions
.add(SendSyncContactsAction
.create());
1940 if (rm
.isGroupsRequest()) {
1941 actions
.add(SendSyncGroupsAction
.create());
1943 if (rm
.isBlockedListRequest()) {
1944 actions
.add(SendSyncBlockedListAction
.create());
1946 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1948 if (syncMessage
.getGroups().isPresent()) {
1949 File tmpFile
= null;
1951 tmpFile
= IOUtils
.createTempFile();
1952 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups()
1954 .asPointer(), tmpFile
)) {
1955 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1957 while ((g
= s
.read()) != null) {
1958 GroupInfoV1 syncGroup
= account
.getGroupStore()
1959 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1960 if (syncGroup
!= null) {
1961 if (g
.getName().isPresent()) {
1962 syncGroup
.name
= g
.getName().get();
1964 syncGroup
.addMembers(g
.getMembers()
1966 .map(this::resolveSignalServiceAddress
)
1967 .collect(Collectors
.toSet()));
1968 if (!g
.isActive()) {
1969 syncGroup
.removeMember(account
.getSelfAddress());
1971 // Add ourself to the member set as it's marked as active
1972 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1974 syncGroup
.blocked
= g
.isBlocked();
1975 if (g
.getColor().isPresent()) {
1976 syncGroup
.color
= g
.getColor().get();
1979 if (g
.getAvatar().isPresent()) {
1980 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.getGroupId());
1982 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1983 syncGroup
.archived
= g
.isArchived();
1984 account
.getGroupStore().updateGroup(syncGroup
);
1988 } catch (Exception e
) {
1989 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1992 e
.printStackTrace();
1994 if (tmpFile
!= null) {
1996 Files
.delete(tmpFile
.toPath());
1997 } catch (IOException e
) {
1998 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2005 if (syncMessage
.getBlockedList().isPresent()) {
2006 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
2007 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
2008 setContactBlocked(resolveSignalServiceAddress(address
), true);
2010 for (GroupId groupId
: blockedListMessage
.getGroupIds()
2012 .map(GroupId
::unknownVersion
)
2013 .collect(Collectors
.toSet())) {
2015 setGroupBlocked(groupId
, true);
2016 } catch (GroupNotFoundException e
) {
2017 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2018 groupId
.toBase64());
2022 if (syncMessage
.getContacts().isPresent()) {
2023 File tmpFile
= null;
2025 tmpFile
= IOUtils
.createTempFile();
2026 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
2027 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2028 .asPointer(), tmpFile
)) {
2029 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
2030 if (contactsMessage
.isComplete()) {
2031 account
.getContactStore().clear();
2034 while ((c
= s
.read()) != null) {
2035 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2036 account
.setProfileKey(c
.getProfileKey().get());
2038 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
2039 ContactInfo contact
= account
.getContactStore().getContact(address
);
2040 if (contact
== null) {
2041 contact
= new ContactInfo(address
);
2043 if (c
.getName().isPresent()) {
2044 contact
.name
= c
.getName().get();
2046 if (c
.getColor().isPresent()) {
2047 contact
.color
= c
.getColor().get();
2049 if (c
.getProfileKey().isPresent()) {
2050 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
2052 if (c
.getVerified().isPresent()) {
2053 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
2054 account
.getSignalProtocolStore()
2055 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
2056 verifiedMessage
.getIdentityKey(),
2057 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2059 if (c
.getExpirationTimer().isPresent()) {
2060 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
2062 contact
.blocked
= c
.isBlocked();
2063 contact
.inboxPosition
= c
.getInboxPosition().orNull();
2064 contact
.archived
= c
.isArchived();
2065 account
.getContactStore().updateContact(contact
);
2067 if (c
.getAvatar().isPresent()) {
2068 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.getAddress());
2072 } catch (Exception e
) {
2073 e
.printStackTrace();
2075 if (tmpFile
!= null) {
2077 Files
.delete(tmpFile
.toPath());
2078 } catch (IOException e
) {
2079 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2086 if (syncMessage
.getVerified().isPresent()) {
2087 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
2088 account
.getSignalProtocolStore()
2089 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2090 verifiedMessage
.getIdentityKey(),
2091 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2093 if (syncMessage
.getStickerPackOperations().isPresent()) {
2094 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
2096 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
2097 if (!m
.getPackId().isPresent()) {
2100 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2101 if (sticker
== null) {
2102 if (!m
.getPackKey().isPresent()) {
2105 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2107 sticker
.setInstalled(!m
.getType().isPresent()
2108 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2109 account
.getStickerStore().updateSticker(sticker
);
2112 if (syncMessage
.getConfiguration().isPresent()) {
2120 private void retrieveContactAvatarAttachment(
2121 SignalServiceAttachment attachment
, SignalServiceAddress address
2122 ) throws IOException
{
2123 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(attachment
, outputStream
));
2126 private void retrieveGroupAvatarAttachment(
2127 SignalServiceAttachment attachment
, GroupId groupId
2128 ) throws IOException
{
2129 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(attachment
, outputStream
));
2132 private void retrieveGroupAvatar(
2133 GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
2134 ) throws IOException
{
2135 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2137 File tmpFile
= IOUtils
.createTempFile();
2138 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2140 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2141 byte[] encryptedData
= IOUtils
.readFully(input
);
2143 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2144 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> outputStream
.write(decryptedData
));
2147 Files
.delete(tmpFile
.toPath());
2148 } catch (IOException e
) {
2149 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2156 private void retrieveProfileAvatar(
2157 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2158 ) throws IOException
{
2159 File tmpFile
= IOUtils
.createTempFile();
2160 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2163 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2164 avatarStore
.storeProfileAvatar(address
, outputStream
-> {
2165 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2166 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2170 Files
.delete(tmpFile
.toPath());
2171 } catch (IOException e
) {
2172 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2179 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2180 return new File(pathConfig
.getAttachmentsPath(), attachmentId
.toString());
2183 private void retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
{
2184 IOUtils
.createPrivateDirectories(pathConfig
.getAttachmentsPath());
2185 retrieveAttachment(pointer
, getAttachmentFile(pointer
.getRemoteId()));
2188 private void retrieveAttachment(
2189 SignalServiceAttachmentPointer pointer
, File outputFile
2190 ) throws IOException
{
2191 if (pointer
.getPreview().isPresent()) {
2192 File previewFile
= new File(outputFile
+ ".preview");
2193 try (OutputStream output
= new FileOutputStream(previewFile
)) {
2194 byte[] preview
= pointer
.getPreview().get();
2195 output
.write(preview
, 0, preview
.length
);
2196 } catch (FileNotFoundException e
) {
2197 logger
.warn("Failed to retrieve attachment preview, ignoring: {}", e
.getMessage());
2201 try (OutputStream output
= new FileOutputStream(outputFile
)) {
2202 retrieveAttachment(pointer
, output
);
2206 private void retrieveAttachment(
2207 final SignalServiceAttachment attachment
, final OutputStream outputStream
2208 ) throws IOException
{
2209 if (attachment
.isPointer()) {
2210 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2211 retrieveAttachment(pointer
, outputStream
);
2213 SignalServiceAttachmentStream stream
= attachment
.asStream();
2214 AttachmentUtils
.retrieveAttachment(stream
, outputStream
);
2218 private void retrieveAttachment(
2219 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2220 ) throws IOException
{
2221 File tmpFile
= IOUtils
.createTempFile();
2222 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
,
2224 ServiceConfig
.MAX_ATTACHMENT_SIZE
)) {
2225 IOUtils
.copyStream(input
, outputStream
);
2226 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2227 throw new IOException(e
);
2230 Files
.delete(tmpFile
.toPath());
2231 } catch (IOException e
) {
2232 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2239 private InputStream
retrieveAttachmentAsStream(
2240 SignalServiceAttachmentPointer pointer
, File tmpFile
2241 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2242 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2245 void sendGroups() throws IOException
, UntrustedIdentityException
{
2246 File groupsFile
= IOUtils
.createTempFile();
2249 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2250 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2251 for (GroupInfo
record : getGroups()) {
2252 if (record instanceof GroupInfoV1
) {
2253 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2254 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2255 Optional
.fromNullable(groupInfo
.name
),
2256 new ArrayList
<>(groupInfo
.getMembers()),
2257 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2258 groupInfo
.isMember(account
.getSelfAddress()),
2259 Optional
.of(groupInfo
.messageExpirationTime
),
2260 Optional
.fromNullable(groupInfo
.color
),
2262 Optional
.fromNullable(groupInfo
.inboxPosition
),
2263 groupInfo
.archived
));
2268 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2269 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2270 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2271 .withStream(groupsFileStream
)
2272 .withContentType("application/octet-stream")
2273 .withLength(groupsFile
.length())
2276 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2281 Files
.delete(groupsFile
.toPath());
2282 } catch (IOException e
) {
2283 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2288 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2289 File contactsFile
= IOUtils
.createTempFile();
2292 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2293 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2294 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2295 VerifiedMessage verifiedMessage
= null;
2296 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2297 if (currentIdentity
!= null) {
2298 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2299 currentIdentity
.getIdentityKey(),
2300 currentIdentity
.getTrustLevel().toVerifiedState(),
2301 currentIdentity
.getDateAdded().getTime());
2304 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2305 out
.write(new DeviceContact(record.getAddress(),
2306 Optional
.fromNullable(record.name
),
2307 createContactAvatarAttachment(record.getAddress()),
2308 Optional
.fromNullable(record.color
),
2309 Optional
.fromNullable(verifiedMessage
),
2310 Optional
.fromNullable(profileKey
),
2312 Optional
.of(record.messageExpirationTime
),
2313 Optional
.fromNullable(record.inboxPosition
),
2317 if (account
.getProfileKey() != null) {
2318 // Send our own profile key as well
2319 out
.write(new DeviceContact(account
.getSelfAddress(),
2324 Optional
.of(account
.getProfileKey()),
2332 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2333 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2334 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2335 .withStream(contactsFileStream
)
2336 .withContentType("application/octet-stream")
2337 .withLength(contactsFile
.length())
2340 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2345 Files
.delete(contactsFile
.toPath());
2346 } catch (IOException e
) {
2347 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2352 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2353 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2354 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2355 if (record.blocked
) {
2356 addresses
.add(record.getAddress());
2359 List
<byte[]> groupIds
= new ArrayList
<>();
2360 for (GroupInfo
record : getGroups()) {
2361 if (record.isBlocked()) {
2362 groupIds
.add(record.getGroupId().serialize());
2365 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2368 private void sendVerifiedMessage(
2369 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2370 ) throws IOException
, UntrustedIdentityException
{
2371 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2373 trustLevel
.toVerifiedState(),
2374 System
.currentTimeMillis());
2375 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2378 public List
<ContactInfo
> getContacts() {
2379 return account
.getContactStore().getContacts();
2382 public ContactInfo
getContact(String number
) {
2383 return account
.getContactStore().getContact(Utils
.getSignalServiceAddressFromIdentifier(number
));
2386 public GroupInfo
getGroup(GroupId groupId
) {
2387 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2388 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2389 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2390 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2391 account
.getGroupStore().updateGroup(group
);
2396 public List
<IdentityInfo
> getIdentities() {
2397 return account
.getSignalProtocolStore().getIdentities();
2400 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2401 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2405 * Trust this the identity with this fingerprint
2407 * @param name username of the identity
2408 * @param fingerprint Fingerprint
2410 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2411 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2412 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2416 for (IdentityInfo id
: ids
) {
2417 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2421 account
.getSignalProtocolStore()
2422 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2424 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2425 } catch (IOException
| UntrustedIdentityException e
) {
2426 e
.printStackTrace();
2435 * Trust this the identity with this safety number
2437 * @param name username of the identity
2438 * @param safetyNumber Safety number
2440 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2441 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2442 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2446 for (IdentityInfo id
: ids
) {
2447 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2451 account
.getSignalProtocolStore()
2452 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2454 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2455 } catch (IOException
| UntrustedIdentityException e
) {
2456 e
.printStackTrace();
2465 * Trust all keys of this identity without verification
2467 * @param name username of the identity
2469 public boolean trustIdentityAllKeys(String name
) {
2470 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2471 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2475 for (IdentityInfo id
: ids
) {
2476 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2477 account
.getSignalProtocolStore()
2478 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2480 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2481 } catch (IOException
| UntrustedIdentityException e
) {
2482 e
.printStackTrace();
2490 public String
computeSafetyNumber(
2491 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2493 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2494 account
.getSelfAddress(),
2495 getIdentityKeyPair().getPublicKey(),
2500 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2501 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2503 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2504 return resolveSignalServiceAddress(canonicalizedNumber
);
2507 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2508 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2510 return resolveSignalServiceAddress(address
);
2513 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2514 if (address
.matches(account
.getSelfAddress())) {
2515 return account
.getSelfAddress();
2518 return account
.getRecipientStore().resolveServiceAddress(address
);
2522 public void close() throws IOException
{
2526 void close(boolean closeAccount
) throws IOException
{
2527 if (messagePipe
!= null) {
2528 messagePipe
.shutdown();
2532 if (unidentifiedMessagePipe
!= null) {
2533 unidentifiedMessagePipe
.shutdown();
2534 unidentifiedMessagePipe
= null;
2537 if (closeAccount
&& account
!= null) {
2543 public interface ReceiveMessageHandler
{
2545 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);