]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/Manager.java
5bff3cf3fa009d90d64635428c5c02e856f13d8c
[signal-cli] / src / main / java / org / asamk / signal / 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 org.asamk.signal;
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.apache.http.util.TextUtils;
27 import org.asamk.Signal;
28 import org.whispersystems.libsignal.*;
29 import org.whispersystems.libsignal.ecc.Curve;
30 import org.whispersystems.libsignal.ecc.ECKeyPair;
31 import org.whispersystems.libsignal.ecc.ECPublicKey;
32 import org.whispersystems.libsignal.state.PreKeyRecord;
33 import org.whispersystems.libsignal.state.SignalProtocolStore;
34 import org.whispersystems.libsignal.state.SignedPreKeyRecord;
35 import org.whispersystems.libsignal.util.KeyHelper;
36 import org.whispersystems.libsignal.util.Medium;
37 import org.whispersystems.libsignal.util.guava.Optional;
38 import org.whispersystems.signalservice.api.SignalServiceAccountManager;
39 import org.whispersystems.signalservice.api.SignalServiceMessagePipe;
40 import org.whispersystems.signalservice.api.SignalServiceMessageReceiver;
41 import org.whispersystems.signalservice.api.SignalServiceMessageSender;
42 import org.whispersystems.signalservice.api.crypto.SignalServiceCipher;
43 import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
44 import org.whispersystems.signalservice.api.messages.*;
45 import org.whispersystems.signalservice.api.messages.multidevice.*;
46 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
47 import org.whispersystems.signalservice.api.push.TrustStore;
48 import org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedException;
49 import org.whispersystems.signalservice.api.push.exceptions.EncapsulatedExceptions;
50 import org.whispersystems.signalservice.api.util.InvalidNumberException;
51 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
52 import org.whispersystems.signalservice.internal.push.SignalServiceProtos;
53
54 import java.io.*;
55 import java.net.URI;
56 import java.net.URISyntaxException;
57 import java.net.URLDecoder;
58 import java.net.URLEncoder;
59 import java.nio.file.Files;
60 import java.nio.file.Paths;
61 import java.util.*;
62 import java.util.concurrent.TimeUnit;
63 import java.util.concurrent.TimeoutException;
64
65 class Manager implements Signal {
66 private final static String URL = "https://textsecure-service.whispersystems.org";
67 private final static TrustStore TRUST_STORE = new WhisperTrustStore();
68
69 public final static String PROJECT_NAME = Manager.class.getPackage().getImplementationTitle();
70 public final static String PROJECT_VERSION = Manager.class.getPackage().getImplementationVersion();
71 private final static String USER_AGENT = PROJECT_NAME == null ? null : PROJECT_NAME + " " + PROJECT_VERSION;
72
73 private final static int PREKEY_MINIMUM_COUNT = 20;
74 private static final int PREKEY_BATCH_SIZE = 100;
75
76 private final String settingsPath;
77 private final String dataPath;
78 private final String attachmentsPath;
79
80 private final ObjectMapper jsonProcessot = new ObjectMapper();
81 private String username;
82 int deviceId = SignalServiceAddress.DEFAULT_DEVICE_ID;
83 private String password;
84 private String signalingKey;
85 private int preKeyIdOffset;
86 private int nextSignedPreKeyId;
87
88 private boolean registered = false;
89
90 private SignalProtocolStore signalProtocolStore;
91 private SignalServiceAccountManager accountManager;
92 private JsonGroupStore groupStore;
93
94 public Manager(String username, String settingsPath) {
95 this.username = username;
96 this.settingsPath = settingsPath;
97 this.dataPath = this.settingsPath + "/data";
98 this.attachmentsPath = this.settingsPath + "/attachments";
99
100 jsonProcessot.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); // disable autodetect
101 jsonProcessot.enable(SerializationFeature.INDENT_OUTPUT); // for pretty print, you can disable it.
102 jsonProcessot.enable(SerializationFeature.WRITE_NULL_MAP_VALUES);
103 jsonProcessot.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
104 }
105
106 public String getUsername() {
107 return username;
108 }
109
110 public String getFileName() {
111 new File(dataPath).mkdirs();
112 return dataPath + "/" + username;
113 }
114
115 public boolean userExists() {
116 if (username == null) {
117 return false;
118 }
119 File f = new File(getFileName());
120 return !(!f.exists() || f.isDirectory());
121 }
122
123 public boolean userHasKeys() {
124 return signalProtocolStore != null;
125 }
126
127 private JsonNode getNotNullNode(JsonNode parent, String name) throws InvalidObjectException {
128 JsonNode node = parent.get(name);
129 if (node == null) {
130 throw new InvalidObjectException(String.format("Incorrect file format: expected parameter %s not found ", name));
131 }
132
133 return node;
134 }
135
136 public void load() throws IOException, InvalidKeyException {
137 JsonNode rootNode = jsonProcessot.readTree(new File(getFileName()));
138
139 JsonNode node = rootNode.get("deviceId");
140 if (node != null) {
141 deviceId = node.asInt();
142 }
143 username = getNotNullNode(rootNode, "username").asText();
144 password = getNotNullNode(rootNode, "password").asText();
145 if (rootNode.has("signalingKey")) {
146 signalingKey = getNotNullNode(rootNode, "signalingKey").asText();
147 }
148 if (rootNode.has("preKeyIdOffset")) {
149 preKeyIdOffset = getNotNullNode(rootNode, "preKeyIdOffset").asInt(0);
150 } else {
151 preKeyIdOffset = 0;
152 }
153 if (rootNode.has("nextSignedPreKeyId")) {
154 nextSignedPreKeyId = getNotNullNode(rootNode, "nextSignedPreKeyId").asInt();
155 } else {
156 nextSignedPreKeyId = 0;
157 }
158 signalProtocolStore = jsonProcessot.convertValue(getNotNullNode(rootNode, "axolotlStore"), JsonSignalProtocolStore.class);
159 registered = getNotNullNode(rootNode, "registered").asBoolean();
160 JsonNode groupStoreNode = rootNode.get("groupStore");
161 if (groupStoreNode != null) {
162 groupStore = jsonProcessot.convertValue(groupStoreNode, JsonGroupStore.class);
163 }
164 if (groupStore == null) {
165 groupStore = new JsonGroupStore();
166 }
167 accountManager = new SignalServiceAccountManager(URL, TRUST_STORE, username, password, deviceId, USER_AGENT);
168 try {
169 if (registered && accountManager.getPreKeysCount() < PREKEY_MINIMUM_COUNT) {
170 refreshPreKeys();
171 save();
172 }
173 } catch (AuthorizationFailedException e) {
174 System.err.println("Authorization failed, was the number registered elsewhere?");
175 }
176 }
177
178 private void save() {
179 ObjectNode rootNode = jsonProcessot.createObjectNode();
180 rootNode.put("username", username)
181 .put("deviceId", deviceId)
182 .put("password", password)
183 .put("signalingKey", signalingKey)
184 .put("preKeyIdOffset", preKeyIdOffset)
185 .put("nextSignedPreKeyId", nextSignedPreKeyId)
186 .put("registered", registered)
187 .putPOJO("axolotlStore", signalProtocolStore)
188 .putPOJO("groupStore", groupStore)
189 ;
190 try {
191 jsonProcessot.writeValue(new File(getFileName()), rootNode);
192 } catch (Exception e) {
193 System.err.println(String.format("Error saving file: %s", e.getMessage()));
194 }
195 }
196
197 public void createNewIdentity() {
198 IdentityKeyPair identityKey = KeyHelper.generateIdentityKeyPair();
199 int registrationId = KeyHelper.generateRegistrationId(false);
200 signalProtocolStore = new JsonSignalProtocolStore(identityKey, registrationId);
201 groupStore = new JsonGroupStore();
202 registered = false;
203 save();
204 }
205
206 public boolean isRegistered() {
207 return registered;
208 }
209
210 public void register(boolean voiceVerication) throws IOException {
211 password = Util.getSecret(18);
212
213 accountManager = new SignalServiceAccountManager(URL, TRUST_STORE, username, password, USER_AGENT);
214
215 if (voiceVerication)
216 accountManager.requestVoiceVerificationCode();
217 else
218 accountManager.requestSmsVerificationCode();
219
220 registered = false;
221 save();
222 }
223
224 public URI getDeviceLinkUri() throws TimeoutException, IOException {
225 password = Util.getSecret(18);
226
227 accountManager = new SignalServiceAccountManager(URL, TRUST_STORE, username, password, USER_AGENT);
228 String uuid = accountManager.getNewDeviceUuid();
229
230 registered = false;
231 try {
232 return new URI("tsdevice:/?uuid=" + URLEncoder.encode(uuid, "utf-8") + "&pub_key=" + URLEncoder.encode(Base64.encodeBytesWithoutPadding(signalProtocolStore.getIdentityKeyPair().getPublicKey().serialize()), "utf-8"));
233 } catch (URISyntaxException e) {
234 // Shouldn't happen
235 return null;
236 }
237 }
238
239 public void finishDeviceLink(String deviceName) throws IOException, InvalidKeyException, TimeoutException, UserAlreadyExists {
240 signalingKey = Util.getSecret(52);
241 SignalServiceAccountManager.NewDeviceRegistrationReturn ret = accountManager.finishNewDeviceRegistration(signalProtocolStore.getIdentityKeyPair(), signalingKey, false, true, signalProtocolStore.getLocalRegistrationId(), deviceName);
242 deviceId = ret.getDeviceId();
243 username = ret.getNumber();
244 // TODO do this check before actually registering
245 if (userExists()) {
246 throw new UserAlreadyExists(username, getFileName());
247 }
248 signalProtocolStore = new JsonSignalProtocolStore(ret.getIdentity(), signalProtocolStore.getLocalRegistrationId());
249
250 registered = true;
251 refreshPreKeys();
252
253 requestSyncGroups();
254 requestSyncContacts();
255
256 save();
257 }
258
259
260 public static Map<String, String> getQueryMap(String query) {
261 String[] params = query.split("&");
262 Map<String, String> map = new HashMap<>();
263 for (String param : params) {
264 String name = null;
265 try {
266 name = URLDecoder.decode(param.split("=")[0], "utf-8");
267 } catch (UnsupportedEncodingException e) {
268 // Impossible
269 }
270 String value = null;
271 try {
272 value = URLDecoder.decode(param.split("=")[1], "utf-8");
273 } catch (UnsupportedEncodingException e) {
274 // Impossible
275 }
276 map.put(name, value);
277 }
278 return map;
279 }
280
281 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
282 Map<String, String> query = getQueryMap(linkUri.getQuery());
283 String deviceIdentifier = query.get("uuid");
284 String publicKeyEncoded = query.get("pub_key");
285
286 if (TextUtils.isEmpty(deviceIdentifier) || TextUtils.isEmpty(publicKeyEncoded)) {
287 throw new RuntimeException("Invalid device link uri");
288 }
289
290 ECPublicKey deviceKey = Curve.decodePoint(Base64.decode(publicKeyEncoded), 0);
291
292 addDeviceLink(deviceIdentifier, deviceKey);
293 }
294
295 private void addDeviceLink(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
296 IdentityKeyPair identityKeyPair = signalProtocolStore.getIdentityKeyPair();
297 String verificationCode = accountManager.getNewDeviceVerificationCode();
298
299 accountManager.addDevice(deviceIdentifier, deviceKey, identityKeyPair, verificationCode);
300 }
301
302 private List<PreKeyRecord> generatePreKeys() {
303 List<PreKeyRecord> records = new LinkedList<>();
304
305 for (int i = 0; i < PREKEY_BATCH_SIZE; i++) {
306 int preKeyId = (preKeyIdOffset + i) % Medium.MAX_VALUE;
307 ECKeyPair keyPair = Curve.generateKeyPair();
308 PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);
309
310 signalProtocolStore.storePreKey(preKeyId, record);
311 records.add(record);
312 }
313
314 preKeyIdOffset = (preKeyIdOffset + PREKEY_BATCH_SIZE + 1) % Medium.MAX_VALUE;
315 save();
316
317 return records;
318 }
319
320 private PreKeyRecord getOrGenerateLastResortPreKey() {
321 if (signalProtocolStore.containsPreKey(Medium.MAX_VALUE)) {
322 try {
323 return signalProtocolStore.loadPreKey(Medium.MAX_VALUE);
324 } catch (InvalidKeyIdException e) {
325 signalProtocolStore.removePreKey(Medium.MAX_VALUE);
326 }
327 }
328
329 ECKeyPair keyPair = Curve.generateKeyPair();
330 PreKeyRecord record = new PreKeyRecord(Medium.MAX_VALUE, keyPair);
331
332 signalProtocolStore.storePreKey(Medium.MAX_VALUE, record);
333 save();
334
335 return record;
336 }
337
338 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
339 try {
340 ECKeyPair keyPair = Curve.generateKeyPair();
341 byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
342 SignedPreKeyRecord record = new SignedPreKeyRecord(nextSignedPreKeyId, System.currentTimeMillis(), keyPair, signature);
343
344 signalProtocolStore.storeSignedPreKey(nextSignedPreKeyId, record);
345 nextSignedPreKeyId = (nextSignedPreKeyId + 1) % Medium.MAX_VALUE;
346 save();
347
348 return record;
349 } catch (InvalidKeyException e) {
350 throw new AssertionError(e);
351 }
352 }
353
354 public void verifyAccount(String verificationCode) throws IOException {
355 verificationCode = verificationCode.replace("-", "");
356 signalingKey = Util.getSecret(52);
357 accountManager.verifyAccountWithCode(verificationCode, signalingKey, signalProtocolStore.getLocalRegistrationId(), false, true);
358
359 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
360 registered = true;
361
362 refreshPreKeys();
363 save();
364 }
365
366 private void refreshPreKeys() throws IOException {
367 List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
368 PreKeyRecord lastResortKey = getOrGenerateLastResortPreKey();
369 SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(signalProtocolStore.getIdentityKeyPair());
370
371 accountManager.setPreKeys(signalProtocolStore.getIdentityKeyPair().getPublicKey(), lastResortKey, signedPreKeyRecord, oneTimePreKeys);
372 }
373
374
375 private static List<SignalServiceAttachment> getSignalServiceAttachments(List<String> attachments) throws AttachmentInvalidException {
376 List<SignalServiceAttachment> SignalServiceAttachments = null;
377 if (attachments != null) {
378 SignalServiceAttachments = new ArrayList<>(attachments.size());
379 for (String attachment : attachments) {
380 try {
381 SignalServiceAttachments.add(createAttachment(attachment));
382 } catch (IOException e) {
383 throw new AttachmentInvalidException(attachment, e);
384 }
385 }
386 }
387 return SignalServiceAttachments;
388 }
389
390 private static SignalServiceAttachment createAttachment(String attachment) throws IOException {
391 File attachmentFile = new File(attachment);
392 InputStream attachmentStream = new FileInputStream(attachmentFile);
393 final long attachmentSize = attachmentFile.length();
394 String mime = Files.probeContentType(Paths.get(attachment));
395 return new SignalServiceAttachmentStream(attachmentStream, mime, attachmentSize, null);
396 }
397
398 @Override
399 public void sendGroupMessage(String messageText, List<String> attachments,
400 byte[] groupId)
401 throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException, UntrustedIdentityException {
402 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
403 if (attachments != null) {
404 messageBuilder.withAttachments(getSignalServiceAttachments(attachments));
405 }
406 if (groupId != null) {
407 SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.DELIVER)
408 .withId(groupId)
409 .build();
410 messageBuilder.asGroupMessage(group);
411 }
412 SignalServiceDataMessage message = messageBuilder.build();
413
414 sendMessage(message, groupStore.getGroup(groupId).members);
415 }
416
417 public void sendQuitGroupMessage(byte[] groupId) throws GroupNotFoundException, IOException, EncapsulatedExceptions, UntrustedIdentityException {
418 SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.QUIT)
419 .withId(groupId)
420 .build();
421
422 SignalServiceDataMessage message = SignalServiceDataMessage.newBuilder()
423 .asGroupMessage(group)
424 .build();
425
426 sendMessage(message, groupStore.getGroup(groupId).members);
427 }
428
429 public byte[] sendUpdateGroupMessage(byte[] groupId, String name, Collection<String> members, String avatarFile) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException, UntrustedIdentityException {
430 GroupInfo g;
431 if (groupId == null) {
432 // Create new group
433 g = new GroupInfo(Util.getSecretBytes(16));
434 g.members.add(username);
435 } else {
436 g = groupStore.getGroup(groupId);
437 }
438
439 if (name != null) {
440 g.name = name;
441 }
442
443 if (members != null) {
444 for (String member : members) {
445 try {
446 g.members.add(canonicalizeNumber(member));
447 } catch (InvalidNumberException e) {
448 System.err.println("Failed to add member \"" + member + "\" to group: " + e.getMessage());
449 System.err.println("Aborting…");
450 System.exit(1);
451 }
452 }
453 }
454
455 SignalServiceGroup.Builder group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.UPDATE)
456 .withId(g.groupId)
457 .withName(g.name)
458 .withMembers(new ArrayList<>(g.members));
459
460 if (avatarFile != null) {
461 try {
462 group.withAvatar(createAttachment(avatarFile));
463 // TODO
464 g.avatarId = 0;
465 } catch (IOException e) {
466 throw new AttachmentInvalidException(avatarFile, e);
467 }
468 }
469
470 groupStore.updateGroup(g);
471
472 SignalServiceDataMessage message = SignalServiceDataMessage.newBuilder()
473 .asGroupMessage(group.build())
474 .build();
475
476 sendMessage(message, g.members);
477 return g.groupId;
478 }
479
480 @Override
481 public void sendMessage(String message, List<String> attachments, String recipient)
482 throws EncapsulatedExceptions, AttachmentInvalidException, IOException, UntrustedIdentityException {
483 List<String> recipients = new ArrayList<>(1);
484 recipients.add(recipient);
485 sendMessage(message, attachments, recipients);
486 }
487
488 @Override
489 public void sendMessage(String messageText, List<String> attachments,
490 List<String> recipients)
491 throws IOException, EncapsulatedExceptions, AttachmentInvalidException, UntrustedIdentityException {
492 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
493 if (attachments != null) {
494 messageBuilder.withAttachments(getSignalServiceAttachments(attachments));
495 }
496 SignalServiceDataMessage message = messageBuilder.build();
497
498 sendMessage(message, recipients);
499 }
500
501 @Override
502 public void sendEndSessionMessage(List<String> recipients) throws IOException, EncapsulatedExceptions, UntrustedIdentityException {
503 SignalServiceDataMessage message = SignalServiceDataMessage.newBuilder()
504 .asEndSessionMessage()
505 .build();
506
507 sendMessage(message, recipients);
508 }
509
510 private void requestSyncGroups() throws IOException {
511 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS).build();
512 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
513 try {
514 sendMessage(message);
515 } catch (EncapsulatedExceptions encapsulatedExceptions) {
516 encapsulatedExceptions.printStackTrace();
517 } catch (UntrustedIdentityException e) {
518 e.printStackTrace();
519 }
520 }
521
522 private void requestSyncContacts() throws IOException {
523 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS).build();
524 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
525 try {
526 sendMessage(message);
527 } catch (EncapsulatedExceptions encapsulatedExceptions) {
528 encapsulatedExceptions.printStackTrace();
529 } catch (UntrustedIdentityException e) {
530 e.printStackTrace();
531 }
532 }
533
534 private void sendMessage(SignalServiceSyncMessage message)
535 throws IOException, EncapsulatedExceptions, UntrustedIdentityException {
536 SignalServiceMessageSender messageSender = new SignalServiceMessageSender(URL, TRUST_STORE, username, password,
537 deviceId, signalProtocolStore, USER_AGENT, Optional.<SignalServiceMessageSender.EventListener>absent());
538 messageSender.sendMessage(message);
539 }
540
541 private void sendMessage(SignalServiceDataMessage message, Collection<String> recipients)
542 throws IOException, EncapsulatedExceptions, UntrustedIdentityException {
543 SignalServiceMessageSender messageSender = new SignalServiceMessageSender(URL, TRUST_STORE, username, password,
544 deviceId, signalProtocolStore, USER_AGENT, Optional.<SignalServiceMessageSender.EventListener>absent());
545
546 Set<SignalServiceAddress> recipientsTS = new HashSet<>(recipients.size());
547 for (String recipient : recipients) {
548 try {
549 recipientsTS.add(getPushAddress(recipient));
550 } catch (InvalidNumberException e) {
551 System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage());
552 System.err.println("Aborting sending.");
553 save();
554 return;
555 }
556 }
557
558 if (message.getGroupInfo().isPresent()) {
559 messageSender.sendMessage(new ArrayList<>(recipientsTS), message);
560 } else {
561 // Send to all individually, so sync messages are sent correctly
562 for (SignalServiceAddress address : recipientsTS) {
563 messageSender.sendMessage(address, message);
564 }
565 }
566
567 if (message.isEndSession()) {
568 for (SignalServiceAddress recipient : recipientsTS) {
569 handleEndSession(recipient.getNumber());
570 }
571 }
572 save();
573 }
574
575 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) {
576 SignalServiceCipher cipher = new SignalServiceCipher(new SignalServiceAddress(username), signalProtocolStore);
577 try {
578 return cipher.decrypt(envelope);
579 } catch (Exception e) {
580 // TODO handle all exceptions
581 e.printStackTrace();
582 return null;
583 }
584 }
585
586 private void handleEndSession(String source) {
587 signalProtocolStore.deleteAllSessions(source);
588 }
589
590 public interface ReceiveMessageHandler {
591 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, GroupInfo group);
592 }
593
594 private GroupInfo handleSignalServiceDataMessage(SignalServiceDataMessage message, boolean isSync, String source, String destination) {
595 GroupInfo group = null;
596 if (message.getGroupInfo().isPresent()) {
597 SignalServiceGroup groupInfo = message.getGroupInfo().get();
598 switch (groupInfo.getType()) {
599 case UPDATE:
600 try {
601 group = groupStore.getGroup(groupInfo.getGroupId());
602 } catch (GroupNotFoundException e) {
603 group = new GroupInfo(groupInfo.getGroupId());
604 }
605
606 if (groupInfo.getAvatar().isPresent()) {
607 SignalServiceAttachment avatar = groupInfo.getAvatar().get();
608 if (avatar.isPointer()) {
609 long avatarId = avatar.asPointer().getId();
610 try {
611 retrieveAttachment(avatar.asPointer());
612 // TODO store group avatar in /avatar/groups folder
613 group.avatarId = avatarId;
614 } catch (IOException | InvalidMessageException e) {
615 System.err.println("Failed to retrieve group avatar (" + avatarId + "): " + e.getMessage());
616 }
617 }
618 }
619
620 if (groupInfo.getName().isPresent()) {
621 group.name = groupInfo.getName().get();
622 }
623
624 if (groupInfo.getMembers().isPresent()) {
625 group.members.addAll(groupInfo.getMembers().get());
626 }
627
628 groupStore.updateGroup(group);
629 break;
630 case DELIVER:
631 try {
632 group = groupStore.getGroup(groupInfo.getGroupId());
633 } catch (GroupNotFoundException e) {
634 }
635 break;
636 case QUIT:
637 try {
638 group = groupStore.getGroup(groupInfo.getGroupId());
639 group.members.remove(source);
640 } catch (GroupNotFoundException e) {
641 }
642 break;
643 }
644 }
645 if (message.isEndSession()) {
646 handleEndSession(isSync ? destination : source);
647 }
648 if (message.getAttachments().isPresent()) {
649 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
650 if (attachment.isPointer()) {
651 try {
652 retrieveAttachment(attachment.asPointer());
653 } catch (IOException | InvalidMessageException e) {
654 System.err.println("Failed to retrieve attachment (" + attachment.asPointer().getId() + "): " + e.getMessage());
655 }
656 }
657 }
658 }
659 return group;
660 }
661
662 public void receiveMessages(int timeoutSeconds, boolean returnOnTimeout, ReceiveMessageHandler handler) throws IOException {
663 final SignalServiceMessageReceiver messageReceiver = new SignalServiceMessageReceiver(URL, TRUST_STORE, username, password, deviceId, signalingKey, USER_AGENT);
664 SignalServiceMessagePipe messagePipe = null;
665
666 try {
667 messagePipe = messageReceiver.createMessagePipe();
668
669 while (true) {
670 SignalServiceEnvelope envelope;
671 SignalServiceContent content = null;
672 GroupInfo group = null;
673 try {
674 envelope = messagePipe.read(timeoutSeconds, TimeUnit.SECONDS);
675 if (!envelope.isReceipt()) {
676 content = decryptMessage(envelope);
677 if (content != null) {
678 if (content.getDataMessage().isPresent()) {
679 SignalServiceDataMessage message = content.getDataMessage().get();
680 group = handleSignalServiceDataMessage(message, false, envelope.getSource(), username);
681 }
682 if (content.getSyncMessage().isPresent()) {
683 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
684 if (syncMessage.getSent().isPresent()) {
685 SignalServiceDataMessage message = syncMessage.getSent().get().getMessage();
686 group = handleSignalServiceDataMessage(message, true, envelope.getSource(), syncMessage.getSent().get().getDestination().get());
687 }
688 if (syncMessage.getRequest().isPresent()) {
689 RequestMessage rm = syncMessage.getRequest().get();
690 if (rm.isContactsRequest()) {
691 // TODO implement when we have contacts
692 }
693 if (rm.isGroupsRequest()) {
694 try {
695 sendGroups();
696 } catch (EncapsulatedExceptions encapsulatedExceptions) {
697 encapsulatedExceptions.printStackTrace();
698 } catch (UntrustedIdentityException e) {
699 e.printStackTrace();
700 }
701 }
702 }
703 if (syncMessage.getGroups().isPresent()) {
704 try {
705 DeviceGroupsInputStream s = new DeviceGroupsInputStream(retrieveAttachmentAsStream(syncMessage.getGroups().get().asPointer()));
706 DeviceGroup g;
707 while ((g = s.read()) != null) {
708 GroupInfo syncGroup;
709 try {
710 syncGroup = groupStore.getGroup(g.getId());
711 } catch (GroupNotFoundException e) {
712 syncGroup = new GroupInfo(g.getId());
713 }
714 if (g.getName().isPresent()) {
715 syncGroup.name = g.getName().get();
716 }
717 syncGroup.members.addAll(g.getMembers());
718 syncGroup.active = g.isActive();
719
720 if (g.getAvatar().isPresent()) {
721 byte[] ava = new byte[(int) g.getAvatar().get().getLength()];
722 org.whispersystems.signalservice.internal.util.Util.readFully(g.getAvatar().get().getInputStream(), ava);
723 // TODO store group avatar in /avatar/groups folder
724 }
725 groupStore.updateGroup(syncGroup);
726 }
727 } catch (Exception e) {
728 e.printStackTrace();
729 }
730 }
731 if (syncMessage.getContacts().isPresent()) {
732 try {
733 DeviceContactsInputStream s = new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage.getContacts().get().asPointer()));
734 DeviceContact c;
735 while ((c = s.read()) != null) {
736 // TODO implement when we have contact storage
737 if (c.getName().isPresent()) {
738 c.getName().get();
739 }
740 c.getNumber();
741
742 if (c.getAvatar().isPresent()) {
743 byte[] ava = new byte[(int) c.getAvatar().get().getLength()];
744 org.whispersystems.signalservice.internal.util.Util.readFully(c.getAvatar().get().getInputStream(), ava);
745 // TODO store contact avatar in /avatar/contacts folder
746 }
747 }
748 } catch (Exception e) {
749 e.printStackTrace();
750 }
751 }
752 }
753 }
754 }
755 save();
756 handler.handleMessage(envelope, content, group);
757 } catch (TimeoutException e) {
758 if (returnOnTimeout)
759 return;
760 } catch (InvalidVersionException e) {
761 System.err.println("Ignoring error: " + e.getMessage());
762 }
763 }
764 } finally {
765 if (messagePipe != null)
766 messagePipe.shutdown();
767 }
768 }
769
770 public File getAttachmentFile(long attachmentId) {
771 return new File(attachmentsPath, attachmentId + "");
772 }
773
774 private File retrieveAttachment(SignalServiceAttachmentPointer pointer) throws IOException, InvalidMessageException {
775 final SignalServiceMessageReceiver messageReceiver = new SignalServiceMessageReceiver(URL, TRUST_STORE, username, password, deviceId, signalingKey, USER_AGENT);
776
777 File tmpFile = File.createTempFile("ts_attach_" + pointer.getId(), ".tmp");
778 InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile);
779
780 new File(attachmentsPath).mkdirs();
781 File outputFile = getAttachmentFile(pointer.getId());
782 OutputStream output = null;
783 try {
784 output = new FileOutputStream(outputFile);
785 byte[] buffer = new byte[4096];
786 int read;
787
788 while ((read = input.read(buffer)) != -1) {
789 output.write(buffer, 0, read);
790 }
791 } catch (FileNotFoundException e) {
792 e.printStackTrace();
793 return null;
794 } finally {
795 if (output != null) {
796 output.close();
797 output = null;
798 }
799 if (!tmpFile.delete()) {
800 System.err.println("Failed to delete temp file: " + tmpFile);
801 }
802 }
803 if (pointer.getPreview().isPresent()) {
804 File previewFile = new File(outputFile + ".preview");
805 try {
806 output = new FileOutputStream(previewFile);
807 byte[] preview = pointer.getPreview().get();
808 output.write(preview, 0, preview.length);
809 } catch (FileNotFoundException e) {
810 e.printStackTrace();
811 return null;
812 } finally {
813 if (output != null) {
814 output.close();
815 }
816 }
817 }
818 return outputFile;
819 }
820
821 private InputStream retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer) throws IOException, InvalidMessageException {
822 final SignalServiceMessageReceiver messageReceiver = new SignalServiceMessageReceiver(URL, TRUST_STORE, username, password, deviceId, signalingKey, USER_AGENT);
823 File file = File.createTempFile("ts_tmp", "tmp");
824 file.deleteOnExit();
825
826 return messageReceiver.retrieveAttachment(pointer, file);
827 }
828
829 private String canonicalizeNumber(String number) throws InvalidNumberException {
830 String localNumber = username;
831 return PhoneNumberFormatter.formatNumber(number, localNumber);
832 }
833
834 private SignalServiceAddress getPushAddress(String number) throws InvalidNumberException {
835 String e164number = canonicalizeNumber(number);
836 return new SignalServiceAddress(e164number);
837 }
838
839 @Override
840 public boolean isRemote() {
841 return false;
842 }
843
844 private void sendGroups() throws IOException, EncapsulatedExceptions, UntrustedIdentityException {
845 File contactsFile = File.createTempFile("multidevice-contact-update", ".tmp");
846
847 try {
848 DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(new FileOutputStream(contactsFile));
849 try {
850 for (GroupInfo record : groupStore.getGroups()) {
851 out.write(new DeviceGroup(record.groupId, Optional.fromNullable(record.name),
852 new ArrayList<>(record.members), Optional.of(new SignalServiceAttachmentStream(new FileInputStream("/home/sebastian/Bilder/00026_150512_14-00-18.JPG"), "octet", new File("/home/sebastian/Bilder/00026_150512_14-00-18.JPG").length(), null)),
853 record.active));
854 }
855 } finally {
856 out.close();
857 }
858
859 if (contactsFile.exists() && contactsFile.length() > 0) {
860 FileInputStream contactsFileStream = new FileInputStream(contactsFile);
861 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
862 .withStream(contactsFileStream)
863 .withContentType("application/octet-stream")
864 .withLength(contactsFile.length())
865 .build();
866
867 sendMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
868 }
869 } finally {
870 if (contactsFile != null) contactsFile.delete();
871 }
872 }
873 }