1 package org
.asamk
.signal
.manager
.storage
;
3 import com
.fasterxml
.jackson
.databind
.JsonNode
;
4 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
6 import org
.asamk
.signal
.manager
.api
.Pair
;
7 import org
.asamk
.signal
.manager
.api
.TrustLevel
;
8 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
9 import org
.asamk
.signal
.manager
.groups
.GroupId
;
10 import org
.asamk
.signal
.manager
.helper
.RecipientAddressResolver
;
11 import org
.asamk
.signal
.manager
.storage
.configuration
.ConfigurationStore
;
12 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactsStore
;
13 import org
.asamk
.signal
.manager
.storage
.contacts
.LegacyJsonContactsStore
;
14 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
15 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
16 import org
.asamk
.signal
.manager
.storage
.groups
.GroupStore
;
17 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityKeyStore
;
18 import org
.asamk
.signal
.manager
.storage
.identities
.SignalIdentityKeyStore
;
19 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
20 import org
.asamk
.signal
.manager
.storage
.messageCache
.MessageCache
;
21 import org
.asamk
.signal
.manager
.storage
.prekeys
.PreKeyStore
;
22 import org
.asamk
.signal
.manager
.storage
.prekeys
.SignedPreKeyStore
;
23 import org
.asamk
.signal
.manager
.storage
.profiles
.LegacyProfileStore
;
24 import org
.asamk
.signal
.manager
.storage
.profiles
.ProfileStore
;
25 import org
.asamk
.signal
.manager
.storage
.protocol
.LegacyJsonSignalProtocolStore
;
26 import org
.asamk
.signal
.manager
.storage
.protocol
.SignalProtocolStore
;
27 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
28 import org
.asamk
.signal
.manager
.storage
.recipients
.LegacyRecipientStore
;
29 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
30 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
31 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
32 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientResolver
;
33 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientStore
;
34 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientTrustedResolver
;
35 import org
.asamk
.signal
.manager
.storage
.sendLog
.MessageSendLogStore
;
36 import org
.asamk
.signal
.manager
.storage
.senderKeys
.SenderKeyStore
;
37 import org
.asamk
.signal
.manager
.storage
.sessions
.SessionStore
;
38 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerStore
;
39 import org
.asamk
.signal
.manager
.storage
.threads
.LegacyJsonThreadStore
;
40 import org
.asamk
.signal
.manager
.util
.IOUtils
;
41 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
42 import org
.signal
.libsignal
.protocol
.IdentityKeyPair
;
43 import org
.signal
.libsignal
.protocol
.InvalidMessageException
;
44 import org
.signal
.libsignal
.protocol
.SignalProtocolAddress
;
45 import org
.signal
.libsignal
.protocol
.state
.PreKeyRecord
;
46 import org
.signal
.libsignal
.protocol
.state
.SessionRecord
;
47 import org
.signal
.libsignal
.protocol
.state
.SignedPreKeyRecord
;
48 import org
.signal
.libsignal
.protocol
.util
.KeyHelper
;
49 import org
.signal
.libsignal
.protocol
.util
.Medium
;
50 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
51 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
52 import org
.slf4j
.Logger
;
53 import org
.slf4j
.LoggerFactory
;
54 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountDataStore
;
55 import org
.whispersystems
.signalservice
.api
.SignalServiceDataStore
;
56 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
57 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
58 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
59 import org
.whispersystems
.signalservice
.api
.push
.DistributionId
;
60 import org
.whispersystems
.signalservice
.api
.push
.PNI
;
61 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
62 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
63 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
64 import org
.whispersystems
.signalservice
.api
.storage
.SignalStorageManifest
;
65 import org
.whispersystems
.signalservice
.api
.storage
.StorageKey
;
66 import org
.whispersystems
.signalservice
.api
.util
.CredentialsProvider
;
67 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
69 import java
.io
.ByteArrayInputStream
;
70 import java
.io
.ByteArrayOutputStream
;
71 import java
.io
.Closeable
;
73 import java
.io
.FileInputStream
;
74 import java
.io
.FileOutputStream
;
75 import java
.io
.IOException
;
76 import java
.io
.RandomAccessFile
;
77 import java
.nio
.channels
.Channels
;
78 import java
.nio
.channels
.ClosedChannelException
;
79 import java
.nio
.channels
.FileChannel
;
80 import java
.nio
.channels
.FileLock
;
81 import java
.nio
.file
.Files
;
82 import java
.security
.SecureRandom
;
83 import java
.sql
.SQLException
;
84 import java
.util
.Base64
;
85 import java
.util
.Comparator
;
86 import java
.util
.HashSet
;
87 import java
.util
.List
;
88 import java
.util
.Optional
;
89 import java
.util
.function
.Supplier
;
91 public class SignalAccount
implements Closeable
{
93 private final static Logger logger
= LoggerFactory
.getLogger(SignalAccount
.class);
95 private static final int MINIMUM_STORAGE_VERSION
= 1;
96 private static final int CURRENT_STORAGE_VERSION
= 3;
98 private final Object LOCK
= new Object();
100 private final ObjectMapper jsonProcessor
= Utils
.createStorageObjectMapper();
102 private final FileChannel fileChannel
;
103 private final FileLock lock
;
105 private int previousStorageVersion
;
107 private File dataPath
;
108 private String accountPath
;
109 private ServiceEnvironment serviceEnvironment
;
110 private String number
;
113 private String encryptedDeviceName
;
114 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
115 private boolean isMultiDevice
= false;
116 private String password
;
117 private String registrationLockPin
;
118 private MasterKey pinMasterKey
;
119 private StorageKey storageKey
;
120 private long storageManifestVersion
= -1;
121 private ProfileKey profileKey
;
122 private int aciPreKeyIdOffset
= 1;
123 private int aciNextSignedPreKeyId
= 1;
124 private int pniPreKeyIdOffset
= 1;
125 private int pniNextSignedPreKeyId
= 1;
126 private IdentityKeyPair aciIdentityKeyPair
;
127 private IdentityKeyPair pniIdentityKeyPair
;
128 private int localRegistrationId
;
129 private int localPniRegistrationId
;
130 private TrustNewIdentity trustNewIdentity
;
131 private long lastReceiveTimestamp
= 0;
133 private boolean registered
= false;
135 private SignalProtocolStore signalProtocolStore
;
136 private PreKeyStore aciPreKeyStore
;
137 private SignedPreKeyStore aciSignedPreKeyStore
;
138 private PreKeyStore pniPreKeyStore
;
139 private SignedPreKeyStore pniSignedPreKeyStore
;
140 private SessionStore sessionStore
;
141 private IdentityKeyStore identityKeyStore
;
142 private SignalIdentityKeyStore aciIdentityKeyStore
;
143 private SenderKeyStore senderKeyStore
;
144 private GroupStore groupStore
;
145 private GroupStore
.Storage groupStoreStorage
;
146 private RecipientStore recipientStore
;
147 private StickerStore stickerStore
;
148 private StickerStore
.Storage stickerStoreStorage
;
149 private ConfigurationStore configurationStore
;
150 private ConfigurationStore
.Storage configurationStoreStorage
;
152 private MessageCache messageCache
;
153 private MessageSendLogStore messageSendLogStore
;
155 private AccountDatabase accountDatabase
;
157 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
158 this.fileChannel
= fileChannel
;
162 public static SignalAccount
load(
163 File dataPath
, String accountPath
, boolean waitForLock
, final TrustNewIdentity trustNewIdentity
164 ) throws IOException
{
165 logger
.trace("Opening account file");
166 final var fileName
= getFileName(dataPath
, accountPath
);
167 final var pair
= openFileChannel(fileName
, waitForLock
);
169 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
170 logger
.trace("Loading account file");
171 signalAccount
.load(dataPath
, accountPath
, trustNewIdentity
);
172 logger
.trace("Migrating legacy parts of account file");
173 signalAccount
.migrateLegacyConfigs();
175 return signalAccount
;
176 } catch (Throwable e
) {
177 pair
.second().close();
178 pair
.first().close();
183 public static SignalAccount
create(
187 ServiceEnvironment serviceEnvironment
,
188 IdentityKeyPair aciIdentityKey
,
189 IdentityKeyPair pniIdentityKey
,
191 int pniRegistrationId
,
192 ProfileKey profileKey
,
193 final TrustNewIdentity trustNewIdentity
194 ) throws IOException
{
195 IOUtils
.createPrivateDirectories(dataPath
);
196 var fileName
= getFileName(dataPath
, accountPath
);
197 if (!fileName
.exists()) {
198 IOUtils
.createPrivateFile(fileName
);
201 final var pair
= openFileChannel(fileName
, true);
202 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
204 signalAccount
.accountPath
= accountPath
;
205 signalAccount
.number
= number
;
206 signalAccount
.serviceEnvironment
= serviceEnvironment
;
207 signalAccount
.profileKey
= profileKey
;
209 signalAccount
.dataPath
= dataPath
;
210 signalAccount
.aciIdentityKeyPair
= aciIdentityKey
;
211 signalAccount
.pniIdentityKeyPair
= pniIdentityKey
;
212 signalAccount
.localRegistrationId
= registrationId
;
213 signalAccount
.localPniRegistrationId
= pniRegistrationId
;
214 signalAccount
.trustNewIdentity
= trustNewIdentity
;
215 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
216 signalAccount
.getRecipientResolver(),
217 signalAccount
::saveGroupStore
);
218 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
219 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
221 signalAccount
.registered
= false;
223 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
224 signalAccount
.migrateLegacyConfigs();
225 signalAccount
.save();
227 return signalAccount
;
230 public static SignalAccount
createOrUpdateLinkedAccount(
234 ServiceEnvironment serviceEnvironment
,
238 String encryptedDeviceName
,
240 IdentityKeyPair aciIdentityKey
,
241 IdentityKeyPair pniIdentityKey
,
243 int pniRegistrationId
,
244 ProfileKey profileKey
,
245 final TrustNewIdentity trustNewIdentity
246 ) throws IOException
{
247 IOUtils
.createPrivateDirectories(dataPath
);
248 var fileName
= getFileName(dataPath
, accountPath
);
249 if (!fileName
.exists()) {
250 return createLinkedAccount(dataPath
,
267 final var signalAccount
= load(dataPath
, accountPath
, true, trustNewIdentity
);
268 signalAccount
.setProvisioningData(number
,
277 signalAccount
.getRecipientTrustedResolver()
278 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
279 signalAccount
.getSessionStore().archiveAllSessions();
280 signalAccount
.getSenderKeyStore().deleteAll();
281 signalAccount
.clearAllPreKeys();
282 return signalAccount
;
285 public void initDatabase() {
286 getAccountDatabase();
289 private void clearAllPreKeys() {
290 this.aciPreKeyIdOffset
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
291 this.aciNextSignedPreKeyId
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
292 this.pniPreKeyIdOffset
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
293 this.pniNextSignedPreKeyId
= new SecureRandom().nextInt(Medium
.MAX_VALUE
);
294 this.getAciPreKeyStore().removeAllPreKeys();
295 this.getAciSignedPreKeyStore().removeAllSignedPreKeys();
296 this.getPniPreKeyStore().removeAllPreKeys();
297 this.getPniSignedPreKeyStore().removeAllSignedPreKeys();
301 private static SignalAccount
createLinkedAccount(
305 ServiceEnvironment serviceEnvironment
,
309 String encryptedDeviceName
,
311 IdentityKeyPair aciIdentityKey
,
312 IdentityKeyPair pniIdentityKey
,
314 int pniRegistrationId
,
315 ProfileKey profileKey
,
316 final TrustNewIdentity trustNewIdentity
317 ) throws IOException
{
318 var fileName
= getFileName(dataPath
, accountPath
);
319 IOUtils
.createPrivateFile(fileName
);
321 final var pair
= openFileChannel(fileName
, true);
322 var signalAccount
= new SignalAccount(pair
.first(), pair
.second());
324 signalAccount
.dataPath
= dataPath
;
325 signalAccount
.accountPath
= accountPath
;
326 signalAccount
.serviceEnvironment
= serviceEnvironment
;
327 signalAccount
.localRegistrationId
= registrationId
;
328 signalAccount
.localPniRegistrationId
= pniRegistrationId
;
329 signalAccount
.trustNewIdentity
= trustNewIdentity
;
330 signalAccount
.setProvisioningData(number
,
340 signalAccount
.groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
341 signalAccount
.getRecipientResolver(),
342 signalAccount
::saveGroupStore
);
343 signalAccount
.stickerStore
= new StickerStore(signalAccount
::saveStickerStore
);
344 signalAccount
.configurationStore
= new ConfigurationStore(signalAccount
::saveConfigurationStore
);
346 signalAccount
.getRecipientTrustedResolver()
347 .resolveSelfRecipientTrusted(signalAccount
.getSelfRecipientAddress());
348 signalAccount
.previousStorageVersion
= CURRENT_STORAGE_VERSION
;
349 signalAccount
.migrateLegacyConfigs();
350 signalAccount
.clearAllPreKeys();
351 signalAccount
.save();
353 return signalAccount
;
356 private void setProvisioningData(
360 final String password
,
361 final String encryptedDeviceName
,
363 final IdentityKeyPair aciIdentity
,
364 final IdentityKeyPair pniIdentity
,
365 final ProfileKey profileKey
367 this.number
= number
;
370 this.password
= password
;
371 this.profileKey
= profileKey
;
372 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
373 this.encryptedDeviceName
= encryptedDeviceName
;
374 this.deviceId
= deviceId
;
375 this.aciIdentityKeyPair
= aciIdentity
;
376 this.pniIdentityKeyPair
= pniIdentity
;
377 this.registered
= true;
378 this.isMultiDevice
= true;
379 this.lastReceiveTimestamp
= 0;
380 this.pinMasterKey
= null;
381 this.storageManifestVersion
= -1;
382 this.setStorageManifest(null);
383 this.storageKey
= null;
386 private void migrateLegacyConfigs() {
387 if (getPassword() == null) {
388 setPassword(KeyUtils
.createPassword());
391 if (getProfileKey() == null) {
392 // Old config file, creating new profile key
393 setProfileKey(KeyUtils
.createProfileKey());
395 // Ensure our profile key is stored in profile store
396 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
397 if (previousStorageVersion
< 3) {
398 for (final var group
: groupStore
.getGroups()) {
399 if (group
instanceof GroupInfoV2
&& group
.getDistributionId() == null) {
400 ((GroupInfoV2
) group
).setDistributionId(DistributionId
.create());
401 groupStore
.updateGroup(group
);
406 if (isPrimaryDevice() && getPniIdentityKeyPair() == null) {
407 setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
411 private void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
412 getSessionStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
413 getIdentityKeyStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
414 getMessageCache().mergeRecipients(recipientId
, toBeMergedRecipientId
);
415 getGroupStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
416 getSenderKeyStore().mergeRecipients(recipientId
, toBeMergedRecipientId
);
419 public void removeRecipient(final RecipientId recipientId
) {
420 getSessionStore().deleteAllSessions(recipientId
);
421 getIdentityKeyStore().deleteIdentity(recipientId
);
422 getMessageCache().deleteMessages(recipientId
);
423 getSenderKeyStore().deleteAll(recipientId
);
424 getRecipientStore().deleteRecipientData(recipientId
);
427 public static File
getFileName(File dataPath
, String account
) {
428 return new File(dataPath
, account
);
431 private static File
getUserPath(final File dataPath
, final String account
) {
432 final var path
= new File(dataPath
, account
+ ".d");
434 IOUtils
.createPrivateDirectories(path
);
435 } catch (IOException e
) {
436 throw new AssertionError("Failed to create user path", e
);
441 private static File
getMessageCachePath(File dataPath
, String account
) {
442 return new File(getUserPath(dataPath
, account
), "msg-cache");
445 private static File
getGroupCachePath(File dataPath
, String account
) {
446 return new File(getUserPath(dataPath
, account
), "group-cache");
449 private static File
getAciPreKeysPath(File dataPath
, String account
) {
450 return new File(getUserPath(dataPath
, account
), "pre-keys");
453 private static File
getAciSignedPreKeysPath(File dataPath
, String account
) {
454 return new File(getUserPath(dataPath
, account
), "signed-pre-keys");
457 private static File
getPniPreKeysPath(File dataPath
, String account
) {
458 return new File(getUserPath(dataPath
, account
), "pre-keys-pni");
461 private static File
getPniSignedPreKeysPath(File dataPath
, String account
) {
462 return new File(getUserPath(dataPath
, account
), "signed-pre-keys-pni");
465 private static File
getIdentitiesPath(File dataPath
, String account
) {
466 return new File(getUserPath(dataPath
, account
), "identities");
469 private static File
getSessionsPath(File dataPath
, String account
) {
470 return new File(getUserPath(dataPath
, account
), "sessions");
473 private static File
getSenderKeysPath(File dataPath
, String account
) {
474 return new File(getUserPath(dataPath
, account
), "sender-keys");
477 private static File
getSharedSenderKeysFile(File dataPath
, String account
) {
478 return new File(getUserPath(dataPath
, account
), "shared-sender-keys-store");
481 private static File
getRecipientsStoreFile(File dataPath
, String account
) {
482 return new File(getUserPath(dataPath
, account
), "recipients-store");
485 private static File
getStorageManifestFile(File dataPath
, String account
) {
486 return new File(getUserPath(dataPath
, account
), "storage-manifest");
489 private static File
getDatabaseFile(File dataPath
, String account
) {
490 return new File(getUserPath(dataPath
, account
), "account.db");
493 public static boolean accountFileExists(File dataPath
, String account
) {
494 if (account
== null) {
497 var f
= getFileName(dataPath
, account
);
498 return !(!f
.exists() || f
.isDirectory());
502 File dataPath
, String accountPath
, final TrustNewIdentity trustNewIdentity
503 ) throws IOException
{
504 this.dataPath
= dataPath
;
505 this.accountPath
= accountPath
;
506 final JsonNode rootNode
;
507 synchronized (fileChannel
) {
508 fileChannel
.position(0);
509 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
512 if (rootNode
.hasNonNull("version")) {
513 var accountVersion
= rootNode
.get("version").asInt(1);
514 if (accountVersion
> CURRENT_STORAGE_VERSION
) {
515 throw new IOException("Config file was created by a more recent version!");
516 } else if (accountVersion
< MINIMUM_STORAGE_VERSION
) {
517 throw new IOException("Config file was created by a no longer supported older version!");
519 previousStorageVersion
= accountVersion
;
522 number
= Utils
.getNotNullNode(rootNode
, "username").asText();
523 if (rootNode
.hasNonNull("password")) {
524 password
= rootNode
.get("password").asText();
526 if (rootNode
.hasNonNull("serviceEnvironment")) {
527 serviceEnvironment
= ServiceEnvironment
.valueOf(rootNode
.get("serviceEnvironment").asText());
529 registered
= Utils
.getNotNullNode(rootNode
, "registered").asBoolean();
530 if (rootNode
.hasNonNull("uuid")) {
532 aci
= ACI
.parseOrThrow(rootNode
.get("uuid").asText());
533 } catch (IllegalArgumentException e
) {
534 throw new IOException("Config file contains an invalid aci/uuid, needs to be a valid UUID", e
);
537 if (rootNode
.hasNonNull("pni")) {
539 pni
= PNI
.parseOrThrow(rootNode
.get("pni").asText());
540 } catch (IllegalArgumentException e
) {
541 throw new IOException("Config file contains an invalid pni, needs to be a valid UUID", e
);
544 if (rootNode
.hasNonNull("deviceName")) {
545 encryptedDeviceName
= rootNode
.get("deviceName").asText();
547 if (rootNode
.hasNonNull("deviceId")) {
548 deviceId
= rootNode
.get("deviceId").asInt();
550 if (rootNode
.hasNonNull("isMultiDevice")) {
551 isMultiDevice
= rootNode
.get("isMultiDevice").asBoolean();
553 if (rootNode
.hasNonNull("lastReceiveTimestamp")) {
554 lastReceiveTimestamp
= rootNode
.get("lastReceiveTimestamp").asLong();
556 int registrationId
= 0;
557 if (rootNode
.hasNonNull("registrationId")) {
558 registrationId
= rootNode
.get("registrationId").asInt();
560 if (rootNode
.hasNonNull("pniRegistrationId")) {
561 localPniRegistrationId
= rootNode
.get("pniRegistrationId").asInt();
563 localPniRegistrationId
= KeyHelper
.generateRegistrationId(false);
565 IdentityKeyPair aciIdentityKeyPair
= null;
566 if (rootNode
.hasNonNull("identityPrivateKey") && rootNode
.hasNonNull("identityKey")) {
567 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityKey").asText());
568 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("identityPrivateKey").asText());
569 aciIdentityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
571 if (rootNode
.hasNonNull("pniIdentityPrivateKey") && rootNode
.hasNonNull("pniIdentityKey")) {
572 final var publicKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityKey").asText());
573 final var privateKeyBytes
= Base64
.getDecoder().decode(rootNode
.get("pniIdentityPrivateKey").asText());
574 pniIdentityKeyPair
= KeyUtils
.getIdentityKeyPair(publicKeyBytes
, privateKeyBytes
);
577 if (rootNode
.hasNonNull("registrationLockPin")) {
578 registrationLockPin
= rootNode
.get("registrationLockPin").asText();
580 if (rootNode
.hasNonNull("pinMasterKey")) {
581 pinMasterKey
= new MasterKey(Base64
.getDecoder().decode(rootNode
.get("pinMasterKey").asText()));
583 if (rootNode
.hasNonNull("storageKey")) {
584 storageKey
= new StorageKey(Base64
.getDecoder().decode(rootNode
.get("storageKey").asText()));
586 if (rootNode
.hasNonNull("storageManifestVersion")) {
587 storageManifestVersion
= rootNode
.get("storageManifestVersion").asLong();
589 if (rootNode
.hasNonNull("preKeyIdOffset")) {
590 aciPreKeyIdOffset
= rootNode
.get("preKeyIdOffset").asInt(1);
592 aciPreKeyIdOffset
= 1;
594 if (rootNode
.hasNonNull("nextSignedPreKeyId")) {
595 aciNextSignedPreKeyId
= rootNode
.get("nextSignedPreKeyId").asInt(1);
597 aciNextSignedPreKeyId
= 1;
599 if (rootNode
.hasNonNull("pniPreKeyIdOffset")) {
600 pniPreKeyIdOffset
= rootNode
.get("pniPreKeyIdOffset").asInt(1);
602 pniPreKeyIdOffset
= 1;
604 if (rootNode
.hasNonNull("pniNextSignedPreKeyId")) {
605 pniNextSignedPreKeyId
= rootNode
.get("pniNextSignedPreKeyId").asInt(1);
607 pniNextSignedPreKeyId
= 1;
609 if (rootNode
.hasNonNull("profileKey")) {
611 profileKey
= new ProfileKey(Base64
.getDecoder().decode(rootNode
.get("profileKey").asText()));
612 } catch (InvalidInputException e
) {
613 throw new IOException(
614 "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
619 var migratedLegacyConfig
= false;
620 final var legacySignalProtocolStore
= rootNode
.hasNonNull("axolotlStore")
621 ? jsonProcessor
.convertValue(Utils
.getNotNullNode(rootNode
, "axolotlStore"),
622 LegacyJsonSignalProtocolStore
.class)
624 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
625 aciIdentityKeyPair
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentityKeyPair();
626 registrationId
= legacySignalProtocolStore
.getLegacyIdentityKeyStore().getLocalRegistrationId();
627 migratedLegacyConfig
= true;
630 this.aciIdentityKeyPair
= aciIdentityKeyPair
;
631 this.localRegistrationId
= registrationId
;
632 this.trustNewIdentity
= trustNewIdentity
;
634 migratedLegacyConfig
= loadLegacyStores(rootNode
, legacySignalProtocolStore
) || migratedLegacyConfig
;
636 if (rootNode
.hasNonNull("groupStore")) {
637 groupStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("groupStore"), GroupStore
.Storage
.class);
638 groupStore
= GroupStore
.fromStorage(groupStoreStorage
,
639 getGroupCachePath(dataPath
, accountPath
),
640 getRecipientResolver(),
641 this::saveGroupStore
);
643 groupStore
= new GroupStore(getGroupCachePath(dataPath
, accountPath
),
644 getRecipientResolver(),
645 this::saveGroupStore
);
648 if (rootNode
.hasNonNull("stickerStore")) {
649 stickerStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("stickerStore"), StickerStore
.Storage
.class);
650 stickerStore
= StickerStore
.fromStorage(stickerStoreStorage
, this::saveStickerStore
);
652 stickerStore
= new StickerStore(this::saveStickerStore
);
655 if (rootNode
.hasNonNull("configurationStore")) {
656 configurationStoreStorage
= jsonProcessor
.convertValue(rootNode
.get("configurationStore"),
657 ConfigurationStore
.Storage
.class);
658 configurationStore
= ConfigurationStore
.fromStorage(configurationStoreStorage
,
659 this::saveConfigurationStore
);
661 configurationStore
= new ConfigurationStore(this::saveConfigurationStore
);
664 migratedLegacyConfig
= loadLegacyThreadStore(rootNode
) || migratedLegacyConfig
;
666 if (migratedLegacyConfig
) {
671 private boolean loadLegacyStores(
672 final JsonNode rootNode
, final LegacyJsonSignalProtocolStore legacySignalProtocolStore
674 var migrated
= false;
675 var legacyRecipientStoreNode
= rootNode
.get("recipientStore");
676 if (legacyRecipientStoreNode
!= null) {
677 logger
.debug("Migrating legacy recipient store.");
678 var legacyRecipientStore
= jsonProcessor
.convertValue(legacyRecipientStoreNode
, LegacyRecipientStore
.class);
679 if (legacyRecipientStore
!= null) {
680 getRecipientStore().resolveRecipientsTrusted(legacyRecipientStore
.getAddresses());
682 getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
686 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyPreKeyStore() != null) {
687 logger
.debug("Migrating legacy pre key store.");
688 for (var entry
: legacySignalProtocolStore
.getLegacyPreKeyStore().getPreKeys().entrySet()) {
690 getAciPreKeyStore().storePreKey(entry
.getKey(), new PreKeyRecord(entry
.getValue()));
691 } catch (InvalidMessageException e
) {
692 logger
.warn("Failed to migrate pre key, ignoring", e
);
698 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySignedPreKeyStore() != null) {
699 logger
.debug("Migrating legacy signed pre key store.");
700 for (var entry
: legacySignalProtocolStore
.getLegacySignedPreKeyStore().getSignedPreKeys().entrySet()) {
702 getAciSignedPreKeyStore().storeSignedPreKey(entry
.getKey(),
703 new SignedPreKeyRecord(entry
.getValue()));
704 } catch (InvalidMessageException e
) {
705 logger
.warn("Failed to migrate signed pre key, ignoring", e
);
711 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacySessionStore() != null) {
712 logger
.debug("Migrating legacy session store.");
713 for (var session
: legacySignalProtocolStore
.getLegacySessionStore().getSessions()) {
715 getSessionStore().storeSession(new SignalProtocolAddress(session
.address
.getIdentifier(),
716 session
.deviceId
), new SessionRecord(session
.sessionRecord
));
717 } catch (Exception e
) {
718 logger
.warn("Failed to migrate session, ignoring", e
);
724 if (legacySignalProtocolStore
!= null && legacySignalProtocolStore
.getLegacyIdentityKeyStore() != null) {
725 logger
.debug("Migrating legacy identity session store.");
726 for (var identity
: legacySignalProtocolStore
.getLegacyIdentityKeyStore().getIdentities()) {
727 RecipientId recipientId
= getRecipientStore().resolveRecipientTrusted(identity
.getAddress());
728 getIdentityKeyStore().saveIdentity(recipientId
, identity
.getIdentityKey(), identity
.getDateAdded());
729 getIdentityKeyStore().setIdentityTrustLevel(recipientId
,
730 identity
.getIdentityKey(),
731 identity
.getTrustLevel());
736 if (rootNode
.hasNonNull("contactStore")) {
737 logger
.debug("Migrating legacy contact store.");
738 final var contactStoreNode
= rootNode
.get("contactStore");
739 final var contactStore
= jsonProcessor
.convertValue(contactStoreNode
, LegacyJsonContactsStore
.class);
740 for (var contact
: contactStore
.getContacts()) {
741 final var recipientId
= getRecipientStore().resolveRecipientTrusted(contact
.getAddress());
742 getContactStore().storeContact(recipientId
,
743 new Contact(contact
.name
,
746 contact
.messageExpirationTime
,
751 // Store profile keys only in profile store
752 var profileKeyString
= contact
.profileKey
;
753 if (profileKeyString
!= null) {
754 final ProfileKey profileKey
;
756 profileKey
= new ProfileKey(Base64
.getDecoder().decode(profileKeyString
));
757 getProfileStore().storeProfileKey(recipientId
, profileKey
);
758 } catch (InvalidInputException e
) {
759 logger
.warn("Failed to parse legacy contact profile key: {}", e
.getMessage());
766 if (rootNode
.hasNonNull("profileStore")) {
767 logger
.debug("Migrating legacy profile store.");
768 var profileStoreNode
= rootNode
.get("profileStore");
769 final var legacyProfileStore
= jsonProcessor
.convertValue(profileStoreNode
, LegacyProfileStore
.class);
770 for (var profileEntry
: legacyProfileStore
.getProfileEntries()) {
771 var recipientId
= getRecipientResolver().resolveRecipient(profileEntry
.getAddress());
772 // Not migrating profile key credential here, it was changed to expiring profile key credentials
773 getProfileStore().storeProfileKey(recipientId
, profileEntry
.getProfileKey());
774 final var profile
= profileEntry
.getProfile();
775 if (profile
!= null) {
776 final var capabilities
= new HashSet
<Profile
.Capability
>();
777 if (profile
.getCapabilities() != null) {
778 if (profile
.getCapabilities().gv1Migration
) {
779 capabilities
.add(Profile
.Capability
.gv1Migration
);
781 if (profile
.getCapabilities().storage
) {
782 capabilities
.add(Profile
.Capability
.storage
);
785 final var newProfile
= new Profile(profileEntry
.getLastUpdateTimestamp(),
786 profile
.getGivenName(),
787 profile
.getFamilyName(),
789 profile
.getAboutEmoji(),
792 profile
.isUnrestrictedUnidentifiedAccess()
793 ? Profile
.UnidentifiedAccessMode
.UNRESTRICTED
794 : profile
.getUnidentifiedAccess() != null
795 ? Profile
.UnidentifiedAccessMode
.ENABLED
796 : Profile
.UnidentifiedAccessMode
.DISABLED
,
798 getProfileStore().storeProfile(recipientId
, newProfile
);
806 private boolean loadLegacyThreadStore(final JsonNode rootNode
) {
807 var threadStoreNode
= rootNode
.get("threadStore");
808 if (threadStoreNode
!= null && !threadStoreNode
.isNull()) {
809 var threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
810 // Migrate thread info to group and contact store
811 for (var thread
: threadStore
.getThreads()) {
812 if (thread
.id
== null || thread
.id
.isEmpty()) {
816 if (UuidUtil
.isUuid(thread
.id
) || thread
.id
.startsWith("+")) {
817 final var recipientId
= getRecipientResolver().resolveRecipient(thread
.id
);
818 var contact
= getContactStore().getContact(recipientId
);
819 if (contact
!= null) {
820 getContactStore().storeContact(recipientId
,
821 Contact
.newBuilder(contact
)
822 .withMessageExpirationTime(thread
.messageExpirationTime
)
826 var groupInfo
= groupStore
.getGroup(GroupId
.fromBase64(thread
.id
));
827 if (groupInfo
instanceof GroupInfoV1
) {
828 ((GroupInfoV1
) groupInfo
).messageExpirationTime
= thread
.messageExpirationTime
;
829 groupStore
.updateGroup(groupInfo
);
832 } catch (Exception e
) {
833 logger
.warn("Failed to read legacy thread info: {}", e
.getMessage());
842 private void saveStickerStore(StickerStore
.Storage storage
) {
843 this.stickerStoreStorage
= storage
;
847 private void saveGroupStore(GroupStore
.Storage storage
) {
848 this.groupStoreStorage
= storage
;
852 private void saveConfigurationStore(ConfigurationStore
.Storage storage
) {
853 this.configurationStoreStorage
= storage
;
857 private void save() {
858 synchronized (fileChannel
) {
859 var rootNode
= jsonProcessor
.createObjectNode();
860 rootNode
.put("version", CURRENT_STORAGE_VERSION
)
861 .put("username", number
)
862 .put("serviceEnvironment", serviceEnvironment
== null ?
null : serviceEnvironment
.name())
863 .put("uuid", aci
== null ?
null : aci
.toString())
864 .put("pni", pni
== null ?
null : pni
.toString())
865 .put("deviceName", encryptedDeviceName
)
866 .put("deviceId", deviceId
)
867 .put("isMultiDevice", isMultiDevice
)
868 .put("lastReceiveTimestamp", lastReceiveTimestamp
)
869 .put("password", password
)
870 .put("registrationId", localRegistrationId
)
871 .put("pniRegistrationId", localPniRegistrationId
)
872 .put("identityPrivateKey",
873 Base64
.getEncoder().encodeToString(aciIdentityKeyPair
.getPrivateKey().serialize()))
875 Base64
.getEncoder().encodeToString(aciIdentityKeyPair
.getPublicKey().serialize()))
876 .put("pniIdentityPrivateKey",
877 pniIdentityKeyPair
== null
879 : Base64
.getEncoder()
880 .encodeToString(pniIdentityKeyPair
.getPrivateKey().serialize()))
881 .put("pniIdentityKey",
882 pniIdentityKeyPair
== null
884 : Base64
.getEncoder().encodeToString(pniIdentityKeyPair
.getPublicKey().serialize()))
885 .put("registrationLockPin", registrationLockPin
)
887 pinMasterKey
== null ?
null : Base64
.getEncoder().encodeToString(pinMasterKey
.serialize()))
889 storageKey
== null ?
null : Base64
.getEncoder().encodeToString(storageKey
.serialize()))
890 .put("storageManifestVersion", storageManifestVersion
== -1 ?
null : storageManifestVersion
)
891 .put("preKeyIdOffset", aciPreKeyIdOffset
)
892 .put("nextSignedPreKeyId", aciNextSignedPreKeyId
)
893 .put("pniPreKeyIdOffset", pniPreKeyIdOffset
)
894 .put("pniNextSignedPreKeyId", pniNextSignedPreKeyId
)
896 profileKey
== null ?
null : Base64
.getEncoder().encodeToString(profileKey
.serialize()))
897 .put("registered", registered
)
898 .putPOJO("groupStore", groupStoreStorage
)
899 .putPOJO("stickerStore", stickerStoreStorage
)
900 .putPOJO("configurationStore", configurationStoreStorage
);
902 try (var output
= new ByteArrayOutputStream()) {
903 // Write to memory first to prevent corrupting the file in case of serialization errors
904 jsonProcessor
.writeValue(output
, rootNode
);
905 var input
= new ByteArrayInputStream(output
.toByteArray());
906 fileChannel
.position(0);
907 input
.transferTo(Channels
.newOutputStream(fileChannel
));
908 fileChannel
.truncate(fileChannel
.position());
909 fileChannel
.force(false);
911 } catch (Exception e
) {
912 logger
.error("Error saving file: {}", e
.getMessage(), e
);
917 private static Pair
<FileChannel
, FileLock
> openFileChannel(File fileName
, boolean waitForLock
) throws IOException
{
918 var fileChannel
= new RandomAccessFile(fileName
, "rw").getChannel();
920 var lock
= fileChannel
.tryLock();
923 logger
.debug("Config file is in use by another instance.");
924 throw new IOException("Config file is in use by another instance.");
926 logger
.info("Config file is in use by another instance, waiting…");
927 lock
= fileChannel
.lock();
928 logger
.info("Config file lock acquired.");
930 final var result
= new Pair
<>(fileChannel
, lock
);
934 if (fileChannel
!= null) {
940 public void addPreKeys(ServiceIdType serviceIdType
, List
<PreKeyRecord
> records
) {
941 if (serviceIdType
.equals(ServiceIdType
.ACI
)) {
942 addAciPreKeys(records
);
944 addPniPreKeys(records
);
948 public void addAciPreKeys(List
<PreKeyRecord
> records
) {
949 for (var record : records
) {
950 if (aciPreKeyIdOffset
!= record.getId()) {
951 logger
.error("Invalid pre key id {}, expected {}", record.getId(), aciPreKeyIdOffset
);
952 throw new AssertionError("Invalid pre key id");
954 getAciPreKeyStore().storePreKey(record.getId(), record);
955 aciPreKeyIdOffset
= (aciPreKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
960 public void addPniPreKeys(List
<PreKeyRecord
> records
) {
961 for (var record : records
) {
962 if (pniPreKeyIdOffset
!= record.getId()) {
963 logger
.error("Invalid pre key id {}, expected {}", record.getId(), pniPreKeyIdOffset
);
964 throw new AssertionError("Invalid pre key id");
966 getPniPreKeyStore().storePreKey(record.getId(), record);
967 pniPreKeyIdOffset
= (pniPreKeyIdOffset
+ 1) % Medium
.MAX_VALUE
;
972 public void addSignedPreKey(ServiceIdType serviceIdType
, SignedPreKeyRecord
record) {
973 if (serviceIdType
.equals(ServiceIdType
.ACI
)) {
974 addAciSignedPreKey(record);
976 addPniSignedPreKey(record);
980 public void addAciSignedPreKey(SignedPreKeyRecord
record) {
981 if (aciNextSignedPreKeyId
!= record.getId()) {
982 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), aciNextSignedPreKeyId
);
983 throw new AssertionError("Invalid signed pre key id");
985 getAciSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
986 aciNextSignedPreKeyId
= (aciNextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
990 public void addPniSignedPreKey(SignedPreKeyRecord
record) {
991 if (pniNextSignedPreKeyId
!= record.getId()) {
992 logger
.error("Invalid signed pre key id {}, expected {}", record.getId(), pniNextSignedPreKeyId
);
993 throw new AssertionError("Invalid signed pre key id");
995 getPniSignedPreKeyStore().storeSignedPreKey(record.getId(), record);
996 pniNextSignedPreKeyId
= (pniNextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
1000 public SignalServiceDataStore
getSignalServiceDataStore() {
1001 return new SignalServiceDataStore() {
1003 public SignalServiceAccountDataStore
get(final ServiceId accountIdentifier
) {
1004 if (accountIdentifier
.equals(aci
)) {
1005 return getSignalServiceAccountDataStore();
1006 } else if (accountIdentifier
.equals(pni
)) {
1007 throw new AssertionError("PNI not to be used yet!");
1009 throw new IllegalArgumentException("No matching store found for " + accountIdentifier
);
1014 public SignalServiceAccountDataStore
aci() {
1015 return getSignalServiceAccountDataStore();
1019 public SignalServiceAccountDataStore
pni() {
1020 throw new AssertionError("PNI not to be used yet!");
1024 public boolean isMultiDevice() {
1025 return SignalAccount
.this.isMultiDevice();
1030 public SignalServiceAccountDataStore
getSignalServiceAccountDataStore() {
1031 return getOrCreate(() -> signalProtocolStore
,
1032 () -> signalProtocolStore
= new SignalProtocolStore(getAciPreKeyStore(),
1033 getAciSignedPreKeyStore(),
1035 getAciIdentityKeyStore(),
1036 getSenderKeyStore(),
1037 this::isMultiDevice
));
1040 private PreKeyStore
getAciPreKeyStore() {
1041 return getOrCreate(() -> aciPreKeyStore
,
1042 () -> aciPreKeyStore
= new PreKeyStore(getAciPreKeysPath(dataPath
, accountPath
)));
1045 private SignedPreKeyStore
getAciSignedPreKeyStore() {
1046 return getOrCreate(() -> aciSignedPreKeyStore
,
1047 () -> aciSignedPreKeyStore
= new SignedPreKeyStore(getAciSignedPreKeysPath(dataPath
, accountPath
)));
1050 private PreKeyStore
getPniPreKeyStore() {
1051 return getOrCreate(() -> pniPreKeyStore
,
1052 () -> pniPreKeyStore
= new PreKeyStore(getPniPreKeysPath(dataPath
, accountPath
)));
1055 private SignedPreKeyStore
getPniSignedPreKeyStore() {
1056 return getOrCreate(() -> pniSignedPreKeyStore
,
1057 () -> pniSignedPreKeyStore
= new SignedPreKeyStore(getPniSignedPreKeysPath(dataPath
, accountPath
)));
1060 public SessionStore
getSessionStore() {
1061 return getOrCreate(() -> sessionStore
,
1062 () -> sessionStore
= new SessionStore(getSessionsPath(dataPath
, accountPath
), getRecipientResolver()));
1065 public IdentityKeyStore
getIdentityKeyStore() {
1066 return getOrCreate(() -> identityKeyStore
,
1067 () -> identityKeyStore
= new IdentityKeyStore(getIdentitiesPath(dataPath
, accountPath
),
1068 getRecipientResolver(),
1072 public SignalIdentityKeyStore
getAciIdentityKeyStore() {
1073 return getOrCreate(() -> aciIdentityKeyStore
,
1074 () -> aciIdentityKeyStore
= new SignalIdentityKeyStore(getRecipientResolver(),
1075 () -> aciIdentityKeyPair
,
1076 localRegistrationId
,
1077 getIdentityKeyStore()));
1080 public GroupStore
getGroupStore() {
1084 public ContactsStore
getContactStore() {
1085 return getRecipientStore();
1088 public RecipientResolver
getRecipientResolver() {
1089 return getRecipientStore();
1092 public RecipientTrustedResolver
getRecipientTrustedResolver() {
1093 return getRecipientStore();
1096 public RecipientAddressResolver
getRecipientAddressResolver() {
1097 return getRecipientStore()::resolveRecipientAddress
;
1100 public RecipientStore
getRecipientStore() {
1101 return getOrCreate(() -> recipientStore
,
1102 () -> recipientStore
= RecipientStore
.load(getRecipientsStoreFile(dataPath
, accountPath
),
1103 this::mergeRecipients
,
1104 this::getSelfRecipientAddress
));
1107 public ProfileStore
getProfileStore() {
1108 return getRecipientStore();
1111 public StickerStore
getStickerStore() {
1112 return stickerStore
;
1115 public SenderKeyStore
getSenderKeyStore() {
1116 return getOrCreate(() -> senderKeyStore
,
1117 () -> senderKeyStore
= new SenderKeyStore(getSharedSenderKeysFile(dataPath
, accountPath
),
1118 getSenderKeysPath(dataPath
, accountPath
),
1119 getRecipientAddressResolver(),
1120 getRecipientResolver()));
1123 public ConfigurationStore
getConfigurationStore() {
1124 return configurationStore
;
1127 public MessageCache
getMessageCache() {
1128 return getOrCreate(() -> messageCache
,
1129 () -> messageCache
= new MessageCache(getMessageCachePath(dataPath
, accountPath
)));
1132 public AccountDatabase
getAccountDatabase() {
1133 return getOrCreate(() -> accountDatabase
, () -> {
1135 accountDatabase
= AccountDatabase
.init(getDatabaseFile(dataPath
, accountPath
));
1136 } catch (SQLException e
) {
1137 throw new RuntimeException(e
);
1142 public MessageSendLogStore
getMessageSendLogStore() {
1143 return getOrCreate(() -> messageSendLogStore
,
1144 () -> messageSendLogStore
= new MessageSendLogStore(getRecipientResolver(), getAccountDatabase()));
1147 public CredentialsProvider
getCredentialsProvider() {
1148 return new CredentialsProvider() {
1150 public ACI
getAci() {
1155 public PNI
getPni() {
1160 public String
getE164() {
1165 public String
getPassword() {
1170 public int getDeviceId() {
1176 public String
getNumber() {
1180 public void setNumber(final String number
) {
1181 this.number
= number
;
1185 public ServiceEnvironment
getServiceEnvironment() {
1186 return serviceEnvironment
;
1189 public void setServiceEnvironment(final ServiceEnvironment serviceEnvironment
) {
1190 this.serviceEnvironment
= serviceEnvironment
;
1194 public ACI
getAci() {
1198 public void setAci(final ACI aci
) {
1203 public PNI
getPni() {
1207 public void setPni(final PNI pni
) {
1212 public SignalServiceAddress
getSelfAddress() {
1213 return new SignalServiceAddress(aci
, number
);
1216 public RecipientAddress
getSelfRecipientAddress() {
1217 return new RecipientAddress(aci
== null ?
null : aci
.uuid(), number
);
1220 public RecipientId
getSelfRecipientId() {
1221 return getRecipientResolver().resolveRecipient(getSelfRecipientAddress());
1224 public byte[] getEncryptedDeviceName() {
1225 return encryptedDeviceName
== null ?
null : Base64
.getDecoder().decode(encryptedDeviceName
);
1228 public void setEncryptedDeviceName(final String encryptedDeviceName
) {
1229 this.encryptedDeviceName
= encryptedDeviceName
;
1233 public int getDeviceId() {
1237 public boolean isPrimaryDevice() {
1238 return deviceId
== SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1241 public IdentityKeyPair
getIdentityKeyPair(ServiceIdType serviceIdType
) {
1242 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciIdentityKeyPair
: pniIdentityKeyPair
;
1245 public IdentityKeyPair
getAciIdentityKeyPair() {
1246 return aciIdentityKeyPair
;
1249 public IdentityKeyPair
getPniIdentityKeyPair() {
1250 return pniIdentityKeyPair
;
1253 public void setPniIdentityKeyPair(final IdentityKeyPair identityKeyPair
) {
1254 pniIdentityKeyPair
= identityKeyPair
;
1258 public int getLocalRegistrationId() {
1259 return localRegistrationId
;
1262 public int getLocalPniRegistrationId() {
1263 return localPniRegistrationId
;
1266 public String
getPassword() {
1270 private void setPassword(final String password
) {
1271 this.password
= password
;
1275 public void setRegistrationLockPin(final String registrationLockPin
) {
1276 this.registrationLockPin
= registrationLockPin
;
1280 public String
getRegistrationLock() {
1281 final var masterKey
= getPinBackedMasterKey();
1282 if (masterKey
== null) {
1285 return masterKey
.deriveRegistrationLock();
1288 public MasterKey
getPinBackedMasterKey() {
1289 if (registrationLockPin
== null) {
1292 return pinMasterKey
;
1295 public MasterKey
getOrCreatePinMasterKey() {
1296 if (pinMasterKey
== null) {
1297 pinMasterKey
= KeyUtils
.createMasterKey();
1300 return pinMasterKey
;
1303 public StorageKey
getStorageKey() {
1304 if (pinMasterKey
!= null) {
1305 return pinMasterKey
.deriveStorageServiceKey();
1310 public StorageKey
getOrCreateStorageKey() {
1311 if (isPrimaryDevice()) {
1312 return getOrCreatePinMasterKey().deriveStorageServiceKey();
1317 public void setStorageKey(final StorageKey storageKey
) {
1318 if (storageKey
.equals(this.storageKey
)) {
1321 this.storageKey
= storageKey
;
1325 public long getStorageManifestVersion() {
1326 return this.storageManifestVersion
;
1329 public void setStorageManifestVersion(final long storageManifestVersion
) {
1330 if (storageManifestVersion
== this.storageManifestVersion
) {
1333 this.storageManifestVersion
= storageManifestVersion
;
1337 public Optional
<SignalStorageManifest
> getStorageManifest() {
1338 final var storageManifestFile
= getStorageManifestFile(dataPath
, accountPath
);
1339 if (!storageManifestFile
.exists()) {
1340 return Optional
.empty();
1342 try (var inputStream
= new FileInputStream(storageManifestFile
)) {
1343 return Optional
.of(SignalStorageManifest
.deserialize(inputStream
.readAllBytes()));
1344 } catch (IOException e
) {
1345 logger
.warn("Failed to read local storage manifest.", e
);
1346 return Optional
.empty();
1350 public void setStorageManifest(SignalStorageManifest manifest
) {
1351 final var storageManifestFile
= getStorageManifestFile(dataPath
, accountPath
);
1352 if (manifest
== null) {
1353 if (storageManifestFile
.exists()) {
1355 Files
.delete(storageManifestFile
.toPath());
1356 } catch (IOException e
) {
1357 logger
.error("Failed to delete local storage manifest.", e
);
1363 final var manifestBytes
= manifest
.serialize();
1364 try (var outputStream
= new FileOutputStream(storageManifestFile
)) {
1365 outputStream
.write(manifestBytes
);
1366 } catch (IOException e
) {
1367 logger
.error("Failed to store local storage manifest.", e
);
1371 public ProfileKey
getProfileKey() {
1375 public void setProfileKey(final ProfileKey profileKey
) {
1376 if (profileKey
.equals(this.profileKey
)) {
1379 this.profileKey
= profileKey
;
1381 getProfileStore().storeSelfProfileKey(getSelfRecipientId(), getProfileKey());
1384 public byte[] getSelfUnidentifiedAccessKey() {
1385 return UnidentifiedAccess
.deriveAccessKeyFrom(getProfileKey());
1388 public int getPreKeyIdOffset(ServiceIdType serviceIdType
) {
1389 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciPreKeyIdOffset
: pniPreKeyIdOffset
;
1392 public int getNextSignedPreKeyId(ServiceIdType serviceIdType
) {
1393 return serviceIdType
.equals(ServiceIdType
.ACI
) ? aciNextSignedPreKeyId
: pniNextSignedPreKeyId
;
1396 public boolean isRegistered() {
1400 public void setRegistered(final boolean registered
) {
1401 this.registered
= registered
;
1405 public boolean isMultiDevice() {
1406 return isMultiDevice
;
1409 public void setMultiDevice(final boolean multiDevice
) {
1410 if (isMultiDevice
== multiDevice
) {
1413 isMultiDevice
= multiDevice
;
1417 public long getLastReceiveTimestamp() {
1418 return lastReceiveTimestamp
;
1421 public void setLastReceiveTimestamp(final long lastReceiveTimestamp
) {
1422 this.lastReceiveTimestamp
= lastReceiveTimestamp
;
1426 public boolean isUnrestrictedUnidentifiedAccess() {
1427 final var profile
= getProfileStore().getProfile(getSelfRecipientId());
1428 return profile
!= null && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
;
1431 public boolean isDiscoverableByPhoneNumber() {
1432 return configurationStore
.getPhoneNumberUnlisted() == null || !configurationStore
.getPhoneNumberUnlisted();
1435 public void finishRegistration(final ACI aci
, final PNI pni
, final MasterKey masterKey
, final String pin
) {
1436 this.pinMasterKey
= masterKey
;
1437 this.storageManifestVersion
= -1;
1438 this.setStorageManifest(null);
1439 this.storageKey
= null;
1440 this.encryptedDeviceName
= null;
1441 this.deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
1442 this.isMultiDevice
= false;
1443 this.registered
= true;
1446 this.registrationLockPin
= pin
;
1447 this.lastReceiveTimestamp
= 0;
1451 getSessionStore().archiveAllSessions();
1452 getSenderKeyStore().deleteAll();
1453 final var recipientId
= getRecipientTrustedResolver().resolveSelfRecipientTrusted(getSelfRecipientAddress());
1454 final var publicKey
= getAciIdentityKeyPair().getPublicKey();
1455 getIdentityKeyStore().saveIdentity(recipientId
, publicKey
);
1456 getIdentityKeyStore().setIdentityTrustLevel(recipientId
, publicKey
, TrustLevel
.TRUSTED_VERIFIED
);
1459 public void deleteAccountData() throws IOException
{
1461 try (final var files
= Files
.walk(getUserPath(dataPath
, accountPath
).toPath())
1462 .sorted(Comparator
.reverseOrder())) {
1463 for (final var file
= files
.iterator(); file
.hasNext(); ) {
1464 Files
.delete(file
.next());
1467 Files
.delete(getFileName(dataPath
, accountPath
).toPath());
1471 public void close() {
1472 synchronized (fileChannel
) {
1473 if (accountDatabase
!= null) {
1475 accountDatabase
.close();
1476 } catch (SQLException e
) {
1477 logger
.warn("Failed to close account database: {}", e
.getMessage(), e
);
1480 if (messageSendLogStore
!= null) {
1481 messageSendLogStore
.close();
1486 } catch (ClosedChannelException ignored
) {
1488 fileChannel
.close();
1489 } catch (IOException e
) {
1490 logger
.warn("Failed to close account: {}", e
.getMessage(), e
);
1495 private <T
> T
getOrCreate(Supplier
<T
> supplier
, Callable creator
) {
1496 var value
= supplier
.get();
1497 if (value
!= null) {
1501 synchronized (LOCK
) {
1502 value
= supplier
.get();
1503 if (value
!= null) {
1507 return supplier
.get();
1511 private interface Callable
{