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
.senderKeys
.SenderKeyStore
;
31 import org
.asamk
.signal
.manager
.storage
.sessions
.SessionStore
;
32 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerStore
;
33 import org
.asamk
.signal
.manager
.storage
.threads
.LegacyJsonThreadStore
;
34 import org
.asamk
.signal
.manager
.util
.IOUtils
;
35 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
36 import org
.signal
.zkgroup
.InvalidInputException
;
37 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
38 import org
.slf4j
.Logger
;
39 import org
.slf4j
.LoggerFactory
;
40 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
41 import org
.whispersystems
.libsignal
.SignalProtocolAddress
;
42 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
43 import org
.whispersystems
.libsignal
.state
.SessionRecord
;
44 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
45 import org
.whispersystems
.libsignal
.util
.Medium
;
46 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
47 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
48 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
49 import org
.whispersystems
.signalservice
.api
.push
.DistributionId
;
50 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
51 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
52 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
54 import java
.io
.ByteArrayInputStream
;
55 import java
.io
.ByteArrayOutputStream
;
56 import java
.io
.Closeable
;
58 import java
.io
.IOException
;
59 import java
.io
.RandomAccessFile
;
60 import java
.nio
.channels
.Channels
;
61 import java
.nio
.channels
.ClosedChannelException
;
62 import java
.nio
.channels
.FileChannel
;
63 import java
.nio
.channels
.FileLock
;
64 import java
.util
.Base64
;
65 import java
.util
.Date
;
66 import java
.util
.HashSet
;
67 import java
.util
.List
;
69 public class SignalAccount
implements Closeable
{
71 private final static Logger logger
= LoggerFactory
.getLogger(SignalAccount
.class);
73 private static final int MINIMUM_STORAGE_VERSION
= 1;
74 private static final int CURRENT_STORAGE_VERSION
= 3;
76 private int previousStorageVersion
;
78 private final ObjectMapper jsonProcessor
= Utils
.createStorageObjectMapper();
80 private final FileChannel fileChannel
;
81 private final FileLock lock
;
83 private String account
;
85 private String encryptedDeviceName
;
86 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
87 private boolean isMultiDevice
= false;
88 private String password
;
89 private String registrationLockPin
;
90 private MasterKey pinMasterKey
;
91 private StorageKey storageKey
;
92 private long storageManifestVersion
= -1;
93 private ProfileKey profileKey
;
94 private int preKeyIdOffset
;
95 private int nextSignedPreKeyId
;
96 private long lastReceiveTimestamp
= 0;
98 private boolean registered
= false;
100 private SignalProtocolStore signalProtocolStore
;
101 private PreKeyStore preKeyStore
;
102 private SignedPreKeyStore signedPreKeyStore
;
103 private SessionStore sessionStore
;
104 private IdentityKeyStore identityKeyStore
;
105 private SenderKeyStore senderKeyStore
;
106 private GroupStore groupStore
;
107 private GroupStore
.Storage groupStoreStorage
;
108 private RecipientStore recipientStore
;
109 private StickerStore stickerStore
;
110 private StickerStore
.Storage stickerStoreStorage
;
111 private ConfigurationStore configurationStore
;
112 private ConfigurationStore
.Storage configurationStoreStorage
;
114 private MessageCache messageCache
;
116 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
117 this.fileChannel
= fileChannel
;
121 public static SignalAccount
load(
122 File dataPath
, String account
, boolean waitForLock
, final TrustNewIdentity trustNewIdentity
123 ) throws IOException
{
124 final var fileName
= getFileName(dataPath
, account
);
125 final var pair
= openFileChannel(fileName
, waitForLock
);
127 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
128 signalAccount
.load(dataPath
, trustNewIdentity
);
129 signalAccount
.migrateLegacyConfigs();
131 if (!account
.equals(signalAccount
.getAccount())) {
132 throw new IOException("Number in account file doesn't match expected number: "
133 + signalAccount
.getAccount());
136 return signalAccount
;
137 } catch (Throwable e
) {
138 pair
.second().close();
139 pair
.first().close();
144 public static SignalAccount
create(
147 IdentityKeyPair identityKey
,
149 ProfileKey profileKey
,
150 final TrustNewIdentity trustNewIdentity
151 ) throws IOException
{
152 IOUtils
.createPrivateDirectories(dataPath
);
153 var fileName
= getFileName(dataPath
, account
);
154 if (!fileName
.exists()) {
155 IOUtils
.createPrivateFile(fileName
);
158 final var pair
= openFileChannel(fileName
, true);
159 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
161 signalAccount
.account
= account
;
162 signalAccount
.profileKey
= profileKey
;
164 signalAccount
.initStores(dataPath
, identityKey
, registrationId
, trustNewIdentity
);
165 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, account
),
166 signalAccount
.recipientStore
,
167 signalAccount
::saveGroupStore
);
168 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
169 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
171 signalAccount
.registered
= false;
173 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
174 signalAccount
.migrateLegacyConfigs();
175 signalAccount
.save();
177 return signalAccount
;
180 private void initStores(
182 final IdentityKeyPair identityKey
,
183 final int registrationId
,
184 final TrustNewIdentity trustNewIdentity
185 ) throws IOException
{
186 recipientStore
= RecipientStore
.load(getRecipientsStoreFile(dataPath
, account
), this::mergeRecipients
);
188 preKeyStore
= new PreKeyStore(getPreKeysPath(dataPath
, account
));
189 signedPreKeyStore
= new SignedPreKeyStore(getSignedPreKeysPath(dataPath
, account
));
190 sessionStore
= new SessionStore(getSessionsPath(dataPath
, account
), recipientStore
);
191 identityKeyStore
= new IdentityKeyStore(getIdentitiesPath(dataPath
, account
),
196 senderKeyStore
= new SenderKeyStore(getSharedSenderKeysFile(dataPath
, account
),
197 getSenderKeysPath(dataPath
, account
),
198 recipientStore
::resolveRecipientAddress
,
200 signalProtocolStore
= new SignalProtocolStore(preKeyStore
,
205 this::isMultiDevice
);
207 messageCache
= new MessageCache(getMessageCachePath(dataPath
, account
));
210 public static SignalAccount
createOrUpdateLinkedAccount(
215 String encryptedDeviceName
,
217 IdentityKeyPair identityKey
,
219 ProfileKey profileKey
,
220 final TrustNewIdentity trustNewIdentity
221 ) throws IOException
{
222 IOUtils
.createPrivateDirectories(dataPath
);
223 var fileName
= getFileName(dataPath
, account
);
224 if (!fileName
.exists()) {
225 return createLinkedAccount(dataPath
,
237 final var signalAccount
= load(dataPath
, account
, true, trustNewIdentity
);
238 signalAccount
.setProvisioningData(account
, aci
, password
, encryptedDeviceName
, deviceId
, profileKey
);
239 signalAccount
.recipientStore
.resolveRecipientTrusted(signalAccount
.getSelfAddress());
240 signalAccount
.sessionStore
.archiveAllSessions();
241 signalAccount
.senderKeyStore
.deleteAll();
242 signalAccount
.clearAllPreKeys();
243 return signalAccount
;
246 private void clearAllPreKeys() {
247 this.preKeyIdOffset
= 0;
248 this.nextSignedPreKeyId
= 0;
249 this.preKeyStore
.removeAllPreKeys();
250 this.signedPreKeyStore
.removeAllSignedPreKeys();
254 private static SignalAccount
createLinkedAccount(
259 String encryptedDeviceName
,
261 IdentityKeyPair identityKey
,
263 ProfileKey profileKey
,
264 final TrustNewIdentity trustNewIdentity
265 ) throws IOException
{
266 var fileName
= getFileName(dataPath
, account
);
267 IOUtils
.createPrivateFile(fileName
);
269 final var pair
= openFileChannel(fileName
, true);
270 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
272 signalAccount
.setProvisioningData(account
, aci
, password
, encryptedDeviceName
, deviceId
, profileKey
);
274 signalAccount
.initStores(dataPath
, identityKey
, registrationId
, trustNewIdentity
);
275 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, account
),
276 signalAccount
.recipientStore
,
277 signalAccount
::saveGroupStore
);
278 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
279 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
281 signalAccount
.recipientStore
.resolveRecipientTrusted(signalAccount
.getSelfAddress());
282 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
283 signalAccount
.migrateLegacyConfigs();
284 signalAccount
.save();
286 return signalAccount
;
289 private void setProvisioningData(
290 final String account
,
292 final String password
,
293 final String encryptedDeviceName
,
295 final ProfileKey profileKey
297 this.account
= account
;
299 this.password
= password
;
300 this.profileKey
= profileKey
;
301 this.encryptedDeviceName
= encryptedDeviceName
;
302 this.deviceId
= deviceId
;
303 this.registered
= true;
304 this.isMultiDevice
= true;
305 this.lastReceiveTimestamp
= 0;
306 this.pinMasterKey
= null;
307 this.storageManifestVersion
= -1;
308 this.storageKey
= null;
311 private void migrateLegacyConfigs() {
312 if (getPassword() == null) {
313 setPassword(KeyUtils
.createPassword());
316 if (getProfileKey() == null) {
317 // Old config file, creating new profile key
318 setProfileKey(KeyUtils
.createProfileKey());
320 // Ensure our profile key is stored in profile store
321 getProfileStore().storeProfileKey(getSelfRecipientId(), getProfileKey());
322 if (previousStorageVersion
< 3) {
323 for (final var group
: groupStore
.getGroups()) {
324 if (group
instanceof GroupInfoV2
&& group
.getDistributionId() == null) {
325 ((GroupInfoV2
) group
).setDistributionId(DistributionId
.create());
326 groupStore
.updateGroup(group
);
333 private void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
334 sessionStore
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
335 identityKeyStore
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
336 messageCache
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
337 groupStore
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
338 senderKeyStore
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
341 public void removeRecipient(final RecipientId recipientId
) {
342 sessionStore
.deleteAllSessions(recipientId
);
343 identityKeyStore
.deleteIdentity(recipientId
);
344 messageCache
.deleteMessages(recipientId
);
345 senderKeyStore
.deleteAll(recipientId
);
346 recipientStore
.deleteRecipientData(recipientId
);
349 public static File
getFileName(File dataPath
, String account
) {
350 return new File(dataPath
, account
);
353 private static File
getUserPath(final File dataPath
, final String account
) {
354 final var path
= new File(dataPath
, account
+ ".d");
356 IOUtils
.createPrivateDirectories(path
);
357 } catch (IOException e
) {
358 throw new AssertionError("Failed to create user path", e
);
363 private static File
getMessageCachePath(File dataPath
, String account
) {
364 return new File(getUserPath(dataPath
, account
), "msg-cache");
367 private static File
getGroupCachePath(File dataPath
, String account
) {
368 return new File(getUserPath(dataPath
, account
), "group-cache");
371 private static File
getPreKeysPath(File dataPath
, String account
) {
372 return new File(getUserPath(dataPath
, account
), "pre-keys");
375 private static File
getSignedPreKeysPath(File dataPath
, String account
) {
376 return new File(getUserPath(dataPath
, account
), "signed-pre-keys");
379 private static File
getIdentitiesPath(File dataPath
, String account
) {
380 return new File(getUserPath(dataPath
, account
), "identities");
383 private static File
getSessionsPath(File dataPath
, String account
) {
384 return new File(getUserPath(dataPath
, account
), "sessions");
387 private static File
getSenderKeysPath(File dataPath
, String account
) {
388 return new File(getUserPath(dataPath
, account
), "sender-keys");
391 private static File
getSharedSenderKeysFile(File dataPath
, String account
) {
392 return new File(getUserPath(dataPath
, account
), "shared-sender-keys-store");
395 private static File
getRecipientsStoreFile(File dataPath
, String account
) {
396 return new File(getUserPath(dataPath
, account
), "recipients-store");
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 initStores(dataPath
, identityKeyPair
, registrationId
, trustNewIdentity
);
506 migratedLegacyConfig
= loadLegacyStores(rootNode
, legacySignalProtocolStore
) || migratedLegacyConfig
;
508 if (rootNode
.hasNonNull("groupStore")) {
509 groupStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("groupStore"), GroupStore
.Storage
.class);
510 groupStore
= GroupStore
.fromStorage(groupStoreStorage
,
511 getGroupCachePath(dataPath
, account
),
513 this::saveGroupStore
);
515 groupStore
= new GroupStore(getGroupCachePath(dataPath
, account
), recipientStore
, this::saveGroupStore
);
518 if (rootNode
.hasNonNull("stickerStore")) {
519 stickerStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("stickerStore"), StickerStore
.Storage
.class);
520 stickerStore
= StickerStore
.fromStorage(stickerStoreStorage
, this::saveStickerStore
);
522 stickerStore
= new StickerStore(this::saveStickerStore
);
525 if (rootNode
.hasNonNull("configurationStore")) {
526 configurationStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("configurationStore"),
527 ConfigurationStore
.Storage
.class);
528 configurationStore
= ConfigurationStore
.fromStorage(configurationStoreStorage
,
529 this::saveConfigurationStore
);
531 configurationStore
= new ConfigurationStore(this::saveConfigurationStore
);
534 migratedLegacyConfig
= loadLegacyThreadStore(rootNode
) || migratedLegacyConfig
;
536 if (migratedLegacyConfig
) {
541 private boolean loadLegacyStores(
542 final JsonNode rootNode
, final LegacyJsonSignalProtocolStore legacySignalProtocolStore
544 var migrated
= false;
545 var legacyRecipientStoreNode
= rootNode
.get("recipientStore");
546 if (legacyRecipientStoreNode
!= null) {
547 logger
.debug("Migrating legacy recipient store.");
548 var legacyRecipientStore
= jsonProcessor
.convertValue(legacyRecipientStoreNode
, LegacyRecipientStore
.class);
549 if (legacyRecipientStore
!= null) {
550 recipientStore
.resolveRecipientsTrusted(legacyRecipientStore
.getAddresses());
552 getSelfRecipientId();
556 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyPreKeyStore() != null) {
557 logger
.debug("Migrating legacy pre key store.");
558 for (var entry
: legacySignalProtocolStore
.getLegacyPreKeyStore().getPreKeys().entrySet()) {
560 preKeyStore
.storePreKey(entry
.getKey(), new PreKeyRecord(entry
.getValue()));
561 } catch (IOException e
) {
562 logger
.warn("Failed to migrate pre key, ignoring", e
);
568 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySignedPreKeyStore() != null) {
569 logger
.debug("Migrating legacy signed pre key store.");
570 for (var entry
: legacySignalProtocolStore
.getLegacySignedPreKeyStore().getSignedPreKeys().entrySet()) {
572 signedPreKeyStore
.storeSignedPreKey(entry
.getKey(), new SignedPreKeyRecord(entry
.getValue()));
573 } catch (IOException e
) {
574 logger
.warn("Failed to migrate signed pre key, ignoring", e
);
580 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySessionStore() != null) {
581 logger
.debug("Migrating legacy session store.");
582 for (var session
: legacySignalProtocolStore
.getLegacySessionStore().getSessions()) {
584 sessionStore
.storeSession(new SignalProtocolAddress(session
.address
.getIdentifier(),
585 session
.deviceId
), new SessionRecord(session
.sessionRecord
));
586 } catch (Exception e
) {
587 logger
.warn("Failed to migrate session, ignoring", e
);
593 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
594 logger
.debug("Migrating legacy identity session store.");
595 for (var identity
: legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentities()) {
596 RecipientId recipientId
= recipientStore
.resolveRecipientTrusted(identity
.getAddress());
597 identityKeyStore
.saveIdentity(recipientId
, identity
.getIdentityKey(), identity
.getDateAdded());
598 identityKeyStore
.setIdentityTrustLevel(recipientId
,
599 identity
.getIdentityKey(),
600 identity
.getTrustLevel());
605 if (rootNode
.hasNonNull("contactStore")) {
606 logger
.debug("Migrating legacy contact store.");
607 final var contactStoreNode
= rootNode
.get("contactStore");
608 final var contactStore
= jsonProcessor
.convertValue(contactStoreNode
, LegacyJsonContactsStore
.class);
609 for (var contact
: contactStore
.getContacts()) {
610 final var recipientId
= recipientStore
.resolveRecipientTrusted(contact
.getAddress());
611 recipientStore
.storeContact(recipientId
,
612 new Contact(contact
.name
,
614 contact
.messageExpirationTime
,
618 // Store profile keys only in profile store
619 var profileKeyString
= contact
.profileKey
;
620 if (profileKeyString
!= null) {
621 final ProfileKey profileKey
;
623 profileKey
= new ProfileKey(Base64
.getDecoder().decode(profileKeyString
));
624 getProfileStore().storeProfileKey(recipientId
, profileKey
);
625 } catch (InvalidInputException e
) {
626 logger
.warn("Failed to parse legacy contact profile key: {}", e
.getMessage());
633 if (rootNode
.hasNonNull("profileStore")) {
634 logger
.debug("Migrating legacy profile store.");
635 var profileStoreNode
= rootNode
.get("profileStore");
636 final var legacyProfileStore
= jsonProcessor
.convertValue(profileStoreNode
, LegacyProfileStore
.class);
637 for (var profileEntry
: legacyProfileStore
.getProfileEntries()) {
638 var recipientId
= recipientStore
.resolveRecipient(profileEntry
.getAddress());
639 recipientStore
.storeProfileKeyCredential(recipientId
, profileEntry
.getProfileKeyCredential());
640 recipientStore
.storeProfileKey(recipientId
, profileEntry
.getProfileKey());
641 final var profile
= profileEntry
.getProfile();
642 if (profile
!= null) {
643 final var capabilities
= new HashSet
<Profile
.Capability
>();
644 if (profile
.getCapabilities() != null) {
645 if (profile
.getCapabilities().gv1Migration
) {
646 capabilities
.add(Profile
.Capability
.gv1Migration
);
648 if (profile
.getCapabilities().gv2
) {
649 capabilities
.add(Profile
.Capability
.gv2
);
651 if (profile
.getCapabilities().storage
) {
652 capabilities
.add(Profile
.Capability
.storage
);
655 final var newProfile
= new Profile(profileEntry
.getLastUpdateTimestamp(),
656 profile
.getGivenName(),
657 profile
.getFamilyName(),
659 profile
.getAboutEmoji(),
661 profile
.isUnrestrictedUnidentifiedAccess()
662 ? Profile
.UnidentifiedAccessMode
.UNRESTRICTED
663 : profile
.getUnidentifiedAccess() != null
664 ? Profile
.UnidentifiedAccessMode
.ENABLED
665 : Profile
.UnidentifiedAccessMode
.DISABLED
,
667 recipientStore
.storeProfile(recipientId
, newProfile
);
675 private boolean loadLegacyThreadStore(final JsonNode rootNode
) {
676 var threadStoreNode
= rootNode
.get("threadStore");
677 if (threadStoreNode
!= null && !threadStoreNode
.isNull()) {
678 var threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
679 // Migrate thread info to group and contact store
680 for (var thread
: threadStore
.getThreads()) {
681 if (thread
.id
== null || thread
.id
.isEmpty()) {
685 if (UuidUtil
.isUuid(thread
.id
) || thread
.id
.startsWith("+")) {
686 final var recipientId
= recipientStore
.resolveRecipient(thread
.id
);
687 var contact
= recipientStore
.getContact(recipientId
);
688 if (contact
!= null) {
689 recipientStore
.storeContact(recipientId
,
690 Contact
.newBuilder(contact
)
691 .withMessageExpirationTime(thread
.messageExpirationTime
)
695 var groupInfo
= groupStore
.getGroup(GroupId
.fromBase64(thread
.id
));
696 if (groupInfo
instanceof GroupInfoV1
) {
697 ((GroupInfoV1
) groupInfo
).messageExpirationTime
= thread
.messageExpirationTime
;
698 groupStore
.updateGroup(groupInfo
);
701 } catch (Exception e
) {
702 logger
.warn("Failed to read legacy thread info: {}", e
.getMessage());
711 private void saveStickerStore(StickerStore
.Storage storage
) {
712 this.stickerStoreStorage
= storage
;
716 private void saveGroupStore(GroupStore
.Storage storage
) {
717 this.groupStoreStorage
= storage
;
721 private void saveConfigurationStore(ConfigurationStore
.Storage storage
) {
722 this.configurationStoreStorage
= storage
;
726 private void save() {
727 synchronized (fileChannel
) {
728 var rootNode
= jsonProcessor
.createObjectNode();
729 rootNode
.put("version", CURRENT_STORAGE_VERSION
)
730 .put("username", account
)
731 .put("uuid", aci
== null ?
null : aci
.toString())
732 .put("deviceName", encryptedDeviceName
)
733 .put("deviceId", deviceId
)
734 .put("isMultiDevice", isMultiDevice
)
735 .put("lastReceiveTimestamp", lastReceiveTimestamp
)
736 .put("password", password
)
737 .put("registrationId", identityKeyStore
.getLocalRegistrationId())
738 .put("identityPrivateKey",
740 .encodeToString(identityKeyStore
.getIdentityKeyPair().getPrivateKey().serialize()))
743 .encodeToString(identityKeyStore
.getIdentityKeyPair().getPublicKey().serialize()))
744 .put("registrationLockPin", registrationLockPin
)
746 pinMasterKey
== null ?
null : Base64
.getEncoder().encodeToString(pinMasterKey
.serialize()))
748 storageKey
== null ?
null : Base64
.getEncoder().encodeToString(storageKey
.serialize()))
749 .put("storageManifestVersion", storageManifestVersion
== -1 ?
null : storageManifestVersion
)
750 .put("preKeyIdOffset", preKeyIdOffset
)
751 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
753 profileKey
== null ?
null : Base64
.getEncoder().encodeToString(profileKey
.serialize()))
754 .put("registered", registered
)
755 .putPOJO("groupStore", groupStoreStorage
)
756 .putPOJO("stickerStore", stickerStoreStorage
)
757 .putPOJO("configurationStore", configurationStoreStorage
);
759 try (var output
= new ByteArrayOutputStream()) {
760 // Write to memory first to prevent corrupting the file in case of serialization errors
761 jsonProcessor
.writeValue(output
, rootNode
);
762 var input
= new ByteArrayInputStream(output
.toByteArray());
763 fileChannel
.position(0);
764 input
.transferTo(Channels
.newOutputStream(fileChannel
));
765 fileChannel
.truncate(fileChannel
.position());
766 fileChannel
.force(false);
768 } catch (Exception e
) {
769 logger
.error("Error saving file: {}", e
.getMessage());
774 private static Pair
<FileChannel
, FileLock
> openFileChannel(File fileName
, boolean waitForLock
) throws IOException
{
775 var fileChannel
= new RandomAccessFile(fileName
, "rw").getChannel();
776 var lock
= fileChannel
.tryLock();
779 logger
.debug("Config file is in use by another instance.");
780 throw new IOException("Config file is in use by another instance.");
782 logger
.info("Config file is in use by another instance, waiting…");
783 lock
= fileChannel
.lock();
784 logger
.info("Config file lock acquired.");
786 return new Pair
<>(fileChannel
, lock
);
789 public void addPreKeys(List
<PreKeyRecord
> records
) {
790 for (var record : records
) {
791 if (preKeyIdOffset
!= record.getId()) {
792 logger
.error("Invalid pre key id {}, expected {}", record.getId(), preKeyIdOffset
);
793 throw new AssertionError("Invalid pre key id");
795 preKeyStore
.storePreKey(record.getId(), record);
796 preKeyIdOffset
= (preKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
801 public void addSignedPreKey(SignedPreKeyRecord
record) {
802 if (nextSignedPreKeyId
!= record.getId()) {
803 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), nextSignedPreKeyId
);
804 throw new AssertionError("Invalid signed pre key id");
806 signalProtocolStore
.storeSignedPreKey(record.getId(), record);
807 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
811 public SignalProtocolStore
getSignalProtocolStore() {
812 return signalProtocolStore
;
815 public SessionStore
getSessionStore() {
819 public IdentityKeyStore
getIdentityKeyStore() {
820 return identityKeyStore
;
823 public GroupStore
getGroupStore() {
827 public ContactsStore
getContactStore() {
828 return recipientStore
;
831 public RecipientStore
getRecipientStore() {
832 return recipientStore
;
835 public ProfileStore
getProfileStore() {
836 return recipientStore
;
839 public StickerStore
getStickerStore() {
843 public SenderKeyStore
getSenderKeyStore() {
844 return senderKeyStore
;
847 public ConfigurationStore
getConfigurationStore() {
848 return configurationStore
;
851 public MessageCache
getMessageCache() {
855 public String
getAccount() {
859 public ACI
getAci() {
863 public void setAci(final ACI aci
) {
868 public SignalServiceAddress
getSelfAddress() {
869 return new SignalServiceAddress(aci
, account
);
872 public RecipientId
getSelfRecipientId() {
873 return recipientStore
.resolveRecipientTrusted(new RecipientAddress(aci
== null ?
null : aci
.uuid(), account
));
876 public String
getEncryptedDeviceName() {
877 return encryptedDeviceName
;
880 public void setEncryptedDeviceName(final String encryptedDeviceName
) {
881 this.encryptedDeviceName
= encryptedDeviceName
;
885 public int getDeviceId() {
889 public boolean isMasterDevice() {
890 return deviceId
== SignalServiceAddress
.DEFAULT_DEVICE_ID
;
893 public IdentityKeyPair
getIdentityKeyPair() {
894 return signalProtocolStore
.getIdentityKeyPair();
897 public int getLocalRegistrationId() {
898 return signalProtocolStore
.getLocalRegistrationId();
901 public String
getPassword() {
905 private void setPassword(final String password
) {
906 this.password
= password
;
910 public void setRegistrationLockPin(final String registrationLockPin
, final MasterKey pinMasterKey
) {
911 this.registrationLockPin
= registrationLockPin
;
912 this.pinMasterKey
= pinMasterKey
;
916 public MasterKey
getPinMasterKey() {
920 public StorageKey
getStorageKey() {
921 if (pinMasterKey
!= null) {
922 return pinMasterKey
.deriveStorageServiceKey();
927 public void setStorageKey(final StorageKey storageKey
) {
928 if (storageKey
.equals(this.storageKey
)) {
931 this.storageKey
= storageKey
;
935 public long getStorageManifestVersion() {
936 return this.storageManifestVersion
;
939 public void setStorageManifestVersion(final long storageManifestVersion
) {
940 if (storageManifestVersion
== this.storageManifestVersion
) {
943 this.storageManifestVersion
= storageManifestVersion
;
947 public ProfileKey
getProfileKey() {
951 public void setProfileKey(final ProfileKey profileKey
) {
952 if (profileKey
.equals(this.profileKey
)) {
955 this.profileKey
= profileKey
;
959 public byte[] getSelfUnidentifiedAccessKey() {
960 return UnidentifiedAccess
.deriveAccessKeyFrom(getProfileKey());
963 public int getPreKeyIdOffset() {
964 return preKeyIdOffset
;
967 public int getNextSignedPreKeyId() {
968 return nextSignedPreKeyId
;
971 public boolean isRegistered() {
975 public void setRegistered(final boolean registered
) {
976 this.registered
= registered
;
980 public boolean isMultiDevice() {
981 return isMultiDevice
;
984 public void setMultiDevice(final boolean multiDevice
) {
985 if (isMultiDevice
== multiDevice
) {
988 isMultiDevice
= multiDevice
;
992 public long getLastReceiveTimestamp() {
993 return lastReceiveTimestamp
;
996 public void setLastReceiveTimestamp(final long lastReceiveTimestamp
) {
997 this.lastReceiveTimestamp
= lastReceiveTimestamp
;
1001 public boolean isUnrestrictedUnidentifiedAccess() {
1002 // TODO make configurable
1006 public boolean isDiscoverableByPhoneNumber() {
1007 return configurationStore
.getPhoneNumberUnlisted() == null || !configurationStore
.getPhoneNumberUnlisted();
1010 public void finishRegistration(final ACI aci
, final MasterKey masterKey
, final String pin
) {
1011 this.pinMasterKey
= masterKey
;
1012 this.storageManifestVersion
= -1;
1013 this.storageKey
= null;
1014 this.encryptedDeviceName
= null;
1015 this.deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1016 this.isMultiDevice
= false;
1017 this.registered
= true;
1019 this.registrationLockPin
= pin
;
1020 this.lastReceiveTimestamp
= 0;
1023 getSessionStore().archiveAllSessions();
1024 senderKeyStore
.deleteAll();
1025 final var recipientId
= getRecipientStore().resolveRecipientTrusted(getSelfAddress());
1026 final var publicKey
= getIdentityKeyPair().getPublicKey();
1027 getIdentityKeyStore().saveIdentity(recipientId
, publicKey
, new Date());
1028 getIdentityKeyStore().setIdentityTrustLevel(recipientId
, publicKey
, TrustLevel
.TRUSTED_VERIFIED
);
1032 public void close() throws IOException
{
1033 synchronized (fileChannel
) {
1036 } catch (ClosedChannelException ignored
) {
1038 fileChannel
.close();