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
.profiles
.ProfileStore
;
18 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
19 import org
.asamk
.signal
.storage
.protocol
.JsonSignalProtocolStore
;
20 import org
.asamk
.signal
.storage
.protocol
.RecipientStore
;
21 import org
.asamk
.signal
.storage
.protocol
.SessionInfo
;
22 import org
.asamk
.signal
.storage
.protocol
.SignalServiceAddressResolver
;
23 import org
.asamk
.signal
.storage
.threads
.LegacyJsonThreadStore
;
24 import org
.asamk
.signal
.storage
.threads
.ThreadInfo
;
25 import org
.asamk
.signal
.util
.IOUtils
;
26 import org
.asamk
.signal
.util
.Util
;
27 import org
.signal
.zkgroup
.InvalidInputException
;
28 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
29 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
30 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
31 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
32 import org
.whispersystems
.libsignal
.util
.Medium
;
33 import org
.whispersystems
.libsignal
.util
.Pair
;
34 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
35 import org
.whispersystems
.util
.Base64
;
37 import java
.io
.Closeable
;
39 import java
.io
.IOException
;
40 import java
.io
.RandomAccessFile
;
41 import java
.nio
.channels
.Channels
;
42 import java
.nio
.channels
.ClosedChannelException
;
43 import java
.nio
.channels
.FileChannel
;
44 import java
.nio
.channels
.FileLock
;
45 import java
.util
.Collection
;
46 import java
.util
.UUID
;
47 import java
.util
.stream
.Collectors
;
49 public class SignalAccount
implements Closeable
{
51 private final ObjectMapper jsonProcessor
= new ObjectMapper();
52 private final FileChannel fileChannel
;
53 private final FileLock lock
;
54 private String username
;
56 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
57 private boolean isMultiDevice
= false;
58 private String password
;
59 private String registrationLockPin
;
60 private String signalingKey
;
61 private ProfileKey profileKey
;
62 private int preKeyIdOffset
;
63 private int nextSignedPreKeyId
;
65 private boolean registered
= false;
67 private JsonSignalProtocolStore signalProtocolStore
;
68 private JsonGroupStore groupStore
;
69 private JsonContactsStore contactStore
;
70 private RecipientStore recipientStore
;
71 private ProfileStore profileStore
;
73 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
74 this.fileChannel
= fileChannel
;
76 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
77 jsonProcessor
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
78 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
79 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
80 jsonProcessor
.disable(JsonParser
.Feature
.AUTO_CLOSE_SOURCE
);
81 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
84 public static SignalAccount
load(String dataPath
, String username
) throws IOException
{
85 final String fileName
= getFileName(dataPath
, username
);
86 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
88 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
91 } catch (Throwable e
) {
92 pair
.second().close();
98 public static SignalAccount
create(String dataPath
, String username
, IdentityKeyPair identityKey
, int registrationId
, ProfileKey profileKey
) throws IOException
{
99 IOUtils
.createPrivateDirectories(dataPath
);
100 String fileName
= getFileName(dataPath
, username
);
101 if (!new File(fileName
).exists()) {
102 IOUtils
.createPrivateFile(fileName
);
105 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
106 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
108 account
.username
= username
;
109 account
.profileKey
= profileKey
;
110 account
.signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
111 account
.groupStore
= new JsonGroupStore();
112 account
.contactStore
= new JsonContactsStore();
113 account
.recipientStore
= new RecipientStore();
114 account
.profileStore
= new ProfileStore();
115 account
.registered
= false;
120 public static SignalAccount
createLinkedAccount(String dataPath
, String username
, UUID uuid
, String password
, int deviceId
, IdentityKeyPair identityKey
, int registrationId
, String signalingKey
, ProfileKey profileKey
) throws IOException
{
121 IOUtils
.createPrivateDirectories(dataPath
);
122 String fileName
= getFileName(dataPath
, username
);
123 if (!new File(fileName
).exists()) {
124 IOUtils
.createPrivateFile(fileName
);
127 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
128 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
130 account
.username
= username
;
132 account
.password
= password
;
133 account
.profileKey
= profileKey
;
134 account
.deviceId
= deviceId
;
135 account
.signalingKey
= signalingKey
;
136 account
.signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
137 account
.groupStore
= new JsonGroupStore();
138 account
.contactStore
= new JsonContactsStore();
139 account
.recipientStore
= new RecipientStore();
140 account
.profileStore
= new ProfileStore();
141 account
.registered
= true;
142 account
.isMultiDevice
= true;
147 public static String
getFileName(String dataPath
, String username
) {
148 return dataPath
+ "/" + username
;
151 public static boolean userExists(String dataPath
, String username
) {
152 if (username
== null) {
155 File f
= new File(getFileName(dataPath
, username
));
156 return !(!f
.exists() || f
.isDirectory());
159 private void load() throws IOException
{
161 synchronized (fileChannel
) {
162 fileChannel
.position(0);
163 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
166 JsonNode uuidNode
= rootNode
.get("uuid");
167 if (uuidNode
!= null && !uuidNode
.isNull()) {
169 uuid
= UUID
.fromString(uuidNode
.asText());
170 } catch (IllegalArgumentException e
) {
171 throw new IOException("Config file contains an invalid uuid, needs to be a valid UUID", e
);
174 JsonNode node
= rootNode
.get("deviceId");
176 deviceId
= node
.asInt();
178 if (rootNode
.has("isMultiDevice")) {
179 isMultiDevice
= Util
.getNotNullNode(rootNode
, "isMultiDevice").asBoolean();
181 username
= Util
.getNotNullNode(rootNode
, "username").asText();
182 password
= Util
.getNotNullNode(rootNode
, "password").asText();
183 JsonNode pinNode
= rootNode
.get("registrationLockPin");
184 registrationLockPin
= pinNode
== null || pinNode
.isNull() ?
null : pinNode
.asText();
185 if (rootNode
.has("signalingKey")) {
186 signalingKey
= Util
.getNotNullNode(rootNode
, "signalingKey").asText();
188 if (rootNode
.has("preKeyIdOffset")) {
189 preKeyIdOffset
= Util
.getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
193 if (rootNode
.has("nextSignedPreKeyId")) {
194 nextSignedPreKeyId
= Util
.getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
196 nextSignedPreKeyId
= 0;
198 if (rootNode
.has("profileKey")) {
200 profileKey
= new ProfileKey(Base64
.decode(Util
.getNotNullNode(rootNode
, "profileKey").asText()));
201 } catch (InvalidInputException e
) {
202 throw new IOException("Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes", e
);
206 signalProtocolStore
= jsonProcessor
.convertValue(Util
.getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
207 registered
= Util
.getNotNullNode(rootNode
, "registered").asBoolean();
208 JsonNode groupStoreNode
= rootNode
.get("groupStore");
209 if (groupStoreNode
!= null) {
210 groupStore
= jsonProcessor
.convertValue(groupStoreNode
, JsonGroupStore
.class);
212 if (groupStore
== null) {
213 groupStore
= new JsonGroupStore();
216 JsonNode contactStoreNode
= rootNode
.get("contactStore");
217 if (contactStoreNode
!= null) {
218 contactStore
= jsonProcessor
.convertValue(contactStoreNode
, JsonContactsStore
.class);
220 if (contactStore
== null) {
221 contactStore
= new JsonContactsStore();
224 JsonNode recipientStoreNode
= rootNode
.get("recipientStore");
225 if (recipientStoreNode
!= null) {
226 recipientStore
= jsonProcessor
.convertValue(recipientStoreNode
, RecipientStore
.class);
228 if (recipientStore
== null) {
229 recipientStore
= new RecipientStore();
231 recipientStore
.resolveServiceAddress(getSelfAddress());
233 for (ContactInfo contact
: contactStore
.getContacts()) {
234 recipientStore
.resolveServiceAddress(contact
.getAddress());
237 for (GroupInfo group
: groupStore
.getGroups()) {
238 group
.members
= group
.members
.stream()
239 .map(m
-> recipientStore
.resolveServiceAddress(m
))
240 .collect(Collectors
.toSet());
243 for (SessionInfo session
: signalProtocolStore
.getSessions()) {
244 session
.address
= recipientStore
.resolveServiceAddress(session
.address
);
247 for (JsonIdentityKeyStore
.Identity identity
: signalProtocolStore
.getIdentities()) {
248 identity
.setAddress(recipientStore
.resolveServiceAddress(identity
.getAddress()));
252 JsonNode profileStoreNode
= rootNode
.get("profileStore");
253 if (profileStoreNode
!= null) {
254 profileStore
= jsonProcessor
.convertValue(profileStoreNode
, ProfileStore
.class);
256 if (profileStore
== null) {
257 profileStore
= new ProfileStore();
260 JsonNode threadStoreNode
= rootNode
.get("threadStore");
261 if (threadStoreNode
!= null) {
262 LegacyJsonThreadStore threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
263 // Migrate thread info to group and contact store
264 for (ThreadInfo thread
: threadStore
.getThreads()) {
265 if (thread
.id
== null || thread
.id
.isEmpty()) {
269 ContactInfo contactInfo
= contactStore
.getContact(new SignalServiceAddress(null, thread
.id
));
270 if (contactInfo
!= null) {
271 contactInfo
.messageExpirationTime
= thread
.messageExpirationTime
;
272 contactStore
.updateContact(contactInfo
);
274 GroupInfo groupInfo
= groupStore
.getGroup(Base64
.decode(thread
.id
));
275 if (groupInfo
!= null) {
276 groupInfo
.messageExpirationTime
= thread
.messageExpirationTime
;
277 groupStore
.updateGroup(groupInfo
);
280 } catch (Exception ignored
) {
287 if (fileChannel
== null) {
290 ObjectNode rootNode
= jsonProcessor
.createObjectNode();
291 rootNode
.put("username", username
)
292 .put("uuid", uuid
== null ?
null : uuid
.toString())
293 .put("deviceId", deviceId
)
294 .put("isMultiDevice", isMultiDevice
)
295 .put("password", password
)
296 .put("registrationLockPin", registrationLockPin
)
297 .put("signalingKey", signalingKey
)
298 .put("preKeyIdOffset", preKeyIdOffset
)
299 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
300 .put("profileKey", Base64
.encodeBytes(profileKey
.serialize()))
301 .put("registered", registered
)
302 .putPOJO("axolotlStore", signalProtocolStore
)
303 .putPOJO("groupStore", groupStore
)
304 .putPOJO("contactStore", contactStore
)
305 .putPOJO("recipientStore", recipientStore
)
306 .putPOJO("profileStore", profileStore
)
309 synchronized (fileChannel
) {
310 fileChannel
.position(0);
311 jsonProcessor
.writeValue(Channels
.newOutputStream(fileChannel
), rootNode
);
312 fileChannel
.truncate(fileChannel
.position());
313 fileChannel
.force(false);
315 } catch (Exception e
) {
316 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
320 private static Pair
<FileChannel
, FileLock
> openFileChannel(String fileName
) throws IOException
{
321 FileChannel fileChannel
= new RandomAccessFile(new File(fileName
), "rw").getChannel();
322 FileLock lock
= fileChannel
.tryLock();
324 System
.err
.println("Config file is in use by another instance, waiting…");
325 lock
= fileChannel
.lock();
326 System
.err
.println("Config file lock acquired.");
328 return new Pair
<>(fileChannel
, lock
);
331 public void setResolver(final SignalServiceAddressResolver resolver
) {
332 signalProtocolStore
.setResolver(resolver
);
335 public void addPreKeys(Collection
<PreKeyRecord
> records
) {
336 for (PreKeyRecord
record : records
) {
337 signalProtocolStore
.storePreKey(record.getId(), record);
339 preKeyIdOffset
= (preKeyIdOffset
+ records
.size()) % Medium
.MAX_VALUE
;
342 public void addSignedPreKey(SignedPreKeyRecord
record) {
343 signalProtocolStore
.storeSignedPreKey(record.getId(), record);
344 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
347 public JsonSignalProtocolStore
getSignalProtocolStore() {
348 return signalProtocolStore
;
351 public JsonGroupStore
getGroupStore() {
355 public JsonContactsStore
getContactStore() {
359 public RecipientStore
getRecipientStore() {
360 return recipientStore
;
363 public ProfileStore
getProfileStore() {
367 public String
getUsername() {
371 public UUID
getUuid() {
375 public void setUuid(final UUID uuid
) {
379 public SignalServiceAddress
getSelfAddress() {
380 return new SignalServiceAddress(uuid
, username
);
383 public int getDeviceId() {
387 public String
getPassword() {
391 public void setPassword(final String password
) {
392 this.password
= password
;
395 public String
getRegistrationLockPin() {
396 return registrationLockPin
;
399 public String
getRegistrationLock() {
400 return null; // TODO implement KBS
403 public void setRegistrationLockPin(final String registrationLockPin
) {
404 this.registrationLockPin
= registrationLockPin
;
407 public String
getSignalingKey() {
411 public void setSignalingKey(final String signalingKey
) {
412 this.signalingKey
= signalingKey
;
415 public ProfileKey
getProfileKey() {
419 public void setProfileKey(final ProfileKey profileKey
) {
420 this.profileKey
= profileKey
;
423 public int getPreKeyIdOffset() {
424 return preKeyIdOffset
;
427 public int getNextSignedPreKeyId() {
428 return nextSignedPreKeyId
;
431 public boolean isRegistered() {
435 public void setRegistered(final boolean registered
) {
436 this.registered
= registered
;
439 public boolean isMultiDevice() {
440 return isMultiDevice
;
443 public void setMultiDevice(final boolean multiDevice
) {
444 isMultiDevice
= multiDevice
;
448 public void close() throws IOException
{
449 synchronized (fileChannel
) {
452 } catch (ClosedChannelException ignored
) {