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
.storage
.contacts
.ContactInfo
;
14 import org
.asamk
.signal
.storage
.contacts
.JsonContactsStore
;
15 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
16 import org
.asamk
.signal
.storage
.groups
.JsonGroupStore
;
17 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
18 import org
.asamk
.signal
.storage
.protocol
.JsonSignalProtocolStore
;
19 import org
.asamk
.signal
.storage
.protocol
.RecipientStore
;
20 import org
.asamk
.signal
.storage
.protocol
.SessionInfo
;
21 import org
.asamk
.signal
.storage
.protocol
.SignalServiceAddressResolver
;
22 import org
.asamk
.signal
.storage
.threads
.LegacyJsonThreadStore
;
23 import org
.asamk
.signal
.storage
.threads
.ThreadInfo
;
24 import org
.asamk
.signal
.util
.IOUtils
;
25 import org
.asamk
.signal
.util
.Util
;
26 import org
.signal
.zkgroup
.InvalidInputException
;
27 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
28 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
29 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
30 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
31 import org
.whispersystems
.libsignal
.util
.Medium
;
32 import org
.whispersystems
.libsignal
.util
.Pair
;
33 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
34 import org
.whispersystems
.util
.Base64
;
36 import java
.io
.Closeable
;
38 import java
.io
.IOException
;
39 import java
.io
.RandomAccessFile
;
40 import java
.nio
.channels
.Channels
;
41 import java
.nio
.channels
.FileChannel
;
42 import java
.nio
.channels
.FileLock
;
43 import java
.util
.Collection
;
44 import java
.util
.UUID
;
45 import java
.util
.stream
.Collectors
;
47 public class SignalAccount
implements Closeable
{
49 private final ObjectMapper jsonProcessor
= new ObjectMapper();
50 private final FileChannel fileChannel
;
51 private final FileLock lock
;
52 private String username
;
54 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
55 private boolean isMultiDevice
= false;
56 private String password
;
57 private String registrationLockPin
;
58 private String signalingKey
;
59 private ProfileKey profileKey
;
60 private int preKeyIdOffset
;
61 private int nextSignedPreKeyId
;
63 private boolean registered
= false;
65 private JsonSignalProtocolStore signalProtocolStore
;
66 private JsonGroupStore groupStore
;
67 private JsonContactsStore contactStore
;
68 private RecipientStore recipientStore
;
70 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
71 this.fileChannel
= fileChannel
;
73 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
74 jsonProcessor
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
75 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
76 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
77 jsonProcessor
.disable(JsonParser
.Feature
.AUTO_CLOSE_SOURCE
);
78 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
81 public static SignalAccount
load(String dataPath
, String username
) throws IOException
{
82 final String fileName
= getFileName(dataPath
, username
);
83 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
85 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
88 } catch (Throwable e
) {
89 pair
.second().close();
95 public static SignalAccount
create(String dataPath
, String username
, IdentityKeyPair identityKey
, int registrationId
, ProfileKey profileKey
) throws IOException
{
96 IOUtils
.createPrivateDirectories(dataPath
);
97 String fileName
= getFileName(dataPath
, username
);
98 if (!new File(fileName
).exists()) {
99 IOUtils
.createPrivateFile(fileName
);
102 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
103 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
105 account
.username
= username
;
106 account
.profileKey
= profileKey
;
107 account
.signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
108 account
.groupStore
= new JsonGroupStore();
109 account
.contactStore
= new JsonContactsStore();
110 account
.recipientStore
= new RecipientStore();
111 account
.registered
= false;
116 public static SignalAccount
createLinkedAccount(String dataPath
, String username
, UUID uuid
, String password
, int deviceId
, IdentityKeyPair identityKey
, int registrationId
, String signalingKey
, ProfileKey profileKey
) throws IOException
{
117 IOUtils
.createPrivateDirectories(dataPath
);
118 String fileName
= getFileName(dataPath
, username
);
119 if (!new File(fileName
).exists()) {
120 IOUtils
.createPrivateFile(fileName
);
123 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
124 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
126 account
.username
= username
;
128 account
.password
= password
;
129 account
.profileKey
= profileKey
;
130 account
.deviceId
= deviceId
;
131 account
.signalingKey
= signalingKey
;
132 account
.signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
133 account
.groupStore
= new JsonGroupStore();
134 account
.contactStore
= new JsonContactsStore();
135 account
.recipientStore
= new RecipientStore();
136 account
.registered
= true;
137 account
.isMultiDevice
= true;
142 public static String
getFileName(String dataPath
, String username
) {
143 return dataPath
+ "/" + username
;
146 public static boolean userExists(String dataPath
, String username
) {
147 if (username
== null) {
150 File f
= new File(getFileName(dataPath
, username
));
151 return !(!f
.exists() || f
.isDirectory());
154 private void load() throws IOException
{
156 synchronized (fileChannel
) {
157 fileChannel
.position(0);
158 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
161 JsonNode uuidNode
= rootNode
.get("uuid");
162 if (uuidNode
!= null && !uuidNode
.isNull()) {
164 uuid
= UUID
.fromString(uuidNode
.asText());
165 } catch (IllegalArgumentException e
) {
166 throw new IOException("Config file contains an invalid uuid, needs to be a valid UUID", e
);
169 JsonNode node
= rootNode
.get("deviceId");
171 deviceId
= node
.asInt();
173 if (rootNode
.has("isMultiDevice")) {
174 isMultiDevice
= Util
.getNotNullNode(rootNode
, "isMultiDevice").asBoolean();
176 username
= Util
.getNotNullNode(rootNode
, "username").asText();
177 password
= Util
.getNotNullNode(rootNode
, "password").asText();
178 JsonNode pinNode
= rootNode
.get("registrationLockPin");
179 registrationLockPin
= pinNode
== null || pinNode
.isNull() ?
null : pinNode
.asText();
180 if (rootNode
.has("signalingKey")) {
181 signalingKey
= Util
.getNotNullNode(rootNode
, "signalingKey").asText();
183 if (rootNode
.has("preKeyIdOffset")) {
184 preKeyIdOffset
= Util
.getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
188 if (rootNode
.has("nextSignedPreKeyId")) {
189 nextSignedPreKeyId
= Util
.getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
191 nextSignedPreKeyId
= 0;
193 if (rootNode
.has("profileKey")) {
195 profileKey
= new ProfileKey(Base64
.decode(Util
.getNotNullNode(rootNode
, "profileKey").asText()));
196 } catch (InvalidInputException e
) {
197 throw new IOException("Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes", e
);
201 signalProtocolStore
= jsonProcessor
.convertValue(Util
.getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
202 registered
= Util
.getNotNullNode(rootNode
, "registered").asBoolean();
203 JsonNode groupStoreNode
= rootNode
.get("groupStore");
204 if (groupStoreNode
!= null) {
205 groupStore
= jsonProcessor
.convertValue(groupStoreNode
, JsonGroupStore
.class);
207 if (groupStore
== null) {
208 groupStore
= new JsonGroupStore();
211 JsonNode contactStoreNode
= rootNode
.get("contactStore");
212 if (contactStoreNode
!= null) {
213 contactStore
= jsonProcessor
.convertValue(contactStoreNode
, JsonContactsStore
.class);
215 if (contactStore
== null) {
216 contactStore
= new JsonContactsStore();
219 JsonNode recipientStoreNode
= rootNode
.get("recipientStore");
220 if (recipientStoreNode
!= null) {
221 recipientStore
= jsonProcessor
.convertValue(recipientStoreNode
, RecipientStore
.class);
223 if (recipientStore
== null) {
224 recipientStore
= new RecipientStore();
226 recipientStore
.resolveServiceAddress(getSelfAddress());
228 for (ContactInfo contact
: contactStore
.getContacts()) {
229 recipientStore
.resolveServiceAddress(contact
.getAddress());
232 for (GroupInfo group
: groupStore
.getGroups()) {
233 group
.members
= group
.members
.stream()
234 .map(m
-> recipientStore
.resolveServiceAddress(m
))
235 .collect(Collectors
.toSet());
238 for (SessionInfo session
: signalProtocolStore
.getSessions()) {
239 session
.address
= recipientStore
.resolveServiceAddress(session
.address
);
242 for (JsonIdentityKeyStore
.Identity identity
: signalProtocolStore
.getIdentities()) {
243 identity
.setAddress(recipientStore
.resolveServiceAddress(identity
.getAddress()));
247 JsonNode threadStoreNode
= rootNode
.get("threadStore");
248 if (threadStoreNode
!= null) {
249 LegacyJsonThreadStore threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
250 // Migrate thread info to group and contact store
251 for (ThreadInfo thread
: threadStore
.getThreads()) {
252 if (thread
.id
== null || thread
.id
.isEmpty()) {
256 ContactInfo contactInfo
= contactStore
.getContact(new SignalServiceAddress(null, thread
.id
));
257 if (contactInfo
!= null) {
258 contactInfo
.messageExpirationTime
= thread
.messageExpirationTime
;
259 contactStore
.updateContact(contactInfo
);
261 GroupInfo groupInfo
= groupStore
.getGroup(Base64
.decode(thread
.id
));
262 if (groupInfo
!= null) {
263 groupInfo
.messageExpirationTime
= thread
.messageExpirationTime
;
264 groupStore
.updateGroup(groupInfo
);
267 } catch (Exception ignored
) {
274 if (fileChannel
== null) {
277 ObjectNode rootNode
= jsonProcessor
.createObjectNode();
278 rootNode
.put("username", username
)
279 .put("uuid", uuid
== null ?
null : uuid
.toString())
280 .put("deviceId", deviceId
)
281 .put("isMultiDevice", isMultiDevice
)
282 .put("password", password
)
283 .put("registrationLockPin", registrationLockPin
)
284 .put("signalingKey", signalingKey
)
285 .put("preKeyIdOffset", preKeyIdOffset
)
286 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
287 .put("profileKey", Base64
.encodeBytes(profileKey
.serialize()))
288 .put("registered", registered
)
289 .putPOJO("axolotlStore", signalProtocolStore
)
290 .putPOJO("groupStore", groupStore
)
291 .putPOJO("contactStore", contactStore
)
292 .putPOJO("recipientStore", recipientStore
)
295 synchronized (fileChannel
) {
296 fileChannel
.position(0);
297 jsonProcessor
.writeValue(Channels
.newOutputStream(fileChannel
), rootNode
);
298 fileChannel
.truncate(fileChannel
.position());
299 fileChannel
.force(false);
301 } catch (Exception e
) {
302 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
306 private static Pair
<FileChannel
, FileLock
> openFileChannel(String fileName
) throws IOException
{
307 FileChannel fileChannel
= new RandomAccessFile(new File(fileName
), "rw").getChannel();
308 FileLock lock
= fileChannel
.tryLock();
310 System
.err
.println("Config file is in use by another instance, waiting…");
311 lock
= fileChannel
.lock();
312 System
.err
.println("Config file lock acquired.");
314 return new Pair
<>(fileChannel
, lock
);
317 public void setResolver(final SignalServiceAddressResolver resolver
) {
318 signalProtocolStore
.setResolver(resolver
);
321 public void addPreKeys(Collection
<PreKeyRecord
> records
) {
322 for (PreKeyRecord
record : records
) {
323 signalProtocolStore
.storePreKey(record.getId(), record);
325 preKeyIdOffset
= (preKeyIdOffset
+ records
.size()) % Medium
.MAX_VALUE
;
328 public void addSignedPreKey(SignedPreKeyRecord
record) {
329 signalProtocolStore
.storeSignedPreKey(record.getId(), record);
330 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
333 public JsonSignalProtocolStore
getSignalProtocolStore() {
334 return signalProtocolStore
;
337 public JsonGroupStore
getGroupStore() {
341 public JsonContactsStore
getContactStore() {
345 public RecipientStore
getRecipientStore() {
346 return recipientStore
;
349 public String
getUsername() {
353 public UUID
getUuid() {
357 public void setUuid(final UUID uuid
) {
361 public SignalServiceAddress
getSelfAddress() {
362 return new SignalServiceAddress(uuid
, username
);
365 public int getDeviceId() {
369 public String
getPassword() {
373 public void setPassword(final String password
) {
374 this.password
= password
;
377 public String
getRegistrationLockPin() {
378 return registrationLockPin
;
381 public String
getRegistrationLock() {
382 return null; // TODO implement KBS
385 public void setRegistrationLockPin(final String registrationLockPin
) {
386 this.registrationLockPin
= registrationLockPin
;
389 public String
getSignalingKey() {
393 public void setSignalingKey(final String signalingKey
) {
394 this.signalingKey
= signalingKey
;
397 public ProfileKey
getProfileKey() {
401 public void setProfileKey(final ProfileKey profileKey
) {
402 this.profileKey
= profileKey
;
405 public int getPreKeyIdOffset() {
406 return preKeyIdOffset
;
409 public int getNextSignedPreKeyId() {
410 return nextSignedPreKeyId
;
413 public boolean isRegistered() {
417 public void setRegistered(final boolean registered
) {
418 this.registered
= registered
;
421 public boolean isMultiDevice() {
422 return isMultiDevice
;
425 public void setMultiDevice(final boolean multiDevice
) {
426 isMultiDevice
= multiDevice
;
430 public void close() throws IOException
{
431 synchronized (fileChannel
) {