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
.ecc
.ECPublicKey
;
80 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
81 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
82 import org
.whispersystems
.libsignal
.util
.Pair
;
83 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
84 import org
.whispersystems
.signalservice
.api
.KeyBackupService
;
85 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
86 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
87 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
88 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
89 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
90 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
91 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
92 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
93 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
94 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
95 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
96 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
97 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
106 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
107 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
108 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
109 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceStickerManifestUpload
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.KeysMessage
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
121 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
122 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
123 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
124 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
125 import org
.whispersystems
.signalservice
.api
.messages
.shared
.SharedContact
;
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
.Executors
;
171 import java
.util
.concurrent
.TimeUnit
;
172 import java
.util
.concurrent
.TimeoutException
;
173 import java
.util
.stream
.Collectors
;
175 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
177 public class Manager
implements Closeable
{
179 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
181 private final CertificateValidator certificateValidator
;
183 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
184 private final String userAgent
;
186 private SignalAccount account
;
187 private final SignalServiceAccountManager accountManager
;
188 private final GroupsV2Api groupsV2Api
;
189 private final GroupsV2Operations groupsV2Operations
;
190 private final SignalServiceMessageReceiver messageReceiver
;
191 private final ClientZkProfileOperations clientZkProfileOperations
;
193 private final ExecutorService executor
= Executors
.newCachedThreadPool();
195 private SignalServiceMessagePipe messagePipe
= null;
196 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
198 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
199 private final ProfileHelper profileHelper
;
200 private final GroupHelper groupHelper
;
201 private final PinHelper pinHelper
;
202 private final AvatarStore avatarStore
;
203 private final AttachmentStore attachmentStore
;
206 SignalAccount account
,
207 PathConfig pathConfig
,
208 ServiceEnvironmentConfig serviceEnvironmentConfig
,
211 this.account
= account
;
212 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
213 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
214 this.userAgent
= userAgent
;
215 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
216 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
217 final SleepTimer timer
= new UptimeSleepTimer();
218 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
219 new DynamicCredentialsProvider(account
.getUuid(),
220 account
.getUsername(),
221 account
.getPassword(),
222 account
.getDeviceId()),
225 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
227 this.groupsV2Api
= accountManager
.getGroupsV2Api();
228 final KeyBackupService keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
229 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
230 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
231 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
234 this.pinHelper
= new PinHelper(keyBackupService
);
235 this.clientZkProfileOperations
= capabilities
.isGv2()
236 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
237 .getProfileOperations()
239 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
241 account
.getUsername(),
242 account
.getPassword(),
243 account
.getDeviceId(),
247 clientZkProfileOperations
,
248 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
250 this.account
.setResolver(this::resolveSignalServiceAddress
);
252 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
253 account
.getProfileStore()::getProfileKey
,
254 this::getRecipientProfile
,
255 this::getSenderCertificate
);
256 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
257 unidentifiedAccessHelper
::getAccessFor
,
258 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
259 () -> messageReceiver
);
260 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
261 this::getRecipientProfile
,
262 account
::getSelfAddress
,
265 this::getGroupAuthForToday
);
266 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
267 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
270 public String
getUsername() {
271 return account
.getUsername();
274 public SignalServiceAddress
getSelfAddress() {
275 return account
.getSelfAddress();
278 private IdentityKeyPair
getIdentityKeyPair() {
279 return account
.getSignalProtocolStore().getIdentityKeyPair();
282 public int getDeviceId() {
283 return account
.getDeviceId();
286 public static Manager
init(
287 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
288 ) throws IOException
, NotRegisteredException
{
289 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
291 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
292 throw new NotRegisteredException();
295 SignalAccount account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
297 if (!account
.isRegistered()) {
298 throw new NotRegisteredException();
301 final ServiceEnvironmentConfig serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(
305 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
308 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
309 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
310 final File dataPath
= pathConfig
.getDataPath();
311 final File
[] files
= dataPath
.listFiles();
317 return Arrays
.stream(files
)
318 .filter(File
::isFile
)
320 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
321 .collect(Collectors
.toList());
324 public void checkAccountState() throws IOException
{
325 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
329 if (account
.getUuid() == null) {
330 account
.setUuid(accountManager
.getOwnUuid());
333 updateAccountAttributes();
337 * This is used for checking a set of phone numbers for registration on Signal
339 * @param numbers The set of phone number in question
340 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
341 * @throws IOException if its unable to get the contacts to check if they're registered
343 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
344 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
345 Map
<String
, UUID
> contactDetails
= getRegisteredUsers(numbers
);
347 Set
<String
> registeredUsers
= contactDetails
.keySet();
349 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
352 public void updateAccountAttributes() throws IOException
{
353 accountManager
.setAccountAttributes(null,
354 account
.getSignalProtocolStore().getLocalRegistrationId(),
356 // set legacy pin only if no KBS master key is set
357 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
358 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
359 account
.getSelfUnidentifiedAccessKey(),
360 account
.isUnrestrictedUnidentifiedAccess(),
362 account
.isDiscoverableByPhoneNumber());
366 * @param name if null, the previous name will be kept
367 * @param about if null, the previous about text will be kept
368 * @param aboutEmoji if null, the previous about emoji will be kept
369 * @param avatar if avatar is null the image from the local avatar store is used (if present),
370 * if it's Optional.absent(), the avatar will be removed
372 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
373 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(getSelfAddress());
374 SignalProfile profile
= profileEntry
== null ?
null : profileEntry
.getProfile();
375 SignalProfile newProfile
= new SignalProfile(profile
== null ?
null : profile
.getIdentityKey(),
376 name
!= null ? name
: profile
== null || profile
.getName() == null ?
"" : profile
.getName(),
377 about
!= null ? about
: profile
== null || profile
.getAbout() == null ?
"" : profile
.getAbout(),
380 : profile
== null || profile
.getAboutEmoji() == null ?
"" : profile
.getAboutEmoji(),
381 profile
== null ?
null : profile
.getUnidentifiedAccess(),
382 account
.isUnrestrictedUnidentifiedAccess(),
383 profile
== null ?
null : profile
.getCapabilities());
385 try (final StreamDetails streamDetails
= avatar
== null
386 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
387 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
388 accountManager
.setVersionedProfile(account
.getUuid(),
389 account
.getProfileKey(),
390 newProfile
.getName(),
391 newProfile
.getAbout(),
392 newProfile
.getAboutEmoji(),
396 if (avatar
!= null) {
397 if (avatar
.isPresent()) {
398 avatarStore
.storeProfileAvatar(getSelfAddress(),
399 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
401 avatarStore
.deleteProfileAvatar(getSelfAddress());
404 account
.getProfileStore()
405 .updateProfile(getSelfAddress(),
406 account
.getProfileKey(),
407 System
.currentTimeMillis(),
409 profileEntry
== null ?
null : profileEntry
.getProfileKeyCredential());
412 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
413 } catch (UntrustedIdentityException ignored
) {
417 public void unregister() throws IOException
{
418 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
419 // If this is the master device, other users can't send messages to this number anymore.
420 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
421 accountManager
.setGcmId(Optional
.absent());
422 accountManager
.deleteAccount();
424 account
.setRegistered(false);
428 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
429 List
<DeviceInfo
> devices
= accountManager
.getDevices();
430 account
.setMultiDevice(devices
.size() > 1);
435 public void removeLinkedDevices(int deviceId
) throws IOException
{
436 accountManager
.removeDevice(deviceId
);
437 List
<DeviceInfo
> devices
= accountManager
.getDevices();
438 account
.setMultiDevice(devices
.size() > 1);
442 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
443 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
445 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
448 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
449 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
450 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
452 accountManager
.addDevice(deviceIdentifier
,
455 Optional
.of(account
.getProfileKey().serialize()),
457 account
.setMultiDevice(true);
461 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
462 if (!account
.isMasterDevice()) {
463 throw new RuntimeException("Only master device can set a PIN");
465 if (pin
.isPresent()) {
466 final MasterKey masterKey
= account
.getPinMasterKey() != null
467 ? account
.getPinMasterKey()
468 : KeyUtils
.createMasterKey();
470 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
472 account
.setRegistrationLockPin(pin
.get());
473 account
.setPinMasterKey(masterKey
);
475 // Remove legacy registration lock
476 accountManager
.removeRegistrationLockV1();
479 pinHelper
.removeRegistrationLockPin();
481 account
.setRegistrationLockPin(null);
482 account
.setPinMasterKey(null);
487 void refreshPreKeys() throws IOException
{
488 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
489 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
490 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
492 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
495 private List
<PreKeyRecord
> generatePreKeys() {
496 final int offset
= account
.getPreKeyIdOffset();
498 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
499 account
.addPreKeys(records
);
505 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
506 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
508 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
509 account
.addSignedPreKey(record);
515 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
516 if (messagePipe
== null) {
517 messagePipe
= messageReceiver
.createMessagePipe();
522 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
523 if (unidentifiedMessagePipe
== null) {
524 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
526 return unidentifiedMessagePipe
;
529 private SignalServiceMessageSender
createMessageSender() {
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 (!ignoreAttachments
) {
1558 if (message
.getAttachments().isPresent()) {
1559 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1560 downloadAttachment(attachment
);
1563 if (message
.getSharedContacts().isPresent()) {
1564 for (SharedContact contact
: message
.getSharedContacts().get()) {
1565 if (contact
.getAvatar().isPresent()) {
1566 downloadAttachment(contact
.getAvatar().get().getAttachment());
1571 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1572 final ProfileKey profileKey
;
1574 profileKey
= new ProfileKey(message
.getProfileKey().get());
1575 } catch (InvalidInputException e
) {
1576 throw new AssertionError(e
);
1578 if (source
.matches(account
.getSelfAddress())) {
1579 this.account
.setProfileKey(profileKey
);
1581 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1583 if (message
.getPreviews().isPresent()) {
1584 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1585 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1586 if (preview
.getImage().isPresent()) {
1587 downloadAttachment(preview
.getImage().get());
1591 if (message
.getQuote().isPresent()) {
1592 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1594 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1595 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1596 if (thumbnail
!= null) {
1597 downloadAttachment(thumbnail
);
1601 if (message
.getSticker().isPresent()) {
1602 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1603 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1604 if (sticker
== null) {
1605 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1606 account
.getStickerStore().updateSticker(sticker
);
1612 private GroupInfoV2
getOrMigrateGroup(
1613 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1615 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1617 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1618 GroupInfo groupInfo
= getGroup(groupId
);
1619 final GroupInfoV2 groupInfoV2
;
1620 if (groupInfo
instanceof GroupInfoV1
) {
1621 // Received a v2 group message for a v1 group, we need to locally migrate the group
1622 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1623 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1624 logger
.info("Locally migrated group {} to group v2, id: {}",
1625 groupInfo
.getGroupId().toBase64(),
1626 groupInfoV2
.getGroupId().toBase64());
1627 } else if (groupInfo
instanceof GroupInfoV2
) {
1628 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1630 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1633 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1634 DecryptedGroup group
= null;
1635 if (signedGroupChange
!= null
1636 && groupInfoV2
.getGroup() != null
1637 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1638 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1640 if (group
== null) {
1641 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1643 if (group
!= null) {
1644 storeProfileKeysFromMembers(group
);
1645 final String avatar
= group
.getAvatar();
1646 if (avatar
!= null && !avatar
.isEmpty()) {
1647 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1650 groupInfoV2
.setGroup(group
);
1651 account
.getGroupStore().updateGroup(groupInfoV2
);
1657 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1658 for (DecryptedMember member
: group
.getMembersList()) {
1659 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1660 member
.getUuid().toByteArray()), null));
1662 account
.getProfileStore()
1663 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1664 } catch (InvalidInputException ignored
) {
1669 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1670 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1671 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1675 private void retryFailedReceivedMessage(
1676 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1678 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1679 if (envelope
== null) {
1682 SignalServiceContent content
= null;
1683 if (!envelope
.isReceipt()) {
1685 content
= decryptMessage(envelope
);
1686 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1688 } catch (Exception er
) {
1689 // All other errors are not recoverable, so delete the cached message
1690 cachedMessage
.delete();
1693 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1694 for (HandleAction action
: actions
) {
1696 action
.execute(this);
1697 } catch (Throwable e
) {
1698 logger
.warn("Message action failed.", e
);
1703 handler
.handleMessage(envelope
, content
, null);
1704 cachedMessage
.delete();
1707 public void receiveMessages(
1710 boolean returnOnTimeout
,
1711 boolean ignoreAttachments
,
1712 ReceiveMessageHandler handler
1713 ) throws IOException
{
1714 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1716 Set
<HandleAction
> queuedActions
= null;
1718 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1720 boolean hasCaughtUpWithOldMessages
= false;
1723 SignalServiceEnvelope envelope
;
1724 SignalServiceContent content
= null;
1725 Exception exception
= null;
1726 final CachedMessage
[] cachedMessage
= {null};
1728 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1729 // store message on disk, before acknowledging receipt to the server
1730 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1732 if (result
.isPresent()) {
1733 envelope
= result
.get();
1735 // Received indicator that server queue is empty
1736 hasCaughtUpWithOldMessages
= true;
1738 if (queuedActions
!= null) {
1739 for (HandleAction action
: queuedActions
) {
1741 action
.execute(this);
1742 } catch (Throwable e
) {
1743 logger
.warn("Message action failed.", e
);
1747 queuedActions
.clear();
1748 queuedActions
= null;
1751 // Continue to wait another timeout for new messages
1754 } catch (TimeoutException e
) {
1755 if (returnOnTimeout
) return;
1759 if (envelope
.hasSource()) {
1760 // Store uuid if we don't have it already
1761 SignalServiceAddress source
= envelope
.getSourceAddress();
1762 resolveSignalServiceAddress(source
);
1764 if (!envelope
.isReceipt()) {
1766 content
= decryptMessage(envelope
);
1767 } catch (Exception e
) {
1770 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1771 if (hasCaughtUpWithOldMessages
) {
1772 for (HandleAction action
: actions
) {
1774 action
.execute(this);
1775 } catch (Throwable e
) {
1776 logger
.warn("Message action failed.", e
);
1780 if (queuedActions
== null) {
1781 queuedActions
= new HashSet
<>();
1783 queuedActions
.addAll(actions
);
1787 if (isMessageBlocked(envelope
, content
)) {
1788 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1789 } else if (isNotAGroupMember(envelope
, content
)) {
1790 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1792 handler
.handleMessage(envelope
, content
, exception
);
1794 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1795 if (cachedMessage
[0] != null) {
1796 cachedMessage
[0].delete();
1802 private boolean isMessageBlocked(
1803 SignalServiceEnvelope envelope
, SignalServiceContent content
1805 SignalServiceAddress source
;
1806 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1807 source
= envelope
.getSourceAddress();
1808 } else if (content
!= null) {
1809 source
= content
.getSender();
1813 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1814 if (sourceContact
!= null && sourceContact
.blocked
) {
1818 if (content
!= null && content
.getDataMessage().isPresent()) {
1819 SignalServiceDataMessage message
= content
.getDataMessage().get();
1820 if (message
.getGroupContext().isPresent()) {
1821 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1822 GroupInfo group
= getGroup(groupId
);
1823 if (group
!= null && group
.isBlocked()) {
1831 private boolean isNotAGroupMember(
1832 SignalServiceEnvelope envelope
, SignalServiceContent content
1834 SignalServiceAddress source
;
1835 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1836 source
= envelope
.getSourceAddress();
1837 } else if (content
!= null) {
1838 source
= content
.getSender();
1843 if (content
!= null && content
.getDataMessage().isPresent()) {
1844 SignalServiceDataMessage message
= content
.getDataMessage().get();
1845 if (message
.getGroupContext().isPresent()) {
1846 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1847 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1848 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1852 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1853 GroupInfo group
= getGroup(groupId
);
1854 if (group
!= null && !group
.isMember(source
)) {
1862 private List
<HandleAction
> handleMessage(
1863 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1865 List
<HandleAction
> actions
= new ArrayList
<>();
1866 if (content
!= null) {
1867 final SignalServiceAddress sender
;
1868 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1869 sender
= envelope
.getSourceAddress();
1871 sender
= content
.getSender();
1873 // Store uuid if we don't have it already
1874 resolveSignalServiceAddress(sender
);
1876 if (content
.getDataMessage().isPresent()) {
1877 SignalServiceDataMessage message
= content
.getDataMessage().get();
1879 if (content
.isNeedsReceipt()) {
1880 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1883 actions
.addAll(handleSignalServiceDataMessage(message
,
1886 account
.getSelfAddress(),
1887 ignoreAttachments
));
1889 if (content
.getSyncMessage().isPresent()) {
1890 account
.setMultiDevice(true);
1891 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1892 if (syncMessage
.getSent().isPresent()) {
1893 SentTranscriptMessage message
= syncMessage
.getSent().get();
1894 final SignalServiceAddress destination
= message
.getDestination().orNull();
1895 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1899 ignoreAttachments
));
1901 if (syncMessage
.getRequest().isPresent()) {
1902 RequestMessage rm
= syncMessage
.getRequest().get();
1903 if (rm
.isContactsRequest()) {
1904 actions
.add(SendSyncContactsAction
.create());
1906 if (rm
.isGroupsRequest()) {
1907 actions
.add(SendSyncGroupsAction
.create());
1909 if (rm
.isBlockedListRequest()) {
1910 actions
.add(SendSyncBlockedListAction
.create());
1912 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1914 if (syncMessage
.getGroups().isPresent()) {
1915 File tmpFile
= null;
1917 tmpFile
= IOUtils
.createTempFile();
1918 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1919 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1921 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1923 while ((g
= s
.read()) != null) {
1924 GroupInfoV1 syncGroup
= account
.getGroupStore()
1925 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1926 if (syncGroup
!= null) {
1927 if (g
.getName().isPresent()) {
1928 syncGroup
.name
= g
.getName().get();
1930 syncGroup
.addMembers(g
.getMembers()
1932 .map(this::resolveSignalServiceAddress
)
1933 .collect(Collectors
.toSet()));
1934 if (!g
.isActive()) {
1935 syncGroup
.removeMember(account
.getSelfAddress());
1937 // Add ourself to the member set as it's marked as active
1938 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1940 syncGroup
.blocked
= g
.isBlocked();
1941 if (g
.getColor().isPresent()) {
1942 syncGroup
.color
= g
.getColor().get();
1945 if (g
.getAvatar().isPresent()) {
1946 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1948 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1949 syncGroup
.archived
= g
.isArchived();
1950 account
.getGroupStore().updateGroup(syncGroup
);
1954 } catch (Exception e
) {
1955 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1959 if (tmpFile
!= null) {
1961 Files
.delete(tmpFile
.toPath());
1962 } catch (IOException e
) {
1963 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1970 if (syncMessage
.getBlockedList().isPresent()) {
1971 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1972 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1973 setContactBlocked(resolveSignalServiceAddress(address
), true);
1975 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1977 .map(GroupId
::unknownVersion
)
1978 .collect(Collectors
.toSet())) {
1980 setGroupBlocked(groupId
, true);
1981 } catch (GroupNotFoundException e
) {
1982 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1983 groupId
.toBase64());
1987 if (syncMessage
.getContacts().isPresent()) {
1988 File tmpFile
= null;
1990 tmpFile
= IOUtils
.createTempFile();
1991 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1992 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1993 .asPointer(), tmpFile
)) {
1994 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1995 if (contactsMessage
.isComplete()) {
1996 account
.getContactStore().clear();
1999 while ((c
= s
.read()) != null) {
2000 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2001 account
.setProfileKey(c
.getProfileKey().get());
2003 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
2004 ContactInfo contact
= account
.getContactStore().getContact(address
);
2005 if (contact
== null) {
2006 contact
= new ContactInfo(address
);
2008 if (c
.getName().isPresent()) {
2009 contact
.name
= c
.getName().get();
2011 if (c
.getColor().isPresent()) {
2012 contact
.color
= c
.getColor().get();
2014 if (c
.getProfileKey().isPresent()) {
2015 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
2017 if (c
.getVerified().isPresent()) {
2018 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
2019 account
.getSignalProtocolStore()
2020 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
2021 verifiedMessage
.getIdentityKey(),
2022 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2024 if (c
.getExpirationTimer().isPresent()) {
2025 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
2027 contact
.blocked
= c
.isBlocked();
2028 contact
.inboxPosition
= c
.getInboxPosition().orNull();
2029 contact
.archived
= c
.isArchived();
2030 account
.getContactStore().updateContact(contact
);
2032 if (c
.getAvatar().isPresent()) {
2033 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2037 } catch (Exception e
) {
2038 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2042 if (tmpFile
!= null) {
2044 Files
.delete(tmpFile
.toPath());
2045 } catch (IOException e
) {
2046 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2053 if (syncMessage
.getVerified().isPresent()) {
2054 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
2055 account
.getSignalProtocolStore()
2056 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2057 verifiedMessage
.getIdentityKey(),
2058 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2060 if (syncMessage
.getStickerPackOperations().isPresent()) {
2061 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
2063 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
2064 if (!m
.getPackId().isPresent()) {
2067 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2068 if (sticker
== null) {
2069 if (!m
.getPackKey().isPresent()) {
2072 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2074 sticker
.setInstalled(!m
.getType().isPresent()
2075 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2076 account
.getStickerStore().updateSticker(sticker
);
2079 if (syncMessage
.getFetchType().isPresent()) {
2080 switch (syncMessage
.getFetchType().get()) {
2082 getRecipientProfile(getSelfAddress(), true);
2083 case STORAGE_MANIFEST
:
2087 if (syncMessage
.getKeys().isPresent()) {
2088 final KeysMessage keysMessage
= syncMessage
.getKeys().get();
2089 if (keysMessage
.getStorageService().isPresent()) {
2090 final StorageKey storageKey
= keysMessage
.getStorageService().get();
2091 account
.setStorageKey(storageKey
);
2094 if (syncMessage
.getConfiguration().isPresent()) {
2102 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2104 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2105 } catch (IOException e
) {
2106 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2110 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2112 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2113 } catch (IOException e
) {
2114 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2118 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2120 avatarStore
.storeGroupAvatar(groupId
,
2121 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2122 } catch (IOException e
) {
2123 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2127 private void downloadProfileAvatar(
2128 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2131 avatarStore
.storeProfileAvatar(address
,
2132 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2133 } catch (Throwable e
) {
2134 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2138 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2139 return attachmentStore
.getAttachmentFile(attachmentId
);
2142 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2143 if (!attachment
.isPointer()) {
2144 logger
.warn("Invalid state, can't store an attachment stream.");
2147 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2148 if (pointer
.getPreview().isPresent()) {
2149 final byte[] preview
= pointer
.getPreview().get();
2151 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2152 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2153 } catch (IOException e
) {
2154 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2159 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2160 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2161 } catch (IOException e
) {
2162 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2166 private void retrieveGroupV2Avatar(
2167 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2168 ) throws IOException
{
2169 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2171 File tmpFile
= IOUtils
.createTempFile();
2172 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2174 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2175 byte[] encryptedData
= IOUtils
.readFully(input
);
2177 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2178 outputStream
.write(decryptedData
);
2181 Files
.delete(tmpFile
.toPath());
2182 } catch (IOException e
) {
2183 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2190 private void retrieveProfileAvatar(
2191 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2192 ) throws IOException
{
2193 File tmpFile
= IOUtils
.createTempFile();
2194 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2197 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2198 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2199 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2202 Files
.delete(tmpFile
.toPath());
2203 } catch (IOException e
) {
2204 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2211 private void retrieveAttachment(
2212 final SignalServiceAttachment attachment
, final OutputStream outputStream
2213 ) throws IOException
{
2214 if (attachment
.isPointer()) {
2215 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2216 retrieveAttachmentPointer(pointer
, outputStream
);
2218 SignalServiceAttachmentStream stream
= attachment
.asStream();
2219 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2223 private void retrieveAttachmentPointer(
2224 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2225 ) throws IOException
{
2226 File tmpFile
= IOUtils
.createTempFile();
2227 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2228 IOUtils
.copyStream(input
, outputStream
);
2229 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2230 throw new IOException(e
);
2233 Files
.delete(tmpFile
.toPath());
2234 } catch (IOException e
) {
2235 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2242 private InputStream
retrieveAttachmentAsStream(
2243 SignalServiceAttachmentPointer pointer
, File tmpFile
2244 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2245 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2248 void sendGroups() throws IOException
, UntrustedIdentityException
{
2249 File groupsFile
= IOUtils
.createTempFile();
2252 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2253 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2254 for (GroupInfo
record : getGroups()) {
2255 if (record instanceof GroupInfoV1
) {
2256 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2257 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2258 Optional
.fromNullable(groupInfo
.name
),
2259 new ArrayList
<>(groupInfo
.getMembers()),
2260 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2261 groupInfo
.isMember(account
.getSelfAddress()),
2262 Optional
.of(groupInfo
.messageExpirationTime
),
2263 Optional
.fromNullable(groupInfo
.color
),
2265 Optional
.fromNullable(groupInfo
.inboxPosition
),
2266 groupInfo
.archived
));
2271 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2272 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2273 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2274 .withStream(groupsFileStream
)
2275 .withContentType("application/octet-stream")
2276 .withLength(groupsFile
.length())
2279 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2284 Files
.delete(groupsFile
.toPath());
2285 } catch (IOException e
) {
2286 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2291 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2292 File contactsFile
= IOUtils
.createTempFile();
2295 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2296 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2297 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2298 VerifiedMessage verifiedMessage
= null;
2299 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2300 if (currentIdentity
!= null) {
2301 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2302 currentIdentity
.getIdentityKey(),
2303 currentIdentity
.getTrustLevel().toVerifiedState(),
2304 currentIdentity
.getDateAdded().getTime());
2307 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2308 out
.write(new DeviceContact(record.getAddress(),
2309 Optional
.fromNullable(record.name
),
2310 createContactAvatarAttachment(record.getAddress()),
2311 Optional
.fromNullable(record.color
),
2312 Optional
.fromNullable(verifiedMessage
),
2313 Optional
.fromNullable(profileKey
),
2315 Optional
.of(record.messageExpirationTime
),
2316 Optional
.fromNullable(record.inboxPosition
),
2320 if (account
.getProfileKey() != null) {
2321 // Send our own profile key as well
2322 out
.write(new DeviceContact(account
.getSelfAddress(),
2327 Optional
.of(account
.getProfileKey()),
2335 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2336 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2337 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2338 .withStream(contactsFileStream
)
2339 .withContentType("application/octet-stream")
2340 .withLength(contactsFile
.length())
2343 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2348 Files
.delete(contactsFile
.toPath());
2349 } catch (IOException e
) {
2350 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2355 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2356 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2357 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2358 if (record.blocked
) {
2359 addresses
.add(record.getAddress());
2362 List
<byte[]> groupIds
= new ArrayList
<>();
2363 for (GroupInfo
record : getGroups()) {
2364 if (record.isBlocked()) {
2365 groupIds
.add(record.getGroupId().serialize());
2368 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2371 private void sendVerifiedMessage(
2372 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2373 ) throws IOException
, UntrustedIdentityException
{
2374 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2376 trustLevel
.toVerifiedState(),
2377 System
.currentTimeMillis());
2378 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2381 public List
<ContactInfo
> getContacts() {
2382 return account
.getContactStore().getContacts();
2385 public String
getContactOrProfileName(String number
) {
2386 final SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2388 final ContactInfo contact
= account
.getContactStore().getContact(address
);
2389 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2390 return contact
.name
;
2393 final SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2394 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2395 return profileEntry
.getProfile().getName();
2401 public GroupInfo
getGroup(GroupId groupId
) {
2402 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2403 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2404 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2405 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2406 account
.getGroupStore().updateGroup(group
);
2411 public List
<IdentityInfo
> getIdentities() {
2412 return account
.getSignalProtocolStore().getIdentities();
2415 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2416 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2420 * Trust this the identity with this fingerprint
2422 * @param name username of the identity
2423 * @param fingerprint Fingerprint
2425 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2426 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2427 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2431 for (IdentityInfo id
: ids
) {
2432 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2436 account
.getSignalProtocolStore()
2437 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2439 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2440 } catch (IOException
| UntrustedIdentityException e
) {
2441 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2450 * Trust this the identity with this safety number
2452 * @param name username of the identity
2453 * @param safetyNumber Safety number
2455 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2456 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2457 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2461 for (IdentityInfo id
: ids
) {
2462 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2466 account
.getSignalProtocolStore()
2467 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2469 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2470 } catch (IOException
| UntrustedIdentityException e
) {
2471 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2480 * Trust all keys of this identity without verification
2482 * @param name username of the identity
2484 public boolean trustIdentityAllKeys(String name
) {
2485 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2486 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2490 for (IdentityInfo id
: ids
) {
2491 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2492 account
.getSignalProtocolStore()
2493 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2495 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2496 } catch (IOException
| UntrustedIdentityException e
) {
2497 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2505 public String
computeSafetyNumber(
2506 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2508 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2509 account
.getSelfAddress(),
2510 getIdentityKeyPair().getPublicKey(),
2515 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2516 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2518 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2519 return resolveSignalServiceAddress(canonicalizedNumber
);
2522 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2523 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2525 return resolveSignalServiceAddress(address
);
2528 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2529 if (address
.matches(account
.getSelfAddress())) {
2530 return account
.getSelfAddress();
2533 return account
.getRecipientStore().resolveServiceAddress(address
);
2537 public void close() throws IOException
{
2541 void close(boolean closeAccount
) throws IOException
{
2542 executor
.shutdown();
2544 if (messagePipe
!= null) {
2545 messagePipe
.shutdown();
2549 if (unidentifiedMessagePipe
!= null) {
2550 unidentifiedMessagePipe
.shutdown();
2551 unidentifiedMessagePipe
= null;
2554 if (closeAccount
&& account
!= null) {
2560 public interface ReceiveMessageHandler
{
2562 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);