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
.GroupInfoV2
;
16 import org
.asamk
.signal
.manager
.storage
.groups
.GroupStore
;
17 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityKeyStore
;
18 import org
.asamk
.signal
.manager
.storage
.identities
.SignalIdentityKeyStore
;
19 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
20 import org
.asamk
.signal
.manager
.storage
.messageCache
.MessageCache
;
21 import org
.asamk
.signal
.manager
.storage
.prekeys
.PreKeyStore
;
22 import org
.asamk
.signal
.manager
.storage
.prekeys
.SignedPreKeyStore
;
23 import org
.asamk
.signal
.manager
.storage
.profiles
.LegacyProfileStore
;
24 import org
.asamk
.signal
.manager
.storage
.profiles
.ProfileStore
;
25 import org
.asamk
.signal
.manager
.storage
.protocol
.LegacyJsonSignalProtocolStore
;
26 import org
.asamk
.signal
.manager
.storage
.protocol
.SignalProtocolStore
;
27 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
28 import org
.asamk
.signal
.manager
.storage
.recipients
.LegacyRecipientStore
;
29 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
30 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
31 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
32 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientResolver
;
33 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientStore
;
34 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientTrustedResolver
;
35 import org
.asamk
.signal
.manager
.storage
.sendLog
.MessageSendLogStore
;
36 import org
.asamk
.signal
.manager
.storage
.senderKeys
.SenderKeyStore
;
37 import org
.asamk
.signal
.manager
.storage
.sessions
.SessionStore
;
38 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerStore
;
39 import org
.asamk
.signal
.manager
.storage
.threads
.LegacyJsonThreadStore
;
40 import org
.asamk
.signal
.manager
.util
.IOUtils
;
41 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
42 import org
.signal
.libsignal
.protocol
.IdentityKeyPair
;
43 import org
.signal
.libsignal
.protocol
.InvalidMessageException
;
44 import org
.signal
.libsignal
.protocol
.SignalProtocolAddress
;
45 import org
.signal
.libsignal
.protocol
.state
.PreKeyRecord
;
46 import org
.signal
.libsignal
.protocol
.state
.SessionRecord
;
47 import org
.signal
.libsignal
.protocol
.state
.SignedPreKeyRecord
;
48 import org
.signal
.libsignal
.protocol
.util
.Medium
;
49 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
50 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
51 import org
.slf4j
.Logger
;
52 import org
.slf4j
.LoggerFactory
;
53 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountDataStore
;
54 import org
.whispersystems
.signalservice
.api
.SignalServiceDataStore
;
55 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
56 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
57 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
58 import org
.whispersystems
.signalservice
.api
.push
.DistributionId
;
59 import org
.whispersystems
.signalservice
.api
.push
.PNI
;
60 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
61 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
62 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
63 import org
.whispersystems
.signalservice
.api
.storage
.SignalStorageManifest
;
64 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
65 import org
.whispersystems
.signalservice
.api
.util
.CredentialsProvider
;
66 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
68 import java
.io
.ByteArrayInputStream
;
69 import java
.io
.ByteArrayOutputStream
;
70 import java
.io
.Closeable
;
72 import java
.io
.FileInputStream
;
73 import java
.io
.FileOutputStream
;
74 import java
.io
.IOException
;
75 import java
.io
.RandomAccessFile
;
76 import java
.nio
.channels
.Channels
;
77 import java
.nio
.channels
.ClosedChannelException
;
78 import java
.nio
.channels
.FileChannel
;
79 import java
.nio
.channels
.FileLock
;
80 import java
.nio
.file
.Files
;
81 import java
.security
.SecureRandom
;
82 import java
.sql
.SQLException
;
83 import java
.util
.Base64
;
84 import java
.util
.Comparator
;
85 import java
.util
.HashSet
;
86 import java
.util
.List
;
87 import java
.util
.Optional
;
88 import java
.util
.function
.Supplier
;
90 public class SignalAccount
implements Closeable
{
92 private final static Logger logger
= LoggerFactory
.getLogger(SignalAccount
.class);
94 private static final int MINIMUM_STORAGE_VERSION
= 1;
95 private static final int CURRENT_STORAGE_VERSION
= 3;
97 private final Object LOCK
= new Object();
99 private final ObjectMapper jsonProcessor
= Utils
.createStorageObjectMapper();
101 private final FileChannel fileChannel
;
102 private final FileLock lock
;
104 private int previousStorageVersion
;
106 private File dataPath
;
107 private String accountPath
;
108 private ServiceEnvironment serviceEnvironment
;
109 private String number
;
112 private String encryptedDeviceName
;
113 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
114 private boolean isMultiDevice
= false;
115 private String password
;
116 private String registrationLockPin
;
117 private MasterKey pinMasterKey
;
118 private StorageKey storageKey
;
119 private long storageManifestVersion
= -1;
120 private ProfileKey profileKey
;
121 private int aciPreKeyIdOffset
= 1;
122 private int aciNextSignedPreKeyId
= 1;
123 private int pniPreKeyIdOffset
= 1;
124 private int pniNextSignedPreKeyId
= 1;
125 private IdentityKeyPair aciIdentityKeyPair
;
126 private IdentityKeyPair pniIdentityKeyPair
;
127 private int localRegistrationId
;
128 private TrustNewIdentity trustNewIdentity
;
129 private long lastReceiveTimestamp
= 0;
131 private boolean registered
= false;
133 private SignalProtocolStore signalProtocolStore
;
134 private PreKeyStore aciPreKeyStore
;
135 private SignedPreKeyStore aciSignedPreKeyStore
;
136 private PreKeyStore pniPreKeyStore
;
137 private SignedPreKeyStore pniSignedPreKeyStore
;
138 private SessionStore sessionStore
;
139 private IdentityKeyStore identityKeyStore
;
140 private SignalIdentityKeyStore aciIdentityKeyStore
;
141 private SenderKeyStore senderKeyStore
;
142 private GroupStore groupStore
;
143 private GroupStore
.Storage groupStoreStorage
;
144 private RecipientStore recipientStore
;
145 private StickerStore stickerStore
;
146 private StickerStore
.Storage stickerStoreStorage
;
147 private ConfigurationStore configurationStore
;
148 private ConfigurationStore
.Storage configurationStoreStorage
;
150 private MessageCache messageCache
;
151 private MessageSendLogStore messageSendLogStore
;
153 private AccountDatabase accountDatabase
;
155 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
156 this.fileChannel
= fileChannel
;
160 public static SignalAccount
load(
161 File dataPath
, String accountPath
, boolean waitForLock
, final TrustNewIdentity trustNewIdentity
162 ) throws IOException
{
163 logger
.trace("Opening account file");
164 final var fileName
= getFileName(dataPath
, accountPath
);
165 final var pair
= openFileChannel(fileName
, waitForLock
);
167 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
168 logger
.trace("Loading account file");
169 signalAccount
.load(dataPath
, accountPath
, trustNewIdentity
);
170 logger
.trace("Migrating legacy parts of account file");
171 signalAccount
.migrateLegacyConfigs();
173 return signalAccount
;
174 } catch (Throwable e
) {
175 pair
.second().close();
176 pair
.first().close();
181 public static SignalAccount
create(
185 ServiceEnvironment serviceEnvironment
,
186 IdentityKeyPair aciIdentityKey
,
187 IdentityKeyPair pniIdentityKey
,
189 ProfileKey profileKey
,
190 final TrustNewIdentity trustNewIdentity
191 ) throws IOException
{
192 IOUtils
.createPrivateDirectories(dataPath
);
193 var fileName
= getFileName(dataPath
, accountPath
);
194 if (!fileName
.exists()) {
195 IOUtils
.createPrivateFile(fileName
);
198 final var pair
= openFileChannel(fileName
, true);
199 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
201 signalAccount
.accountPath
= accountPath
;
202 signalAccount
.number
= number
;
203 signalAccount
.serviceEnvironment
= serviceEnvironment
;
204 signalAccount
.profileKey
= profileKey
;
206 signalAccount
.dataPath
= dataPath
;
207 signalAccount
.aciIdentityKeyPair
= aciIdentityKey
;
208 signalAccount
.pniIdentityKeyPair
= pniIdentityKey
;
209 signalAccount
.localRegistrationId
= registrationId
;
210 signalAccount
.trustNewIdentity
= trustNewIdentity
;
211 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
212 signalAccount
.getRecipientResolver(),
213 signalAccount
::saveGroupStore
);
214 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
215 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
217 signalAccount
.registered
= false;
219 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
220 signalAccount
.migrateLegacyConfigs();
221 signalAccount
.save();
223 return signalAccount
;
226 public static SignalAccount
createOrUpdateLinkedAccount(
230 ServiceEnvironment serviceEnvironment
,
234 String encryptedDeviceName
,
236 IdentityKeyPair aciIdentityKey
,
237 IdentityKeyPair pniIdentityKey
,
239 ProfileKey profileKey
,
240 final TrustNewIdentity trustNewIdentity
241 ) throws IOException
{
242 IOUtils
.createPrivateDirectories(dataPath
);
243 var fileName
= getFileName(dataPath
, accountPath
);
244 if (!fileName
.exists()) {
245 return createLinkedAccount(dataPath
,
261 final var signalAccount
= load(dataPath
, accountPath
, true, trustNewIdentity
);
262 signalAccount
.setProvisioningData(number
,
271 signalAccount
.getRecipientTrustedResolver()
272 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
273 signalAccount
.getSessionStore().archiveAllSessions();
274 signalAccount
.getSenderKeyStore().deleteAll();
275 signalAccount
.clearAllPreKeys();
276 return signalAccount
;
279 public void initDatabase() {
280 getAccountDatabase();
283 private void clearAllPreKeys() {
284 this.aciPreKeyIdOffset
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
285 this.aciNextSignedPreKeyId
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
286 this.pniPreKeyIdOffset
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
287 this.pniNextSignedPreKeyId
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
288 this.getAciPreKeyStore().removeAllPreKeys();
289 this.getAciSignedPreKeyStore().removeAllSignedPreKeys();
290 this.getPniPreKeyStore().removeAllPreKeys();
291 this.getPniSignedPreKeyStore().removeAllSignedPreKeys();
295 private static SignalAccount
createLinkedAccount(
299 ServiceEnvironment serviceEnvironment
,
303 String encryptedDeviceName
,
305 IdentityKeyPair aciIdentityKey
,
306 IdentityKeyPair pniIdentityKey
,
308 ProfileKey profileKey
,
309 final TrustNewIdentity trustNewIdentity
310 ) throws IOException
{
311 var fileName
= getFileName(dataPath
, accountPath
);
312 IOUtils
.createPrivateFile(fileName
);
314 final var pair
= openFileChannel(fileName
, true);
315 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
317 signalAccount
.dataPath
= dataPath
;
318 signalAccount
.accountPath
= accountPath
;
319 signalAccount
.serviceEnvironment
= serviceEnvironment
;
320 signalAccount
.localRegistrationId
= registrationId
;
321 signalAccount
.trustNewIdentity
= trustNewIdentity
;
322 signalAccount
.setProvisioningData(number
,
332 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
333 signalAccount
.getRecipientResolver(),
334 signalAccount
::saveGroupStore
);
335 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
336 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
338 signalAccount
.getRecipientTrustedResolver()
339 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
340 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
341 signalAccount
.migrateLegacyConfigs();
342 signalAccount
.clearAllPreKeys();
343 signalAccount
.save();
345 return signalAccount
;
348 private void setProvisioningData(
352 final String password
,
353 final String encryptedDeviceName
,
355 final IdentityKeyPair aciIdentity
,
356 final IdentityKeyPair pniIdentity
,
357 final ProfileKey profileKey
359 this.number
= number
;
362 this.password
= password
;
363 this.profileKey
= profileKey
;
364 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
365 this.encryptedDeviceName
= encryptedDeviceName
;
366 this.deviceId
= deviceId
;
367 this.aciIdentityKeyPair
= aciIdentity
;
368 this.pniIdentityKeyPair
= pniIdentity
;
369 this.registered
= true;
370 this.isMultiDevice
= true;
371 this.lastReceiveTimestamp
= 0;
372 this.pinMasterKey
= null;
373 this.storageManifestVersion
= -1;
374 this.storageKey
= null;
377 private void migrateLegacyConfigs() {
378 if (getPassword() == null) {
379 setPassword(KeyUtils
.createPassword());
382 if (getProfileKey() == null) {
383 // Old config file, creating new profile key
384 setProfileKey(KeyUtils
.createProfileKey());
386 // Ensure our profile key is stored in profile store
387 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
388 if (previousStorageVersion
< 3) {
389 for (final var group
: groupStore
.getGroups()) {
390 if (group
instanceof GroupInfoV2
&& group
.getDistributionId() == null) {
391 ((GroupInfoV2
) group
).setDistributionId(DistributionId
.create());
392 groupStore
.updateGroup(group
);
397 if (isPrimaryDevice() && getPniIdentityKeyPair() == null) {
398 setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
402 private void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
403 getSessionStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
404 getIdentityKeyStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
405 getMessageCache().mergeRecipients(recipientId
, toBeMergedRecipientId
);
406 getGroupStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
407 getSenderKeyStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
410 public void removeRecipient(final RecipientId recipientId
) {
411 getSessionStore().deleteAllSessions(recipientId
);
412 getIdentityKeyStore().deleteIdentity(recipientId
);
413 getMessageCache().deleteMessages(recipientId
);
414 getSenderKeyStore().deleteAll(recipientId
);
415 getRecipientStore().deleteRecipientData(recipientId
);
418 public static File
getFileName(File dataPath
, String account
) {
419 return new File(dataPath
, account
);
422 private static File
getUserPath(final File dataPath
, final String account
) {
423 final var path
= new File(dataPath
, account
+ ".d");
425 IOUtils
.createPrivateDirectories(path
);
426 } catch (IOException e
) {
427 throw new AssertionError("Failed to create user path", e
);
432 private static File
getMessageCachePath(File dataPath
, String account
) {
433 return new File(getUserPath(dataPath
, account
), "msg-cache");
436 private static File
getGroupCachePath(File dataPath
, String account
) {
437 return new File(getUserPath(dataPath
, account
), "group-cache");
440 private static File
getAciPreKeysPath(File dataPath
, String account
) {
441 return new File(getUserPath(dataPath
, account
), "pre-keys");
444 private static File
getAciSignedPreKeysPath(File dataPath
, String account
) {
445 return new File(getUserPath(dataPath
, account
), "signed-pre-keys");
448 private static File
getPniPreKeysPath(File dataPath
, String account
) {
449 return new File(getUserPath(dataPath
, account
), "pre-keys-pni");
452 private static File
getPniSignedPreKeysPath(File dataPath
, String account
) {
453 return new File(getUserPath(dataPath
, account
), "signed-pre-keys-pni");
456 private static File
getIdentitiesPath(File dataPath
, String account
) {
457 return new File(getUserPath(dataPath
, account
), "identities");
460 private static File
getSessionsPath(File dataPath
, String account
) {
461 return new File(getUserPath(dataPath
, account
), "sessions");
464 private static File
getSenderKeysPath(File dataPath
, String account
) {
465 return new File(getUserPath(dataPath
, account
), "sender-keys");
468 private static File
getSharedSenderKeysFile(File dataPath
, String account
) {
469 return new File(getUserPath(dataPath
, account
), "shared-sender-keys-store");
472 private static File
getRecipientsStoreFile(File dataPath
, String account
) {
473 return new File(getUserPath(dataPath
, account
), "recipients-store");
476 private static File
getStorageManifestFile(File dataPath
, String account
) {
477 return new File(getUserPath(dataPath
, account
), "storage-manifest");
480 private static File
getDatabaseFile(File dataPath
, String account
) {
481 return new File(getUserPath(dataPath
, account
), "account.db");
484 public static boolean accountFileExists(File dataPath
, String account
) {
485 if (account
== null) {
488 var f
= getFileName(dataPath
, account
);
489 return !(!f
.exists() || f
.isDirectory());
493 File dataPath
, String accountPath
, final TrustNewIdentity trustNewIdentity
494 ) throws IOException
{
495 this.dataPath
= dataPath
;
496 this.accountPath
= accountPath
;
497 final JsonNode rootNode
;
498 synchronized (fileChannel
) {
499 fileChannel
.position(0);
500 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
503 if (rootNode
.hasNonNull("version")) {
504 var accountVersion
= rootNode
.get("version").asInt(1);
505 if (accountVersion
> CURRENT_STORAGE_VERSION
) {
506 throw new IOException("Config file was created by a more recent version!");
507 } else if (accountVersion
< MINIMUM_STORAGE_VERSION
) {
508 throw new IOException("Config file was created by a no longer supported older version!");
510 previousStorageVersion
= accountVersion
;
513 number
= Utils
.getNotNullNode(rootNode
, "username").asText();
514 if (rootNode
.hasNonNull("password")) {
515 password
= rootNode
.get("password").asText();
517 if (rootNode
.hasNonNull("serviceEnvironment")) {
518 serviceEnvironment
= ServiceEnvironment
.valueOf(rootNode
.get("serviceEnvironment").asText());
520 registered
= Utils
.getNotNullNode(rootNode
, "registered").asBoolean();
521 if (rootNode
.hasNonNull("uuid")) {
523 aci
= ACI
.parseOrThrow(rootNode
.get("uuid").asText());
524 } catch (IllegalArgumentException e
) {
525 throw new IOException("Config file contains an invalid aci/uuid, needs to be a valid UUID", e
);
528 if (rootNode
.hasNonNull("pni")) {
530 pni
= PNI
.parseOrThrow(rootNode
.get("pni").asText());
531 } catch (IllegalArgumentException e
) {
532 throw new IOException("Config file contains an invalid pni, needs to be a valid UUID", e
);
535 if (rootNode
.hasNonNull("deviceName")) {
536 encryptedDeviceName
= rootNode
.get("deviceName").asText();
538 if (rootNode
.hasNonNull("deviceId")) {
539 deviceId
= rootNode
.get("deviceId").asInt();
541 if (rootNode
.hasNonNull("isMultiDevice")) {
542 isMultiDevice
= rootNode
.get("isMultiDevice").asBoolean();
544 if (rootNode
.hasNonNull("lastReceiveTimestamp")) {
545 lastReceiveTimestamp
= rootNode
.get("lastReceiveTimestamp").asLong();
547 int registrationId
= 0;
548 if (rootNode
.hasNonNull("registrationId")) {
549 registrationId
= rootNode
.get("registrationId").asInt();
551 IdentityKeyPair aciIdentityKeyPair
= null;
552 if (rootNode
.hasNonNull("identityPrivateKey") && rootNode
.hasNonNull("identityKey")) {
553 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityKey").asText());
554 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityPrivateKey").asText());
555 aciIdentityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
557 if (rootNode
.hasNonNull("pniIdentityPrivateKey") && rootNode
.hasNonNull("pniIdentityKey")) {
558 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityKey").asText());
559 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityPrivateKey").asText());
560 pniIdentityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
563 if (rootNode
.hasNonNull("registrationLockPin")) {
564 registrationLockPin
= rootNode
.get("registrationLockPin").asText();
566 if (rootNode
.hasNonNull("pinMasterKey")) {
567 pinMasterKey
= new MasterKey(Base64
.getDecoder().decode(rootNode
.get("pinMasterKey").asText()));
569 if (rootNode
.hasNonNull("storageKey")) {
570 storageKey
= new StorageKey(Base64
.getDecoder().decode(rootNode
.get("storageKey").asText()));
572 if (rootNode
.hasNonNull("storageManifestVersion")) {
573 storageManifestVersion
= rootNode
.get("storageManifestVersion").asLong();
575 if (rootNode
.hasNonNull("preKeyIdOffset")) {
576 aciPreKeyIdOffset
= rootNode
.get("preKeyIdOffset").asInt(1);
578 aciPreKeyIdOffset
= 1;
580 if (rootNode
.hasNonNull("nextSignedPreKeyId")) {
581 aciNextSignedPreKeyId
= rootNode
.get("nextSignedPreKeyId").asInt(1);
583 aciNextSignedPreKeyId
= 1;
585 if (rootNode
.hasNonNull("pniPreKeyIdOffset")) {
586 pniPreKeyIdOffset
= rootNode
.get("pniPreKeyIdOffset").asInt(1);
588 pniPreKeyIdOffset
= 1;
590 if (rootNode
.hasNonNull("pniNextSignedPreKeyId")) {
591 pniNextSignedPreKeyId
= rootNode
.get("pniNextSignedPreKeyId").asInt(1);
593 pniNextSignedPreKeyId
= 1;
595 if (rootNode
.hasNonNull("profileKey")) {
597 profileKey
= new ProfileKey(Base64
.getDecoder().decode(rootNode
.get("profileKey").asText()));
598 } catch (InvalidInputException e
) {
599 throw new IOException(
600 "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
605 var migratedLegacyConfig
= false;
606 final var legacySignalProtocolStore
= rootNode
.hasNonNull("axolotlStore")
607 ? jsonProcessor
.convertValue(Utils
.getNotNullNode(rootNode
, "axolotlStore"),
608 LegacyJsonSignalProtocolStore
.class)
610 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
611 aciIdentityKeyPair
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentityKeyPair();
612 registrationId
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getLocalRegistrationId();
613 migratedLegacyConfig
= true;
616 this.aciIdentityKeyPair
= aciIdentityKeyPair
;
617 this.localRegistrationId
= registrationId
;
618 this.trustNewIdentity
= trustNewIdentity
;
620 migratedLegacyConfig
= loadLegacyStores(rootNode
, legacySignalProtocolStore
) || migratedLegacyConfig
;
622 if (rootNode
.hasNonNull("groupStore")) {
623 groupStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("groupStore"), GroupStore
.Storage
.class);
624 groupStore
= GroupStore
.fromStorage(groupStoreStorage
,
625 getGroupCachePath(dataPath
, accountPath
),
626 getRecipientResolver(),
627 this::saveGroupStore
);
629 groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
630 getRecipientResolver(),
631 this::saveGroupStore
);
634 if (rootNode
.hasNonNull("stickerStore")) {
635 stickerStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("stickerStore"), StickerStore
.Storage
.class);
636 stickerStore
= StickerStore
.fromStorage(stickerStoreStorage
, this::saveStickerStore
);
638 stickerStore
= new StickerStore(this::saveStickerStore
);
641 if (rootNode
.hasNonNull("configurationStore")) {
642 configurationStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("configurationStore"),
643 ConfigurationStore
.Storage
.class);
644 configurationStore
= ConfigurationStore
.fromStorage(configurationStoreStorage
,
645 this::saveConfigurationStore
);
647 configurationStore
= new ConfigurationStore(this::saveConfigurationStore
);
650 migratedLegacyConfig
= loadLegacyThreadStore(rootNode
) || migratedLegacyConfig
;
652 if (migratedLegacyConfig
) {
657 private boolean loadLegacyStores(
658 final JsonNode rootNode
, final LegacyJsonSignalProtocolStore legacySignalProtocolStore
660 var migrated
= false;
661 var legacyRecipientStoreNode
= rootNode
.get("recipientStore");
662 if (legacyRecipientStoreNode
!= null) {
663 logger
.debug("Migrating legacy recipient store.");
664 var legacyRecipientStore
= jsonProcessor
.convertValue(legacyRecipientStoreNode
, LegacyRecipientStore
.class);
665 if (legacyRecipientStore
!= null) {
666 getRecipientStore().resolveRecipientsTrusted(legacyRecipientStore
.getAddresses());
668 getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
672 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyPreKeyStore() != null) {
673 logger
.debug("Migrating legacy pre key store.");
674 for (var entry
: legacySignalProtocolStore
.getLegacyPreKeyStore().getPreKeys().entrySet()) {
676 getAciPreKeyStore().storePreKey(entry
.getKey(), new PreKeyRecord(entry
.getValue()));
677 } catch (InvalidMessageException e
) {
678 logger
.warn("Failed to migrate pre key, ignoring", e
);
684 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySignedPreKeyStore() != null) {
685 logger
.debug("Migrating legacy signed pre key store.");
686 for (var entry
: legacySignalProtocolStore
.getLegacySignedPreKeyStore().getSignedPreKeys().entrySet()) {
688 getAciSignedPreKeyStore().storeSignedPreKey(entry
.getKey(),
689 new SignedPreKeyRecord(entry
.getValue()));
690 } catch (InvalidMessageException e
) {
691 logger
.warn("Failed to migrate signed pre key, ignoring", e
);
697 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySessionStore() != null) {
698 logger
.debug("Migrating legacy session store.");
699 for (var session
: legacySignalProtocolStore
.getLegacySessionStore().getSessions()) {
701 getSessionStore().storeSession(new SignalProtocolAddress(session
.address
.getIdentifier(),
702 session
.deviceId
), new SessionRecord(session
.sessionRecord
));
703 } catch (Exception e
) {
704 logger
.warn("Failed to migrate session, ignoring", e
);
710 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
711 logger
.debug("Migrating legacy identity session store.");
712 for (var identity
: legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentities()) {
713 RecipientId recipientId
= getRecipientStore().resolveRecipientTrusted(identity
.getAddress());
714 getIdentityKeyStore().saveIdentity(recipientId
, identity
.getIdentityKey(), identity
.getDateAdded());
715 getIdentityKeyStore().setIdentityTrustLevel(recipientId
,
716 identity
.getIdentityKey(),
717 identity
.getTrustLevel());
722 if (rootNode
.hasNonNull("contactStore")) {
723 logger
.debug("Migrating legacy contact store.");
724 final var contactStoreNode
= rootNode
.get("contactStore");
725 final var contactStore
= jsonProcessor
.convertValue(contactStoreNode
, LegacyJsonContactsStore
.class);
726 for (var contact
: contactStore
.getContacts()) {
727 final var recipientId
= getRecipientStore().resolveRecipientTrusted(contact
.getAddress());
728 getContactStore().storeContact(recipientId
,
729 new Contact(contact
.name
,
732 contact
.messageExpirationTime
,
737 // Store profile keys only in profile store
738 var profileKeyString
= contact
.profileKey
;
739 if (profileKeyString
!= null) {
740 final ProfileKey profileKey
;
742 profileKey
= new ProfileKey(Base64
.getDecoder().decode(profileKeyString
));
743 getProfileStore().storeProfileKey(recipientId
, profileKey
);
744 } catch (InvalidInputException e
) {
745 logger
.warn("Failed to parse legacy contact profile key: {}", e
.getMessage());
752 if (rootNode
.hasNonNull("profileStore")) {
753 logger
.debug("Migrating legacy profile store.");
754 var profileStoreNode
= rootNode
.get("profileStore");
755 final var legacyProfileStore
= jsonProcessor
.convertValue(profileStoreNode
, LegacyProfileStore
.class);
756 for (var profileEntry
: legacyProfileStore
.getProfileEntries()) {
757 var recipientId
= getRecipientResolver().resolveRecipient(profileEntry
.getAddress());
758 getProfileStore().storeProfileKeyCredential(recipientId
, profileEntry
.getProfileKeyCredential());
759 getProfileStore().storeProfileKey(recipientId
, profileEntry
.getProfileKey());
760 final var profile
= profileEntry
.getProfile();
761 if (profile
!= null) {
762 final var capabilities
= new HashSet
<Profile
.Capability
>();
763 if (profile
.getCapabilities() != null) {
764 if (profile
.getCapabilities().gv1Migration
) {
765 capabilities
.add(Profile
.Capability
.gv1Migration
);
767 if (profile
.getCapabilities().storage
) {
768 capabilities
.add(Profile
.Capability
.storage
);
771 final var newProfile
= new Profile(profileEntry
.getLastUpdateTimestamp(),
772 profile
.getGivenName(),
773 profile
.getFamilyName(),
775 profile
.getAboutEmoji(),
778 profile
.isUnrestrictedUnidentifiedAccess()
779 ? Profile
.UnidentifiedAccessMode
.UNRESTRICTED
780 : profile
.getUnidentifiedAccess() != null
781 ? Profile
.UnidentifiedAccessMode
.ENABLED
782 : Profile
.UnidentifiedAccessMode
.DISABLED
,
784 getProfileStore().storeProfile(recipientId
, newProfile
);
792 private boolean loadLegacyThreadStore(final JsonNode rootNode
) {
793 var threadStoreNode
= rootNode
.get("threadStore");
794 if (threadStoreNode
!= null && !threadStoreNode
.isNull()) {
795 var threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
796 // Migrate thread info to group and contact store
797 for (var thread
: threadStore
.getThreads()) {
798 if (thread
.id
== null || thread
.id
.isEmpty()) {
802 if (UuidUtil
.isUuid(thread
.id
) || thread
.id
.startsWith("+")) {
803 final var recipientId
= getRecipientResolver().resolveRecipient(thread
.id
);
804 var contact
= getContactStore().getContact(recipientId
);
805 if (contact
!= null) {
806 getContactStore().storeContact(recipientId
,
807 Contact
.newBuilder(contact
)
808 .withMessageExpirationTime(thread
.messageExpirationTime
)
812 var groupInfo
= groupStore
.getGroup(GroupId
.fromBase64(thread
.id
));
813 if (groupInfo
instanceof GroupInfoV1
) {
814 ((GroupInfoV1
) groupInfo
).messageExpirationTime
= thread
.messageExpirationTime
;
815 groupStore
.updateGroup(groupInfo
);
818 } catch (Exception e
) {
819 logger
.warn("Failed to read legacy thread info: {}", e
.getMessage());
828 private void saveStickerStore(StickerStore
.Storage storage
) {
829 this.stickerStoreStorage
= storage
;
833 private void saveGroupStore(GroupStore
.Storage storage
) {
834 this.groupStoreStorage
= storage
;
838 private void saveConfigurationStore(ConfigurationStore
.Storage storage
) {
839 this.configurationStoreStorage
= storage
;
843 private void save() {
844 synchronized (fileChannel
) {
845 var rootNode
= jsonProcessor
.createObjectNode();
846 rootNode
.put("version", CURRENT_STORAGE_VERSION
)
847 .put("username", number
)
848 .put("serviceEnvironment", serviceEnvironment
== null ?
null : serviceEnvironment
.name())
849 .put("uuid", aci
== null ?
null : aci
.toString())
850 .put("pni", pni
== null ?
null : pni
.toString())
851 .put("deviceName", encryptedDeviceName
)
852 .put("deviceId", deviceId
)
853 .put("isMultiDevice", isMultiDevice
)
854 .put("lastReceiveTimestamp", lastReceiveTimestamp
)
855 .put("password", password
)
856 .put("registrationId", localRegistrationId
)
857 .put("identityPrivateKey",
858 Base64
.getEncoder().encodeToString(aciIdentityKeyPair
.getPrivateKey().serialize()))
860 Base64
.getEncoder().encodeToString(aciIdentityKeyPair
.getPublicKey().serialize()))
861 .put("pniIdentityPrivateKey",
862 pniIdentityKeyPair
== null
864 : Base64
.getEncoder()
865 .encodeToString(pniIdentityKeyPair
.getPrivateKey().serialize()))
866 .put("pniIdentityKey",
867 pniIdentityKeyPair
== null
869 : Base64
.getEncoder().encodeToString(pniIdentityKeyPair
.getPublicKey().serialize()))
870 .put("registrationLockPin", registrationLockPin
)
872 pinMasterKey
== null ?
null : Base64
.getEncoder().encodeToString(pinMasterKey
.serialize()))
874 storageKey
== null ?
null : Base64
.getEncoder().encodeToString(storageKey
.serialize()))
875 .put("storageManifestVersion", storageManifestVersion
== -1 ?
null : storageManifestVersion
)
876 .put("preKeyIdOffset", aciPreKeyIdOffset
)
877 .put("nextSignedPreKeyId", aciNextSignedPreKeyId
)
878 .put("pniPreKeyIdOffset", pniPreKeyIdOffset
)
879 .put("pniNextSignedPreKeyId", pniNextSignedPreKeyId
)
881 profileKey
== null ?
null : Base64
.getEncoder().encodeToString(profileKey
.serialize()))
882 .put("registered", registered
)
883 .putPOJO("groupStore", groupStoreStorage
)
884 .putPOJO("stickerStore", stickerStoreStorage
)
885 .putPOJO("configurationStore", configurationStoreStorage
);
887 try (var output
= new ByteArrayOutputStream()) {
888 // Write to memory first to prevent corrupting the file in case of serialization errors
889 jsonProcessor
.writeValue(output
, rootNode
);
890 var input
= new ByteArrayInputStream(output
.toByteArray());
891 fileChannel
.position(0);
892 input
.transferTo(Channels
.newOutputStream(fileChannel
));
893 fileChannel
.truncate(fileChannel
.position());
894 fileChannel
.force(false);
896 } catch (Exception e
) {
897 logger
.error("Error saving file: {}", e
.getMessage(), e
);
902 private static Pair
<FileChannel
, FileLock
> openFileChannel(File fileName
, boolean waitForLock
) throws IOException
{
903 var fileChannel
= new RandomAccessFile(fileName
, "rw").getChannel();
905 var lock
= fileChannel
.tryLock();
908 logger
.debug("Config file is in use by another instance.");
909 throw new IOException("Config file is in use by another instance.");
911 logger
.info("Config file is in use by another instance, waiting…");
912 lock
= fileChannel
.lock();
913 logger
.info("Config file lock acquired.");
915 final var result
= new Pair
<>(fileChannel
, lock
);
919 if (fileChannel
!= null) {
925 public void addPreKeys(ServiceIdType serviceIdType
, List
<PreKeyRecord
> records
) {
926 if (serviceIdType
.equals(ServiceIdType
.ACI
)) {
927 addAciPreKeys(records
);
929 addPniPreKeys(records
);
933 public void addAciPreKeys(List
<PreKeyRecord
> records
) {
934 for (var record : records
) {
935 if (aciPreKeyIdOffset
!= record.getId()) {
936 logger
.error("Invalid pre key id {}, expected {}", record.getId(), aciPreKeyIdOffset
);
937 throw new AssertionError("Invalid pre key id");
939 getAciPreKeyStore().storePreKey(record.getId(), record);
940 aciPreKeyIdOffset
= (aciPreKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
945 public void addPniPreKeys(List
<PreKeyRecord
> records
) {
946 for (var record : records
) {
947 if (pniPreKeyIdOffset
!= record.getId()) {
948 logger
.error("Invalid pre key id {}, expected {}", record.getId(), pniPreKeyIdOffset
);
949 throw new AssertionError("Invalid pre key id");
951 getPniPreKeyStore().storePreKey(record.getId(), record);
952 pniPreKeyIdOffset
= (pniPreKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
957 public void addSignedPreKey(ServiceIdType serviceIdType
, SignedPreKeyRecord
record) {
958 if (serviceIdType
.equals(ServiceIdType
.ACI
)) {
959 addAciSignedPreKey(record);
961 addPniSignedPreKey(record);
965 public void addAciSignedPreKey(SignedPreKeyRecord
record) {
966 if (aciNextSignedPreKeyId
!= record.getId()) {
967 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), aciNextSignedPreKeyId
);
968 throw new AssertionError("Invalid signed pre key id");
970 getAciSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
971 aciNextSignedPreKeyId
= (aciNextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
975 public void addPniSignedPreKey(SignedPreKeyRecord
record) {
976 if (pniNextSignedPreKeyId
!= record.getId()) {
977 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), pniNextSignedPreKeyId
);
978 throw new AssertionError("Invalid signed pre key id");
980 getPniSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
981 pniNextSignedPreKeyId
= (pniNextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
985 public SignalServiceDataStore
getSignalServiceDataStore() {
986 return new SignalServiceDataStore() {
988 public SignalServiceAccountDataStore
get(final ServiceId accountIdentifier
) {
989 if (accountIdentifier
.equals(aci
)) {
990 return getSignalServiceAccountDataStore();
991 } else if (accountIdentifier
.equals(pni
)) {
992 throw new AssertionError("PNI not to be used yet!");
994 throw new IllegalArgumentException("No matching store found for " + accountIdentifier
);
999 public SignalServiceAccountDataStore
aci() {
1000 return getSignalServiceAccountDataStore();
1004 public SignalServiceAccountDataStore
pni() {
1005 throw new AssertionError("PNI not to be used yet!");
1009 public boolean isMultiDevice() {
1010 return SignalAccount
.this.isMultiDevice();
1015 public SignalServiceAccountDataStore
getSignalServiceAccountDataStore() {
1016 return getOrCreate(() -> signalProtocolStore
,
1017 () -> signalProtocolStore
= new SignalProtocolStore(getAciPreKeyStore(),
1018 getAciSignedPreKeyStore(),
1020 getAciIdentityKeyStore(),
1021 getSenderKeyStore(),
1022 this::isMultiDevice
));
1025 private PreKeyStore
getAciPreKeyStore() {
1026 return getOrCreate(() -> aciPreKeyStore
,
1027 () -> aciPreKeyStore
= new PreKeyStore(getAciPreKeysPath(dataPath
, accountPath
)));
1030 private SignedPreKeyStore
getAciSignedPreKeyStore() {
1031 return getOrCreate(() -> aciSignedPreKeyStore
,
1032 () -> aciSignedPreKeyStore
= new SignedPreKeyStore(getAciSignedPreKeysPath(dataPath
, accountPath
)));
1035 private PreKeyStore
getPniPreKeyStore() {
1036 return getOrCreate(() -> pniPreKeyStore
,
1037 () -> pniPreKeyStore
= new PreKeyStore(getPniPreKeysPath(dataPath
, accountPath
)));
1040 private SignedPreKeyStore
getPniSignedPreKeyStore() {
1041 return getOrCreate(() -> pniSignedPreKeyStore
,
1042 () -> pniSignedPreKeyStore
= new SignedPreKeyStore(getPniSignedPreKeysPath(dataPath
, accountPath
)));
1045 public SessionStore
getSessionStore() {
1046 return getOrCreate(() -> sessionStore
,
1047 () -> sessionStore
= new SessionStore(getSessionsPath(dataPath
, accountPath
), getRecipientResolver()));
1050 public IdentityKeyStore
getIdentityKeyStore() {
1051 return getOrCreate(() -> identityKeyStore
,
1052 () -> identityKeyStore
= new IdentityKeyStore(getIdentitiesPath(dataPath
, accountPath
),
1053 getRecipientResolver(),
1057 public SignalIdentityKeyStore
getAciIdentityKeyStore() {
1058 return getOrCreate(() -> aciIdentityKeyStore
,
1059 () -> aciIdentityKeyStore
= new SignalIdentityKeyStore(getRecipientResolver(),
1060 () -> aciIdentityKeyPair
,
1061 localRegistrationId
,
1062 getIdentityKeyStore()));
1065 public GroupStore
getGroupStore() {
1069 public ContactsStore
getContactStore() {
1070 return getRecipientStore();
1073 public RecipientResolver
getRecipientResolver() {
1074 return getRecipientStore();
1077 public RecipientTrustedResolver
getRecipientTrustedResolver() {
1078 return getRecipientStore();
1081 public RecipientAddressResolver
getRecipientAddressResolver() {
1082 return getRecipientStore()::resolveRecipientAddress
;
1085 public RecipientStore
getRecipientStore() {
1086 return getOrCreate(() -> recipientStore
,
1087 () -> recipientStore
= RecipientStore
.load(getRecipientsStoreFile(dataPath
, accountPath
),
1088 this::mergeRecipients
,
1089 this::getSelfRecipientAddress
));
1092 public ProfileStore
getProfileStore() {
1093 return getRecipientStore();
1096 public StickerStore
getStickerStore() {
1097 return stickerStore
;
1100 public SenderKeyStore
getSenderKeyStore() {
1101 return getOrCreate(() -> senderKeyStore
,
1102 () -> senderKeyStore
= new SenderKeyStore(getSharedSenderKeysFile(dataPath
, accountPath
),
1103 getSenderKeysPath(dataPath
, accountPath
),
1104 getRecipientAddressResolver(),
1105 getRecipientResolver()));
1108 public ConfigurationStore
getConfigurationStore() {
1109 return configurationStore
;
1112 public MessageCache
getMessageCache() {
1113 return getOrCreate(() -> messageCache
,
1114 () -> messageCache
= new MessageCache(getMessageCachePath(dataPath
, accountPath
)));
1117 public AccountDatabase
getAccountDatabase() {
1118 return getOrCreate(() -> accountDatabase
, () -> {
1120 accountDatabase
= AccountDatabase
.init(getDatabaseFile(dataPath
, accountPath
));
1121 } catch (SQLException e
) {
1122 throw new RuntimeException(e
);
1127 public MessageSendLogStore
getMessageSendLogStore() {
1128 return getOrCreate(() -> messageSendLogStore
,
1129 () -> messageSendLogStore
= new MessageSendLogStore(getRecipientResolver(), getAccountDatabase()));
1132 public CredentialsProvider
getCredentialsProvider() {
1133 return new CredentialsProvider() {
1135 public ACI
getAci() {
1140 public PNI
getPni() {
1145 public String
getE164() {
1150 public String
getPassword() {
1155 public int getDeviceId() {
1161 public String
getNumber() {
1165 public void setNumber(final String number
) {
1166 this.number
= number
;
1170 public ServiceEnvironment
getServiceEnvironment() {
1171 return serviceEnvironment
;
1174 public void setServiceEnvironment(final ServiceEnvironment serviceEnvironment
) {
1175 this.serviceEnvironment
= serviceEnvironment
;
1179 public ACI
getAci() {
1183 public void setAci(final ACI aci
) {
1188 public PNI
getPni() {
1192 public void setPni(final PNI pni
) {
1197 public SignalServiceAddress
getSelfAddress() {
1198 return new SignalServiceAddress(aci
, number
);
1201 public RecipientAddress
getSelfRecipientAddress() {
1202 return new RecipientAddress(aci
== null ?
null : aci
.uuid(), number
);
1205 public RecipientId
getSelfRecipientId() {
1206 return getRecipientResolver().resolveRecipient(getSelfRecipientAddress());
1209 public byte[] getEncryptedDeviceName() {
1210 return encryptedDeviceName
== null ?
null : Base64
.getDecoder().decode(encryptedDeviceName
);
1213 public void setEncryptedDeviceName(final String encryptedDeviceName
) {
1214 this.encryptedDeviceName
= encryptedDeviceName
;
1218 public int getDeviceId() {
1222 public boolean isPrimaryDevice() {
1223 return deviceId
== SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1226 public IdentityKeyPair
getIdentityKeyPair(ServiceIdType serviceIdType
) {
1227 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciIdentityKeyPair
: pniIdentityKeyPair
;
1230 public IdentityKeyPair
getAciIdentityKeyPair() {
1231 return aciIdentityKeyPair
;
1234 public IdentityKeyPair
getPniIdentityKeyPair() {
1235 return pniIdentityKeyPair
;
1238 public void setPniIdentityKeyPair(final IdentityKeyPair identityKeyPair
) {
1239 pniIdentityKeyPair
= identityKeyPair
;
1243 public int getLocalRegistrationId() {
1244 return localRegistrationId
;
1247 public String
getPassword() {
1251 private void setPassword(final String password
) {
1252 this.password
= password
;
1256 public void setRegistrationLockPin(final String registrationLockPin
) {
1257 this.registrationLockPin
= registrationLockPin
;
1261 public String
getRegistrationLock() {
1262 final var masterKey
= getPinBackedMasterKey();
1263 if (masterKey
== null) {
1266 return masterKey
.deriveRegistrationLock();
1269 public MasterKey
getPinBackedMasterKey() {
1270 if (registrationLockPin
== null) {
1273 return pinMasterKey
;
1276 public MasterKey
getOrCreatePinMasterKey() {
1277 if (pinMasterKey
== null) {
1278 pinMasterKey
= KeyUtils
.createMasterKey();
1281 return pinMasterKey
;
1284 public StorageKey
getStorageKey() {
1285 if (pinMasterKey
!= null) {
1286 return pinMasterKey
.deriveStorageServiceKey();
1291 public StorageKey
getOrCreateStorageKey() {
1292 if (isPrimaryDevice()) {
1293 return getOrCreatePinMasterKey().deriveStorageServiceKey();
1298 public void setStorageKey(final StorageKey storageKey
) {
1299 if (storageKey
.equals(this.storageKey
)) {
1302 this.storageKey
= storageKey
;
1306 public long getStorageManifestVersion() {
1307 return this.storageManifestVersion
;
1310 public void setStorageManifestVersion(final long storageManifestVersion
) {
1311 if (storageManifestVersion
== this.storageManifestVersion
) {
1314 this.storageManifestVersion
= storageManifestVersion
;
1318 public Optional
<SignalStorageManifest
> getStorageManifest() {
1319 final var storageManifestFile
= getStorageManifestFile(dataPath
, accountPath
);
1320 if (!storageManifestFile
.exists()) {
1321 return Optional
.empty();
1323 try (var inputStream
= new FileInputStream(storageManifestFile
)) {
1324 return Optional
.of(SignalStorageManifest
.deserialize(inputStream
.readAllBytes()));
1325 } catch (IOException e
) {
1326 logger
.warn("Failed to read local storage manifest.", e
);
1327 return Optional
.empty();
1331 public void setStorageManifest(SignalStorageManifest manifest
) {
1332 final var manifestBytes
= manifest
.serialize();
1334 final var storageManifestFile
= getStorageManifestFile(dataPath
, accountPath
);
1335 try (var outputStream
= new FileOutputStream(storageManifestFile
)) {
1336 outputStream
.write(manifestBytes
);
1337 } catch (IOException e
) {
1338 logger
.error("Failed to store local storage manifest.", e
);
1342 public ProfileKey
getProfileKey() {
1346 public void setProfileKey(final ProfileKey profileKey
) {
1347 if (profileKey
.equals(this.profileKey
)) {
1350 this.profileKey
= profileKey
;
1352 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
1355 public byte[] getSelfUnidentifiedAccessKey() {
1356 return UnidentifiedAccess
.deriveAccessKeyFrom(getProfileKey());
1359 public int getPreKeyIdOffset(ServiceIdType serviceIdType
) {
1360 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciPreKeyIdOffset
: pniPreKeyIdOffset
;
1363 public int getNextSignedPreKeyId(ServiceIdType serviceIdType
) {
1364 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciNextSignedPreKeyId
: pniNextSignedPreKeyId
;
1367 public boolean isRegistered() {
1371 public void setRegistered(final boolean registered
) {
1372 this.registered
= registered
;
1376 public boolean isMultiDevice() {
1377 return isMultiDevice
;
1380 public void setMultiDevice(final boolean multiDevice
) {
1381 if (isMultiDevice
== multiDevice
) {
1384 isMultiDevice
= multiDevice
;
1388 public long getLastReceiveTimestamp() {
1389 return lastReceiveTimestamp
;
1392 public void setLastReceiveTimestamp(final long lastReceiveTimestamp
) {
1393 this.lastReceiveTimestamp
= lastReceiveTimestamp
;
1397 public boolean isUnrestrictedUnidentifiedAccess() {
1398 final var profile
= getProfileStore().getProfile(getSelfRecipientId());
1399 return profile
!= null && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
;
1402 public boolean isDiscoverableByPhoneNumber() {
1403 return configurationStore
.getPhoneNumberUnlisted() == null || !configurationStore
.getPhoneNumberUnlisted();
1406 public void finishRegistration(final ACI aci
, final PNI pni
, final MasterKey masterKey
, final String pin
) {
1407 this.pinMasterKey
= masterKey
;
1408 this.storageManifestVersion
= -1;
1409 this.storageKey
= null;
1410 this.encryptedDeviceName
= null;
1411 this.deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1412 this.isMultiDevice
= false;
1413 this.registered
= true;
1416 this.registrationLockPin
= pin
;
1417 this.lastReceiveTimestamp
= 0;
1421 getSessionStore().archiveAllSessions();
1422 getSenderKeyStore().deleteAll();
1423 final var recipientId
= getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
1424 final var publicKey
= getAciIdentityKeyPair().getPublicKey();
1425 getIdentityKeyStore().saveIdentity(recipientId
, publicKey
);
1426 getIdentityKeyStore().setIdentityTrustLevel(recipientId
, publicKey
, TrustLevel
.TRUSTED_VERIFIED
);
1429 public void deleteAccountData() throws IOException
{
1431 try (final var files
= Files
.walk(getUserPath(dataPath
, accountPath
).toPath())
1432 .sorted(Comparator
.reverseOrder())) {
1433 for (final var file
= files
.iterator(); file
.hasNext(); ) {
1434 Files
.delete(file
.next());
1437 Files
.delete(getFileName(dataPath
, accountPath
).toPath());
1441 public void close() {
1442 synchronized (fileChannel
) {
1443 if (accountDatabase
!= null) {
1445 accountDatabase
.close();
1446 } catch (SQLException e
) {
1447 logger
.warn("Failed to close account database: {}", e
.getMessage(), e
);
1450 if (messageSendLogStore
!= null) {
1451 messageSendLogStore
.close();
1456 } catch (ClosedChannelException ignored
) {
1458 fileChannel
.close();
1459 } catch (IOException e
) {
1460 logger
.warn("Failed to close account: {}", e
.getMessage(), e
);
1465 private <T
> T
getOrCreate(Supplier
<T
> supplier
, Callable creator
) {
1466 var value
= supplier
.get();
1467 if (value
!= null) {
1471 synchronized (LOCK
) {
1472 value
= supplier
.get();
1473 if (value
!= null) {
1477 return supplier
.get();
1481 private interface Callable
{