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
.TrustLevel
;
7 import org
.asamk
.signal
.manager
.api
.Pair
;
8 import org
.asamk
.signal
.manager
.groups
.GroupId
;
9 import org
.asamk
.signal
.manager
.storage
.configuration
.ConfigurationStore
;
10 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactsStore
;
11 import org
.asamk
.signal
.manager
.storage
.contacts
.LegacyJsonContactsStore
;
12 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
13 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
14 import org
.asamk
.signal
.manager
.storage
.groups
.GroupStore
;
15 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityKeyStore
;
16 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
17 import org
.asamk
.signal
.manager
.storage
.messageCache
.MessageCache
;
18 import org
.asamk
.signal
.manager
.storage
.prekeys
.PreKeyStore
;
19 import org
.asamk
.signal
.manager
.storage
.prekeys
.SignedPreKeyStore
;
20 import org
.asamk
.signal
.manager
.storage
.profiles
.LegacyProfileStore
;
21 import org
.asamk
.signal
.manager
.storage
.profiles
.ProfileStore
;
22 import org
.asamk
.signal
.manager
.storage
.protocol
.LegacyJsonSignalProtocolStore
;
23 import org
.asamk
.signal
.manager
.storage
.protocol
.SignalProtocolStore
;
24 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
25 import org
.asamk
.signal
.manager
.storage
.recipients
.LegacyRecipientStore
;
26 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
27 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
28 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
29 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientStore
;
30 import org
.asamk
.signal
.manager
.storage
.sendLog
.MessageSendLogStore
;
31 import org
.asamk
.signal
.manager
.storage
.senderKeys
.SenderKeyStore
;
32 import org
.asamk
.signal
.manager
.storage
.sessions
.SessionStore
;
33 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerStore
;
34 import org
.asamk
.signal
.manager
.storage
.threads
.LegacyJsonThreadStore
;
35 import org
.asamk
.signal
.manager
.util
.IOUtils
;
36 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
37 import org
.signal
.zkgroup
.InvalidInputException
;
38 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
39 import org
.slf4j
.Logger
;
40 import org
.slf4j
.LoggerFactory
;
41 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
42 import org
.whispersystems
.libsignal
.SignalProtocolAddress
;
43 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
44 import org
.whispersystems
.libsignal
.state
.SessionRecord
;
45 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
46 import org
.whispersystems
.libsignal
.util
.Medium
;
47 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
48 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
49 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
50 import org
.whispersystems
.signalservice
.api
.push
.DistributionId
;
51 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
52 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
53 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
55 import java
.io
.ByteArrayInputStream
;
56 import java
.io
.ByteArrayOutputStream
;
57 import java
.io
.Closeable
;
59 import java
.io
.IOException
;
60 import java
.io
.RandomAccessFile
;
61 import java
.nio
.channels
.Channels
;
62 import java
.nio
.channels
.ClosedChannelException
;
63 import java
.nio
.channels
.FileChannel
;
64 import java
.nio
.channels
.FileLock
;
65 import java
.security
.SecureRandom
;
66 import java
.sql
.SQLException
;
67 import java
.util
.Base64
;
68 import java
.util
.Date
;
69 import java
.util
.HashSet
;
70 import java
.util
.List
;
71 import java
.util
.function
.Supplier
;
73 public class SignalAccount
implements Closeable
{
75 private final static Logger logger
= LoggerFactory
.getLogger(SignalAccount
.class);
77 private static final int MINIMUM_STORAGE_VERSION
= 1;
78 private static final int CURRENT_STORAGE_VERSION
= 3;
80 private final Object LOCK
= new Object();
82 private final ObjectMapper jsonProcessor
= Utils
.createStorageObjectMapper();
84 private final FileChannel fileChannel
;
85 private final FileLock lock
;
87 private int previousStorageVersion
;
89 private File dataPath
;
90 private String account
;
92 private String encryptedDeviceName
;
93 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
94 private boolean isMultiDevice
= false;
95 private String password
;
96 private String registrationLockPin
;
97 private MasterKey pinMasterKey
;
98 private StorageKey storageKey
;
99 private long storageManifestVersion
= -1;
100 private ProfileKey profileKey
;
101 private int preKeyIdOffset
;
102 private int nextSignedPreKeyId
;
103 private IdentityKeyPair identityKeyPair
;
104 private int localRegistrationId
;
105 private TrustNewIdentity trustNewIdentity
;
106 private long lastReceiveTimestamp
= 0;
108 private boolean registered
= false;
110 private SignalProtocolStore signalProtocolStore
;
111 private PreKeyStore preKeyStore
;
112 private SignedPreKeyStore signedPreKeyStore
;
113 private SessionStore sessionStore
;
114 private IdentityKeyStore identityKeyStore
;
115 private SenderKeyStore senderKeyStore
;
116 private GroupStore groupStore
;
117 private GroupStore
.Storage groupStoreStorage
;
118 private RecipientStore recipientStore
;
119 private StickerStore stickerStore
;
120 private StickerStore
.Storage stickerStoreStorage
;
121 private ConfigurationStore configurationStore
;
122 private ConfigurationStore
.Storage configurationStoreStorage
;
124 private MessageCache messageCache
;
125 private MessageSendLogStore messageSendLogStore
;
127 private Database database
;
129 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
130 this.fileChannel
= fileChannel
;
134 public static SignalAccount
load(
135 File dataPath
, String account
, boolean waitForLock
, final TrustNewIdentity trustNewIdentity
136 ) throws IOException
{
137 logger
.trace("Opening account file");
138 final var fileName
= getFileName(dataPath
, account
);
139 final var pair
= openFileChannel(fileName
, waitForLock
);
141 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
142 logger
.trace("Loading account file");
143 signalAccount
.load(dataPath
, trustNewIdentity
);
144 logger
.trace("Migrating legacy parts of account file");
145 signalAccount
.migrateLegacyConfigs();
147 if (!account
.equals(signalAccount
.getAccount())) {
148 throw new IOException("Number in account file doesn't match expected number: "
149 + signalAccount
.getAccount());
152 return signalAccount
;
153 } catch (Throwable e
) {
154 pair
.second().close();
155 pair
.first().close();
160 public static SignalAccount
create(
163 IdentityKeyPair identityKey
,
165 ProfileKey profileKey
,
166 final TrustNewIdentity trustNewIdentity
167 ) throws IOException
{
168 IOUtils
.createPrivateDirectories(dataPath
);
169 var fileName
= getFileName(dataPath
, account
);
170 if (!fileName
.exists()) {
171 IOUtils
.createPrivateFile(fileName
);
174 final var pair
= openFileChannel(fileName
, true);
175 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
177 signalAccount
.account
= account
;
178 signalAccount
.profileKey
= profileKey
;
180 signalAccount
.dataPath
= dataPath
;
181 signalAccount
.identityKeyPair
= identityKey
;
182 signalAccount
.localRegistrationId
= registrationId
;
183 signalAccount
.trustNewIdentity
= trustNewIdentity
;
184 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, account
),
185 signalAccount
.getRecipientStore(),
186 signalAccount
::saveGroupStore
);
187 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
188 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
190 signalAccount
.registered
= false;
192 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
193 signalAccount
.migrateLegacyConfigs();
194 signalAccount
.save();
196 return signalAccount
;
199 public static SignalAccount
createOrUpdateLinkedAccount(
204 String encryptedDeviceName
,
206 IdentityKeyPair identityKey
,
208 ProfileKey profileKey
,
209 final TrustNewIdentity trustNewIdentity
210 ) throws IOException
{
211 IOUtils
.createPrivateDirectories(dataPath
);
212 var fileName
= getFileName(dataPath
, account
);
213 if (!fileName
.exists()) {
214 return createLinkedAccount(dataPath
,
226 final var signalAccount
= load(dataPath
, account
, true, trustNewIdentity
);
227 signalAccount
.setProvisioningData(account
, aci
, password
, encryptedDeviceName
, deviceId
, profileKey
);
228 signalAccount
.getRecipientStore().resolveRecipientTrusted(signalAccount
.getSelfAddress());
229 signalAccount
.getSessionStore().archiveAllSessions();
230 signalAccount
.getSenderKeyStore().deleteAll();
231 signalAccount
.clearAllPreKeys();
232 return signalAccount
;
235 public void initDatabase() {
239 private void clearAllPreKeys() {
240 this.preKeyIdOffset
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
241 this.nextSignedPreKeyId
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
242 this.getPreKeyStore().removeAllPreKeys();
243 this.getSignedPreKeyStore().removeAllSignedPreKeys();
247 private static SignalAccount
createLinkedAccount(
252 String encryptedDeviceName
,
254 IdentityKeyPair identityKey
,
256 ProfileKey profileKey
,
257 final TrustNewIdentity trustNewIdentity
258 ) throws IOException
{
259 var fileName
= getFileName(dataPath
, account
);
260 IOUtils
.createPrivateFile(fileName
);
262 final var pair
= openFileChannel(fileName
, true);
263 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
265 signalAccount
.setProvisioningData(account
, aci
, password
, encryptedDeviceName
, deviceId
, profileKey
);
267 signalAccount
.dataPath
= dataPath
;
268 signalAccount
.identityKeyPair
= identityKey
;
269 signalAccount
.localRegistrationId
= registrationId
;
270 signalAccount
.trustNewIdentity
= trustNewIdentity
;
271 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, account
),
272 signalAccount
.getRecipientStore(),
273 signalAccount
::saveGroupStore
);
274 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
275 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
277 signalAccount
.getRecipientStore().resolveRecipientTrusted(signalAccount
.getSelfAddress());
278 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
279 signalAccount
.migrateLegacyConfigs();
280 signalAccount
.save();
282 return signalAccount
;
285 private void setProvisioningData(
286 final String account
,
288 final String password
,
289 final String encryptedDeviceName
,
291 final ProfileKey profileKey
293 this.account
= account
;
295 this.password
= password
;
296 this.profileKey
= profileKey
;
297 this.encryptedDeviceName
= encryptedDeviceName
;
298 this.deviceId
= deviceId
;
299 this.registered
= true;
300 this.isMultiDevice
= true;
301 this.lastReceiveTimestamp
= 0;
302 this.pinMasterKey
= null;
303 this.storageManifestVersion
= -1;
304 this.storageKey
= null;
307 private void migrateLegacyConfigs() {
308 if (getPassword() == null) {
309 setPassword(KeyUtils
.createPassword());
312 if (getProfileKey() == null) {
313 // Old config file, creating new profile key
314 setProfileKey(KeyUtils
.createProfileKey());
316 // Ensure our profile key is stored in profile store
317 getProfileStore().storeProfileKey(getSelfRecipientId(), getProfileKey());
318 if (previousStorageVersion
< 3) {
319 for (final var group
: groupStore
.getGroups()) {
320 if (group
instanceof GroupInfoV2
&& group
.getDistributionId() == null) {
321 ((GroupInfoV2
) group
).setDistributionId(DistributionId
.create());
322 groupStore
.updateGroup(group
);
329 private void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
330 getSessionStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
331 getIdentityKeyStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
332 getMessageCache().mergeRecipients(recipientId
, toBeMergedRecipientId
);
333 getGroupStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
334 getSenderKeyStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
337 public void removeRecipient(final RecipientId recipientId
) {
338 getSessionStore().deleteAllSessions(recipientId
);
339 getIdentityKeyStore().deleteIdentity(recipientId
);
340 getMessageCache().deleteMessages(recipientId
);
341 getSenderKeyStore().deleteAll(recipientId
);
342 getRecipientStore().deleteRecipientData(recipientId
);
345 public static File
getFileName(File dataPath
, String account
) {
346 return new File(dataPath
, account
);
349 private static File
getUserPath(final File dataPath
, final String account
) {
350 final var path
= new File(dataPath
, account
+ ".d");
352 IOUtils
.createPrivateDirectories(path
);
353 } catch (IOException e
) {
354 throw new AssertionError("Failed to create user path", e
);
359 private static File
getMessageCachePath(File dataPath
, String account
) {
360 return new File(getUserPath(dataPath
, account
), "msg-cache");
363 private static File
getGroupCachePath(File dataPath
, String account
) {
364 return new File(getUserPath(dataPath
, account
), "group-cache");
367 private static File
getPreKeysPath(File dataPath
, String account
) {
368 return new File(getUserPath(dataPath
, account
), "pre-keys");
371 private static File
getSignedPreKeysPath(File dataPath
, String account
) {
372 return new File(getUserPath(dataPath
, account
), "signed-pre-keys");
375 private static File
getIdentitiesPath(File dataPath
, String account
) {
376 return new File(getUserPath(dataPath
, account
), "identities");
379 private static File
getSessionsPath(File dataPath
, String account
) {
380 return new File(getUserPath(dataPath
, account
), "sessions");
383 private static File
getSenderKeysPath(File dataPath
, String account
) {
384 return new File(getUserPath(dataPath
, account
), "sender-keys");
387 private static File
getSharedSenderKeysFile(File dataPath
, String account
) {
388 return new File(getUserPath(dataPath
, account
), "shared-sender-keys-store");
391 private static File
getRecipientsStoreFile(File dataPath
, String account
) {
392 return new File(getUserPath(dataPath
, account
), "recipients-store");
395 private static File
getDatabaseFile(File dataPath
, String account
) {
396 return new File(getUserPath(dataPath
, account
), "account.db");
399 public static boolean userExists(File dataPath
, String account
) {
400 if (account
== null) {
403 var f
= getFileName(dataPath
, account
);
404 return !(!f
.exists() || f
.isDirectory());
408 File dataPath
, final TrustNewIdentity trustNewIdentity
409 ) throws IOException
{
411 synchronized (fileChannel
) {
412 fileChannel
.position(0);
413 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
416 if (rootNode
.hasNonNull("version")) {
417 var accountVersion
= rootNode
.get("version").asInt(1);
418 if (accountVersion
> CURRENT_STORAGE_VERSION
) {
419 throw new IOException("Config file was created by a more recent version!");
420 } else if (accountVersion
< MINIMUM_STORAGE_VERSION
) {
421 throw new IOException("Config file was created by a no longer supported older version!");
423 previousStorageVersion
= accountVersion
;
426 account
= Utils
.getNotNullNode(rootNode
, "username").asText();
427 if (rootNode
.hasNonNull("password")) {
428 password
= rootNode
.get("password").asText();
430 registered
= Utils
.getNotNullNode(rootNode
, "registered").asBoolean();
431 if (rootNode
.hasNonNull("uuid")) {
433 aci
= ACI
.parseOrThrow(rootNode
.get("uuid").asText());
434 } catch (IllegalArgumentException e
) {
435 throw new IOException("Config file contains an invalid uuid, needs to be a valid UUID", e
);
438 if (rootNode
.hasNonNull("deviceName")) {
439 encryptedDeviceName
= rootNode
.get("deviceName").asText();
441 if (rootNode
.hasNonNull("deviceId")) {
442 deviceId
= rootNode
.get("deviceId").asInt();
444 if (rootNode
.hasNonNull("isMultiDevice")) {
445 isMultiDevice
= rootNode
.get("isMultiDevice").asBoolean();
447 if (rootNode
.hasNonNull("lastReceiveTimestamp")) {
448 lastReceiveTimestamp
= rootNode
.get("lastReceiveTimestamp").asLong();
450 int registrationId
= 0;
451 if (rootNode
.hasNonNull("registrationId")) {
452 registrationId
= rootNode
.get("registrationId").asInt();
454 IdentityKeyPair identityKeyPair
= null;
455 if (rootNode
.hasNonNull("identityPrivateKey") && rootNode
.hasNonNull("identityKey")) {
456 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityKey").asText());
457 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityPrivateKey").asText());
458 identityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
461 if (rootNode
.hasNonNull("registrationLockPin")) {
462 registrationLockPin
= rootNode
.get("registrationLockPin").asText();
464 if (rootNode
.hasNonNull("pinMasterKey")) {
465 pinMasterKey
= new MasterKey(Base64
.getDecoder().decode(rootNode
.get("pinMasterKey").asText()));
467 if (rootNode
.hasNonNull("storageKey")) {
468 storageKey
= new StorageKey(Base64
.getDecoder().decode(rootNode
.get("storageKey").asText()));
470 if (rootNode
.hasNonNull("storageManifestVersion")) {
471 storageManifestVersion
= rootNode
.get("storageManifestVersion").asLong();
473 if (rootNode
.hasNonNull("preKeyIdOffset")) {
474 preKeyIdOffset
= rootNode
.get("preKeyIdOffset").asInt(0);
478 if (rootNode
.hasNonNull("nextSignedPreKeyId")) {
479 nextSignedPreKeyId
= rootNode
.get("nextSignedPreKeyId").asInt();
481 nextSignedPreKeyId
= 0;
483 if (rootNode
.hasNonNull("profileKey")) {
485 profileKey
= new ProfileKey(Base64
.getDecoder().decode(rootNode
.get("profileKey").asText()));
486 } catch (InvalidInputException e
) {
487 throw new IOException(
488 "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
493 var migratedLegacyConfig
= false;
494 final var legacySignalProtocolStore
= rootNode
.hasNonNull("axolotlStore")
495 ? jsonProcessor
.convertValue(Utils
.getNotNullNode(rootNode
, "axolotlStore"),
496 LegacyJsonSignalProtocolStore
.class)
498 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
499 identityKeyPair
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentityKeyPair();
500 registrationId
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getLocalRegistrationId();
501 migratedLegacyConfig
= true;
504 this.dataPath
= dataPath
;
505 this.identityKeyPair
= identityKeyPair
;
506 this.localRegistrationId
= registrationId
;
507 this.trustNewIdentity
= trustNewIdentity
;
509 migratedLegacyConfig
= loadLegacyStores(rootNode
, legacySignalProtocolStore
) || migratedLegacyConfig
;
511 if (rootNode
.hasNonNull("groupStore")) {
512 groupStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("groupStore"), GroupStore
.Storage
.class);
513 groupStore
= GroupStore
.fromStorage(groupStoreStorage
,
514 getGroupCachePath(dataPath
, account
),
516 this::saveGroupStore
);
518 groupStore
= new GroupStore(getGroupCachePath(dataPath
, account
),
520 this::saveGroupStore
);
523 if (rootNode
.hasNonNull("stickerStore")) {
524 stickerStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("stickerStore"), StickerStore
.Storage
.class);
525 stickerStore
= StickerStore
.fromStorage(stickerStoreStorage
, this::saveStickerStore
);
527 stickerStore
= new StickerStore(this::saveStickerStore
);
530 if (rootNode
.hasNonNull("configurationStore")) {
531 configurationStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("configurationStore"),
532 ConfigurationStore
.Storage
.class);
533 configurationStore
= ConfigurationStore
.fromStorage(configurationStoreStorage
,
534 this::saveConfigurationStore
);
536 configurationStore
= new ConfigurationStore(this::saveConfigurationStore
);
539 migratedLegacyConfig
= loadLegacyThreadStore(rootNode
) || migratedLegacyConfig
;
541 if (migratedLegacyConfig
) {
546 private boolean loadLegacyStores(
547 final JsonNode rootNode
, final LegacyJsonSignalProtocolStore legacySignalProtocolStore
549 var migrated
= false;
550 var legacyRecipientStoreNode
= rootNode
.get("recipientStore");
551 if (legacyRecipientStoreNode
!= null) {
552 logger
.debug("Migrating legacy recipient store.");
553 var legacyRecipientStore
= jsonProcessor
.convertValue(legacyRecipientStoreNode
, LegacyRecipientStore
.class);
554 if (legacyRecipientStore
!= null) {
555 getRecipientStore().resolveRecipientsTrusted(legacyRecipientStore
.getAddresses());
557 getRecipientStore().resolveRecipientTrusted(getSelfRecipientAddress());
561 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyPreKeyStore() != null) {
562 logger
.debug("Migrating legacy pre key store.");
563 for (var entry
: legacySignalProtocolStore
.getLegacyPreKeyStore().getPreKeys().entrySet()) {
565 getPreKeyStore().storePreKey(entry
.getKey(), new PreKeyRecord(entry
.getValue()));
566 } catch (IOException e
) {
567 logger
.warn("Failed to migrate pre key, ignoring", e
);
573 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySignedPreKeyStore() != null) {
574 logger
.debug("Migrating legacy signed pre key store.");
575 for (var entry
: legacySignalProtocolStore
.getLegacySignedPreKeyStore().getSignedPreKeys().entrySet()) {
577 getSignedPreKeyStore().storeSignedPreKey(entry
.getKey(), new SignedPreKeyRecord(entry
.getValue()));
578 } catch (IOException e
) {
579 logger
.warn("Failed to migrate signed pre key, ignoring", e
);
585 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySessionStore() != null) {
586 logger
.debug("Migrating legacy session store.");
587 for (var session
: legacySignalProtocolStore
.getLegacySessionStore().getSessions()) {
589 getSessionStore().storeSession(new SignalProtocolAddress(session
.address
.getIdentifier(),
590 session
.deviceId
), new SessionRecord(session
.sessionRecord
));
591 } catch (Exception e
) {
592 logger
.warn("Failed to migrate session, ignoring", e
);
598 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
599 logger
.debug("Migrating legacy identity session store.");
600 for (var identity
: legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentities()) {
601 RecipientId recipientId
= getRecipientStore().resolveRecipientTrusted(identity
.getAddress());
602 getIdentityKeyStore().saveIdentity(recipientId
, identity
.getIdentityKey(), identity
.getDateAdded());
603 getIdentityKeyStore().setIdentityTrustLevel(recipientId
,
604 identity
.getIdentityKey(),
605 identity
.getTrustLevel());
610 if (rootNode
.hasNonNull("contactStore")) {
611 logger
.debug("Migrating legacy contact store.");
612 final var contactStoreNode
= rootNode
.get("contactStore");
613 final var contactStore
= jsonProcessor
.convertValue(contactStoreNode
, LegacyJsonContactsStore
.class);
614 for (var contact
: contactStore
.getContacts()) {
615 final var recipientId
= getRecipientStore().resolveRecipientTrusted(contact
.getAddress());
616 getRecipientStore().storeContact(recipientId
,
617 new Contact(contact
.name
,
619 contact
.messageExpirationTime
,
623 // Store profile keys only in profile store
624 var profileKeyString
= contact
.profileKey
;
625 if (profileKeyString
!= null) {
626 final ProfileKey profileKey
;
628 profileKey
= new ProfileKey(Base64
.getDecoder().decode(profileKeyString
));
629 getProfileStore().storeProfileKey(recipientId
, profileKey
);
630 } catch (InvalidInputException e
) {
631 logger
.warn("Failed to parse legacy contact profile key: {}", e
.getMessage());
638 if (rootNode
.hasNonNull("profileStore")) {
639 logger
.debug("Migrating legacy profile store.");
640 var profileStoreNode
= rootNode
.get("profileStore");
641 final var legacyProfileStore
= jsonProcessor
.convertValue(profileStoreNode
, LegacyProfileStore
.class);
642 for (var profileEntry
: legacyProfileStore
.getProfileEntries()) {
643 var recipientId
= getRecipientStore().resolveRecipient(profileEntry
.getAddress());
644 getRecipientStore().storeProfileKeyCredential(recipientId
, profileEntry
.getProfileKeyCredential());
645 getRecipientStore().storeProfileKey(recipientId
, profileEntry
.getProfileKey());
646 final var profile
= profileEntry
.getProfile();
647 if (profile
!= null) {
648 final var capabilities
= new HashSet
<Profile
.Capability
>();
649 if (profile
.getCapabilities() != null) {
650 if (profile
.getCapabilities().gv1Migration
) {
651 capabilities
.add(Profile
.Capability
.gv1Migration
);
653 if (profile
.getCapabilities().gv2
) {
654 capabilities
.add(Profile
.Capability
.gv2
);
656 if (profile
.getCapabilities().storage
) {
657 capabilities
.add(Profile
.Capability
.storage
);
660 final var newProfile
= new Profile(profileEntry
.getLastUpdateTimestamp(),
661 profile
.getGivenName(),
662 profile
.getFamilyName(),
664 profile
.getAboutEmoji(),
666 profile
.isUnrestrictedUnidentifiedAccess()
667 ? Profile
.UnidentifiedAccessMode
.UNRESTRICTED
668 : profile
.getUnidentifiedAccess() != null
669 ? Profile
.UnidentifiedAccessMode
.ENABLED
670 : Profile
.UnidentifiedAccessMode
.DISABLED
,
672 getRecipientStore().storeProfile(recipientId
, newProfile
);
680 private boolean loadLegacyThreadStore(final JsonNode rootNode
) {
681 var threadStoreNode
= rootNode
.get("threadStore");
682 if (threadStoreNode
!= null && !threadStoreNode
.isNull()) {
683 var threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
684 // Migrate thread info to group and contact store
685 for (var thread
: threadStore
.getThreads()) {
686 if (thread
.id
== null || thread
.id
.isEmpty()) {
690 if (UuidUtil
.isUuid(thread
.id
) || thread
.id
.startsWith("+")) {
691 final var recipientId
= getRecipientStore().resolveRecipient(thread
.id
);
692 var contact
= getRecipientStore().getContact(recipientId
);
693 if (contact
!= null) {
694 getRecipientStore().storeContact(recipientId
,
695 Contact
.newBuilder(contact
)
696 .withMessageExpirationTime(thread
.messageExpirationTime
)
700 var groupInfo
= groupStore
.getGroup(GroupId
.fromBase64(thread
.id
));
701 if (groupInfo
instanceof GroupInfoV1
) {
702 ((GroupInfoV1
) groupInfo
).messageExpirationTime
= thread
.messageExpirationTime
;
703 groupStore
.updateGroup(groupInfo
);
706 } catch (Exception e
) {
707 logger
.warn("Failed to read legacy thread info: {}", e
.getMessage());
716 private void saveStickerStore(StickerStore
.Storage storage
) {
717 this.stickerStoreStorage
= storage
;
721 private void saveGroupStore(GroupStore
.Storage storage
) {
722 this.groupStoreStorage
= storage
;
726 private void saveConfigurationStore(ConfigurationStore
.Storage storage
) {
727 this.configurationStoreStorage
= storage
;
731 private void save() {
732 synchronized (fileChannel
) {
733 var rootNode
= jsonProcessor
.createObjectNode();
734 rootNode
.put("version", CURRENT_STORAGE_VERSION
)
735 .put("username", account
)
736 .put("uuid", aci
== null ?
null : aci
.toString())
737 .put("deviceName", encryptedDeviceName
)
738 .put("deviceId", deviceId
)
739 .put("isMultiDevice", isMultiDevice
)
740 .put("lastReceiveTimestamp", lastReceiveTimestamp
)
741 .put("password", password
)
742 .put("registrationId", localRegistrationId
)
743 .put("identityPrivateKey",
744 Base64
.getEncoder().encodeToString(identityKeyPair
.getPrivateKey().serialize()))
745 .put("identityKey", Base64
.getEncoder().encodeToString(identityKeyPair
.getPublicKey().serialize()))
746 .put("registrationLockPin", registrationLockPin
)
748 pinMasterKey
== null ?
null : Base64
.getEncoder().encodeToString(pinMasterKey
.serialize()))
750 storageKey
== null ?
null : Base64
.getEncoder().encodeToString(storageKey
.serialize()))
751 .put("storageManifestVersion", storageManifestVersion
== -1 ?
null : storageManifestVersion
)
752 .put("preKeyIdOffset", preKeyIdOffset
)
753 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
755 profileKey
== null ?
null : Base64
.getEncoder().encodeToString(profileKey
.serialize()))
756 .put("registered", registered
)
757 .putPOJO("groupStore", groupStoreStorage
)
758 .putPOJO("stickerStore", stickerStoreStorage
)
759 .putPOJO("configurationStore", configurationStoreStorage
);
761 try (var output
= new ByteArrayOutputStream()) {
762 // Write to memory first to prevent corrupting the file in case of serialization errors
763 jsonProcessor
.writeValue(output
, rootNode
);
764 var input
= new ByteArrayInputStream(output
.toByteArray());
765 fileChannel
.position(0);
766 input
.transferTo(Channels
.newOutputStream(fileChannel
));
767 fileChannel
.truncate(fileChannel
.position());
768 fileChannel
.force(false);
770 } catch (Exception e
) {
771 logger
.error("Error saving file: {}", e
.getMessage(), e
);
776 private static Pair
<FileChannel
, FileLock
> openFileChannel(File fileName
, boolean waitForLock
) throws IOException
{
777 var fileChannel
= new RandomAccessFile(fileName
, "rw").getChannel();
778 var lock
= fileChannel
.tryLock();
781 logger
.debug("Config file is in use by another instance.");
782 throw new IOException("Config file is in use by another instance.");
784 logger
.info("Config file is in use by another instance, waiting…");
785 lock
= fileChannel
.lock();
786 logger
.info("Config file lock acquired.");
788 return new Pair
<>(fileChannel
, lock
);
791 public void addPreKeys(List
<PreKeyRecord
> records
) {
792 for (var record : records
) {
793 if (preKeyIdOffset
!= record.getId()) {
794 logger
.error("Invalid pre key id {}, expected {}", record.getId(), preKeyIdOffset
);
795 throw new AssertionError("Invalid pre key id");
797 getPreKeyStore().storePreKey(record.getId(), record);
798 preKeyIdOffset
= (preKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
803 public void addSignedPreKey(SignedPreKeyRecord
record) {
804 if (nextSignedPreKeyId
!= record.getId()) {
805 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), nextSignedPreKeyId
);
806 throw new AssertionError("Invalid signed pre key id");
808 getSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
809 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
813 public SignalProtocolStore
getSignalProtocolStore() {
814 return getOrCreate(() -> signalProtocolStore
,
815 () -> signalProtocolStore
= new SignalProtocolStore(getPreKeyStore(),
816 getSignedPreKeyStore(),
818 getIdentityKeyStore(),
820 this::isMultiDevice
));
823 private PreKeyStore
getPreKeyStore() {
824 return getOrCreate(() -> preKeyStore
, () -> preKeyStore
= new PreKeyStore(getPreKeysPath(dataPath
, account
)));
827 private SignedPreKeyStore
getSignedPreKeyStore() {
828 return getOrCreate(() -> signedPreKeyStore
,
829 () -> signedPreKeyStore
= new SignedPreKeyStore(getSignedPreKeysPath(dataPath
, account
)));
832 public SessionStore
getSessionStore() {
833 return getOrCreate(() -> sessionStore
,
834 () -> sessionStore
= new SessionStore(getSessionsPath(dataPath
, account
), getRecipientStore()));
837 public IdentityKeyStore
getIdentityKeyStore() {
838 return getOrCreate(() -> identityKeyStore
,
839 () -> identityKeyStore
= new IdentityKeyStore(getIdentitiesPath(dataPath
, account
),
846 public GroupStore
getGroupStore() {
850 public ContactsStore
getContactStore() {
851 return getRecipientStore();
854 public RecipientStore
getRecipientStore() {
855 return getOrCreate(() -> recipientStore
,
856 () -> recipientStore
= RecipientStore
.load(getRecipientsStoreFile(dataPath
, account
),
857 this::mergeRecipients
));
860 public ProfileStore
getProfileStore() {
861 return getRecipientStore();
864 public StickerStore
getStickerStore() {
868 public SenderKeyStore
getSenderKeyStore() {
869 return getOrCreate(() -> senderKeyStore
,
870 () -> senderKeyStore
= new SenderKeyStore(getSharedSenderKeysFile(dataPath
, account
),
871 getSenderKeysPath(dataPath
, account
),
872 getRecipientStore()::resolveRecipientAddress
,
873 getRecipientStore()));
876 public ConfigurationStore
getConfigurationStore() {
877 return configurationStore
;
880 public MessageCache
getMessageCache() {
881 return getOrCreate(() -> messageCache
,
882 () -> messageCache
= new MessageCache(getMessageCachePath(dataPath
, account
)));
885 public Database
getDatabase() {
886 return getOrCreate(() -> database
, () -> {
888 database
= Database
.init(getDatabaseFile(dataPath
, account
));
889 } catch (SQLException e
) {
890 throw new RuntimeException(e
);
895 public MessageSendLogStore
getMessageSendLogStore() {
896 return getOrCreate(() -> messageSendLogStore
,
897 () -> messageSendLogStore
= new MessageSendLogStore(getRecipientStore(), getDatabase()));
900 public String
getAccount() {
904 public ACI
getAci() {
908 public void setAci(final ACI aci
) {
913 public SignalServiceAddress
getSelfAddress() {
914 return new SignalServiceAddress(aci
, account
);
917 public RecipientAddress
getSelfRecipientAddress() {
918 return new RecipientAddress(aci
== null ?
null : aci
.uuid(), account
);
921 public RecipientId
getSelfRecipientId() {
922 return getRecipientStore().resolveRecipient(getSelfRecipientAddress());
925 public String
getEncryptedDeviceName() {
926 return encryptedDeviceName
;
929 public void setEncryptedDeviceName(final String encryptedDeviceName
) {
930 this.encryptedDeviceName
= encryptedDeviceName
;
934 public int getDeviceId() {
938 public boolean isMasterDevice() {
939 return deviceId
== SignalServiceAddress
.DEFAULT_DEVICE_ID
;
942 public IdentityKeyPair
getIdentityKeyPair() {
943 return identityKeyPair
;
946 public int getLocalRegistrationId() {
947 return localRegistrationId
;
950 public String
getPassword() {
954 private void setPassword(final String password
) {
955 this.password
= password
;
959 public void setRegistrationLockPin(final String registrationLockPin
, final MasterKey pinMasterKey
) {
960 this.registrationLockPin
= registrationLockPin
;
961 this.pinMasterKey
= pinMasterKey
;
965 public MasterKey
getPinMasterKey() {
969 public StorageKey
getStorageKey() {
970 if (pinMasterKey
!= null) {
971 return pinMasterKey
.deriveStorageServiceKey();
976 public void setStorageKey(final StorageKey storageKey
) {
977 if (storageKey
.equals(this.storageKey
)) {
980 this.storageKey
= storageKey
;
984 public long getStorageManifestVersion() {
985 return this.storageManifestVersion
;
988 public void setStorageManifestVersion(final long storageManifestVersion
) {
989 if (storageManifestVersion
== this.storageManifestVersion
) {
992 this.storageManifestVersion
= storageManifestVersion
;
996 public ProfileKey
getProfileKey() {
1000 public void setProfileKey(final ProfileKey profileKey
) {
1001 if (profileKey
.equals(this.profileKey
)) {
1004 this.profileKey
= profileKey
;
1008 public byte[] getSelfUnidentifiedAccessKey() {
1009 return UnidentifiedAccess
.deriveAccessKeyFrom(getProfileKey());
1012 public int getPreKeyIdOffset() {
1013 return preKeyIdOffset
;
1016 public int getNextSignedPreKeyId() {
1017 return nextSignedPreKeyId
;
1020 public boolean isRegistered() {
1024 public void setRegistered(final boolean registered
) {
1025 this.registered
= registered
;
1029 public boolean isMultiDevice() {
1030 return isMultiDevice
;
1033 public void setMultiDevice(final boolean multiDevice
) {
1034 if (isMultiDevice
== multiDevice
) {
1037 isMultiDevice
= multiDevice
;
1041 public long getLastReceiveTimestamp() {
1042 return lastReceiveTimestamp
;
1045 public void setLastReceiveTimestamp(final long lastReceiveTimestamp
) {
1046 this.lastReceiveTimestamp
= lastReceiveTimestamp
;
1050 public boolean isUnrestrictedUnidentifiedAccess() {
1051 // TODO make configurable
1055 public boolean isDiscoverableByPhoneNumber() {
1056 return configurationStore
.getPhoneNumberUnlisted() == null || !configurationStore
.getPhoneNumberUnlisted();
1059 public void finishRegistration(final ACI aci
, final MasterKey masterKey
, final String pin
) {
1060 this.pinMasterKey
= masterKey
;
1061 this.storageManifestVersion
= -1;
1062 this.storageKey
= null;
1063 this.encryptedDeviceName
= null;
1064 this.deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1065 this.isMultiDevice
= false;
1066 this.registered
= true;
1068 this.registrationLockPin
= pin
;
1069 this.lastReceiveTimestamp
= 0;
1073 getSessionStore().archiveAllSessions();
1074 getSenderKeyStore().deleteAll();
1075 final var recipientId
= getRecipientStore().resolveRecipientTrusted(getSelfAddress());
1076 final var publicKey
= getIdentityKeyPair().getPublicKey();
1077 getIdentityKeyStore().saveIdentity(recipientId
, publicKey
, new Date());
1078 getIdentityKeyStore().setIdentityTrustLevel(recipientId
, publicKey
, TrustLevel
.TRUSTED_VERIFIED
);
1082 public void close() {
1083 synchronized (fileChannel
) {
1084 if (database
!= null) {
1087 } catch (SQLException e
) {
1088 logger
.warn("Failed to close account database: {}", e
.getMessage(), e
);
1091 if (messageSendLogStore
!= null) {
1092 messageSendLogStore
.close();
1097 } catch (ClosedChannelException ignored
) {
1099 fileChannel
.close();
1100 } catch (IOException e
) {
1101 logger
.warn("Failed to close account: {}", e
.getMessage(), e
);
1106 private <T
> T
getOrCreate(Supplier
<T
> supplier
, Callable creator
) {
1107 var value
= supplier
.get();
1108 if (value
!= null) {
1112 synchronized (LOCK
) {
1113 value
= supplier
.get();
1114 if (value
!= null) {
1118 return supplier
.get();
1122 private interface Callable
{