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
.groups
.GroupId
;
8 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactsStore
;
9 import org
.asamk
.signal
.manager
.storage
.contacts
.LegacyJsonContactsStore
;
10 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
11 import org
.asamk
.signal
.manager
.storage
.groups
.GroupStore
;
12 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityKeyStore
;
13 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
14 import org
.asamk
.signal
.manager
.storage
.messageCache
.MessageCache
;
15 import org
.asamk
.signal
.manager
.storage
.prekeys
.PreKeyStore
;
16 import org
.asamk
.signal
.manager
.storage
.prekeys
.SignedPreKeyStore
;
17 import org
.asamk
.signal
.manager
.storage
.profiles
.LegacyProfileStore
;
18 import org
.asamk
.signal
.manager
.storage
.profiles
.ProfileStore
;
19 import org
.asamk
.signal
.manager
.storage
.protocol
.LegacyJsonSignalProtocolStore
;
20 import org
.asamk
.signal
.manager
.storage
.protocol
.SignalProtocolStore
;
21 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
22 import org
.asamk
.signal
.manager
.storage
.recipients
.LegacyRecipientStore
;
23 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
24 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
25 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientStore
;
26 import org
.asamk
.signal
.manager
.storage
.sessions
.SessionStore
;
27 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerStore
;
28 import org
.asamk
.signal
.manager
.storage
.threads
.LegacyJsonThreadStore
;
29 import org
.asamk
.signal
.manager
.util
.IOUtils
;
30 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
31 import org
.signal
.zkgroup
.InvalidInputException
;
32 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
33 import org
.slf4j
.Logger
;
34 import org
.slf4j
.LoggerFactory
;
35 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
36 import org
.whispersystems
.libsignal
.SignalProtocolAddress
;
37 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
38 import org
.whispersystems
.libsignal
.state
.SessionRecord
;
39 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
40 import org
.whispersystems
.libsignal
.util
.Medium
;
41 import org
.whispersystems
.libsignal
.util
.Pair
;
42 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
43 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
44 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
45 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
46 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
48 import java
.io
.ByteArrayInputStream
;
49 import java
.io
.ByteArrayOutputStream
;
50 import java
.io
.Closeable
;
52 import java
.io
.IOException
;
53 import java
.io
.RandomAccessFile
;
54 import java
.nio
.channels
.Channels
;
55 import java
.nio
.channels
.ClosedChannelException
;
56 import java
.nio
.channels
.FileChannel
;
57 import java
.nio
.channels
.FileLock
;
58 import java
.util
.Base64
;
59 import java
.util
.Date
;
60 import java
.util
.HashSet
;
61 import java
.util
.List
;
62 import java
.util
.UUID
;
64 public class SignalAccount
implements Closeable
{
66 private final static Logger logger
= LoggerFactory
.getLogger(SignalAccount
.class);
68 private static final int MINIMUM_STORAGE_VERSION
= 1;
69 private static final int CURRENT_STORAGE_VERSION
= 2;
71 private final ObjectMapper jsonProcessor
= Utils
.createStorageObjectMapper();
73 private final FileChannel fileChannel
;
74 private final FileLock lock
;
76 private String username
;
78 private String encryptedDeviceName
;
79 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
80 private boolean isMultiDevice
= false;
81 private String password
;
82 private String registrationLockPin
;
83 private MasterKey pinMasterKey
;
84 private StorageKey storageKey
;
85 private ProfileKey profileKey
;
86 private int preKeyIdOffset
;
87 private int nextSignedPreKeyId
;
88 private long lastReceiveTimestamp
= 0;
90 private boolean registered
= false;
92 private SignalProtocolStore signalProtocolStore
;
93 private PreKeyStore preKeyStore
;
94 private SignedPreKeyStore signedPreKeyStore
;
95 private SessionStore sessionStore
;
96 private IdentityKeyStore identityKeyStore
;
97 private GroupStore groupStore
;
98 private GroupStore
.Storage groupStoreStorage
;
99 private RecipientStore recipientStore
;
100 private StickerStore stickerStore
;
101 private StickerStore
.Storage stickerStoreStorage
;
103 private MessageCache messageCache
;
105 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
106 this.fileChannel
= fileChannel
;
110 public static SignalAccount
load(
111 File dataPath
, String username
, boolean waitForLock
, final TrustNewIdentity trustNewIdentity
112 ) throws IOException
{
113 final var fileName
= getFileName(dataPath
, username
);
114 final var pair
= openFileChannel(fileName
, waitForLock
);
116 var account
= new SignalAccount(pair
.first(), pair
.second());
117 account
.load(dataPath
, trustNewIdentity
);
118 account
.migrateLegacyConfigs();
120 if (!username
.equals(account
.getUsername())) {
121 throw new IOException("Username in account file doesn't match expected number: "
122 + account
.getUsername());
126 } catch (Throwable e
) {
127 pair
.second().close();
128 pair
.first().close();
133 public static SignalAccount
create(
136 IdentityKeyPair identityKey
,
138 ProfileKey profileKey
,
139 final TrustNewIdentity trustNewIdentity
140 ) throws IOException
{
141 IOUtils
.createPrivateDirectories(dataPath
);
142 var fileName
= getFileName(dataPath
, username
);
143 if (!fileName
.exists()) {
144 IOUtils
.createPrivateFile(fileName
);
147 final var pair
= openFileChannel(fileName
, true);
148 var account
= new SignalAccount(pair
.first(), pair
.second());
150 account
.username
= username
;
151 account
.profileKey
= profileKey
;
153 account
.initStores(dataPath
, identityKey
, registrationId
, trustNewIdentity
);
154 account
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, username
),
155 account
.recipientStore
,
156 account
::saveGroupStore
);
157 account
.stickerStore
= new StickerStore(account
::saveStickerStore
);
159 account
.registered
= false;
161 account
.migrateLegacyConfigs();
167 private void initStores(
169 final IdentityKeyPair identityKey
,
170 final int registrationId
,
171 final TrustNewIdentity trustNewIdentity
172 ) throws IOException
{
173 recipientStore
= RecipientStore
.load(getRecipientsStoreFile(dataPath
, username
), this::mergeRecipients
);
175 preKeyStore
= new PreKeyStore(getPreKeysPath(dataPath
, username
));
176 signedPreKeyStore
= new SignedPreKeyStore(getSignedPreKeysPath(dataPath
, username
));
177 sessionStore
= new SessionStore(getSessionsPath(dataPath
, username
), recipientStore
);
178 identityKeyStore
= new IdentityKeyStore(getIdentitiesPath(dataPath
, username
),
183 signalProtocolStore
= new SignalProtocolStore(preKeyStore
,
187 this::isMultiDevice
);
189 messageCache
= new MessageCache(getMessageCachePath(dataPath
, username
));
192 public static SignalAccount
createOrUpdateLinkedAccount(
197 String encryptedDeviceName
,
199 IdentityKeyPair identityKey
,
201 ProfileKey profileKey
,
202 final TrustNewIdentity trustNewIdentity
203 ) throws IOException
{
204 IOUtils
.createPrivateDirectories(dataPath
);
205 var fileName
= getFileName(dataPath
, username
);
206 if (!fileName
.exists()) {
207 return createLinkedAccount(dataPath
,
219 final var account
= load(dataPath
, username
, true, trustNewIdentity
);
220 account
.setProvisioningData(username
, uuid
, password
, encryptedDeviceName
, deviceId
, profileKey
);
221 account
.recipientStore
.resolveRecipientTrusted(account
.getSelfAddress());
222 account
.sessionStore
.archiveAllSessions();
223 account
.clearAllPreKeys();
227 private void clearAllPreKeys() {
228 this.preKeyIdOffset
= 0;
229 this.nextSignedPreKeyId
= 0;
230 this.preKeyStore
.removeAllPreKeys();
231 this.signedPreKeyStore
.removeAllSignedPreKeys();
235 private static SignalAccount
createLinkedAccount(
240 String encryptedDeviceName
,
242 IdentityKeyPair identityKey
,
244 ProfileKey profileKey
,
245 final TrustNewIdentity trustNewIdentity
246 ) throws IOException
{
247 var fileName
= getFileName(dataPath
, username
);
248 IOUtils
.createPrivateFile(fileName
);
250 final var pair
= openFileChannel(fileName
, true);
251 var account
= new SignalAccount(pair
.first(), pair
.second());
253 account
.setProvisioningData(username
, uuid
, password
, encryptedDeviceName
, deviceId
, profileKey
);
255 account
.initStores(dataPath
, identityKey
, registrationId
, trustNewIdentity
);
256 account
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, username
),
257 account
.recipientStore
,
258 account
::saveGroupStore
);
259 account
.stickerStore
= new StickerStore(account
::saveStickerStore
);
261 account
.recipientStore
.resolveRecipientTrusted(account
.getSelfAddress());
262 account
.migrateLegacyConfigs();
268 private void setProvisioningData(
269 final String username
,
271 final String password
,
272 final String encryptedDeviceName
,
274 final ProfileKey profileKey
276 this.username
= username
;
278 this.password
= password
;
279 this.profileKey
= profileKey
;
280 this.encryptedDeviceName
= encryptedDeviceName
;
281 this.deviceId
= deviceId
;
282 this.registered
= true;
283 this.isMultiDevice
= true;
284 this.lastReceiveTimestamp
= 0;
287 private void migrateLegacyConfigs() {
288 if (getPassword() == null) {
289 setPassword(KeyUtils
.createPassword());
292 if (getProfileKey() == null && isRegistered()) {
293 // Old config file, creating new profile key
294 setProfileKey(KeyUtils
.createProfileKey());
296 // Ensure our profile key is stored in profile store
297 getProfileStore().storeProfileKey(getSelfRecipientId(), getProfileKey());
300 private void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
301 sessionStore
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
302 identityKeyStore
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
303 messageCache
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
304 groupStore
.mergeRecipients(recipientId
, toBeMergedRecipientId
);
307 public static File
getFileName(File dataPath
, String username
) {
308 return new File(dataPath
, username
);
311 private static File
getUserPath(final File dataPath
, final String username
) {
312 final var path
= new File(dataPath
, username
+ ".d");
314 IOUtils
.createPrivateDirectories(path
);
315 } catch (IOException e
) {
316 throw new AssertionError("Failed to create user path", e
);
321 private static File
getMessageCachePath(File dataPath
, String username
) {
322 return new File(getUserPath(dataPath
, username
), "msg-cache");
325 private static File
getGroupCachePath(File dataPath
, String username
) {
326 return new File(getUserPath(dataPath
, username
), "group-cache");
329 private static File
getPreKeysPath(File dataPath
, String username
) {
330 return new File(getUserPath(dataPath
, username
), "pre-keys");
333 private static File
getSignedPreKeysPath(File dataPath
, String username
) {
334 return new File(getUserPath(dataPath
, username
), "signed-pre-keys");
337 private static File
getIdentitiesPath(File dataPath
, String username
) {
338 return new File(getUserPath(dataPath
, username
), "identities");
341 private static File
getSessionsPath(File dataPath
, String username
) {
342 return new File(getUserPath(dataPath
, username
), "sessions");
345 private static File
getRecipientsStoreFile(File dataPath
, String username
) {
346 return new File(getUserPath(dataPath
, username
), "recipients-store");
349 public static boolean userExists(File dataPath
, String username
) {
350 if (username
== null) {
353 var f
= getFileName(dataPath
, username
);
354 return !(!f
.exists() || f
.isDirectory());
358 File dataPath
, final TrustNewIdentity trustNewIdentity
359 ) throws IOException
{
361 synchronized (fileChannel
) {
362 fileChannel
.position(0);
363 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
366 if (rootNode
.hasNonNull("version")) {
367 var accountVersion
= rootNode
.get("version").asInt(1);
368 if (accountVersion
> CURRENT_STORAGE_VERSION
) {
369 throw new IOException("Config file was created by a more recent version!");
370 } else if (accountVersion
< MINIMUM_STORAGE_VERSION
) {
371 throw new IOException("Config file was created by a no longer supported older version!");
375 username
= Utils
.getNotNullNode(rootNode
, "username").asText();
376 password
= Utils
.getNotNullNode(rootNode
, "password").asText();
377 registered
= Utils
.getNotNullNode(rootNode
, "registered").asBoolean();
378 if (rootNode
.hasNonNull("uuid")) {
380 uuid
= UUID
.fromString(rootNode
.get("uuid").asText());
381 } catch (IllegalArgumentException e
) {
382 throw new IOException("Config file contains an invalid uuid, needs to be a valid UUID", e
);
385 if (rootNode
.hasNonNull("deviceName")) {
386 encryptedDeviceName
= rootNode
.get("deviceName").asText();
388 if (rootNode
.hasNonNull("deviceId")) {
389 deviceId
= rootNode
.get("deviceId").asInt();
391 if (rootNode
.hasNonNull("isMultiDevice")) {
392 isMultiDevice
= rootNode
.get("isMultiDevice").asBoolean();
394 if (rootNode
.hasNonNull("lastReceiveTimestamp")) {
395 lastReceiveTimestamp
= rootNode
.get("lastReceiveTimestamp").asLong();
397 int registrationId
= 0;
398 if (rootNode
.hasNonNull("registrationId")) {
399 registrationId
= rootNode
.get("registrationId").asInt();
401 IdentityKeyPair identityKeyPair
= null;
402 if (rootNode
.hasNonNull("identityPrivateKey") && rootNode
.hasNonNull("identityKey")) {
403 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityKey").asText());
404 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityPrivateKey").asText());
405 identityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
408 if (rootNode
.hasNonNull("registrationLockPin")) {
409 registrationLockPin
= rootNode
.get("registrationLockPin").asText();
411 if (rootNode
.hasNonNull("pinMasterKey")) {
412 pinMasterKey
= new MasterKey(Base64
.getDecoder().decode(rootNode
.get("pinMasterKey").asText()));
414 if (rootNode
.hasNonNull("storageKey")) {
415 storageKey
= new StorageKey(Base64
.getDecoder().decode(rootNode
.get("storageKey").asText()));
417 if (rootNode
.hasNonNull("preKeyIdOffset")) {
418 preKeyIdOffset
= rootNode
.get("preKeyIdOffset").asInt(0);
422 if (rootNode
.hasNonNull("nextSignedPreKeyId")) {
423 nextSignedPreKeyId
= rootNode
.get("nextSignedPreKeyId").asInt();
425 nextSignedPreKeyId
= 0;
427 if (rootNode
.hasNonNull("profileKey")) {
429 profileKey
= new ProfileKey(Base64
.getDecoder().decode(rootNode
.get("profileKey").asText()));
430 } catch (InvalidInputException e
) {
431 throw new IOException(
432 "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
437 var migratedLegacyConfig
= false;
438 final var legacySignalProtocolStore
= rootNode
.hasNonNull("axolotlStore")
439 ? jsonProcessor
.convertValue(Utils
.getNotNullNode(rootNode
, "axolotlStore"),
440 LegacyJsonSignalProtocolStore
.class)
442 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
443 identityKeyPair
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentityKeyPair();
444 registrationId
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getLocalRegistrationId();
445 migratedLegacyConfig
= true;
448 initStores(dataPath
, identityKeyPair
, registrationId
, trustNewIdentity
);
450 migratedLegacyConfig
= loadLegacyStores(rootNode
, legacySignalProtocolStore
) || migratedLegacyConfig
;
452 if (rootNode
.hasNonNull("groupStore")) {
453 groupStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("groupStore"), GroupStore
.Storage
.class);
454 groupStore
= GroupStore
.fromStorage(groupStoreStorage
,
455 getGroupCachePath(dataPath
, username
),
457 this::saveGroupStore
);
459 groupStore
= new GroupStore(getGroupCachePath(dataPath
, username
), recipientStore
, this::saveGroupStore
);
462 if (rootNode
.hasNonNull("stickerStore")) {
463 stickerStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("stickerStore"), StickerStore
.Storage
.class);
464 stickerStore
= StickerStore
.fromStorage(stickerStoreStorage
, this::saveStickerStore
);
466 stickerStore
= new StickerStore(this::saveStickerStore
);
469 migratedLegacyConfig
= loadLegacyThreadStore(rootNode
) || migratedLegacyConfig
;
471 if (migratedLegacyConfig
) {
476 private boolean loadLegacyStores(
477 final JsonNode rootNode
, final LegacyJsonSignalProtocolStore legacySignalProtocolStore
479 var migrated
= false;
480 var legacyRecipientStoreNode
= rootNode
.get("recipientStore");
481 if (legacyRecipientStoreNode
!= null) {
482 logger
.debug("Migrating legacy recipient store.");
483 var legacyRecipientStore
= jsonProcessor
.convertValue(legacyRecipientStoreNode
, LegacyRecipientStore
.class);
484 if (legacyRecipientStore
!= null) {
485 recipientStore
.resolveRecipientsTrusted(legacyRecipientStore
.getAddresses());
487 recipientStore
.resolveRecipientTrusted(getSelfAddress());
491 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyPreKeyStore() != null) {
492 logger
.debug("Migrating legacy pre key store.");
493 for (var entry
: legacySignalProtocolStore
.getLegacyPreKeyStore().getPreKeys().entrySet()) {
495 preKeyStore
.storePreKey(entry
.getKey(), new PreKeyRecord(entry
.getValue()));
496 } catch (IOException e
) {
497 logger
.warn("Failed to migrate pre key, ignoring", e
);
503 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySignedPreKeyStore() != null) {
504 logger
.debug("Migrating legacy signed pre key store.");
505 for (var entry
: legacySignalProtocolStore
.getLegacySignedPreKeyStore().getSignedPreKeys().entrySet()) {
507 signedPreKeyStore
.storeSignedPreKey(entry
.getKey(), new SignedPreKeyRecord(entry
.getValue()));
508 } catch (IOException e
) {
509 logger
.warn("Failed to migrate signed pre key, ignoring", e
);
515 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySessionStore() != null) {
516 logger
.debug("Migrating legacy session store.");
517 for (var session
: legacySignalProtocolStore
.getLegacySessionStore().getSessions()) {
519 sessionStore
.storeSession(new SignalProtocolAddress(session
.address
.getIdentifier(),
520 session
.deviceId
), new SessionRecord(session
.sessionRecord
));
521 } catch (IOException e
) {
522 logger
.warn("Failed to migrate session, ignoring", e
);
528 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
529 logger
.debug("Migrating legacy identity session store.");
530 for (var identity
: legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentities()) {
531 RecipientId recipientId
= recipientStore
.resolveRecipientTrusted(identity
.getAddress());
532 identityKeyStore
.saveIdentity(recipientId
, identity
.getIdentityKey(), identity
.getDateAdded());
533 identityKeyStore
.setIdentityTrustLevel(recipientId
,
534 identity
.getIdentityKey(),
535 identity
.getTrustLevel());
540 if (rootNode
.hasNonNull("contactStore")) {
541 logger
.debug("Migrating legacy contact store.");
542 final var contactStoreNode
= rootNode
.get("contactStore");
543 final var contactStore
= jsonProcessor
.convertValue(contactStoreNode
, LegacyJsonContactsStore
.class);
544 for (var contact
: contactStore
.getContacts()) {
545 final var recipientId
= recipientStore
.resolveRecipientTrusted(contact
.getAddress());
546 recipientStore
.storeContact(recipientId
,
547 new Contact(contact
.name
,
549 contact
.messageExpirationTime
,
553 // Store profile keys only in profile store
554 var profileKeyString
= contact
.profileKey
;
555 if (profileKeyString
!= null) {
556 final ProfileKey profileKey
;
558 profileKey
= new ProfileKey(Base64
.getDecoder().decode(profileKeyString
));
559 getProfileStore().storeProfileKey(recipientId
, profileKey
);
560 } catch (InvalidInputException e
) {
561 logger
.warn("Failed to parse legacy contact profile key: {}", e
.getMessage());
568 if (rootNode
.hasNonNull("profileStore")) {
569 logger
.debug("Migrating legacy profile store.");
570 var profileStoreNode
= rootNode
.get("profileStore");
571 final var legacyProfileStore
= jsonProcessor
.convertValue(profileStoreNode
, LegacyProfileStore
.class);
572 for (var profileEntry
: legacyProfileStore
.getProfileEntries()) {
573 var recipientId
= recipientStore
.resolveRecipient(profileEntry
.getAddress());
574 recipientStore
.storeProfileKeyCredential(recipientId
, profileEntry
.getProfileKeyCredential());
575 recipientStore
.storeProfileKey(recipientId
, profileEntry
.getProfileKey());
576 final var profile
= profileEntry
.getProfile();
577 if (profile
!= null) {
578 final var capabilities
= new HashSet
<Profile
.Capability
>();
579 if (profile
.getCapabilities() != null) {
580 if (profile
.getCapabilities().gv1Migration
) {
581 capabilities
.add(Profile
.Capability
.gv1Migration
);
583 if (profile
.getCapabilities().gv2
) {
584 capabilities
.add(Profile
.Capability
.gv2
);
586 if (profile
.getCapabilities().storage
) {
587 capabilities
.add(Profile
.Capability
.storage
);
590 final var newProfile
= new Profile(profileEntry
.getLastUpdateTimestamp(),
591 profile
.getGivenName(),
592 profile
.getFamilyName(),
594 profile
.getAboutEmoji(),
595 profile
.isUnrestrictedUnidentifiedAccess()
596 ? Profile
.UnidentifiedAccessMode
.UNRESTRICTED
597 : profile
.getUnidentifiedAccess() != null
598 ? Profile
.UnidentifiedAccessMode
.ENABLED
599 : Profile
.UnidentifiedAccessMode
.DISABLED
,
601 recipientStore
.storeProfile(recipientId
, newProfile
);
609 private boolean loadLegacyThreadStore(final JsonNode rootNode
) {
610 var threadStoreNode
= rootNode
.get("threadStore");
611 if (threadStoreNode
!= null && !threadStoreNode
.isNull()) {
612 var threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
613 // Migrate thread info to group and contact store
614 for (var thread
: threadStore
.getThreads()) {
615 if (thread
.id
== null || thread
.id
.isEmpty()) {
619 if (UuidUtil
.isUuid(thread
.id
) || thread
.id
.startsWith("+")) {
620 final var recipientId
= recipientStore
.resolveRecipient(thread
.id
);
621 var contact
= recipientStore
.getContact(recipientId
);
622 if (contact
!= null) {
623 recipientStore
.storeContact(recipientId
,
624 Contact
.newBuilder(contact
)
625 .withMessageExpirationTime(thread
.messageExpirationTime
)
629 var groupInfo
= groupStore
.getGroup(GroupId
.fromBase64(thread
.id
));
630 if (groupInfo
instanceof GroupInfoV1
) {
631 ((GroupInfoV1
) groupInfo
).messageExpirationTime
= thread
.messageExpirationTime
;
632 groupStore
.updateGroup(groupInfo
);
635 } catch (Exception e
) {
636 logger
.warn("Failed to read legacy thread info: {}", e
.getMessage());
645 private void saveStickerStore(StickerStore
.Storage storage
) {
646 this.stickerStoreStorage
= storage
;
650 private void saveGroupStore(GroupStore
.Storage storage
) {
651 this.groupStoreStorage
= storage
;
655 private void save() {
656 synchronized (fileChannel
) {
657 var rootNode
= jsonProcessor
.createObjectNode();
658 rootNode
.put("version", CURRENT_STORAGE_VERSION
)
659 .put("username", username
)
660 .put("uuid", uuid
== null ?
null : uuid
.toString())
661 .put("deviceName", encryptedDeviceName
)
662 .put("deviceId", deviceId
)
663 .put("isMultiDevice", isMultiDevice
)
664 .put("lastReceiveTimestamp", lastReceiveTimestamp
)
665 .put("password", password
)
666 .put("registrationId", identityKeyStore
.getLocalRegistrationId())
667 .put("identityPrivateKey",
669 .encodeToString(identityKeyStore
.getIdentityKeyPair().getPrivateKey().serialize()))
672 .encodeToString(identityKeyStore
.getIdentityKeyPair().getPublicKey().serialize()))
673 .put("registrationLockPin", registrationLockPin
)
675 pinMasterKey
== null ?
null : Base64
.getEncoder().encodeToString(pinMasterKey
.serialize()))
677 storageKey
== null ?
null : Base64
.getEncoder().encodeToString(storageKey
.serialize()))
678 .put("preKeyIdOffset", preKeyIdOffset
)
679 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
681 profileKey
== null ?
null : Base64
.getEncoder().encodeToString(profileKey
.serialize()))
682 .put("registered", registered
)
683 .putPOJO("groupStore", groupStoreStorage
)
684 .putPOJO("stickerStore", stickerStoreStorage
);
686 try (var output
= new ByteArrayOutputStream()) {
687 // Write to memory first to prevent corrupting the file in case of serialization errors
688 jsonProcessor
.writeValue(output
, rootNode
);
689 var input
= new ByteArrayInputStream(output
.toByteArray());
690 fileChannel
.position(0);
691 input
.transferTo(Channels
.newOutputStream(fileChannel
));
692 fileChannel
.truncate(fileChannel
.position());
693 fileChannel
.force(false);
695 } catch (Exception e
) {
696 logger
.error("Error saving file: {}", e
.getMessage());
701 private static Pair
<FileChannel
, FileLock
> openFileChannel(File fileName
, boolean waitForLock
) throws IOException
{
702 var fileChannel
= new RandomAccessFile(fileName
, "rw").getChannel();
703 var lock
= fileChannel
.tryLock();
706 logger
.debug("Config file is in use by another instance.");
707 throw new IOException("Config file is in use by another instance.");
709 logger
.info("Config file is in use by another instance, waiting…");
710 lock
= fileChannel
.lock();
711 logger
.info("Config file lock acquired.");
713 return new Pair
<>(fileChannel
, lock
);
716 public void addPreKeys(List
<PreKeyRecord
> records
) {
717 for (var record : records
) {
718 if (preKeyIdOffset
!= record.getId()) {
719 logger
.error("Invalid pre key id {}, expected {}", record.getId(), preKeyIdOffset
);
720 throw new AssertionError("Invalid pre key id");
722 preKeyStore
.storePreKey(record.getId(), record);
723 preKeyIdOffset
= (preKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
728 public void addSignedPreKey(SignedPreKeyRecord
record) {
729 if (nextSignedPreKeyId
!= record.getId()) {
730 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), nextSignedPreKeyId
);
731 throw new AssertionError("Invalid signed pre key id");
733 signalProtocolStore
.storeSignedPreKey(record.getId(), record);
734 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
738 public SignalProtocolStore
getSignalProtocolStore() {
739 return signalProtocolStore
;
742 public SessionStore
getSessionStore() {
746 public IdentityKeyStore
getIdentityKeyStore() {
747 return identityKeyStore
;
750 public GroupStore
getGroupStore() {
754 public ContactsStore
getContactStore() {
755 return recipientStore
;
758 public RecipientStore
getRecipientStore() {
759 return recipientStore
;
762 public ProfileStore
getProfileStore() {
763 return recipientStore
;
766 public StickerStore
getStickerStore() {
770 public MessageCache
getMessageCache() {
774 public String
getUsername() {
778 public UUID
getUuid() {
782 public void setUuid(final UUID uuid
) {
787 public SignalServiceAddress
getSelfAddress() {
788 return new SignalServiceAddress(uuid
, username
);
791 public RecipientId
getSelfRecipientId() {
792 return recipientStore
.resolveRecipientTrusted(getSelfAddress());
795 public String
getEncryptedDeviceName() {
796 return encryptedDeviceName
;
799 public int getDeviceId() {
803 public boolean isMasterDevice() {
804 return deviceId
== SignalServiceAddress
.DEFAULT_DEVICE_ID
;
807 public IdentityKeyPair
getIdentityKeyPair() {
808 return signalProtocolStore
.getIdentityKeyPair();
811 public int getLocalRegistrationId() {
812 return signalProtocolStore
.getLocalRegistrationId();
815 public String
getPassword() {
819 private void setPassword(final String password
) {
820 this.password
= password
;
824 public String
getRegistrationLockPin() {
825 return registrationLockPin
;
828 public void setRegistrationLockPin(final String registrationLockPin
, final MasterKey pinMasterKey
) {
829 this.registrationLockPin
= registrationLockPin
;
830 this.pinMasterKey
= pinMasterKey
;
834 public MasterKey
getPinMasterKey() {
838 public StorageKey
getStorageKey() {
839 if (pinMasterKey
!= null) {
840 return pinMasterKey
.deriveStorageServiceKey();
845 public void setStorageKey(final StorageKey storageKey
) {
846 if (storageKey
.equals(this.storageKey
)) {
849 this.storageKey
= storageKey
;
853 public ProfileKey
getProfileKey() {
857 public void setProfileKey(final ProfileKey profileKey
) {
858 if (profileKey
.equals(this.profileKey
)) {
861 this.profileKey
= profileKey
;
865 public byte[] getSelfUnidentifiedAccessKey() {
866 return UnidentifiedAccess
.deriveAccessKeyFrom(getProfileKey());
869 public int getPreKeyIdOffset() {
870 return preKeyIdOffset
;
873 public int getNextSignedPreKeyId() {
874 return nextSignedPreKeyId
;
877 public boolean isRegistered() {
881 public void setRegistered(final boolean registered
) {
882 this.registered
= registered
;
886 public boolean isMultiDevice() {
887 return isMultiDevice
;
890 public void setMultiDevice(final boolean multiDevice
) {
891 if (isMultiDevice
== multiDevice
) {
894 isMultiDevice
= multiDevice
;
898 public long getLastReceiveTimestamp() {
899 return lastReceiveTimestamp
;
902 public void setLastReceiveTimestamp(final long lastReceiveTimestamp
) {
903 this.lastReceiveTimestamp
= lastReceiveTimestamp
;
907 public boolean isUnrestrictedUnidentifiedAccess() {
908 // TODO make configurable
912 public boolean isDiscoverableByPhoneNumber() {
913 // TODO make configurable
917 public boolean isPhoneNumberShared() {
918 // TODO make configurable
922 public void finishRegistration(final UUID uuid
, final MasterKey masterKey
, final String pin
) {
923 this.pinMasterKey
= masterKey
;
924 this.encryptedDeviceName
= null;
925 this.deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
926 this.isMultiDevice
= false;
927 this.registered
= true;
929 this.registrationLockPin
= pin
;
930 this.lastReceiveTimestamp
= 0;
933 getSessionStore().archiveAllSessions();
934 final var recipientId
= getRecipientStore().resolveRecipientTrusted(getSelfAddress());
935 final var publicKey
= getIdentityKeyPair().getPublicKey();
936 getIdentityKeyStore().saveIdentity(recipientId
, publicKey
, new Date());
937 getIdentityKeyStore().setIdentityTrustLevel(recipientId
, publicKey
, TrustLevel
.TRUSTED_VERIFIED
);
941 public void close() throws IOException
{
942 synchronized (fileChannel
) {
945 } catch (ClosedChannelException ignored
) {