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
.configuration
.ConfigurationStore
;
8 import org
.asamk
.signal
.manager
.groups
.GroupId
;
9 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactsStore
;
10 import org
.asamk
.signal
.manager
.storage
.contacts
.LegacyJsonContactsStore
;
11 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
12 import org
.asamk
.signal
.manager
.storage
.groups
.GroupStore
;
13 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityKeyStore
;
14 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
15 import org
.asamk
.signal
.manager
.storage
.messageCache
.MessageCache
;
16 import org
.asamk
.signal
.manager
.storage
.prekeys
.PreKeyStore
;
17 import org
.asamk
.signal
.manager
.storage
.prekeys
.SignedPreKeyStore
;
18 import org
.asamk
.signal
.manager
.storage
.profiles
.LegacyProfileStore
;
19 import org
.asamk
.signal
.manager
.storage
.profiles
.ProfileStore
;
20 import org
.asamk
.signal
.manager
.storage
.protocol
.LegacyJsonSignalProtocolStore
;
21 import org
.asamk
.signal
.manager
.storage
.protocol
.SignalProtocolStore
;
22 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
23 import org
.asamk
.signal
.manager
.storage
.recipients
.LegacyRecipientStore
;
24 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
25 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
26 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
27 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientStore
;
28 import org
.asamk
.signal
.manager
.storage
.senderKeys
.SenderKeyStore
;
29 import org
.asamk
.signal
.manager
.storage
.sessions
.SessionStore
;
30 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerStore
;
31 import org
.asamk
.signal
.manager
.storage
.threads
.LegacyJsonThreadStore
;
32 import org
.asamk
.signal
.manager
.util
.IOUtils
;
33 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
34 import org
.signal
.zkgroup
.InvalidInputException
;
35 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
36 import org
.slf4j
.Logger
;
37 import org
.slf4j
.LoggerFactory
;
38 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
39 import org
.whispersystems
.libsignal
.SignalProtocolAddress
;
40 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
41 import org
.whispersystems
.libsignal
.state
.SessionRecord
;
42 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
43 import org
.whispersystems
.libsignal
.util
.Medium
;
44 import org
.whispersystems
.libsignal
.util
.Pair
;
45 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
46 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
47 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
48 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
49 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
51 import java
.io
.ByteArrayInputStream
;
52 import java
.io
.ByteArrayOutputStream
;
53 import java
.io
.Closeable
;
55 import java
.io
.IOException
;
56 import java
.io
.RandomAccessFile
;
57 import java
.nio
.channels
.Channels
;
58 import java
.nio
.channels
.ClosedChannelException
;
59 import java
.nio
.channels
.FileChannel
;
60 import java
.nio
.channels
.FileLock
;
61 import java
.util
.Base64
;
62 import java
.util
.Date
;
63 import java
.util
.HashSet
;
64 import java
.util
.List
;
65 import java
.util
.UUID
;
67 public class SignalAccount
implements Closeable
{
69 private final static Logger logger
= LoggerFactory
.getLogger(SignalAccount
.class);
71 private static final int MINIMUM_STORAGE_VERSION
= 1;
72 private static final int CURRENT_STORAGE_VERSION
= 2;
74 private final ObjectMapper jsonProcessor
= Utils
.createStorageObjectMapper();
76 private final FileChannel fileChannel
;
77 private final FileLock lock
;
79 private String username
;
81 private String encryptedDeviceName
;
82 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
83 private boolean isMultiDevice
= false;
84 private String password
;
85 private String registrationLockPin
;
86 private MasterKey pinMasterKey
;
87 private StorageKey storageKey
;
88 private long storageManifestVersion
= -1;
89 private ProfileKey profileKey
;
90 private int preKeyIdOffset
;
91 private int nextSignedPreKeyId
;
92 private long lastReceiveTimestamp
= 0;
94 private boolean registered
= false;
96 private SignalProtocolStore signalProtocolStore
;
97 private PreKeyStore preKeyStore
;
98 private SignedPreKeyStore signedPreKeyStore
;
99 private SessionStore sessionStore
;
100 private IdentityKeyStore identityKeyStore
;
101 private SenderKeyStore senderKeyStore
;
102 private GroupStore groupStore
;
103 private GroupStore
.Storage groupStoreStorage
;
104 private RecipientStore recipientStore
;
105 private StickerStore stickerStore
;
106 private StickerStore
.Storage stickerStoreStorage
;
107 private ConfigurationStore configurationStore
;
108 private ConfigurationStore
.Storage configurationStoreStorage
;
110 private MessageCache messageCache
;
112 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
113 this.fileChannel
= fileChannel
;
117 public static SignalAccount
load(
118 File dataPath
, String username
, boolean waitForLock
, final TrustNewIdentity trustNewIdentity
119 ) throws IOException
{
120 final var fileName
= getFileName(dataPath
, username
);
121 final var pair
= openFileChannel(fileName
, waitForLock
);
123 var account
= new SignalAccount(pair
.first(), pair
.second());
124 account
.load(dataPath
, trustNewIdentity
);
125 account
.migrateLegacyConfigs();
127 if (!username
.equals(account
.getUsername())) {
128 throw new IOException("Username in account file doesn't match expected number: "
129 + account
.getUsername());
133 } catch (Throwable e
) {
134 pair
.second().close();
135 pair
.first().close();
140 public static SignalAccount
create(
143 IdentityKeyPair identityKey
,
145 ProfileKey profileKey
,
146 final TrustNewIdentity trustNewIdentity
147 ) throws IOException
{
148 IOUtils
.createPrivateDirectories(dataPath
);
149 var fileName
= getFileName(dataPath
, username
);
150 if (!fileName
.exists()) {
151 IOUtils
.createPrivateFile(fileName
);
154 final var pair
= openFileChannel(fileName
, true);
155 var account
= new SignalAccount(pair
.first(), pair
.second());
157 account
.username
= username
;
158 account
.profileKey
= profileKey
;
160 account
.initStores(dataPath
, identityKey
, registrationId
, trustNewIdentity
);
161 account
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, username
),
162 account
.recipientStore
,
163 account
::saveGroupStore
);
164 account
.stickerStore
= new StickerStore(account
::saveStickerStore
);
165 account
.configurationStore
= new ConfigurationStore(account
::saveConfigurationStore
);
167 account
.registered
= false;
169 account
.migrateLegacyConfigs();
175 private void initStores(
177 final IdentityKeyPair identityKey
,
178 final int registrationId
,
179 final TrustNewIdentity trustNewIdentity
180 ) throws IOException
{
181 recipientStore
= RecipientStore
.load(getRecipientsStoreFile(dataPath
, username
), this::mergeRecipients
);
183 preKeyStore
= new PreKeyStore(getPreKeysPath(dataPath
, username
));
184 signedPreKeyStore
= new SignedPreKeyStore(getSignedPreKeysPath(dataPath
, username
));
185 sessionStore
= new SessionStore(getSessionsPath(dataPath
, username
), recipientStore
);
186 identityKeyStore
= new IdentityKeyStore(getIdentitiesPath(dataPath
, username
),
191 senderKeyStore
= new SenderKeyStore(getSharedSenderKeysFile(dataPath
, username
),
192 getSenderKeysPath(dataPath
, username
),
193 recipientStore
::resolveRecipientAddress
,
195 signalProtocolStore
= new SignalProtocolStore(preKeyStore
,
200 this::isMultiDevice
);
202 messageCache
= new MessageCache(getMessageCachePath(dataPath
, username
));
205 public static SignalAccount
createOrUpdateLinkedAccount(
210 String encryptedDeviceName
,
212 IdentityKeyPair identityKey
,
214 ProfileKey profileKey
,
215 final TrustNewIdentity trustNewIdentity
216 ) throws IOException
{
217 IOUtils
.createPrivateDirectories(dataPath
);
218 var fileName
= getFileName(dataPath
, username
);
219 if (!fileName
.exists()) {
220 return createLinkedAccount(dataPath
,
232 final var account
= load(dataPath
, username
, true, trustNewIdentity
);
233 account
.setProvisioningData(username
, uuid
, password
, encryptedDeviceName
, deviceId
, profileKey
);
234 account
.recipientStore
.resolveRecipientTrusted(account
.getSelfAddress());
235 account
.sessionStore
.archiveAllSessions();
236 account
.senderKeyStore
.deleteAll();
237 account
.clearAllPreKeys();
241 private void clearAllPreKeys() {
242 this.preKeyIdOffset
= 0;
243 this.nextSignedPreKeyId
= 0;
244 this.preKeyStore
.removeAllPreKeys();
245 this.signedPreKeyStore
.removeAllSignedPreKeys();
249 private static SignalAccount
createLinkedAccount(
254 String encryptedDeviceName
,
256 IdentityKeyPair identityKey
,
258 ProfileKey profileKey
,
259 final TrustNewIdentity trustNewIdentity
260 ) throws IOException
{
261 var fileName
= getFileName(dataPath
, username
);
262 IOUtils
.createPrivateFile(fileName
);
264 final var pair
= openFileChannel(fileName
, true);
265 var account
= new SignalAccount(pair
.first(), pair
.second());
267 account
.setProvisioningData(username
, uuid
, password
, encryptedDeviceName
, deviceId
, profileKey
);
269 account
.initStores(dataPath
, identityKey
, registrationId
, trustNewIdentity
);
270 account
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, username
),
271 account
.recipientStore
,
272 account
::saveGroupStore
);
273 account
.stickerStore
= new StickerStore(account
::saveStickerStore
);
274 account
.configurationStore
= new ConfigurationStore(account
::saveConfigurationStore
);
276 account
.recipientStore
.resolveRecipientTrusted(account
.getSelfAddress());
277 account
.migrateLegacyConfigs();
283 private void setProvisioningData(
284 final String username
,
286 final String password
,
287 final String encryptedDeviceName
,
289 final ProfileKey profileKey
291 this.username
= username
;
293 this.password
= password
;
294 this.profileKey
= profileKey
;
295 this.encryptedDeviceName
= encryptedDeviceName
;
296 this.deviceId
= deviceId
;
297 this.registered
= true;
298 this.isMultiDevice
= true;
299 this.lastReceiveTimestamp
= 0;
300 this.pinMasterKey
= null;
301 this.storageManifestVersion
= -1;
302 this.storageKey
= null;
305 private void migrateLegacyConfigs() {
306 if (getPassword() == null) {
307 setPassword(KeyUtils
.createPassword());
310 if (getProfileKey() == null && isRegistered()) {
311 // Old config file, creating new profile key
312 setProfileKey(KeyUtils
.createProfileKey());
314 // Ensure our profile key is stored in profile store
315 getProfileStore().storeProfileKey(getSelfRecipientId(), getProfileKey());
318 private void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
319 sessionStore
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
320 identityKeyStore
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
321 messageCache
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
322 groupStore
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
323 senderKeyStore
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
326 public static File
getFileName(File dataPath
, String username
) {
327 return new File(dataPath
, username
);
330 private static File
getUserPath(final File dataPath
, final String username
) {
331 final var path
= new File(dataPath
, username
+ ".d");
333 IOUtils
.createPrivateDirectories(path
);
334 } catch (IOException e
) {
335 throw new AssertionError("Failed to create user path", e
);
340 private static File
getMessageCachePath(File dataPath
, String username
) {
341 return new File(getUserPath(dataPath
, username
), "msg-cache");
344 private static File
getGroupCachePath(File dataPath
, String username
) {
345 return new File(getUserPath(dataPath
, username
), "group-cache");
348 private static File
getPreKeysPath(File dataPath
, String username
) {
349 return new File(getUserPath(dataPath
, username
), "pre-keys");
352 private static File
getSignedPreKeysPath(File dataPath
, String username
) {
353 return new File(getUserPath(dataPath
, username
), "signed-pre-keys");
356 private static File
getIdentitiesPath(File dataPath
, String username
) {
357 return new File(getUserPath(dataPath
, username
), "identities");
360 private static File
getSessionsPath(File dataPath
, String username
) {
361 return new File(getUserPath(dataPath
, username
), "sessions");
364 private static File
getSenderKeysPath(File dataPath
, String username
) {
365 return new File(getUserPath(dataPath
, username
), "sender-keys");
368 private static File
getSharedSenderKeysFile(File dataPath
, String username
) {
369 return new File(getUserPath(dataPath
, username
), "shared-sender-keys-store");
372 private static File
getRecipientsStoreFile(File dataPath
, String username
) {
373 return new File(getUserPath(dataPath
, username
), "recipients-store");
376 public static boolean userExists(File dataPath
, String username
) {
377 if (username
== null) {
380 var f
= getFileName(dataPath
, username
);
381 return !(!f
.exists() || f
.isDirectory());
385 File dataPath
, final TrustNewIdentity trustNewIdentity
386 ) throws IOException
{
388 synchronized (fileChannel
) {
389 fileChannel
.position(0);
390 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
393 if (rootNode
.hasNonNull("version")) {
394 var accountVersion
= rootNode
.get("version").asInt(1);
395 if (accountVersion
> CURRENT_STORAGE_VERSION
) {
396 throw new IOException("Config file was created by a more recent version!");
397 } else if (accountVersion
< MINIMUM_STORAGE_VERSION
) {
398 throw new IOException("Config file was created by a no longer supported older version!");
402 username
= Utils
.getNotNullNode(rootNode
, "username").asText();
403 password
= Utils
.getNotNullNode(rootNode
, "password").asText();
404 registered
= Utils
.getNotNullNode(rootNode
, "registered").asBoolean();
405 if (rootNode
.hasNonNull("uuid")) {
407 uuid
= UUID
.fromString(rootNode
.get("uuid").asText());
408 } catch (IllegalArgumentException e
) {
409 throw new IOException("Config file contains an invalid uuid, needs to be a valid UUID", e
);
412 if (rootNode
.hasNonNull("deviceName")) {
413 encryptedDeviceName
= rootNode
.get("deviceName").asText();
415 if (rootNode
.hasNonNull("deviceId")) {
416 deviceId
= rootNode
.get("deviceId").asInt();
418 if (rootNode
.hasNonNull("isMultiDevice")) {
419 isMultiDevice
= rootNode
.get("isMultiDevice").asBoolean();
421 if (rootNode
.hasNonNull("lastReceiveTimestamp")) {
422 lastReceiveTimestamp
= rootNode
.get("lastReceiveTimestamp").asLong();
424 int registrationId
= 0;
425 if (rootNode
.hasNonNull("registrationId")) {
426 registrationId
= rootNode
.get("registrationId").asInt();
428 IdentityKeyPair identityKeyPair
= null;
429 if (rootNode
.hasNonNull("identityPrivateKey") && rootNode
.hasNonNull("identityKey")) {
430 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityKey").asText());
431 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityPrivateKey").asText());
432 identityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
435 if (rootNode
.hasNonNull("registrationLockPin")) {
436 registrationLockPin
= rootNode
.get("registrationLockPin").asText();
438 if (rootNode
.hasNonNull("pinMasterKey")) {
439 pinMasterKey
= new MasterKey(Base64
.getDecoder().decode(rootNode
.get("pinMasterKey").asText()));
441 if (rootNode
.hasNonNull("storageKey")) {
442 storageKey
= new StorageKey(Base64
.getDecoder().decode(rootNode
.get("storageKey").asText()));
444 if (rootNode
.hasNonNull("storageManifestVersion")) {
445 storageManifestVersion
= rootNode
.get("storageManifestVersion").asLong();
447 if (rootNode
.hasNonNull("preKeyIdOffset")) {
448 preKeyIdOffset
= rootNode
.get("preKeyIdOffset").asInt(0);
452 if (rootNode
.hasNonNull("nextSignedPreKeyId")) {
453 nextSignedPreKeyId
= rootNode
.get("nextSignedPreKeyId").asInt();
455 nextSignedPreKeyId
= 0;
457 if (rootNode
.hasNonNull("profileKey")) {
459 profileKey
= new ProfileKey(Base64
.getDecoder().decode(rootNode
.get("profileKey").asText()));
460 } catch (InvalidInputException e
) {
461 throw new IOException(
462 "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
467 var migratedLegacyConfig
= false;
468 final var legacySignalProtocolStore
= rootNode
.hasNonNull("axolotlStore")
469 ? jsonProcessor
.convertValue(Utils
.getNotNullNode(rootNode
, "axolotlStore"),
470 LegacyJsonSignalProtocolStore
.class)
472 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
473 identityKeyPair
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentityKeyPair();
474 registrationId
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getLocalRegistrationId();
475 migratedLegacyConfig
= true;
478 initStores(dataPath
, identityKeyPair
, registrationId
, trustNewIdentity
);
480 migratedLegacyConfig
= loadLegacyStores(rootNode
, legacySignalProtocolStore
) || migratedLegacyConfig
;
482 if (rootNode
.hasNonNull("groupStore")) {
483 groupStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("groupStore"), GroupStore
.Storage
.class);
484 groupStore
= GroupStore
.fromStorage(groupStoreStorage
,
485 getGroupCachePath(dataPath
, username
),
487 this::saveGroupStore
);
489 groupStore
= new GroupStore(getGroupCachePath(dataPath
, username
), recipientStore
, this::saveGroupStore
);
492 if (rootNode
.hasNonNull("stickerStore")) {
493 stickerStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("stickerStore"), StickerStore
.Storage
.class);
494 stickerStore
= StickerStore
.fromStorage(stickerStoreStorage
, this::saveStickerStore
);
496 stickerStore
= new StickerStore(this::saveStickerStore
);
499 if (rootNode
.hasNonNull("configurationStore")) {
500 configurationStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("configurationStore"),
501 ConfigurationStore
.Storage
.class);
502 configurationStore
= ConfigurationStore
.fromStorage(configurationStoreStorage
,
503 this::saveConfigurationStore
);
505 configurationStore
= new ConfigurationStore(this::saveConfigurationStore
);
508 migratedLegacyConfig
= loadLegacyThreadStore(rootNode
) || migratedLegacyConfig
;
510 if (migratedLegacyConfig
) {
515 private boolean loadLegacyStores(
516 final JsonNode rootNode
, final LegacyJsonSignalProtocolStore legacySignalProtocolStore
518 var migrated
= false;
519 var legacyRecipientStoreNode
= rootNode
.get("recipientStore");
520 if (legacyRecipientStoreNode
!= null) {
521 logger
.debug("Migrating legacy recipient store.");
522 var legacyRecipientStore
= jsonProcessor
.convertValue(legacyRecipientStoreNode
, LegacyRecipientStore
.class);
523 if (legacyRecipientStore
!= null) {
524 recipientStore
.resolveRecipientsTrusted(legacyRecipientStore
.getAddresses());
526 recipientStore
.resolveRecipientTrusted(getSelfAddress());
530 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyPreKeyStore() != null) {
531 logger
.debug("Migrating legacy pre key store.");
532 for (var entry
: legacySignalProtocolStore
.getLegacyPreKeyStore().getPreKeys().entrySet()) {
534 preKeyStore
.storePreKey(entry
.getKey(), new PreKeyRecord(entry
.getValue()));
535 } catch (IOException e
) {
536 logger
.warn("Failed to migrate pre key, ignoring", e
);
542 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySignedPreKeyStore() != null) {
543 logger
.debug("Migrating legacy signed pre key store.");
544 for (var entry
: legacySignalProtocolStore
.getLegacySignedPreKeyStore().getSignedPreKeys().entrySet()) {
546 signedPreKeyStore
.storeSignedPreKey(entry
.getKey(), new SignedPreKeyRecord(entry
.getValue()));
547 } catch (IOException e
) {
548 logger
.warn("Failed to migrate signed pre key, ignoring", e
);
554 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySessionStore() != null) {
555 logger
.debug("Migrating legacy session store.");
556 for (var session
: legacySignalProtocolStore
.getLegacySessionStore().getSessions()) {
558 sessionStore
.storeSession(new SignalProtocolAddress(session
.address
.getIdentifier(),
559 session
.deviceId
), new SessionRecord(session
.sessionRecord
));
560 } catch (IOException e
) {
561 logger
.warn("Failed to migrate session, ignoring", e
);
567 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
568 logger
.debug("Migrating legacy identity session store.");
569 for (var identity
: legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentities()) {
570 RecipientId recipientId
= recipientStore
.resolveRecipientTrusted(identity
.getAddress());
571 identityKeyStore
.saveIdentity(recipientId
, identity
.getIdentityKey(), identity
.getDateAdded());
572 identityKeyStore
.setIdentityTrustLevel(recipientId
,
573 identity
.getIdentityKey(),
574 identity
.getTrustLevel());
579 if (rootNode
.hasNonNull("contactStore")) {
580 logger
.debug("Migrating legacy contact store.");
581 final var contactStoreNode
= rootNode
.get("contactStore");
582 final var contactStore
= jsonProcessor
.convertValue(contactStoreNode
, LegacyJsonContactsStore
.class);
583 for (var contact
: contactStore
.getContacts()) {
584 final var recipientId
= recipientStore
.resolveRecipientTrusted(contact
.getAddress());
585 recipientStore
.storeContact(recipientId
,
586 new Contact(contact
.name
,
588 contact
.messageExpirationTime
,
592 // Store profile keys only in profile store
593 var profileKeyString
= contact
.profileKey
;
594 if (profileKeyString
!= null) {
595 final ProfileKey profileKey
;
597 profileKey
= new ProfileKey(Base64
.getDecoder().decode(profileKeyString
));
598 getProfileStore().storeProfileKey(recipientId
, profileKey
);
599 } catch (InvalidInputException e
) {
600 logger
.warn("Failed to parse legacy contact profile key: {}", e
.getMessage());
607 if (rootNode
.hasNonNull("profileStore")) {
608 logger
.debug("Migrating legacy profile store.");
609 var profileStoreNode
= rootNode
.get("profileStore");
610 final var legacyProfileStore
= jsonProcessor
.convertValue(profileStoreNode
, LegacyProfileStore
.class);
611 for (var profileEntry
: legacyProfileStore
.getProfileEntries()) {
612 var recipientId
= recipientStore
.resolveRecipient(profileEntry
.getAddress());
613 recipientStore
.storeProfileKeyCredential(recipientId
, profileEntry
.getProfileKeyCredential());
614 recipientStore
.storeProfileKey(recipientId
, profileEntry
.getProfileKey());
615 final var profile
= profileEntry
.getProfile();
616 if (profile
!= null) {
617 final var capabilities
= new HashSet
<Profile
.Capability
>();
618 if (profile
.getCapabilities() != null) {
619 if (profile
.getCapabilities().gv1Migration
) {
620 capabilities
.add(Profile
.Capability
.gv1Migration
);
622 if (profile
.getCapabilities().gv2
) {
623 capabilities
.add(Profile
.Capability
.gv2
);
625 if (profile
.getCapabilities().storage
) {
626 capabilities
.add(Profile
.Capability
.storage
);
629 final var newProfile
= new Profile(profileEntry
.getLastUpdateTimestamp(),
630 profile
.getGivenName(),
631 profile
.getFamilyName(),
633 profile
.getAboutEmoji(),
635 profile
.isUnrestrictedUnidentifiedAccess()
636 ? Profile
.UnidentifiedAccessMode
.UNRESTRICTED
637 : profile
.getUnidentifiedAccess() != null
638 ? Profile
.UnidentifiedAccessMode
.ENABLED
639 : Profile
.UnidentifiedAccessMode
.DISABLED
,
641 recipientStore
.storeProfile(recipientId
, newProfile
);
649 private boolean loadLegacyThreadStore(final JsonNode rootNode
) {
650 var threadStoreNode
= rootNode
.get("threadStore");
651 if (threadStoreNode
!= null && !threadStoreNode
.isNull()) {
652 var threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
653 // Migrate thread info to group and contact store
654 for (var thread
: threadStore
.getThreads()) {
655 if (thread
.id
== null || thread
.id
.isEmpty()) {
659 if (UuidUtil
.isUuid(thread
.id
) || thread
.id
.startsWith("+")) {
660 final var recipientId
= recipientStore
.resolveRecipient(thread
.id
);
661 var contact
= recipientStore
.getContact(recipientId
);
662 if (contact
!= null) {
663 recipientStore
.storeContact(recipientId
,
664 Contact
.newBuilder(contact
)
665 .withMessageExpirationTime(thread
.messageExpirationTime
)
669 var groupInfo
= groupStore
.getGroup(GroupId
.fromBase64(thread
.id
));
670 if (groupInfo
instanceof GroupInfoV1
) {
671 ((GroupInfoV1
) groupInfo
).messageExpirationTime
= thread
.messageExpirationTime
;
672 groupStore
.updateGroup(groupInfo
);
675 } catch (Exception e
) {
676 logger
.warn("Failed to read legacy thread info: {}", e
.getMessage());
685 private void saveStickerStore(StickerStore
.Storage storage
) {
686 this.stickerStoreStorage
= storage
;
690 private void saveGroupStore(GroupStore
.Storage storage
) {
691 this.groupStoreStorage
= storage
;
695 private void saveConfigurationStore(ConfigurationStore
.Storage storage
) {
696 this.configurationStoreStorage
= storage
;
700 private void save() {
701 synchronized (fileChannel
) {
702 var rootNode
= jsonProcessor
.createObjectNode();
703 rootNode
.put("version", CURRENT_STORAGE_VERSION
)
704 .put("username", username
)
705 .put("uuid", uuid
== null ?
null : uuid
.toString())
706 .put("deviceName", encryptedDeviceName
)
707 .put("deviceId", deviceId
)
708 .put("isMultiDevice", isMultiDevice
)
709 .put("lastReceiveTimestamp", lastReceiveTimestamp
)
710 .put("password", password
)
711 .put("registrationId", identityKeyStore
.getLocalRegistrationId())
712 .put("identityPrivateKey",
714 .encodeToString(identityKeyStore
.getIdentityKeyPair().getPrivateKey().serialize()))
717 .encodeToString(identityKeyStore
.getIdentityKeyPair().getPublicKey().serialize()))
718 .put("registrationLockPin", registrationLockPin
)
720 pinMasterKey
== null ?
null : Base64
.getEncoder().encodeToString(pinMasterKey
.serialize()))
722 storageKey
== null ?
null : Base64
.getEncoder().encodeToString(storageKey
.serialize()))
723 .put("storageManifestVersion", storageManifestVersion
== -1 ?
null : storageManifestVersion
)
724 .put("preKeyIdOffset", preKeyIdOffset
)
725 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
727 profileKey
== null ?
null : Base64
.getEncoder().encodeToString(profileKey
.serialize()))
728 .put("registered", registered
)
729 .putPOJO("groupStore", groupStoreStorage
)
730 .putPOJO("stickerStore", stickerStoreStorage
)
731 .putPOJO("configurationStore", configurationStoreStorage
);
733 try (var output
= new ByteArrayOutputStream()) {
734 // Write to memory first to prevent corrupting the file in case of serialization errors
735 jsonProcessor
.writeValue(output
, rootNode
);
736 var input
= new ByteArrayInputStream(output
.toByteArray());
737 fileChannel
.position(0);
738 input
.transferTo(Channels
.newOutputStream(fileChannel
));
739 fileChannel
.truncate(fileChannel
.position());
740 fileChannel
.force(false);
742 } catch (Exception e
) {
743 logger
.error("Error saving file: {}", e
.getMessage());
748 private static Pair
<FileChannel
, FileLock
> openFileChannel(File fileName
, boolean waitForLock
) throws IOException
{
749 var fileChannel
= new RandomAccessFile(fileName
, "rw").getChannel();
750 var lock
= fileChannel
.tryLock();
753 logger
.debug("Config file is in use by another instance.");
754 throw new IOException("Config file is in use by another instance.");
756 logger
.info("Config file is in use by another instance, waiting…");
757 lock
= fileChannel
.lock();
758 logger
.info("Config file lock acquired.");
760 return new Pair
<>(fileChannel
, lock
);
763 public void addPreKeys(List
<PreKeyRecord
> records
) {
764 for (var record : records
) {
765 if (preKeyIdOffset
!= record.getId()) {
766 logger
.error("Invalid pre key id {}, expected {}", record.getId(), preKeyIdOffset
);
767 throw new AssertionError("Invalid pre key id");
769 preKeyStore
.storePreKey(record.getId(), record);
770 preKeyIdOffset
= (preKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
775 public void addSignedPreKey(SignedPreKeyRecord
record) {
776 if (nextSignedPreKeyId
!= record.getId()) {
777 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), nextSignedPreKeyId
);
778 throw new AssertionError("Invalid signed pre key id");
780 signalProtocolStore
.storeSignedPreKey(record.getId(), record);
781 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
785 public SignalProtocolStore
getSignalProtocolStore() {
786 return signalProtocolStore
;
789 public SessionStore
getSessionStore() {
793 public IdentityKeyStore
getIdentityKeyStore() {
794 return identityKeyStore
;
797 public GroupStore
getGroupStore() {
801 public ContactsStore
getContactStore() {
802 return recipientStore
;
805 public RecipientStore
getRecipientStore() {
806 return recipientStore
;
809 public ProfileStore
getProfileStore() {
810 return recipientStore
;
813 public StickerStore
getStickerStore() {
817 public SenderKeyStore
getSenderKeyStore() {
818 return senderKeyStore
;
821 public ConfigurationStore
getConfigurationStore() {
822 return configurationStore
;
825 public MessageCache
getMessageCache() {
829 public String
getUsername() {
833 public UUID
getUuid() {
837 public void setUuid(final UUID uuid
) {
842 public SignalServiceAddress
getSelfAddress() {
843 return new SignalServiceAddress(uuid
, username
);
846 public RecipientId
getSelfRecipientId() {
847 return recipientStore
.resolveRecipientTrusted(new RecipientAddress(uuid
, username
));
850 public String
getEncryptedDeviceName() {
851 return encryptedDeviceName
;
854 public void setEncryptedDeviceName(final String encryptedDeviceName
) {
855 this.encryptedDeviceName
= encryptedDeviceName
;
859 public int getDeviceId() {
863 public boolean isMasterDevice() {
864 return deviceId
== SignalServiceAddress
.DEFAULT_DEVICE_ID
;
867 public IdentityKeyPair
getIdentityKeyPair() {
868 return signalProtocolStore
.getIdentityKeyPair();
871 public int getLocalRegistrationId() {
872 return signalProtocolStore
.getLocalRegistrationId();
875 public String
getPassword() {
879 private void setPassword(final String password
) {
880 this.password
= password
;
884 public String
getRegistrationLockPin() {
885 return registrationLockPin
;
888 public void setRegistrationLockPin(final String registrationLockPin
, final MasterKey pinMasterKey
) {
889 this.registrationLockPin
= registrationLockPin
;
890 this.pinMasterKey
= pinMasterKey
;
894 public MasterKey
getPinMasterKey() {
898 public StorageKey
getStorageKey() {
899 if (pinMasterKey
!= null) {
900 return pinMasterKey
.deriveStorageServiceKey();
905 public void setStorageKey(final StorageKey storageKey
) {
906 if (storageKey
.equals(this.storageKey
)) {
909 this.storageKey
= storageKey
;
913 public long getStorageManifestVersion() {
914 return this.storageManifestVersion
;
917 public void setStorageManifestVersion(final long storageManifestVersion
) {
918 if (storageManifestVersion
== this.storageManifestVersion
) {
921 this.storageManifestVersion
= storageManifestVersion
;
925 public ProfileKey
getProfileKey() {
929 public void setProfileKey(final ProfileKey profileKey
) {
930 if (profileKey
.equals(this.profileKey
)) {
933 this.profileKey
= profileKey
;
937 public byte[] getSelfUnidentifiedAccessKey() {
938 return UnidentifiedAccess
.deriveAccessKeyFrom(getProfileKey());
941 public int getPreKeyIdOffset() {
942 return preKeyIdOffset
;
945 public int getNextSignedPreKeyId() {
946 return nextSignedPreKeyId
;
949 public boolean isRegistered() {
953 public void setRegistered(final boolean registered
) {
954 this.registered
= registered
;
958 public boolean isMultiDevice() {
959 return isMultiDevice
;
962 public void setMultiDevice(final boolean multiDevice
) {
963 if (isMultiDevice
== multiDevice
) {
966 isMultiDevice
= multiDevice
;
970 public long getLastReceiveTimestamp() {
971 return lastReceiveTimestamp
;
974 public void setLastReceiveTimestamp(final long lastReceiveTimestamp
) {
975 this.lastReceiveTimestamp
= lastReceiveTimestamp
;
979 public boolean isUnrestrictedUnidentifiedAccess() {
980 // TODO make configurable
984 public boolean isDiscoverableByPhoneNumber() {
985 // TODO make configurable
989 public boolean isPhoneNumberShared() {
990 // TODO make configurable
994 public void finishRegistration(final UUID uuid
, final MasterKey masterKey
, final String pin
) {
995 this.pinMasterKey
= masterKey
;
996 this.storageManifestVersion
= -1;
997 this.storageKey
= null;
998 this.encryptedDeviceName
= null;
999 this.deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1000 this.isMultiDevice
= false;
1001 this.registered
= true;
1003 this.registrationLockPin
= pin
;
1004 this.lastReceiveTimestamp
= 0;
1007 getSessionStore().archiveAllSessions();
1008 senderKeyStore
.deleteAll();
1009 final var recipientId
= getRecipientStore().resolveRecipientTrusted(getSelfAddress());
1010 final var publicKey
= getIdentityKeyPair().getPublicKey();
1011 getIdentityKeyStore().saveIdentity(recipientId
, publicKey
, new Date());
1012 getIdentityKeyStore().setIdentityTrustLevel(recipientId
, publicKey
, TrustLevel
.TRUSTED_VERIFIED
);
1016 public void close() throws IOException
{
1017 synchronized (fileChannel
) {
1020 } catch (ClosedChannelException ignored
) {
1022 fileChannel
.close();