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
.TrustNewIdentity
;
19 import org
.asamk
.signal
.manager
.storage
.messageCache
.MessageCache
;
20 import org
.asamk
.signal
.manager
.storage
.prekeys
.PreKeyStore
;
21 import org
.asamk
.signal
.manager
.storage
.prekeys
.SignedPreKeyStore
;
22 import org
.asamk
.signal
.manager
.storage
.profiles
.LegacyProfileStore
;
23 import org
.asamk
.signal
.manager
.storage
.profiles
.ProfileStore
;
24 import org
.asamk
.signal
.manager
.storage
.protocol
.LegacyJsonSignalProtocolStore
;
25 import org
.asamk
.signal
.manager
.storage
.protocol
.SignalProtocolStore
;
26 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
27 import org
.asamk
.signal
.manager
.storage
.recipients
.LegacyRecipientStore
;
28 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
29 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
30 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
31 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientResolver
;
32 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientStore
;
33 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientTrustedResolver
;
34 import org
.asamk
.signal
.manager
.storage
.sendLog
.MessageSendLogStore
;
35 import org
.asamk
.signal
.manager
.storage
.senderKeys
.SenderKeyStore
;
36 import org
.asamk
.signal
.manager
.storage
.sessions
.SessionStore
;
37 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerStore
;
38 import org
.asamk
.signal
.manager
.storage
.threads
.LegacyJsonThreadStore
;
39 import org
.asamk
.signal
.manager
.util
.IOUtils
;
40 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
41 import org
.signal
.libsignal
.protocol
.IdentityKeyPair
;
42 import org
.signal
.libsignal
.protocol
.InvalidMessageException
;
43 import org
.signal
.libsignal
.protocol
.SignalProtocolAddress
;
44 import org
.signal
.libsignal
.protocol
.state
.PreKeyRecord
;
45 import org
.signal
.libsignal
.protocol
.state
.SessionRecord
;
46 import org
.signal
.libsignal
.protocol
.state
.SignedPreKeyRecord
;
47 import org
.signal
.libsignal
.protocol
.util
.Medium
;
48 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
49 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
50 import org
.slf4j
.Logger
;
51 import org
.slf4j
.LoggerFactory
;
52 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountDataStore
;
53 import org
.whispersystems
.signalservice
.api
.SignalServiceDataStore
;
54 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
55 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
56 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
57 import org
.whispersystems
.signalservice
.api
.push
.DistributionId
;
58 import org
.whispersystems
.signalservice
.api
.push
.PNI
;
59 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
60 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
61 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
62 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
63 import org
.whispersystems
.signalservice
.api
.util
.CredentialsProvider
;
64 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
66 import java
.io
.ByteArrayInputStream
;
67 import java
.io
.ByteArrayOutputStream
;
68 import java
.io
.Closeable
;
70 import java
.io
.IOException
;
71 import java
.io
.RandomAccessFile
;
72 import java
.nio
.channels
.Channels
;
73 import java
.nio
.channels
.ClosedChannelException
;
74 import java
.nio
.channels
.FileChannel
;
75 import java
.nio
.channels
.FileLock
;
76 import java
.nio
.file
.Files
;
77 import java
.security
.SecureRandom
;
78 import java
.sql
.SQLException
;
79 import java
.util
.Base64
;
80 import java
.util
.Comparator
;
81 import java
.util
.Date
;
82 import java
.util
.HashSet
;
83 import java
.util
.List
;
84 import java
.util
.function
.Supplier
;
86 public class SignalAccount
implements Closeable
{
88 private final static Logger logger
= LoggerFactory
.getLogger(SignalAccount
.class);
90 private static final int MINIMUM_STORAGE_VERSION
= 1;
91 private static final int CURRENT_STORAGE_VERSION
= 3;
93 private final Object LOCK
= new Object();
95 private final ObjectMapper jsonProcessor
= Utils
.createStorageObjectMapper();
97 private final FileChannel fileChannel
;
98 private final FileLock lock
;
100 private int previousStorageVersion
;
102 private File dataPath
;
103 private String accountPath
;
104 private ServiceEnvironment serviceEnvironment
;
105 private String number
;
108 private String encryptedDeviceName
;
109 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
110 private boolean isMultiDevice
= false;
111 private String password
;
112 private String registrationLockPin
;
113 private MasterKey pinMasterKey
;
114 private StorageKey storageKey
;
115 private long storageManifestVersion
= -1;
116 private ProfileKey profileKey
;
117 private int aciPreKeyIdOffset
= 1;
118 private int aciNextSignedPreKeyId
= 1;
119 private int pniPreKeyIdOffset
= 1;
120 private int pniNextSignedPreKeyId
= 1;
121 private IdentityKeyPair aciIdentityKeyPair
;
122 private IdentityKeyPair pniIdentityKeyPair
;
123 private int localRegistrationId
;
124 private TrustNewIdentity trustNewIdentity
;
125 private long lastReceiveTimestamp
= 0;
127 private boolean registered
= false;
129 private SignalProtocolStore signalProtocolStore
;
130 private PreKeyStore aciPreKeyStore
;
131 private SignedPreKeyStore aciSignedPreKeyStore
;
132 private PreKeyStore pniPreKeyStore
;
133 private SignedPreKeyStore pniSignedPreKeyStore
;
134 private SessionStore sessionStore
;
135 private IdentityKeyStore identityKeyStore
;
136 private SenderKeyStore senderKeyStore
;
137 private GroupStore groupStore
;
138 private GroupStore
.Storage groupStoreStorage
;
139 private RecipientStore recipientStore
;
140 private StickerStore stickerStore
;
141 private StickerStore
.Storage stickerStoreStorage
;
142 private ConfigurationStore configurationStore
;
143 private ConfigurationStore
.Storage configurationStoreStorage
;
145 private MessageCache messageCache
;
146 private MessageSendLogStore messageSendLogStore
;
148 private AccountDatabase accountDatabase
;
150 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
151 this.fileChannel
= fileChannel
;
155 public static SignalAccount
load(
156 File dataPath
, String accountPath
, boolean waitForLock
, final TrustNewIdentity trustNewIdentity
157 ) throws IOException
{
158 logger
.trace("Opening account file");
159 final var fileName
= getFileName(dataPath
, accountPath
);
160 final var pair
= openFileChannel(fileName
, waitForLock
);
162 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
163 logger
.trace("Loading account file");
164 signalAccount
.load(dataPath
, accountPath
, trustNewIdentity
);
165 logger
.trace("Migrating legacy parts of account file");
166 signalAccount
.migrateLegacyConfigs();
168 return signalAccount
;
169 } catch (Throwable e
) {
170 pair
.second().close();
171 pair
.first().close();
176 public static SignalAccount
create(
180 ServiceEnvironment serviceEnvironment
,
181 IdentityKeyPair aciIdentityKey
,
182 IdentityKeyPair pniIdentityKey
,
184 ProfileKey profileKey
,
185 final TrustNewIdentity trustNewIdentity
186 ) throws IOException
{
187 IOUtils
.createPrivateDirectories(dataPath
);
188 var fileName
= getFileName(dataPath
, accountPath
);
189 if (!fileName
.exists()) {
190 IOUtils
.createPrivateFile(fileName
);
193 final var pair
= openFileChannel(fileName
, true);
194 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
196 signalAccount
.accountPath
= accountPath
;
197 signalAccount
.number
= number
;
198 signalAccount
.serviceEnvironment
= serviceEnvironment
;
199 signalAccount
.profileKey
= profileKey
;
201 signalAccount
.dataPath
= dataPath
;
202 signalAccount
.aciIdentityKeyPair
= aciIdentityKey
;
203 signalAccount
.pniIdentityKeyPair
= pniIdentityKey
;
204 signalAccount
.localRegistrationId
= registrationId
;
205 signalAccount
.trustNewIdentity
= trustNewIdentity
;
206 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
207 signalAccount
.getRecipientResolver(),
208 signalAccount
::saveGroupStore
);
209 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
210 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
212 signalAccount
.registered
= false;
214 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
215 signalAccount
.migrateLegacyConfigs();
216 signalAccount
.save();
218 return signalAccount
;
221 public static SignalAccount
createOrUpdateLinkedAccount(
225 ServiceEnvironment serviceEnvironment
,
229 String encryptedDeviceName
,
231 IdentityKeyPair aciIdentityKey
,
232 IdentityKeyPair pniIdentityKey
,
234 ProfileKey profileKey
,
235 final TrustNewIdentity trustNewIdentity
236 ) throws IOException
{
237 IOUtils
.createPrivateDirectories(dataPath
);
238 var fileName
= getFileName(dataPath
, accountPath
);
239 if (!fileName
.exists()) {
240 return createLinkedAccount(dataPath
,
256 final var signalAccount
= load(dataPath
, accountPath
, true, trustNewIdentity
);
257 signalAccount
.setProvisioningData(number
,
266 signalAccount
.getRecipientTrustedResolver()
267 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
268 signalAccount
.getSessionStore().archiveAllSessions();
269 signalAccount
.getSenderKeyStore().deleteAll();
270 signalAccount
.clearAllPreKeys();
271 return signalAccount
;
274 public void initDatabase() {
275 getAccountDatabase();
278 private void clearAllPreKeys() {
279 this.aciPreKeyIdOffset
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
280 this.aciNextSignedPreKeyId
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
281 this.pniPreKeyIdOffset
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
282 this.pniNextSignedPreKeyId
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
283 this.getAciPreKeyStore().removeAllPreKeys();
284 this.getAciSignedPreKeyStore().removeAllSignedPreKeys();
285 this.getPniPreKeyStore().removeAllPreKeys();
286 this.getPniSignedPreKeyStore().removeAllSignedPreKeys();
290 private static SignalAccount
createLinkedAccount(
294 ServiceEnvironment serviceEnvironment
,
298 String encryptedDeviceName
,
300 IdentityKeyPair aciIdentityKey
,
301 IdentityKeyPair pniIdentityKey
,
303 ProfileKey profileKey
,
304 final TrustNewIdentity trustNewIdentity
305 ) throws IOException
{
306 var fileName
= getFileName(dataPath
, accountPath
);
307 IOUtils
.createPrivateFile(fileName
);
309 final var pair
= openFileChannel(fileName
, true);
310 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
312 signalAccount
.setProvisioningData(number
,
322 signalAccount
.dataPath
= dataPath
;
323 signalAccount
.accountPath
= accountPath
;
324 signalAccount
.serviceEnvironment
= serviceEnvironment
;
325 signalAccount
.localRegistrationId
= registrationId
;
326 signalAccount
.trustNewIdentity
= trustNewIdentity
;
327 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
328 signalAccount
.getRecipientResolver(),
329 signalAccount
::saveGroupStore
);
330 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
331 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
333 signalAccount
.getRecipientTrustedResolver()
334 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
335 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
336 signalAccount
.migrateLegacyConfigs();
337 signalAccount
.clearAllPreKeys();
338 signalAccount
.save();
340 return signalAccount
;
343 private void setProvisioningData(
347 final String password
,
348 final String encryptedDeviceName
,
350 final IdentityKeyPair aciIdentity
,
351 final IdentityKeyPair pniIdentity
,
352 final ProfileKey profileKey
354 this.number
= number
;
357 this.password
= password
;
358 this.profileKey
= profileKey
;
359 this.encryptedDeviceName
= encryptedDeviceName
;
360 this.deviceId
= deviceId
;
361 this.aciIdentityKeyPair
= aciIdentity
;
362 this.pniIdentityKeyPair
= pniIdentity
;
363 this.registered
= true;
364 this.isMultiDevice
= true;
365 this.lastReceiveTimestamp
= 0;
366 this.pinMasterKey
= null;
367 this.storageManifestVersion
= -1;
368 this.storageKey
= null;
371 private void migrateLegacyConfigs() {
372 if (getPassword() == null) {
373 setPassword(KeyUtils
.createPassword());
376 if (getProfileKey() == null) {
377 // Old config file, creating new profile key
378 setProfileKey(KeyUtils
.createProfileKey());
380 // Ensure our profile key is stored in profile store
381 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
382 if (previousStorageVersion
< 3) {
383 for (final var group
: groupStore
.getGroups()) {
384 if (group
instanceof GroupInfoV2
&& group
.getDistributionId() == null) {
385 ((GroupInfoV2
) group
).setDistributionId(DistributionId
.create());
386 groupStore
.updateGroup(group
);
391 if (isMasterDevice() && getPniIdentityKeyPair() == null) {
392 setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
396 private void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
397 getSessionStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
398 getIdentityKeyStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
399 getMessageCache().mergeRecipients(recipientId
, toBeMergedRecipientId
);
400 getGroupStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
401 getSenderKeyStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
404 public void removeRecipient(final RecipientId recipientId
) {
405 getSessionStore().deleteAllSessions(recipientId
);
406 getIdentityKeyStore().deleteIdentity(recipientId
);
407 getMessageCache().deleteMessages(recipientId
);
408 getSenderKeyStore().deleteAll(recipientId
);
409 getRecipientStore().deleteRecipientData(recipientId
);
412 public static File
getFileName(File dataPath
, String account
) {
413 return new File(dataPath
, account
);
416 private static File
getUserPath(final File dataPath
, final String account
) {
417 final var path
= new File(dataPath
, account
+ ".d");
419 IOUtils
.createPrivateDirectories(path
);
420 } catch (IOException e
) {
421 throw new AssertionError("Failed to create user path", e
);
426 private static File
getMessageCachePath(File dataPath
, String account
) {
427 return new File(getUserPath(dataPath
, account
), "msg-cache");
430 private static File
getGroupCachePath(File dataPath
, String account
) {
431 return new File(getUserPath(dataPath
, account
), "group-cache");
434 private static File
getAciPreKeysPath(File dataPath
, String account
) {
435 return new File(getUserPath(dataPath
, account
), "pre-keys");
438 private static File
getAciSignedPreKeysPath(File dataPath
, String account
) {
439 return new File(getUserPath(dataPath
, account
), "signed-pre-keys");
442 private static File
getPniPreKeysPath(File dataPath
, String account
) {
443 return new File(getUserPath(dataPath
, account
), "pre-keys-pni");
446 private static File
getPniSignedPreKeysPath(File dataPath
, String account
) {
447 return new File(getUserPath(dataPath
, account
), "signed-pre-keys-pni");
450 private static File
getIdentitiesPath(File dataPath
, String account
) {
451 return new File(getUserPath(dataPath
, account
), "identities");
454 private static File
getSessionsPath(File dataPath
, String account
) {
455 return new File(getUserPath(dataPath
, account
), "sessions");
458 private static File
getSenderKeysPath(File dataPath
, String account
) {
459 return new File(getUserPath(dataPath
, account
), "sender-keys");
462 private static File
getSharedSenderKeysFile(File dataPath
, String account
) {
463 return new File(getUserPath(dataPath
, account
), "shared-sender-keys-store");
466 private static File
getRecipientsStoreFile(File dataPath
, String account
) {
467 return new File(getUserPath(dataPath
, account
), "recipients-store");
470 private static File
getDatabaseFile(File dataPath
, String account
) {
471 return new File(getUserPath(dataPath
, account
), "account.db");
474 public static boolean accountFileExists(File dataPath
, String account
) {
475 if (account
== null) {
478 var f
= getFileName(dataPath
, account
);
479 return !(!f
.exists() || f
.isDirectory());
483 File dataPath
, String accountPath
, final TrustNewIdentity trustNewIdentity
484 ) throws IOException
{
485 this.dataPath
= dataPath
;
486 this.accountPath
= accountPath
;
487 final JsonNode rootNode
;
488 synchronized (fileChannel
) {
489 fileChannel
.position(0);
490 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
493 if (rootNode
.hasNonNull("version")) {
494 var accountVersion
= rootNode
.get("version").asInt(1);
495 if (accountVersion
> CURRENT_STORAGE_VERSION
) {
496 throw new IOException("Config file was created by a more recent version!");
497 } else if (accountVersion
< MINIMUM_STORAGE_VERSION
) {
498 throw new IOException("Config file was created by a no longer supported older version!");
500 previousStorageVersion
= accountVersion
;
503 number
= Utils
.getNotNullNode(rootNode
, "username").asText();
504 if (rootNode
.hasNonNull("password")) {
505 password
= rootNode
.get("password").asText();
507 if (rootNode
.hasNonNull("serviceEnvironment")) {
508 serviceEnvironment
= ServiceEnvironment
.valueOf(rootNode
.get("serviceEnvironment").asText());
510 registered
= Utils
.getNotNullNode(rootNode
, "registered").asBoolean();
511 if (rootNode
.hasNonNull("uuid")) {
513 aci
= ACI
.parseOrThrow(rootNode
.get("uuid").asText());
514 } catch (IllegalArgumentException e
) {
515 throw new IOException("Config file contains an invalid aci/uuid, needs to be a valid UUID", e
);
518 if (rootNode
.hasNonNull("pni")) {
520 pni
= PNI
.parseOrThrow(rootNode
.get("pni").asText());
521 } catch (IllegalArgumentException e
) {
522 throw new IOException("Config file contains an invalid pni, needs to be a valid UUID", e
);
525 if (rootNode
.hasNonNull("deviceName")) {
526 encryptedDeviceName
= rootNode
.get("deviceName").asText();
528 if (rootNode
.hasNonNull("deviceId")) {
529 deviceId
= rootNode
.get("deviceId").asInt();
531 if (rootNode
.hasNonNull("isMultiDevice")) {
532 isMultiDevice
= rootNode
.get("isMultiDevice").asBoolean();
534 if (rootNode
.hasNonNull("lastReceiveTimestamp")) {
535 lastReceiveTimestamp
= rootNode
.get("lastReceiveTimestamp").asLong();
537 int registrationId
= 0;
538 if (rootNode
.hasNonNull("registrationId")) {
539 registrationId
= rootNode
.get("registrationId").asInt();
541 IdentityKeyPair aciIdentityKeyPair
= null;
542 if (rootNode
.hasNonNull("identityPrivateKey") && rootNode
.hasNonNull("identityKey")) {
543 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityKey").asText());
544 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityPrivateKey").asText());
545 aciIdentityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
547 if (rootNode
.hasNonNull("pniIdentityPrivateKey") && rootNode
.hasNonNull("pniIdentityKey")) {
548 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityKey").asText());
549 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityPrivateKey").asText());
550 pniIdentityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
553 if (rootNode
.hasNonNull("registrationLockPin")) {
554 registrationLockPin
= rootNode
.get("registrationLockPin").asText();
556 if (rootNode
.hasNonNull("pinMasterKey")) {
557 pinMasterKey
= new MasterKey(Base64
.getDecoder().decode(rootNode
.get("pinMasterKey").asText()));
559 if (rootNode
.hasNonNull("storageKey")) {
560 storageKey
= new StorageKey(Base64
.getDecoder().decode(rootNode
.get("storageKey").asText()));
562 if (rootNode
.hasNonNull("storageManifestVersion")) {
563 storageManifestVersion
= rootNode
.get("storageManifestVersion").asLong();
565 if (rootNode
.hasNonNull("preKeyIdOffset")) {
566 aciPreKeyIdOffset
= rootNode
.get("preKeyIdOffset").asInt(1);
568 aciPreKeyIdOffset
= 1;
570 if (rootNode
.hasNonNull("nextSignedPreKeyId")) {
571 aciNextSignedPreKeyId
= rootNode
.get("nextSignedPreKeyId").asInt(1);
573 aciNextSignedPreKeyId
= 1;
575 if (rootNode
.hasNonNull("pniPreKeyIdOffset")) {
576 pniPreKeyIdOffset
= rootNode
.get("pniPreKeyIdOffset").asInt(1);
578 pniPreKeyIdOffset
= 1;
580 if (rootNode
.hasNonNull("pniNextSignedPreKeyId")) {
581 pniNextSignedPreKeyId
= rootNode
.get("pniNextSignedPreKeyId").asInt(1);
583 pniNextSignedPreKeyId
= 1;
585 if (rootNode
.hasNonNull("profileKey")) {
587 profileKey
= new ProfileKey(Base64
.getDecoder().decode(rootNode
.get("profileKey").asText()));
588 } catch (InvalidInputException e
) {
589 throw new IOException(
590 "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
595 var migratedLegacyConfig
= false;
596 final var legacySignalProtocolStore
= rootNode
.hasNonNull("axolotlStore")
597 ? jsonProcessor
.convertValue(Utils
.getNotNullNode(rootNode
, "axolotlStore"),
598 LegacyJsonSignalProtocolStore
.class)
600 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
601 aciIdentityKeyPair
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentityKeyPair();
602 registrationId
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getLocalRegistrationId();
603 migratedLegacyConfig
= true;
606 this.aciIdentityKeyPair
= aciIdentityKeyPair
;
607 this.localRegistrationId
= registrationId
;
608 this.trustNewIdentity
= trustNewIdentity
;
610 migratedLegacyConfig
= loadLegacyStores(rootNode
, legacySignalProtocolStore
) || migratedLegacyConfig
;
612 if (rootNode
.hasNonNull("groupStore")) {
613 groupStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("groupStore"), GroupStore
.Storage
.class);
614 groupStore
= GroupStore
.fromStorage(groupStoreStorage
,
615 getGroupCachePath(dataPath
, accountPath
),
616 getRecipientResolver(),
617 this::saveGroupStore
);
619 groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
620 getRecipientResolver(),
621 this::saveGroupStore
);
624 if (rootNode
.hasNonNull("stickerStore")) {
625 stickerStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("stickerStore"), StickerStore
.Storage
.class);
626 stickerStore
= StickerStore
.fromStorage(stickerStoreStorage
, this::saveStickerStore
);
628 stickerStore
= new StickerStore(this::saveStickerStore
);
631 if (rootNode
.hasNonNull("configurationStore")) {
632 configurationStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("configurationStore"),
633 ConfigurationStore
.Storage
.class);
634 configurationStore
= ConfigurationStore
.fromStorage(configurationStoreStorage
,
635 this::saveConfigurationStore
);
637 configurationStore
= new ConfigurationStore(this::saveConfigurationStore
);
640 migratedLegacyConfig
= loadLegacyThreadStore(rootNode
) || migratedLegacyConfig
;
642 if (migratedLegacyConfig
) {
647 private boolean loadLegacyStores(
648 final JsonNode rootNode
, final LegacyJsonSignalProtocolStore legacySignalProtocolStore
650 var migrated
= false;
651 var legacyRecipientStoreNode
= rootNode
.get("recipientStore");
652 if (legacyRecipientStoreNode
!= null) {
653 logger
.debug("Migrating legacy recipient store.");
654 var legacyRecipientStore
= jsonProcessor
.convertValue(legacyRecipientStoreNode
, LegacyRecipientStore
.class);
655 if (legacyRecipientStore
!= null) {
656 getRecipientStore().resolveRecipientsTrusted(legacyRecipientStore
.getAddresses());
658 getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
662 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyPreKeyStore() != null) {
663 logger
.debug("Migrating legacy pre key store.");
664 for (var entry
: legacySignalProtocolStore
.getLegacyPreKeyStore().getPreKeys().entrySet()) {
666 getAciPreKeyStore().storePreKey(entry
.getKey(), new PreKeyRecord(entry
.getValue()));
667 } catch (InvalidMessageException e
) {
668 logger
.warn("Failed to migrate pre key, ignoring", e
);
674 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySignedPreKeyStore() != null) {
675 logger
.debug("Migrating legacy signed pre key store.");
676 for (var entry
: legacySignalProtocolStore
.getLegacySignedPreKeyStore().getSignedPreKeys().entrySet()) {
678 getAciSignedPreKeyStore().storeSignedPreKey(entry
.getKey(),
679 new SignedPreKeyRecord(entry
.getValue()));
680 } catch (InvalidMessageException e
) {
681 logger
.warn("Failed to migrate signed pre key, ignoring", e
);
687 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySessionStore() != null) {
688 logger
.debug("Migrating legacy session store.");
689 for (var session
: legacySignalProtocolStore
.getLegacySessionStore().getSessions()) {
691 getSessionStore().storeSession(new SignalProtocolAddress(session
.address
.getIdentifier(),
692 session
.deviceId
), new SessionRecord(session
.sessionRecord
));
693 } catch (Exception e
) {
694 logger
.warn("Failed to migrate session, ignoring", e
);
700 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
701 logger
.debug("Migrating legacy identity session store.");
702 for (var identity
: legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentities()) {
703 RecipientId recipientId
= getRecipientStore().resolveRecipientTrusted(identity
.getAddress());
704 getIdentityKeyStore().saveIdentity(recipientId
, identity
.getIdentityKey(), identity
.getDateAdded());
705 getIdentityKeyStore().setIdentityTrustLevel(recipientId
,
706 identity
.getIdentityKey(),
707 identity
.getTrustLevel());
712 if (rootNode
.hasNonNull("contactStore")) {
713 logger
.debug("Migrating legacy contact store.");
714 final var contactStoreNode
= rootNode
.get("contactStore");
715 final var contactStore
= jsonProcessor
.convertValue(contactStoreNode
, LegacyJsonContactsStore
.class);
716 for (var contact
: contactStore
.getContacts()) {
717 final var recipientId
= getRecipientStore().resolveRecipientTrusted(contact
.getAddress());
718 getContactStore().storeContact(recipientId
,
719 new Contact(contact
.name
,
722 contact
.messageExpirationTime
,
727 // Store profile keys only in profile store
728 var profileKeyString
= contact
.profileKey
;
729 if (profileKeyString
!= null) {
730 final ProfileKey profileKey
;
732 profileKey
= new ProfileKey(Base64
.getDecoder().decode(profileKeyString
));
733 getProfileStore().storeProfileKey(recipientId
, profileKey
);
734 } catch (InvalidInputException e
) {
735 logger
.warn("Failed to parse legacy contact profile key: {}", e
.getMessage());
742 if (rootNode
.hasNonNull("profileStore")) {
743 logger
.debug("Migrating legacy profile store.");
744 var profileStoreNode
= rootNode
.get("profileStore");
745 final var legacyProfileStore
= jsonProcessor
.convertValue(profileStoreNode
, LegacyProfileStore
.class);
746 for (var profileEntry
: legacyProfileStore
.getProfileEntries()) {
747 var recipientId
= getRecipientResolver().resolveRecipient(profileEntry
.getAddress());
748 getProfileStore().storeProfileKeyCredential(recipientId
, profileEntry
.getProfileKeyCredential());
749 getProfileStore().storeProfileKey(recipientId
, profileEntry
.getProfileKey());
750 final var profile
= profileEntry
.getProfile();
751 if (profile
!= null) {
752 final var capabilities
= new HashSet
<Profile
.Capability
>();
753 if (profile
.getCapabilities() != null) {
754 if (profile
.getCapabilities().gv1Migration
) {
755 capabilities
.add(Profile
.Capability
.gv1Migration
);
757 if (profile
.getCapabilities().storage
) {
758 capabilities
.add(Profile
.Capability
.storage
);
761 final var newProfile
= new Profile(profileEntry
.getLastUpdateTimestamp(),
762 profile
.getGivenName(),
763 profile
.getFamilyName(),
765 profile
.getAboutEmoji(),
768 profile
.isUnrestrictedUnidentifiedAccess()
769 ? Profile
.UnidentifiedAccessMode
.UNRESTRICTED
770 : profile
.getUnidentifiedAccess() != null
771 ? Profile
.UnidentifiedAccessMode
.ENABLED
772 : Profile
.UnidentifiedAccessMode
.DISABLED
,
774 getProfileStore().storeProfile(recipientId
, newProfile
);
782 private boolean loadLegacyThreadStore(final JsonNode rootNode
) {
783 var threadStoreNode
= rootNode
.get("threadStore");
784 if (threadStoreNode
!= null && !threadStoreNode
.isNull()) {
785 var threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
786 // Migrate thread info to group and contact store
787 for (var thread
: threadStore
.getThreads()) {
788 if (thread
.id
== null || thread
.id
.isEmpty()) {
792 if (UuidUtil
.isUuid(thread
.id
) || thread
.id
.startsWith("+")) {
793 final var recipientId
= getRecipientResolver().resolveRecipient(thread
.id
);
794 var contact
= getContactStore().getContact(recipientId
);
795 if (contact
!= null) {
796 getContactStore().storeContact(recipientId
,
797 Contact
.newBuilder(contact
)
798 .withMessageExpirationTime(thread
.messageExpirationTime
)
802 var groupInfo
= groupStore
.getGroup(GroupId
.fromBase64(thread
.id
));
803 if (groupInfo
instanceof GroupInfoV1
) {
804 ((GroupInfoV1
) groupInfo
).messageExpirationTime
= thread
.messageExpirationTime
;
805 groupStore
.updateGroup(groupInfo
);
808 } catch (Exception e
) {
809 logger
.warn("Failed to read legacy thread info: {}", e
.getMessage());
818 private void saveStickerStore(StickerStore
.Storage storage
) {
819 this.stickerStoreStorage
= storage
;
823 private void saveGroupStore(GroupStore
.Storage storage
) {
824 this.groupStoreStorage
= storage
;
828 private void saveConfigurationStore(ConfigurationStore
.Storage storage
) {
829 this.configurationStoreStorage
= storage
;
833 private void save() {
834 synchronized (fileChannel
) {
835 var rootNode
= jsonProcessor
.createObjectNode();
836 rootNode
.put("version", CURRENT_STORAGE_VERSION
)
837 .put("username", number
)
838 .put("serviceEnvironment", serviceEnvironment
== null ?
null : serviceEnvironment
.name())
839 .put("uuid", aci
== null ?
null : aci
.toString())
840 .put("pni", pni
== null ?
null : pni
.toString())
841 .put("deviceName", encryptedDeviceName
)
842 .put("deviceId", deviceId
)
843 .put("isMultiDevice", isMultiDevice
)
844 .put("lastReceiveTimestamp", lastReceiveTimestamp
)
845 .put("password", password
)
846 .put("registrationId", localRegistrationId
)
847 .put("identityPrivateKey",
848 Base64
.getEncoder().encodeToString(aciIdentityKeyPair
.getPrivateKey().serialize()))
850 Base64
.getEncoder().encodeToString(aciIdentityKeyPair
.getPublicKey().serialize()))
851 .put("pniIdentityPrivateKey",
852 pniIdentityKeyPair
== null
854 : Base64
.getEncoder()
855 .encodeToString(pniIdentityKeyPair
.getPrivateKey().serialize()))
856 .put("pniIdentityKey",
857 pniIdentityKeyPair
== null
859 : Base64
.getEncoder().encodeToString(pniIdentityKeyPair
.getPublicKey().serialize()))
860 .put("registrationLockPin", registrationLockPin
)
862 pinMasterKey
== null ?
null : Base64
.getEncoder().encodeToString(pinMasterKey
.serialize()))
864 storageKey
== null ?
null : Base64
.getEncoder().encodeToString(storageKey
.serialize()))
865 .put("storageManifestVersion", storageManifestVersion
== -1 ?
null : storageManifestVersion
)
866 .put("preKeyIdOffset", aciPreKeyIdOffset
)
867 .put("nextSignedPreKeyId", aciNextSignedPreKeyId
)
868 .put("pniPreKeyIdOffset", pniPreKeyIdOffset
)
869 .put("pniNextSignedPreKeyId", pniNextSignedPreKeyId
)
871 profileKey
== null ?
null : Base64
.getEncoder().encodeToString(profileKey
.serialize()))
872 .put("registered", registered
)
873 .putPOJO("groupStore", groupStoreStorage
)
874 .putPOJO("stickerStore", stickerStoreStorage
)
875 .putPOJO("configurationStore", configurationStoreStorage
);
877 try (var output
= new ByteArrayOutputStream()) {
878 // Write to memory first to prevent corrupting the file in case of serialization errors
879 jsonProcessor
.writeValue(output
, rootNode
);
880 var input
= new ByteArrayInputStream(output
.toByteArray());
881 fileChannel
.position(0);
882 input
.transferTo(Channels
.newOutputStream(fileChannel
));
883 fileChannel
.truncate(fileChannel
.position());
884 fileChannel
.force(false);
886 } catch (Exception e
) {
887 logger
.error("Error saving file: {}", e
.getMessage(), e
);
892 private static Pair
<FileChannel
, FileLock
> openFileChannel(File fileName
, boolean waitForLock
) throws IOException
{
893 var fileChannel
= new RandomAccessFile(fileName
, "rw").getChannel();
895 var lock
= fileChannel
.tryLock();
898 logger
.debug("Config file is in use by another instance.");
899 throw new IOException("Config file is in use by another instance.");
901 logger
.info("Config file is in use by another instance, waiting…");
902 lock
= fileChannel
.lock();
903 logger
.info("Config file lock acquired.");
905 final var result
= new Pair
<>(fileChannel
, lock
);
909 if (fileChannel
!= null) {
915 public void addPreKeys(ServiceIdType serviceIdType
, List
<PreKeyRecord
> records
) {
916 if (serviceIdType
.equals(ServiceIdType
.ACI
)) {
917 addAciPreKeys(records
);
919 addPniPreKeys(records
);
923 public void addAciPreKeys(List
<PreKeyRecord
> records
) {
924 for (var record : records
) {
925 if (aciPreKeyIdOffset
!= record.getId()) {
926 logger
.error("Invalid pre key id {}, expected {}", record.getId(), aciPreKeyIdOffset
);
927 throw new AssertionError("Invalid pre key id");
929 getAciPreKeyStore().storePreKey(record.getId(), record);
930 aciPreKeyIdOffset
= (aciPreKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
935 public void addPniPreKeys(List
<PreKeyRecord
> records
) {
936 for (var record : records
) {
937 if (pniPreKeyIdOffset
!= record.getId()) {
938 logger
.error("Invalid pre key id {}, expected {}", record.getId(), pniPreKeyIdOffset
);
939 throw new AssertionError("Invalid pre key id");
941 getPniPreKeyStore().storePreKey(record.getId(), record);
942 pniPreKeyIdOffset
= (pniPreKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
947 public void addSignedPreKey(ServiceIdType serviceIdType
, SignedPreKeyRecord
record) {
948 if (serviceIdType
.equals(ServiceIdType
.ACI
)) {
949 addAciSignedPreKey(record);
951 addPniSignedPreKey(record);
955 public void addAciSignedPreKey(SignedPreKeyRecord
record) {
956 if (aciNextSignedPreKeyId
!= record.getId()) {
957 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), aciNextSignedPreKeyId
);
958 throw new AssertionError("Invalid signed pre key id");
960 getAciSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
961 aciNextSignedPreKeyId
= (aciNextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
965 public void addPniSignedPreKey(SignedPreKeyRecord
record) {
966 if (pniNextSignedPreKeyId
!= record.getId()) {
967 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), pniNextSignedPreKeyId
);
968 throw new AssertionError("Invalid signed pre key id");
970 getPniSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
971 pniNextSignedPreKeyId
= (pniNextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
975 public SignalServiceDataStore
getSignalServiceDataStore() {
976 return new SignalServiceDataStore() {
978 public SignalServiceAccountDataStore
get(final ServiceId accountIdentifier
) {
979 if (accountIdentifier
.equals(aci
)) {
980 return getSignalServiceAccountDataStore();
981 } else if (accountIdentifier
.equals(pni
)) {
982 throw new AssertionError("PNI not to be used yet!");
984 throw new IllegalArgumentException("No matching store found for " + accountIdentifier
);
989 public SignalServiceAccountDataStore
aci() {
990 return getSignalServiceAccountDataStore();
994 public SignalServiceAccountDataStore
pni() {
995 throw new AssertionError("PNI not to be used yet!");
999 public boolean isMultiDevice() {
1000 return SignalAccount
.this.isMultiDevice();
1005 public SignalServiceAccountDataStore
getSignalServiceAccountDataStore() {
1006 return getOrCreate(() -> signalProtocolStore
,
1007 () -> signalProtocolStore
= new SignalProtocolStore(getAciPreKeyStore(),
1008 getAciSignedPreKeyStore(),
1010 getIdentityKeyStore(),
1011 getSenderKeyStore(),
1012 this::isMultiDevice
));
1015 private PreKeyStore
getAciPreKeyStore() {
1016 return getOrCreate(() -> aciPreKeyStore
,
1017 () -> aciPreKeyStore
= new PreKeyStore(getAciPreKeysPath(dataPath
, accountPath
)));
1020 private SignedPreKeyStore
getAciSignedPreKeyStore() {
1021 return getOrCreate(() -> aciSignedPreKeyStore
,
1022 () -> aciSignedPreKeyStore
= new SignedPreKeyStore(getAciSignedPreKeysPath(dataPath
, accountPath
)));
1025 private PreKeyStore
getPniPreKeyStore() {
1026 return getOrCreate(() -> pniPreKeyStore
,
1027 () -> pniPreKeyStore
= new PreKeyStore(getPniPreKeysPath(dataPath
, accountPath
)));
1030 private SignedPreKeyStore
getPniSignedPreKeyStore() {
1031 return getOrCreate(() -> pniSignedPreKeyStore
,
1032 () -> pniSignedPreKeyStore
= new SignedPreKeyStore(getPniSignedPreKeysPath(dataPath
, accountPath
)));
1035 public SessionStore
getSessionStore() {
1036 return getOrCreate(() -> sessionStore
,
1037 () -> sessionStore
= new SessionStore(getSessionsPath(dataPath
, accountPath
), getRecipientResolver()));
1040 public IdentityKeyStore
getIdentityKeyStore() {
1041 return getOrCreate(() -> identityKeyStore
,
1042 () -> identityKeyStore
= new IdentityKeyStore(getIdentitiesPath(dataPath
, accountPath
),
1043 getRecipientResolver(),
1045 localRegistrationId
,
1049 public GroupStore
getGroupStore() {
1053 public ContactsStore
getContactStore() {
1054 return getRecipientStore();
1057 public RecipientResolver
getRecipientResolver() {
1058 return getRecipientStore();
1061 public RecipientTrustedResolver
getRecipientTrustedResolver() {
1062 return getRecipientStore();
1065 public RecipientAddressResolver
getRecipientAddressResolver() {
1066 return getRecipientStore()::resolveRecipientAddress
;
1069 public RecipientStore
getRecipientStore() {
1070 return getOrCreate(() -> recipientStore
,
1071 () -> recipientStore
= RecipientStore
.load(getRecipientsStoreFile(dataPath
, accountPath
),
1072 this::mergeRecipients
,
1073 this::getSelfRecipientAddress
));
1076 public ProfileStore
getProfileStore() {
1077 return getRecipientStore();
1080 public StickerStore
getStickerStore() {
1081 return stickerStore
;
1084 public SenderKeyStore
getSenderKeyStore() {
1085 return getOrCreate(() -> senderKeyStore
,
1086 () -> senderKeyStore
= new SenderKeyStore(getSharedSenderKeysFile(dataPath
, accountPath
),
1087 getSenderKeysPath(dataPath
, accountPath
),
1088 getRecipientAddressResolver(),
1089 getRecipientResolver()));
1092 public ConfigurationStore
getConfigurationStore() {
1093 return configurationStore
;
1096 public MessageCache
getMessageCache() {
1097 return getOrCreate(() -> messageCache
,
1098 () -> messageCache
= new MessageCache(getMessageCachePath(dataPath
, accountPath
)));
1101 public AccountDatabase
getAccountDatabase() {
1102 return getOrCreate(() -> accountDatabase
, () -> {
1104 accountDatabase
= AccountDatabase
.init(getDatabaseFile(dataPath
, accountPath
));
1105 } catch (SQLException e
) {
1106 throw new RuntimeException(e
);
1111 public MessageSendLogStore
getMessageSendLogStore() {
1112 return getOrCreate(() -> messageSendLogStore
,
1113 () -> messageSendLogStore
= new MessageSendLogStore(getRecipientResolver(), getAccountDatabase()));
1116 public CredentialsProvider
getCredentialsProvider() {
1117 return new CredentialsProvider() {
1119 public ACI
getAci() {
1124 public PNI
getPni() {
1129 public String
getE164() {
1134 public String
getPassword() {
1139 public int getDeviceId() {
1145 public String
getNumber() {
1149 public void setNumber(final String number
) {
1150 this.number
= number
;
1154 public ServiceEnvironment
getServiceEnvironment() {
1155 return serviceEnvironment
;
1158 public void setServiceEnvironment(final ServiceEnvironment serviceEnvironment
) {
1159 this.serviceEnvironment
= serviceEnvironment
;
1163 public ACI
getAci() {
1167 public void setAci(final ACI aci
) {
1172 public PNI
getPni() {
1176 public void setPni(final PNI pni
) {
1181 public SignalServiceAddress
getSelfAddress() {
1182 return new SignalServiceAddress(aci
, number
);
1185 public RecipientAddress
getSelfRecipientAddress() {
1186 return new RecipientAddress(aci
== null ?
null : aci
.uuid(), number
);
1189 public RecipientId
getSelfRecipientId() {
1190 return getRecipientResolver().resolveRecipient(getSelfRecipientAddress());
1193 public byte[] getEncryptedDeviceName() {
1194 return encryptedDeviceName
== null ?
null : Base64
.getDecoder().decode(encryptedDeviceName
);
1197 public void setEncryptedDeviceName(final String encryptedDeviceName
) {
1198 this.encryptedDeviceName
= encryptedDeviceName
;
1202 public int getDeviceId() {
1206 public boolean isMasterDevice() {
1207 return deviceId
== SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1210 public IdentityKeyPair
getIdentityKeyPair(ServiceIdType serviceIdType
) {
1211 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciIdentityKeyPair
: pniIdentityKeyPair
;
1214 public IdentityKeyPair
getAciIdentityKeyPair() {
1215 return aciIdentityKeyPair
;
1218 public IdentityKeyPair
getPniIdentityKeyPair() {
1219 return pniIdentityKeyPair
;
1222 public void setPniIdentityKeyPair(final IdentityKeyPair identityKeyPair
) {
1223 pniIdentityKeyPair
= identityKeyPair
;
1227 public int getLocalRegistrationId() {
1228 return localRegistrationId
;
1231 public String
getPassword() {
1235 private void setPassword(final String password
) {
1236 this.password
= password
;
1240 public void setRegistrationLockPin(final String registrationLockPin
, final MasterKey pinMasterKey
) {
1241 this.registrationLockPin
= registrationLockPin
;
1242 this.pinMasterKey
= pinMasterKey
;
1246 public MasterKey
getPinMasterKey() {
1247 return pinMasterKey
;
1250 public StorageKey
getStorageKey() {
1251 if (pinMasterKey
!= null) {
1252 return pinMasterKey
.deriveStorageServiceKey();
1257 public void setStorageKey(final StorageKey storageKey
) {
1258 if (storageKey
.equals(this.storageKey
)) {
1261 this.storageKey
= storageKey
;
1265 public long getStorageManifestVersion() {
1266 return this.storageManifestVersion
;
1269 public void setStorageManifestVersion(final long storageManifestVersion
) {
1270 if (storageManifestVersion
== this.storageManifestVersion
) {
1273 this.storageManifestVersion
= storageManifestVersion
;
1277 public ProfileKey
getProfileKey() {
1281 public void setProfileKey(final ProfileKey profileKey
) {
1282 if (profileKey
.equals(this.profileKey
)) {
1285 this.profileKey
= profileKey
;
1287 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
1290 public byte[] getSelfUnidentifiedAccessKey() {
1291 return UnidentifiedAccess
.deriveAccessKeyFrom(getProfileKey());
1294 public int getPreKeyIdOffset(ServiceIdType serviceIdType
) {
1295 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciPreKeyIdOffset
: pniPreKeyIdOffset
;
1298 public int getNextSignedPreKeyId(ServiceIdType serviceIdType
) {
1299 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciNextSignedPreKeyId
: pniNextSignedPreKeyId
;
1302 public boolean isRegistered() {
1306 public void setRegistered(final boolean registered
) {
1307 this.registered
= registered
;
1311 public boolean isMultiDevice() {
1312 return isMultiDevice
;
1315 public void setMultiDevice(final boolean multiDevice
) {
1316 if (isMultiDevice
== multiDevice
) {
1319 isMultiDevice
= multiDevice
;
1323 public long getLastReceiveTimestamp() {
1324 return lastReceiveTimestamp
;
1327 public void setLastReceiveTimestamp(final long lastReceiveTimestamp
) {
1328 this.lastReceiveTimestamp
= lastReceiveTimestamp
;
1332 public boolean isUnrestrictedUnidentifiedAccess() {
1333 final var profile
= getProfileStore().getProfile(getSelfRecipientId());
1334 return profile
!= null && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
;
1337 public boolean isDiscoverableByPhoneNumber() {
1338 return configurationStore
.getPhoneNumberUnlisted() == null || !configurationStore
.getPhoneNumberUnlisted();
1341 public void finishRegistration(final ACI aci
, final PNI pni
, final MasterKey masterKey
, final String pin
) {
1342 this.pinMasterKey
= masterKey
;
1343 this.storageManifestVersion
= -1;
1344 this.storageKey
= null;
1345 this.encryptedDeviceName
= null;
1346 this.deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1347 this.isMultiDevice
= false;
1348 this.registered
= true;
1351 this.registrationLockPin
= pin
;
1352 this.lastReceiveTimestamp
= 0;
1356 getSessionStore().archiveAllSessions();
1357 getSenderKeyStore().deleteAll();
1358 final var recipientId
= getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
1359 final var publicKey
= getAciIdentityKeyPair().getPublicKey();
1360 getIdentityKeyStore().saveIdentity(recipientId
, publicKey
, new Date());
1361 getIdentityKeyStore().setIdentityTrustLevel(recipientId
, publicKey
, TrustLevel
.TRUSTED_VERIFIED
);
1364 public void deleteAccountData() throws IOException
{
1366 try (final var files
= Files
.walk(getUserPath(dataPath
, accountPath
).toPath())
1367 .sorted(Comparator
.reverseOrder())) {
1368 for (final var file
= files
.iterator(); file
.hasNext(); ) {
1369 Files
.delete(file
.next());
1372 Files
.delete(getFileName(dataPath
, accountPath
).toPath());
1376 public void close() {
1377 synchronized (fileChannel
) {
1378 if (accountDatabase
!= null) {
1380 accountDatabase
.close();
1381 } catch (SQLException e
) {
1382 logger
.warn("Failed to close account database: {}", e
.getMessage(), e
);
1385 if (messageSendLogStore
!= null) {
1386 messageSendLogStore
.close();
1391 } catch (ClosedChannelException ignored
) {
1393 fileChannel
.close();
1394 } catch (IOException e
) {
1395 logger
.warn("Failed to close account: {}", e
.getMessage(), e
);
1400 private <T
> T
getOrCreate(Supplier
<T
> supplier
, Callable creator
) {
1401 var value
= supplier
.get();
1402 if (value
!= null) {
1406 synchronized (LOCK
) {
1407 value
= supplier
.get();
1408 if (value
!= null) {
1412 return supplier
.get();
1416 private interface Callable
{