1 package org
.asamk
.signal
.manager
.storage
;
3 import com
.fasterxml
.jackson
.databind
.JsonNode
;
4 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
6 import org
.asamk
.signal
.manager
.api
.Pair
;
7 import org
.asamk
.signal
.manager
.api
.TrustLevel
;
8 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
9 import org
.asamk
.signal
.manager
.groups
.GroupId
;
10 import org
.asamk
.signal
.manager
.helper
.RecipientAddressResolver
;
11 import org
.asamk
.signal
.manager
.storage
.configuration
.ConfigurationStore
;
12 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactsStore
;
13 import org
.asamk
.signal
.manager
.storage
.contacts
.LegacyJsonContactsStore
;
14 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
15 import org
.asamk
.signal
.manager
.storage
.groups
.GroupStore
;
16 import org
.asamk
.signal
.manager
.storage
.groups
.LegacyGroupStore
;
17 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityKeyStore
;
18 import org
.asamk
.signal
.manager
.storage
.identities
.LegacyIdentityKeyStore
;
19 import org
.asamk
.signal
.manager
.storage
.identities
.SignalIdentityKeyStore
;
20 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
21 import org
.asamk
.signal
.manager
.storage
.messageCache
.MessageCache
;
22 import org
.asamk
.signal
.manager
.storage
.prekeys
.LegacyPreKeyStore
;
23 import org
.asamk
.signal
.manager
.storage
.prekeys
.LegacySignedPreKeyStore
;
24 import org
.asamk
.signal
.manager
.storage
.prekeys
.PreKeyStore
;
25 import org
.asamk
.signal
.manager
.storage
.prekeys
.SignedPreKeyStore
;
26 import org
.asamk
.signal
.manager
.storage
.profiles
.LegacyProfileStore
;
27 import org
.asamk
.signal
.manager
.storage
.profiles
.ProfileStore
;
28 import org
.asamk
.signal
.manager
.storage
.protocol
.LegacyJsonSignalProtocolStore
;
29 import org
.asamk
.signal
.manager
.storage
.protocol
.SignalProtocolStore
;
30 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
31 import org
.asamk
.signal
.manager
.storage
.recipients
.LegacyRecipientStore
;
32 import org
.asamk
.signal
.manager
.storage
.recipients
.LegacyRecipientStore2
;
33 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
34 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
35 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
36 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientIdCreator
;
37 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientResolver
;
38 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientStore
;
39 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientTrustedResolver
;
40 import org
.asamk
.signal
.manager
.storage
.sendLog
.MessageSendLogStore
;
41 import org
.asamk
.signal
.manager
.storage
.senderKeys
.LegacySenderKeyRecordStore
;
42 import org
.asamk
.signal
.manager
.storage
.senderKeys
.LegacySenderKeySharedStore
;
43 import org
.asamk
.signal
.manager
.storage
.senderKeys
.SenderKeyStore
;
44 import org
.asamk
.signal
.manager
.storage
.sessions
.LegacySessionStore
;
45 import org
.asamk
.signal
.manager
.storage
.sessions
.SessionStore
;
46 import org
.asamk
.signal
.manager
.storage
.stickers
.LegacyStickerStore
;
47 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerStore
;
48 import org
.asamk
.signal
.manager
.storage
.threads
.LegacyJsonThreadStore
;
49 import org
.asamk
.signal
.manager
.util
.IOUtils
;
50 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
51 import org
.signal
.libsignal
.protocol
.IdentityKeyPair
;
52 import org
.signal
.libsignal
.protocol
.InvalidMessageException
;
53 import org
.signal
.libsignal
.protocol
.SignalProtocolAddress
;
54 import org
.signal
.libsignal
.protocol
.state
.PreKeyRecord
;
55 import org
.signal
.libsignal
.protocol
.state
.SessionRecord
;
56 import org
.signal
.libsignal
.protocol
.state
.SignedPreKeyRecord
;
57 import org
.signal
.libsignal
.protocol
.util
.KeyHelper
;
58 import org
.signal
.libsignal
.protocol
.util
.Medium
;
59 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
60 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
61 import org
.slf4j
.Logger
;
62 import org
.slf4j
.LoggerFactory
;
63 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountDataStore
;
64 import org
.whispersystems
.signalservice
.api
.SignalServiceDataStore
;
65 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
66 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
67 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
68 import org
.whispersystems
.signalservice
.api
.push
.PNI
;
69 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
70 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
71 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
72 import org
.whispersystems
.signalservice
.api
.storage
.SignalStorageManifest
;
73 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
74 import org
.whispersystems
.signalservice
.api
.util
.CredentialsProvider
;
75 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
77 import java
.io
.ByteArrayInputStream
;
78 import java
.io
.ByteArrayOutputStream
;
79 import java
.io
.Closeable
;
81 import java
.io
.FileInputStream
;
82 import java
.io
.FileOutputStream
;
83 import java
.io
.IOException
;
84 import java
.io
.RandomAccessFile
;
85 import java
.nio
.channels
.Channels
;
86 import java
.nio
.channels
.ClosedChannelException
;
87 import java
.nio
.channels
.FileChannel
;
88 import java
.nio
.channels
.FileLock
;
89 import java
.nio
.file
.Files
;
90 import java
.security
.SecureRandom
;
91 import java
.sql
.SQLException
;
92 import java
.util
.Base64
;
93 import java
.util
.Comparator
;
94 import java
.util
.HashSet
;
95 import java
.util
.List
;
96 import java
.util
.Optional
;
97 import java
.util
.function
.Supplier
;
99 public class SignalAccount
implements Closeable
{
101 private final static Logger logger
= LoggerFactory
.getLogger(SignalAccount
.class);
103 private static final int MINIMUM_STORAGE_VERSION
= 1;
104 private static final int CURRENT_STORAGE_VERSION
= 5;
106 private final Object LOCK
= new Object();
108 private final ObjectMapper jsonProcessor
= Utils
.createStorageObjectMapper();
110 private final FileChannel fileChannel
;
111 private final FileLock lock
;
113 private int previousStorageVersion
;
115 private File dataPath
;
116 private String accountPath
;
117 private ServiceEnvironment serviceEnvironment
;
118 private String number
;
121 private String encryptedDeviceName
;
122 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
123 private boolean isMultiDevice
= false;
124 private String password
;
125 private String registrationLockPin
;
126 private MasterKey pinMasterKey
;
127 private StorageKey storageKey
;
128 private long storageManifestVersion
= -1;
129 private ProfileKey profileKey
;
130 private int aciPreKeyIdOffset
= 1;
131 private int aciNextSignedPreKeyId
= 1;
132 private int pniPreKeyIdOffset
= 1;
133 private int pniNextSignedPreKeyId
= 1;
134 private IdentityKeyPair aciIdentityKeyPair
;
135 private IdentityKeyPair pniIdentityKeyPair
;
136 private int localRegistrationId
;
137 private int localPniRegistrationId
;
138 private TrustNewIdentity trustNewIdentity
;
139 private long lastReceiveTimestamp
= 0;
141 private boolean registered
= false;
143 private SignalProtocolStore aciSignalProtocolStore
;
144 private SignalProtocolStore pniSignalProtocolStore
;
145 private PreKeyStore aciPreKeyStore
;
146 private SignedPreKeyStore aciSignedPreKeyStore
;
147 private PreKeyStore pniPreKeyStore
;
148 private SignedPreKeyStore pniSignedPreKeyStore
;
149 private SessionStore aciSessionStore
;
150 private SessionStore pniSessionStore
;
151 private IdentityKeyStore identityKeyStore
;
152 private SignalIdentityKeyStore aciIdentityKeyStore
;
153 private SignalIdentityKeyStore pniIdentityKeyStore
;
154 private SenderKeyStore senderKeyStore
;
155 private GroupStore groupStore
;
156 private RecipientStore recipientStore
;
157 private StickerStore stickerStore
;
158 private ConfigurationStore configurationStore
;
159 private ConfigurationStore
.Storage configurationStoreStorage
;
161 private MessageCache messageCache
;
162 private MessageSendLogStore messageSendLogStore
;
164 private AccountDatabase accountDatabase
;
166 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
167 this.fileChannel
= fileChannel
;
171 public static SignalAccount
load(
172 File dataPath
, String accountPath
, boolean waitForLock
, final TrustNewIdentity trustNewIdentity
173 ) throws IOException
{
174 logger
.trace("Opening account file");
175 final var fileName
= getFileName(dataPath
, accountPath
);
176 final var pair
= openFileChannel(fileName
, waitForLock
);
178 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
179 logger
.trace("Loading account file");
180 signalAccount
.load(dataPath
, accountPath
, trustNewIdentity
);
181 logger
.trace("Migrating legacy parts of account file");
182 signalAccount
.migrateLegacyConfigs();
184 return signalAccount
;
185 } catch (Throwable e
) {
186 pair
.second().close();
187 pair
.first().close();
192 public static SignalAccount
create(
196 ServiceEnvironment serviceEnvironment
,
197 IdentityKeyPair aciIdentityKey
,
198 IdentityKeyPair pniIdentityKey
,
200 int pniRegistrationId
,
201 ProfileKey profileKey
,
202 final TrustNewIdentity trustNewIdentity
203 ) throws IOException
{
204 IOUtils
.createPrivateDirectories(dataPath
);
205 var fileName
= getFileName(dataPath
, accountPath
);
206 if (!fileName
.exists()) {
207 IOUtils
.createPrivateFile(fileName
);
210 final var pair
= openFileChannel(fileName
, true);
211 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
213 signalAccount
.accountPath
= accountPath
;
214 signalAccount
.number
= number
;
215 signalAccount
.serviceEnvironment
= serviceEnvironment
;
216 signalAccount
.profileKey
= profileKey
;
218 signalAccount
.dataPath
= dataPath
;
219 signalAccount
.aciIdentityKeyPair
= aciIdentityKey
;
220 signalAccount
.pniIdentityKeyPair
= pniIdentityKey
;
221 signalAccount
.localRegistrationId
= registrationId
;
222 signalAccount
.localPniRegistrationId
= pniRegistrationId
;
223 signalAccount
.trustNewIdentity
= trustNewIdentity
;
224 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
226 signalAccount
.registered
= false;
228 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
229 signalAccount
.migrateLegacyConfigs();
230 signalAccount
.save();
232 return signalAccount
;
235 public static SignalAccount
createOrUpdateLinkedAccount(
239 ServiceEnvironment serviceEnvironment
,
243 String encryptedDeviceName
,
245 IdentityKeyPair aciIdentityKey
,
246 IdentityKeyPair pniIdentityKey
,
248 int pniRegistrationId
,
249 ProfileKey profileKey
,
250 final TrustNewIdentity trustNewIdentity
251 ) throws IOException
{
252 IOUtils
.createPrivateDirectories(dataPath
);
253 var fileName
= getFileName(dataPath
, accountPath
);
254 if (!fileName
.exists()) {
255 return createLinkedAccount(dataPath
,
272 final var signalAccount
= load(dataPath
, accountPath
, true, trustNewIdentity
);
273 signalAccount
.setProvisioningData(number
,
282 signalAccount
.getRecipientTrustedResolver()
283 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
284 signalAccount
.getAciSessionStore().archiveAllSessions();
285 signalAccount
.getPniSessionStore().archiveAllSessions();
286 signalAccount
.getSenderKeyStore().deleteAll();
287 signalAccount
.clearAllPreKeys();
288 return signalAccount
;
291 public void initDatabase() {
292 getAccountDatabase();
295 private void clearAllPreKeys() {
296 this.aciPreKeyIdOffset
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
297 this.aciNextSignedPreKeyId
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
298 this.pniPreKeyIdOffset
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
299 this.pniNextSignedPreKeyId
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
300 this.getAciPreKeyStore().removeAllPreKeys();
301 this.getAciSignedPreKeyStore().removeAllSignedPreKeys();
302 this.getPniPreKeyStore().removeAllPreKeys();
303 this.getPniSignedPreKeyStore().removeAllSignedPreKeys();
307 private static SignalAccount
createLinkedAccount(
311 ServiceEnvironment serviceEnvironment
,
315 String encryptedDeviceName
,
317 IdentityKeyPair aciIdentityKey
,
318 IdentityKeyPair pniIdentityKey
,
320 int pniRegistrationId
,
321 ProfileKey profileKey
,
322 final TrustNewIdentity trustNewIdentity
323 ) throws IOException
{
324 var fileName
= getFileName(dataPath
, accountPath
);
325 IOUtils
.createPrivateFile(fileName
);
327 final var pair
= openFileChannel(fileName
, true);
328 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
330 signalAccount
.dataPath
= dataPath
;
331 signalAccount
.accountPath
= accountPath
;
332 signalAccount
.serviceEnvironment
= serviceEnvironment
;
333 signalAccount
.localRegistrationId
= registrationId
;
334 signalAccount
.localPniRegistrationId
= pniRegistrationId
;
335 signalAccount
.trustNewIdentity
= trustNewIdentity
;
336 signalAccount
.setProvisioningData(number
,
346 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
348 signalAccount
.getRecipientTrustedResolver()
349 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
350 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
351 signalAccount
.migrateLegacyConfigs();
352 signalAccount
.clearAllPreKeys();
353 signalAccount
.save();
355 return signalAccount
;
358 private void setProvisioningData(
362 final String password
,
363 final String encryptedDeviceName
,
365 final IdentityKeyPair aciIdentity
,
366 final IdentityKeyPair pniIdentity
,
367 final ProfileKey profileKey
369 this.number
= number
;
372 this.password
= password
;
373 this.profileKey
= profileKey
;
374 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
375 this.encryptedDeviceName
= encryptedDeviceName
;
376 this.deviceId
= deviceId
;
377 this.aciIdentityKeyPair
= aciIdentity
;
378 this.pniIdentityKeyPair
= pniIdentity
;
379 this.registered
= true;
380 this.isMultiDevice
= true;
381 this.lastReceiveTimestamp
= 0;
382 this.pinMasterKey
= null;
383 this.storageManifestVersion
= -1;
384 this.setStorageManifest(null);
385 this.storageKey
= null;
386 final var aciPublicKey
= getAciIdentityKeyPair().getPublicKey();
387 getIdentityKeyStore().saveIdentity(getAci(), aciPublicKey
);
388 getIdentityKeyStore().setIdentityTrustLevel(getAci(), aciPublicKey
, TrustLevel
.TRUSTED_VERIFIED
);
389 if (getPniIdentityKeyPair() != null) {
390 final var pniPublicKey
= getPniIdentityKeyPair().getPublicKey();
391 getIdentityKeyStore().saveIdentity(getPni(), pniPublicKey
);
392 getIdentityKeyStore().setIdentityTrustLevel(getPni(), pniPublicKey
, TrustLevel
.TRUSTED_VERIFIED
);
396 private void migrateLegacyConfigs() {
397 if (getPassword() == null) {
398 setPassword(KeyUtils
.createPassword());
401 if (getProfileKey() == null) {
402 // Old config file, creating new profile key
403 setProfileKey(KeyUtils
.createProfileKey());
405 getProfileStore().storeProfileKey(getSelfRecipientId(), getProfileKey());
406 if (isPrimaryDevice() && getPniIdentityKeyPair() == null && getPni() != null) {
407 setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
411 private void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
412 getMessageCache().mergeRecipients(recipientId
, toBeMergedRecipientId
);
413 getGroupStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
416 public void removeRecipient(final RecipientId recipientId
) {
417 getRecipientStore().deleteRecipientData(recipientId
);
418 getMessageCache().deleteMessages(recipientId
);
419 final var recipientAddress
= getRecipientStore().resolveRecipientAddress(recipientId
);
420 if (recipientAddress
.uuid().isPresent()) {
421 final var serviceId
= ServiceId
.from(recipientAddress
.uuid().get());
422 getAciSessionStore().deleteAllSessions(serviceId
);
423 getPniSessionStore().deleteAllSessions(serviceId
);
424 getIdentityKeyStore().deleteIdentity(serviceId
);
425 getSenderKeyStore().deleteAll(serviceId
);
429 public static File
getFileName(File dataPath
, String account
) {
430 return new File(dataPath
, account
);
433 private static File
getUserPath(final File dataPath
, final String account
) {
434 final var path
= new File(dataPath
, account
+ ".d");
436 IOUtils
.createPrivateDirectories(path
);
437 } catch (IOException e
) {
438 throw new AssertionError("Failed to create user path", e
);
443 private static File
getMessageCachePath(File dataPath
, String account
) {
444 return new File(getUserPath(dataPath
, account
), "msg-cache");
447 private static File
getGroupCachePath(File dataPath
, String account
) {
448 return new File(getUserPath(dataPath
, account
), "group-cache");
451 private static File
getAciPreKeysPath(File dataPath
, String account
) {
452 return new File(getUserPath(dataPath
, account
), "pre-keys");
455 private static File
getAciSignedPreKeysPath(File dataPath
, String account
) {
456 return new File(getUserPath(dataPath
, account
), "signed-pre-keys");
459 private static File
getPniPreKeysPath(File dataPath
, String account
) {
460 return new File(getUserPath(dataPath
, account
), "pre-keys-pni");
463 private static File
getPniSignedPreKeysPath(File dataPath
, String account
) {
464 return new File(getUserPath(dataPath
, account
), "signed-pre-keys-pni");
467 private static File
getIdentitiesPath(File dataPath
, String account
) {
468 return new File(getUserPath(dataPath
, account
), "identities");
471 private static File
getSessionsPath(File dataPath
, String account
) {
472 return new File(getUserPath(dataPath
, account
), "sessions");
475 private static File
getSenderKeysPath(File dataPath
, String account
) {
476 return new File(getUserPath(dataPath
, account
), "sender-keys");
479 private static File
getSharedSenderKeysFile(File dataPath
, String account
) {
480 return new File(getUserPath(dataPath
, account
), "shared-sender-keys-store");
483 private static File
getRecipientsStoreFile(File dataPath
, String account
) {
484 return new File(getUserPath(dataPath
, account
), "recipients-store");
487 private static File
getStorageManifestFile(File dataPath
, String account
) {
488 return new File(getUserPath(dataPath
, account
), "storage-manifest");
491 private static File
getDatabaseFile(File dataPath
, String account
) {
492 return new File(getUserPath(dataPath
, account
), "account.db");
495 public static boolean accountFileExists(File dataPath
, String account
) {
496 if (account
== null) {
499 var f
= getFileName(dataPath
, account
);
500 return !(!f
.exists() || f
.isDirectory());
504 File dataPath
, String accountPath
, final TrustNewIdentity trustNewIdentity
505 ) throws IOException
{
506 this.dataPath
= dataPath
;
507 this.accountPath
= accountPath
;
508 final JsonNode rootNode
;
509 synchronized (fileChannel
) {
510 fileChannel
.position(0);
511 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
514 var migratedLegacyConfig
= false;
516 if (rootNode
.hasNonNull("version")) {
517 var accountVersion
= rootNode
.get("version").asInt(1);
518 if (accountVersion
> CURRENT_STORAGE_VERSION
) {
519 throw new IOException("Config file was created by a more recent version: " + accountVersion
);
520 } else if (accountVersion
< MINIMUM_STORAGE_VERSION
) {
521 throw new IOException("Config file was created by a no longer supported older version: "
524 previousStorageVersion
= accountVersion
;
525 if (accountVersion
< CURRENT_STORAGE_VERSION
) {
526 migratedLegacyConfig
= true;
530 number
= Utils
.getNotNullNode(rootNode
, "username").asText();
531 if (rootNode
.hasNonNull("password")) {
532 password
= rootNode
.get("password").asText();
534 if (rootNode
.hasNonNull("serviceEnvironment")) {
535 serviceEnvironment
= ServiceEnvironment
.valueOf(rootNode
.get("serviceEnvironment").asText());
537 registered
= Utils
.getNotNullNode(rootNode
, "registered").asBoolean();
538 if (rootNode
.hasNonNull("uuid")) {
540 aci
= ACI
.parseOrThrow(rootNode
.get("uuid").asText());
541 } catch (IllegalArgumentException e
) {
542 throw new IOException("Config file contains an invalid aci/uuid, needs to be a valid UUID", e
);
545 if (rootNode
.hasNonNull("pni")) {
547 pni
= PNI
.parseOrThrow(rootNode
.get("pni").asText());
548 } catch (IllegalArgumentException e
) {
549 throw new IOException("Config file contains an invalid pni, needs to be a valid UUID", e
);
552 if (rootNode
.hasNonNull("deviceName")) {
553 encryptedDeviceName
= rootNode
.get("deviceName").asText();
555 if (rootNode
.hasNonNull("deviceId")) {
556 deviceId
= rootNode
.get("deviceId").asInt();
558 if (rootNode
.hasNonNull("isMultiDevice")) {
559 isMultiDevice
= rootNode
.get("isMultiDevice").asBoolean();
561 if (rootNode
.hasNonNull("lastReceiveTimestamp")) {
562 lastReceiveTimestamp
= rootNode
.get("lastReceiveTimestamp").asLong();
564 int registrationId
= 0;
565 if (rootNode
.hasNonNull("registrationId")) {
566 registrationId
= rootNode
.get("registrationId").asInt();
568 if (rootNode
.hasNonNull("pniRegistrationId")) {
569 localPniRegistrationId
= rootNode
.get("pniRegistrationId").asInt();
571 localPniRegistrationId
= KeyHelper
.generateRegistrationId(false);
573 IdentityKeyPair aciIdentityKeyPair
= null;
574 if (rootNode
.hasNonNull("identityPrivateKey") && rootNode
.hasNonNull("identityKey")) {
575 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityKey").asText());
576 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityPrivateKey").asText());
577 aciIdentityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
579 if (rootNode
.hasNonNull("pniIdentityPrivateKey") && rootNode
.hasNonNull("pniIdentityKey")) {
580 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityKey").asText());
581 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityPrivateKey").asText());
582 pniIdentityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
585 if (rootNode
.hasNonNull("registrationLockPin")) {
586 registrationLockPin
= rootNode
.get("registrationLockPin").asText();
588 if (rootNode
.hasNonNull("pinMasterKey")) {
589 pinMasterKey
= new MasterKey(Base64
.getDecoder().decode(rootNode
.get("pinMasterKey").asText()));
591 if (rootNode
.hasNonNull("storageKey")) {
592 storageKey
= new StorageKey(Base64
.getDecoder().decode(rootNode
.get("storageKey").asText()));
594 if (rootNode
.hasNonNull("storageManifestVersion")) {
595 storageManifestVersion
= rootNode
.get("storageManifestVersion").asLong();
597 if (rootNode
.hasNonNull("preKeyIdOffset")) {
598 aciPreKeyIdOffset
= rootNode
.get("preKeyIdOffset").asInt(1);
600 aciPreKeyIdOffset
= 1;
602 if (rootNode
.hasNonNull("nextSignedPreKeyId")) {
603 aciNextSignedPreKeyId
= rootNode
.get("nextSignedPreKeyId").asInt(1);
605 aciNextSignedPreKeyId
= 1;
607 if (rootNode
.hasNonNull("pniPreKeyIdOffset")) {
608 pniPreKeyIdOffset
= rootNode
.get("pniPreKeyIdOffset").asInt(1);
610 pniPreKeyIdOffset
= 1;
612 if (rootNode
.hasNonNull("pniNextSignedPreKeyId")) {
613 pniNextSignedPreKeyId
= rootNode
.get("pniNextSignedPreKeyId").asInt(1);
615 pniNextSignedPreKeyId
= 1;
617 if (rootNode
.hasNonNull("profileKey")) {
619 profileKey
= new ProfileKey(Base64
.getDecoder().decode(rootNode
.get("profileKey").asText()));
620 } catch (InvalidInputException e
) {
621 throw new IOException(
622 "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
627 if (previousStorageVersion
< 5) {
628 final var legacyRecipientsStoreFile
= getRecipientsStoreFile(dataPath
, accountPath
);
629 if (legacyRecipientsStoreFile
.exists()) {
630 LegacyRecipientStore2
.migrate(legacyRecipientsStoreFile
, getRecipientStore());
631 // Ensure our profile key is stored in profile store
632 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
633 migratedLegacyConfig
= true;
636 final var legacyAciPreKeysPath
= getAciPreKeysPath(dataPath
, accountPath
);
637 if (legacyAciPreKeysPath
.exists()) {
638 LegacyPreKeyStore
.migrate(legacyAciPreKeysPath
, getAciPreKeyStore());
639 migratedLegacyConfig
= true;
641 final var legacyPniPreKeysPath
= getPniPreKeysPath(dataPath
, accountPath
);
642 if (legacyPniPreKeysPath
.exists()) {
643 LegacyPreKeyStore
.migrate(legacyPniPreKeysPath
, getPniPreKeyStore());
644 migratedLegacyConfig
= true;
646 final var legacyAciSignedPreKeysPath
= getAciSignedPreKeysPath(dataPath
, accountPath
);
647 if (legacyAciSignedPreKeysPath
.exists()) {
648 LegacySignedPreKeyStore
.migrate(legacyAciSignedPreKeysPath
, getAciSignedPreKeyStore());
649 migratedLegacyConfig
= true;
651 final var legacyPniSignedPreKeysPath
= getPniSignedPreKeysPath(dataPath
, accountPath
);
652 if (legacyPniSignedPreKeysPath
.exists()) {
653 LegacySignedPreKeyStore
.migrate(legacyPniSignedPreKeysPath
, getPniSignedPreKeyStore());
654 migratedLegacyConfig
= true;
656 final var legacySessionsPath
= getSessionsPath(dataPath
, accountPath
);
657 if (legacySessionsPath
.exists()) {
658 LegacySessionStore
.migrate(legacySessionsPath
,
659 getRecipientResolver(),
660 getRecipientAddressResolver(),
661 getAciSessionStore());
662 migratedLegacyConfig
= true;
664 final var legacyIdentitiesPath
= getIdentitiesPath(dataPath
, accountPath
);
665 if (legacyIdentitiesPath
.exists()) {
666 LegacyIdentityKeyStore
.migrate(legacyIdentitiesPath
,
667 getRecipientResolver(),
668 getRecipientAddressResolver(),
669 getIdentityKeyStore());
670 migratedLegacyConfig
= true;
672 final var legacySignalProtocolStore
= rootNode
.hasNonNull("axolotlStore")
673 ? jsonProcessor
.convertValue(Utils
.getNotNullNode(rootNode
, "axolotlStore"),
674 LegacyJsonSignalProtocolStore
.class)
676 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
677 aciIdentityKeyPair
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentityKeyPair();
678 registrationId
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getLocalRegistrationId();
679 migratedLegacyConfig
= true;
682 this.aciIdentityKeyPair
= aciIdentityKeyPair
;
683 this.localRegistrationId
= registrationId
;
684 this.trustNewIdentity
= trustNewIdentity
;
686 migratedLegacyConfig
= loadLegacyStores(rootNode
, legacySignalProtocolStore
) || migratedLegacyConfig
;
688 final var legacySenderKeysPath
= getSenderKeysPath(dataPath
, accountPath
);
689 if (legacySenderKeysPath
.exists()) {
690 LegacySenderKeyRecordStore
.migrate(legacySenderKeysPath
,
691 getRecipientResolver(),
692 getRecipientAddressResolver(),
693 getSenderKeyStore());
694 migratedLegacyConfig
= true;
696 final var legacySenderKeysSharedPath
= getSharedSenderKeysFile(dataPath
, accountPath
);
697 if (legacySenderKeysSharedPath
.exists()) {
698 LegacySenderKeySharedStore
.migrate(legacySenderKeysSharedPath
,
699 getRecipientResolver(),
700 getRecipientAddressResolver(),
701 getSenderKeyStore());
702 migratedLegacyConfig
= true;
704 if (rootNode
.hasNonNull("groupStore")) {
705 final var groupStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("groupStore"),
706 LegacyGroupStore
.Storage
.class);
707 LegacyGroupStore
.migrate(groupStoreStorage
,
708 getGroupCachePath(dataPath
, accountPath
),
709 getRecipientResolver(),
711 migratedLegacyConfig
= true;
714 if (rootNode
.hasNonNull("stickerStore")) {
715 final var storage
= jsonProcessor
.convertValue(rootNode
.get("stickerStore"),
716 LegacyStickerStore
.Storage
.class);
717 LegacyStickerStore
.migrate(storage
, getStickerStore());
718 migratedLegacyConfig
= true;
721 if (rootNode
.hasNonNull("configurationStore")) {
722 configurationStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("configurationStore"),
723 ConfigurationStore
.Storage
.class);
724 configurationStore
= ConfigurationStore
.fromStorage(configurationStoreStorage
,
725 this::saveConfigurationStore
);
727 configurationStore
= new ConfigurationStore(this::saveConfigurationStore
);
730 migratedLegacyConfig
= loadLegacyThreadStore(rootNode
) || migratedLegacyConfig
;
732 if (migratedLegacyConfig
) {
737 private boolean loadLegacyStores(
738 final JsonNode rootNode
, final LegacyJsonSignalProtocolStore legacySignalProtocolStore
740 var migrated
= false;
741 var legacyRecipientStoreNode
= rootNode
.get("recipientStore");
742 if (legacyRecipientStoreNode
!= null) {
743 logger
.debug("Migrating legacy recipient store.");
744 var legacyRecipientStore
= jsonProcessor
.convertValue(legacyRecipientStoreNode
, LegacyRecipientStore
.class);
745 if (legacyRecipientStore
!= null) {
746 legacyRecipientStore
.getAddresses()
747 .forEach(recipient
-> getRecipientStore().resolveRecipientTrusted(recipient
));
749 getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
753 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyPreKeyStore() != null) {
754 logger
.debug("Migrating legacy pre key store.");
755 for (var entry
: legacySignalProtocolStore
.getLegacyPreKeyStore().getPreKeys().entrySet()) {
757 getAciPreKeyStore().storePreKey(entry
.getKey(), new PreKeyRecord(entry
.getValue()));
758 } catch (InvalidMessageException e
) {
759 logger
.warn("Failed to migrate pre key, ignoring", e
);
765 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySignedPreKeyStore() != null) {
766 logger
.debug("Migrating legacy signed pre key store.");
767 for (var entry
: legacySignalProtocolStore
.getLegacySignedPreKeyStore().getSignedPreKeys().entrySet()) {
769 getAciSignedPreKeyStore().storeSignedPreKey(entry
.getKey(),
770 new SignedPreKeyRecord(entry
.getValue()));
771 } catch (InvalidMessageException e
) {
772 logger
.warn("Failed to migrate signed pre key, ignoring", e
);
778 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySessionStore() != null) {
779 logger
.debug("Migrating legacy session store.");
780 for (var session
: legacySignalProtocolStore
.getLegacySessionStore().getSessions()) {
782 getAciSessionStore().storeSession(new SignalProtocolAddress(session
.address
.getIdentifier(),
783 session
.deviceId
), new SessionRecord(session
.sessionRecord
));
784 } catch (Exception e
) {
785 logger
.warn("Failed to migrate session, ignoring", e
);
791 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
792 logger
.debug("Migrating legacy identity session store.");
793 for (var identity
: legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentities()) {
794 if (identity
.getAddress().uuid().isEmpty()) {
797 final var serviceId
= identity
.getAddress().getServiceId();
798 getIdentityKeyStore().saveIdentity(serviceId
, identity
.getIdentityKey());
799 getIdentityKeyStore().setIdentityTrustLevel(serviceId
,
800 identity
.getIdentityKey(),
801 identity
.getTrustLevel());
806 if (rootNode
.hasNonNull("contactStore")) {
807 logger
.debug("Migrating legacy contact store.");
808 final var contactStoreNode
= rootNode
.get("contactStore");
809 final var contactStore
= jsonProcessor
.convertValue(contactStoreNode
, LegacyJsonContactsStore
.class);
810 for (var contact
: contactStore
.getContacts()) {
811 final var recipientId
= getRecipientStore().resolveRecipientTrusted(contact
.getAddress());
812 getContactStore().storeContact(recipientId
,
813 new Contact(contact
.name
,
816 contact
.messageExpirationTime
,
821 // Store profile keys only in profile store
822 var profileKeyString
= contact
.profileKey
;
823 if (profileKeyString
!= null) {
824 final ProfileKey profileKey
;
826 profileKey
= new ProfileKey(Base64
.getDecoder().decode(profileKeyString
));
827 getProfileStore().storeProfileKey(recipientId
, profileKey
);
828 } catch (InvalidInputException e
) {
829 logger
.warn("Failed to parse legacy contact profile key: {}", e
.getMessage());
836 if (rootNode
.hasNonNull("profileStore")) {
837 logger
.debug("Migrating legacy profile store.");
838 var profileStoreNode
= rootNode
.get("profileStore");
839 final var legacyProfileStore
= jsonProcessor
.convertValue(profileStoreNode
, LegacyProfileStore
.class);
840 for (var profileEntry
: legacyProfileStore
.getProfileEntries()) {
841 var recipientId
= getRecipientResolver().resolveRecipient(profileEntry
.getAddress());
842 // Not migrating profile key credential here, it was changed to expiring profile key credentials
843 getProfileStore().storeProfileKey(recipientId
, profileEntry
.getProfileKey());
844 final var profile
= profileEntry
.getProfile();
845 if (profile
!= null) {
846 final var capabilities
= new HashSet
<Profile
.Capability
>();
847 if (profile
.getCapabilities() != null) {
848 if (profile
.getCapabilities().gv1Migration
) {
849 capabilities
.add(Profile
.Capability
.gv1Migration
);
851 if (profile
.getCapabilities().storage
) {
852 capabilities
.add(Profile
.Capability
.storage
);
855 final var newProfile
= new Profile(profileEntry
.getLastUpdateTimestamp(),
856 profile
.getGivenName(),
857 profile
.getFamilyName(),
859 profile
.getAboutEmoji(),
862 profile
.isUnrestrictedUnidentifiedAccess()
863 ? Profile
.UnidentifiedAccessMode
.UNRESTRICTED
864 : profile
.getUnidentifiedAccess() != null
865 ? Profile
.UnidentifiedAccessMode
.ENABLED
866 : Profile
.UnidentifiedAccessMode
.DISABLED
,
868 getProfileStore().storeProfile(recipientId
, newProfile
);
876 private boolean loadLegacyThreadStore(final JsonNode rootNode
) {
877 var threadStoreNode
= rootNode
.get("threadStore");
878 if (threadStoreNode
!= null && !threadStoreNode
.isNull()) {
879 var threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
880 // Migrate thread info to group and contact store
881 for (var thread
: threadStore
.getThreads()) {
882 if (thread
.id
== null || thread
.id
.isEmpty()) {
886 if (UuidUtil
.isUuid(thread
.id
) || thread
.id
.startsWith("+")) {
887 final var recipientId
= getRecipientResolver().resolveRecipient(thread
.id
);
888 var contact
= getContactStore().getContact(recipientId
);
889 if (contact
!= null) {
890 getContactStore().storeContact(recipientId
,
891 Contact
.newBuilder(contact
)
892 .withMessageExpirationTime(thread
.messageExpirationTime
)
896 var groupInfo
= getGroupStore().getGroup(GroupId
.fromBase64(thread
.id
));
897 if (groupInfo
instanceof GroupInfoV1
) {
898 ((GroupInfoV1
) groupInfo
).messageExpirationTime
= thread
.messageExpirationTime
;
899 getGroupStore().updateGroup(groupInfo
);
902 } catch (Exception e
) {
903 logger
.warn("Failed to read legacy thread info: {}", e
.getMessage());
912 private void saveConfigurationStore(ConfigurationStore
.Storage storage
) {
913 this.configurationStoreStorage
= storage
;
917 private void save() {
918 synchronized (fileChannel
) {
919 var rootNode
= jsonProcessor
.createObjectNode();
920 rootNode
.put("version", CURRENT_STORAGE_VERSION
)
921 .put("username", number
)
922 .put("serviceEnvironment", serviceEnvironment
== null ?
null : serviceEnvironment
.name())
923 .put("uuid", aci
== null ?
null : aci
.toString())
924 .put("pni", pni
== null ?
null : pni
.toString())
925 .put("deviceName", encryptedDeviceName
)
926 .put("deviceId", deviceId
)
927 .put("isMultiDevice", isMultiDevice
)
928 .put("lastReceiveTimestamp", lastReceiveTimestamp
)
929 .put("password", password
)
930 .put("registrationId", localRegistrationId
)
931 .put("pniRegistrationId", localPniRegistrationId
)
932 .put("identityPrivateKey",
933 Base64
.getEncoder().encodeToString(aciIdentityKeyPair
.getPrivateKey().serialize()))
935 Base64
.getEncoder().encodeToString(aciIdentityKeyPair
.getPublicKey().serialize()))
936 .put("pniIdentityPrivateKey",
937 pniIdentityKeyPair
== null
939 : Base64
.getEncoder()
940 .encodeToString(pniIdentityKeyPair
.getPrivateKey().serialize()))
941 .put("pniIdentityKey",
942 pniIdentityKeyPair
== null
944 : Base64
.getEncoder().encodeToString(pniIdentityKeyPair
.getPublicKey().serialize()))
945 .put("registrationLockPin", registrationLockPin
)
947 pinMasterKey
== null ?
null : Base64
.getEncoder().encodeToString(pinMasterKey
.serialize()))
949 storageKey
== null ?
null : Base64
.getEncoder().encodeToString(storageKey
.serialize()))
950 .put("storageManifestVersion", storageManifestVersion
== -1 ?
null : storageManifestVersion
)
951 .put("preKeyIdOffset", aciPreKeyIdOffset
)
952 .put("nextSignedPreKeyId", aciNextSignedPreKeyId
)
953 .put("pniPreKeyIdOffset", pniPreKeyIdOffset
)
954 .put("pniNextSignedPreKeyId", pniNextSignedPreKeyId
)
956 profileKey
== null ?
null : Base64
.getEncoder().encodeToString(profileKey
.serialize()))
957 .put("registered", registered
)
958 .putPOJO("configurationStore", configurationStoreStorage
);
960 try (var output
= new ByteArrayOutputStream()) {
961 // Write to memory first to prevent corrupting the file in case of serialization errors
962 jsonProcessor
.writeValue(output
, rootNode
);
963 var input
= new ByteArrayInputStream(output
.toByteArray());
964 fileChannel
.position(0);
965 input
.transferTo(Channels
.newOutputStream(fileChannel
));
966 fileChannel
.truncate(fileChannel
.position());
967 fileChannel
.force(false);
969 } catch (Exception e
) {
970 logger
.error("Error saving file: {}", e
.getMessage(), e
);
975 private static Pair
<FileChannel
, FileLock
> openFileChannel(File fileName
, boolean waitForLock
) throws IOException
{
976 var fileChannel
= new RandomAccessFile(fileName
, "rw").getChannel();
978 var lock
= fileChannel
.tryLock();
981 logger
.debug("Config file is in use by another instance.");
982 throw new IOException("Config file is in use by another instance.");
984 logger
.info("Config file is in use by another instance, waiting…");
985 lock
= fileChannel
.lock();
986 logger
.info("Config file lock acquired.");
988 final var result
= new Pair
<>(fileChannel
, lock
);
992 if (fileChannel
!= null) {
998 public void addPreKeys(ServiceIdType serviceIdType
, List
<PreKeyRecord
> records
) {
999 if (serviceIdType
.equals(ServiceIdType
.ACI
)) {
1000 addAciPreKeys(records
);
1002 addPniPreKeys(records
);
1006 public void addAciPreKeys(List
<PreKeyRecord
> records
) {
1007 for (var record : records
) {
1008 if (aciPreKeyIdOffset
!= record.getId()) {
1009 logger
.error("Invalid pre key id {}, expected {}", record.getId(), aciPreKeyIdOffset
);
1010 throw new AssertionError("Invalid pre key id");
1012 getAciPreKeyStore().storePreKey(record.getId(), record);
1013 aciPreKeyIdOffset
= (aciPreKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
1018 public void addPniPreKeys(List
<PreKeyRecord
> records
) {
1019 for (var record : records
) {
1020 if (pniPreKeyIdOffset
!= record.getId()) {
1021 logger
.error("Invalid pre key id {}, expected {}", record.getId(), pniPreKeyIdOffset
);
1022 throw new AssertionError("Invalid pre key id");
1024 getPniPreKeyStore().storePreKey(record.getId(), record);
1025 pniPreKeyIdOffset
= (pniPreKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
1030 public void addSignedPreKey(ServiceIdType serviceIdType
, SignedPreKeyRecord
record) {
1031 if (serviceIdType
.equals(ServiceIdType
.ACI
)) {
1032 addAciSignedPreKey(record);
1034 addPniSignedPreKey(record);
1038 public void addAciSignedPreKey(SignedPreKeyRecord
record) {
1039 if (aciNextSignedPreKeyId
!= record.getId()) {
1040 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), aciNextSignedPreKeyId
);
1041 throw new AssertionError("Invalid signed pre key id");
1043 getAciSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
1044 aciNextSignedPreKeyId
= (aciNextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
1048 public void addPniSignedPreKey(SignedPreKeyRecord
record) {
1049 if (pniNextSignedPreKeyId
!= record.getId()) {
1050 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), pniNextSignedPreKeyId
);
1051 throw new AssertionError("Invalid signed pre key id");
1053 getPniSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
1054 pniNextSignedPreKeyId
= (pniNextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
1058 public int getPreviousStorageVersion() {
1059 return previousStorageVersion
;
1062 public SignalServiceDataStore
getSignalServiceDataStore() {
1063 return new SignalServiceDataStore() {
1065 public SignalServiceAccountDataStore
get(final ServiceId accountIdentifier
) {
1066 if (accountIdentifier
.equals(aci
)) {
1068 } else if (accountIdentifier
.equals(pni
)) {
1071 throw new IllegalArgumentException("No matching store found for " + accountIdentifier
);
1076 public SignalServiceAccountDataStore
aci() {
1077 return getAciSignalServiceAccountDataStore();
1081 public SignalServiceAccountDataStore
pni() {
1082 return getPniSignalServiceAccountDataStore();
1086 public boolean isMultiDevice() {
1087 return SignalAccount
.this.isMultiDevice();
1092 private SignalServiceAccountDataStore
getAciSignalServiceAccountDataStore() {
1093 return getOrCreate(() -> aciSignalProtocolStore
,
1094 () -> aciSignalProtocolStore
= new SignalProtocolStore(getAciPreKeyStore(),
1095 getAciSignedPreKeyStore(),
1096 getAciSessionStore(),
1097 getAciIdentityKeyStore(),
1098 getSenderKeyStore(),
1099 this::isMultiDevice
));
1102 private SignalServiceAccountDataStore
getPniSignalServiceAccountDataStore() {
1103 return getOrCreate(() -> pniSignalProtocolStore
,
1104 () -> pniSignalProtocolStore
= new SignalProtocolStore(getPniPreKeyStore(),
1105 getPniSignedPreKeyStore(),
1106 getPniSessionStore(),
1107 getPniIdentityKeyStore(),
1108 getSenderKeyStore(),
1109 this::isMultiDevice
));
1112 private PreKeyStore
getAciPreKeyStore() {
1113 return getOrCreate(() -> aciPreKeyStore
,
1114 () -> aciPreKeyStore
= new PreKeyStore(getAccountDatabase(), ServiceIdType
.ACI
));
1117 private SignedPreKeyStore
getAciSignedPreKeyStore() {
1118 return getOrCreate(() -> aciSignedPreKeyStore
,
1119 () -> aciSignedPreKeyStore
= new SignedPreKeyStore(getAccountDatabase(), ServiceIdType
.ACI
));
1122 private PreKeyStore
getPniPreKeyStore() {
1123 return getOrCreate(() -> pniPreKeyStore
,
1124 () -> pniPreKeyStore
= new PreKeyStore(getAccountDatabase(), ServiceIdType
.PNI
));
1127 private SignedPreKeyStore
getPniSignedPreKeyStore() {
1128 return getOrCreate(() -> pniSignedPreKeyStore
,
1129 () -> pniSignedPreKeyStore
= new SignedPreKeyStore(getAccountDatabase(), ServiceIdType
.PNI
));
1132 public SessionStore
getAciSessionStore() {
1133 return getOrCreate(() -> aciSessionStore
,
1134 () -> aciSessionStore
= new SessionStore(getAccountDatabase(), ServiceIdType
.ACI
));
1137 public SessionStore
getPniSessionStore() {
1138 return getOrCreate(() -> pniSessionStore
,
1139 () -> pniSessionStore
= new SessionStore(getAccountDatabase(), ServiceIdType
.PNI
));
1142 public IdentityKeyStore
getIdentityKeyStore() {
1143 return getOrCreate(() -> identityKeyStore
,
1144 () -> identityKeyStore
= new IdentityKeyStore(getAccountDatabase(), trustNewIdentity
));
1147 public SignalIdentityKeyStore
getAciIdentityKeyStore() {
1148 return getOrCreate(() -> aciIdentityKeyStore
,
1149 () -> aciIdentityKeyStore
= new SignalIdentityKeyStore(getRecipientResolver(),
1150 () -> aciIdentityKeyPair
,
1151 localRegistrationId
,
1152 getIdentityKeyStore()));
1155 public SignalIdentityKeyStore
getPniIdentityKeyStore() {
1156 return getOrCreate(() -> pniIdentityKeyStore
,
1157 () -> pniIdentityKeyStore
= new SignalIdentityKeyStore(getRecipientResolver(),
1158 () -> pniIdentityKeyPair
,
1159 localRegistrationId
,
1160 getIdentityKeyStore()));
1163 public GroupStore
getGroupStore() {
1164 return getOrCreate(() -> groupStore
,
1165 () -> groupStore
= new GroupStore(getAccountDatabase(),
1166 getRecipientResolver(),
1167 getRecipientIdCreator()));
1170 public ContactsStore
getContactStore() {
1171 return getRecipientStore();
1174 private RecipientIdCreator
getRecipientIdCreator() {
1175 return recipientId
-> getRecipientStore().create(recipientId
);
1178 public RecipientResolver
getRecipientResolver() {
1179 return new RecipientResolver() {
1181 public RecipientId
resolveRecipient(final RecipientAddress address
) {
1182 return getRecipientStore().resolveRecipient(address
);
1186 public RecipientId
resolveRecipient(final long recipientId
) {
1187 return getRecipientStore().resolveRecipient(recipientId
);
1192 public RecipientTrustedResolver
getRecipientTrustedResolver() {
1193 return new RecipientTrustedResolver() {
1195 public RecipientId
resolveSelfRecipientTrusted(final RecipientAddress address
) {
1196 return getRecipientStore().resolveSelfRecipientTrusted(address
);
1200 public RecipientId
resolveRecipientTrusted(final SignalServiceAddress address
) {
1201 return getRecipientStore().resolveRecipientTrusted(address
);
1206 public RecipientAddressResolver
getRecipientAddressResolver() {
1207 return recipientId
-> getRecipientStore().resolveRecipientAddress(recipientId
);
1210 public RecipientStore
getRecipientStore() {
1211 return getOrCreate(() -> recipientStore
,
1212 () -> recipientStore
= new RecipientStore(this::mergeRecipients
,
1213 this::getSelfRecipientAddress
,
1214 getAccountDatabase()));
1217 public ProfileStore
getProfileStore() {
1218 return getRecipientStore();
1221 public StickerStore
getStickerStore() {
1222 return getOrCreate(() -> stickerStore
, () -> stickerStore
= new StickerStore(getAccountDatabase()));
1225 public SenderKeyStore
getSenderKeyStore() {
1226 return getOrCreate(() -> senderKeyStore
, () -> senderKeyStore
= new SenderKeyStore(getAccountDatabase()));
1229 public ConfigurationStore
getConfigurationStore() {
1230 return configurationStore
;
1233 public MessageCache
getMessageCache() {
1234 return getOrCreate(() -> messageCache
,
1235 () -> messageCache
= new MessageCache(getMessageCachePath(dataPath
, accountPath
)));
1238 public AccountDatabase
getAccountDatabase() {
1239 return getOrCreate(() -> accountDatabase
, () -> {
1241 accountDatabase
= AccountDatabase
.init(getDatabaseFile(dataPath
, accountPath
));
1242 } catch (SQLException e
) {
1243 throw new RuntimeException(e
);
1248 public MessageSendLogStore
getMessageSendLogStore() {
1249 return getOrCreate(() -> messageSendLogStore
,
1250 () -> messageSendLogStore
= new MessageSendLogStore(getAccountDatabase()));
1253 public CredentialsProvider
getCredentialsProvider() {
1254 return new CredentialsProvider() {
1256 public ACI
getAci() {
1261 public PNI
getPni() {
1266 public String
getE164() {
1271 public String
getPassword() {
1276 public int getDeviceId() {
1282 public String
getNumber() {
1286 public void setNumber(final String number
) {
1287 this.number
= number
;
1291 public ServiceEnvironment
getServiceEnvironment() {
1292 return serviceEnvironment
;
1295 public void setServiceEnvironment(final ServiceEnvironment serviceEnvironment
) {
1296 this.serviceEnvironment
= serviceEnvironment
;
1300 public ServiceId
getAccountId(ServiceIdType serviceIdType
) {
1301 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aci
: pni
;
1304 public ACI
getAci() {
1308 public void setAci(final ACI aci
) {
1313 public PNI
getPni() {
1317 public void setPni(final PNI pni
) {
1322 public SignalServiceAddress
getSelfAddress() {
1323 return new SignalServiceAddress(aci
, number
);
1326 public RecipientAddress
getSelfRecipientAddress() {
1327 return new RecipientAddress(aci
== null ?
null : aci
.uuid(), number
);
1330 public RecipientId
getSelfRecipientId() {
1331 return getRecipientResolver().resolveRecipient(getSelfRecipientAddress());
1334 public byte[] getEncryptedDeviceName() {
1335 return encryptedDeviceName
== null ?
null : Base64
.getDecoder().decode(encryptedDeviceName
);
1338 public void setEncryptedDeviceName(final String encryptedDeviceName
) {
1339 this.encryptedDeviceName
= encryptedDeviceName
;
1343 public int getDeviceId() {
1347 public boolean isPrimaryDevice() {
1348 return deviceId
== SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1351 public IdentityKeyPair
getIdentityKeyPair(ServiceIdType serviceIdType
) {
1352 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciIdentityKeyPair
: pniIdentityKeyPair
;
1355 public IdentityKeyPair
getAciIdentityKeyPair() {
1356 return aciIdentityKeyPair
;
1359 public IdentityKeyPair
getPniIdentityKeyPair() {
1360 return pniIdentityKeyPair
;
1363 public void setPniIdentityKeyPair(final IdentityKeyPair identityKeyPair
) {
1364 pniIdentityKeyPair
= identityKeyPair
;
1365 final var pniPublicKey
= getPniIdentityKeyPair().getPublicKey();
1366 getIdentityKeyStore().saveIdentity(getPni(), pniPublicKey
);
1367 getIdentityKeyStore().setIdentityTrustLevel(getPni(), pniPublicKey
, TrustLevel
.TRUSTED_VERIFIED
);
1371 public int getLocalRegistrationId() {
1372 return localRegistrationId
;
1375 public int getLocalPniRegistrationId() {
1376 return localPniRegistrationId
;
1379 public String
getPassword() {
1383 private void setPassword(final String password
) {
1384 this.password
= password
;
1388 public void setRegistrationLockPin(final String registrationLockPin
) {
1389 this.registrationLockPin
= registrationLockPin
;
1393 public String
getRegistrationLockPin() {
1394 return registrationLockPin
;
1397 public String
getRegistrationLock() {
1398 final var masterKey
= getPinBackedMasterKey();
1399 if (masterKey
== null) {
1402 return masterKey
.deriveRegistrationLock();
1405 public MasterKey
getPinBackedMasterKey() {
1406 if (registrationLockPin
== null) {
1409 return pinMasterKey
;
1412 public MasterKey
getOrCreatePinMasterKey() {
1413 if (pinMasterKey
== null) {
1414 pinMasterKey
= KeyUtils
.createMasterKey();
1417 return pinMasterKey
;
1420 public StorageKey
getStorageKey() {
1421 if (pinMasterKey
!= null) {
1422 return pinMasterKey
.deriveStorageServiceKey();
1427 public StorageKey
getOrCreateStorageKey() {
1428 if (isPrimaryDevice()) {
1429 return getOrCreatePinMasterKey().deriveStorageServiceKey();
1434 public void setStorageKey(final StorageKey storageKey
) {
1435 if (storageKey
.equals(this.storageKey
)) {
1438 this.storageKey
= storageKey
;
1442 public long getStorageManifestVersion() {
1443 return this.storageManifestVersion
;
1446 public void setStorageManifestVersion(final long storageManifestVersion
) {
1447 if (storageManifestVersion
== this.storageManifestVersion
) {
1450 this.storageManifestVersion
= storageManifestVersion
;
1454 public Optional
<SignalStorageManifest
> getStorageManifest() {
1455 final var storageManifestFile
= getStorageManifestFile(dataPath
, accountPath
);
1456 if (!storageManifestFile
.exists()) {
1457 return Optional
.empty();
1459 try (var inputStream
= new FileInputStream(storageManifestFile
)) {
1460 return Optional
.of(SignalStorageManifest
.deserialize(inputStream
.readAllBytes()));
1461 } catch (IOException e
) {
1462 logger
.warn("Failed to read local storage manifest.", e
);
1463 return Optional
.empty();
1467 public void setStorageManifest(SignalStorageManifest manifest
) {
1468 final var storageManifestFile
= getStorageManifestFile(dataPath
, accountPath
);
1469 if (manifest
== null) {
1470 if (storageManifestFile
.exists()) {
1472 Files
.delete(storageManifestFile
.toPath());
1473 } catch (IOException e
) {
1474 logger
.error("Failed to delete local storage manifest.", e
);
1480 final var manifestBytes
= manifest
.serialize();
1481 try (var outputStream
= new FileOutputStream(storageManifestFile
)) {
1482 outputStream
.write(manifestBytes
);
1483 } catch (IOException e
) {
1484 logger
.error("Failed to store local storage manifest.", e
);
1488 public ProfileKey
getProfileKey() {
1492 public void setProfileKey(final ProfileKey profileKey
) {
1493 if (profileKey
.equals(this.profileKey
)) {
1496 this.profileKey
= profileKey
;
1498 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
1501 public byte[] getSelfUnidentifiedAccessKey() {
1502 return UnidentifiedAccess
.deriveAccessKeyFrom(getProfileKey());
1505 public int getPreKeyIdOffset(ServiceIdType serviceIdType
) {
1506 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciPreKeyIdOffset
: pniPreKeyIdOffset
;
1509 public int getNextSignedPreKeyId(ServiceIdType serviceIdType
) {
1510 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciNextSignedPreKeyId
: pniNextSignedPreKeyId
;
1513 public boolean isRegistered() {
1517 public void setRegistered(final boolean registered
) {
1518 this.registered
= registered
;
1522 public boolean isMultiDevice() {
1523 return isMultiDevice
;
1526 public void setMultiDevice(final boolean multiDevice
) {
1527 if (isMultiDevice
== multiDevice
) {
1530 isMultiDevice
= multiDevice
;
1534 public long getLastReceiveTimestamp() {
1535 return lastReceiveTimestamp
;
1538 public void setLastReceiveTimestamp(final long lastReceiveTimestamp
) {
1539 this.lastReceiveTimestamp
= lastReceiveTimestamp
;
1543 public boolean isUnrestrictedUnidentifiedAccess() {
1544 final var profile
= getProfileStore().getProfile(getSelfRecipientId());
1545 return profile
!= null && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
;
1548 public boolean isDiscoverableByPhoneNumber() {
1549 final var phoneNumberUnlisted
= configurationStore
.getPhoneNumberUnlisted();
1550 return phoneNumberUnlisted
== null || !phoneNumberUnlisted
;
1553 public void finishRegistration(final ACI aci
, final PNI pni
, final MasterKey masterKey
, final String pin
) {
1554 this.pinMasterKey
= masterKey
;
1555 this.storageManifestVersion
= -1;
1556 this.setStorageManifest(null);
1557 this.storageKey
= null;
1558 this.encryptedDeviceName
= null;
1559 this.deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1560 this.isMultiDevice
= false;
1561 this.registered
= true;
1564 this.registrationLockPin
= pin
;
1565 this.lastReceiveTimestamp
= 0;
1569 getAciSessionStore().archiveAllSessions();
1570 getPniSessionStore().archiveAllSessions();
1571 getSenderKeyStore().deleteAll();
1572 getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
1573 final var aciPublicKey
= getAciIdentityKeyPair().getPublicKey();
1574 getIdentityKeyStore().saveIdentity(getAci(), aciPublicKey
);
1575 getIdentityKeyStore().setIdentityTrustLevel(getAci(), aciPublicKey
, TrustLevel
.TRUSTED_VERIFIED
);
1576 final var pniPublicKey
= getPniIdentityKeyPair().getPublicKey();
1577 getIdentityKeyStore().saveIdentity(getPni(), pniPublicKey
);
1578 getIdentityKeyStore().setIdentityTrustLevel(getPni(), pniPublicKey
, TrustLevel
.TRUSTED_VERIFIED
);
1581 public void deleteAccountData() throws IOException
{
1583 try (final var files
= Files
.walk(getUserPath(dataPath
, accountPath
).toPath())
1584 .sorted(Comparator
.reverseOrder())) {
1585 for (final var file
= files
.iterator(); file
.hasNext(); ) {
1586 Files
.delete(file
.next());
1589 Files
.delete(getFileName(dataPath
, accountPath
).toPath());
1593 public void close() {
1594 synchronized (fileChannel
) {
1595 if (accountDatabase
!= null) {
1597 accountDatabase
.close();
1598 } catch (SQLException e
) {
1599 logger
.warn("Failed to close account database: {}", e
.getMessage(), e
);
1602 if (messageSendLogStore
!= null) {
1603 messageSendLogStore
.close();
1608 } catch (ClosedChannelException ignored
) {
1610 fileChannel
.close();
1611 } catch (IOException e
) {
1612 logger
.warn("Failed to close account: {}", e
.getMessage(), e
);
1617 private <T
> T
getOrCreate(Supplier
<T
> supplier
, Callable creator
) {
1618 var value
= supplier
.get();
1619 if (value
!= null) {
1623 synchronized (LOCK
) {
1624 value
= supplier
.get();
1625 if (value
!= null) {
1629 return supplier
.get();
1633 private interface Callable
{