1 package org
.asamk
.signal
.storage
;
3 import com
.fasterxml
.jackson
.annotation
.JsonAutoDetect
;
4 import com
.fasterxml
.jackson
.annotation
.PropertyAccessor
;
5 import com
.fasterxml
.jackson
.core
.JsonGenerator
;
6 import com
.fasterxml
.jackson
.core
.JsonParser
;
7 import com
.fasterxml
.jackson
.databind
.DeserializationFeature
;
8 import com
.fasterxml
.jackson
.databind
.JsonNode
;
9 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
10 import com
.fasterxml
.jackson
.databind
.SerializationFeature
;
11 import com
.fasterxml
.jackson
.databind
.node
.ObjectNode
;
13 import org
.asamk
.signal
.manager
.GroupId
;
14 import org
.asamk
.signal
.storage
.contacts
.ContactInfo
;
15 import org
.asamk
.signal
.storage
.contacts
.JsonContactsStore
;
16 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
17 import org
.asamk
.signal
.storage
.groups
.GroupInfoV1
;
18 import org
.asamk
.signal
.storage
.groups
.JsonGroupStore
;
19 import org
.asamk
.signal
.storage
.profiles
.ProfileStore
;
20 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
21 import org
.asamk
.signal
.storage
.protocol
.JsonSignalProtocolStore
;
22 import org
.asamk
.signal
.storage
.protocol
.RecipientStore
;
23 import org
.asamk
.signal
.storage
.protocol
.SessionInfo
;
24 import org
.asamk
.signal
.storage
.protocol
.SignalServiceAddressResolver
;
25 import org
.asamk
.signal
.storage
.stickers
.StickerStore
;
26 import org
.asamk
.signal
.storage
.threads
.LegacyJsonThreadStore
;
27 import org
.asamk
.signal
.storage
.threads
.ThreadInfo
;
28 import org
.asamk
.signal
.util
.IOUtils
;
29 import org
.asamk
.signal
.util
.Util
;
30 import org
.signal
.zkgroup
.InvalidInputException
;
31 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
32 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
33 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
34 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
35 import org
.whispersystems
.libsignal
.util
.Medium
;
36 import org
.whispersystems
.libsignal
.util
.Pair
;
37 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
38 import org
.whispersystems
.util
.Base64
;
40 import java
.io
.ByteArrayInputStream
;
41 import java
.io
.ByteArrayOutputStream
;
42 import java
.io
.Closeable
;
44 import java
.io
.IOException
;
45 import java
.io
.RandomAccessFile
;
46 import java
.nio
.channels
.Channels
;
47 import java
.nio
.channels
.ClosedChannelException
;
48 import java
.nio
.channels
.FileChannel
;
49 import java
.nio
.channels
.FileLock
;
50 import java
.util
.Collection
;
51 import java
.util
.UUID
;
52 import java
.util
.stream
.Collectors
;
54 public class SignalAccount
implements Closeable
{
56 private final ObjectMapper jsonProcessor
= new ObjectMapper();
57 private final FileChannel fileChannel
;
58 private final FileLock lock
;
59 private String username
;
61 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
62 private boolean isMultiDevice
= false;
63 private String password
;
64 private String registrationLockPin
;
65 private String signalingKey
;
66 private ProfileKey profileKey
;
67 private int preKeyIdOffset
;
68 private int nextSignedPreKeyId
;
70 private boolean registered
= false;
72 private JsonSignalProtocolStore signalProtocolStore
;
73 private JsonGroupStore groupStore
;
74 private JsonContactsStore contactStore
;
75 private RecipientStore recipientStore
;
76 private ProfileStore profileStore
;
77 private StickerStore stickerStore
;
79 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
80 this.fileChannel
= fileChannel
;
82 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
83 jsonProcessor
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
84 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
85 jsonProcessor
.disable(JsonParser
.Feature
.AUTO_CLOSE_SOURCE
);
86 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
89 public static SignalAccount
load(String dataPath
, String username
) throws IOException
{
90 final String fileName
= getFileName(dataPath
, username
);
91 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
93 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
94 account
.load(dataPath
);
96 } catch (Throwable e
) {
97 pair
.second().close();
103 public static SignalAccount
create(
104 String dataPath
, String username
, IdentityKeyPair identityKey
, int registrationId
, ProfileKey profileKey
105 ) throws IOException
{
106 IOUtils
.createPrivateDirectories(dataPath
);
107 String fileName
= getFileName(dataPath
, username
);
108 if (!new File(fileName
).exists()) {
109 IOUtils
.createPrivateFile(fileName
);
112 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
113 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
115 account
.username
= username
;
116 account
.profileKey
= profileKey
;
117 account
.signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
118 account
.groupStore
= new JsonGroupStore(getGroupCachePath(dataPath
, username
));
119 account
.contactStore
= new JsonContactsStore();
120 account
.recipientStore
= new RecipientStore();
121 account
.profileStore
= new ProfileStore();
122 account
.stickerStore
= new StickerStore();
123 account
.registered
= false;
128 public static SignalAccount
createLinkedAccount(
134 IdentityKeyPair identityKey
,
137 ProfileKey profileKey
138 ) throws IOException
{
139 IOUtils
.createPrivateDirectories(dataPath
);
140 String fileName
= getFileName(dataPath
, username
);
141 if (!new File(fileName
).exists()) {
142 IOUtils
.createPrivateFile(fileName
);
145 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
146 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
148 account
.username
= username
;
150 account
.password
= password
;
151 account
.profileKey
= profileKey
;
152 account
.deviceId
= deviceId
;
153 account
.signalingKey
= signalingKey
;
154 account
.signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
155 account
.groupStore
= new JsonGroupStore(getGroupCachePath(dataPath
, username
));
156 account
.contactStore
= new JsonContactsStore();
157 account
.recipientStore
= new RecipientStore();
158 account
.profileStore
= new ProfileStore();
159 account
.stickerStore
= new StickerStore();
160 account
.registered
= true;
161 account
.isMultiDevice
= true;
166 public static String
getFileName(String dataPath
, String username
) {
167 return dataPath
+ "/" + username
;
170 private static File
getGroupCachePath(String dataPath
, String username
) {
171 return new File(new File(dataPath
, username
+ ".d"), "group-cache");
174 public static boolean userExists(String dataPath
, String username
) {
175 if (username
== null) {
178 File f
= new File(getFileName(dataPath
, username
));
179 return !(!f
.exists() || f
.isDirectory());
182 private void load(String dataPath
) throws IOException
{
184 synchronized (fileChannel
) {
185 fileChannel
.position(0);
186 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
189 JsonNode uuidNode
= rootNode
.get("uuid");
190 if (uuidNode
!= null && !uuidNode
.isNull()) {
192 uuid
= UUID
.fromString(uuidNode
.asText());
193 } catch (IllegalArgumentException e
) {
194 throw new IOException("Config file contains an invalid uuid, needs to be a valid UUID", e
);
197 JsonNode node
= rootNode
.get("deviceId");
199 deviceId
= node
.asInt();
201 if (rootNode
.has("isMultiDevice")) {
202 isMultiDevice
= Util
.getNotNullNode(rootNode
, "isMultiDevice").asBoolean();
204 username
= Util
.getNotNullNode(rootNode
, "username").asText();
205 password
= Util
.getNotNullNode(rootNode
, "password").asText();
206 JsonNode pinNode
= rootNode
.get("registrationLockPin");
207 registrationLockPin
= pinNode
== null || pinNode
.isNull() ?
null : pinNode
.asText();
208 if (rootNode
.has("signalingKey")) {
209 signalingKey
= Util
.getNotNullNode(rootNode
, "signalingKey").asText();
211 if (rootNode
.has("preKeyIdOffset")) {
212 preKeyIdOffset
= Util
.getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
216 if (rootNode
.has("nextSignedPreKeyId")) {
217 nextSignedPreKeyId
= Util
.getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
219 nextSignedPreKeyId
= 0;
221 if (rootNode
.has("profileKey")) {
223 profileKey
= new ProfileKey(Base64
.decode(Util
.getNotNullNode(rootNode
, "profileKey").asText()));
224 } catch (InvalidInputException e
) {
225 throw new IOException(
226 "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
231 signalProtocolStore
= jsonProcessor
.convertValue(Util
.getNotNullNode(rootNode
, "axolotlStore"),
232 JsonSignalProtocolStore
.class);
233 registered
= Util
.getNotNullNode(rootNode
, "registered").asBoolean();
234 JsonNode groupStoreNode
= rootNode
.get("groupStore");
235 if (groupStoreNode
!= null) {
236 groupStore
= jsonProcessor
.convertValue(groupStoreNode
, JsonGroupStore
.class);
237 groupStore
.groupCachePath
= getGroupCachePath(dataPath
, username
);
239 if (groupStore
== null) {
240 groupStore
= new JsonGroupStore(getGroupCachePath(dataPath
, username
));
243 JsonNode contactStoreNode
= rootNode
.get("contactStore");
244 if (contactStoreNode
!= null) {
245 contactStore
= jsonProcessor
.convertValue(contactStoreNode
, JsonContactsStore
.class);
247 if (contactStore
== null) {
248 contactStore
= new JsonContactsStore();
251 JsonNode recipientStoreNode
= rootNode
.get("recipientStore");
252 if (recipientStoreNode
!= null) {
253 recipientStore
= jsonProcessor
.convertValue(recipientStoreNode
, RecipientStore
.class);
255 if (recipientStore
== null) {
256 recipientStore
= new RecipientStore();
258 recipientStore
.resolveServiceAddress(getSelfAddress());
260 for (ContactInfo contact
: contactStore
.getContacts()) {
261 recipientStore
.resolveServiceAddress(contact
.getAddress());
264 for (GroupInfo group
: groupStore
.getGroups()) {
265 if (group
instanceof GroupInfoV1
) {
266 GroupInfoV1 groupInfoV1
= (GroupInfoV1
) group
;
267 groupInfoV1
.members
= groupInfoV1
.members
.stream()
268 .map(m
-> recipientStore
.resolveServiceAddress(m
))
269 .collect(Collectors
.toSet());
273 for (SessionInfo session
: signalProtocolStore
.getSessions()) {
274 session
.address
= recipientStore
.resolveServiceAddress(session
.address
);
277 for (JsonIdentityKeyStore
.Identity identity
: signalProtocolStore
.getIdentities()) {
278 identity
.setAddress(recipientStore
.resolveServiceAddress(identity
.getAddress()));
282 JsonNode profileStoreNode
= rootNode
.get("profileStore");
283 if (profileStoreNode
!= null) {
284 profileStore
= jsonProcessor
.convertValue(profileStoreNode
, ProfileStore
.class);
286 if (profileStore
== null) {
287 profileStore
= new ProfileStore();
290 JsonNode stickerStoreNode
= rootNode
.get("stickerStore");
291 if (stickerStoreNode
!= null) {
292 stickerStore
= jsonProcessor
.convertValue(stickerStoreNode
, StickerStore
.class);
294 if (stickerStore
== null) {
295 stickerStore
= new StickerStore();
298 JsonNode threadStoreNode
= rootNode
.get("threadStore");
299 if (threadStoreNode
!= null) {
300 LegacyJsonThreadStore threadStore
= jsonProcessor
.convertValue(threadStoreNode
,
301 LegacyJsonThreadStore
.class);
302 // Migrate thread info to group and contact store
303 for (ThreadInfo thread
: threadStore
.getThreads()) {
304 if (thread
.id
== null || thread
.id
.isEmpty()) {
308 ContactInfo contactInfo
= contactStore
.getContact(new SignalServiceAddress(null, thread
.id
));
309 if (contactInfo
!= null) {
310 contactInfo
.messageExpirationTime
= thread
.messageExpirationTime
;
311 contactStore
.updateContact(contactInfo
);
313 GroupInfo groupInfo
= groupStore
.getGroup(GroupId
.fromBase64(thread
.id
));
314 if (groupInfo
instanceof GroupInfoV1
) {
315 ((GroupInfoV1
) groupInfo
).messageExpirationTime
= thread
.messageExpirationTime
;
316 groupStore
.updateGroup(groupInfo
);
319 } catch (Exception ignored
) {
326 if (fileChannel
== null) {
329 ObjectNode rootNode
= jsonProcessor
.createObjectNode();
330 rootNode
.put("username", username
)
331 .put("uuid", uuid
== null ?
null : uuid
.toString())
332 .put("deviceId", deviceId
)
333 .put("isMultiDevice", isMultiDevice
)
334 .put("password", password
)
335 .put("registrationLockPin", registrationLockPin
)
336 .put("signalingKey", signalingKey
)
337 .put("preKeyIdOffset", preKeyIdOffset
)
338 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
339 .put("profileKey", Base64
.encodeBytes(profileKey
.serialize()))
340 .put("registered", registered
)
341 .putPOJO("axolotlStore", signalProtocolStore
)
342 .putPOJO("groupStore", groupStore
)
343 .putPOJO("contactStore", contactStore
)
344 .putPOJO("recipientStore", recipientStore
)
345 .putPOJO("profileStore", profileStore
)
346 .putPOJO("stickerStore", stickerStore
);
348 try (ByteArrayOutputStream output
= new ByteArrayOutputStream()) {
349 // Write to memory first to prevent corrupting the file in case of serialization errors
350 jsonProcessor
.writeValue(output
, rootNode
);
351 ByteArrayInputStream input
= new ByteArrayInputStream(output
.toByteArray());
352 synchronized (fileChannel
) {
353 fileChannel
.position(0);
354 input
.transferTo(Channels
.newOutputStream(fileChannel
));
355 fileChannel
.truncate(fileChannel
.position());
356 fileChannel
.force(false);
359 } catch (Exception e
) {
360 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
364 private static Pair
<FileChannel
, FileLock
> openFileChannel(String fileName
) throws IOException
{
365 FileChannel fileChannel
= new RandomAccessFile(new File(fileName
), "rw").getChannel();
366 FileLock lock
= fileChannel
.tryLock();
368 System
.err
.println("Config file is in use by another instance, waiting…");
369 lock
= fileChannel
.lock();
370 System
.err
.println("Config file lock acquired.");
372 return new Pair
<>(fileChannel
, lock
);
375 public void setResolver(final SignalServiceAddressResolver resolver
) {
376 signalProtocolStore
.setResolver(resolver
);
379 public void addPreKeys(Collection
<PreKeyRecord
> records
) {
380 for (PreKeyRecord
record : records
) {
381 signalProtocolStore
.storePreKey(record.getId(), record);
383 preKeyIdOffset
= (preKeyIdOffset
+ records
.size()) % Medium
.MAX_VALUE
;
386 public void addSignedPreKey(SignedPreKeyRecord
record) {
387 signalProtocolStore
.storeSignedPreKey(record.getId(), record);
388 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
391 public JsonSignalProtocolStore
getSignalProtocolStore() {
392 return signalProtocolStore
;
395 public JsonGroupStore
getGroupStore() {
399 public JsonContactsStore
getContactStore() {
403 public RecipientStore
getRecipientStore() {
404 return recipientStore
;
407 public ProfileStore
getProfileStore() {
411 public StickerStore
getStickerStore() {
415 public String
getUsername() {
419 public UUID
getUuid() {
423 public void setUuid(final UUID uuid
) {
427 public SignalServiceAddress
getSelfAddress() {
428 return new SignalServiceAddress(uuid
, username
);
431 public int getDeviceId() {
435 public String
getPassword() {
439 public void setPassword(final String password
) {
440 this.password
= password
;
443 public String
getRegistrationLockPin() {
444 return registrationLockPin
;
447 public String
getRegistrationLock() {
448 return null; // TODO implement KBS
451 public void setRegistrationLockPin(final String registrationLockPin
) {
452 this.registrationLockPin
= registrationLockPin
;
455 public String
getSignalingKey() {
459 public void setSignalingKey(final String signalingKey
) {
460 this.signalingKey
= signalingKey
;
463 public ProfileKey
getProfileKey() {
467 public void setProfileKey(final ProfileKey profileKey
) {
468 this.profileKey
= profileKey
;
471 public int getPreKeyIdOffset() {
472 return preKeyIdOffset
;
475 public int getNextSignedPreKeyId() {
476 return nextSignedPreKeyId
;
479 public boolean isRegistered() {
483 public void setRegistered(final boolean registered
) {
484 this.registered
= registered
;
487 public boolean isMultiDevice() {
488 return isMultiDevice
;
491 public void setMultiDevice(final boolean multiDevice
) {
492 isMultiDevice
= multiDevice
;
496 public void close() throws IOException
{
497 synchronized (fileChannel
) {
500 } catch (ClosedChannelException ignored
) {