2 Copyright (C) 2015-2021 AsamK and contributors
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
20 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
21 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
22 import org
.asamk
.signal
.manager
.groups
.GroupId
;
23 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
24 import org
.asamk
.signal
.manager
.groups
.GroupIdV2
;
25 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
26 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
27 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
28 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
29 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
30 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
31 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
32 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
33 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
34 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactInfo
;
35 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
36 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
37 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
38 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
39 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfile
;
40 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfileEntry
;
41 import org
.asamk
.signal
.manager
.storage
.protocol
.IdentityInfo
;
42 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
43 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
44 import org
.asamk
.signal
.manager
.util
.IOUtils
;
45 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
46 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
47 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
48 import org
.asamk
.signal
.manager
.util
.Utils
;
49 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
50 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
51 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
52 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
53 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
54 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
56 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
57 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
58 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
59 import org
.signal
.libsignal
.metadata
.SelfSendException
;
60 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
61 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
62 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
63 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroupJoinInfo
;
64 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedMember
;
65 import org
.signal
.zkgroup
.InvalidInputException
;
66 import org
.signal
.zkgroup
.VerificationFailedException
;
67 import org
.signal
.zkgroup
.auth
.AuthCredentialResponse
;
68 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
69 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
70 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
71 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
72 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
73 import org
.slf4j
.Logger
;
74 import org
.slf4j
.LoggerFactory
;
75 import org
.whispersystems
.libsignal
.IdentityKey
;
76 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
77 import org
.whispersystems
.libsignal
.InvalidKeyException
;
78 import org
.whispersystems
.libsignal
.InvalidMessageException
;
79 import org
.whispersystems
.libsignal
.InvalidVersionException
;
80 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
81 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
82 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
83 import org
.whispersystems
.libsignal
.util
.Pair
;
84 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
85 import org
.whispersystems
.signalservice
.api
.KeyBackupService
;
86 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
87 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
88 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
89 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
90 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
91 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
92 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
93 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
94 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
95 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
96 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
97 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
98 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
106 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
107 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
108 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
109 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
110 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceStickerManifestUpload
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.KeysMessage
;
121 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
122 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
123 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
124 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
125 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
126 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
127 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
128 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
129 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
130 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
131 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
132 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
133 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
134 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
135 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
136 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
137 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
138 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
139 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
140 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
141 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
142 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
143 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
144 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
146 import java
.io
.Closeable
;
148 import java
.io
.FileInputStream
;
149 import java
.io
.FileOutputStream
;
150 import java
.io
.IOException
;
151 import java
.io
.InputStream
;
152 import java
.io
.OutputStream
;
154 import java
.net
.URISyntaxException
;
155 import java
.net
.URLEncoder
;
156 import java
.nio
.charset
.StandardCharsets
;
157 import java
.nio
.file
.Files
;
158 import java
.security
.SignatureException
;
159 import java
.util
.ArrayList
;
160 import java
.util
.Arrays
;
161 import java
.util
.Collection
;
162 import java
.util
.Date
;
163 import java
.util
.HashMap
;
164 import java
.util
.HashSet
;
165 import java
.util
.List
;
166 import java
.util
.Map
;
167 import java
.util
.Set
;
168 import java
.util
.UUID
;
169 import java
.util
.concurrent
.ExecutorService
;
170 import java
.util
.concurrent
.TimeUnit
;
171 import java
.util
.concurrent
.TimeoutException
;
172 import java
.util
.stream
.Collectors
;
174 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
176 public class Manager
implements Closeable
{
178 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
180 private final CertificateValidator certificateValidator
;
182 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
183 private final String userAgent
;
185 private SignalAccount account
;
186 private final SignalServiceAccountManager accountManager
;
187 private final GroupsV2Api groupsV2Api
;
188 private final GroupsV2Operations groupsV2Operations
;
189 private final SignalServiceMessageReceiver messageReceiver
;
190 private final ClientZkProfileOperations clientZkProfileOperations
;
192 private SignalServiceMessagePipe messagePipe
= null;
193 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
195 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
196 private final ProfileHelper profileHelper
;
197 private final GroupHelper groupHelper
;
198 private final PinHelper pinHelper
;
199 private final AvatarStore avatarStore
;
200 private final AttachmentStore attachmentStore
;
203 SignalAccount account
,
204 PathConfig pathConfig
,
205 ServiceEnvironmentConfig serviceEnvironmentConfig
,
208 this.account
= account
;
209 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
210 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
211 this.userAgent
= userAgent
;
212 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
213 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
214 final SleepTimer timer
= new UptimeSleepTimer();
215 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
216 new DynamicCredentialsProvider(account
.getUuid(),
217 account
.getUsername(),
218 account
.getPassword(),
219 account
.getSignalingKey(),
220 account
.getDeviceId()),
223 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
225 this.groupsV2Api
= accountManager
.getGroupsV2Api();
226 final KeyBackupService keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
227 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
228 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
229 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
232 this.pinHelper
= new PinHelper(keyBackupService
);
233 this.clientZkProfileOperations
= capabilities
.isGv2()
234 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
235 .getProfileOperations()
237 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
239 account
.getUsername(),
240 account
.getPassword(),
241 account
.getDeviceId(),
242 account
.getSignalingKey(),
246 clientZkProfileOperations
,
247 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
249 this.account
.setResolver(this::resolveSignalServiceAddress
);
251 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
252 account
.getProfileStore()::getProfileKey
,
253 this::getRecipientProfile
,
254 this::getSenderCertificate
);
255 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
256 unidentifiedAccessHelper
::getAccessFor
,
257 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
258 () -> messageReceiver
);
259 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
260 this::getRecipientProfile
,
261 account
::getSelfAddress
,
264 this::getGroupAuthForToday
);
265 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
266 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
269 public String
getUsername() {
270 return account
.getUsername();
273 public SignalServiceAddress
getSelfAddress() {
274 return account
.getSelfAddress();
277 private IdentityKeyPair
getIdentityKeyPair() {
278 return account
.getSignalProtocolStore().getIdentityKeyPair();
281 public int getDeviceId() {
282 return account
.getDeviceId();
285 public static Manager
init(
286 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
287 ) throws IOException
, NotRegisteredException
{
288 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
290 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
291 throw new NotRegisteredException();
294 SignalAccount account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
296 if (!account
.isRegistered()) {
297 throw new NotRegisteredException();
300 final ServiceEnvironmentConfig serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(
304 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
307 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
308 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
309 final File dataPath
= pathConfig
.getDataPath();
310 final File
[] files
= dataPath
.listFiles();
316 return Arrays
.stream(files
)
317 .filter(File
::isFile
)
319 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
320 .collect(Collectors
.toList());
323 public void checkAccountState() throws IOException
{
324 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
328 if (account
.getUuid() == null) {
329 account
.setUuid(accountManager
.getOwnUuid());
332 updateAccountAttributes();
336 * This is used for checking a set of phone numbers for registration on Signal
338 * @param numbers The set of phone number in question
339 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
340 * @throws IOException if its unable to get the contacts to check if they're registered
342 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
343 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
344 Map
<String
, UUID
> contactDetails
= getRegisteredUsers(numbers
);
346 Set
<String
> registeredUsers
= contactDetails
.keySet();
348 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
351 public void updateAccountAttributes() throws IOException
{
352 accountManager
.setAccountAttributes(account
.getSignalingKey(),
353 account
.getSignalProtocolStore().getLocalRegistrationId(),
355 // set legacy pin only if no KBS master key is set
356 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
357 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
358 account
.getSelfUnidentifiedAccessKey(),
359 account
.isUnrestrictedUnidentifiedAccess(),
361 account
.isDiscoverableByPhoneNumber());
365 * @param name if null, the previous name will be kept
366 * @param about if null, the previous about text will be kept
367 * @param aboutEmoji if null, the previous about emoji will be kept
368 * @param avatar if avatar is null the image from the local avatar store is used (if present),
369 * if it's Optional.absent(), the avatar will be removed
371 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
372 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(getSelfAddress());
373 SignalProfile profile
= profileEntry
== null ?
null : profileEntry
.getProfile();
374 SignalProfile newProfile
= new SignalProfile(profile
== null ?
null : profile
.getIdentityKey(),
375 name
!= null ? name
: profile
== null || profile
.getName() == null ?
"" : profile
.getName(),
376 about
!= null ? about
: profile
== null || profile
.getAbout() == null ?
"" : profile
.getAbout(),
379 : profile
== null || profile
.getAboutEmoji() == null ?
"" : profile
.getAboutEmoji(),
380 profile
== null ?
null : profile
.getUnidentifiedAccess(),
381 account
.isUnrestrictedUnidentifiedAccess(),
382 profile
== null ?
null : profile
.getCapabilities());
384 try (final StreamDetails streamDetails
= avatar
== null
385 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
386 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
387 accountManager
.setVersionedProfile(account
.getUuid(),
388 account
.getProfileKey(),
389 newProfile
.getName(),
390 newProfile
.getAbout(),
391 newProfile
.getAboutEmoji(),
395 if (avatar
!= null) {
396 if (avatar
.isPresent()) {
397 avatarStore
.storeProfileAvatar(getSelfAddress(),
398 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
400 avatarStore
.deleteProfileAvatar(getSelfAddress());
403 account
.getProfileStore()
404 .updateProfile(getSelfAddress(),
405 account
.getProfileKey(),
406 System
.currentTimeMillis(),
408 profileEntry
== null ?
null : profileEntry
.getProfileKeyCredential());
411 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
412 } catch (UntrustedIdentityException ignored
) {
416 public void unregister() throws IOException
{
417 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
418 // If this is the master device, other users can't send messages to this number anymore.
419 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
420 accountManager
.setGcmId(Optional
.absent());
421 accountManager
.deleteAccount();
423 account
.setRegistered(false);
427 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
428 List
<DeviceInfo
> devices
= accountManager
.getDevices();
429 account
.setMultiDevice(devices
.size() > 1);
434 public void removeLinkedDevices(int deviceId
) throws IOException
{
435 accountManager
.removeDevice(deviceId
);
436 List
<DeviceInfo
> devices
= accountManager
.getDevices();
437 account
.setMultiDevice(devices
.size() > 1);
441 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
442 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
444 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
447 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
448 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
449 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
451 accountManager
.addDevice(deviceIdentifier
,
454 Optional
.of(account
.getProfileKey().serialize()),
456 account
.setMultiDevice(true);
460 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
461 if (!account
.isMasterDevice()) {
462 throw new RuntimeException("Only master device can set a PIN");
464 if (pin
.isPresent()) {
465 final MasterKey masterKey
= account
.getPinMasterKey() != null
466 ? account
.getPinMasterKey()
467 : KeyUtils
.createMasterKey();
469 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
471 account
.setRegistrationLockPin(pin
.get());
472 account
.setPinMasterKey(masterKey
);
474 // Remove legacy registration lock
475 accountManager
.removeRegistrationLockV1();
478 pinHelper
.removeRegistrationLockPin();
480 account
.setRegistrationLockPin(null);
481 account
.setPinMasterKey(null);
486 void refreshPreKeys() throws IOException
{
487 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
488 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
489 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
491 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
494 private List
<PreKeyRecord
> generatePreKeys() {
495 final int offset
= account
.getPreKeyIdOffset();
497 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
498 account
.addPreKeys(records
);
504 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
505 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
507 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
508 account
.addSignedPreKey(record);
514 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
515 if (messagePipe
== null) {
516 messagePipe
= messageReceiver
.createMessagePipe();
521 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
522 if (unidentifiedMessagePipe
== null) {
523 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
525 return unidentifiedMessagePipe
;
528 private SignalServiceMessageSender
createMessageSender() {
529 final ExecutorService executor
= null;
530 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
532 account
.getUsername(),
533 account
.getPassword(),
534 account
.getDeviceId(),
535 account
.getSignalProtocolStore(),
537 account
.isMultiDevice(),
538 Optional
.fromNullable(messagePipe
),
539 Optional
.fromNullable(unidentifiedMessagePipe
),
541 clientZkProfileOperations
,
543 ServiceConfig
.MAX_ENVELOPE_SIZE
,
544 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
547 private SignalProfile
getRecipientProfile(
548 SignalServiceAddress address
550 return getRecipientProfile(address
, false);
553 private SignalProfile
getRecipientProfile(
554 SignalServiceAddress address
, boolean force
556 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
557 if (profileEntry
== null) {
560 long now
= new Date().getTime();
561 // Profiles are cached for 24h before retrieving them again
562 if (!profileEntry
.isRequestPending() && (
564 || profileEntry
.getProfile() == null
565 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
567 profileEntry
.setRequestPending(true);
568 final SignalServiceProfile encryptedProfile
;
570 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
572 } catch (IOException e
) {
573 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
576 profileEntry
.setRequestPending(false);
579 final ProfileKey profileKey
= profileEntry
.getProfileKey();
580 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
581 account
.getProfileStore()
582 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
585 return profileEntry
.getProfile();
588 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
589 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
590 if (profileEntry
== null) {
593 if (profileEntry
.getProfileKeyCredential() == null) {
594 ProfileAndCredential profileAndCredential
;
596 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
597 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
598 } catch (IOException e
) {
599 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
603 long now
= new Date().getTime();
604 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
605 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
606 profileEntry
.getProfileKey(),
607 profileAndCredential
.getProfile());
608 account
.getProfileStore()
609 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
610 return profileKeyCredential
;
612 return profileEntry
.getProfileKeyCredential();
615 private SignalProfile
decryptProfileAndDownloadAvatar(
616 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
618 if (encryptedProfile
.getAvatar() != null) {
619 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
622 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
625 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
626 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
627 if (streamDetails
== null) {
628 return Optional
.absent();
631 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
634 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
635 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
636 if (streamDetails
== null) {
637 return Optional
.absent();
640 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
643 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
644 GroupInfo g
= getGroup(groupId
);
646 throw new GroupNotFoundException(groupId
);
648 if (!g
.isMember(account
.getSelfAddress())) {
649 throw new NotAGroupMemberException(groupId
, g
.getTitle());
654 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
655 GroupInfo g
= getGroup(groupId
);
657 throw new GroupNotFoundException(groupId
);
659 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
660 throw new NotAGroupMemberException(groupId
, g
.getTitle());
665 public List
<GroupInfo
> getGroups() {
666 return account
.getGroupStore().getGroups();
669 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
670 String messageText
, List
<String
> attachments
, GroupId groupId
671 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
672 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
673 .withBody(messageText
);
674 if (attachments
!= null) {
675 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
678 return sendGroupMessage(messageBuilder
, groupId
);
681 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
682 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
683 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
684 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
686 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
687 targetSentTimestamp
);
688 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
689 .withReaction(reaction
);
691 return sendGroupMessage(messageBuilder
, groupId
);
694 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
695 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
696 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
697 final GroupInfo g
= getGroupForSending(groupId
);
699 GroupUtils
.setGroupContext(messageBuilder
, g
);
700 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
702 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
705 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
706 SignalServiceDataMessage
.Builder messageBuilder
;
708 final GroupInfo g
= getGroupForUpdating(groupId
);
709 if (g
instanceof GroupInfoV1
) {
710 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
711 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
712 .withId(groupId
.serialize())
714 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
715 groupInfoV1
.removeMember(account
.getSelfAddress());
716 account
.getGroupStore().updateGroup(groupInfoV1
);
718 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
719 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
720 groupInfoV2
.setGroup(groupGroupChangePair
.first());
721 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
722 account
.getGroupStore().updateGroup(groupInfoV2
);
725 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
728 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
729 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
730 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
731 return sendUpdateGroupMessage(groupId
,
733 members
== null ?
null : getSignalServiceAddresses(members
),
737 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
738 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
739 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
741 SignalServiceDataMessage
.Builder messageBuilder
;
742 if (groupId
== null) {
744 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
745 members
== null ? List
.of() : members
,
748 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
749 gv1
.addMembers(List
.of(account
.getSelfAddress()));
750 updateGroupV1(gv1
, name
, members
, avatarFile
);
751 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
754 if (avatarFile
!= null) {
755 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
756 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
758 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
762 GroupInfo group
= getGroupForUpdating(groupId
);
763 if (group
instanceof GroupInfoV2
) {
764 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
766 Pair
<Long
, List
<SendMessageResult
>> result
= null;
767 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
768 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
769 result
= sendUpdateGroupMessage(groupInfoV2
,
770 groupGroupChangePair
.first(),
771 groupGroupChangePair
.second());
774 if (members
!= null) {
775 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
776 newMembers
.removeAll(group
.getMembers()
778 .map(this::resolveSignalServiceAddress
)
779 .collect(Collectors
.toSet()));
780 if (newMembers
.size() > 0) {
781 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
783 result
= sendUpdateGroupMessage(groupInfoV2
,
784 groupGroupChangePair
.first(),
785 groupGroupChangePair
.second());
788 if (result
== null || name
!= null || avatarFile
!= null) {
789 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
792 if (avatarFile
!= null) {
793 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
794 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
796 result
= sendUpdateGroupMessage(groupInfoV2
,
797 groupGroupChangePair
.first(),
798 groupGroupChangePair
.second());
801 return new Pair
<>(group
.getGroupId(), result
.second());
803 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
804 updateGroupV1(gv1
, name
, members
, avatarFile
);
805 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
810 account
.getGroupStore().updateGroup(g
);
812 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
813 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
814 return new Pair
<>(g
.getGroupId(), result
.second());
817 private void updateGroupV1(
820 final Collection
<SignalServiceAddress
> members
,
821 final File avatarFile
822 ) throws IOException
{
827 if (members
!= null) {
828 final Set
<String
> newE164Members
= new HashSet
<>();
829 for (SignalServiceAddress member
: members
) {
830 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
833 newE164Members
.add(member
.getNumber().get());
836 final Map
<String
, UUID
> registeredUsers
= getRegisteredUsers(newE164Members
);
837 if (registeredUsers
.size() != newE164Members
.size()) {
838 // Some of the new members are not registered on Signal
839 newE164Members
.removeAll(registeredUsers
.keySet());
840 throw new IOException("Failed to add members "
841 + String
.join(", ", newE164Members
)
842 + " to group: Not registered on Signal");
845 g
.addMembers(members
);
848 if (avatarFile
!= null) {
849 avatarStore
.storeGroupAvatar(g
.getGroupId(),
850 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
854 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
855 GroupInviteLinkUrl inviteLinkUrl
856 ) throws IOException
, GroupLinkNotActiveException
{
857 return sendJoinGroupMessage(inviteLinkUrl
);
860 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
861 GroupInviteLinkUrl inviteLinkUrl
862 ) throws IOException
, GroupLinkNotActiveException
{
863 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
864 inviteLinkUrl
.getPassword());
865 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
866 inviteLinkUrl
.getPassword(),
868 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
869 groupJoinInfo
.getRevision() + 1,
870 groupChange
.toByteArray());
872 if (group
.getGroup() == null) {
873 // Only requested member, can't send update to group members
874 return new Pair
<>(group
.getGroupId(), List
.of());
877 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
879 return new Pair
<>(group
.getGroupId(), result
.second());
882 private static int currentTimeDays() {
883 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
886 private GroupsV2AuthorizationString
getGroupAuthForToday(
887 final GroupSecretParams groupSecretParams
888 ) throws IOException
{
889 final int today
= currentTimeDays();
890 // Returns credentials for the next 7 days
891 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
892 // TODO cache credentials until they expire
893 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
895 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
898 authCredentialResponse
);
899 } catch (VerificationFailedException e
) {
900 throw new IOException(e
);
904 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
905 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
906 ) throws IOException
{
907 group
.setGroup(newDecryptedGroup
);
908 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
909 groupChange
.toByteArray());
910 account
.getGroupStore().updateGroup(group
);
911 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
914 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
915 GroupIdV1 groupId
, SignalServiceAddress recipient
916 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
918 GroupInfo group
= getGroupForSending(groupId
);
919 if (!(group
instanceof GroupInfoV1
)) {
920 throw new RuntimeException("Received an invalid group request for a v2 group!");
922 g
= (GroupInfoV1
) group
;
924 if (!g
.isMember(recipient
)) {
925 throw new NotAGroupMemberException(groupId
, g
.name
);
928 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
930 // Send group message only to the recipient who requested it
931 return sendMessage(messageBuilder
, List
.of(recipient
));
934 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
935 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
936 .withId(g
.getGroupId().serialize())
938 .withMembers(new ArrayList
<>(g
.getMembers()));
941 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
942 if (attachment
.isPresent()) {
943 group
.withAvatar(attachment
.get());
945 } catch (IOException e
) {
946 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
949 return SignalServiceDataMessage
.newBuilder()
950 .asGroupMessage(group
.build())
951 .withExpiration(g
.getMessageExpirationTime());
954 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
955 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
956 .withRevision(g
.getGroup().getRevision())
957 .withSignedGroupChange(signedGroupChange
);
958 return SignalServiceDataMessage
.newBuilder()
959 .asGroupMessage(group
.build())
960 .withExpiration(g
.getMessageExpirationTime());
963 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
964 GroupIdV1 groupId
, SignalServiceAddress recipient
965 ) throws IOException
{
966 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
967 .withId(groupId
.serialize());
969 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
970 .asGroupMessage(group
.build());
972 // Send group info request message to the recipient who sent us a message with this groupId
973 return sendMessage(messageBuilder
, List
.of(recipient
));
977 SignalServiceAddress remoteAddress
, long messageId
978 ) throws IOException
, UntrustedIdentityException
{
979 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
981 System
.currentTimeMillis());
983 createMessageSender().sendReceipt(remoteAddress
,
984 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
988 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
989 String messageText
, List
<String
> attachments
, List
<String
> recipients
990 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
991 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
992 .withBody(messageText
);
993 if (attachments
!= null) {
994 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
996 // Upload attachments here, so we only upload once even for multiple recipients
997 SignalServiceMessageSender messageSender
= createMessageSender();
998 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
999 for (SignalServiceAttachment attachment
: attachmentStreams
) {
1000 if (attachment
.isStream()) {
1001 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1002 } else if (attachment
.isPointer()) {
1003 attachmentPointers
.add(attachment
.asPointer());
1007 messageBuilder
.withAttachments(attachmentPointers
);
1009 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1012 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1013 String messageText
, List
<String
> attachments
1014 ) throws IOException
, AttachmentInvalidException
{
1015 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1016 .withBody(messageText
);
1017 if (attachments
!= null) {
1018 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1020 return sendSelfMessage(messageBuilder
);
1023 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1024 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1025 ) throws IOException
, InvalidNumberException
{
1026 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1028 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1029 targetSentTimestamp
);
1030 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1031 .withReaction(reaction
);
1032 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1035 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1036 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1038 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1040 return sendMessage(messageBuilder
, signalServiceAddresses
);
1041 } catch (Exception e
) {
1042 for (SignalServiceAddress address
: signalServiceAddresses
) {
1043 handleEndSession(address
);
1050 public String
getContactName(String number
) throws InvalidNumberException
{
1051 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1052 if (contact
== null) {
1055 return contact
.name
;
1059 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1060 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1061 ContactInfo contact
= account
.getContactStore().getContact(address
);
1062 if (contact
== null) {
1063 contact
= new ContactInfo(address
);
1065 contact
.name
= name
;
1066 account
.getContactStore().updateContact(contact
);
1070 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1071 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1074 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1075 ContactInfo contact
= account
.getContactStore().getContact(address
);
1076 if (contact
== null) {
1077 contact
= new ContactInfo(address
);
1079 contact
.blocked
= blocked
;
1080 account
.getContactStore().updateContact(contact
);
1084 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1085 GroupInfo group
= getGroup(groupId
);
1086 if (group
== null) {
1087 throw new GroupNotFoundException(groupId
);
1090 group
.setBlocked(blocked
);
1091 account
.getGroupStore().updateGroup(group
);
1096 * Change the expiration timer for a contact
1098 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1099 ContactInfo contact
= account
.getContactStore().getContact(address
);
1100 contact
.messageExpirationTime
= messageExpirationTimer
;
1101 account
.getContactStore().updateContact(contact
);
1102 sendExpirationTimerUpdate(address
);
1106 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1107 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1108 .asExpirationUpdate();
1109 sendMessage(messageBuilder
, List
.of(address
));
1113 * Change the expiration timer for a contact
1115 public void setExpirationTimer(
1116 String number
, int messageExpirationTimer
1117 ) throws IOException
, InvalidNumberException
{
1118 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1119 setExpirationTimer(address
, messageExpirationTimer
);
1123 * Change the expiration timer for a group
1125 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1126 GroupInfo g
= getGroup(groupId
);
1127 if (g
instanceof GroupInfoV1
) {
1128 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1129 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1130 account
.getGroupStore().updateGroup(groupInfoV1
);
1132 throw new RuntimeException("TODO Not implemented!");
1137 * Upload the sticker pack from path.
1139 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1140 * @return if successful, returns the URL to install the sticker pack in the signal app
1142 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1143 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1145 SignalServiceMessageSender messageSender
= createMessageSender();
1147 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1148 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1150 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1151 account
.getStickerStore().updateSticker(sticker
);
1155 return new URI("https",
1158 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1159 Hex
.toStringCondensed(packKey
),
1160 StandardCharsets
.UTF_8
)).toString();
1161 } catch (URISyntaxException e
) {
1162 throw new AssertionError(e
);
1166 void requestSyncGroups() throws IOException
{
1167 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1168 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1170 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1172 sendSyncMessage(message
);
1173 } catch (UntrustedIdentityException e
) {
1174 throw new AssertionError(e
);
1178 void requestSyncContacts() throws IOException
{
1179 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1180 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1182 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1184 sendSyncMessage(message
);
1185 } catch (UntrustedIdentityException e
) {
1186 throw new AssertionError(e
);
1190 void requestSyncBlocked() throws IOException
{
1191 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1192 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1194 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1196 sendSyncMessage(message
);
1197 } catch (UntrustedIdentityException e
) {
1198 throw new AssertionError(e
);
1202 void requestSyncConfiguration() throws IOException
{
1203 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1204 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1206 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1208 sendSyncMessage(message
);
1209 } catch (UntrustedIdentityException e
) {
1210 throw new AssertionError(e
);
1214 void requestSyncKeys() throws IOException
{
1215 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1216 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1218 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1220 sendSyncMessage(message
);
1221 } catch (UntrustedIdentityException e
) {
1222 throw new AssertionError(e
);
1226 private byte[] getSenderCertificate() {
1227 // TODO support UUID capable sender certificates
1228 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1231 certificate
= accountManager
.getSenderCertificate();
1232 } catch (IOException e
) {
1233 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1236 // TODO cache for a day
1240 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1241 SignalServiceMessageSender messageSender
= createMessageSender();
1243 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1244 } catch (UntrustedIdentityException e
) {
1245 account
.getSignalProtocolStore()
1246 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1248 TrustLevel
.UNTRUSTED
);
1253 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1254 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1255 final Set
<SignalServiceAddress
> addressesMissingUuid
= new HashSet
<>();
1257 for (String number
: numbers
) {
1258 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1259 if (resolvedAddress
.getUuid().isPresent()) {
1260 signalServiceAddresses
.add(resolvedAddress
);
1262 addressesMissingUuid
.add(resolvedAddress
);
1266 final Set
<String
> numbersMissingUuid
= addressesMissingUuid
.stream()
1267 .map(a
-> a
.getNumber().get())
1268 .collect(Collectors
.toSet());
1269 Map
<String
, UUID
> registeredUsers
;
1271 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1272 } catch (IOException e
) {
1273 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1274 registeredUsers
= Map
.of();
1277 for (SignalServiceAddress address
: addressesMissingUuid
) {
1278 final String number
= address
.getNumber().get();
1279 if (registeredUsers
.containsKey(number
)) {
1280 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1281 registeredUsers
.get(number
),
1283 signalServiceAddresses
.add(newAddress
);
1285 signalServiceAddresses
.add(address
);
1289 return signalServiceAddresses
;
1292 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1294 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1296 serviceEnvironmentConfig
.getCdsMrenclave());
1297 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1298 throw new IOException(e
);
1302 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1303 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1304 ) throws IOException
{
1305 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1306 final long timestamp
= System
.currentTimeMillis();
1307 messageBuilder
.withTimestamp(timestamp
);
1308 getOrCreateMessagePipe();
1309 getOrCreateUnidentifiedMessagePipe();
1310 SignalServiceDataMessage message
= null;
1312 message
= messageBuilder
.build();
1313 if (message
.getGroupContext().isPresent()) {
1315 SignalServiceMessageSender messageSender
= createMessageSender();
1316 final boolean isRecipientUpdate
= false;
1317 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1318 unidentifiedAccessHelper
.getAccessFor(recipients
),
1321 for (SendMessageResult r
: result
) {
1322 if (r
.getIdentityFailure() != null) {
1323 account
.getSignalProtocolStore()
1324 .saveIdentity(r
.getAddress(),
1325 r
.getIdentityFailure().getIdentityKey(),
1326 TrustLevel
.UNTRUSTED
);
1329 return new Pair
<>(timestamp
, result
);
1330 } catch (UntrustedIdentityException e
) {
1331 account
.getSignalProtocolStore()
1332 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1334 TrustLevel
.UNTRUSTED
);
1335 return new Pair
<>(timestamp
, List
.of());
1338 // Send to all individually, so sync messages are sent correctly
1339 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1340 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1341 for (SignalServiceAddress address
: recipients
) {
1342 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1343 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1344 messageBuilder
.withExpiration(expirationTime
);
1345 message
= messageBuilder
.build();
1346 results
.add(sendMessage(address
, message
));
1348 return new Pair
<>(timestamp
, results
);
1351 if (message
!= null && message
.isEndSession()) {
1352 for (SignalServiceAddress recipient
: recipients
) {
1353 handleEndSession(recipient
);
1360 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1361 SignalServiceDataMessage
.Builder messageBuilder
1362 ) throws IOException
{
1363 final long timestamp
= System
.currentTimeMillis();
1364 messageBuilder
.withTimestamp(timestamp
);
1365 getOrCreateMessagePipe();
1366 getOrCreateUnidentifiedMessagePipe();
1368 final SignalServiceAddress address
= getSelfAddress();
1370 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1371 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1372 messageBuilder
.withExpiration(expirationTime
);
1374 SignalServiceDataMessage message
= messageBuilder
.build();
1375 final SendMessageResult result
= sendSelfMessage(message
);
1376 return new Pair
<>(timestamp
, result
);
1382 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1383 SignalServiceMessageSender messageSender
= createMessageSender();
1385 SignalServiceAddress recipient
= account
.getSelfAddress();
1387 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1388 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1389 message
.getTimestamp(),
1391 message
.getExpiresInSeconds(),
1392 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1394 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1397 long startTime
= System
.currentTimeMillis();
1398 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1399 return SendMessageResult
.success(recipient
,
1400 unidentifiedAccess
.isPresent(),
1402 System
.currentTimeMillis() - startTime
);
1403 } catch (UntrustedIdentityException e
) {
1404 account
.getSignalProtocolStore()
1405 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1407 TrustLevel
.UNTRUSTED
);
1408 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1412 private SendMessageResult
sendMessage(
1413 SignalServiceAddress address
, SignalServiceDataMessage message
1414 ) throws IOException
{
1415 SignalServiceMessageSender messageSender
= createMessageSender();
1418 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1419 } catch (UntrustedIdentityException e
) {
1420 account
.getSignalProtocolStore()
1421 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1423 TrustLevel
.UNTRUSTED
);
1424 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1428 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1429 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1430 account
.getSignalProtocolStore(),
1431 certificateValidator
);
1433 return cipher
.decrypt(envelope
);
1434 } catch (ProtocolUntrustedIdentityException e
) {
1435 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1436 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1438 final IdentityKey untrustedIdentity
= identityException
.getUntrustedIdentity();
1439 if (untrustedIdentity
!= null) {
1440 account
.getSignalProtocolStore()
1441 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1443 TrustLevel
.UNTRUSTED
);
1445 throw identityException
;
1447 throw new AssertionError(e
);
1451 private void handleEndSession(SignalServiceAddress source
) {
1452 account
.getSignalProtocolStore().deleteAllSessions(source
);
1455 private List
<HandleAction
> handleSignalServiceDataMessage(
1456 SignalServiceDataMessage message
,
1458 SignalServiceAddress source
,
1459 SignalServiceAddress destination
,
1460 boolean ignoreAttachments
1462 List
<HandleAction
> actions
= new ArrayList
<>();
1463 if (message
.getGroupContext().isPresent()) {
1464 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1465 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1466 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1467 GroupInfo group
= getGroup(groupId
);
1468 if (group
== null || group
instanceof GroupInfoV1
) {
1469 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1470 switch (groupInfo
.getType()) {
1472 if (groupV1
== null) {
1473 groupV1
= new GroupInfoV1(groupId
);
1476 if (groupInfo
.getAvatar().isPresent()) {
1477 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1478 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1481 if (groupInfo
.getName().isPresent()) {
1482 groupV1
.name
= groupInfo
.getName().get();
1485 if (groupInfo
.getMembers().isPresent()) {
1486 groupV1
.addMembers(groupInfo
.getMembers()
1489 .map(this::resolveSignalServiceAddress
)
1490 .collect(Collectors
.toSet()));
1493 account
.getGroupStore().updateGroup(groupV1
);
1497 if (groupV1
== null && !isSync
) {
1498 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1502 if (groupV1
!= null) {
1503 groupV1
.removeMember(source
);
1504 account
.getGroupStore().updateGroup(groupV1
);
1509 if (groupV1
!= null && !isSync
) {
1510 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1515 // Received a group v1 message for a v2 group
1518 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1519 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1520 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1522 getOrMigrateGroup(groupMasterKey
,
1523 groupContext
.getRevision(),
1524 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1528 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1529 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1530 handleEndSession(conversationPartnerAddress
);
1532 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1533 if (message
.getGroupContext().isPresent()) {
1534 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1535 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1536 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1537 if (group
!= null) {
1538 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1539 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1540 account
.getGroupStore().updateGroup(group
);
1543 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1544 // disappearing message timer already stored in the DecryptedGroup
1546 } else if (conversationPartnerAddress
!= null) {
1547 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1548 if (contact
== null) {
1549 contact
= new ContactInfo(conversationPartnerAddress
);
1551 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1552 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1553 account
.getContactStore().updateContact(contact
);
1557 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1558 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1559 downloadAttachment(attachment
);
1562 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1563 final ProfileKey profileKey
;
1565 profileKey
= new ProfileKey(message
.getProfileKey().get());
1566 } catch (InvalidInputException e
) {
1567 throw new AssertionError(e
);
1569 if (source
.matches(account
.getSelfAddress())) {
1570 this.account
.setProfileKey(profileKey
);
1572 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1574 if (message
.getPreviews().isPresent()) {
1575 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1576 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1577 if (preview
.getImage().isPresent()) {
1578 downloadAttachment(preview
.getImage().get());
1582 if (message
.getQuote().isPresent()) {
1583 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1585 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1586 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1587 if (thumbnail
!= null) {
1588 downloadAttachment(thumbnail
);
1592 if (message
.getSticker().isPresent()) {
1593 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1594 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1595 if (sticker
== null) {
1596 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1597 account
.getStickerStore().updateSticker(sticker
);
1603 private GroupInfoV2
getOrMigrateGroup(
1604 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1606 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1608 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1609 GroupInfo groupInfo
= getGroup(groupId
);
1610 final GroupInfoV2 groupInfoV2
;
1611 if (groupInfo
instanceof GroupInfoV1
) {
1612 // Received a v2 group message for a v1 group, we need to locally migrate the group
1613 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1614 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1615 logger
.info("Locally migrated group {} to group v2, id: {}",
1616 groupInfo
.getGroupId().toBase64(),
1617 groupInfoV2
.getGroupId().toBase64());
1618 } else if (groupInfo
instanceof GroupInfoV2
) {
1619 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1621 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1624 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1625 DecryptedGroup group
= null;
1626 if (signedGroupChange
!= null
1627 && groupInfoV2
.getGroup() != null
1628 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1629 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1631 if (group
== null) {
1632 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1634 if (group
!= null) {
1635 storeProfileKeysFromMembers(group
);
1636 final String avatar
= group
.getAvatar();
1637 if (avatar
!= null && !avatar
.isEmpty()) {
1638 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1641 groupInfoV2
.setGroup(group
);
1642 account
.getGroupStore().updateGroup(groupInfoV2
);
1648 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1649 for (DecryptedMember member
: group
.getMembersList()) {
1650 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1651 member
.getUuid().toByteArray()), null));
1653 account
.getProfileStore()
1654 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1655 } catch (InvalidInputException ignored
) {
1660 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1661 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1662 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1666 private void retryFailedReceivedMessage(
1667 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1669 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1670 if (envelope
== null) {
1673 SignalServiceContent content
= null;
1674 if (!envelope
.isReceipt()) {
1676 content
= decryptMessage(envelope
);
1677 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1679 } catch (Exception er
) {
1680 // All other errors are not recoverable, so delete the cached message
1681 cachedMessage
.delete();
1684 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1685 for (HandleAction action
: actions
) {
1687 action
.execute(this);
1688 } catch (Throwable e
) {
1689 logger
.warn("Message action failed.", e
);
1694 handler
.handleMessage(envelope
, content
, null);
1695 cachedMessage
.delete();
1698 public void receiveMessages(
1701 boolean returnOnTimeout
,
1702 boolean ignoreAttachments
,
1703 ReceiveMessageHandler handler
1704 ) throws IOException
{
1705 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1707 Set
<HandleAction
> queuedActions
= null;
1709 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1711 boolean hasCaughtUpWithOldMessages
= false;
1714 SignalServiceEnvelope envelope
;
1715 SignalServiceContent content
= null;
1716 Exception exception
= null;
1717 final CachedMessage
[] cachedMessage
= {null};
1719 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1720 // store message on disk, before acknowledging receipt to the server
1721 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1723 if (result
.isPresent()) {
1724 envelope
= result
.get();
1726 // Received indicator that server queue is empty
1727 hasCaughtUpWithOldMessages
= true;
1729 if (queuedActions
!= null) {
1730 for (HandleAction action
: queuedActions
) {
1732 action
.execute(this);
1733 } catch (Throwable e
) {
1734 logger
.warn("Message action failed.", e
);
1738 queuedActions
.clear();
1739 queuedActions
= null;
1742 // Continue to wait another timeout for new messages
1745 } catch (TimeoutException e
) {
1746 if (returnOnTimeout
) return;
1748 } catch (InvalidVersionException e
) {
1749 logger
.warn("Error while receiving messages, ignoring: {}", e
.getMessage());
1753 if (envelope
.hasSource()) {
1754 // Store uuid if we don't have it already
1755 SignalServiceAddress source
= envelope
.getSourceAddress();
1756 resolveSignalServiceAddress(source
);
1758 if (!envelope
.isReceipt()) {
1760 content
= decryptMessage(envelope
);
1761 } catch (Exception e
) {
1764 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1765 if (hasCaughtUpWithOldMessages
) {
1766 for (HandleAction action
: actions
) {
1768 action
.execute(this);
1769 } catch (Throwable e
) {
1770 logger
.warn("Message action failed.", e
);
1774 if (queuedActions
== null) {
1775 queuedActions
= new HashSet
<>();
1777 queuedActions
.addAll(actions
);
1781 if (isMessageBlocked(envelope
, content
)) {
1782 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1783 } else if (isNotAGroupMember(envelope
, content
)) {
1784 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1786 handler
.handleMessage(envelope
, content
, exception
);
1788 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1789 if (cachedMessage
[0] != null) {
1790 cachedMessage
[0].delete();
1796 private boolean isMessageBlocked(
1797 SignalServiceEnvelope envelope
, SignalServiceContent content
1799 SignalServiceAddress source
;
1800 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1801 source
= envelope
.getSourceAddress();
1802 } else if (content
!= null) {
1803 source
= content
.getSender();
1807 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1808 if (sourceContact
!= null && sourceContact
.blocked
) {
1812 if (content
!= null && content
.getDataMessage().isPresent()) {
1813 SignalServiceDataMessage message
= content
.getDataMessage().get();
1814 if (message
.getGroupContext().isPresent()) {
1815 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1816 GroupInfo group
= getGroup(groupId
);
1817 if (group
!= null && group
.isBlocked()) {
1825 private boolean isNotAGroupMember(
1826 SignalServiceEnvelope envelope
, SignalServiceContent content
1828 SignalServiceAddress source
;
1829 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1830 source
= envelope
.getSourceAddress();
1831 } else if (content
!= null) {
1832 source
= content
.getSender();
1837 if (content
!= null && content
.getDataMessage().isPresent()) {
1838 SignalServiceDataMessage message
= content
.getDataMessage().get();
1839 if (message
.getGroupContext().isPresent()) {
1840 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1841 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1842 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1846 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1847 GroupInfo group
= getGroup(groupId
);
1848 if (group
!= null && !group
.isMember(source
)) {
1856 private List
<HandleAction
> handleMessage(
1857 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1859 List
<HandleAction
> actions
= new ArrayList
<>();
1860 if (content
!= null) {
1861 final SignalServiceAddress sender
;
1862 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1863 sender
= envelope
.getSourceAddress();
1865 sender
= content
.getSender();
1867 // Store uuid if we don't have it already
1868 resolveSignalServiceAddress(sender
);
1870 if (content
.getDataMessage().isPresent()) {
1871 SignalServiceDataMessage message
= content
.getDataMessage().get();
1873 if (content
.isNeedsReceipt()) {
1874 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1877 actions
.addAll(handleSignalServiceDataMessage(message
,
1880 account
.getSelfAddress(),
1881 ignoreAttachments
));
1883 if (content
.getSyncMessage().isPresent()) {
1884 account
.setMultiDevice(true);
1885 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1886 if (syncMessage
.getSent().isPresent()) {
1887 SentTranscriptMessage message
= syncMessage
.getSent().get();
1888 final SignalServiceAddress destination
= message
.getDestination().orNull();
1889 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1893 ignoreAttachments
));
1895 if (syncMessage
.getRequest().isPresent()) {
1896 RequestMessage rm
= syncMessage
.getRequest().get();
1897 if (rm
.isContactsRequest()) {
1898 actions
.add(SendSyncContactsAction
.create());
1900 if (rm
.isGroupsRequest()) {
1901 actions
.add(SendSyncGroupsAction
.create());
1903 if (rm
.isBlockedListRequest()) {
1904 actions
.add(SendSyncBlockedListAction
.create());
1906 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1908 if (syncMessage
.getGroups().isPresent()) {
1909 File tmpFile
= null;
1911 tmpFile
= IOUtils
.createTempFile();
1912 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1913 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1915 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1917 while ((g
= s
.read()) != null) {
1918 GroupInfoV1 syncGroup
= account
.getGroupStore()
1919 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1920 if (syncGroup
!= null) {
1921 if (g
.getName().isPresent()) {
1922 syncGroup
.name
= g
.getName().get();
1924 syncGroup
.addMembers(g
.getMembers()
1926 .map(this::resolveSignalServiceAddress
)
1927 .collect(Collectors
.toSet()));
1928 if (!g
.isActive()) {
1929 syncGroup
.removeMember(account
.getSelfAddress());
1931 // Add ourself to the member set as it's marked as active
1932 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1934 syncGroup
.blocked
= g
.isBlocked();
1935 if (g
.getColor().isPresent()) {
1936 syncGroup
.color
= g
.getColor().get();
1939 if (g
.getAvatar().isPresent()) {
1940 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1942 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1943 syncGroup
.archived
= g
.isArchived();
1944 account
.getGroupStore().updateGroup(syncGroup
);
1948 } catch (Exception e
) {
1949 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1953 if (tmpFile
!= null) {
1955 Files
.delete(tmpFile
.toPath());
1956 } catch (IOException e
) {
1957 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1964 if (syncMessage
.getBlockedList().isPresent()) {
1965 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1966 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1967 setContactBlocked(resolveSignalServiceAddress(address
), true);
1969 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1971 .map(GroupId
::unknownVersion
)
1972 .collect(Collectors
.toSet())) {
1974 setGroupBlocked(groupId
, true);
1975 } catch (GroupNotFoundException e
) {
1976 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1977 groupId
.toBase64());
1981 if (syncMessage
.getContacts().isPresent()) {
1982 File tmpFile
= null;
1984 tmpFile
= IOUtils
.createTempFile();
1985 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1986 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1987 .asPointer(), tmpFile
)) {
1988 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1989 if (contactsMessage
.isComplete()) {
1990 account
.getContactStore().clear();
1993 while ((c
= s
.read()) != null) {
1994 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1995 account
.setProfileKey(c
.getProfileKey().get());
1997 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1998 ContactInfo contact
= account
.getContactStore().getContact(address
);
1999 if (contact
== null) {
2000 contact
= new ContactInfo(address
);
2002 if (c
.getName().isPresent()) {
2003 contact
.name
= c
.getName().get();
2005 if (c
.getColor().isPresent()) {
2006 contact
.color
= c
.getColor().get();
2008 if (c
.getProfileKey().isPresent()) {
2009 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
2011 if (c
.getVerified().isPresent()) {
2012 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
2013 account
.getSignalProtocolStore()
2014 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
2015 verifiedMessage
.getIdentityKey(),
2016 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2018 if (c
.getExpirationTimer().isPresent()) {
2019 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
2021 contact
.blocked
= c
.isBlocked();
2022 contact
.inboxPosition
= c
.getInboxPosition().orNull();
2023 contact
.archived
= c
.isArchived();
2024 account
.getContactStore().updateContact(contact
);
2026 if (c
.getAvatar().isPresent()) {
2027 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2031 } catch (Exception e
) {
2032 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2036 if (tmpFile
!= null) {
2038 Files
.delete(tmpFile
.toPath());
2039 } catch (IOException e
) {
2040 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2047 if (syncMessage
.getVerified().isPresent()) {
2048 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
2049 account
.getSignalProtocolStore()
2050 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2051 verifiedMessage
.getIdentityKey(),
2052 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2054 if (syncMessage
.getStickerPackOperations().isPresent()) {
2055 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
2057 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
2058 if (!m
.getPackId().isPresent()) {
2061 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2062 if (sticker
== null) {
2063 if (!m
.getPackKey().isPresent()) {
2066 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2068 sticker
.setInstalled(!m
.getType().isPresent()
2069 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2070 account
.getStickerStore().updateSticker(sticker
);
2073 if (syncMessage
.getFetchType().isPresent()) {
2074 switch (syncMessage
.getFetchType().get()) {
2076 getRecipientProfile(getSelfAddress(), true);
2077 case STORAGE_MANIFEST
:
2081 if (syncMessage
.getKeys().isPresent()) {
2082 final KeysMessage keysMessage
= syncMessage
.getKeys().get();
2083 if (keysMessage
.getStorageService().isPresent()) {
2084 final StorageKey storageKey
= keysMessage
.getStorageService().get();
2085 account
.setStorageKey(storageKey
);
2088 if (syncMessage
.getConfiguration().isPresent()) {
2096 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2098 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2099 } catch (IOException e
) {
2100 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2104 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2106 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2107 } catch (IOException e
) {
2108 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2112 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2114 avatarStore
.storeGroupAvatar(groupId
,
2115 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2116 } catch (IOException e
) {
2117 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2121 private void downloadProfileAvatar(
2122 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2125 avatarStore
.storeProfileAvatar(address
,
2126 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2127 } catch (Throwable e
) {
2128 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2132 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2133 return attachmentStore
.getAttachmentFile(attachmentId
);
2136 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2137 if (!attachment
.isPointer()) {
2138 logger
.warn("Invalid state, can't store an attachment stream.");
2141 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2142 if (pointer
.getPreview().isPresent()) {
2143 final byte[] preview
= pointer
.getPreview().get();
2145 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2146 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2147 } catch (IOException e
) {
2148 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2153 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2154 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2155 } catch (IOException e
) {
2156 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2160 private void retrieveGroupV2Avatar(
2161 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2162 ) throws IOException
{
2163 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2165 File tmpFile
= IOUtils
.createTempFile();
2166 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2168 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2169 byte[] encryptedData
= IOUtils
.readFully(input
);
2171 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2172 outputStream
.write(decryptedData
);
2175 Files
.delete(tmpFile
.toPath());
2176 } catch (IOException e
) {
2177 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2184 private void retrieveProfileAvatar(
2185 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2186 ) throws IOException
{
2187 File tmpFile
= IOUtils
.createTempFile();
2188 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2191 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2192 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2193 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2196 Files
.delete(tmpFile
.toPath());
2197 } catch (IOException e
) {
2198 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2205 private void retrieveAttachment(
2206 final SignalServiceAttachment attachment
, final OutputStream outputStream
2207 ) throws IOException
{
2208 if (attachment
.isPointer()) {
2209 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2210 retrieveAttachmentPointer(pointer
, outputStream
);
2212 SignalServiceAttachmentStream stream
= attachment
.asStream();
2213 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2217 private void retrieveAttachmentPointer(
2218 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2219 ) throws IOException
{
2220 File tmpFile
= IOUtils
.createTempFile();
2221 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2222 IOUtils
.copyStream(input
, outputStream
);
2223 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2224 throw new IOException(e
);
2227 Files
.delete(tmpFile
.toPath());
2228 } catch (IOException e
) {
2229 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2236 private InputStream
retrieveAttachmentAsStream(
2237 SignalServiceAttachmentPointer pointer
, File tmpFile
2238 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2239 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2242 void sendGroups() throws IOException
, UntrustedIdentityException
{
2243 File groupsFile
= IOUtils
.createTempFile();
2246 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2247 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2248 for (GroupInfo
record : getGroups()) {
2249 if (record instanceof GroupInfoV1
) {
2250 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2251 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2252 Optional
.fromNullable(groupInfo
.name
),
2253 new ArrayList
<>(groupInfo
.getMembers()),
2254 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2255 groupInfo
.isMember(account
.getSelfAddress()),
2256 Optional
.of(groupInfo
.messageExpirationTime
),
2257 Optional
.fromNullable(groupInfo
.color
),
2259 Optional
.fromNullable(groupInfo
.inboxPosition
),
2260 groupInfo
.archived
));
2265 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2266 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2267 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2268 .withStream(groupsFileStream
)
2269 .withContentType("application/octet-stream")
2270 .withLength(groupsFile
.length())
2273 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2278 Files
.delete(groupsFile
.toPath());
2279 } catch (IOException e
) {
2280 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2285 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2286 File contactsFile
= IOUtils
.createTempFile();
2289 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2290 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2291 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2292 VerifiedMessage verifiedMessage
= null;
2293 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2294 if (currentIdentity
!= null) {
2295 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2296 currentIdentity
.getIdentityKey(),
2297 currentIdentity
.getTrustLevel().toVerifiedState(),
2298 currentIdentity
.getDateAdded().getTime());
2301 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2302 out
.write(new DeviceContact(record.getAddress(),
2303 Optional
.fromNullable(record.name
),
2304 createContactAvatarAttachment(record.getAddress()),
2305 Optional
.fromNullable(record.color
),
2306 Optional
.fromNullable(verifiedMessage
),
2307 Optional
.fromNullable(profileKey
),
2309 Optional
.of(record.messageExpirationTime
),
2310 Optional
.fromNullable(record.inboxPosition
),
2314 if (account
.getProfileKey() != null) {
2315 // Send our own profile key as well
2316 out
.write(new DeviceContact(account
.getSelfAddress(),
2321 Optional
.of(account
.getProfileKey()),
2329 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2330 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2331 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2332 .withStream(contactsFileStream
)
2333 .withContentType("application/octet-stream")
2334 .withLength(contactsFile
.length())
2337 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2342 Files
.delete(contactsFile
.toPath());
2343 } catch (IOException e
) {
2344 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2349 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2350 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2351 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2352 if (record.blocked
) {
2353 addresses
.add(record.getAddress());
2356 List
<byte[]> groupIds
= new ArrayList
<>();
2357 for (GroupInfo
record : getGroups()) {
2358 if (record.isBlocked()) {
2359 groupIds
.add(record.getGroupId().serialize());
2362 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2365 private void sendVerifiedMessage(
2366 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2367 ) throws IOException
, UntrustedIdentityException
{
2368 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2370 trustLevel
.toVerifiedState(),
2371 System
.currentTimeMillis());
2372 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2375 public List
<ContactInfo
> getContacts() {
2376 return account
.getContactStore().getContacts();
2379 public String
getContactOrProfileName(String number
) {
2380 final SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2382 final ContactInfo contact
= account
.getContactStore().getContact(address
);
2383 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2384 return contact
.name
;
2387 final SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2388 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2389 return profileEntry
.getProfile().getName();
2395 public GroupInfo
getGroup(GroupId groupId
) {
2396 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2397 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2398 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2399 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2400 account
.getGroupStore().updateGroup(group
);
2405 public List
<IdentityInfo
> getIdentities() {
2406 return account
.getSignalProtocolStore().getIdentities();
2409 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2410 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2414 * Trust this the identity with this fingerprint
2416 * @param name username of the identity
2417 * @param fingerprint Fingerprint
2419 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2420 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2421 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2425 for (IdentityInfo id
: ids
) {
2426 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2430 account
.getSignalProtocolStore()
2431 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2433 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2434 } catch (IOException
| UntrustedIdentityException e
) {
2435 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2444 * Trust this the identity with this safety number
2446 * @param name username of the identity
2447 * @param safetyNumber Safety number
2449 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2450 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2451 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2455 for (IdentityInfo id
: ids
) {
2456 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2460 account
.getSignalProtocolStore()
2461 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2463 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2464 } catch (IOException
| UntrustedIdentityException e
) {
2465 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2474 * Trust all keys of this identity without verification
2476 * @param name username of the identity
2478 public boolean trustIdentityAllKeys(String name
) {
2479 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2480 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2484 for (IdentityInfo id
: ids
) {
2485 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2486 account
.getSignalProtocolStore()
2487 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2489 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2490 } catch (IOException
| UntrustedIdentityException e
) {
2491 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2499 public String
computeSafetyNumber(
2500 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2502 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2503 account
.getSelfAddress(),
2504 getIdentityKeyPair().getPublicKey(),
2509 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2510 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2512 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2513 return resolveSignalServiceAddress(canonicalizedNumber
);
2516 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2517 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2519 return resolveSignalServiceAddress(address
);
2522 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2523 if (address
.matches(account
.getSelfAddress())) {
2524 return account
.getSelfAddress();
2527 return account
.getRecipientStore().resolveServiceAddress(address
);
2531 public void close() throws IOException
{
2535 void close(boolean closeAccount
) throws IOException
{
2536 if (messagePipe
!= null) {
2537 messagePipe
.shutdown();
2541 if (unidentifiedMessagePipe
!= null) {
2542 unidentifiedMessagePipe
.shutdown();
2543 unidentifiedMessagePipe
= null;
2546 if (closeAccount
&& account
!= null) {
2552 public interface ReceiveMessageHandler
{
2554 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);