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
.ClosedChannelException
;
42 import java
.nio
.channels
.FileChannel
;
43 import java
.nio
.channels
.FileLock
;
44 import java
.util
.Collection
;
45 import java
.util
.UUID
;
46 import java
.util
.stream
.Collectors
;
48 public class SignalAccount
implements Closeable
{
50 private final ObjectMapper jsonProcessor
= new ObjectMapper();
51 private final FileChannel fileChannel
;
52 private final FileLock lock
;
53 private String username
;
55 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
56 private boolean isMultiDevice
= false;
57 private String password
;
58 private String registrationLockPin
;
59 private String signalingKey
;
60 private ProfileKey profileKey
;
61 private int preKeyIdOffset
;
62 private int nextSignedPreKeyId
;
64 private boolean registered
= false;
66 private JsonSignalProtocolStore signalProtocolStore
;
67 private JsonGroupStore groupStore
;
68 private JsonContactsStore contactStore
;
69 private RecipientStore recipientStore
;
71 private SignalAccount(final FileChannel fileChannel
, final FileLock lock
) {
72 this.fileChannel
= fileChannel
;
74 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
75 jsonProcessor
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
76 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
77 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
78 jsonProcessor
.disable(JsonParser
.Feature
.AUTO_CLOSE_SOURCE
);
79 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
82 public static SignalAccount
load(String dataPath
, String username
) throws IOException
{
83 final String fileName
= getFileName(dataPath
, username
);
84 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
86 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
89 } catch (Throwable e
) {
90 pair
.second().close();
96 public static SignalAccount
create(String dataPath
, String username
, IdentityKeyPair identityKey
, int registrationId
, ProfileKey profileKey
) throws IOException
{
97 IOUtils
.createPrivateDirectories(dataPath
);
98 String fileName
= getFileName(dataPath
, username
);
99 if (!new File(fileName
).exists()) {
100 IOUtils
.createPrivateFile(fileName
);
103 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
104 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
106 account
.username
= username
;
107 account
.profileKey
= profileKey
;
108 account
.signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
109 account
.groupStore
= new JsonGroupStore();
110 account
.contactStore
= new JsonContactsStore();
111 account
.recipientStore
= new RecipientStore();
112 account
.registered
= false;
117 public static SignalAccount
createLinkedAccount(String dataPath
, String username
, UUID uuid
, String password
, int deviceId
, IdentityKeyPair identityKey
, int registrationId
, String signalingKey
, ProfileKey profileKey
) throws IOException
{
118 IOUtils
.createPrivateDirectories(dataPath
);
119 String fileName
= getFileName(dataPath
, username
);
120 if (!new File(fileName
).exists()) {
121 IOUtils
.createPrivateFile(fileName
);
124 final Pair
<FileChannel
, FileLock
> pair
= openFileChannel(fileName
);
125 SignalAccount account
= new SignalAccount(pair
.first(), pair
.second());
127 account
.username
= username
;
129 account
.password
= password
;
130 account
.profileKey
= profileKey
;
131 account
.deviceId
= deviceId
;
132 account
.signalingKey
= signalingKey
;
133 account
.signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
134 account
.groupStore
= new JsonGroupStore();
135 account
.contactStore
= new JsonContactsStore();
136 account
.recipientStore
= new RecipientStore();
137 account
.registered
= true;
138 account
.isMultiDevice
= true;
143 public static String
getFileName(String dataPath
, String username
) {
144 return dataPath
+ "/" + username
;
147 public static boolean userExists(String dataPath
, String username
) {
148 if (username
== null) {
151 File f
= new File(getFileName(dataPath
, username
));
152 return !(!f
.exists() || f
.isDirectory());
155 private void load() throws IOException
{
157 synchronized (fileChannel
) {
158 fileChannel
.position(0);
159 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
162 JsonNode uuidNode
= rootNode
.get("uuid");
163 if (uuidNode
!= null && !uuidNode
.isNull()) {
165 uuid
= UUID
.fromString(uuidNode
.asText());
166 } catch (IllegalArgumentException e
) {
167 throw new IOException("Config file contains an invalid uuid, needs to be a valid UUID", e
);
170 JsonNode node
= rootNode
.get("deviceId");
172 deviceId
= node
.asInt();
174 if (rootNode
.has("isMultiDevice")) {
175 isMultiDevice
= Util
.getNotNullNode(rootNode
, "isMultiDevice").asBoolean();
177 username
= Util
.getNotNullNode(rootNode
, "username").asText();
178 password
= Util
.getNotNullNode(rootNode
, "password").asText();
179 JsonNode pinNode
= rootNode
.get("registrationLockPin");
180 registrationLockPin
= pinNode
== null || pinNode
.isNull() ?
null : pinNode
.asText();
181 if (rootNode
.has("signalingKey")) {
182 signalingKey
= Util
.getNotNullNode(rootNode
, "signalingKey").asText();
184 if (rootNode
.has("preKeyIdOffset")) {
185 preKeyIdOffset
= Util
.getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
189 if (rootNode
.has("nextSignedPreKeyId")) {
190 nextSignedPreKeyId
= Util
.getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
192 nextSignedPreKeyId
= 0;
194 if (rootNode
.has("profileKey")) {
196 profileKey
= new ProfileKey(Base64
.decode(Util
.getNotNullNode(rootNode
, "profileKey").asText()));
197 } catch (InvalidInputException e
) {
198 throw new IOException("Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes", e
);
202 signalProtocolStore
= jsonProcessor
.convertValue(Util
.getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
203 registered
= Util
.getNotNullNode(rootNode
, "registered").asBoolean();
204 JsonNode groupStoreNode
= rootNode
.get("groupStore");
205 if (groupStoreNode
!= null) {
206 groupStore
= jsonProcessor
.convertValue(groupStoreNode
, JsonGroupStore
.class);
208 if (groupStore
== null) {
209 groupStore
= new JsonGroupStore();
212 JsonNode contactStoreNode
= rootNode
.get("contactStore");
213 if (contactStoreNode
!= null) {
214 contactStore
= jsonProcessor
.convertValue(contactStoreNode
, JsonContactsStore
.class);
216 if (contactStore
== null) {
217 contactStore
= new JsonContactsStore();
220 JsonNode recipientStoreNode
= rootNode
.get("recipientStore");
221 if (recipientStoreNode
!= null) {
222 recipientStore
= jsonProcessor
.convertValue(recipientStoreNode
, RecipientStore
.class);
224 if (recipientStore
== null) {
225 recipientStore
= new RecipientStore();
227 recipientStore
.resolveServiceAddress(getSelfAddress());
229 for (ContactInfo contact
: contactStore
.getContacts()) {
230 recipientStore
.resolveServiceAddress(contact
.getAddress());
233 for (GroupInfo group
: groupStore
.getGroups()) {
234 group
.members
= group
.members
.stream()
235 .map(m
-> recipientStore
.resolveServiceAddress(m
))
236 .collect(Collectors
.toSet());
239 for (SessionInfo session
: signalProtocolStore
.getSessions()) {
240 session
.address
= recipientStore
.resolveServiceAddress(session
.address
);
243 for (JsonIdentityKeyStore
.Identity identity
: signalProtocolStore
.getIdentities()) {
244 identity
.setAddress(recipientStore
.resolveServiceAddress(identity
.getAddress()));
248 JsonNode threadStoreNode
= rootNode
.get("threadStore");
249 if (threadStoreNode
!= null) {
250 LegacyJsonThreadStore threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
251 // Migrate thread info to group and contact store
252 for (ThreadInfo thread
: threadStore
.getThreads()) {
253 if (thread
.id
== null || thread
.id
.isEmpty()) {
257 ContactInfo contactInfo
= contactStore
.getContact(new SignalServiceAddress(null, thread
.id
));
258 if (contactInfo
!= null) {
259 contactInfo
.messageExpirationTime
= thread
.messageExpirationTime
;
260 contactStore
.updateContact(contactInfo
);
262 GroupInfo groupInfo
= groupStore
.getGroup(Base64
.decode(thread
.id
));
263 if (groupInfo
!= null) {
264 groupInfo
.messageExpirationTime
= thread
.messageExpirationTime
;
265 groupStore
.updateGroup(groupInfo
);
268 } catch (Exception ignored
) {
275 if (fileChannel
== null) {
278 ObjectNode rootNode
= jsonProcessor
.createObjectNode();
279 rootNode
.put("username", username
)
280 .put("uuid", uuid
== null ?
null : uuid
.toString())
281 .put("deviceId", deviceId
)
282 .put("isMultiDevice", isMultiDevice
)
283 .put("password", password
)
284 .put("registrationLockPin", registrationLockPin
)
285 .put("signalingKey", signalingKey
)
286 .put("preKeyIdOffset", preKeyIdOffset
)
287 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
288 .put("profileKey", Base64
.encodeBytes(profileKey
.serialize()))
289 .put("registered", registered
)
290 .putPOJO("axolotlStore", signalProtocolStore
)
291 .putPOJO("groupStore", groupStore
)
292 .putPOJO("contactStore", contactStore
)
293 .putPOJO("recipientStore", recipientStore
)
296 synchronized (fileChannel
) {
297 fileChannel
.position(0);
298 jsonProcessor
.writeValue(Channels
.newOutputStream(fileChannel
), rootNode
);
299 fileChannel
.truncate(fileChannel
.position());
300 fileChannel
.force(false);
302 } catch (Exception e
) {
303 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
307 private static Pair
<FileChannel
, FileLock
> openFileChannel(String fileName
) throws IOException
{
308 FileChannel fileChannel
= new RandomAccessFile(new File(fileName
), "rw").getChannel();
309 FileLock lock
= fileChannel
.tryLock();
311 System
.err
.println("Config file is in use by another instance, waiting…");
312 lock
= fileChannel
.lock();
313 System
.err
.println("Config file lock acquired.");
315 return new Pair
<>(fileChannel
, lock
);
318 public void setResolver(final SignalServiceAddressResolver resolver
) {
319 signalProtocolStore
.setResolver(resolver
);
322 public void addPreKeys(Collection
<PreKeyRecord
> records
) {
323 for (PreKeyRecord
record : records
) {
324 signalProtocolStore
.storePreKey(record.getId(), record);
326 preKeyIdOffset
= (preKeyIdOffset
+ records
.size()) % Medium
.MAX_VALUE
;
329 public void addSignedPreKey(SignedPreKeyRecord
record) {
330 signalProtocolStore
.storeSignedPreKey(record.getId(), record);
331 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
334 public JsonSignalProtocolStore
getSignalProtocolStore() {
335 return signalProtocolStore
;
338 public JsonGroupStore
getGroupStore() {
342 public JsonContactsStore
getContactStore() {
346 public RecipientStore
getRecipientStore() {
347 return recipientStore
;
350 public String
getUsername() {
354 public UUID
getUuid() {
358 public void setUuid(final UUID uuid
) {
362 public SignalServiceAddress
getSelfAddress() {
363 return new SignalServiceAddress(uuid
, username
);
366 public int getDeviceId() {
370 public String
getPassword() {
374 public void setPassword(final String password
) {
375 this.password
= password
;
378 public String
getRegistrationLockPin() {
379 return registrationLockPin
;
382 public String
getRegistrationLock() {
383 return null; // TODO implement KBS
386 public void setRegistrationLockPin(final String registrationLockPin
) {
387 this.registrationLockPin
= registrationLockPin
;
390 public String
getSignalingKey() {
394 public void setSignalingKey(final String signalingKey
) {
395 this.signalingKey
= signalingKey
;
398 public ProfileKey
getProfileKey() {
402 public void setProfileKey(final ProfileKey profileKey
) {
403 this.profileKey
= profileKey
;
406 public int getPreKeyIdOffset() {
407 return preKeyIdOffset
;
410 public int getNextSignedPreKeyId() {
411 return nextSignedPreKeyId
;
414 public boolean isRegistered() {
418 public void setRegistered(final boolean registered
) {
419 this.registered
= registered
;
422 public boolean isMultiDevice() {
423 return isMultiDevice
;
426 public void setMultiDevice(final boolean multiDevice
) {
427 isMultiDevice
= multiDevice
;
431 public void close() throws IOException
{
432 synchronized (fileChannel
) {
435 } catch (ClosedChannelException ignored
) {