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
.signalservice
.api
.push
.SignalServiceAddress
;
33 import org
.whispersystems
.util
.Base64
;
36 import java
.io
.IOException
;
37 import java
.io
.RandomAccessFile
;
38 import java
.nio
.channels
.Channels
;
39 import java
.nio
.channels
.FileChannel
;
40 import java
.nio
.channels
.FileLock
;
41 import java
.util
.Collection
;
42 import java
.util
.UUID
;
43 import java
.util
.stream
.Collectors
;
45 public class SignalAccount
{
47 private final ObjectMapper jsonProcessor
= new ObjectMapper();
48 private FileChannel fileChannel
;
49 private FileLock lock
;
50 private String username
;
52 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
53 private boolean isMultiDevice
= false;
54 private String password
;
55 private String registrationLockPin
;
56 private String signalingKey
;
57 private ProfileKey profileKey
;
58 private int preKeyIdOffset
;
59 private int nextSignedPreKeyId
;
61 private boolean registered
= false;
63 private JsonSignalProtocolStore signalProtocolStore
;
64 private JsonGroupStore groupStore
;
65 private JsonContactsStore contactStore
;
66 private RecipientStore recipientStore
;
68 private SignalAccount() {
69 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
70 jsonProcessor
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
71 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
72 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
73 jsonProcessor
.disable(JsonParser
.Feature
.AUTO_CLOSE_SOURCE
);
74 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
77 public static SignalAccount
load(String dataPath
, String username
) throws IOException
{
78 SignalAccount account
= new SignalAccount();
79 IOUtils
.createPrivateDirectories(dataPath
);
80 account
.openFileChannel(getFileName(dataPath
, username
));
85 public static SignalAccount
create(String dataPath
, String username
, IdentityKeyPair identityKey
, int registrationId
, ProfileKey profileKey
) throws IOException
{
86 IOUtils
.createPrivateDirectories(dataPath
);
88 SignalAccount account
= new SignalAccount();
89 account
.openFileChannel(getFileName(dataPath
, username
));
91 account
.username
= username
;
92 account
.profileKey
= profileKey
;
93 account
.signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
94 account
.groupStore
= new JsonGroupStore();
95 account
.contactStore
= new JsonContactsStore();
96 account
.recipientStore
= new RecipientStore();
97 account
.registered
= false;
102 public static SignalAccount
createLinkedAccount(String dataPath
, String username
, UUID uuid
, String password
, int deviceId
, IdentityKeyPair identityKey
, int registrationId
, String signalingKey
, ProfileKey profileKey
) throws IOException
{
103 IOUtils
.createPrivateDirectories(dataPath
);
105 SignalAccount account
= new SignalAccount();
106 account
.openFileChannel(getFileName(dataPath
, username
));
108 account
.username
= username
;
110 account
.password
= password
;
111 account
.profileKey
= profileKey
;
112 account
.deviceId
= deviceId
;
113 account
.signalingKey
= signalingKey
;
114 account
.signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
115 account
.groupStore
= new JsonGroupStore();
116 account
.contactStore
= new JsonContactsStore();
117 account
.recipientStore
= new RecipientStore();
118 account
.registered
= true;
119 account
.isMultiDevice
= true;
124 public static SignalAccount
createTemporaryAccount(IdentityKeyPair identityKey
, int registrationId
) {
125 SignalAccount account
= new SignalAccount();
127 account
.signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
128 account
.registered
= false;
133 public static String
getFileName(String dataPath
, String username
) {
134 return dataPath
+ "/" + username
;
137 public static boolean userExists(String dataPath
, String username
) {
138 if (username
== null) {
141 File f
= new File(getFileName(dataPath
, username
));
142 return !(!f
.exists() || f
.isDirectory());
145 private void load() throws IOException
{
147 synchronized (fileChannel
) {
148 fileChannel
.position(0);
149 rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
152 JsonNode uuidNode
= rootNode
.get("uuid");
153 if (uuidNode
!= null && !uuidNode
.isNull()) {
155 uuid
= UUID
.fromString(uuidNode
.asText());
156 } catch (IllegalArgumentException e
) {
157 throw new IOException("Config file contains an invalid uuid, needs to be a valid UUID", e
);
160 JsonNode node
= rootNode
.get("deviceId");
162 deviceId
= node
.asInt();
164 if (rootNode
.has("isMultiDevice")) {
165 isMultiDevice
= Util
.getNotNullNode(rootNode
, "isMultiDevice").asBoolean();
167 username
= Util
.getNotNullNode(rootNode
, "username").asText();
168 password
= Util
.getNotNullNode(rootNode
, "password").asText();
169 JsonNode pinNode
= rootNode
.get("registrationLockPin");
170 registrationLockPin
= pinNode
== null || pinNode
.isNull() ?
null : pinNode
.asText();
171 if (rootNode
.has("signalingKey")) {
172 signalingKey
= Util
.getNotNullNode(rootNode
, "signalingKey").asText();
174 if (rootNode
.has("preKeyIdOffset")) {
175 preKeyIdOffset
= Util
.getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
179 if (rootNode
.has("nextSignedPreKeyId")) {
180 nextSignedPreKeyId
= Util
.getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
182 nextSignedPreKeyId
= 0;
184 if (rootNode
.has("profileKey")) {
186 profileKey
= new ProfileKey(Base64
.decode(Util
.getNotNullNode(rootNode
, "profileKey").asText()));
187 } catch (InvalidInputException e
) {
188 throw new IOException("Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes", e
);
192 signalProtocolStore
= jsonProcessor
.convertValue(Util
.getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
193 registered
= Util
.getNotNullNode(rootNode
, "registered").asBoolean();
194 JsonNode groupStoreNode
= rootNode
.get("groupStore");
195 if (groupStoreNode
!= null) {
196 groupStore
= jsonProcessor
.convertValue(groupStoreNode
, JsonGroupStore
.class);
198 if (groupStore
== null) {
199 groupStore
= new JsonGroupStore();
202 JsonNode contactStoreNode
= rootNode
.get("contactStore");
203 if (contactStoreNode
!= null) {
204 contactStore
= jsonProcessor
.convertValue(contactStoreNode
, JsonContactsStore
.class);
206 if (contactStore
== null) {
207 contactStore
= new JsonContactsStore();
210 JsonNode recipientStoreNode
= rootNode
.get("recipientStore");
211 if (recipientStoreNode
!= null) {
212 recipientStore
= jsonProcessor
.convertValue(recipientStoreNode
, RecipientStore
.class);
214 if (recipientStore
== null) {
215 recipientStore
= new RecipientStore();
217 recipientStore
.resolveServiceAddress(getSelfAddress());
219 for (ContactInfo contact
: contactStore
.getContacts()) {
220 recipientStore
.resolveServiceAddress(contact
.getAddress());
223 for (GroupInfo group
: groupStore
.getGroups()) {
224 group
.members
= group
.members
.stream()
225 .map(m
-> recipientStore
.resolveServiceAddress(m
))
226 .collect(Collectors
.toSet());
229 for (SessionInfo session
: signalProtocolStore
.getSessions()) {
230 session
.address
= recipientStore
.resolveServiceAddress(session
.address
);
233 for (JsonIdentityKeyStore
.Identity identity
: signalProtocolStore
.getIdentities()) {
234 identity
.setAddress(recipientStore
.resolveServiceAddress(identity
.getAddress()));
238 JsonNode threadStoreNode
= rootNode
.get("threadStore");
239 if (threadStoreNode
!= null) {
240 LegacyJsonThreadStore threadStore
= jsonProcessor
.convertValue(threadStoreNode
, LegacyJsonThreadStore
.class);
241 // Migrate thread info to group and contact store
242 for (ThreadInfo thread
: threadStore
.getThreads()) {
243 if (thread
.id
== null || thread
.id
.isEmpty()) {
247 ContactInfo contactInfo
= contactStore
.getContact(new SignalServiceAddress(null, thread
.id
));
248 if (contactInfo
!= null) {
249 contactInfo
.messageExpirationTime
= thread
.messageExpirationTime
;
250 contactStore
.updateContact(contactInfo
);
252 GroupInfo groupInfo
= groupStore
.getGroup(Base64
.decode(thread
.id
));
253 if (groupInfo
!= null) {
254 groupInfo
.messageExpirationTime
= thread
.messageExpirationTime
;
255 groupStore
.updateGroup(groupInfo
);
258 } catch (Exception ignored
) {
265 if (fileChannel
== null) {
268 ObjectNode rootNode
= jsonProcessor
.createObjectNode();
269 rootNode
.put("username", username
)
270 .put("uuid", uuid
== null ?
null : uuid
.toString())
271 .put("deviceId", deviceId
)
272 .put("isMultiDevice", isMultiDevice
)
273 .put("password", password
)
274 .put("registrationLockPin", registrationLockPin
)
275 .put("signalingKey", signalingKey
)
276 .put("preKeyIdOffset", preKeyIdOffset
)
277 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
278 .put("profileKey", Base64
.encodeBytes(profileKey
.serialize()))
279 .put("registered", registered
)
280 .putPOJO("axolotlStore", signalProtocolStore
)
281 .putPOJO("groupStore", groupStore
)
282 .putPOJO("contactStore", contactStore
)
283 .putPOJO("recipientStore", recipientStore
)
286 synchronized (fileChannel
) {
287 fileChannel
.position(0);
288 jsonProcessor
.writeValue(Channels
.newOutputStream(fileChannel
), rootNode
);
289 fileChannel
.truncate(fileChannel
.position());
290 fileChannel
.force(false);
292 } catch (Exception e
) {
293 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
297 private void openFileChannel(String fileName
) throws IOException
{
298 if (fileChannel
!= null) {
302 if (!new File(fileName
).exists()) {
303 IOUtils
.createPrivateFile(fileName
);
305 fileChannel
= new RandomAccessFile(new File(fileName
), "rw").getChannel();
306 lock
= fileChannel
.tryLock();
308 System
.err
.println("Config file is in use by another instance, waiting…");
309 lock
= fileChannel
.lock();
310 System
.err
.println("Config file lock acquired.");
314 public void setResolver(final SignalServiceAddressResolver resolver
) {
315 signalProtocolStore
.setResolver(resolver
);
318 public void addPreKeys(Collection
<PreKeyRecord
> records
) {
319 for (PreKeyRecord
record : records
) {
320 signalProtocolStore
.storePreKey(record.getId(), record);
322 preKeyIdOffset
= (preKeyIdOffset
+ records
.size()) % Medium
.MAX_VALUE
;
325 public void addSignedPreKey(SignedPreKeyRecord
record) {
326 signalProtocolStore
.storeSignedPreKey(record.getId(), record);
327 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
330 public JsonSignalProtocolStore
getSignalProtocolStore() {
331 return signalProtocolStore
;
334 public JsonGroupStore
getGroupStore() {
338 public JsonContactsStore
getContactStore() {
342 public RecipientStore
getRecipientStore() {
343 return recipientStore
;
346 public String
getUsername() {
350 public UUID
getUuid() {
354 public void setUuid(final UUID uuid
) {
358 public SignalServiceAddress
getSelfAddress() {
359 return new SignalServiceAddress(uuid
, username
);
362 public int getDeviceId() {
366 public String
getPassword() {
370 public void setPassword(final String password
) {
371 this.password
= password
;
374 public String
getRegistrationLockPin() {
375 return registrationLockPin
;
378 public String
getRegistrationLock() {
379 return null; // TODO implement KBS
382 public void setRegistrationLockPin(final String registrationLockPin
) {
383 this.registrationLockPin
= registrationLockPin
;
386 public String
getSignalingKey() {
390 public void setSignalingKey(final String signalingKey
) {
391 this.signalingKey
= signalingKey
;
394 public ProfileKey
getProfileKey() {
398 public void setProfileKey(final ProfileKey profileKey
) {
399 this.profileKey
= profileKey
;
402 public int getPreKeyIdOffset() {
403 return preKeyIdOffset
;
406 public int getNextSignedPreKeyId() {
407 return nextSignedPreKeyId
;
410 public boolean isRegistered() {
414 public void setRegistered(final boolean registered
) {
415 this.registered
= registered
;
418 public boolean isMultiDevice() {
419 return isMultiDevice
;
422 public void setMultiDevice(final boolean multiDevice
) {
423 isMultiDevice
= multiDevice
;