]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Manager.java
Make Json store use Jackson instead of Gson (as it's already linked)
[signal-cli] / src / main / java / cli / Manager.java
1 /**
2 * Copyright (C) 2015 AsamK
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package cli;
18
19 import com.fasterxml.jackson.annotation.JsonAutoDetect;
20 import com.fasterxml.jackson.annotation.PropertyAccessor;
21 import com.fasterxml.jackson.databind.DeserializationFeature;
22 import com.fasterxml.jackson.databind.JsonNode;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.fasterxml.jackson.databind.SerializationFeature;
25 import com.fasterxml.jackson.databind.node.ObjectNode;
26 import org.whispersystems.libaxolotl.*;
27 import org.whispersystems.libaxolotl.ecc.Curve;
28 import org.whispersystems.libaxolotl.ecc.ECKeyPair;
29 import org.whispersystems.libaxolotl.state.PreKeyRecord;
30 import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
31 import org.whispersystems.libaxolotl.util.KeyHelper;
32 import org.whispersystems.libaxolotl.util.Medium;
33 import org.whispersystems.libaxolotl.util.guava.Optional;
34 import org.whispersystems.textsecure.api.TextSecureAccountManager;
35 import org.whispersystems.textsecure.api.TextSecureMessagePipe;
36 import org.whispersystems.textsecure.api.TextSecureMessageReceiver;
37 import org.whispersystems.textsecure.api.TextSecureMessageSender;
38 import org.whispersystems.textsecure.api.crypto.TextSecureCipher;
39 import org.whispersystems.textsecure.api.messages.TextSecureAttachmentPointer;
40 import org.whispersystems.textsecure.api.messages.TextSecureContent;
41 import org.whispersystems.textsecure.api.messages.TextSecureDataMessage;
42 import org.whispersystems.textsecure.api.messages.TextSecureEnvelope;
43 import org.whispersystems.textsecure.api.push.TextSecureAddress;
44 import org.whispersystems.textsecure.api.push.TrustStore;
45 import org.whispersystems.textsecure.api.push.exceptions.EncapsulatedExceptions;
46 import org.whispersystems.textsecure.api.util.InvalidNumberException;
47 import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
48
49 import java.io.*;
50 import java.util.LinkedList;
51 import java.util.List;
52 import java.util.concurrent.TimeUnit;
53 import java.util.concurrent.TimeoutException;
54
55 class Manager {
56 private final static String URL = "https://textsecure-service.whispersystems.org";
57 private final static TrustStore TRUST_STORE = new WhisperTrustStore();
58
59 public final static String PROJECT_NAME = Manager.class.getPackage().getImplementationTitle();
60 public final static String PROJECT_VERSION = Manager.class.getPackage().getImplementationVersion();
61 private final static String USER_AGENT = PROJECT_NAME + " " + PROJECT_VERSION;
62
63 private final static String settingsPath = System.getProperty("user.home") + "/.config/textsecure";
64 private final static String dataPath = settingsPath + "/data";
65 private final static String attachmentsPath = settingsPath + "/attachments";
66
67 private final ObjectMapper jsonProcessot = new ObjectMapper();
68 private String username;
69 private String password;
70 private String signalingKey;
71 private int preKeyIdOffset;
72 private int nextSignedPreKeyId;
73
74 private boolean registered = false;
75
76 private JsonAxolotlStore axolotlStore;
77 private TextSecureAccountManager accountManager;
78
79 public Manager(String username) {
80 this.username = username;
81 jsonProcessot.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); // disable autodetect
82 jsonProcessot.enable(SerializationFeature.INDENT_OUTPUT); // for pretty print, you can disable it.
83 jsonProcessot.enable(SerializationFeature.WRITE_NULL_MAP_VALUES);
84 jsonProcessot.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
85 }
86
87 public String getFileName() {
88 new File(dataPath).mkdirs();
89 return dataPath + "/" + username;
90 }
91
92 public boolean userExists() {
93 File f = new File(getFileName());
94 return !(!f.exists() || f.isDirectory());
95 }
96
97 public boolean userHasKeys() {
98 return axolotlStore != null;
99 }
100
101 private JsonNode getNotNullNode(JsonNode parent, String name) throws InvalidObjectException {
102 JsonNode node = parent.get(name);
103 if (node == null) {
104 throw new InvalidObjectException(String.format("Incorrect file format: expected parameter %s not found ", name));
105 }
106
107 return node;
108 }
109
110
111 public void load() throws IOException, InvalidKeyException {
112 JsonNode rootNode = jsonProcessot.readTree(new File(getFileName()));
113
114 username = getNotNullNode(rootNode, "username").asText();
115 password = getNotNullNode(rootNode, "password").asText();
116 if (rootNode.has("signalingKey")) {
117 signalingKey = getNotNullNode(rootNode, "signalingKey").asText();
118 }
119 if (rootNode.has("preKeyIdOffset")) {
120 preKeyIdOffset = getNotNullNode(rootNode, "preKeyIdOffset").asInt(0);
121 } else {
122 preKeyIdOffset = 0;
123 }
124 if (rootNode.has("nextSignedPreKeyId")) {
125 nextSignedPreKeyId = getNotNullNode(rootNode, "nextSignedPreKeyId").asInt();
126 } else {
127 nextSignedPreKeyId = 0;
128 }
129 axolotlStore = jsonProcessot.convertValue(getNotNullNode(rootNode, "axolotlStore"), JsonAxolotlStore.class); //new JsonAxolotlStore(in.getJSONObject("axolotlStore"));
130 registered = getNotNullNode(rootNode, "registered").asBoolean();
131 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password, USER_AGENT);
132 }
133
134 public void save() {
135 ObjectNode rootNode = jsonProcessot.createObjectNode();
136 rootNode.put("username", username)
137 .put("password", password)
138 .put("signalingKey", signalingKey)
139 .put("preKeyIdOffset", preKeyIdOffset)
140 .put("nextSignedPreKeyId", nextSignedPreKeyId)
141 .put("registered", registered)
142 .putPOJO("axolotlStore", axolotlStore)
143 ;
144 try {
145 jsonProcessot.writeValue(new File(getFileName()), rootNode);
146 } catch (Exception e) {
147 System.err.println(String.format("Error saving file: %s", e.getMessage()));
148 }
149 }
150
151 public void createNewIdentity() {
152 IdentityKeyPair identityKey = KeyHelper.generateIdentityKeyPair();
153 int registrationId = KeyHelper.generateRegistrationId(false);
154 axolotlStore = new JsonAxolotlStore(identityKey, registrationId);
155 registered = false;
156 }
157
158 public boolean isRegistered() {
159 return registered;
160 }
161
162 public void register(boolean voiceVerication) throws IOException {
163 password = Util.getSecret(18);
164
165 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password, USER_AGENT);
166
167 if (voiceVerication)
168 accountManager.requestVoiceVerificationCode();
169 else
170 accountManager.requestSmsVerificationCode();
171
172 registered = false;
173 }
174
175 private static final int BATCH_SIZE = 100;
176
177 private List<PreKeyRecord> generatePreKeys() {
178 List<PreKeyRecord> records = new LinkedList<>();
179
180 for (int i = 0; i < BATCH_SIZE; i++) {
181 int preKeyId = (preKeyIdOffset + i) % Medium.MAX_VALUE;
182 ECKeyPair keyPair = Curve.generateKeyPair();
183 PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);
184
185 axolotlStore.storePreKey(preKeyId, record);
186 records.add(record);
187 }
188
189 preKeyIdOffset = (preKeyIdOffset + BATCH_SIZE + 1) % Medium.MAX_VALUE;
190 return records;
191 }
192
193 private PreKeyRecord generateLastResortPreKey() {
194 if (axolotlStore.containsPreKey(Medium.MAX_VALUE)) {
195 try {
196 return axolotlStore.loadPreKey(Medium.MAX_VALUE);
197 } catch (InvalidKeyIdException e) {
198 axolotlStore.removePreKey(Medium.MAX_VALUE);
199 }
200 }
201
202 ECKeyPair keyPair = Curve.generateKeyPair();
203 PreKeyRecord record = new PreKeyRecord(Medium.MAX_VALUE, keyPair);
204
205 axolotlStore.storePreKey(Medium.MAX_VALUE, record);
206
207 return record;
208 }
209
210 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
211 try {
212 ECKeyPair keyPair = Curve.generateKeyPair();
213 byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
214 SignedPreKeyRecord record = new SignedPreKeyRecord(nextSignedPreKeyId, System.currentTimeMillis(), keyPair, signature);
215
216 axolotlStore.storeSignedPreKey(nextSignedPreKeyId, record);
217 nextSignedPreKeyId = (nextSignedPreKeyId + 1) % Medium.MAX_VALUE;
218
219 return record;
220 } catch (InvalidKeyException e) {
221 throw new AssertionError(e);
222 }
223 }
224
225 public void verifyAccount(String verificationCode) throws IOException {
226 verificationCode = verificationCode.replace("-", "");
227 signalingKey = Util.getSecret(52);
228 accountManager.verifyAccountWithCode(verificationCode, signalingKey, axolotlStore.getLocalRegistrationId(), false);
229
230 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
231 registered = true;
232
233 List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
234
235 PreKeyRecord lastResortKey = generateLastResortPreKey();
236
237 SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(axolotlStore.getIdentityKeyPair());
238
239 accountManager.setPreKeys(axolotlStore.getIdentityKeyPair().getPublicKey(), lastResortKey, signedPreKeyRecord, oneTimePreKeys);
240 }
241
242 public void sendMessage(List<TextSecureAddress> recipients, TextSecureDataMessage message)
243 throws IOException, EncapsulatedExceptions {
244 TextSecureMessageSender messageSender = new TextSecureMessageSender(URL, TRUST_STORE, username, password,
245 axolotlStore, USER_AGENT, Optional.<TextSecureMessageSender.EventListener>absent());
246 messageSender.sendMessage(recipients, message);
247 }
248
249 public TextSecureContent decryptMessage(TextSecureEnvelope envelope) {
250 TextSecureCipher cipher = new TextSecureCipher(new TextSecureAddress(username), axolotlStore);
251 try {
252 return cipher.decrypt(envelope);
253 } catch (Exception e) {
254 // TODO handle all exceptions
255 e.printStackTrace();
256 return null;
257 }
258 }
259
260 public void handleEndSession(String source) {
261 axolotlStore.deleteAllSessions(source);
262 }
263
264 public interface ReceiveMessageHandler {
265 void handleMessage(TextSecureEnvelope envelope);
266 }
267
268 public void receiveMessages(int timeoutSeconds, boolean returnOnTimeout, ReceiveMessageHandler handler) throws IOException {
269 final TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey, USER_AGENT);
270 TextSecureMessagePipe messagePipe = null;
271
272 try {
273 messagePipe = messageReceiver.createMessagePipe();
274
275 while (true) {
276 TextSecureEnvelope envelope;
277 try {
278 envelope = messagePipe.read(timeoutSeconds, TimeUnit.SECONDS);
279 handler.handleMessage(envelope);
280 } catch (TimeoutException e) {
281 if (returnOnTimeout)
282 return;
283 } catch (InvalidVersionException e) {
284 System.err.println("Ignoring error: " + e.getMessage());
285 }
286 save();
287 }
288 } finally {
289 if (messagePipe != null)
290 messagePipe.shutdown();
291 }
292 }
293
294 public File retrieveAttachment(TextSecureAttachmentPointer pointer) throws IOException, InvalidMessageException {
295 final TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey, USER_AGENT);
296
297 File tmpFile = File.createTempFile("ts_attach_" + pointer.getId(), ".tmp");
298 InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile);
299
300 new File(attachmentsPath).mkdirs();
301 File outputFile = new File(attachmentsPath + "/" + pointer.getId());
302 OutputStream output = null;
303 try {
304 output = new FileOutputStream(outputFile);
305 byte[] buffer = new byte[4096];
306 int read;
307
308 while ((read = input.read(buffer)) != -1) {
309 output.write(buffer, 0, read);
310 }
311 } catch (FileNotFoundException e) {
312 e.printStackTrace();
313 return null;
314 } finally {
315 if (output != null) {
316 output.close();
317 output = null;
318 }
319 if (!tmpFile.delete()) {
320 System.err.println("Failed to delete temp file: " + tmpFile);
321 }
322 }
323 if (pointer.getPreview().isPresent()) {
324 File previewFile = new File(outputFile + ".preview");
325 try {
326 output = new FileOutputStream(previewFile);
327 byte[] preview = pointer.getPreview().get();
328 output.write(preview, 0, preview.length);
329 } catch (FileNotFoundException e) {
330 e.printStackTrace();
331 return null;
332 } finally {
333 if (output != null) {
334 output.close();
335 }
336 }
337 }
338 return outputFile;
339 }
340
341 private String canonicalizeNumber(String number) throws InvalidNumberException {
342 String localNumber = username;
343 return PhoneNumberFormatter.formatNumber(number, localNumber);
344 }
345
346 TextSecureAddress getPushAddress(String number) throws InvalidNumberException {
347 String e164number = canonicalizeNumber(number);
348 return new TextSecureAddress(e164number);
349 }
350 }