]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Manager.java
3b11d7b443a2cb65a422798351c9c2a041546b46
[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.*;
40 import org.whispersystems.textsecure.api.push.TextSecureAddress;
41 import org.whispersystems.textsecure.api.push.TrustStore;
42 import org.whispersystems.textsecure.api.push.exceptions.EncapsulatedExceptions;
43 import org.whispersystems.textsecure.api.util.InvalidNumberException;
44 import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
45
46 import java.io.*;
47 import java.nio.file.Files;
48 import java.nio.file.Paths;
49 import java.util.*;
50 import java.util.concurrent.TimeUnit;
51 import java.util.concurrent.TimeoutException;
52
53 class Manager implements TextSecure {
54 private final static String URL = "https://textsecure-service.whispersystems.org";
55 private final static TrustStore TRUST_STORE = new WhisperTrustStore();
56
57 public final static String PROJECT_NAME = Manager.class.getPackage().getImplementationTitle();
58 public final static String PROJECT_VERSION = Manager.class.getPackage().getImplementationVersion();
59 private final static String USER_AGENT = PROJECT_NAME + " " + PROJECT_VERSION;
60
61 private final static String settingsPath = System.getProperty("user.home") + "/.config/textsecure";
62 private final static String dataPath = settingsPath + "/data";
63 private final static String attachmentsPath = settingsPath + "/attachments";
64
65 private final ObjectMapper jsonProcessot = new ObjectMapper();
66 private String username;
67 private String password;
68 private String signalingKey;
69 private int preKeyIdOffset;
70 private int nextSignedPreKeyId;
71
72 private boolean registered = false;
73
74 private JsonAxolotlStore axolotlStore;
75 private TextSecureAccountManager accountManager;
76 private JsonGroupStore groupStore;
77
78 public Manager(String username) {
79 this.username = username;
80 jsonProcessot.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); // disable autodetect
81 jsonProcessot.enable(SerializationFeature.INDENT_OUTPUT); // for pretty print, you can disable it.
82 jsonProcessot.enable(SerializationFeature.WRITE_NULL_MAP_VALUES);
83 jsonProcessot.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
84 }
85
86 public String getFileName() {
87 new File(dataPath).mkdirs();
88 return dataPath + "/" + username;
89 }
90
91 public boolean userExists() {
92 File f = new File(getFileName());
93 return !(!f.exists() || f.isDirectory());
94 }
95
96 public boolean userHasKeys() {
97 return axolotlStore != null;
98 }
99
100 private JsonNode getNotNullNode(JsonNode parent, String name) throws InvalidObjectException {
101 JsonNode node = parent.get(name);
102 if (node == null) {
103 throw new InvalidObjectException(String.format("Incorrect file format: expected parameter %s not found ", name));
104 }
105
106 return node;
107 }
108
109 public void load() throws IOException, InvalidKeyException {
110 JsonNode rootNode = jsonProcessot.readTree(new File(getFileName()));
111
112 username = getNotNullNode(rootNode, "username").asText();
113 password = getNotNullNode(rootNode, "password").asText();
114 if (rootNode.has("signalingKey")) {
115 signalingKey = getNotNullNode(rootNode, "signalingKey").asText();
116 }
117 if (rootNode.has("preKeyIdOffset")) {
118 preKeyIdOffset = getNotNullNode(rootNode, "preKeyIdOffset").asInt(0);
119 } else {
120 preKeyIdOffset = 0;
121 }
122 if (rootNode.has("nextSignedPreKeyId")) {
123 nextSignedPreKeyId = getNotNullNode(rootNode, "nextSignedPreKeyId").asInt();
124 } else {
125 nextSignedPreKeyId = 0;
126 }
127 axolotlStore = jsonProcessot.convertValue(getNotNullNode(rootNode, "axolotlStore"), JsonAxolotlStore.class); //new JsonAxolotlStore(in.getJSONObject("axolotlStore"));
128 registered = getNotNullNode(rootNode, "registered").asBoolean();
129 JsonNode groupStoreNode = rootNode.get("groupStore");
130 if (groupStoreNode != null) {
131 groupStore = jsonProcessot.convertValue(groupStoreNode, JsonGroupStore.class);
132 }
133 if (groupStore == null) {
134 groupStore = new JsonGroupStore();
135 }
136 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password, USER_AGENT);
137 }
138
139 private void save() {
140 ObjectNode rootNode = jsonProcessot.createObjectNode();
141 rootNode.put("username", username)
142 .put("password", password)
143 .put("signalingKey", signalingKey)
144 .put("preKeyIdOffset", preKeyIdOffset)
145 .put("nextSignedPreKeyId", nextSignedPreKeyId)
146 .put("registered", registered)
147 .putPOJO("axolotlStore", axolotlStore)
148 .putPOJO("groupStore", groupStore)
149 ;
150 try {
151 jsonProcessot.writeValue(new File(getFileName()), rootNode);
152 } catch (Exception e) {
153 System.err.println(String.format("Error saving file: %s", e.getMessage()));
154 }
155 }
156
157 public void createNewIdentity() {
158 IdentityKeyPair identityKey = KeyHelper.generateIdentityKeyPair();
159 int registrationId = KeyHelper.generateRegistrationId(false);
160 axolotlStore = new JsonAxolotlStore(identityKey, registrationId);
161 groupStore = new JsonGroupStore();
162 registered = false;
163 save();
164 }
165
166 public boolean isRegistered() {
167 return registered;
168 }
169
170 public void register(boolean voiceVerication) throws IOException {
171 password = Util.getSecret(18);
172
173 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password, USER_AGENT);
174
175 if (voiceVerication)
176 accountManager.requestVoiceVerificationCode();
177 else
178 accountManager.requestSmsVerificationCode();
179
180 registered = false;
181 save();
182 }
183
184 private static final int BATCH_SIZE = 100;
185
186 private List<PreKeyRecord> generatePreKeys() {
187 List<PreKeyRecord> records = new LinkedList<>();
188
189 for (int i = 0; i < BATCH_SIZE; i++) {
190 int preKeyId = (preKeyIdOffset + i) % Medium.MAX_VALUE;
191 ECKeyPair keyPair = Curve.generateKeyPair();
192 PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);
193
194 axolotlStore.storePreKey(preKeyId, record);
195 records.add(record);
196 }
197
198 preKeyIdOffset = (preKeyIdOffset + BATCH_SIZE + 1) % Medium.MAX_VALUE;
199 save();
200
201 return records;
202 }
203
204 private PreKeyRecord generateLastResortPreKey() {
205 if (axolotlStore.containsPreKey(Medium.MAX_VALUE)) {
206 try {
207 return axolotlStore.loadPreKey(Medium.MAX_VALUE);
208 } catch (InvalidKeyIdException e) {
209 axolotlStore.removePreKey(Medium.MAX_VALUE);
210 }
211 }
212
213 ECKeyPair keyPair = Curve.generateKeyPair();
214 PreKeyRecord record = new PreKeyRecord(Medium.MAX_VALUE, keyPair);
215
216 axolotlStore.storePreKey(Medium.MAX_VALUE, record);
217 save();
218
219 return record;
220 }
221
222 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
223 try {
224 ECKeyPair keyPair = Curve.generateKeyPair();
225 byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
226 SignedPreKeyRecord record = new SignedPreKeyRecord(nextSignedPreKeyId, System.currentTimeMillis(), keyPair, signature);
227
228 axolotlStore.storeSignedPreKey(nextSignedPreKeyId, record);
229 nextSignedPreKeyId = (nextSignedPreKeyId + 1) % Medium.MAX_VALUE;
230 save();
231
232 return record;
233 } catch (InvalidKeyException e) {
234 throw new AssertionError(e);
235 }
236 }
237
238 public void verifyAccount(String verificationCode) throws IOException {
239 verificationCode = verificationCode.replace("-", "");
240 signalingKey = Util.getSecret(52);
241 accountManager.verifyAccountWithCode(verificationCode, signalingKey, axolotlStore.getLocalRegistrationId(), false);
242
243 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
244 registered = true;
245
246 List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
247
248 PreKeyRecord lastResortKey = generateLastResortPreKey();
249
250 SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(axolotlStore.getIdentityKeyPair());
251
252 accountManager.setPreKeys(axolotlStore.getIdentityKeyPair().getPublicKey(), lastResortKey, signedPreKeyRecord, oneTimePreKeys);
253 save();
254 }
255
256
257 private static List<TextSecureAttachment> getTextSecureAttachments(List<String> attachments) throws AttachmentInvalidException {
258 List<TextSecureAttachment> textSecureAttachments = null;
259 if (attachments != null) {
260 textSecureAttachments = new ArrayList<>(attachments.size());
261 for (String attachment : attachments) {
262 try {
263 textSecureAttachments.add(createAttachment(attachment));
264 } catch (IOException e) {
265 throw new AttachmentInvalidException(attachment, e);
266 }
267 }
268 }
269 return textSecureAttachments;
270 }
271
272 private static TextSecureAttachmentStream createAttachment(String attachment) throws IOException {
273 File attachmentFile = new File(attachment);
274 InputStream attachmentStream = new FileInputStream(attachmentFile);
275 final long attachmentSize = attachmentFile.length();
276 String mime = Files.probeContentType(Paths.get(attachment));
277 return new TextSecureAttachmentStream(attachmentStream, mime, attachmentSize, null);
278 }
279
280 @Override
281 public void sendGroupMessage(String messageText, List<String> attachments,
282 byte[] groupId)
283 throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
284 final TextSecureDataMessage.Builder messageBuilder = TextSecureDataMessage.newBuilder().withBody(messageText);
285 if (attachments != null) {
286 messageBuilder.withAttachments(getTextSecureAttachments(attachments));
287 }
288 if (groupId != null) {
289 TextSecureGroup group = TextSecureGroup.newBuilder(TextSecureGroup.Type.DELIVER)
290 .withId(groupId)
291 .build();
292 messageBuilder.asGroupMessage(group);
293 }
294 TextSecureDataMessage message = messageBuilder.build();
295
296 sendMessage(message, groupStore.getGroup(groupId).members);
297 }
298
299 public void sendQuitGroupMessage(byte[] groupId) throws GroupNotFoundException, IOException, EncapsulatedExceptions {
300 TextSecureGroup group = TextSecureGroup.newBuilder(TextSecureGroup.Type.QUIT)
301 .withId(groupId)
302 .build();
303
304 TextSecureDataMessage message = TextSecureDataMessage.newBuilder()
305 .asGroupMessage(group)
306 .build();
307
308 sendMessage(message, groupStore.getGroup(groupId).members);
309 }
310
311 public byte[] sendUpdateGroupMessage(byte[] groupId, String name, Collection<String> members, String avatarFile) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
312 GroupInfo g;
313 if (groupId == null) {
314 // Create new group
315 g = new GroupInfo(Util.getSecretBytes(16));
316 g.members.add(username);
317 } else {
318 g = groupStore.getGroup(groupId);
319 }
320
321 if (name != null) {
322 g.name = name;
323 }
324
325 if (members != null) {
326 for (String member : members) {
327 try {
328 g.members.add(canonicalizeNumber(member));
329 } catch (InvalidNumberException e) {
330 System.err.println("Failed to add member \"" + member + "\" to group: " + e.getMessage());
331 System.err.println("Aborting…");
332 System.exit(1);
333 }
334 }
335 }
336
337 TextSecureGroup.Builder group = TextSecureGroup.newBuilder(TextSecureGroup.Type.UPDATE)
338 .withId(g.groupId)
339 .withName(g.name)
340 .withMembers(new ArrayList<>(g.members));
341
342 if (avatarFile != null) {
343 try {
344 group.withAvatar(createAttachment(avatarFile));
345 // TODO
346 g.avatarId = 0;
347 } catch (IOException e) {
348 throw new AttachmentInvalidException(avatarFile, e);
349 }
350 }
351
352 groupStore.updateGroup(g);
353
354 TextSecureDataMessage message = TextSecureDataMessage.newBuilder()
355 .asGroupMessage(group.build())
356 .build();
357
358 sendMessage(message, g.members);
359 return g.groupId;
360 }
361
362 @Override
363 public void sendMessage(String message, List<String> attachments, String recipient)
364 throws EncapsulatedExceptions, AttachmentInvalidException, IOException {
365 List<String> recipients = new ArrayList<>(1);
366 recipients.add(recipient);
367 sendMessage(message, attachments, recipients);
368 }
369
370 public void sendMessage(String messageText, List<String> attachments,
371 Collection<String> recipients)
372 throws IOException, EncapsulatedExceptions, AttachmentInvalidException {
373 final TextSecureDataMessage.Builder messageBuilder = TextSecureDataMessage.newBuilder().withBody(messageText);
374 if (attachments != null) {
375 messageBuilder.withAttachments(getTextSecureAttachments(attachments));
376 }
377 TextSecureDataMessage message = messageBuilder.build();
378
379 sendMessage(message, recipients);
380 }
381
382 public void sendEndSessionMessage(List<String> recipients) throws IOException, EncapsulatedExceptions {
383 TextSecureDataMessage message = TextSecureDataMessage.newBuilder()
384 .asEndSessionMessage()
385 .build();
386
387 sendMessage(message, recipients);
388 }
389
390 private void sendMessage(TextSecureDataMessage message, Collection<String> recipients)
391 throws IOException, EncapsulatedExceptions {
392 TextSecureMessageSender messageSender = new TextSecureMessageSender(URL, TRUST_STORE, username, password,
393 axolotlStore, USER_AGENT, Optional.<TextSecureMessageSender.EventListener>absent());
394
395 Set<TextSecureAddress> recipientsTS = new HashSet<>(recipients.size());
396 for (String recipient : recipients) {
397 try {
398 recipientsTS.add(getPushAddress(recipient));
399 } catch (InvalidNumberException e) {
400 System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage());
401 System.err.println("Aborting sending.");
402 save();
403 return;
404 }
405 }
406
407 messageSender.sendMessage(new ArrayList<>(recipientsTS), message);
408
409 if (message.isEndSession()) {
410 for (TextSecureAddress recipient : recipientsTS) {
411 handleEndSession(recipient.getNumber());
412 }
413 }
414 save();
415 }
416
417 private TextSecureContent decryptMessage(TextSecureEnvelope envelope) {
418 TextSecureCipher cipher = new TextSecureCipher(new TextSecureAddress(username), axolotlStore);
419 try {
420 return cipher.decrypt(envelope);
421 } catch (Exception e) {
422 // TODO handle all exceptions
423 e.printStackTrace();
424 return null;
425 }
426 }
427
428 private void handleEndSession(String source) {
429 axolotlStore.deleteAllSessions(source);
430 }
431
432 public interface ReceiveMessageHandler {
433 void handleMessage(TextSecureEnvelope envelope, TextSecureContent decryptedContent, GroupInfo group);
434 }
435
436 public void receiveMessages(int timeoutSeconds, boolean returnOnTimeout, ReceiveMessageHandler handler) throws IOException {
437 final TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey, USER_AGENT);
438 TextSecureMessagePipe messagePipe = null;
439
440 try {
441 messagePipe = messageReceiver.createMessagePipe();
442
443 while (true) {
444 TextSecureEnvelope envelope;
445 TextSecureContent content = null;
446 GroupInfo group = null;
447 try {
448 envelope = messagePipe.read(timeoutSeconds, TimeUnit.SECONDS);
449 if (!envelope.isReceipt()) {
450 content = decryptMessage(envelope);
451 if (content != null) {
452 if (content.getDataMessage().isPresent()) {
453 TextSecureDataMessage message = content.getDataMessage().get();
454 if (message.getGroupInfo().isPresent()) {
455 TextSecureGroup groupInfo = message.getGroupInfo().get();
456 switch (groupInfo.getType()) {
457 case UPDATE:
458 try {
459 group = groupStore.getGroup(groupInfo.getGroupId());
460 } catch (GroupNotFoundException e) {
461 group = new GroupInfo(groupInfo.getGroupId());
462 }
463
464 if (groupInfo.getAvatar().isPresent()) {
465 TextSecureAttachment avatar = groupInfo.getAvatar().get();
466 if (avatar.isPointer()) {
467 long avatarId = avatar.asPointer().getId();
468 try {
469 retrieveAttachment(avatar.asPointer());
470 group.avatarId = avatarId;
471 } catch (IOException | InvalidMessageException e) {
472 System.err.println("Failed to retrieve group avatar (" + avatarId + "): " + e.getMessage());
473 }
474 }
475 }
476
477 if (groupInfo.getName().isPresent()) {
478 group.name = groupInfo.getName().get();
479 }
480
481 if (groupInfo.getMembers().isPresent()) {
482 group.members.addAll(groupInfo.getMembers().get());
483 }
484
485 groupStore.updateGroup(group);
486 break;
487 case DELIVER:
488 try {
489 group = groupStore.getGroup(groupInfo.getGroupId());
490 } catch (GroupNotFoundException e) {
491 }
492 break;
493 case QUIT:
494 try {
495 group = groupStore.getGroup(groupInfo.getGroupId());
496 group.members.remove(envelope.getSource());
497 } catch (GroupNotFoundException e) {
498 }
499 break;
500 }
501 }
502 if (message.isEndSession()) {
503 handleEndSession(envelope.getSource());
504 }
505 if (message.getAttachments().isPresent()) {
506 for (TextSecureAttachment attachment : message.getAttachments().get()) {
507 if (attachment.isPointer()) {
508 try {
509 retrieveAttachment(attachment.asPointer());
510 } catch (IOException | InvalidMessageException e) {
511 System.err.println("Failed to retrieve attachment (" + attachment.asPointer().getId() + "): " + e.getMessage());
512 }
513 }
514 }
515 }
516 }
517 }
518 }
519 save();
520 handler.handleMessage(envelope, content, group);
521 } catch (TimeoutException e) {
522 if (returnOnTimeout)
523 return;
524 } catch (InvalidVersionException e) {
525 System.err.println("Ignoring error: " + e.getMessage());
526 }
527 }
528 } finally {
529 if (messagePipe != null)
530 messagePipe.shutdown();
531 }
532 }
533
534 public File getAttachmentFile(long attachmentId) {
535 return new File(attachmentsPath + "/" + attachmentId);
536 }
537
538 private File retrieveAttachment(TextSecureAttachmentPointer pointer) throws IOException, InvalidMessageException {
539 final TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey, USER_AGENT);
540
541 File tmpFile = File.createTempFile("ts_attach_" + pointer.getId(), ".tmp");
542 InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile);
543
544 new File(attachmentsPath).mkdirs();
545 File outputFile = getAttachmentFile(pointer.getId());
546 OutputStream output = null;
547 try {
548 output = new FileOutputStream(outputFile);
549 byte[] buffer = new byte[4096];
550 int read;
551
552 while ((read = input.read(buffer)) != -1) {
553 output.write(buffer, 0, read);
554 }
555 } catch (FileNotFoundException e) {
556 e.printStackTrace();
557 return null;
558 } finally {
559 if (output != null) {
560 output.close();
561 output = null;
562 }
563 if (!tmpFile.delete()) {
564 System.err.println("Failed to delete temp file: " + tmpFile);
565 }
566 }
567 if (pointer.getPreview().isPresent()) {
568 File previewFile = new File(outputFile + ".preview");
569 try {
570 output = new FileOutputStream(previewFile);
571 byte[] preview = pointer.getPreview().get();
572 output.write(preview, 0, preview.length);
573 } catch (FileNotFoundException e) {
574 e.printStackTrace();
575 return null;
576 } finally {
577 if (output != null) {
578 output.close();
579 }
580 }
581 }
582 return outputFile;
583 }
584
585 private String canonicalizeNumber(String number) throws InvalidNumberException {
586 String localNumber = username;
587 return PhoneNumberFormatter.formatNumber(number, localNumber);
588 }
589
590 private TextSecureAddress getPushAddress(String number) throws InvalidNumberException {
591 String e164number = canonicalizeNumber(number);
592 return new TextSecureAddress(e164number);
593 }
594
595 @Override
596 public boolean isRemote() {
597 return false;
598 }
599 }