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
.SignalStorageManifest
;
63 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
64 import org
.whispersystems
.signalservice
.api
.util
.CredentialsProvider
;
65 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
67 import java
.io
.ByteArrayInputStream
;
68 import java
.io
.ByteArrayOutputStream
;
69 import java
.io
.Closeable
;
71 import java
.io
.FileInputStream
;
72 import java
.io
.FileOutputStream
;
73 import java
.io
.IOException
;
74 import java
.io
.RandomAccessFile
;
75 import java
.nio
.channels
.Channels
;
76 import java
.nio
.channels
.ClosedChannelException
;
77 import java
.nio
.channels
.FileChannel
;
78 import java
.nio
.channels
.FileLock
;
79 import java
.nio
.file
.Files
;
80 import java
.security
.SecureRandom
;
81 import java
.sql
.SQLException
;
82 import java
.util
.Base64
;
83 import java
.util
.Comparator
;
84 import java
.util
.Date
;
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 SenderKeyStore senderKeyStore
;
141 private GroupStore groupStore
;
142 private GroupStore
.Storage groupStoreStorage
;
143 private RecipientStore recipientStore
;
144 private StickerStore stickerStore
;
145 private StickerStore
.Storage stickerStoreStorage
;
146 private ConfigurationStore configurationStore
;
147 private ConfigurationStore
.Storage configurationStoreStorage
;
149 private MessageCache messageCache
;
150 private MessageSendLogStore messageSendLogStore
;
152 private AccountDatabase accountDatabase
;
154 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
155 this.fileChannel
= fileChannel
;
159 public static SignalAccount
load(
160 File dataPath
, String accountPath
, boolean waitForLock
, final TrustNewIdentity trustNewIdentity
161 ) throws IOException
{
162 logger
.trace("Opening account file");
163 final var fileName
= getFileName(dataPath
, accountPath
);
164 final var pair
= openFileChannel(fileName
, waitForLock
);
166 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
167 logger
.trace("Loading account file");
168 signalAccount
.load(dataPath
, accountPath
, trustNewIdentity
);
169 logger
.trace("Migrating legacy parts of account file");
170 signalAccount
.migrateLegacyConfigs();
172 return signalAccount
;
173 } catch (Throwable e
) {
174 pair
.second().close();
175 pair
.first().close();
180 public static SignalAccount
create(
184 ServiceEnvironment serviceEnvironment
,
185 IdentityKeyPair aciIdentityKey
,
186 IdentityKeyPair pniIdentityKey
,
188 ProfileKey profileKey
,
189 final TrustNewIdentity trustNewIdentity
190 ) throws IOException
{
191 IOUtils
.createPrivateDirectories(dataPath
);
192 var fileName
= getFileName(dataPath
, accountPath
);
193 if (!fileName
.exists()) {
194 IOUtils
.createPrivateFile(fileName
);
197 final var pair
= openFileChannel(fileName
, true);
198 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
200 signalAccount
.accountPath
= accountPath
;
201 signalAccount
.number
= number
;
202 signalAccount
.serviceEnvironment
= serviceEnvironment
;
203 signalAccount
.profileKey
= profileKey
;
205 signalAccount
.dataPath
= dataPath
;
206 signalAccount
.aciIdentityKeyPair
= aciIdentityKey
;
207 signalAccount
.pniIdentityKeyPair
= pniIdentityKey
;
208 signalAccount
.localRegistrationId
= registrationId
;
209 signalAccount
.trustNewIdentity
= trustNewIdentity
;
210 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
211 signalAccount
.getRecipientResolver(),
212 signalAccount
::saveGroupStore
);
213 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
214 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
216 signalAccount
.registered
= false;
218 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
219 signalAccount
.migrateLegacyConfigs();
220 signalAccount
.save();
222 return signalAccount
;
225 public static SignalAccount
createOrUpdateLinkedAccount(
229 ServiceEnvironment serviceEnvironment
,
233 String encryptedDeviceName
,
235 IdentityKeyPair aciIdentityKey
,
236 IdentityKeyPair pniIdentityKey
,
238 ProfileKey profileKey
,
239 final TrustNewIdentity trustNewIdentity
240 ) throws IOException
{
241 IOUtils
.createPrivateDirectories(dataPath
);
242 var fileName
= getFileName(dataPath
, accountPath
);
243 if (!fileName
.exists()) {
244 return createLinkedAccount(dataPath
,
260 final var signalAccount
= load(dataPath
, accountPath
, true, trustNewIdentity
);
261 signalAccount
.setProvisioningData(number
,
270 signalAccount
.getRecipientTrustedResolver()
271 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
272 signalAccount
.getSessionStore().archiveAllSessions();
273 signalAccount
.getSenderKeyStore().deleteAll();
274 signalAccount
.clearAllPreKeys();
275 return signalAccount
;
278 public void initDatabase() {
279 getAccountDatabase();
282 private void clearAllPreKeys() {
283 this.aciPreKeyIdOffset
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
284 this.aciNextSignedPreKeyId
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
285 this.pniPreKeyIdOffset
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
286 this.pniNextSignedPreKeyId
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
287 this.getAciPreKeyStore().removeAllPreKeys();
288 this.getAciSignedPreKeyStore().removeAllSignedPreKeys();
289 this.getPniPreKeyStore().removeAllPreKeys();
290 this.getPniSignedPreKeyStore().removeAllSignedPreKeys();
294 private static SignalAccount
createLinkedAccount(
298 ServiceEnvironment serviceEnvironment
,
302 String encryptedDeviceName
,
304 IdentityKeyPair aciIdentityKey
,
305 IdentityKeyPair pniIdentityKey
,
307 ProfileKey profileKey
,
308 final TrustNewIdentity trustNewIdentity
309 ) throws IOException
{
310 var fileName
= getFileName(dataPath
, accountPath
);
311 IOUtils
.createPrivateFile(fileName
);
313 final var pair
= openFileChannel(fileName
, true);
314 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
316 signalAccount
.setProvisioningData(number
,
326 signalAccount
.dataPath
= dataPath
;
327 signalAccount
.accountPath
= accountPath
;
328 signalAccount
.serviceEnvironment
= serviceEnvironment
;
329 signalAccount
.localRegistrationId
= registrationId
;
330 signalAccount
.trustNewIdentity
= trustNewIdentity
;
331 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
332 signalAccount
.getRecipientResolver(),
333 signalAccount
::saveGroupStore
);
334 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
335 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
337 signalAccount
.getRecipientTrustedResolver()
338 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
339 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
340 signalAccount
.migrateLegacyConfigs();
341 signalAccount
.clearAllPreKeys();
342 signalAccount
.save();
344 return signalAccount
;
347 private void setProvisioningData(
351 final String password
,
352 final String encryptedDeviceName
,
354 final IdentityKeyPair aciIdentity
,
355 final IdentityKeyPair pniIdentity
,
356 final ProfileKey profileKey
358 this.number
= number
;
361 this.password
= password
;
362 this.profileKey
= profileKey
;
363 this.encryptedDeviceName
= encryptedDeviceName
;
364 this.deviceId
= deviceId
;
365 this.aciIdentityKeyPair
= aciIdentity
;
366 this.pniIdentityKeyPair
= pniIdentity
;
367 this.registered
= true;
368 this.isMultiDevice
= true;
369 this.lastReceiveTimestamp
= 0;
370 this.pinMasterKey
= null;
371 this.storageManifestVersion
= -1;
372 this.storageKey
= null;
375 private void migrateLegacyConfigs() {
376 if (getPassword() == null) {
377 setPassword(KeyUtils
.createPassword());
380 if (getProfileKey() == null) {
381 // Old config file, creating new profile key
382 setProfileKey(KeyUtils
.createProfileKey());
384 // Ensure our profile key is stored in profile store
385 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
386 if (previousStorageVersion
< 3) {
387 for (final var group
: groupStore
.getGroups()) {
388 if (group
instanceof GroupInfoV2
&& group
.getDistributionId() == null) {
389 ((GroupInfoV2
) group
).setDistributionId(DistributionId
.create());
390 groupStore
.updateGroup(group
);
395 if (isPrimaryDevice() && getPniIdentityKeyPair() == null) {
396 setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
400 private void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
401 getSessionStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
402 getIdentityKeyStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
403 getMessageCache().mergeRecipients(recipientId
, toBeMergedRecipientId
);
404 getGroupStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
405 getSenderKeyStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
408 public void removeRecipient(final RecipientId recipientId
) {
409 getSessionStore().deleteAllSessions(recipientId
);
410 getIdentityKeyStore().deleteIdentity(recipientId
);
411 getMessageCache().deleteMessages(recipientId
);
412 getSenderKeyStore().deleteAll(recipientId
);
413 getRecipientStore().deleteRecipientData(recipientId
);
416 public static File
getFileName(File dataPath
, String account
) {
417 return new File(dataPath
, account
);
420 private static File
getUserPath(final File dataPath
, final String account
) {
421 final var path
= new File(dataPath
, account
+ ".d");
423 IOUtils
.createPrivateDirectories(path
);
424 } catch (IOException e
) {
425 throw new AssertionError("Failed to create user path", e
);
430 private static File
getMessageCachePath(File dataPath
, String account
) {
431 return new File(getUserPath(dataPath
, account
), "msg-cache");
434 private static File
getGroupCachePath(File dataPath
, String account
) {
435 return new File(getUserPath(dataPath
, account
), "group-cache");
438 private static File
getAciPreKeysPath(File dataPath
, String account
) {
439 return new File(getUserPath(dataPath
, account
), "pre-keys");
442 private static File
getAciSignedPreKeysPath(File dataPath
, String account
) {
443 return new File(getUserPath(dataPath
, account
), "signed-pre-keys");
446 private static File
getPniPreKeysPath(File dataPath
, String account
) {
447 return new File(getUserPath(dataPath
, account
), "pre-keys-pni");
450 private static File
getPniSignedPreKeysPath(File dataPath
, String account
) {
451 return new File(getUserPath(dataPath
, account
), "signed-pre-keys-pni");
454 private static File
getIdentitiesPath(File dataPath
, String account
) {
455 return new File(getUserPath(dataPath
, account
), "identities");
458 private static File
getSessionsPath(File dataPath
, String account
) {
459 return new File(getUserPath(dataPath
, account
), "sessions");
462 private static File
getSenderKeysPath(File dataPath
, String account
) {
463 return new File(getUserPath(dataPath
, account
), "sender-keys");
466 private static File
getSharedSenderKeysFile(File dataPath
, String account
) {
467 return new File(getUserPath(dataPath
, account
), "shared-sender-keys-store");
470 private static File
getRecipientsStoreFile(File dataPath
, String account
) {
471 return new File(getUserPath(dataPath
, account
), "recipients-store");
474 private static File
getStorageManifestFile(File dataPath
, String account
) {
475 return new File(getUserPath(dataPath
, account
), "storage-manifest");
478 private static File
getDatabaseFile(File dataPath
, String account
) {
479 return new File(getUserPath(dataPath
, account
), "account.db");
482 public static boolean accountFileExists(File dataPath
, String account
) {
483 if (account
== null) {
486 var f
= getFileName(dataPath
, account
);
487 return !(!f
.exists() || f
.isDirectory());
491 File dataPath
, String accountPath
, final TrustNewIdentity trustNewIdentity
492 ) throws IOException
{
493 this.dataPath
= dataPath
;
494 this.accountPath
= accountPath
;
495 final JsonNode rootNode
;
496 synchronized (fileChannel
) {
497 fileChannel
.position(0);
498 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
501 if (rootNode
.hasNonNull("version")) {
502 var accountVersion
= rootNode
.get("version").asInt(1);
503 if (accountVersion
> CURRENT_STORAGE_VERSION
) {
504 throw new IOException("Config file was created by a more recent version!");
505 } else if (accountVersion
< MINIMUM_STORAGE_VERSION
) {
506 throw new IOException("Config file was created by a no longer supported older version!");
508 previousStorageVersion
= accountVersion
;
511 number
= Utils
.getNotNullNode(rootNode
, "username").asText();
512 if (rootNode
.hasNonNull("password")) {
513 password
= rootNode
.get("password").asText();
515 if (rootNode
.hasNonNull("serviceEnvironment")) {
516 serviceEnvironment
= ServiceEnvironment
.valueOf(rootNode
.get("serviceEnvironment").asText());
518 registered
= Utils
.getNotNullNode(rootNode
, "registered").asBoolean();
519 if (rootNode
.hasNonNull("uuid")) {
521 aci
= ACI
.parseOrThrow(rootNode
.get("uuid").asText());
522 } catch (IllegalArgumentException e
) {
523 throw new IOException("Config file contains an invalid aci/uuid, needs to be a valid UUID", e
);
526 if (rootNode
.hasNonNull("pni")) {
528 pni
= PNI
.parseOrThrow(rootNode
.get("pni").asText());
529 } catch (IllegalArgumentException e
) {
530 throw new IOException("Config file contains an invalid pni, needs to be a valid UUID", e
);
533 if (rootNode
.hasNonNull("deviceName")) {
534 encryptedDeviceName
= rootNode
.get("deviceName").asText();
536 if (rootNode
.hasNonNull("deviceId")) {
537 deviceId
= rootNode
.get("deviceId").asInt();
539 if (rootNode
.hasNonNull("isMultiDevice")) {
540 isMultiDevice
= rootNode
.get("isMultiDevice").asBoolean();
542 if (rootNode
.hasNonNull("lastReceiveTimestamp")) {
543 lastReceiveTimestamp
= rootNode
.get("lastReceiveTimestamp").asLong();
545 int registrationId
= 0;
546 if (rootNode
.hasNonNull("registrationId")) {
547 registrationId
= rootNode
.get("registrationId").asInt();
549 IdentityKeyPair aciIdentityKeyPair
= null;
550 if (rootNode
.hasNonNull("identityPrivateKey") && rootNode
.hasNonNull("identityKey")) {
551 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityKey").asText());
552 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityPrivateKey").asText());
553 aciIdentityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
555 if (rootNode
.hasNonNull("pniIdentityPrivateKey") && rootNode
.hasNonNull("pniIdentityKey")) {
556 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityKey").asText());
557 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityPrivateKey").asText());
558 pniIdentityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
561 if (rootNode
.hasNonNull("registrationLockPin")) {
562 registrationLockPin
= rootNode
.get("registrationLockPin").asText();
564 if (rootNode
.hasNonNull("pinMasterKey")) {
565 pinMasterKey
= new MasterKey(Base64
.getDecoder().decode(rootNode
.get("pinMasterKey").asText()));
567 if (rootNode
.hasNonNull("storageKey")) {
568 storageKey
= new StorageKey(Base64
.getDecoder().decode(rootNode
.get("storageKey").asText()));
570 if (rootNode
.hasNonNull("storageManifestVersion")) {
571 storageManifestVersion
= rootNode
.get("storageManifestVersion").asLong();
573 if (rootNode
.hasNonNull("preKeyIdOffset")) {
574 aciPreKeyIdOffset
= rootNode
.get("preKeyIdOffset").asInt(1);
576 aciPreKeyIdOffset
= 1;
578 if (rootNode
.hasNonNull("nextSignedPreKeyId")) {
579 aciNextSignedPreKeyId
= rootNode
.get("nextSignedPreKeyId").asInt(1);
581 aciNextSignedPreKeyId
= 1;
583 if (rootNode
.hasNonNull("pniPreKeyIdOffset")) {
584 pniPreKeyIdOffset
= rootNode
.get("pniPreKeyIdOffset").asInt(1);
586 pniPreKeyIdOffset
= 1;
588 if (rootNode
.hasNonNull("pniNextSignedPreKeyId")) {
589 pniNextSignedPreKeyId
= rootNode
.get("pniNextSignedPreKeyId").asInt(1);
591 pniNextSignedPreKeyId
= 1;
593 if (rootNode
.hasNonNull("profileKey")) {
595 profileKey
= new ProfileKey(Base64
.getDecoder().decode(rootNode
.get("profileKey").asText()));
596 } catch (InvalidInputException e
) {
597 throw new IOException(
598 "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
603 var migratedLegacyConfig
= false;
604 final var legacySignalProtocolStore
= rootNode
.hasNonNull("axolotlStore")
605 ? jsonProcessor
.convertValue(Utils
.getNotNullNode(rootNode
, "axolotlStore"),
606 LegacyJsonSignalProtocolStore
.class)
608 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
609 aciIdentityKeyPair
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentityKeyPair();
610 registrationId
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getLocalRegistrationId();
611 migratedLegacyConfig
= true;
614 this.aciIdentityKeyPair
= aciIdentityKeyPair
;
615 this.localRegistrationId
= registrationId
;
616 this.trustNewIdentity
= trustNewIdentity
;
618 migratedLegacyConfig
= loadLegacyStores(rootNode
, legacySignalProtocolStore
) || migratedLegacyConfig
;
620 if (rootNode
.hasNonNull("groupStore")) {
621 groupStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("groupStore"), GroupStore
.Storage
.class);
622 groupStore
= GroupStore
.fromStorage(groupStoreStorage
,
623 getGroupCachePath(dataPath
, accountPath
),
624 getRecipientResolver(),
625 this::saveGroupStore
);
627 groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
628 getRecipientResolver(),
629 this::saveGroupStore
);
632 if (rootNode
.hasNonNull("stickerStore")) {
633 stickerStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("stickerStore"), StickerStore
.Storage
.class);
634 stickerStore
= StickerStore
.fromStorage(stickerStoreStorage
, this::saveStickerStore
);
636 stickerStore
= new StickerStore(this::saveStickerStore
);
639 if (rootNode
.hasNonNull("configurationStore")) {
640 configurationStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("configurationStore"),
641 ConfigurationStore
.Storage
.class);
642 configurationStore
= ConfigurationStore
.fromStorage(configurationStoreStorage
,
643 this::saveConfigurationStore
);
645 configurationStore
= new ConfigurationStore(this::saveConfigurationStore
);
648 migratedLegacyConfig
= loadLegacyThreadStore(rootNode
) || migratedLegacyConfig
;
650 if (migratedLegacyConfig
) {
655 private boolean loadLegacyStores(
656 final JsonNode rootNode
, final LegacyJsonSignalProtocolStore legacySignalProtocolStore
658 var migrated
= false;
659 var legacyRecipientStoreNode
= rootNode
.get("recipientStore");
660 if (legacyRecipientStoreNode
!= null) {
661 logger
.debug("Migrating legacy recipient store.");
662 var legacyRecipientStore
= jsonProcessor
.convertValue(legacyRecipientStoreNode
, LegacyRecipientStore
.class);
663 if (legacyRecipientStore
!= null) {
664 getRecipientStore().resolveRecipientsTrusted(legacyRecipientStore
.getAddresses());
666 getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
670 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyPreKeyStore() != null) {
671 logger
.debug("Migrating legacy pre key store.");
672 for (var entry
: legacySignalProtocolStore
.getLegacyPreKeyStore().getPreKeys().entrySet()) {
674 getAciPreKeyStore().storePreKey(entry
.getKey(), new PreKeyRecord(entry
.getValue()));
675 } catch (InvalidMessageException e
) {
676 logger
.warn("Failed to migrate pre key, ignoring", e
);
682 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySignedPreKeyStore() != null) {
683 logger
.debug("Migrating legacy signed pre key store.");
684 for (var entry
: legacySignalProtocolStore
.getLegacySignedPreKeyStore().getSignedPreKeys().entrySet()) {
686 getAciSignedPreKeyStore().storeSignedPreKey(entry
.getKey(),
687 new SignedPreKeyRecord(entry
.getValue()));
688 } catch (InvalidMessageException e
) {
689 logger
.warn("Failed to migrate signed pre key, ignoring", e
);
695 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySessionStore() != null) {
696 logger
.debug("Migrating legacy session store.");
697 for (var session
: legacySignalProtocolStore
.getLegacySessionStore().getSessions()) {
699 getSessionStore().storeSession(new SignalProtocolAddress(session
.address
.getIdentifier(),
700 session
.deviceId
), new SessionRecord(session
.sessionRecord
));
701 } catch (Exception e
) {
702 logger
.warn("Failed to migrate session, ignoring", e
);
708 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
709 logger
.debug("Migrating legacy identity session store.");
710 for (var identity
: legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentities()) {
711 RecipientId recipientId
= getRecipientStore().resolveRecipientTrusted(identity
.getAddress());
712 getIdentityKeyStore().saveIdentity(recipientId
, identity
.getIdentityKey(), identity
.getDateAdded());
713 getIdentityKeyStore().setIdentityTrustLevel(recipientId
,
714 identity
.getIdentityKey(),
715 identity
.getTrustLevel());
720 if (rootNode
.hasNonNull("contactStore")) {
721 logger
.debug("Migrating legacy contact store.");
722 final var contactStoreNode
= rootNode
.get("contactStore");
723 final var contactStore
= jsonProcessor
.convertValue(contactStoreNode
, LegacyJsonContactsStore
.class);
724 for (var contact
: contactStore
.getContacts()) {
725 final var recipientId
= getRecipientStore().resolveRecipientTrusted(contact
.getAddress());
726 getContactStore().storeContact(recipientId
,
727 new Contact(contact
.name
,
730 contact
.messageExpirationTime
,
735 // Store profile keys only in profile store
736 var profileKeyString
= contact
.profileKey
;
737 if (profileKeyString
!= null) {
738 final ProfileKey profileKey
;
740 profileKey
= new ProfileKey(Base64
.getDecoder().decode(profileKeyString
));
741 getProfileStore().storeProfileKey(recipientId
, profileKey
);
742 } catch (InvalidInputException e
) {
743 logger
.warn("Failed to parse legacy contact profile key: {}", e
.getMessage());
750 if (rootNode
.hasNonNull("profileStore")) {
751 logger
.debug("Migrating legacy profile store.");
752 var profileStoreNode
= rootNode
.get("profileStore");
753 final var legacyProfileStore
= jsonProcessor
.convertValue(profileStoreNode
, LegacyProfileStore
.class);
754 for (var profileEntry
: legacyProfileStore
.getProfileEntries()) {
755 var recipientId
= getRecipientResolver().resolveRecipient(profileEntry
.getAddress());
756 getProfileStore().storeProfileKeyCredential(recipientId
, profileEntry
.getProfileKeyCredential());
757 getProfileStore().storeProfileKey(recipientId
, profileEntry
.getProfileKey());
758 final var profile
= profileEntry
.getProfile();
759 if (profile
!= null) {
760 final var capabilities
= new HashSet
<Profile
.Capability
>();
761 if (profile
.getCapabilities() != null) {
762 if (profile
.getCapabilities().gv1Migration
) {
763 capabilities
.add(Profile
.Capability
.gv1Migration
);
765 if (profile
.getCapabilities().storage
) {
766 capabilities
.add(Profile
.Capability
.storage
);
769 final var newProfile
= new Profile(profileEntry
.getLastUpdateTimestamp(),
770 profile
.getGivenName(),
771 profile
.getFamilyName(),
773 profile
.getAboutEmoji(),
776 profile
.isUnrestrictedUnidentifiedAccess()
777 ? Profile
.UnidentifiedAccessMode
.UNRESTRICTED
778 : profile
.getUnidentifiedAccess() != null
779 ? Profile
.UnidentifiedAccessMode
.ENABLED
780 : Profile
.UnidentifiedAccessMode
.DISABLED
,
782 getProfileStore().storeProfile(recipientId
, newProfile
);
790 private boolean loadLegacyThreadStore(final JsonNode rootNode
) {
791 var threadStoreNode
= rootNode
.get("threadStore");
792 if (threadStoreNode
!= null && !threadStoreNode
.isNull()) {
793 var threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
794 // Migrate thread info to group and contact store
795 for (var thread
: threadStore
.getThreads()) {
796 if (thread
.id
== null || thread
.id
.isEmpty()) {
800 if (UuidUtil
.isUuid(thread
.id
) || thread
.id
.startsWith("+")) {
801 final var recipientId
= getRecipientResolver().resolveRecipient(thread
.id
);
802 var contact
= getContactStore().getContact(recipientId
);
803 if (contact
!= null) {
804 getContactStore().storeContact(recipientId
,
805 Contact
.newBuilder(contact
)
806 .withMessageExpirationTime(thread
.messageExpirationTime
)
810 var groupInfo
= groupStore
.getGroup(GroupId
.fromBase64(thread
.id
));
811 if (groupInfo
instanceof GroupInfoV1
) {
812 ((GroupInfoV1
) groupInfo
).messageExpirationTime
= thread
.messageExpirationTime
;
813 groupStore
.updateGroup(groupInfo
);
816 } catch (Exception e
) {
817 logger
.warn("Failed to read legacy thread info: {}", e
.getMessage());
826 private void saveStickerStore(StickerStore
.Storage storage
) {
827 this.stickerStoreStorage
= storage
;
831 private void saveGroupStore(GroupStore
.Storage storage
) {
832 this.groupStoreStorage
= storage
;
836 private void saveConfigurationStore(ConfigurationStore
.Storage storage
) {
837 this.configurationStoreStorage
= storage
;
841 private void save() {
842 synchronized (fileChannel
) {
843 var rootNode
= jsonProcessor
.createObjectNode();
844 rootNode
.put("version", CURRENT_STORAGE_VERSION
)
845 .put("username", number
)
846 .put("serviceEnvironment", serviceEnvironment
== null ?
null : serviceEnvironment
.name())
847 .put("uuid", aci
== null ?
null : aci
.toString())
848 .put("pni", pni
== null ?
null : pni
.toString())
849 .put("deviceName", encryptedDeviceName
)
850 .put("deviceId", deviceId
)
851 .put("isMultiDevice", isMultiDevice
)
852 .put("lastReceiveTimestamp", lastReceiveTimestamp
)
853 .put("password", password
)
854 .put("registrationId", localRegistrationId
)
855 .put("identityPrivateKey",
856 Base64
.getEncoder().encodeToString(aciIdentityKeyPair
.getPrivateKey().serialize()))
858 Base64
.getEncoder().encodeToString(aciIdentityKeyPair
.getPublicKey().serialize()))
859 .put("pniIdentityPrivateKey",
860 pniIdentityKeyPair
== null
862 : Base64
.getEncoder()
863 .encodeToString(pniIdentityKeyPair
.getPrivateKey().serialize()))
864 .put("pniIdentityKey",
865 pniIdentityKeyPair
== null
867 : Base64
.getEncoder().encodeToString(pniIdentityKeyPair
.getPublicKey().serialize()))
868 .put("registrationLockPin", registrationLockPin
)
870 pinMasterKey
== null ?
null : Base64
.getEncoder().encodeToString(pinMasterKey
.serialize()))
872 storageKey
== null ?
null : Base64
.getEncoder().encodeToString(storageKey
.serialize()))
873 .put("storageManifestVersion", storageManifestVersion
== -1 ?
null : storageManifestVersion
)
874 .put("preKeyIdOffset", aciPreKeyIdOffset
)
875 .put("nextSignedPreKeyId", aciNextSignedPreKeyId
)
876 .put("pniPreKeyIdOffset", pniPreKeyIdOffset
)
877 .put("pniNextSignedPreKeyId", pniNextSignedPreKeyId
)
879 profileKey
== null ?
null : Base64
.getEncoder().encodeToString(profileKey
.serialize()))
880 .put("registered", registered
)
881 .putPOJO("groupStore", groupStoreStorage
)
882 .putPOJO("stickerStore", stickerStoreStorage
)
883 .putPOJO("configurationStore", configurationStoreStorage
);
885 try (var output
= new ByteArrayOutputStream()) {
886 // Write to memory first to prevent corrupting the file in case of serialization errors
887 jsonProcessor
.writeValue(output
, rootNode
);
888 var input
= new ByteArrayInputStream(output
.toByteArray());
889 fileChannel
.position(0);
890 input
.transferTo(Channels
.newOutputStream(fileChannel
));
891 fileChannel
.truncate(fileChannel
.position());
892 fileChannel
.force(false);
894 } catch (Exception e
) {
895 logger
.error("Error saving file: {}", e
.getMessage(), e
);
900 private static Pair
<FileChannel
, FileLock
> openFileChannel(File fileName
, boolean waitForLock
) throws IOException
{
901 var fileChannel
= new RandomAccessFile(fileName
, "rw").getChannel();
903 var lock
= fileChannel
.tryLock();
906 logger
.debug("Config file is in use by another instance.");
907 throw new IOException("Config file is in use by another instance.");
909 logger
.info("Config file is in use by another instance, waiting…");
910 lock
= fileChannel
.lock();
911 logger
.info("Config file lock acquired.");
913 final var result
= new Pair
<>(fileChannel
, lock
);
917 if (fileChannel
!= null) {
923 public void addPreKeys(ServiceIdType serviceIdType
, List
<PreKeyRecord
> records
) {
924 if (serviceIdType
.equals(ServiceIdType
.ACI
)) {
925 addAciPreKeys(records
);
927 addPniPreKeys(records
);
931 public void addAciPreKeys(List
<PreKeyRecord
> records
) {
932 for (var record : records
) {
933 if (aciPreKeyIdOffset
!= record.getId()) {
934 logger
.error("Invalid pre key id {}, expected {}", record.getId(), aciPreKeyIdOffset
);
935 throw new AssertionError("Invalid pre key id");
937 getAciPreKeyStore().storePreKey(record.getId(), record);
938 aciPreKeyIdOffset
= (aciPreKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
943 public void addPniPreKeys(List
<PreKeyRecord
> records
) {
944 for (var record : records
) {
945 if (pniPreKeyIdOffset
!= record.getId()) {
946 logger
.error("Invalid pre key id {}, expected {}", record.getId(), pniPreKeyIdOffset
);
947 throw new AssertionError("Invalid pre key id");
949 getPniPreKeyStore().storePreKey(record.getId(), record);
950 pniPreKeyIdOffset
= (pniPreKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
955 public void addSignedPreKey(ServiceIdType serviceIdType
, SignedPreKeyRecord
record) {
956 if (serviceIdType
.equals(ServiceIdType
.ACI
)) {
957 addAciSignedPreKey(record);
959 addPniSignedPreKey(record);
963 public void addAciSignedPreKey(SignedPreKeyRecord
record) {
964 if (aciNextSignedPreKeyId
!= record.getId()) {
965 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), aciNextSignedPreKeyId
);
966 throw new AssertionError("Invalid signed pre key id");
968 getAciSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
969 aciNextSignedPreKeyId
= (aciNextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
973 public void addPniSignedPreKey(SignedPreKeyRecord
record) {
974 if (pniNextSignedPreKeyId
!= record.getId()) {
975 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), pniNextSignedPreKeyId
);
976 throw new AssertionError("Invalid signed pre key id");
978 getPniSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
979 pniNextSignedPreKeyId
= (pniNextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
983 public SignalServiceDataStore
getSignalServiceDataStore() {
984 return new SignalServiceDataStore() {
986 public SignalServiceAccountDataStore
get(final ServiceId accountIdentifier
) {
987 if (accountIdentifier
.equals(aci
)) {
988 return getSignalServiceAccountDataStore();
989 } else if (accountIdentifier
.equals(pni
)) {
990 throw new AssertionError("PNI not to be used yet!");
992 throw new IllegalArgumentException("No matching store found for " + accountIdentifier
);
997 public SignalServiceAccountDataStore
aci() {
998 return getSignalServiceAccountDataStore();
1002 public SignalServiceAccountDataStore
pni() {
1003 throw new AssertionError("PNI not to be used yet!");
1007 public boolean isMultiDevice() {
1008 return SignalAccount
.this.isMultiDevice();
1013 public SignalServiceAccountDataStore
getSignalServiceAccountDataStore() {
1014 return getOrCreate(() -> signalProtocolStore
,
1015 () -> signalProtocolStore
= new SignalProtocolStore(getAciPreKeyStore(),
1016 getAciSignedPreKeyStore(),
1018 getIdentityKeyStore(),
1019 getSenderKeyStore(),
1020 this::isMultiDevice
));
1023 private PreKeyStore
getAciPreKeyStore() {
1024 return getOrCreate(() -> aciPreKeyStore
,
1025 () -> aciPreKeyStore
= new PreKeyStore(getAciPreKeysPath(dataPath
, accountPath
)));
1028 private SignedPreKeyStore
getAciSignedPreKeyStore() {
1029 return getOrCreate(() -> aciSignedPreKeyStore
,
1030 () -> aciSignedPreKeyStore
= new SignedPreKeyStore(getAciSignedPreKeysPath(dataPath
, accountPath
)));
1033 private PreKeyStore
getPniPreKeyStore() {
1034 return getOrCreate(() -> pniPreKeyStore
,
1035 () -> pniPreKeyStore
= new PreKeyStore(getPniPreKeysPath(dataPath
, accountPath
)));
1038 private SignedPreKeyStore
getPniSignedPreKeyStore() {
1039 return getOrCreate(() -> pniSignedPreKeyStore
,
1040 () -> pniSignedPreKeyStore
= new SignedPreKeyStore(getPniSignedPreKeysPath(dataPath
, accountPath
)));
1043 public SessionStore
getSessionStore() {
1044 return getOrCreate(() -> sessionStore
,
1045 () -> sessionStore
= new SessionStore(getSessionsPath(dataPath
, accountPath
), getRecipientResolver()));
1048 public IdentityKeyStore
getIdentityKeyStore() {
1049 return getOrCreate(() -> identityKeyStore
,
1050 () -> identityKeyStore
= new IdentityKeyStore(getIdentitiesPath(dataPath
, accountPath
),
1051 getRecipientResolver(),
1053 localRegistrationId
,
1057 public GroupStore
getGroupStore() {
1061 public ContactsStore
getContactStore() {
1062 return getRecipientStore();
1065 public RecipientResolver
getRecipientResolver() {
1066 return getRecipientStore();
1069 public RecipientTrustedResolver
getRecipientTrustedResolver() {
1070 return getRecipientStore();
1073 public RecipientAddressResolver
getRecipientAddressResolver() {
1074 return getRecipientStore()::resolveRecipientAddress
;
1077 public RecipientStore
getRecipientStore() {
1078 return getOrCreate(() -> recipientStore
,
1079 () -> recipientStore
= RecipientStore
.load(getRecipientsStoreFile(dataPath
, accountPath
),
1080 this::mergeRecipients
,
1081 this::getSelfRecipientAddress
));
1084 public ProfileStore
getProfileStore() {
1085 return getRecipientStore();
1088 public StickerStore
getStickerStore() {
1089 return stickerStore
;
1092 public SenderKeyStore
getSenderKeyStore() {
1093 return getOrCreate(() -> senderKeyStore
,
1094 () -> senderKeyStore
= new SenderKeyStore(getSharedSenderKeysFile(dataPath
, accountPath
),
1095 getSenderKeysPath(dataPath
, accountPath
),
1096 getRecipientAddressResolver(),
1097 getRecipientResolver()));
1100 public ConfigurationStore
getConfigurationStore() {
1101 return configurationStore
;
1104 public MessageCache
getMessageCache() {
1105 return getOrCreate(() -> messageCache
,
1106 () -> messageCache
= new MessageCache(getMessageCachePath(dataPath
, accountPath
)));
1109 public AccountDatabase
getAccountDatabase() {
1110 return getOrCreate(() -> accountDatabase
, () -> {
1112 accountDatabase
= AccountDatabase
.init(getDatabaseFile(dataPath
, accountPath
));
1113 } catch (SQLException e
) {
1114 throw new RuntimeException(e
);
1119 public MessageSendLogStore
getMessageSendLogStore() {
1120 return getOrCreate(() -> messageSendLogStore
,
1121 () -> messageSendLogStore
= new MessageSendLogStore(getRecipientResolver(), getAccountDatabase()));
1124 public CredentialsProvider
getCredentialsProvider() {
1125 return new CredentialsProvider() {
1127 public ACI
getAci() {
1132 public PNI
getPni() {
1137 public String
getE164() {
1142 public String
getPassword() {
1147 public int getDeviceId() {
1153 public String
getNumber() {
1157 public void setNumber(final String number
) {
1158 this.number
= number
;
1162 public ServiceEnvironment
getServiceEnvironment() {
1163 return serviceEnvironment
;
1166 public void setServiceEnvironment(final ServiceEnvironment serviceEnvironment
) {
1167 this.serviceEnvironment
= serviceEnvironment
;
1171 public ACI
getAci() {
1175 public void setAci(final ACI aci
) {
1180 public PNI
getPni() {
1184 public void setPni(final PNI pni
) {
1189 public SignalServiceAddress
getSelfAddress() {
1190 return new SignalServiceAddress(aci
, number
);
1193 public RecipientAddress
getSelfRecipientAddress() {
1194 return new RecipientAddress(aci
== null ?
null : aci
.uuid(), number
);
1197 public RecipientId
getSelfRecipientId() {
1198 return getRecipientResolver().resolveRecipient(getSelfRecipientAddress());
1201 public byte[] getEncryptedDeviceName() {
1202 return encryptedDeviceName
== null ?
null : Base64
.getDecoder().decode(encryptedDeviceName
);
1205 public void setEncryptedDeviceName(final String encryptedDeviceName
) {
1206 this.encryptedDeviceName
= encryptedDeviceName
;
1210 public int getDeviceId() {
1214 public boolean isPrimaryDevice() {
1215 return deviceId
== SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1218 public IdentityKeyPair
getIdentityKeyPair(ServiceIdType serviceIdType
) {
1219 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciIdentityKeyPair
: pniIdentityKeyPair
;
1222 public IdentityKeyPair
getAciIdentityKeyPair() {
1223 return aciIdentityKeyPair
;
1226 public IdentityKeyPair
getPniIdentityKeyPair() {
1227 return pniIdentityKeyPair
;
1230 public void setPniIdentityKeyPair(final IdentityKeyPair identityKeyPair
) {
1231 pniIdentityKeyPair
= identityKeyPair
;
1235 public int getLocalRegistrationId() {
1236 return localRegistrationId
;
1239 public String
getPassword() {
1243 private void setPassword(final String password
) {
1244 this.password
= password
;
1248 public void setRegistrationLockPin(final String registrationLockPin
, final MasterKey pinMasterKey
) {
1249 this.registrationLockPin
= registrationLockPin
;
1250 this.pinMasterKey
= pinMasterKey
;
1254 public MasterKey
getPinMasterKey() {
1255 return pinMasterKey
;
1258 public StorageKey
getStorageKey() {
1259 if (pinMasterKey
!= null) {
1260 return pinMasterKey
.deriveStorageServiceKey();
1265 public void setStorageKey(final StorageKey storageKey
) {
1266 if (storageKey
.equals(this.storageKey
)) {
1269 this.storageKey
= storageKey
;
1273 public long getStorageManifestVersion() {
1274 return this.storageManifestVersion
;
1277 public void setStorageManifestVersion(final long storageManifestVersion
) {
1278 if (storageManifestVersion
== this.storageManifestVersion
) {
1281 this.storageManifestVersion
= storageManifestVersion
;
1285 public Optional
<SignalStorageManifest
> getStorageManifest() {
1286 final var storageManifestFile
= getStorageManifestFile(dataPath
, accountPath
);
1287 if (!storageManifestFile
.exists()) {
1288 return Optional
.empty();
1290 try (var inputStream
= new FileInputStream(storageManifestFile
)) {
1291 return Optional
.of(SignalStorageManifest
.deserialize(inputStream
.readAllBytes()));
1292 } catch (IOException e
) {
1293 logger
.warn("Failed to read local storage manifest.", e
);
1294 return Optional
.empty();
1298 public void setStorageManifest(SignalStorageManifest manifest
) {
1299 final var manifestBytes
= manifest
.serialize();
1301 final var storageManifestFile
= getStorageManifestFile(dataPath
, accountPath
);
1302 try (var outputStream
= new FileOutputStream(storageManifestFile
)) {
1303 outputStream
.write(manifestBytes
);
1304 } catch (IOException e
) {
1305 logger
.error("Failed to store local storage manifest.", e
);
1309 public ProfileKey
getProfileKey() {
1313 public void setProfileKey(final ProfileKey profileKey
) {
1314 if (profileKey
.equals(this.profileKey
)) {
1317 this.profileKey
= profileKey
;
1319 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
1322 public byte[] getSelfUnidentifiedAccessKey() {
1323 return UnidentifiedAccess
.deriveAccessKeyFrom(getProfileKey());
1326 public int getPreKeyIdOffset(ServiceIdType serviceIdType
) {
1327 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciPreKeyIdOffset
: pniPreKeyIdOffset
;
1330 public int getNextSignedPreKeyId(ServiceIdType serviceIdType
) {
1331 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciNextSignedPreKeyId
: pniNextSignedPreKeyId
;
1334 public boolean isRegistered() {
1338 public void setRegistered(final boolean registered
) {
1339 this.registered
= registered
;
1343 public boolean isMultiDevice() {
1344 return isMultiDevice
;
1347 public void setMultiDevice(final boolean multiDevice
) {
1348 if (isMultiDevice
== multiDevice
) {
1351 isMultiDevice
= multiDevice
;
1355 public long getLastReceiveTimestamp() {
1356 return lastReceiveTimestamp
;
1359 public void setLastReceiveTimestamp(final long lastReceiveTimestamp
) {
1360 this.lastReceiveTimestamp
= lastReceiveTimestamp
;
1364 public boolean isUnrestrictedUnidentifiedAccess() {
1365 final var profile
= getProfileStore().getProfile(getSelfRecipientId());
1366 return profile
!= null && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
;
1369 public boolean isDiscoverableByPhoneNumber() {
1370 return configurationStore
.getPhoneNumberUnlisted() == null || !configurationStore
.getPhoneNumberUnlisted();
1373 public void finishRegistration(final ACI aci
, final PNI pni
, final MasterKey masterKey
, final String pin
) {
1374 this.pinMasterKey
= masterKey
;
1375 this.storageManifestVersion
= -1;
1376 this.storageKey
= null;
1377 this.encryptedDeviceName
= null;
1378 this.deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1379 this.isMultiDevice
= false;
1380 this.registered
= true;
1383 this.registrationLockPin
= pin
;
1384 this.lastReceiveTimestamp
= 0;
1388 getSessionStore().archiveAllSessions();
1389 getSenderKeyStore().deleteAll();
1390 final var recipientId
= getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
1391 final var publicKey
= getAciIdentityKeyPair().getPublicKey();
1392 getIdentityKeyStore().saveIdentity(recipientId
, publicKey
, new Date());
1393 getIdentityKeyStore().setIdentityTrustLevel(recipientId
, publicKey
, TrustLevel
.TRUSTED_VERIFIED
);
1396 public void deleteAccountData() throws IOException
{
1398 try (final var files
= Files
.walk(getUserPath(dataPath
, accountPath
).toPath())
1399 .sorted(Comparator
.reverseOrder())) {
1400 for (final var file
= files
.iterator(); file
.hasNext(); ) {
1401 Files
.delete(file
.next());
1404 Files
.delete(getFileName(dataPath
, accountPath
).toPath());
1408 public void close() {
1409 synchronized (fileChannel
) {
1410 if (accountDatabase
!= null) {
1412 accountDatabase
.close();
1413 } catch (SQLException e
) {
1414 logger
.warn("Failed to close account database: {}", e
.getMessage(), e
);
1417 if (messageSendLogStore
!= null) {
1418 messageSendLogStore
.close();
1423 } catch (ClosedChannelException ignored
) {
1425 fileChannel
.close();
1426 } catch (IOException e
) {
1427 logger
.warn("Failed to close account: {}", e
.getMessage(), e
);
1432 private <T
> T
getOrCreate(Supplier
<T
> supplier
, Callable creator
) {
1433 var value
= supplier
.get();
1434 if (value
!= null) {
1438 synchronized (LOCK
) {
1439 value
= supplier
.get();
1440 if (value
!= null) {
1444 return supplier
.get();
1448 private interface Callable
{