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
.profiles
.ProfileAndCredential
;
126 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
127 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
128 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
129 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
130 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
131 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
132 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
133 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
134 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
135 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
136 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
137 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
138 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
139 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
140 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
141 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
142 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
143 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
145 import java
.io
.Closeable
;
147 import java
.io
.FileInputStream
;
148 import java
.io
.FileOutputStream
;
149 import java
.io
.IOException
;
150 import java
.io
.InputStream
;
151 import java
.io
.OutputStream
;
153 import java
.net
.URISyntaxException
;
154 import java
.net
.URLEncoder
;
155 import java
.nio
.charset
.StandardCharsets
;
156 import java
.nio
.file
.Files
;
157 import java
.security
.SignatureException
;
158 import java
.util
.ArrayList
;
159 import java
.util
.Arrays
;
160 import java
.util
.Collection
;
161 import java
.util
.Date
;
162 import java
.util
.HashMap
;
163 import java
.util
.HashSet
;
164 import java
.util
.List
;
165 import java
.util
.Map
;
166 import java
.util
.Set
;
167 import java
.util
.UUID
;
168 import java
.util
.concurrent
.ExecutorService
;
169 import java
.util
.concurrent
.Executors
;
170 import java
.util
.concurrent
.TimeUnit
;
171 import java
.util
.concurrent
.TimeoutException
;
172 import java
.util
.stream
.Collectors
;
174 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
176 public class Manager
implements Closeable
{
178 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
180 private final CertificateValidator certificateValidator
;
182 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
183 private final String userAgent
;
185 private SignalAccount account
;
186 private final SignalServiceAccountManager accountManager
;
187 private final GroupsV2Api groupsV2Api
;
188 private final GroupsV2Operations groupsV2Operations
;
189 private final SignalServiceMessageReceiver messageReceiver
;
190 private final ClientZkProfileOperations clientZkProfileOperations
;
192 private final ExecutorService executor
= Executors
.newCachedThreadPool();
194 private SignalServiceMessagePipe messagePipe
= null;
195 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
197 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
198 private final ProfileHelper profileHelper
;
199 private final GroupHelper groupHelper
;
200 private final PinHelper pinHelper
;
201 private final AvatarStore avatarStore
;
202 private final AttachmentStore attachmentStore
;
205 SignalAccount account
,
206 PathConfig pathConfig
,
207 ServiceEnvironmentConfig serviceEnvironmentConfig
,
210 this.account
= account
;
211 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
212 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
213 this.userAgent
= userAgent
;
214 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
215 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
216 final SleepTimer timer
= new UptimeSleepTimer();
217 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
218 new DynamicCredentialsProvider(account
.getUuid(),
219 account
.getUsername(),
220 account
.getPassword(),
221 account
.getDeviceId()),
224 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
226 this.groupsV2Api
= accountManager
.getGroupsV2Api();
227 final KeyBackupService keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
228 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
229 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
230 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
233 this.pinHelper
= new PinHelper(keyBackupService
);
234 this.clientZkProfileOperations
= capabilities
.isGv2()
235 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
236 .getProfileOperations()
238 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
240 account
.getUsername(),
241 account
.getPassword(),
242 account
.getDeviceId(),
246 clientZkProfileOperations
,
247 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
249 this.account
.setResolver(this::resolveSignalServiceAddress
);
251 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
252 account
.getProfileStore()::getProfileKey
,
253 this::getRecipientProfile
,
254 this::getSenderCertificate
);
255 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
256 unidentifiedAccessHelper
::getAccessFor
,
257 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
258 () -> messageReceiver
);
259 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
260 this::getRecipientProfile
,
261 account
::getSelfAddress
,
264 this::getGroupAuthForToday
);
265 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
266 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
269 public String
getUsername() {
270 return account
.getUsername();
273 public SignalServiceAddress
getSelfAddress() {
274 return account
.getSelfAddress();
277 private IdentityKeyPair
getIdentityKeyPair() {
278 return account
.getSignalProtocolStore().getIdentityKeyPair();
281 public int getDeviceId() {
282 return account
.getDeviceId();
285 public static Manager
init(
286 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
287 ) throws IOException
, NotRegisteredException
{
288 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
290 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
291 throw new NotRegisteredException();
294 SignalAccount account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
296 if (!account
.isRegistered()) {
297 throw new NotRegisteredException();
300 final ServiceEnvironmentConfig serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(
304 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
307 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
308 PathConfig pathConfig
= PathConfig
.createDefault(settingsPath
);
309 final File dataPath
= pathConfig
.getDataPath();
310 final File
[] files
= dataPath
.listFiles();
316 return Arrays
.stream(files
)
317 .filter(File
::isFile
)
319 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
320 .collect(Collectors
.toList());
323 public void checkAccountState() throws IOException
{
324 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
328 if (account
.getUuid() == null) {
329 account
.setUuid(accountManager
.getOwnUuid());
332 updateAccountAttributes();
336 * This is used for checking a set of phone numbers for registration on Signal
338 * @param numbers The set of phone number in question
339 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
340 * @throws IOException if its unable to get the contacts to check if they're registered
342 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
343 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
344 Map
<String
, UUID
> contactDetails
= getRegisteredUsers(numbers
);
346 Set
<String
> registeredUsers
= contactDetails
.keySet();
348 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
351 public void updateAccountAttributes() throws IOException
{
352 accountManager
.setAccountAttributes(null,
353 account
.getSignalProtocolStore().getLocalRegistrationId(),
355 // set legacy pin only if no KBS master key is set
356 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
357 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
358 account
.getSelfUnidentifiedAccessKey(),
359 account
.isUnrestrictedUnidentifiedAccess(),
361 account
.isDiscoverableByPhoneNumber());
365 * @param name if null, the previous name will be kept
366 * @param about if null, the previous about text will be kept
367 * @param aboutEmoji if null, the previous about emoji will be kept
368 * @param avatar if avatar is null the image from the local avatar store is used (if present),
369 * if it's Optional.absent(), the avatar will be removed
371 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
372 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(getSelfAddress());
373 SignalProfile profile
= profileEntry
== null ?
null : profileEntry
.getProfile();
374 SignalProfile newProfile
= new SignalProfile(profile
== null ?
null : profile
.getIdentityKey(),
375 name
!= null ? name
: profile
== null || profile
.getName() == null ?
"" : profile
.getName(),
376 about
!= null ? about
: profile
== null || profile
.getAbout() == null ?
"" : profile
.getAbout(),
379 : profile
== null || profile
.getAboutEmoji() == null ?
"" : profile
.getAboutEmoji(),
380 profile
== null ?
null : profile
.getUnidentifiedAccess(),
381 account
.isUnrestrictedUnidentifiedAccess(),
382 profile
== null ?
null : profile
.getCapabilities());
384 try (final StreamDetails streamDetails
= avatar
== null
385 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
386 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
387 accountManager
.setVersionedProfile(account
.getUuid(),
388 account
.getProfileKey(),
389 newProfile
.getName(),
390 newProfile
.getAbout(),
391 newProfile
.getAboutEmoji(),
395 if (avatar
!= null) {
396 if (avatar
.isPresent()) {
397 avatarStore
.storeProfileAvatar(getSelfAddress(),
398 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
400 avatarStore
.deleteProfileAvatar(getSelfAddress());
403 account
.getProfileStore()
404 .updateProfile(getSelfAddress(),
405 account
.getProfileKey(),
406 System
.currentTimeMillis(),
408 profileEntry
== null ?
null : profileEntry
.getProfileKeyCredential());
411 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
412 } catch (UntrustedIdentityException ignored
) {
416 public void unregister() throws IOException
{
417 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
418 // If this is the master device, other users can't send messages to this number anymore.
419 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
420 accountManager
.setGcmId(Optional
.absent());
421 accountManager
.deleteAccount();
423 account
.setRegistered(false);
427 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
428 List
<DeviceInfo
> devices
= accountManager
.getDevices();
429 account
.setMultiDevice(devices
.size() > 1);
434 public void removeLinkedDevices(int deviceId
) throws IOException
{
435 accountManager
.removeDevice(deviceId
);
436 List
<DeviceInfo
> devices
= accountManager
.getDevices();
437 account
.setMultiDevice(devices
.size() > 1);
441 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
442 DeviceLinkInfo info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
444 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
447 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
448 IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
449 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
451 accountManager
.addDevice(deviceIdentifier
,
454 Optional
.of(account
.getProfileKey().serialize()),
456 account
.setMultiDevice(true);
460 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
461 if (!account
.isMasterDevice()) {
462 throw new RuntimeException("Only master device can set a PIN");
464 if (pin
.isPresent()) {
465 final MasterKey masterKey
= account
.getPinMasterKey() != null
466 ? account
.getPinMasterKey()
467 : KeyUtils
.createMasterKey();
469 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
471 account
.setRegistrationLockPin(pin
.get());
472 account
.setPinMasterKey(masterKey
);
474 // Remove legacy registration lock
475 accountManager
.removeRegistrationLockV1();
478 pinHelper
.removeRegistrationLockPin();
480 account
.setRegistrationLockPin(null);
481 account
.setPinMasterKey(null);
486 void refreshPreKeys() throws IOException
{
487 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
488 final IdentityKeyPair identityKeyPair
= getIdentityKeyPair();
489 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
491 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
494 private List
<PreKeyRecord
> generatePreKeys() {
495 final int offset
= account
.getPreKeyIdOffset();
497 List
<PreKeyRecord
> records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
498 account
.addPreKeys(records
);
504 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
505 final int signedPreKeyId
= account
.getNextSignedPreKeyId();
507 SignedPreKeyRecord
record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
508 account
.addSignedPreKey(record);
514 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
515 if (messagePipe
== null) {
516 messagePipe
= messageReceiver
.createMessagePipe();
521 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
522 if (unidentifiedMessagePipe
== null) {
523 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
525 return unidentifiedMessagePipe
;
528 private SignalServiceMessageSender
createMessageSender() {
529 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
531 account
.getUsername(),
532 account
.getPassword(),
533 account
.getDeviceId(),
534 account
.getSignalProtocolStore(),
536 account
.isMultiDevice(),
537 Optional
.fromNullable(messagePipe
),
538 Optional
.fromNullable(unidentifiedMessagePipe
),
540 clientZkProfileOperations
,
542 ServiceConfig
.MAX_ENVELOPE_SIZE
,
543 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
546 private SignalProfile
getRecipientProfile(
547 SignalServiceAddress address
549 return getRecipientProfile(address
, false);
552 private SignalProfile
getRecipientProfile(
553 SignalServiceAddress address
, boolean force
555 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
556 if (profileEntry
== null) {
559 long now
= new Date().getTime();
560 // Profiles are cached for 24h before retrieving them again
561 if (!profileEntry
.isRequestPending() && (
563 || profileEntry
.getProfile() == null
564 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
566 profileEntry
.setRequestPending(true);
567 final SignalServiceProfile encryptedProfile
;
569 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
571 } catch (IOException e
) {
572 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
575 profileEntry
.setRequestPending(false);
578 final ProfileKey profileKey
= profileEntry
.getProfileKey();
579 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
580 account
.getProfileStore()
581 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
584 return profileEntry
.getProfile();
587 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
588 SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
589 if (profileEntry
== null) {
592 if (profileEntry
.getProfileKeyCredential() == null) {
593 ProfileAndCredential profileAndCredential
;
595 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
596 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
597 } catch (IOException e
) {
598 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
602 long now
= new Date().getTime();
603 final ProfileKeyCredential profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
604 final SignalProfile profile
= decryptProfileAndDownloadAvatar(address
,
605 profileEntry
.getProfileKey(),
606 profileAndCredential
.getProfile());
607 account
.getProfileStore()
608 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
609 return profileKeyCredential
;
611 return profileEntry
.getProfileKeyCredential();
614 private SignalProfile
decryptProfileAndDownloadAvatar(
615 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
617 if (encryptedProfile
.getAvatar() != null) {
618 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
621 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
624 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
625 final StreamDetails streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
626 if (streamDetails
== null) {
627 return Optional
.absent();
630 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
633 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
634 final StreamDetails streamDetails
= avatarStore
.retrieveContactAvatar(address
);
635 if (streamDetails
== null) {
636 return Optional
.absent();
639 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
642 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
643 GroupInfo g
= getGroup(groupId
);
645 throw new GroupNotFoundException(groupId
);
647 if (!g
.isMember(account
.getSelfAddress())) {
648 throw new NotAGroupMemberException(groupId
, g
.getTitle());
653 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
654 GroupInfo g
= getGroup(groupId
);
656 throw new GroupNotFoundException(groupId
);
658 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
659 throw new NotAGroupMemberException(groupId
, g
.getTitle());
664 public List
<GroupInfo
> getGroups() {
665 return account
.getGroupStore().getGroups();
668 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
669 String messageText
, List
<String
> attachments
, GroupId groupId
670 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
671 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
672 .withBody(messageText
);
673 if (attachments
!= null) {
674 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
677 return sendGroupMessage(messageBuilder
, groupId
);
680 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
681 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
682 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
683 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
685 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
686 targetSentTimestamp
);
687 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
688 .withReaction(reaction
);
690 return sendGroupMessage(messageBuilder
, groupId
);
693 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
694 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
695 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
696 final GroupInfo g
= getGroupForSending(groupId
);
698 GroupUtils
.setGroupContext(messageBuilder
, g
);
699 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
701 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
704 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
705 SignalServiceDataMessage
.Builder messageBuilder
;
707 final GroupInfo g
= getGroupForUpdating(groupId
);
708 if (g
instanceof GroupInfoV1
) {
709 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
710 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
711 .withId(groupId
.serialize())
713 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
714 groupInfoV1
.removeMember(account
.getSelfAddress());
715 account
.getGroupStore().updateGroup(groupInfoV1
);
717 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) g
;
718 final Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
719 groupInfoV2
.setGroup(groupGroupChangePair
.first());
720 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
721 account
.getGroupStore().updateGroup(groupInfoV2
);
724 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
727 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
728 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
729 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
730 return sendUpdateGroupMessage(groupId
,
732 members
== null ?
null : getSignalServiceAddresses(members
),
736 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
737 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
738 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
740 SignalServiceDataMessage
.Builder messageBuilder
;
741 if (groupId
== null) {
743 GroupInfoV2 gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
744 members
== null ? List
.of() : members
,
747 GroupInfoV1 gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
748 gv1
.addMembers(List
.of(account
.getSelfAddress()));
749 updateGroupV1(gv1
, name
, members
, avatarFile
);
750 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
753 if (avatarFile
!= null) {
754 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
755 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
757 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
761 GroupInfo group
= getGroupForUpdating(groupId
);
762 if (group
instanceof GroupInfoV2
) {
763 final GroupInfoV2 groupInfoV2
= (GroupInfoV2
) group
;
765 Pair
<Long
, List
<SendMessageResult
>> result
= null;
766 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
767 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
768 result
= sendUpdateGroupMessage(groupInfoV2
,
769 groupGroupChangePair
.first(),
770 groupGroupChangePair
.second());
773 if (members
!= null) {
774 final Set
<SignalServiceAddress
> newMembers
= new HashSet
<>(members
);
775 newMembers
.removeAll(group
.getMembers()
777 .map(this::resolveSignalServiceAddress
)
778 .collect(Collectors
.toSet()));
779 if (newMembers
.size() > 0) {
780 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
782 result
= sendUpdateGroupMessage(groupInfoV2
,
783 groupGroupChangePair
.first(),
784 groupGroupChangePair
.second());
787 if (result
== null || name
!= null || avatarFile
!= null) {
788 Pair
<DecryptedGroup
, GroupChange
> groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
,
791 if (avatarFile
!= null) {
792 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
793 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
795 result
= sendUpdateGroupMessage(groupInfoV2
,
796 groupGroupChangePair
.first(),
797 groupGroupChangePair
.second());
800 return new Pair
<>(group
.getGroupId(), result
.second());
802 GroupInfoV1 gv1
= (GroupInfoV1
) group
;
803 updateGroupV1(gv1
, name
, members
, avatarFile
);
804 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
809 account
.getGroupStore().updateGroup(g
);
811 final Pair
<Long
, List
<SendMessageResult
>> result
= sendMessage(messageBuilder
,
812 g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
813 return new Pair
<>(g
.getGroupId(), result
.second());
816 private void updateGroupV1(
819 final Collection
<SignalServiceAddress
> members
,
820 final File avatarFile
821 ) throws IOException
{
826 if (members
!= null) {
827 final Set
<String
> newE164Members
= new HashSet
<>();
828 for (SignalServiceAddress member
: members
) {
829 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
832 newE164Members
.add(member
.getNumber().get());
835 final Map
<String
, UUID
> registeredUsers
= getRegisteredUsers(newE164Members
);
836 if (registeredUsers
.size() != newE164Members
.size()) {
837 // Some of the new members are not registered on Signal
838 newE164Members
.removeAll(registeredUsers
.keySet());
839 throw new IOException("Failed to add members "
840 + String
.join(", ", newE164Members
)
841 + " to group: Not registered on Signal");
844 g
.addMembers(members
);
847 if (avatarFile
!= null) {
848 avatarStore
.storeGroupAvatar(g
.getGroupId(),
849 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
853 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
854 GroupInviteLinkUrl inviteLinkUrl
855 ) throws IOException
, GroupLinkNotActiveException
{
856 return sendJoinGroupMessage(inviteLinkUrl
);
859 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
860 GroupInviteLinkUrl inviteLinkUrl
861 ) throws IOException
, GroupLinkNotActiveException
{
862 final DecryptedGroupJoinInfo groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
863 inviteLinkUrl
.getPassword());
864 final GroupChange groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
865 inviteLinkUrl
.getPassword(),
867 final GroupInfoV2 group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
868 groupJoinInfo
.getRevision() + 1,
869 groupChange
.toByteArray());
871 if (group
.getGroup() == null) {
872 // Only requested member, can't send update to group members
873 return new Pair
<>(group
.getGroupId(), List
.of());
876 final Pair
<Long
, List
<SendMessageResult
>> result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
878 return new Pair
<>(group
.getGroupId(), result
.second());
881 private static int currentTimeDays() {
882 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
885 private GroupsV2AuthorizationString
getGroupAuthForToday(
886 final GroupSecretParams groupSecretParams
887 ) throws IOException
{
888 final int today
= currentTimeDays();
889 // Returns credentials for the next 7 days
890 final HashMap
<Integer
, AuthCredentialResponse
> credentials
= groupsV2Api
.getCredentials(today
);
891 // TODO cache credentials until they expire
892 AuthCredentialResponse authCredentialResponse
= credentials
.get(today
);
894 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
897 authCredentialResponse
);
898 } catch (VerificationFailedException e
) {
899 throw new IOException(e
);
903 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
904 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
905 ) throws IOException
{
906 group
.setGroup(newDecryptedGroup
);
907 final SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(group
,
908 groupChange
.toByteArray());
909 account
.getGroupStore().updateGroup(group
);
910 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
913 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
914 GroupIdV1 groupId
, SignalServiceAddress recipient
915 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
917 GroupInfo group
= getGroupForSending(groupId
);
918 if (!(group
instanceof GroupInfoV1
)) {
919 throw new RuntimeException("Received an invalid group request for a v2 group!");
921 g
= (GroupInfoV1
) group
;
923 if (!g
.isMember(recipient
)) {
924 throw new NotAGroupMemberException(groupId
, g
.name
);
927 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
929 // Send group message only to the recipient who requested it
930 return sendMessage(messageBuilder
, List
.of(recipient
));
933 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
934 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
935 .withId(g
.getGroupId().serialize())
937 .withMembers(new ArrayList
<>(g
.getMembers()));
940 final Optional
<SignalServiceAttachmentStream
> attachment
= createGroupAvatarAttachment(g
.getGroupId());
941 if (attachment
.isPresent()) {
942 group
.withAvatar(attachment
.get());
944 } catch (IOException e
) {
945 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
948 return SignalServiceDataMessage
.newBuilder()
949 .asGroupMessage(group
.build())
950 .withExpiration(g
.getMessageExpirationTime());
953 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
954 SignalServiceGroupV2
.Builder group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
955 .withRevision(g
.getGroup().getRevision())
956 .withSignedGroupChange(signedGroupChange
);
957 return SignalServiceDataMessage
.newBuilder()
958 .asGroupMessage(group
.build())
959 .withExpiration(g
.getMessageExpirationTime());
962 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
963 GroupIdV1 groupId
, SignalServiceAddress recipient
964 ) throws IOException
{
965 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
966 .withId(groupId
.serialize());
968 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
969 .asGroupMessage(group
.build());
971 // Send group info request message to the recipient who sent us a message with this groupId
972 return sendMessage(messageBuilder
, List
.of(recipient
));
976 SignalServiceAddress remoteAddress
, long messageId
977 ) throws IOException
, UntrustedIdentityException
{
978 SignalServiceReceiptMessage receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
980 System
.currentTimeMillis());
982 createMessageSender().sendReceipt(remoteAddress
,
983 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
987 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
988 String messageText
, List
<String
> attachments
, List
<String
> recipients
989 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
990 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
991 .withBody(messageText
);
992 if (attachments
!= null) {
993 List
<SignalServiceAttachment
> attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
995 // Upload attachments here, so we only upload once even for multiple recipients
996 SignalServiceMessageSender messageSender
= createMessageSender();
997 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
998 for (SignalServiceAttachment attachment
: attachmentStreams
) {
999 if (attachment
.isStream()) {
1000 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1001 } else if (attachment
.isPointer()) {
1002 attachmentPointers
.add(attachment
.asPointer());
1006 messageBuilder
.withAttachments(attachmentPointers
);
1008 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1011 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1012 String messageText
, List
<String
> attachments
1013 ) throws IOException
, AttachmentInvalidException
{
1014 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1015 .withBody(messageText
);
1016 if (attachments
!= null) {
1017 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1019 return sendSelfMessage(messageBuilder
);
1022 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1023 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1024 ) throws IOException
, InvalidNumberException
{
1025 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1027 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1028 targetSentTimestamp
);
1029 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1030 .withReaction(reaction
);
1031 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1034 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1035 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1037 final Collection
<SignalServiceAddress
> signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1039 return sendMessage(messageBuilder
, signalServiceAddresses
);
1040 } catch (Exception e
) {
1041 for (SignalServiceAddress address
: signalServiceAddresses
) {
1042 handleEndSession(address
);
1049 public String
getContactName(String number
) throws InvalidNumberException
{
1050 ContactInfo contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1051 if (contact
== null) {
1054 return contact
.name
;
1058 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1059 final SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1060 ContactInfo contact
= account
.getContactStore().getContact(address
);
1061 if (contact
== null) {
1062 contact
= new ContactInfo(address
);
1064 contact
.name
= name
;
1065 account
.getContactStore().updateContact(contact
);
1069 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1070 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1073 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1074 ContactInfo contact
= account
.getContactStore().getContact(address
);
1075 if (contact
== null) {
1076 contact
= new ContactInfo(address
);
1078 contact
.blocked
= blocked
;
1079 account
.getContactStore().updateContact(contact
);
1083 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1084 GroupInfo group
= getGroup(groupId
);
1085 if (group
== null) {
1086 throw new GroupNotFoundException(groupId
);
1089 group
.setBlocked(blocked
);
1090 account
.getGroupStore().updateGroup(group
);
1095 * Change the expiration timer for a contact
1097 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1098 ContactInfo contact
= account
.getContactStore().getContact(address
);
1099 contact
.messageExpirationTime
= messageExpirationTimer
;
1100 account
.getContactStore().updateContact(contact
);
1101 sendExpirationTimerUpdate(address
);
1105 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1106 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
1107 .asExpirationUpdate();
1108 sendMessage(messageBuilder
, List
.of(address
));
1112 * Change the expiration timer for a contact
1114 public void setExpirationTimer(
1115 String number
, int messageExpirationTimer
1116 ) throws IOException
, InvalidNumberException
{
1117 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(number
);
1118 setExpirationTimer(address
, messageExpirationTimer
);
1122 * Change the expiration timer for a group
1124 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1125 GroupInfo g
= getGroup(groupId
);
1126 if (g
instanceof GroupInfoV1
) {
1127 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) g
;
1128 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1129 account
.getGroupStore().updateGroup(groupInfoV1
);
1131 throw new RuntimeException("TODO Not implemented!");
1136 * Upload the sticker pack from path.
1138 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1139 * @return if successful, returns the URL to install the sticker pack in the signal app
1141 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1142 SignalServiceStickerManifestUpload manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1144 SignalServiceMessageSender messageSender
= createMessageSender();
1146 byte[] packKey
= KeyUtils
.createStickerUploadKey();
1147 String packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1149 Sticker sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1150 account
.getStickerStore().updateSticker(sticker
);
1154 return new URI("https",
1157 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1158 Hex
.toStringCondensed(packKey
),
1159 StandardCharsets
.UTF_8
)).toString();
1160 } catch (URISyntaxException e
) {
1161 throw new AssertionError(e
);
1165 void requestSyncGroups() throws IOException
{
1166 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1167 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1169 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1171 sendSyncMessage(message
);
1172 } catch (UntrustedIdentityException e
) {
1173 throw new AssertionError(e
);
1177 void requestSyncContacts() throws IOException
{
1178 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1179 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1181 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1183 sendSyncMessage(message
);
1184 } catch (UntrustedIdentityException e
) {
1185 throw new AssertionError(e
);
1189 void requestSyncBlocked() throws IOException
{
1190 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1191 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1193 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1195 sendSyncMessage(message
);
1196 } catch (UntrustedIdentityException e
) {
1197 throw new AssertionError(e
);
1201 void requestSyncConfiguration() throws IOException
{
1202 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1203 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1205 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1207 sendSyncMessage(message
);
1208 } catch (UntrustedIdentityException e
) {
1209 throw new AssertionError(e
);
1213 void requestSyncKeys() throws IOException
{
1214 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1215 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1217 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1219 sendSyncMessage(message
);
1220 } catch (UntrustedIdentityException e
) {
1221 throw new AssertionError(e
);
1225 private byte[] getSenderCertificate() {
1226 // TODO support UUID capable sender certificates
1227 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1230 certificate
= accountManager
.getSenderCertificate();
1231 } catch (IOException e
) {
1232 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1235 // TODO cache for a day
1239 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1240 SignalServiceMessageSender messageSender
= createMessageSender();
1242 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1243 } catch (UntrustedIdentityException e
) {
1244 account
.getSignalProtocolStore()
1245 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1247 TrustLevel
.UNTRUSTED
);
1252 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1253 final Set
<SignalServiceAddress
> signalServiceAddresses
= new HashSet
<>(numbers
.size());
1254 final Set
<SignalServiceAddress
> addressesMissingUuid
= new HashSet
<>();
1256 for (String number
: numbers
) {
1257 final SignalServiceAddress resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1258 if (resolvedAddress
.getUuid().isPresent()) {
1259 signalServiceAddresses
.add(resolvedAddress
);
1261 addressesMissingUuid
.add(resolvedAddress
);
1265 final Set
<String
> numbersMissingUuid
= addressesMissingUuid
.stream()
1266 .map(a
-> a
.getNumber().get())
1267 .collect(Collectors
.toSet());
1268 Map
<String
, UUID
> registeredUsers
;
1270 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1271 } catch (IOException e
) {
1272 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1273 registeredUsers
= Map
.of();
1276 for (SignalServiceAddress address
: addressesMissingUuid
) {
1277 final String number
= address
.getNumber().get();
1278 if (registeredUsers
.containsKey(number
)) {
1279 final SignalServiceAddress newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(
1280 registeredUsers
.get(number
),
1282 signalServiceAddresses
.add(newAddress
);
1284 signalServiceAddresses
.add(address
);
1288 return signalServiceAddresses
;
1291 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1293 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1295 serviceEnvironmentConfig
.getCdsMrenclave());
1296 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1297 throw new IOException(e
);
1301 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1302 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1303 ) throws IOException
{
1304 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1305 final long timestamp
= System
.currentTimeMillis();
1306 messageBuilder
.withTimestamp(timestamp
);
1307 getOrCreateMessagePipe();
1308 getOrCreateUnidentifiedMessagePipe();
1309 SignalServiceDataMessage message
= null;
1311 message
= messageBuilder
.build();
1312 if (message
.getGroupContext().isPresent()) {
1314 SignalServiceMessageSender messageSender
= createMessageSender();
1315 final boolean isRecipientUpdate
= false;
1316 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1317 unidentifiedAccessHelper
.getAccessFor(recipients
),
1320 for (SendMessageResult r
: result
) {
1321 if (r
.getIdentityFailure() != null) {
1322 account
.getSignalProtocolStore()
1323 .saveIdentity(r
.getAddress(),
1324 r
.getIdentityFailure().getIdentityKey(),
1325 TrustLevel
.UNTRUSTED
);
1328 return new Pair
<>(timestamp
, result
);
1329 } catch (UntrustedIdentityException e
) {
1330 account
.getSignalProtocolStore()
1331 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1333 TrustLevel
.UNTRUSTED
);
1334 return new Pair
<>(timestamp
, List
.of());
1337 // Send to all individually, so sync messages are sent correctly
1338 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1339 List
<SendMessageResult
> results
= new ArrayList
<>(recipients
.size());
1340 for (SignalServiceAddress address
: recipients
) {
1341 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1342 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1343 messageBuilder
.withExpiration(expirationTime
);
1344 message
= messageBuilder
.build();
1345 results
.add(sendMessage(address
, message
));
1347 return new Pair
<>(timestamp
, results
);
1350 if (message
!= null && message
.isEndSession()) {
1351 for (SignalServiceAddress recipient
: recipients
) {
1352 handleEndSession(recipient
);
1359 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1360 SignalServiceDataMessage
.Builder messageBuilder
1361 ) throws IOException
{
1362 final long timestamp
= System
.currentTimeMillis();
1363 messageBuilder
.withTimestamp(timestamp
);
1364 getOrCreateMessagePipe();
1365 getOrCreateUnidentifiedMessagePipe();
1367 final SignalServiceAddress address
= getSelfAddress();
1369 final ContactInfo contact
= account
.getContactStore().getContact(address
);
1370 final int expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1371 messageBuilder
.withExpiration(expirationTime
);
1373 SignalServiceDataMessage message
= messageBuilder
.build();
1374 final SendMessageResult result
= sendSelfMessage(message
);
1375 return new Pair
<>(timestamp
, result
);
1381 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1382 SignalServiceMessageSender messageSender
= createMessageSender();
1384 SignalServiceAddress recipient
= account
.getSelfAddress();
1386 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1387 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1388 message
.getTimestamp(),
1390 message
.getExpiresInSeconds(),
1391 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1393 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1396 long startTime
= System
.currentTimeMillis();
1397 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1398 return SendMessageResult
.success(recipient
,
1399 unidentifiedAccess
.isPresent(),
1401 System
.currentTimeMillis() - startTime
);
1402 } catch (UntrustedIdentityException e
) {
1403 account
.getSignalProtocolStore()
1404 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1406 TrustLevel
.UNTRUSTED
);
1407 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1411 private SendMessageResult
sendMessage(
1412 SignalServiceAddress address
, SignalServiceDataMessage message
1413 ) throws IOException
{
1414 SignalServiceMessageSender messageSender
= createMessageSender();
1417 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1418 } catch (UntrustedIdentityException e
) {
1419 account
.getSignalProtocolStore()
1420 .saveIdentity(resolveSignalServiceAddress(e
.getIdentifier()),
1422 TrustLevel
.UNTRUSTED
);
1423 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1427 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1428 SignalServiceCipher cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1429 account
.getSignalProtocolStore(),
1430 certificateValidator
);
1432 return cipher
.decrypt(envelope
);
1433 } catch (ProtocolUntrustedIdentityException e
) {
1434 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1435 org
.whispersystems
.libsignal
.UntrustedIdentityException identityException
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
1437 final IdentityKey untrustedIdentity
= identityException
.getUntrustedIdentity();
1438 if (untrustedIdentity
!= null) {
1439 account
.getSignalProtocolStore()
1440 .saveIdentity(resolveSignalServiceAddress(identityException
.getName()),
1442 TrustLevel
.UNTRUSTED
);
1444 throw identityException
;
1446 throw new AssertionError(e
);
1450 private void handleEndSession(SignalServiceAddress source
) {
1451 account
.getSignalProtocolStore().deleteAllSessions(source
);
1454 private List
<HandleAction
> handleSignalServiceDataMessage(
1455 SignalServiceDataMessage message
,
1457 SignalServiceAddress source
,
1458 SignalServiceAddress destination
,
1459 boolean ignoreAttachments
1461 List
<HandleAction
> actions
= new ArrayList
<>();
1462 if (message
.getGroupContext().isPresent()) {
1463 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1464 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1465 GroupIdV1 groupId
= GroupId
.v1(groupInfo
.getGroupId());
1466 GroupInfo group
= getGroup(groupId
);
1467 if (group
== null || group
instanceof GroupInfoV1
) {
1468 GroupInfoV1 groupV1
= (GroupInfoV1
) group
;
1469 switch (groupInfo
.getType()) {
1471 if (groupV1
== null) {
1472 groupV1
= new GroupInfoV1(groupId
);
1475 if (groupInfo
.getAvatar().isPresent()) {
1476 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1477 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1480 if (groupInfo
.getName().isPresent()) {
1481 groupV1
.name
= groupInfo
.getName().get();
1484 if (groupInfo
.getMembers().isPresent()) {
1485 groupV1
.addMembers(groupInfo
.getMembers()
1488 .map(this::resolveSignalServiceAddress
)
1489 .collect(Collectors
.toSet()));
1492 account
.getGroupStore().updateGroup(groupV1
);
1496 if (groupV1
== null && !isSync
) {
1497 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1501 if (groupV1
!= null) {
1502 groupV1
.removeMember(source
);
1503 account
.getGroupStore().updateGroup(groupV1
);
1508 if (groupV1
!= null && !isSync
) {
1509 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1514 // Received a group v1 message for a v2 group
1517 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1518 final SignalServiceGroupV2 groupContext
= message
.getGroupContext().get().getGroupV2().get();
1519 final GroupMasterKey groupMasterKey
= groupContext
.getMasterKey();
1521 getOrMigrateGroup(groupMasterKey
,
1522 groupContext
.getRevision(),
1523 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1527 final SignalServiceAddress conversationPartnerAddress
= isSync ? destination
: source
;
1528 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1529 handleEndSession(conversationPartnerAddress
);
1531 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1532 if (message
.getGroupContext().isPresent()) {
1533 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1534 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1535 GroupInfoV1 group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1536 if (group
!= null) {
1537 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1538 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1539 account
.getGroupStore().updateGroup(group
);
1542 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1543 // disappearing message timer already stored in the DecryptedGroup
1545 } else if (conversationPartnerAddress
!= null) {
1546 ContactInfo contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1547 if (contact
== null) {
1548 contact
= new ContactInfo(conversationPartnerAddress
);
1550 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1551 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1552 account
.getContactStore().updateContact(contact
);
1556 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1557 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1558 downloadAttachment(attachment
);
1561 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1562 final ProfileKey profileKey
;
1564 profileKey
= new ProfileKey(message
.getProfileKey().get());
1565 } catch (InvalidInputException e
) {
1566 throw new AssertionError(e
);
1568 if (source
.matches(account
.getSelfAddress())) {
1569 this.account
.setProfileKey(profileKey
);
1571 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1573 if (message
.getPreviews().isPresent()) {
1574 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1575 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1576 if (preview
.getImage().isPresent()) {
1577 downloadAttachment(preview
.getImage().get());
1581 if (message
.getQuote().isPresent()) {
1582 final SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1584 for (SignalServiceDataMessage
.Quote
.QuotedAttachment quotedAttachment
: quote
.getAttachments()) {
1585 final SignalServiceAttachment thumbnail
= quotedAttachment
.getThumbnail();
1586 if (thumbnail
!= null) {
1587 downloadAttachment(thumbnail
);
1591 if (message
.getSticker().isPresent()) {
1592 final SignalServiceDataMessage
.Sticker messageSticker
= message
.getSticker().get();
1593 Sticker sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1594 if (sticker
== null) {
1595 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1596 account
.getStickerStore().updateSticker(sticker
);
1602 private GroupInfoV2
getOrMigrateGroup(
1603 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1605 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1607 GroupIdV2 groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1608 GroupInfo groupInfo
= getGroup(groupId
);
1609 final GroupInfoV2 groupInfoV2
;
1610 if (groupInfo
instanceof GroupInfoV1
) {
1611 // Received a v2 group message for a v1 group, we need to locally migrate the group
1612 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1613 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1614 logger
.info("Locally migrated group {} to group v2, id: {}",
1615 groupInfo
.getGroupId().toBase64(),
1616 groupInfoV2
.getGroupId().toBase64());
1617 } else if (groupInfo
instanceof GroupInfoV2
) {
1618 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1620 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1623 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1624 DecryptedGroup group
= null;
1625 if (signedGroupChange
!= null
1626 && groupInfoV2
.getGroup() != null
1627 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1628 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1630 if (group
== null) {
1631 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1633 if (group
!= null) {
1634 storeProfileKeysFromMembers(group
);
1635 final String avatar
= group
.getAvatar();
1636 if (avatar
!= null && !avatar
.isEmpty()) {
1637 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1640 groupInfoV2
.setGroup(group
);
1641 account
.getGroupStore().updateGroup(groupInfoV2
);
1647 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1648 for (DecryptedMember member
: group
.getMembersList()) {
1649 final SignalServiceAddress address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(
1650 member
.getUuid().toByteArray()), null));
1652 account
.getProfileStore()
1653 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1654 } catch (InvalidInputException ignored
) {
1659 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1660 for (CachedMessage cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1661 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1665 private void retryFailedReceivedMessage(
1666 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1668 SignalServiceEnvelope envelope
= cachedMessage
.loadEnvelope();
1669 if (envelope
== null) {
1672 SignalServiceContent content
= null;
1673 if (!envelope
.isReceipt()) {
1675 content
= decryptMessage(envelope
);
1676 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1678 } catch (Exception er
) {
1679 // All other errors are not recoverable, so delete the cached message
1680 cachedMessage
.delete();
1683 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1684 for (HandleAction action
: actions
) {
1686 action
.execute(this);
1687 } catch (Throwable e
) {
1688 logger
.warn("Message action failed.", e
);
1693 handler
.handleMessage(envelope
, content
, null);
1694 cachedMessage
.delete();
1697 public void receiveMessages(
1700 boolean returnOnTimeout
,
1701 boolean ignoreAttachments
,
1702 ReceiveMessageHandler handler
1703 ) throws IOException
{
1704 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1706 Set
<HandleAction
> queuedActions
= null;
1708 final SignalServiceMessagePipe messagePipe
= getOrCreateMessagePipe();
1710 boolean hasCaughtUpWithOldMessages
= false;
1713 SignalServiceEnvelope envelope
;
1714 SignalServiceContent content
= null;
1715 Exception exception
= null;
1716 final CachedMessage
[] cachedMessage
= {null};
1718 Optional
<SignalServiceEnvelope
> result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1719 // store message on disk, before acknowledging receipt to the server
1720 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
);
1722 if (result
.isPresent()) {
1723 envelope
= result
.get();
1725 // Received indicator that server queue is empty
1726 hasCaughtUpWithOldMessages
= true;
1728 if (queuedActions
!= null) {
1729 for (HandleAction action
: queuedActions
) {
1731 action
.execute(this);
1732 } catch (Throwable e
) {
1733 logger
.warn("Message action failed.", e
);
1737 queuedActions
.clear();
1738 queuedActions
= null;
1741 // Continue to wait another timeout for new messages
1744 } catch (TimeoutException e
) {
1745 if (returnOnTimeout
) return;
1749 if (envelope
.hasSource()) {
1750 // Store uuid if we don't have it already
1751 SignalServiceAddress source
= envelope
.getSourceAddress();
1752 resolveSignalServiceAddress(source
);
1754 if (!envelope
.isReceipt()) {
1756 content
= decryptMessage(envelope
);
1757 } catch (Exception e
) {
1760 List
<HandleAction
> actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1761 if (hasCaughtUpWithOldMessages
) {
1762 for (HandleAction action
: actions
) {
1764 action
.execute(this);
1765 } catch (Throwable e
) {
1766 logger
.warn("Message action failed.", e
);
1770 if (queuedActions
== null) {
1771 queuedActions
= new HashSet
<>();
1773 queuedActions
.addAll(actions
);
1777 if (isMessageBlocked(envelope
, content
)) {
1778 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1779 } else if (isNotAGroupMember(envelope
, content
)) {
1780 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1782 handler
.handleMessage(envelope
, content
, exception
);
1784 if (!(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1785 if (cachedMessage
[0] != null) {
1786 cachedMessage
[0].delete();
1792 private boolean isMessageBlocked(
1793 SignalServiceEnvelope envelope
, SignalServiceContent content
1795 SignalServiceAddress source
;
1796 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1797 source
= envelope
.getSourceAddress();
1798 } else if (content
!= null) {
1799 source
= content
.getSender();
1803 ContactInfo sourceContact
= account
.getContactStore().getContact(source
);
1804 if (sourceContact
!= null && sourceContact
.blocked
) {
1808 if (content
!= null && content
.getDataMessage().isPresent()) {
1809 SignalServiceDataMessage message
= content
.getDataMessage().get();
1810 if (message
.getGroupContext().isPresent()) {
1811 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1812 GroupInfo group
= getGroup(groupId
);
1813 if (group
!= null && group
.isBlocked()) {
1821 private boolean isNotAGroupMember(
1822 SignalServiceEnvelope envelope
, SignalServiceContent content
1824 SignalServiceAddress source
;
1825 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1826 source
= envelope
.getSourceAddress();
1827 } else if (content
!= null) {
1828 source
= content
.getSender();
1833 if (content
!= null && content
.getDataMessage().isPresent()) {
1834 SignalServiceDataMessage message
= content
.getDataMessage().get();
1835 if (message
.getGroupContext().isPresent()) {
1836 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1837 SignalServiceGroup groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1838 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1842 GroupId groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1843 GroupInfo group
= getGroup(groupId
);
1844 if (group
!= null && !group
.isMember(source
)) {
1852 private List
<HandleAction
> handleMessage(
1853 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1855 List
<HandleAction
> actions
= new ArrayList
<>();
1856 if (content
!= null) {
1857 final SignalServiceAddress sender
;
1858 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1859 sender
= envelope
.getSourceAddress();
1861 sender
= content
.getSender();
1863 // Store uuid if we don't have it already
1864 resolveSignalServiceAddress(sender
);
1866 if (content
.getDataMessage().isPresent()) {
1867 SignalServiceDataMessage message
= content
.getDataMessage().get();
1869 if (content
.isNeedsReceipt()) {
1870 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1873 actions
.addAll(handleSignalServiceDataMessage(message
,
1876 account
.getSelfAddress(),
1877 ignoreAttachments
));
1879 if (content
.getSyncMessage().isPresent()) {
1880 account
.setMultiDevice(true);
1881 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1882 if (syncMessage
.getSent().isPresent()) {
1883 SentTranscriptMessage message
= syncMessage
.getSent().get();
1884 final SignalServiceAddress destination
= message
.getDestination().orNull();
1885 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1889 ignoreAttachments
));
1891 if (syncMessage
.getRequest().isPresent()) {
1892 RequestMessage rm
= syncMessage
.getRequest().get();
1893 if (rm
.isContactsRequest()) {
1894 actions
.add(SendSyncContactsAction
.create());
1896 if (rm
.isGroupsRequest()) {
1897 actions
.add(SendSyncGroupsAction
.create());
1899 if (rm
.isBlockedListRequest()) {
1900 actions
.add(SendSyncBlockedListAction
.create());
1902 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1904 if (syncMessage
.getGroups().isPresent()) {
1905 File tmpFile
= null;
1907 tmpFile
= IOUtils
.createTempFile();
1908 final SignalServiceAttachment groupsMessage
= syncMessage
.getGroups().get();
1909 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(),
1911 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1913 while ((g
= s
.read()) != null) {
1914 GroupInfoV1 syncGroup
= account
.getGroupStore()
1915 .getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1916 if (syncGroup
!= null) {
1917 if (g
.getName().isPresent()) {
1918 syncGroup
.name
= g
.getName().get();
1920 syncGroup
.addMembers(g
.getMembers()
1922 .map(this::resolveSignalServiceAddress
)
1923 .collect(Collectors
.toSet()));
1924 if (!g
.isActive()) {
1925 syncGroup
.removeMember(account
.getSelfAddress());
1927 // Add ourself to the member set as it's marked as active
1928 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1930 syncGroup
.blocked
= g
.isBlocked();
1931 if (g
.getColor().isPresent()) {
1932 syncGroup
.color
= g
.getColor().get();
1935 if (g
.getAvatar().isPresent()) {
1936 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1938 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1939 syncGroup
.archived
= g
.isArchived();
1940 account
.getGroupStore().updateGroup(syncGroup
);
1944 } catch (Exception e
) {
1945 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1949 if (tmpFile
!= null) {
1951 Files
.delete(tmpFile
.toPath());
1952 } catch (IOException e
) {
1953 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1960 if (syncMessage
.getBlockedList().isPresent()) {
1961 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1962 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1963 setContactBlocked(resolveSignalServiceAddress(address
), true);
1965 for (GroupId groupId
: blockedListMessage
.getGroupIds()
1967 .map(GroupId
::unknownVersion
)
1968 .collect(Collectors
.toSet())) {
1970 setGroupBlocked(groupId
, true);
1971 } catch (GroupNotFoundException e
) {
1972 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1973 groupId
.toBase64());
1977 if (syncMessage
.getContacts().isPresent()) {
1978 File tmpFile
= null;
1980 tmpFile
= IOUtils
.createTempFile();
1981 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1982 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1983 .asPointer(), tmpFile
)) {
1984 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1985 if (contactsMessage
.isComplete()) {
1986 account
.getContactStore().clear();
1989 while ((c
= s
.read()) != null) {
1990 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1991 account
.setProfileKey(c
.getProfileKey().get());
1993 final SignalServiceAddress address
= resolveSignalServiceAddress(c
.getAddress());
1994 ContactInfo contact
= account
.getContactStore().getContact(address
);
1995 if (contact
== null) {
1996 contact
= new ContactInfo(address
);
1998 if (c
.getName().isPresent()) {
1999 contact
.name
= c
.getName().get();
2001 if (c
.getColor().isPresent()) {
2002 contact
.color
= c
.getColor().get();
2004 if (c
.getProfileKey().isPresent()) {
2005 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
2007 if (c
.getVerified().isPresent()) {
2008 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
2009 account
.getSignalProtocolStore()
2010 .setIdentityTrustLevel(verifiedMessage
.getDestination(),
2011 verifiedMessage
.getIdentityKey(),
2012 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2014 if (c
.getExpirationTimer().isPresent()) {
2015 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
2017 contact
.blocked
= c
.isBlocked();
2018 contact
.inboxPosition
= c
.getInboxPosition().orNull();
2019 contact
.archived
= c
.isArchived();
2020 account
.getContactStore().updateContact(contact
);
2022 if (c
.getAvatar().isPresent()) {
2023 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2027 } catch (Exception e
) {
2028 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2032 if (tmpFile
!= null) {
2034 Files
.delete(tmpFile
.toPath());
2035 } catch (IOException e
) {
2036 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2043 if (syncMessage
.getVerified().isPresent()) {
2044 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
2045 account
.getSignalProtocolStore()
2046 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage
.getDestination()),
2047 verifiedMessage
.getIdentityKey(),
2048 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2050 if (syncMessage
.getStickerPackOperations().isPresent()) {
2051 final List
<StickerPackOperationMessage
> stickerPackOperationMessages
= syncMessage
.getStickerPackOperations()
2053 for (StickerPackOperationMessage m
: stickerPackOperationMessages
) {
2054 if (!m
.getPackId().isPresent()) {
2057 Sticker sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2058 if (sticker
== null) {
2059 if (!m
.getPackKey().isPresent()) {
2062 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2064 sticker
.setInstalled(!m
.getType().isPresent()
2065 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2066 account
.getStickerStore().updateSticker(sticker
);
2069 if (syncMessage
.getFetchType().isPresent()) {
2070 switch (syncMessage
.getFetchType().get()) {
2072 getRecipientProfile(getSelfAddress(), true);
2073 case STORAGE_MANIFEST
:
2077 if (syncMessage
.getKeys().isPresent()) {
2078 final KeysMessage keysMessage
= syncMessage
.getKeys().get();
2079 if (keysMessage
.getStorageService().isPresent()) {
2080 final StorageKey storageKey
= keysMessage
.getStorageService().get();
2081 account
.setStorageKey(storageKey
);
2084 if (syncMessage
.getConfiguration().isPresent()) {
2092 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2094 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2095 } catch (IOException e
) {
2096 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2100 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2102 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2103 } catch (IOException e
) {
2104 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2108 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2110 avatarStore
.storeGroupAvatar(groupId
,
2111 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2112 } catch (IOException e
) {
2113 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2117 private void downloadProfileAvatar(
2118 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2121 avatarStore
.storeProfileAvatar(address
,
2122 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2123 } catch (Throwable e
) {
2124 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2128 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2129 return attachmentStore
.getAttachmentFile(attachmentId
);
2132 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2133 if (!attachment
.isPointer()) {
2134 logger
.warn("Invalid state, can't store an attachment stream.");
2137 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2138 if (pointer
.getPreview().isPresent()) {
2139 final byte[] preview
= pointer
.getPreview().get();
2141 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2142 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2143 } catch (IOException e
) {
2144 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2149 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2150 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2151 } catch (IOException e
) {
2152 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2156 private void retrieveGroupV2Avatar(
2157 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2158 ) throws IOException
{
2159 GroupsV2Operations
.GroupOperations groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2161 File tmpFile
= IOUtils
.createTempFile();
2162 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2164 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2165 byte[] encryptedData
= IOUtils
.readFully(input
);
2167 byte[] decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2168 outputStream
.write(decryptedData
);
2171 Files
.delete(tmpFile
.toPath());
2172 } catch (IOException e
) {
2173 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2180 private void retrieveProfileAvatar(
2181 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2182 ) throws IOException
{
2183 File tmpFile
= IOUtils
.createTempFile();
2184 try (InputStream input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2187 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2188 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2189 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2192 Files
.delete(tmpFile
.toPath());
2193 } catch (IOException e
) {
2194 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2201 private void retrieveAttachment(
2202 final SignalServiceAttachment attachment
, final OutputStream outputStream
2203 ) throws IOException
{
2204 if (attachment
.isPointer()) {
2205 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
2206 retrieveAttachmentPointer(pointer
, outputStream
);
2208 SignalServiceAttachmentStream stream
= attachment
.asStream();
2209 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2213 private void retrieveAttachmentPointer(
2214 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2215 ) throws IOException
{
2216 File tmpFile
= IOUtils
.createTempFile();
2217 try (InputStream input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2218 IOUtils
.copyStream(input
, outputStream
);
2219 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2220 throw new IOException(e
);
2223 Files
.delete(tmpFile
.toPath());
2224 } catch (IOException e
) {
2225 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2232 private InputStream
retrieveAttachmentAsStream(
2233 SignalServiceAttachmentPointer pointer
, File tmpFile
2234 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2235 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2238 void sendGroups() throws IOException
, UntrustedIdentityException
{
2239 File groupsFile
= IOUtils
.createTempFile();
2242 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2243 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
2244 for (GroupInfo
record : getGroups()) {
2245 if (record instanceof GroupInfoV1
) {
2246 GroupInfoV1 groupInfo
= (GroupInfoV1
) record;
2247 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2248 Optional
.fromNullable(groupInfo
.name
),
2249 new ArrayList
<>(groupInfo
.getMembers()),
2250 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2251 groupInfo
.isMember(account
.getSelfAddress()),
2252 Optional
.of(groupInfo
.messageExpirationTime
),
2253 Optional
.fromNullable(groupInfo
.color
),
2255 Optional
.fromNullable(groupInfo
.inboxPosition
),
2256 groupInfo
.archived
));
2261 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2262 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
2263 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2264 .withStream(groupsFileStream
)
2265 .withContentType("application/octet-stream")
2266 .withLength(groupsFile
.length())
2269 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2274 Files
.delete(groupsFile
.toPath());
2275 } catch (IOException e
) {
2276 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2281 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2282 File contactsFile
= IOUtils
.createTempFile();
2285 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2286 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
2287 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2288 VerifiedMessage verifiedMessage
= null;
2289 IdentityInfo currentIdentity
= account
.getSignalProtocolStore().getIdentity(record.getAddress());
2290 if (currentIdentity
!= null) {
2291 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2292 currentIdentity
.getIdentityKey(),
2293 currentIdentity
.getTrustLevel().toVerifiedState(),
2294 currentIdentity
.getDateAdded().getTime());
2297 ProfileKey profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2298 out
.write(new DeviceContact(record.getAddress(),
2299 Optional
.fromNullable(record.name
),
2300 createContactAvatarAttachment(record.getAddress()),
2301 Optional
.fromNullable(record.color
),
2302 Optional
.fromNullable(verifiedMessage
),
2303 Optional
.fromNullable(profileKey
),
2305 Optional
.of(record.messageExpirationTime
),
2306 Optional
.fromNullable(record.inboxPosition
),
2310 if (account
.getProfileKey() != null) {
2311 // Send our own profile key as well
2312 out
.write(new DeviceContact(account
.getSelfAddress(),
2317 Optional
.of(account
.getProfileKey()),
2325 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2326 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
2327 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2328 .withStream(contactsFileStream
)
2329 .withContentType("application/octet-stream")
2330 .withLength(contactsFile
.length())
2333 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2338 Files
.delete(contactsFile
.toPath());
2339 } catch (IOException e
) {
2340 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2345 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2346 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
2347 for (ContactInfo
record : account
.getContactStore().getContacts()) {
2348 if (record.blocked
) {
2349 addresses
.add(record.getAddress());
2352 List
<byte[]> groupIds
= new ArrayList
<>();
2353 for (GroupInfo
record : getGroups()) {
2354 if (record.isBlocked()) {
2355 groupIds
.add(record.getGroupId().serialize());
2358 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2361 private void sendVerifiedMessage(
2362 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2363 ) throws IOException
, UntrustedIdentityException
{
2364 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
,
2366 trustLevel
.toVerifiedState(),
2367 System
.currentTimeMillis());
2368 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2371 public List
<ContactInfo
> getContacts() {
2372 return account
.getContactStore().getContacts();
2375 public String
getContactOrProfileName(String number
) {
2376 final SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2378 final ContactInfo contact
= account
.getContactStore().getContact(address
);
2379 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2380 return contact
.name
;
2383 final SignalProfileEntry profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2384 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2385 return profileEntry
.getProfile().getName();
2391 public GroupInfo
getGroup(GroupId groupId
) {
2392 final GroupInfo group
= account
.getGroupStore().getGroup(groupId
);
2393 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2394 final GroupSecretParams groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2395 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2396 account
.getGroupStore().updateGroup(group
);
2401 public List
<IdentityInfo
> getIdentities() {
2402 return account
.getSignalProtocolStore().getIdentities();
2405 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2406 return account
.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number
));
2410 * Trust this the identity with this fingerprint
2412 * @param name username of the identity
2413 * @param fingerprint Fingerprint
2415 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2416 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2417 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2421 for (IdentityInfo id
: ids
) {
2422 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
2426 account
.getSignalProtocolStore()
2427 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2429 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2430 } catch (IOException
| UntrustedIdentityException e
) {
2431 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2440 * Trust this the identity with this safety number
2442 * @param name username of the identity
2443 * @param safetyNumber Safety number
2445 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2446 SignalServiceAddress address
= canonicalizeAndResolveSignalServiceAddress(name
);
2447 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2451 for (IdentityInfo id
: ids
) {
2452 if (!safetyNumber
.equals(computeSafetyNumber(address
, id
.getIdentityKey()))) {
2456 account
.getSignalProtocolStore()
2457 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2459 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
2460 } catch (IOException
| UntrustedIdentityException e
) {
2461 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2470 * Trust all keys of this identity without verification
2472 * @param name username of the identity
2474 public boolean trustIdentityAllKeys(String name
) {
2475 SignalServiceAddress address
= resolveSignalServiceAddress(name
);
2476 List
<IdentityInfo
> ids
= account
.getSignalProtocolStore().getIdentities(address
);
2480 for (IdentityInfo id
: ids
) {
2481 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
2482 account
.getSignalProtocolStore()
2483 .setIdentityTrustLevel(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2485 sendVerifiedMessage(address
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
2486 } catch (IOException
| UntrustedIdentityException e
) {
2487 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2495 public String
computeSafetyNumber(
2496 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2498 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2499 account
.getSelfAddress(),
2500 getIdentityKeyPair().getPublicKey(),
2505 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2506 String canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2508 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2509 return resolveSignalServiceAddress(canonicalizedNumber
);
2512 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2513 SignalServiceAddress address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2515 return resolveSignalServiceAddress(address
);
2518 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2519 if (address
.matches(account
.getSelfAddress())) {
2520 return account
.getSelfAddress();
2523 return account
.getRecipientStore().resolveServiceAddress(address
);
2527 public void close() throws IOException
{
2531 void close(boolean closeAccount
) throws IOException
{
2532 executor
.shutdown();
2534 if (messagePipe
!= null) {
2535 messagePipe
.shutdown();
2539 if (unidentifiedMessagePipe
!= null) {
2540 unidentifiedMessagePipe
.shutdown();
2541 unidentifiedMessagePipe
= null;
2544 if (closeAccount
&& account
!= null) {
2550 public interface ReceiveMessageHandler
{
2552 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);