]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Manager.java
Move endsession and attachment handling to Manager
[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.util.ArrayList;
48 import java.util.LinkedList;
49 import java.util.List;
50 import java.util.concurrent.TimeUnit;
51 import java.util.concurrent.TimeoutException;
52
53 class Manager {
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 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password, USER_AGENT);
134 }
135
136 public void save() {
137 ObjectNode rootNode = jsonProcessot.createObjectNode();
138 rootNode.put("username", username)
139 .put("password", password)
140 .put("signalingKey", signalingKey)
141 .put("preKeyIdOffset", preKeyIdOffset)
142 .put("nextSignedPreKeyId", nextSignedPreKeyId)
143 .put("registered", registered)
144 .putPOJO("axolotlStore", axolotlStore)
145 .putPOJO("groupStore", groupStore)
146 ;
147 try {
148 jsonProcessot.writeValue(new File(getFileName()), rootNode);
149 } catch (Exception e) {
150 System.err.println(String.format("Error saving file: %s", e.getMessage()));
151 }
152 }
153
154 public void createNewIdentity() {
155 IdentityKeyPair identityKey = KeyHelper.generateIdentityKeyPair();
156 int registrationId = KeyHelper.generateRegistrationId(false);
157 axolotlStore = new JsonAxolotlStore(identityKey, registrationId);
158 groupStore = new JsonGroupStore();
159 registered = false;
160 }
161
162 public boolean isRegistered() {
163 return registered;
164 }
165
166 public void register(boolean voiceVerication) throws IOException {
167 password = Util.getSecret(18);
168
169 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password, USER_AGENT);
170
171 if (voiceVerication)
172 accountManager.requestVoiceVerificationCode();
173 else
174 accountManager.requestSmsVerificationCode();
175
176 registered = false;
177 }
178
179 private static final int BATCH_SIZE = 100;
180
181 private List<PreKeyRecord> generatePreKeys() {
182 List<PreKeyRecord> records = new LinkedList<>();
183
184 for (int i = 0; i < BATCH_SIZE; i++) {
185 int preKeyId = (preKeyIdOffset + i) % Medium.MAX_VALUE;
186 ECKeyPair keyPair = Curve.generateKeyPair();
187 PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);
188
189 axolotlStore.storePreKey(preKeyId, record);
190 records.add(record);
191 }
192
193 preKeyIdOffset = (preKeyIdOffset + BATCH_SIZE + 1) % Medium.MAX_VALUE;
194 return records;
195 }
196
197 private PreKeyRecord generateLastResortPreKey() {
198 if (axolotlStore.containsPreKey(Medium.MAX_VALUE)) {
199 try {
200 return axolotlStore.loadPreKey(Medium.MAX_VALUE);
201 } catch (InvalidKeyIdException e) {
202 axolotlStore.removePreKey(Medium.MAX_VALUE);
203 }
204 }
205
206 ECKeyPair keyPair = Curve.generateKeyPair();
207 PreKeyRecord record = new PreKeyRecord(Medium.MAX_VALUE, keyPair);
208
209 axolotlStore.storePreKey(Medium.MAX_VALUE, record);
210
211 return record;
212 }
213
214 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
215 try {
216 ECKeyPair keyPair = Curve.generateKeyPair();
217 byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
218 SignedPreKeyRecord record = new SignedPreKeyRecord(nextSignedPreKeyId, System.currentTimeMillis(), keyPair, signature);
219
220 axolotlStore.storeSignedPreKey(nextSignedPreKeyId, record);
221 nextSignedPreKeyId = (nextSignedPreKeyId + 1) % Medium.MAX_VALUE;
222
223 return record;
224 } catch (InvalidKeyException e) {
225 throw new AssertionError(e);
226 }
227 }
228
229 public void verifyAccount(String verificationCode) throws IOException {
230 verificationCode = verificationCode.replace("-", "");
231 signalingKey = Util.getSecret(52);
232 accountManager.verifyAccountWithCode(verificationCode, signalingKey, axolotlStore.getLocalRegistrationId(), false);
233
234 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
235 registered = true;
236
237 List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
238
239 PreKeyRecord lastResortKey = generateLastResortPreKey();
240
241 SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(axolotlStore.getIdentityKeyPair());
242
243 accountManager.setPreKeys(axolotlStore.getIdentityKeyPair().getPublicKey(), lastResortKey, signedPreKeyRecord, oneTimePreKeys);
244 }
245
246 public void sendMessage(List<String> recipients, TextSecureDataMessage message)
247 throws IOException, EncapsulatedExceptions {
248 TextSecureMessageSender messageSender = new TextSecureMessageSender(URL, TRUST_STORE, username, password,
249 axolotlStore, USER_AGENT, Optional.<TextSecureMessageSender.EventListener>absent());
250
251 List<TextSecureAddress> recipientsTS = new ArrayList<>(recipients.size());
252 for (String recipient : recipients) {
253 try {
254 recipientsTS.add(getPushAddress(recipient));
255 } catch (InvalidNumberException e) {
256 System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage());
257 System.err.println("Aborting sending.");
258 return;
259 }
260 }
261
262 messageSender.sendMessage(recipientsTS, message);
263
264 if (message.isEndSession()) {
265 for (TextSecureAddress recipient : recipientsTS) {
266 handleEndSession(recipient.getNumber());
267 }
268 }
269 }
270
271 private TextSecureContent decryptMessage(TextSecureEnvelope envelope) {
272 TextSecureCipher cipher = new TextSecureCipher(new TextSecureAddress(username), axolotlStore);
273 try {
274 return cipher.decrypt(envelope);
275 } catch (Exception e) {
276 // TODO handle all exceptions
277 e.printStackTrace();
278 return null;
279 }
280 }
281
282 private void handleEndSession(String source) {
283 axolotlStore.deleteAllSessions(source);
284 }
285
286 public interface ReceiveMessageHandler {
287 void handleMessage(TextSecureEnvelope envelope, TextSecureContent decryptedContent, GroupInfo group);
288 }
289
290 public void receiveMessages(int timeoutSeconds, boolean returnOnTimeout, ReceiveMessageHandler handler) throws IOException {
291 final TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey, USER_AGENT);
292 TextSecureMessagePipe messagePipe = null;
293
294 try {
295 messagePipe = messageReceiver.createMessagePipe();
296
297 while (true) {
298 TextSecureEnvelope envelope;
299 TextSecureContent content = null;
300 GroupInfo group = null;
301 try {
302 envelope = messagePipe.read(timeoutSeconds, TimeUnit.SECONDS);
303 if (!envelope.isReceipt()) {
304 content = decryptMessage(envelope);
305 if (content != null) {
306 if (content.getDataMessage().isPresent()) {
307 TextSecureDataMessage message = content.getDataMessage().get();
308 if (message.getGroupInfo().isPresent()) {
309 TextSecureGroup groupInfo = message.getGroupInfo().get();
310 switch (groupInfo.getType()) {
311 case UPDATE:
312 long avatarId = 0;
313 if (groupInfo.getAvatar().isPresent()) {
314 TextSecureAttachment avatar = groupInfo.getAvatar().get();
315 if (avatar.isPointer()) {
316 avatarId = avatar.asPointer().getId();
317 try {
318 retrieveAttachment(avatar.asPointer());
319 } catch (IOException | InvalidMessageException e) {
320 System.err.println("Failed to retrieve group avatar (" + avatarId + "): " + e.getMessage());
321 }
322 }
323 }
324
325 group = new GroupInfo(groupInfo.getGroupId(), groupInfo.getName().get(), groupInfo.getMembers().get(), avatarId);
326 groupStore.updateGroup(group);
327 break;
328 case DELIVER:
329 group = groupStore.getGroup(groupInfo.getGroupId());
330 break;
331 case QUIT:
332 group = groupStore.getGroup(groupInfo.getGroupId());
333 if (group != null) {
334 group.members.remove(envelope.getSource());
335 }
336 break;
337 }
338 }
339 if (message.isEndSession()) {
340 handleEndSession(envelope.getSource());
341 }
342 if (message.getAttachments().isPresent()) {
343 for (TextSecureAttachment attachment : message.getAttachments().get()) {
344 if (attachment.isPointer()) {
345 try {
346 retrieveAttachment(attachment.asPointer());
347 } catch (IOException | InvalidMessageException e) {
348 System.err.println("Failed to retrieve attachment (" + attachment.asPointer().getId() + "): " + e.getMessage());
349 }
350 }
351 }
352 }
353 }
354 }
355 }
356 handler.handleMessage(envelope, content, group);
357 } catch (TimeoutException e) {
358 if (returnOnTimeout)
359 return;
360 } catch (InvalidVersionException e) {
361 System.err.println("Ignoring error: " + e.getMessage());
362 }
363 save();
364 }
365 } finally {
366 if (messagePipe != null)
367 messagePipe.shutdown();
368 }
369 }
370
371 public File getAttachmentFile(long attachmentId) {
372 return new File(attachmentsPath + "/" + attachmentId);
373 }
374
375 private File retrieveAttachment(TextSecureAttachmentPointer pointer) throws IOException, InvalidMessageException {
376 final TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey, USER_AGENT);
377
378 File tmpFile = File.createTempFile("ts_attach_" + pointer.getId(), ".tmp");
379 InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile);
380
381 new File(attachmentsPath).mkdirs();
382 File outputFile = getAttachmentFile(pointer.getId());
383 OutputStream output = null;
384 try {
385 output = new FileOutputStream(outputFile);
386 byte[] buffer = new byte[4096];
387 int read;
388
389 while ((read = input.read(buffer)) != -1) {
390 output.write(buffer, 0, read);
391 }
392 } catch (FileNotFoundException e) {
393 e.printStackTrace();
394 return null;
395 } finally {
396 if (output != null) {
397 output.close();
398 output = null;
399 }
400 if (!tmpFile.delete()) {
401 System.err.println("Failed to delete temp file: " + tmpFile);
402 }
403 }
404 if (pointer.getPreview().isPresent()) {
405 File previewFile = new File(outputFile + ".preview");
406 try {
407 output = new FileOutputStream(previewFile);
408 byte[] preview = pointer.getPreview().get();
409 output.write(preview, 0, preview.length);
410 } catch (FileNotFoundException e) {
411 e.printStackTrace();
412 return null;
413 } finally {
414 if (output != null) {
415 output.close();
416 }
417 }
418 }
419 return outputFile;
420 }
421
422 private String canonicalizeNumber(String number) throws InvalidNumberException {
423 String localNumber = username;
424 return PhoneNumberFormatter.formatNumber(number, localNumber);
425 }
426
427 private TextSecureAddress getPushAddress(String number) throws InvalidNumberException {
428 String e164number = canonicalizeNumber(number);
429 return new TextSecureAddress(e164number);
430 }
431
432 public GroupInfo getGroupInfo(byte[] groupId) {
433 return groupStore.getGroup(groupId);
434 }
435 }