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
.FileOutputStream
;
150 import java
.io
.IOException
;
151 import java
.io
.InputStream
;
152 import java
.io
.OutputStream
;
154 import java
.net
.URISyntaxException
;
155 import java
.net
.URLEncoder
;
156 import java
.nio
.charset
.StandardCharsets
;
157 import java
.nio
.file
.Files
;
158 import java
.security
.SignatureException
;
159 import java
.util
.ArrayList
;
160 import java
.util
.Arrays
;
161 import java
.util
.Collection
;
162 import java
.util
.Date
;
163 import java
.util
.HashMap
;
164 import java
.util
.HashSet
;
165 import java
.util
.List
;
166 import java
.util
.Map
;
167 import java
.util
.Set
;
168 import java
.util
.UUID
;
169 import java
.util
.concurrent
.ExecutorService
;
170 import java
.util
.concurrent
.TimeUnit
;
171 import java
.util
.concurrent
.TimeoutException
;
172 import java
.util
.stream
.Collectors
;
173 import java
.util
.zip
.ZipEntry
;
174 import java
.util
.zip
.ZipFile
;
176 import static org
.asamk
.signal
.manager
.ServiceConfig
.CDS_MRENCLAVE
;
177 import static org
.asamk
.signal
.manager
.ServiceConfig
.capabilities
;
178 import static org
.asamk
.signal
.manager
.ServiceConfig
.getIasKeyStore
;
180 public class Manager
implements Closeable
{
182 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
184 private final CertificateValidator certificateValidator
= new CertificateValidator(ServiceConfig
.getUnidentifiedSenderTrustRoot());
186 private final SignalServiceConfiguration serviceConfiguration
;
187 private final String userAgent
;
189 private SignalAccount account
;
190 private final SignalServiceAccountManager accountManager
;
191 private final GroupsV2Api groupsV2Api
;
192 private final GroupsV2Operations groupsV2Operations
;
193 private final SignalServiceMessageReceiver messageReceiver
;
194 private final ClientZkProfileOperations clientZkProfileOperations
;
196 private SignalServiceMessagePipe messagePipe
= null;
197 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
199 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
200 private final ProfileHelper profileHelper
;
201 private final GroupHelper groupHelper
;
202 private final PinHelper pinHelper
;
203 private final AvatarStore avatarStore
;
204 private final AttachmentStore attachmentStore
;
207 SignalAccount account
,
208 PathConfig pathConfig
,
209 SignalServiceConfiguration serviceConfiguration
,
212 this.account
= account
;
213 this.serviceConfiguration
= serviceConfiguration
;
214 this.userAgent
= userAgent
;
215 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
216 serviceConfiguration
)) : null;
217 final SleepTimer timer
= new UptimeSleepTimer();
218 this.accountManager
= new SignalServiceAccountManager(serviceConfiguration
,
219 new DynamicCredentialsProvider(account
.getUuid(),
220 account
.getUsername(),
221 account
.getPassword(),
222 account
.getSignalingKey(),
223 account
.getDeviceId()),
227 this.groupsV2Api
= accountManager
.getGroupsV2Api();
228 final KeyBackupService keyBackupService
= ServiceConfig
.createKeyBackupService(accountManager
);
229 this.pinHelper
= new PinHelper(keyBackupService
);
230 this.clientZkProfileOperations
= capabilities
.isGv2() ? ClientZkOperations
.create(serviceConfiguration
)
231 .getProfileOperations() : null;
232 this.messageReceiver
= new SignalServiceMessageReceiver(serviceConfiguration
,
234 account
.getUsername(),
235 account
.getPassword(),
236 account
.getDeviceId(),
237 account
.getSignalingKey(),
241 clientZkProfileOperations
);
243 this.account
.setResolver(this::resolveSignalServiceAddress
);
245 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
246 account
.getProfileStore()::getProfileKey
,
247 this::getRecipientProfile
,
248 this::getSenderCertificate
);
249 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
250 unidentifiedAccessHelper
::getAccessFor
,
251 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
252 () -> messageReceiver
);
253 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
254 this::getRecipientProfile
,
255 account
::getSelfAddress
,
258 this::getGroupAuthForToday
);
259 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
260 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
263 public String
getUsername() {
264 return account
.getUsername();
267 public SignalServiceAddress
getSelfAddress() {
268 return account
.getSelfAddress();
271 private IdentityKeyPair
getIdentityKeyPair() {
272 return account
.getSignalProtocolStore().getIdentityKeyPair();
275 public int getDeviceId() {
276 return account
.getDeviceId();
279 public static Manager
init(
280 String username
, File settingsPath
, SignalServiceConfiguration serviceConfiguration
, String userAgent
281 ) throws IOException
, NotRegisteredException
{
282 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
284 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
285 throw new NotRegisteredException();
288 SignalAccount account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
290 if (!account
.isRegistered()) {
291 throw new NotRegisteredException();
294 return new Manager(account
, pathConfig
, serviceConfiguration
, userAgent
);
297 public void checkAccountState() throws IOException
{
298 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
302 if (account
.getUuid() == null) {
303 account
.setUuid(accountManager
.getOwnUuid());
306 updateAccountAttributes();
310 * This is used for checking a set of phone numbers for registration on Signal
312 * @param numbers The set of phone number in question
313 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
314 * @throws IOException if its unable to get the contacts to check if they're registered
316 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
317 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
318 List
<ContactTokenDetails
> contactDetails
= this.accountManager
.getContacts(numbers
);
320 Set
<String
> registeredUsers
= contactDetails
.stream()
321 .map(ContactTokenDetails
::getNumber
)
322 .collect(Collectors
.toSet());
324 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
327 public void updateAccountAttributes() throws IOException
{
328 accountManager
.setAccountAttributes(account
.getSignalingKey(),
329 account
.getSignalProtocolStore().getLocalRegistrationId(),
331 // set legacy pin only if no KBS master key is set
332 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
333 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
334 account
.getSelfUnidentifiedAccessKey(),
335 account
.isUnrestrictedUnidentifiedAccess(),
337 account
.isDiscoverableByPhoneNumber());
341 * @param avatar if avatar is null the image from the local avatar store is used (if present),
342 * if it's Optional.absent(), the avatar will be removed
344 public void setProfile(String name
, Optional
<File
> avatar
) throws IOException
{
345 try (final StreamDetails streamDetails
= avatar
== null
346 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
347 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
348 accountManager
.setVersionedProfile(account
.getUuid(), account
.getProfileKey(), name
, streamDetails
);
351 if (avatar
!= null) {
352 if (avatar
.isPresent()) {
353 avatarStore
.storeProfileAvatar(getSelfAddress(),
354 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
356 avatarStore
.deleteProfileAvatar(getSelfAddress());
361 public void unregister() throws IOException
{
362 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
363 // If this is the master device, other users can't send messages to this number anymore.
364 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
365 accountManager
.setGcmId(Optional
.absent());
367 account
.setRegistered(false);
371 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
372 List
<DeviceInfo
> devices
= accountManager
.getDevices();
373 account
.setMultiDevice(devices
.size() > 1);
378 public void removeLinkedDevices(int deviceId
) throws IOException
{
379 accountManager
.removeDevice(deviceId
);
380 List
<DeviceInfo
> devices
= accountManager
.getDevices();
381 account
.setMultiDevice(devices
.size() > 1);
385 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
386 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
388 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
391 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
392 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
393 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
395 accountManager
.addDevice(deviceIdentifier
,
398 Optional
.of(account
.getProfileKey().serialize()),
400 account
.setMultiDevice(true);
404 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
405 if (pin
.isPresent()) {
406 final MasterKey masterKey
= account
.getPinMasterKey() != null
407 ? account
.getPinMasterKey()
408 : KeyUtils
.createMasterKey();
410 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
412 account
.setRegistrationLockPin(pin
.get());
413 account
.setPinMasterKey(masterKey
);
415 // Remove legacy registration lock
416 accountManager
.removeRegistrationLockV1();
419 pinHelper
.removeRegistrationLockPin();
421 account
.setRegistrationLockPin(null);
422 account
.setPinMasterKey(null);
427 void refreshPreKeys() throws IOException
{
428 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
429 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
430 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
432 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
435 private List
<PreKeyRecord
> generatePreKeys() {
436 final int offset
= account
.getPreKeyIdOffset();
438 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
439 account
.addPreKeys(records
);
445 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
446 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
448 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
449 account
.addSignedPreKey(record);
455 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
456 if (messagePipe
== null) {
457 messagePipe
= messageReceiver
.createMessagePipe();
462 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
463 if (unidentifiedMessagePipe
== null) {
464 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
466 return unidentifiedMessagePipe
;
469 private SignalServiceMessageSender
createMessageSender() {
470 final ExecutorService executor
= null;
471 return new SignalServiceMessageSender(serviceConfiguration
,
473 account
.getUsername(),
474 account
.getPassword(),
475 account
.getDeviceId(),
476 account
.getSignalProtocolStore(),
478 account
.isMultiDevice(),
479 Optional
.fromNullable(messagePipe
),
480 Optional
.fromNullable(unidentifiedMessagePipe
),
482 clientZkProfileOperations
,
484 ServiceConfig
.MAX_ENVELOPE_SIZE
);
487 private SignalProfile
getRecipientProfile(
488 SignalServiceAddress address
490 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
491 if (profileEntry
== null) {
494 long now
= new Date().getTime();
495 // Profiles are cache for 24h before retrieving them again
496 if (!profileEntry
.isRequestPending() && (
497 profileEntry
.getProfile() == null || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
499 profileEntry
.setRequestPending(true);
500 final SignalServiceProfile encryptedProfile
;
502 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
504 } catch (IOException e
) {
505 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
508 profileEntry
.setRequestPending(false);
511 ProfileKey profileKey
= profileEntry
.getProfileKey();
512 SignalProfile profile
= decryptProfile(address
, profileKey
, encryptedProfile
);
513 account
.getProfileStore()
514 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
517 return profileEntry
.getProfile();
520 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
521 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
522 if (profileEntry
== null) {
525 if (profileEntry
.getProfileKeyCredential() == null) {
526 ProfileAndCredential profileAndCredential
;
528 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
529 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
530 } catch (IOException e
) {
531 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
535 long now
= new Date().getTime();
536 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
537 final SignalProfile profile
= decryptProfile(address
,
538 profileEntry
.getProfileKey(),
539 profileAndCredential
.getProfile());
540 account
.getProfileStore()
541 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
542 return profileKeyCredential
;
544 return profileEntry
.getProfileKeyCredential();
547 private SignalProfile
decryptProfile(
548 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
550 if (encryptedProfile
.getAvatar() != null) {
551 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
554 ProfileCipher profileCipher
= new ProfileCipher(profileKey
);
558 name
= encryptedProfile
.getName() == null
560 : new String(profileCipher
.decryptName(Base64
.decode(encryptedProfile
.getName())));
561 } catch (IOException e
) {
564 String unidentifiedAccess
;
566 unidentifiedAccess
= encryptedProfile
.getUnidentifiedAccess() == null
567 || !profileCipher
.verifyUnidentifiedAccess(Base64
.decode(encryptedProfile
.getUnidentifiedAccess()))
569 : encryptedProfile
.getUnidentifiedAccess();
570 } catch (IOException e
) {
571 unidentifiedAccess
= null;
573 return new SignalProfile(encryptedProfile
.getIdentityKey(),
576 encryptedProfile
.isUnrestrictedUnidentifiedAccess(),
577 encryptedProfile
.getCapabilities());
578 } catch (InvalidCiphertextException e
) {
583 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
584 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
585 if (streamDetails
== null) {
586 return Optional
.absent();
589 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
592 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
593 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
594 if (streamDetails
== null) {
595 return Optional
.absent();
598 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
601 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
602 GroupInfo g
= getGroup(groupId
);
604 throw new GroupNotFoundException(groupId
);
606 if (!g
.isMember(account
.getSelfAddress())) {
607 throw new NotAGroupMemberException(groupId
, g
.getTitle());
612 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
613 GroupInfo g
= getGroup(groupId
);
615 throw new GroupNotFoundException(groupId
);
617 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
618 throw new NotAGroupMemberException(groupId
, g
.getTitle());
623 public List
<GroupInfo
> getGroups() {
624 return account
.getGroupStore().getGroups();
627 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
628 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
629 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
630 final GroupInfo g
= getGroupForSending(groupId
);
632 GroupUtils
.setGroupContext(messageBuilder
, g
);
633 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
635 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
638 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
639 String messageText
, List
<String
> attachments
, GroupId groupId
640 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
641 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
642 .withBody(messageText
);
643 if (attachments
!= null) {
644 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
647 return sendGroupMessage(messageBuilder
, groupId
);
650 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
651 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
652 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
653 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
655 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
656 targetSentTimestamp
);
657 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
658 .withReaction(reaction
);
660 return sendGroupMessage(messageBuilder
, groupId
);
663 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
665 SignalServiceDataMessage
.Builder messageBuilder
;
667 final GroupInfo g
= getGroupForUpdating(groupId
);
668 if (g
instanceof GroupInfoV1
) {
669 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
670 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
671 .withId(groupId
.serialize())
673 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
674 groupInfoV1
.removeMember(account
.getSelfAddress());
675 account
.getGroupStore().updateGroup(groupInfoV1
);
677 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
678 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
679 groupInfoV2
.setGroup(groupGroupChangePair
.first());
680 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
681 account
.getGroupStore().updateGroup(groupInfoV2
);
684 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
687 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
688 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
689 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
691 SignalServiceDataMessage
.Builder messageBuilder
;
692 if (groupId
== null) {
694 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
695 members
== null ? List
.of() : members
,
698 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
699 gv1
.addMembers(List
.of(account
.getSelfAddress()));
700 updateGroupV1(gv1
, name
, members
, avatarFile
);
701 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
704 if (avatarFile
!= null) {
705 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
706 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
708 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
712 GroupInfo group
= getGroupForUpdating(groupId
);
713 if (group
instanceof GroupInfoV2
) {
714 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
716 Pair
<Long
, List
<SendMessageResult
>> result
= null;
717 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
718 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
719 result
= sendUpdateGroupMessage(groupInfoV2
,
720 groupGroupChangePair
.first(),
721 groupGroupChangePair
.second());
724 if (members
!= null) {
725 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
726 newMembers
.removeAll(group
.getMembers()
728 .map(this::resolveSignalServiceAddress
)
729 .collect(Collectors
.toSet()));
730 if (newMembers
.size() > 0) {
731 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
733 result
= sendUpdateGroupMessage(groupInfoV2
,
734 groupGroupChangePair
.first(),
735 groupGroupChangePair
.second());
738 if (result
== null || name
!= null || avatarFile
!= null) {
739 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
742 if (avatarFile
!= null) {
743 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
744 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
746 result
= sendUpdateGroupMessage(groupInfoV2
,
747 groupGroupChangePair
.first(),
748 groupGroupChangePair
.second());
751 return new Pair
<>(group
.getGroupId(), result
.second());
753 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
754 updateGroupV1(gv1
, name
, members
, avatarFile
);
755 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
760 account
.getGroupStore().updateGroup(g
);
762 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
763 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
764 return new Pair
<>(g
.getGroupId(), result
.second());
767 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
768 GroupInviteLinkUrl inviteLinkUrl
769 ) throws IOException
, GroupLinkNotActiveException
{
770 return sendJoinGroupMessage(inviteLinkUrl
);
773 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
774 GroupInviteLinkUrl inviteLinkUrl
775 ) throws IOException
, GroupLinkNotActiveException
{
776 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
777 inviteLinkUrl
.getPassword());
778 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
779 inviteLinkUrl
.getPassword(),
781 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
782 groupJoinInfo
.getRevision() + 1,
783 groupChange
.toByteArray());
785 if (group
.getGroup() == null) {
786 // Only requested member, can't send update to group members
787 return new Pair
<>(group
.getGroupId(), List
.of());
790 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
792 return new Pair
<>(group
.getGroupId(), result
.second());
795 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
796 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
797 ) throws IOException
{
798 group
.setGroup(newDecryptedGroup
);
799 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
800 groupChange
.toByteArray());
801 account
.getGroupStore().updateGroup(group
);
802 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
805 private void updateGroupV1(
808 final Collection
<SignalServiceAddress
> members
,
809 final File avatarFile
810 ) throws IOException
{
815 if (members
!= null) {
816 final Set
<String
> newE164Members
= new HashSet
<>();
817 for (SignalServiceAddress member
: members
) {
818 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
821 newE164Members
.add(member
.getNumber().get());
824 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newE164Members
);
825 if (contacts
.size() != newE164Members
.size()) {
826 // Some of the new members are not registered on Signal
827 for (ContactTokenDetails contact
: contacts
) {
828 newE164Members
.remove(contact
.getNumber());
830 throw new IOException("Failed to add members "
831 + String
.join(", ", newE164Members
)
832 + " to group: Not registered on Signal");
835 g
.addMembers(members
);
838 if (avatarFile
!= null) {
839 avatarStore
.storeGroupAvatar(g
.getGroupId(),
840 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
844 Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
845 GroupIdV1 groupId
, SignalServiceAddress recipient
846 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
848 GroupInfo group
= getGroupForSending(groupId
);
849 if (!(group
instanceof GroupInfoV1
)) {
850 throw new RuntimeException("Received an invalid group request for a v2 group!");
852 g
= (GroupInfoV1
) group
;
854 if (!g
.isMember(recipient
)) {
855 throw new NotAGroupMemberException(groupId
, g
.name
);
858 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
860 // Send group message only to the recipient who requested it
861 return sendMessage(messageBuilder
, List
.of(recipient
));
864 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
865 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
866 .withId(g
.getGroupId().serialize())
868 .withMembers(new ArrayList
<>(g
.getMembers()));
871 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
872 if (attachment
.isPresent()) {
873 group
.withAvatar(attachment
.get());
875 } catch (IOException e
) {
876 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
879 return SignalServiceDataMessage
.newBuilder()
880 .asGroupMessage(group
.build())
881 .withExpiration(g
.getMessageExpirationTime());
884 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
885 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
886 .withRevision(g
.getGroup().getRevision())
887 .withSignedGroupChange(signedGroupChange
);
888 return SignalServiceDataMessage
.newBuilder()
889 .asGroupMessage(group
.build())
890 .withExpiration(g
.getMessageExpirationTime());
893 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
894 GroupIdV1 groupId
, SignalServiceAddress recipient
895 ) throws IOException
{
896 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
897 .withId(groupId
.serialize());
899 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
900 .asGroupMessage(group
.build());
902 // Send group info request message to the recipient who sent us a message with this groupId
903 return sendMessage(messageBuilder
, List
.of(recipient
));
907 SignalServiceAddress remoteAddress
, long messageId
908 ) throws IOException
, UntrustedIdentityException
{
909 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
911 System
.currentTimeMillis());
913 createMessageSender().sendReceipt(remoteAddress
,
914 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
918 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
919 String messageText
, List
<String
> attachments
, List
<String
> recipients
920 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
921 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
922 .withBody(messageText
);
923 if (attachments
!= null) {
924 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
926 // Upload attachments here, so we only upload once even for multiple recipients
927 SignalServiceMessageSender messageSender
= createMessageSender();
928 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
929 for (SignalServiceAttachment attachment
: attachmentStreams
) {
930 if (attachment
.isStream()) {
931 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
932 } else if (attachment
.isPointer()) {
933 attachmentPointers
.add(attachment
.asPointer());
937 messageBuilder
.withAttachments(attachmentPointers
);
939 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
942 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
943 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
944 ) throws IOException
, InvalidNumberException
{
945 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
947 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
948 targetSentTimestamp
);
949 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
950 .withReaction(reaction
);
951 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
954 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
955 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
957 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
959 return sendMessage(messageBuilder
, signalServiceAddresses
);
960 } catch (Exception e
) {
961 for (SignalServiceAddress address
: signalServiceAddresses
) {
962 handleEndSession(address
);
969 public String
getContactName(String number
) throws InvalidNumberException
{
970 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
971 if (contact
== null) {
978 public void setContactName(String number
, String name
) throws InvalidNumberException
{
979 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
980 ContactInfo contact
= account
.getContactStore().getContact(address
);
981 if (contact
== null) {
982 contact
= new ContactInfo(address
);
985 account
.getContactStore().updateContact(contact
);
989 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
990 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
993 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
994 ContactInfo contact
= account
.getContactStore().getContact(address
);
995 if (contact
== null) {
996 contact
= new ContactInfo(address
);
998 contact
.blocked
= blocked
;
999 account
.getContactStore().updateContact(contact
);
1003 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1004 GroupInfo group
= getGroup(groupId
);
1005 if (group
== null) {
1006 throw new GroupNotFoundException(groupId
);
1009 group
.setBlocked(blocked
);
1010 account
.getGroupStore().updateGroup(group
);
1014 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
1015 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
1016 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
1017 return sendUpdateGroupMessage(groupId
,
1019 members
== null ?
null : getSignalServiceAddresses(members
),
1024 * Change the expiration timer for a contact
1026 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1027 ContactInfo contact
= account
.getContactStore().getContact(address
);
1028 contact
.messageExpirationTime
= messageExpirationTimer
;
1029 account
.getContactStore().updateContact(contact
);
1030 sendExpirationTimerUpdate(address
);
1034 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1035 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1036 .asExpirationUpdate();
1037 sendMessage(messageBuilder
, List
.of(address
));
1041 * Change the expiration timer for a contact
1043 public void setExpirationTimer(
1044 String number
, int messageExpirationTimer
1045 ) throws IOException
, InvalidNumberException
{
1046 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1047 setExpirationTimer(address
, messageExpirationTimer
);
1051 * Change the expiration timer for a group
1053 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1054 GroupInfo g
= getGroup(groupId
);
1055 if (g
instanceof GroupInfoV1
) {
1056 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1057 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1058 account
.getGroupStore().updateGroup(groupInfoV1
);
1060 throw new RuntimeException("TODO Not implemented!");
1065 * Upload the sticker pack from path.
1067 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1068 * @return if successful, returns the URL to install the sticker pack in the signal app
1070 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1071 SignalServiceStickerManifestUpload manifest
= getSignalServiceStickerManifestUpload(path
);
1073 SignalServiceMessageSender messageSender
= createMessageSender();
1075 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1076 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1078 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1079 account
.getStickerStore().updateSticker(sticker
);
1083 return new URI("https",
1086 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1087 Hex
.toStringCondensed(packKey
),
1088 StandardCharsets
.UTF_8
)).toString();
1089 } catch (URISyntaxException e
) {
1090 throw new AssertionError(e
);
1094 private SignalServiceStickerManifestUpload
getSignalServiceStickerManifestUpload(
1096 ) throws IOException
, StickerPackInvalidException
{
1098 String rootPath
= null;
1100 if (file
.getName().endsWith(".zip")) {
1101 zip
= new ZipFile(file
);
1102 } else if (file
.getName().equals("manifest.json")) {
1103 rootPath
= file
.getParent();
1105 throw new StickerPackInvalidException("Could not find manifest.json");
1108 JsonStickerPack pack
= parseStickerPack(rootPath
, zip
);
1110 if (pack
.stickers
== null) {
1111 throw new StickerPackInvalidException("Must set a 'stickers' field.");
1114 if (pack
.stickers
.isEmpty()) {
1115 throw new StickerPackInvalidException("Must include stickers.");
1118 List
<StickerInfo
> stickers
= new ArrayList
<>(pack
.stickers
.size());
1119 for (JsonStickerPack
.JsonSticker sticker
: pack
.stickers
) {
1120 if (sticker
.file
== null) {
1121 throw new StickerPackInvalidException("Must set a 'file' field on each sticker.");
1124 Pair
<InputStream
, Long
> data
;
1126 data
= getInputStreamAndLength(rootPath
, zip
, sticker
.file
);
1127 } catch (IOException ignored
) {
1128 throw new StickerPackInvalidException("Could not find find " + sticker
.file
);
1131 String contentType
= Utils
.getFileMimeType(new File(sticker
.file
), null);
1132 StickerInfo stickerInfo
= new StickerInfo(data
.first(),
1134 Optional
.fromNullable(sticker
.emoji
).or(""),
1136 stickers
.add(stickerInfo
);
1139 StickerInfo cover
= null;
1140 if (pack
.cover
!= null) {
1141 if (pack
.cover
.file
== null) {
1142 throw new StickerPackInvalidException("Must set a 'file' field on the cover.");
1145 Pair
<InputStream
, Long
> data
;
1147 data
= getInputStreamAndLength(rootPath
, zip
, pack
.cover
.file
);
1148 } catch (IOException ignored
) {
1149 throw new StickerPackInvalidException("Could not find find " + pack
.cover
.file
);
1152 String contentType
= Utils
.getFileMimeType(new File(pack
.cover
.file
), null);
1153 cover
= new StickerInfo(data
.first(),
1155 Optional
.fromNullable(pack
.cover
.emoji
).or(""),
1159 return new SignalServiceStickerManifestUpload(pack
.title
, pack
.author
, cover
, stickers
);
1162 private static JsonStickerPack
parseStickerPack(String rootPath
, ZipFile zip
) throws IOException
{
1163 InputStream inputStream
;
1165 inputStream
= zip
.getInputStream(zip
.getEntry("manifest.json"));
1167 inputStream
= new FileInputStream((new File(rootPath
, "manifest.json")));
1169 return new ObjectMapper().readValue(inputStream
, JsonStickerPack
.class);
1172 private static Pair
<InputStream
, Long
> getInputStreamAndLength(
1173 final String rootPath
, final ZipFile zip
, final String subfile
1174 ) throws IOException
{
1176 final ZipEntry entry
= zip
.getEntry(subfile
);
1177 return new Pair
<>(zip
.getInputStream(entry
), entry
.getSize());
1179 final File file
= new File(rootPath
, subfile
);
1180 return new Pair
<>(new FileInputStream(file
), file
.length());
1184 void requestSyncGroups() throws IOException
{
1185 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1186 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1188 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1190 sendSyncMessage(message
);
1191 } catch (UntrustedIdentityException e
) {
1192 e
.printStackTrace();
1196 void requestSyncContacts() throws IOException
{
1197 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1198 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1200 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1202 sendSyncMessage(message
);
1203 } catch (UntrustedIdentityException e
) {
1204 e
.printStackTrace();
1208 void requestSyncBlocked() throws IOException
{
1209 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1210 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1212 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1214 sendSyncMessage(message
);
1215 } catch (UntrustedIdentityException e
) {
1216 e
.printStackTrace();
1220 void requestSyncConfiguration() throws IOException
{
1221 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1222 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1224 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1226 sendSyncMessage(message
);
1227 } catch (UntrustedIdentityException e
) {
1228 e
.printStackTrace();
1232 private byte[] getSenderCertificate() {
1233 // TODO support UUID capable sender certificates
1234 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1237 certificate
= accountManager
.getSenderCertificate();
1238 } catch (IOException e
) {
1239 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1242 // TODO cache for a day
1246 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1247 SignalServiceMessageSender messageSender
= createMessageSender();
1249 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1250 } catch (UntrustedIdentityException e
) {
1251 account
.getSignalProtocolStore()
1252 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1254 TrustLevel
.UNTRUSTED
);
1259 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1260 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1261 final Set
<SignalServiceAddress
> missingUuids
= new HashSet
<>();
1263 for (String number
: numbers
) {
1264 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1265 if (resolvedAddress
.getUuid().isPresent()) {
1266 signalServiceAddresses
.add(resolvedAddress
);
1268 missingUuids
.add(resolvedAddress
);
1272 Map
<String
, UUID
> registeredUsers
;
1274 registeredUsers
= accountManager
.getRegisteredUsers(getIasKeyStore(),
1275 missingUuids
.stream().map(a
-> a
.getNumber().get()).collect(Collectors
.toSet()),
1277 } catch (IOException
| Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException e
) {
1278 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1279 registeredUsers
= new HashMap
<>();
1282 for (SignalServiceAddress address
: missingUuids
) {
1283 final String number
= address
.getNumber().get();
1284 if (registeredUsers
.containsKey(number
)) {
1285 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1286 registeredUsers
.get(number
),
1288 signalServiceAddresses
.add(newAddress
);
1290 signalServiceAddresses
.add(address
);
1294 return signalServiceAddresses
;
1297 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1298 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1299 ) throws IOException
{
1300 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1301 final long timestamp
= System
.currentTimeMillis();
1302 messageBuilder
.withTimestamp(timestamp
);
1303 getOrCreateMessagePipe();
1304 getOrCreateUnidentifiedMessagePipe();
1305 SignalServiceDataMessage message
= null;
1307 message
= messageBuilder
.build();
1308 if (message
.getGroupContext().isPresent()) {
1310 SignalServiceMessageSender messageSender
= createMessageSender();
1311 final boolean isRecipientUpdate
= false;
1312 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1313 unidentifiedAccessHelper
.getAccessFor(recipients
),
1316 for (SendMessageResult r
: result
) {
1317 if (r
.getIdentityFailure() != null) {
1318 account
.getSignalProtocolStore()
1319 .saveIdentity(r
.getAddress(),
1320 r
.getIdentityFailure().getIdentityKey(),
1321 TrustLevel
.UNTRUSTED
);
1324 return new Pair
<>(timestamp
, result
);
1325 } catch (UntrustedIdentityException e
) {
1326 account
.getSignalProtocolStore()
1327 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1329 TrustLevel
.UNTRUSTED
);
1330 return new Pair
<>(timestamp
, List
.of());
1333 // Send to all individually, so sync messages are sent correctly
1334 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1335 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1336 for (SignalServiceAddress address
: recipients
) {
1337 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1338 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1339 messageBuilder
.withExpiration(expirationTime
);
1340 message
= messageBuilder
.build();
1341 if (address
.matches(account
.getSelfAddress())) {
1342 results
.add(sendSelfMessage(message
));
1344 results
.add(sendMessage(address
, message
));
1347 return new Pair
<>(timestamp
, results
);
1350 if (message
!= null && message
.isEndSession()) {
1351 for (SignalServiceAddress recipient
: recipients
) {
1352 handleEndSession(recipient
);
1359 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1360 SignalServiceMessageSender messageSender
= createMessageSender();
1362 SignalServiceAddress recipient
= account
.getSelfAddress();
1364 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1365 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1366 message
.getTimestamp(),
1368 message
.getExpiresInSeconds(),
1369 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1371 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1374 long startTime
= System
.currentTimeMillis();
1375 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1376 return SendMessageResult
.success(recipient
,
1377 unidentifiedAccess
.isPresent(),
1379 System
.currentTimeMillis() - startTime
);
1380 } catch (UntrustedIdentityException e
) {
1381 account
.getSignalProtocolStore()
1382 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1384 TrustLevel
.UNTRUSTED
);
1385 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1389 private SendMessageResult
sendMessage(
1390 SignalServiceAddress address
, SignalServiceDataMessage message
1391 ) throws IOException
{
1392 SignalServiceMessageSender messageSender
= createMessageSender();
1395 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1396 } catch (UntrustedIdentityException e
) {
1397 account
.getSignalProtocolStore()
1398 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1400 TrustLevel
.UNTRUSTED
);
1401 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1405 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1406 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1407 account
.getSignalProtocolStore(),
1408 certificateValidator
);
1410 return cipher
.decrypt(envelope
);
1411 } catch (ProtocolUntrustedIdentityException e
) {
1412 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1413 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1415 account
.getSignalProtocolStore()
1416 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1417 identityException
.getUntrustedIdentity(),
1418 TrustLevel
.UNTRUSTED
);
1419 throw identityException
;
1421 throw new AssertionError(e
);
1425 private void handleEndSession(SignalServiceAddress source
) {
1426 account
.getSignalProtocolStore().deleteAllSessions(source
);
1429 private static int currentTimeDays() {
1430 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
1433 private GroupsV2AuthorizationString
getGroupAuthForToday(
1434 final GroupSecretParams groupSecretParams
1435 ) throws IOException
{
1436 final int today
= currentTimeDays();
1437 // Returns credentials for the next 7 days
1438 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
1439 // TODO cache credentials until they expire
1440 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
1442 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
1445 authCredentialResponse
);
1446 } catch (VerificationFailedException e
) {
1447 throw new IOException(e
);
1451 private List
<HandleAction
> handleSignalServiceDataMessage(
1452 SignalServiceDataMessage message
,
1454 SignalServiceAddress source
,
1455 SignalServiceAddress destination
,
1456 boolean ignoreAttachments
1458 List
<HandleAction
> actions
= new ArrayList
<>();
1459 if (message
.getGroupContext().isPresent()) {
1460 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1461 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1462 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1463 GroupInfo group
= getGroup(groupId
);
1464 if (group
== null || group
instanceof GroupInfoV1
) {
1465 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1466 switch (groupInfo
.getType()) {
1468 if (groupV1
== null) {
1469 groupV1
= new GroupInfoV1(groupId
);
1472 if (groupInfo
.getAvatar().isPresent()) {
1473 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1474 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1477 if (groupInfo
.getName().isPresent()) {
1478 groupV1
.name
= groupInfo
.getName().get();
1481 if (groupInfo
.getMembers().isPresent()) {
1482 groupV1
.addMembers(groupInfo
.getMembers()
1485 .map(this::resolveSignalServiceAddress
)
1486 .collect(Collectors
.toSet()));
1489 account
.getGroupStore().updateGroup(groupV1
);
1493 if (groupV1
== null && !isSync
) {
1494 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1498 if (groupV1
!= null) {
1499 groupV1
.removeMember(source
);
1500 account
.getGroupStore().updateGroup(groupV1
);
1505 if (groupV1
!= null && !isSync
) {
1506 actions
.add(new SendGroupUpdateAction(source
, groupV1
.getGroupId()));
1511 // Received a group v1 message for a v2 group
1514 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1515 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1516 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1518 getOrMigrateGroup(groupMasterKey
,
1519 groupContext
.getRevision(),
1520 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1524 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1525 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1526 handleEndSession(conversationPartnerAddress
);
1528 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1529 if (message
.getGroupContext().isPresent()) {
1530 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1531 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1532 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1533 if (group
!= null) {
1534 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1535 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1536 account
.getGroupStore().updateGroup(group
);
1539 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1540 // disappearing message timer already stored in the DecryptedGroup
1542 } else if (conversationPartnerAddress
!= null) {
1543 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1544 if (contact
== null) {
1545 contact
= new ContactInfo(conversationPartnerAddress
);
1547 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1548 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1549 account
.getContactStore().updateContact(contact
);
1553 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1554 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1555 downloadAttachment(attachment
);
1558 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1559 final ProfileKey profileKey
;
1561 profileKey
= new ProfileKey(message
.getProfileKey().get());
1562 } catch (InvalidInputException e
) {
1563 throw new AssertionError(e
);
1565 if (source
.matches(account
.getSelfAddress())) {
1566 this.account
.setProfileKey(profileKey
);
1568 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1570 if (message
.getPreviews().isPresent()) {
1571 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1572 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1573 if (preview
.getImage().isPresent()) {
1574 downloadAttachment(preview
.getImage().get());
1578 if (message
.getQuote().isPresent()) {
1579 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1581 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1582 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1583 if (thumbnail
!= null) {
1584 downloadAttachment(thumbnail
);
1588 if (message
.getSticker().isPresent()) {
1589 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1590 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1591 if (sticker
== null) {
1592 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1593 account
.getStickerStore().updateSticker(sticker
);
1599 private GroupInfoV2
getOrMigrateGroup(
1600 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1602 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1604 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1605 GroupInfo groupInfo
= getGroup(groupId
);
1606 final GroupInfoV2 groupInfoV2
;
1607 if (groupInfo
instanceof GroupInfoV1
) {
1608 // Received a v2 group message for a v1 group, we need to locally migrate the group
1609 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1610 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1611 logger
.info("Locally migrated group {} to group v2, id: {}",
1612 groupInfo
.getGroupId().toBase64(),
1613 groupInfoV2
.getGroupId().toBase64());
1614 } else if (groupInfo
instanceof GroupInfoV2
) {
1615 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1617 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1620 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1621 DecryptedGroup group
= null;
1622 if (signedGroupChange
!= null
1623 && groupInfoV2
.getGroup() != null
1624 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1625 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1627 if (group
== null) {
1628 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1630 if (group
!= null) {
1631 storeProfileKeysFromMembers(group
);
1632 final String avatar
= group
.getAvatar();
1633 if (avatar
!= null && !avatar
.isEmpty()) {
1634 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1637 groupInfoV2
.setGroup(group
);
1638 account
.getGroupStore().updateGroup(groupInfoV2
);
1644 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1645 for (DecryptedMember member
: group
.getMembersList()) {
1646 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1647 member
.getUuid().toByteArray()), null));
1649 account
.getProfileStore()
1650 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1651 } catch (InvalidInputException ignored
) {
1656 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1657 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1658 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1662 private void retryFailedReceivedMessage(
1663 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1665 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1666 if (envelope
== null) {
1669 SignalServiceContent content
= null;
1670 if (!envelope
.isReceipt()) {
1672 content
= decryptMessage(envelope
);
1673 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1675 } catch (Exception er
) {
1676 // All other errors are not recoverable, so delete the cached message
1677 cachedMessage
.delete();
1680 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1681 for (HandleAction action
: actions
) {
1683 action
.execute(this);
1684 } catch (Throwable e
) {
1685 e
.printStackTrace();
1690 handler
.handleMessage(envelope
, content
, null);
1691 cachedMessage
.delete();
1694 public void receiveMessages(
1697 boolean returnOnTimeout
,
1698 boolean ignoreAttachments
,
1699 ReceiveMessageHandler handler
1700 ) throws IOException
{
1701 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1703 Set
<HandleAction
> queuedActions
= null;
1705 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1707 boolean hasCaughtUpWithOldMessages
= false;
1710 SignalServiceEnvelope envelope
;
1711 SignalServiceContent content
= null;
1712 Exception exception
= null;
1713 final CachedMessage
[] cachedMessage
= {null};
1715 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1716 // store message on disk, before acknowledging receipt to the server
1717 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1719 if (result
.isPresent()) {
1720 envelope
= result
.get();
1722 // Received indicator that server queue is empty
1723 hasCaughtUpWithOldMessages
= true;
1725 if (queuedActions
!= null) {
1726 for (HandleAction action
: queuedActions
) {
1728 action
.execute(this);
1729 } catch (Throwable e
) {
1730 e
.printStackTrace();
1734 queuedActions
.clear();
1735 queuedActions
= null;
1738 // Continue to wait another timeout for new messages
1741 } catch (TimeoutException e
) {
1742 if (returnOnTimeout
) return;
1744 } catch (InvalidVersionException e
) {
1745 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1749 if (envelope
.hasSource()) {
1750 // Store uuid if we don't have it already
1751 SignalServiceAddress source
= envelope
.getSourceAddress();
1752 resolveSignalServiceAddress(source
);
1754 if (!envelope
.isReceipt()) {
1756 content
= decryptMessage(envelope
);
1757 } catch (Exception e
) {
1760 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1761 if (hasCaughtUpWithOldMessages
) {
1762 for (HandleAction action
: actions
) {
1764 action
.execute(this);
1765 } catch (Throwable e
) {
1766 e
.printStackTrace();
1770 if (queuedActions
== null) {
1771 queuedActions
= new HashSet
<>();
1773 queuedActions
.addAll(actions
);
1777 if (isMessageBlocked(envelope
, content
)) {
1778 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1779 } else if (isNotAGroupMember(envelope
, content
)) {
1780 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1782 handler
.handleMessage(envelope
, content
, exception
);
1784 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1785 if (cachedMessage
[0] != null) {
1786 cachedMessage
[0].delete();
1792 private boolean isMessageBlocked(
1793 SignalServiceEnvelope envelope
, SignalServiceContent content
1795 SignalServiceAddress source
;
1796 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1797 source
= envelope
.getSourceAddress();
1798 } else if (content
!= null) {
1799 source
= content
.getSender();
1803 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1804 if (sourceContact
!= null && sourceContact
.blocked
) {
1808 if (content
!= null && content
.getDataMessage().isPresent()) {
1809 SignalServiceDataMessage message
= content
.getDataMessage().get();
1810 if (message
.getGroupContext().isPresent()) {
1811 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1812 GroupInfo group
= getGroup(groupId
);
1813 if (group
!= null && group
.isBlocked()) {
1821 private boolean isNotAGroupMember(
1822 SignalServiceEnvelope envelope
, SignalServiceContent content
1824 SignalServiceAddress source
;
1825 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1826 source
= envelope
.getSourceAddress();
1827 } else if (content
!= null) {
1828 source
= content
.getSender();
1833 if (content
!= null && content
.getDataMessage().isPresent()) {
1834 SignalServiceDataMessage message
= content
.getDataMessage().get();
1835 if (message
.getGroupContext().isPresent()) {
1836 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1837 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1838 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1842 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1843 GroupInfo group
= getGroup(groupId
);
1844 if (group
!= null && !group
.isMember(source
)) {
1852 private List
<HandleAction
> handleMessage(
1853 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1855 List
<HandleAction
> actions
= new ArrayList
<>();
1856 if (content
!= null) {
1857 final SignalServiceAddress sender
;
1858 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1859 sender
= envelope
.getSourceAddress();
1861 sender
= content
.getSender();
1863 // Store uuid if we don't have it already
1864 resolveSignalServiceAddress(sender
);
1866 if (content
.getDataMessage().isPresent()) {
1867 SignalServiceDataMessage message
= content
.getDataMessage().get();
1869 if (content
.isNeedsReceipt()) {
1870 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1873 actions
.addAll(handleSignalServiceDataMessage(message
,
1876 account
.getSelfAddress(),
1877 ignoreAttachments
));
1879 if (content
.getSyncMessage().isPresent()) {
1880 account
.setMultiDevice(true);
1881 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1882 if (syncMessage
.getSent().isPresent()) {
1883 SentTranscriptMessage message
= syncMessage
.getSent().get();
1884 final SignalServiceAddress destination
= message
.getDestination().orNull();
1885 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1889 ignoreAttachments
));
1891 if (syncMessage
.getRequest().isPresent()) {
1892 RequestMessage rm
= syncMessage
.getRequest().get();
1893 if (rm
.isContactsRequest()) {
1894 actions
.add(SendSyncContactsAction
.create());
1896 if (rm
.isGroupsRequest()) {
1897 actions
.add(SendSyncGroupsAction
.create());
1899 if (rm
.isBlockedListRequest()) {
1900 actions
.add(SendSyncBlockedListAction
.create());
1902 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1904 if (syncMessage
.getGroups().isPresent()) {
1905 File tmpFile
= null;
1907 tmpFile
= IOUtils
.createTempFile();
1908 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1909 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1911 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1913 while ((g
= s
.read()) != null) {
1914 GroupInfoV1 syncGroup
= account
.getGroupStore()
1915 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1916 if (syncGroup
!= null) {
1917 if (g
.getName().isPresent()) {
1918 syncGroup
.name
= g
.getName().get();
1920 syncGroup
.addMembers(g
.getMembers()
1922 .map(this::resolveSignalServiceAddress
)
1923 .collect(Collectors
.toSet()));
1924 if (!g
.isActive()) {
1925 syncGroup
.removeMember(account
.getSelfAddress());
1927 // Add ourself to the member set as it's marked as active
1928 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1930 syncGroup
.blocked
= g
.isBlocked();
1931 if (g
.getColor().isPresent()) {
1932 syncGroup
.color
= g
.getColor().get();
1935 if (g
.getAvatar().isPresent()) {
1936 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1938 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1939 syncGroup
.archived
= g
.isArchived();
1940 account
.getGroupStore().updateGroup(syncGroup
);
1944 } catch (Exception e
) {
1945 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1948 e
.printStackTrace();
1950 if (tmpFile
!= null) {
1952 Files
.delete(tmpFile
.toPath());
1953 } catch (IOException e
) {
1954 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1961 if (syncMessage
.getBlockedList().isPresent()) {
1962 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1963 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1964 setContactBlocked(resolveSignalServiceAddress(address
), true);
1966 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1968 .map(GroupId
::unknownVersion
)
1969 .collect(Collectors
.toSet())) {
1971 setGroupBlocked(groupId
, true);
1972 } catch (GroupNotFoundException e
) {
1973 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1974 groupId
.toBase64());
1978 if (syncMessage
.getContacts().isPresent()) {
1979 File tmpFile
= null;
1981 tmpFile
= IOUtils
.createTempFile();
1982 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1983 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1984 .asPointer(), tmpFile
)) {
1985 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1986 if (contactsMessage
.isComplete()) {
1987 account
.getContactStore().clear();
1990 while ((c
= s
.read()) != null) {
1991 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1992 account
.setProfileKey(c
.getProfileKey().get());
1994 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1995 ContactInfo contact
= account
.getContactStore().getContact(address
);
1996 if (contact
== null) {
1997 contact
= new ContactInfo(address
);
1999 if (c
.getName().isPresent()) {
2000 contact
.name
= c
.getName().get();
2002 if (c
.getColor().isPresent()) {
2003 contact
.color
= c
.getColor().get();
2005 if (c
.getProfileKey().isPresent()) {
2006 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
2008 if (c
.getVerified().isPresent()) {
2009 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
2010 account
.getSignalProtocolStore()
2011 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
2012 verifiedMessage
.getIdentityKey(),
2013 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2015 if (c
.getExpirationTimer().isPresent()) {
2016 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
2018 contact
.blocked
= c
.isBlocked();
2019 contact
.inboxPosition
= c
.getInboxPosition().orNull();
2020 contact
.archived
= c
.isArchived();
2021 account
.getContactStore().updateContact(contact
);
2023 if (c
.getAvatar().isPresent()) {
2024 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2028 } catch (Exception e
) {
2029 e
.printStackTrace();
2031 if (tmpFile
!= null) {
2033 Files
.delete(tmpFile
.toPath());
2034 } catch (IOException e
) {
2035 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2042 if (syncMessage
.getVerified().isPresent()) {
2043 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
2044 account
.getSignalProtocolStore()
2045 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2046 verifiedMessage
.getIdentityKey(),
2047 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2049 if (syncMessage
.getStickerPackOperations().isPresent()) {
2050 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
2052 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
2053 if (!m
.getPackId().isPresent()) {
2056 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2057 if (sticker
== null) {
2058 if (!m
.getPackKey().isPresent()) {
2061 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2063 sticker
.setInstalled(!m
.getType().isPresent()
2064 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2065 account
.getStickerStore().updateSticker(sticker
);
2068 if (syncMessage
.getConfiguration().isPresent()) {
2076 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2078 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2079 } catch (IOException e
) {
2080 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2084 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2086 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2087 } catch (IOException e
) {
2088 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2092 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2094 avatarStore
.storeGroupAvatar(groupId
,
2095 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2096 } catch (IOException e
) {
2097 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2101 private void downloadProfileAvatar(
2102 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2105 avatarStore
.storeProfileAvatar(address
,
2106 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2107 } catch (Throwable e
) {
2108 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2112 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2113 return attachmentStore
.getAttachmentFile(attachmentId
);
2116 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2117 if (!attachment
.isPointer()) {
2118 logger
.warn("Invalid state, can't store an attachment stream.");
2121 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2122 if (pointer
.getPreview().isPresent()) {
2123 final byte[] preview
= pointer
.getPreview().get();
2125 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2126 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2127 } catch (IOException e
) {
2128 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2133 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2134 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2135 } catch (IOException e
) {
2136 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2140 private void retrieveGroupV2Avatar(
2141 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2142 ) throws IOException
{
2143 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2145 File tmpFile
= IOUtils
.createTempFile();
2146 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2148 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2149 byte[] encryptedData
= IOUtils
.readFully(input
);
2151 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2152 outputStream
.write(decryptedData
);
2155 Files
.delete(tmpFile
.toPath());
2156 } catch (IOException e
) {
2157 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2164 private void retrieveProfileAvatar(
2165 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2166 ) throws IOException
{
2167 File tmpFile
= IOUtils
.createTempFile();
2168 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2171 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2172 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2173 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2176 Files
.delete(tmpFile
.toPath());
2177 } catch (IOException e
) {
2178 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2185 private void retrieveAttachment(
2186 final SignalServiceAttachment attachment
, final OutputStream outputStream
2187 ) throws IOException
{
2188 if (attachment
.isPointer()) {
2189 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2190 retrieveAttachmentPointer(pointer
, outputStream
);
2192 SignalServiceAttachmentStream stream
= attachment
.asStream();
2193 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2197 private void retrieveAttachmentPointer(
2198 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2199 ) throws IOException
{
2200 File tmpFile
= IOUtils
.createTempFile();
2201 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2202 IOUtils
.copyStream(input
, outputStream
);
2203 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2204 throw new IOException(e
);
2207 Files
.delete(tmpFile
.toPath());
2208 } catch (IOException e
) {
2209 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2216 private InputStream
retrieveAttachmentAsStream(
2217 SignalServiceAttachmentPointer pointer
, File tmpFile
2218 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2219 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2222 void sendGroups() throws IOException
, UntrustedIdentityException
{
2223 File groupsFile
= IOUtils
.createTempFile();
2226 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2227 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2228 for (GroupInfo
record : getGroups()) {
2229 if (record instanceof GroupInfoV1
) {
2230 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2231 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2232 Optional
.fromNullable(groupInfo
.name
),
2233 new ArrayList
<>(groupInfo
.getMembers()),
2234 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2235 groupInfo
.isMember(account
.getSelfAddress()),
2236 Optional
.of(groupInfo
.messageExpirationTime
),
2237 Optional
.fromNullable(groupInfo
.color
),
2239 Optional
.fromNullable(groupInfo
.inboxPosition
),
2240 groupInfo
.archived
));
2245 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2246 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2247 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2248 .withStream(groupsFileStream
)
2249 .withContentType("application/octet-stream")
2250 .withLength(groupsFile
.length())
2253 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2258 Files
.delete(groupsFile
.toPath());
2259 } catch (IOException e
) {
2260 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2265 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2266 File contactsFile
= IOUtils
.createTempFile();
2269 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2270 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2271 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2272 VerifiedMessage verifiedMessage
= null;
2273 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2274 if (currentIdentity
!= null) {
2275 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2276 currentIdentity
.getIdentityKey(),
2277 currentIdentity
.getTrustLevel().toVerifiedState(),
2278 currentIdentity
.getDateAdded().getTime());
2281 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2282 out
.write(new DeviceContact(record.getAddress(),
2283 Optional
.fromNullable(record.name
),
2284 createContactAvatarAttachment(record.getAddress()),
2285 Optional
.fromNullable(record.color
),
2286 Optional
.fromNullable(verifiedMessage
),
2287 Optional
.fromNullable(profileKey
),
2289 Optional
.of(record.messageExpirationTime
),
2290 Optional
.fromNullable(record.inboxPosition
),
2294 if (account
.getProfileKey() != null) {
2295 // Send our own profile key as well
2296 out
.write(new DeviceContact(account
.getSelfAddress(),
2301 Optional
.of(account
.getProfileKey()),
2309 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2310 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2311 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2312 .withStream(contactsFileStream
)
2313 .withContentType("application/octet-stream")
2314 .withLength(contactsFile
.length())
2317 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2322 Files
.delete(contactsFile
.toPath());
2323 } catch (IOException e
) {
2324 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2329 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2330 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2331 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2332 if (record.blocked
) {
2333 addresses
.add(record.getAddress());
2336 List
<byte[]> groupIds
= new ArrayList
<>();
2337 for (GroupInfo
record : getGroups()) {
2338 if (record.isBlocked()) {
2339 groupIds
.add(record.getGroupId().serialize());
2342 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2345 private void sendVerifiedMessage(
2346 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2347 ) throws IOException
, UntrustedIdentityException
{
2348 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2350 trustLevel
.toVerifiedState(),
2351 System
.currentTimeMillis());
2352 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2355 public List
<ContactInfo
> getContacts() {
2356 return account
.getContactStore().getContacts();
2359 public ContactInfo
getContact(String number
) {
2360 return account
.getContactStore().getContact(Utils
.getSignalServiceAddressFromIdentifier(number
));
2363 public GroupInfo
getGroup(GroupId groupId
) {
2364 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2365 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2366 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2367 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2368 account
.getGroupStore().updateGroup(group
);
2373 public List
<IdentityInfo
> getIdentities() {
2374 return account
.getSignalProtocolStore().getIdentities();
2377 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2378 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2382 * Trust this the identity with this fingerprint
2384 * @param name username of the identity
2385 * @param fingerprint Fingerprint
2387 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2388 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2389 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2393 for (IdentityInfo id
: ids
) {
2394 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2398 account
.getSignalProtocolStore()
2399 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2401 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2402 } catch (IOException
| UntrustedIdentityException e
) {
2403 e
.printStackTrace();
2412 * Trust this the identity with this safety number
2414 * @param name username of the identity
2415 * @param safetyNumber Safety number
2417 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2418 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2419 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2423 for (IdentityInfo id
: ids
) {
2424 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2428 account
.getSignalProtocolStore()
2429 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2431 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2432 } catch (IOException
| UntrustedIdentityException e
) {
2433 e
.printStackTrace();
2442 * Trust all keys of this identity without verification
2444 * @param name username of the identity
2446 public boolean trustIdentityAllKeys(String name
) {
2447 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2448 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2452 for (IdentityInfo id
: ids
) {
2453 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2454 account
.getSignalProtocolStore()
2455 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2457 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2458 } catch (IOException
| UntrustedIdentityException e
) {
2459 e
.printStackTrace();
2467 public String
computeSafetyNumber(
2468 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2470 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2471 account
.getSelfAddress(),
2472 getIdentityKeyPair().getPublicKey(),
2477 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2478 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2480 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2481 return resolveSignalServiceAddress(canonicalizedNumber
);
2484 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2485 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2487 return resolveSignalServiceAddress(address
);
2490 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2491 if (address
.matches(account
.getSelfAddress())) {
2492 return account
.getSelfAddress();
2495 return account
.getRecipientStore().resolveServiceAddress(address
);
2499 public void close() throws IOException
{
2503 void close(boolean closeAccount
) throws IOException
{
2504 if (messagePipe
!= null) {
2505 messagePipe
.shutdown();
2509 if (unidentifiedMessagePipe
!= null) {
2510 unidentifiedMessagePipe
.shutdown();
2511 unidentifiedMessagePipe
= null;
2514 if (closeAccount
&& account
!= null) {
2520 public interface ReceiveMessageHandler
{
2522 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);