]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/Main.java
e534f05ea7dbbd4aad6eda1ebc5d4780b9fa5aaa
[signal-cli] / src / main / java / org / asamk / signal / Main.java
1 /*
2 Copyright (C) 2015-2018 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.core.JsonGenerator;
22 import com.fasterxml.jackson.databind.DeserializationFeature;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.fasterxml.jackson.databind.SerializationFeature;
25 import com.fasterxml.jackson.databind.node.ObjectNode;
26 import net.sourceforge.argparse4j.ArgumentParsers;
27 import net.sourceforge.argparse4j.impl.Arguments;
28 import net.sourceforge.argparse4j.inf.*;
29 import org.apache.http.util.TextUtils;
30 import org.asamk.Signal;
31 import org.asamk.signal.manager.BaseConfig;
32 import org.asamk.signal.manager.Manager;
33 import org.asamk.signal.storage.contacts.ContactInfo;
34 import org.asamk.signal.storage.groups.GroupInfo;
35 import org.asamk.signal.storage.protocol.JsonIdentityKeyStore;
36 import org.asamk.signal.util.DateUtils;
37 import org.asamk.signal.util.Hex;
38 import org.asamk.signal.util.IOUtils;
39 import org.asamk.signal.util.Util;
40 import org.freedesktop.dbus.DBusConnection;
41 import org.freedesktop.dbus.DBusSigHandler;
42 import org.freedesktop.dbus.exceptions.DBusException;
43 import org.freedesktop.dbus.exceptions.DBusExecutionException;
44 import org.whispersystems.libsignal.InvalidKeyException;
45 import org.whispersystems.libsignal.util.guava.Optional;
46 import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
47 import org.whispersystems.signalservice.api.messages.*;
48 import org.whispersystems.signalservice.api.messages.calls.*;
49 import org.whispersystems.signalservice.api.messages.multidevice.*;
50 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
51 import org.whispersystems.signalservice.api.push.exceptions.EncapsulatedExceptions;
52 import org.whispersystems.signalservice.api.push.exceptions.NetworkFailureException;
53 import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
54 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
55 import org.whispersystems.signalservice.internal.push.LockedException;
56 import org.whispersystems.signalservice.internal.util.Base64;
57
58 import java.io.File;
59 import java.io.IOException;
60 import java.net.URI;
61 import java.net.URISyntaxException;
62 import java.nio.charset.Charset;
63 import java.security.Security;
64 import java.util.ArrayList;
65 import java.util.List;
66 import java.util.Locale;
67 import java.util.Map;
68 import java.util.concurrent.TimeUnit;
69 import java.util.concurrent.TimeoutException;
70
71 public class Main {
72
73 public static final String SIGNAL_BUSNAME = "org.asamk.Signal";
74 public static final String SIGNAL_OBJECTPATH = "/org/asamk/Signal";
75
76 public static void main(String[] args) {
77 // Workaround for BKS truststore
78 Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1);
79
80 Namespace ns = parseArgs(args);
81 if (ns == null) {
82 System.exit(1);
83 }
84
85 int res = handleCommands(ns);
86 System.exit(res);
87 }
88
89 private static int handleCommands(Namespace ns) {
90 final String username = ns.getString("username");
91 Manager m;
92 Signal ts;
93 DBusConnection dBusConn = null;
94 try {
95 if (ns.getBoolean("dbus") || ns.getBoolean("dbus_system")) {
96 try {
97 m = null;
98 int busType;
99 if (ns.getBoolean("dbus_system")) {
100 busType = DBusConnection.SYSTEM;
101 } else {
102 busType = DBusConnection.SESSION;
103 }
104 dBusConn = DBusConnection.getConnection(busType);
105 ts = dBusConn.getRemoteObject(
106 SIGNAL_BUSNAME, SIGNAL_OBJECTPATH,
107 Signal.class);
108 } catch (UnsatisfiedLinkError e) {
109 System.err.println("Missing native library dependency for dbus service: " + e.getMessage());
110 return 1;
111 } catch (DBusException e) {
112 e.printStackTrace();
113 if (dBusConn != null) {
114 dBusConn.disconnect();
115 }
116 return 3;
117 }
118 } else {
119 String settingsPath = ns.getString("config");
120 if (TextUtils.isEmpty(settingsPath)) {
121 settingsPath = System.getProperty("user.home") + "/.config/signal";
122 if (!new File(settingsPath).exists()) {
123 String legacySettingsPath = System.getProperty("user.home") + "/.config/textsecure";
124 if (new File(legacySettingsPath).exists()) {
125 settingsPath = legacySettingsPath;
126 }
127 }
128 }
129
130 m = new Manager(username, settingsPath);
131 ts = m;
132 if (m.userExists()) {
133 try {
134 m.init();
135 } catch (Exception e) {
136 System.err.println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage());
137 return 2;
138 }
139 }
140 }
141
142 switch (ns.getString("command")) {
143 case "register":
144 if (dBusConn != null) {
145 System.err.println("register is not yet implemented via dbus");
146 return 1;
147 }
148 if (!m.userHasKeys()) {
149 m.createNewIdentity();
150 }
151 try {
152 m.register(ns.getBoolean("voice"));
153 } catch (IOException e) {
154 System.err.println("Request verify error: " + e.getMessage());
155 return 3;
156 }
157 break;
158 case "unregister":
159 if (dBusConn != null) {
160 System.err.println("unregister is not yet implemented via dbus");
161 return 1;
162 }
163 if (!m.isRegistered()) {
164 System.err.println("User is not registered.");
165 return 1;
166 }
167 try {
168 m.unregister();
169 } catch (IOException e) {
170 System.err.println("Unregister error: " + e.getMessage());
171 return 3;
172 }
173 break;
174 case "updateAccount":
175 if (dBusConn != null) {
176 System.err.println("updateAccount is not yet implemented via dbus");
177 return 1;
178 }
179 if (!m.isRegistered()) {
180 System.err.println("User is not registered.");
181 return 1;
182 }
183 try {
184 m.updateAccountAttributes();
185 } catch (IOException e) {
186 System.err.println("UpdateAccount error: " + e.getMessage());
187 return 3;
188 }
189 break;
190 case "setPin":
191 if (dBusConn != null) {
192 System.err.println("setPin is not yet implemented via dbus");
193 return 1;
194 }
195 if (!m.isRegistered()) {
196 System.err.println("User is not registered.");
197 return 1;
198 }
199 try {
200 String registrationLockPin = ns.getString("registrationLockPin");
201 m.setRegistrationLockPin(Optional.of(registrationLockPin));
202 } catch (IOException e) {
203 System.err.println("Set pin error: " + e.getMessage());
204 return 3;
205 }
206 break;
207 case "removePin":
208 if (dBusConn != null) {
209 System.err.println("removePin is not yet implemented via dbus");
210 return 1;
211 }
212 if (!m.isRegistered()) {
213 System.err.println("User is not registered.");
214 return 1;
215 }
216 try {
217 m.setRegistrationLockPin(Optional.<String>absent());
218 } catch (IOException e) {
219 System.err.println("Remove pin error: " + e.getMessage());
220 return 3;
221 }
222 break;
223 case "verify":
224 if (dBusConn != null) {
225 System.err.println("verify is not yet implemented via dbus");
226 return 1;
227 }
228 if (!m.userHasKeys()) {
229 System.err.println("User has no keys, first call register.");
230 return 1;
231 }
232 if (m.isRegistered()) {
233 System.err.println("User registration is already verified");
234 return 1;
235 }
236 try {
237 String verificationCode = ns.getString("verificationCode");
238 String pin = ns.getString("pin");
239 m.verifyAccount(verificationCode, pin);
240 } catch (LockedException e) {
241 System.err.println("Verification failed! This number is locked with a pin. Hours remaining until reset: " + (e.getTimeRemaining() / 1000 / 60 / 60));
242 System.err.println("Use '--pin PIN_CODE' to specify the registration lock PIN");
243 return 3;
244 } catch (IOException e) {
245 System.err.println("Verify error: " + e.getMessage());
246 return 3;
247 }
248 break;
249 case "link":
250 if (dBusConn != null) {
251 System.err.println("link is not yet implemented via dbus");
252 return 1;
253 }
254
255 // When linking, username is null and we always have to create keys
256 m.createNewIdentity();
257
258 String deviceName = ns.getString("name");
259 if (deviceName == null) {
260 deviceName = "cli";
261 }
262 try {
263 System.out.println(m.getDeviceLinkUri());
264 m.finishDeviceLink(deviceName);
265 System.out.println("Associated with: " + m.getUsername());
266 } catch (TimeoutException e) {
267 System.err.println("Link request timed out, please try again.");
268 return 3;
269 } catch (IOException e) {
270 System.err.println("Link request error: " + e.getMessage());
271 return 3;
272 } catch (AssertionError e) {
273 handleAssertionError(e);
274 return 1;
275 } catch (InvalidKeyException e) {
276 e.printStackTrace();
277 return 2;
278 } catch (UserAlreadyExists e) {
279 System.err.println("The user " + e.getUsername() + " already exists\nDelete \"" + e.getFileName() + "\" before trying again.");
280 return 1;
281 }
282 break;
283 case "addDevice":
284 if (dBusConn != null) {
285 System.err.println("link is not yet implemented via dbus");
286 return 1;
287 }
288 if (!m.isRegistered()) {
289 System.err.println("User is not registered.");
290 return 1;
291 }
292 try {
293 m.addDeviceLink(new URI(ns.getString("uri")));
294 } catch (IOException e) {
295 e.printStackTrace();
296 return 3;
297 } catch (InvalidKeyException e) {
298 e.printStackTrace();
299 return 2;
300 } catch (AssertionError e) {
301 handleAssertionError(e);
302 return 1;
303 } catch (URISyntaxException e) {
304 e.printStackTrace();
305 return 2;
306 }
307 break;
308 case "listDevices":
309 if (dBusConn != null) {
310 System.err.println("listDevices is not yet implemented via dbus");
311 return 1;
312 }
313 if (!m.isRegistered()) {
314 System.err.println("User is not registered.");
315 return 1;
316 }
317 try {
318 List<DeviceInfo> devices = m.getLinkedDevices();
319 for (DeviceInfo d : devices) {
320 System.out.println("Device " + d.getId() + (d.getId() == m.getDeviceId() ? " (this device)" : "") + ":");
321 System.out.println(" Name: " + d.getName());
322 System.out.println(" Created: " + DateUtils.formatTimestamp(d.getCreated()));
323 System.out.println(" Last seen: " + DateUtils.formatTimestamp(d.getLastSeen()));
324 }
325 } catch (IOException e) {
326 e.printStackTrace();
327 return 3;
328 }
329 break;
330 case "removeDevice":
331 if (dBusConn != null) {
332 System.err.println("removeDevice is not yet implemented via dbus");
333 return 1;
334 }
335 if (!m.isRegistered()) {
336 System.err.println("User is not registered.");
337 return 1;
338 }
339 try {
340 int deviceId = ns.getInt("deviceId");
341 m.removeLinkedDevices(deviceId);
342 } catch (IOException e) {
343 e.printStackTrace();
344 return 3;
345 }
346 break;
347 case "send":
348 if (dBusConn == null && !m.isRegistered()) {
349 System.err.println("User is not registered.");
350 return 1;
351 }
352
353 if (ns.getBoolean("endsession")) {
354 if (ns.getList("recipient") == null) {
355 System.err.println("No recipients given");
356 System.err.println("Aborting sending.");
357 return 1;
358 }
359 try {
360 ts.sendEndSessionMessage(ns.<String>getList("recipient"));
361 } catch (IOException e) {
362 handleIOException(e);
363 return 3;
364 } catch (EncapsulatedExceptions e) {
365 handleEncapsulatedExceptions(e);
366 return 3;
367 } catch (AssertionError e) {
368 handleAssertionError(e);
369 return 1;
370 } catch (DBusExecutionException e) {
371 handleDBusExecutionException(e);
372 return 1;
373 }
374 } else {
375 String messageText = ns.getString("message");
376 if (messageText == null) {
377 try {
378 messageText = IOUtils.readAll(System.in, Charset.defaultCharset());
379 } catch (IOException e) {
380 System.err.println("Failed to read message from stdin: " + e.getMessage());
381 System.err.println("Aborting sending.");
382 return 1;
383 }
384 }
385
386 try {
387 List<String> attachments = ns.getList("attachment");
388 if (attachments == null) {
389 attachments = new ArrayList<>();
390 }
391 if (ns.getString("group") != null) {
392 byte[] groupId = decodeGroupId(ns.getString("group"));
393 ts.sendGroupMessage(messageText, attachments, groupId);
394 } else {
395 ts.sendMessage(messageText, attachments, ns.<String>getList("recipient"));
396 }
397 } catch (IOException e) {
398 handleIOException(e);
399 return 3;
400 } catch (EncapsulatedExceptions e) {
401 handleEncapsulatedExceptions(e);
402 return 3;
403 } catch (AssertionError e) {
404 handleAssertionError(e);
405 return 1;
406 } catch (GroupNotFoundException e) {
407 handleGroupNotFoundException(e);
408 return 1;
409 } catch (NotAGroupMemberException e) {
410 handleNotAGroupMemberException(e);
411 return 1;
412 } catch (AttachmentInvalidException e) {
413 System.err.println("Failed to add attachment: " + e.getMessage());
414 System.err.println("Aborting sending.");
415 return 1;
416 } catch (DBusExecutionException e) {
417 handleDBusExecutionException(e);
418 return 1;
419 }
420 }
421
422 break;
423 case "receive":
424 if (dBusConn != null) {
425 try {
426 dBusConn.addSigHandler(Signal.MessageReceived.class, new DBusSigHandler<Signal.MessageReceived>() {
427 @Override
428 public void handle(Signal.MessageReceived s) {
429 System.out.print(String.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
430 s.getSender(), DateUtils.formatTimestamp(s.getTimestamp()), s.getMessage()));
431 if (s.getGroupId().length > 0) {
432 System.out.println("Group info:");
433 System.out.println(" Id: " + Base64.encodeBytes(s.getGroupId()));
434 }
435 if (s.getAttachments().size() > 0) {
436 System.out.println("Attachments: ");
437 for (String attachment : s.getAttachments()) {
438 System.out.println("- Stored plaintext in: " + attachment);
439 }
440 }
441 System.out.println();
442 }
443 });
444 dBusConn.addSigHandler(Signal.ReceiptReceived.class, new DBusSigHandler<Signal.ReceiptReceived>() {
445 @Override
446 public void handle(Signal.ReceiptReceived s) {
447 System.out.print(String.format("Receipt from: %s\nTimestamp: %s\n",
448 s.getSender(), DateUtils.formatTimestamp(s.getTimestamp())));
449 }
450 });
451 } catch (UnsatisfiedLinkError e) {
452 System.err.println("Missing native library dependency for dbus service: " + e.getMessage());
453 return 1;
454 } catch (DBusException e) {
455 e.printStackTrace();
456 return 1;
457 }
458 while (true) {
459 try {
460 Thread.sleep(10000);
461 } catch (InterruptedException e) {
462 return 0;
463 }
464 }
465 }
466 if (!m.isRegistered()) {
467 System.err.println("User is not registered.");
468 return 1;
469 }
470 double timeout = 5;
471 if (ns.getDouble("timeout") != null) {
472 timeout = ns.getDouble("timeout");
473 }
474 boolean returnOnTimeout = true;
475 if (timeout < 0) {
476 returnOnTimeout = false;
477 timeout = 3600;
478 }
479 boolean ignoreAttachments = ns.getBoolean("ignore_attachments");
480 try {
481 final Manager.ReceiveMessageHandler handler = ns.getBoolean("json") ? new JsonReceiveMessageHandler(m) : new ReceiveMessageHandler(m);
482 m.receiveMessages((long) (timeout * 1000), TimeUnit.MILLISECONDS, returnOnTimeout, ignoreAttachments, handler);
483 } catch (IOException e) {
484 System.err.println("Error while receiving messages: " + e.getMessage());
485 return 3;
486 } catch (AssertionError e) {
487 handleAssertionError(e);
488 return 1;
489 }
490 break;
491 case "quitGroup":
492 if (dBusConn != null) {
493 System.err.println("quitGroup is not yet implemented via dbus");
494 return 1;
495 }
496 if (!m.isRegistered()) {
497 System.err.println("User is not registered.");
498 return 1;
499 }
500
501 try {
502 m.sendQuitGroupMessage(decodeGroupId(ns.getString("group")));
503 } catch (IOException e) {
504 handleIOException(e);
505 return 3;
506 } catch (EncapsulatedExceptions e) {
507 handleEncapsulatedExceptions(e);
508 return 3;
509 } catch (AssertionError e) {
510 handleAssertionError(e);
511 return 1;
512 } catch (GroupNotFoundException e) {
513 handleGroupNotFoundException(e);
514 return 1;
515 } catch (NotAGroupMemberException e) {
516 handleNotAGroupMemberException(e);
517 return 1;
518 }
519
520 break;
521 case "updateGroup":
522 if (dBusConn == null && !m.isRegistered()) {
523 System.err.println("User is not registered.");
524 return 1;
525 }
526
527 try {
528 byte[] groupId = null;
529 if (ns.getString("group") != null) {
530 groupId = decodeGroupId(ns.getString("group"));
531 }
532 if (groupId == null) {
533 groupId = new byte[0];
534 }
535 String groupName = ns.getString("name");
536 if (groupName == null) {
537 groupName = "";
538 }
539 List<String> groupMembers = ns.<String>getList("member");
540 if (groupMembers == null) {
541 groupMembers = new ArrayList<String>();
542 }
543 String groupAvatar = ns.getString("avatar");
544 if (groupAvatar == null) {
545 groupAvatar = "";
546 }
547 byte[] newGroupId = ts.updateGroup(groupId, groupName, groupMembers, groupAvatar);
548 if (groupId.length != newGroupId.length) {
549 System.out.println("Creating new group \"" + Base64.encodeBytes(newGroupId) + "\" …");
550 }
551 } catch (IOException e) {
552 handleIOException(e);
553 return 3;
554 } catch (AttachmentInvalidException e) {
555 System.err.println("Failed to add avatar attachment for group\": " + e.getMessage());
556 System.err.println("Aborting sending.");
557 return 1;
558 } catch (GroupNotFoundException e) {
559 handleGroupNotFoundException(e);
560 return 1;
561 } catch (NotAGroupMemberException e) {
562 handleNotAGroupMemberException(e);
563 return 1;
564 } catch (EncapsulatedExceptions e) {
565 handleEncapsulatedExceptions(e);
566 return 3;
567 }
568
569 break;
570 case "listGroups":
571 if (dBusConn != null) {
572 System.err.println("listGroups is not yet implemented via dbus");
573 return 1;
574 }
575 if (!m.isRegistered()) {
576 System.err.println("User is not registered.");
577 return 1;
578 }
579
580 List<GroupInfo> groups = m.getGroups();
581 boolean detailed = ns.getBoolean("detailed");
582
583 for (GroupInfo group : groups) {
584 printGroup(group, detailed);
585 }
586 break;
587 case "listIdentities":
588 if (dBusConn != null) {
589 System.err.println("listIdentities is not yet implemented via dbus");
590 return 1;
591 }
592 if (!m.isRegistered()) {
593 System.err.println("User is not registered.");
594 return 1;
595 }
596 if (ns.get("number") == null) {
597 for (Map.Entry<String, List<JsonIdentityKeyStore.Identity>> keys : m.getIdentities().entrySet()) {
598 for (JsonIdentityKeyStore.Identity id : keys.getValue()) {
599 printIdentityFingerprint(m, keys.getKey(), id);
600 }
601 }
602 } else {
603 String number = ns.getString("number");
604 for (JsonIdentityKeyStore.Identity id : m.getIdentities(number)) {
605 printIdentityFingerprint(m, number, id);
606 }
607 }
608 break;
609 case "trust":
610 if (dBusConn != null) {
611 System.err.println("trust is not yet implemented via dbus");
612 return 1;
613 }
614 if (!m.isRegistered()) {
615 System.err.println("User is not registered.");
616 return 1;
617 }
618 String number = ns.getString("number");
619 if (ns.getBoolean("trust_all_known_keys")) {
620 boolean res = m.trustIdentityAllKeys(number);
621 if (!res) {
622 System.err.println("Failed to set the trust for this number, make sure the number is correct.");
623 return 1;
624 }
625 } else {
626 String fingerprint = ns.getString("verified_fingerprint");
627 if (fingerprint != null) {
628 fingerprint = fingerprint.replaceAll(" ", "");
629 if (fingerprint.length() == 66) {
630 byte[] fingerprintBytes;
631 try {
632 fingerprintBytes = Hex.toByteArray(fingerprint.toLowerCase(Locale.ROOT));
633 } catch (Exception e) {
634 System.err.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
635 return 1;
636 }
637 boolean res = m.trustIdentityVerified(number, fingerprintBytes);
638 if (!res) {
639 System.err.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
640 return 1;
641 }
642 } else if (fingerprint.length() == 60) {
643 boolean res = m.trustIdentityVerifiedSafetyNumber(number, fingerprint);
644 if (!res) {
645 System.err.println("Failed to set the trust for the safety number of this phone number, make sure the phone number and the safety number are correct.");
646 return 1;
647 }
648 } else {
649 System.err.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
650 return 1;
651 }
652 } else {
653 System.err.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
654 return 1;
655 }
656 }
657 break;
658 case "daemon":
659 if (dBusConn != null) {
660 System.err.println("Stop it.");
661 return 1;
662 }
663 if (!m.isRegistered()) {
664 System.err.println("User is not registered.");
665 return 1;
666 }
667 DBusConnection conn = null;
668 try {
669 try {
670 int busType;
671 if (ns.getBoolean("system")) {
672 busType = DBusConnection.SYSTEM;
673 } else {
674 busType = DBusConnection.SESSION;
675 }
676 conn = DBusConnection.getConnection(busType);
677 conn.exportObject(SIGNAL_OBJECTPATH, m);
678 conn.requestBusName(SIGNAL_BUSNAME);
679 } catch (UnsatisfiedLinkError e) {
680 System.err.println("Missing native library dependency for dbus service: " + e.getMessage());
681 return 1;
682 } catch (DBusException e) {
683 e.printStackTrace();
684 return 2;
685 }
686 ignoreAttachments = ns.getBoolean("ignore_attachments");
687 try {
688 m.receiveMessages(1, TimeUnit.HOURS, false, ignoreAttachments, ns.getBoolean("json") ? new JsonDbusReceiveMessageHandler(m, conn) : new DbusReceiveMessageHandler(m, conn));
689 } catch (IOException e) {
690 System.err.println("Error while receiving messages: " + e.getMessage());
691 return 3;
692 } catch (AssertionError e) {
693 handleAssertionError(e);
694 return 1;
695 }
696 } finally {
697 if (conn != null) {
698 conn.disconnect();
699 }
700 }
701
702 break;
703 }
704 return 0;
705 } finally {
706 if (dBusConn != null) {
707 dBusConn.disconnect();
708 }
709 }
710 }
711
712 private static void printIdentityFingerprint(Manager m, String theirUsername, JsonIdentityKeyStore.Identity theirId) {
713 String digits = Util.formatSafetyNumber(m.computeSafetyNumber(theirUsername, theirId.getIdentityKey()));
714 System.out.println(String.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername,
715 theirId.getTrustLevel(), theirId.getDateAdded(), Hex.toStringCondensed(theirId.getFingerprint()), digits));
716 }
717
718 private static void printGroup(GroupInfo group, boolean detailed) {
719 if (detailed) {
720 System.out.println(String.format("Id: %s Name: %s Active: %s Members: %s",
721 Base64.encodeBytes(group.groupId), group.name, group.active, group.members));
722 } else {
723 System.out.println(String.format("Id: %s Name: %s Active: %s", Base64.encodeBytes(group.groupId),
724 group.name, group.active));
725 }
726 }
727
728 private static void handleGroupNotFoundException(GroupNotFoundException e) {
729 System.err.println("Failed to send to group: " + e.getMessage());
730 System.err.println("Aborting sending.");
731 }
732
733 private static void handleNotAGroupMemberException(NotAGroupMemberException e) {
734 System.err.println("Failed to send to group: " + e.getMessage());
735 System.err.println("Update the group on another device to readd the user to this group.");
736 System.err.println("Aborting sending.");
737 }
738
739
740 private static void handleDBusExecutionException(DBusExecutionException e) {
741 System.err.println("Cannot connect to dbus: " + e.getMessage());
742 System.err.println("Aborting.");
743 }
744
745 private static byte[] decodeGroupId(String groupId) {
746 try {
747 return Base64.decode(groupId);
748 } catch (IOException e) {
749 System.err.println("Failed to decode groupId (must be base64) \"" + groupId + "\": " + e.getMessage());
750 System.err.println("Aborting sending.");
751 System.exit(1);
752 return null;
753 }
754 }
755
756 private static Namespace parseArgs(String[] args) {
757 ArgumentParser parser = ArgumentParsers.newFor("signal-cli")
758 .build()
759 .defaultHelp(true)
760 .description("Commandline interface for Signal.")
761 .version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
762
763 parser.addArgument("-v", "--version")
764 .help("Show package version.")
765 .action(Arguments.version());
766 parser.addArgument("--config")
767 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
768
769 MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
770 mut.addArgument("-u", "--username")
771 .help("Specify your phone number, that will be used for verification.");
772 mut.addArgument("--dbus")
773 .help("Make request via user dbus.")
774 .action(Arguments.storeTrue());
775 mut.addArgument("--dbus-system")
776 .help("Make request via system dbus.")
777 .action(Arguments.storeTrue());
778
779 Subparsers subparsers = parser.addSubparsers()
780 .title("subcommands")
781 .dest("command")
782 .description("valid subcommands")
783 .help("additional help");
784
785 Subparser parserLink = subparsers.addParser("link");
786 parserLink.addArgument("-n", "--name")
787 .help("Specify a name to describe this new device.");
788
789 Subparser parserAddDevice = subparsers.addParser("addDevice");
790 parserAddDevice.addArgument("--uri")
791 .required(true)
792 .help("Specify the uri contained in the QR code shown by the new device.");
793
794 Subparser parserDevices = subparsers.addParser("listDevices");
795
796 Subparser parserRemoveDevice = subparsers.addParser("removeDevice");
797 parserRemoveDevice.addArgument("-d", "--deviceId")
798 .type(int.class)
799 .required(true)
800 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
801
802 Subparser parserRegister = subparsers.addParser("register");
803 parserRegister.addArgument("-v", "--voice")
804 .help("The verification should be done over voice, not sms.")
805 .action(Arguments.storeTrue());
806
807 Subparser parserUnregister = subparsers.addParser("unregister");
808 parserUnregister.help("Unregister the current device from the signal server.");
809
810 Subparser parserUpdateAccount = subparsers.addParser("updateAccount");
811 parserUpdateAccount.help("Update the account attributes on the signal server.");
812
813 Subparser parserSetPin = subparsers.addParser("setPin");
814 parserSetPin.addArgument("registrationLockPin")
815 .help("The registration lock PIN, that will be required for new registrations (resets after 7 days of inactivity)");
816
817 Subparser parserRemovePin = subparsers.addParser("removePin");
818
819 Subparser parserVerify = subparsers.addParser("verify");
820 parserVerify.addArgument("verificationCode")
821 .help("The verification code you received via sms or voice call.");
822 parserVerify.addArgument("-p", "--pin")
823 .help("The registration lock PIN, that was set by the user (Optional)");
824
825 Subparser parserSend = subparsers.addParser("send");
826 parserSend.addArgument("-g", "--group")
827 .help("Specify the recipient group ID.");
828 parserSend.addArgument("recipient")
829 .help("Specify the recipients' phone number.")
830 .nargs("*");
831 parserSend.addArgument("-m", "--message")
832 .help("Specify the message, if missing standard input is used.");
833 parserSend.addArgument("-a", "--attachment")
834 .nargs("*")
835 .help("Add file as attachment");
836 parserSend.addArgument("-e", "--endsession")
837 .help("Clear session state and send end session message.")
838 .action(Arguments.storeTrue());
839
840 Subparser parserLeaveGroup = subparsers.addParser("quitGroup");
841 parserLeaveGroup.addArgument("-g", "--group")
842 .required(true)
843 .help("Specify the recipient group ID.");
844
845 Subparser parserUpdateGroup = subparsers.addParser("updateGroup");
846 parserUpdateGroup.addArgument("-g", "--group")
847 .help("Specify the recipient group ID.");
848 parserUpdateGroup.addArgument("-n", "--name")
849 .help("Specify the new group name.");
850 parserUpdateGroup.addArgument("-a", "--avatar")
851 .help("Specify a new group avatar image file");
852 parserUpdateGroup.addArgument("-m", "--member")
853 .nargs("*")
854 .help("Specify one or more members to add to the group");
855
856 Subparser parserListGroups = subparsers.addParser("listGroups");
857 parserListGroups.addArgument("-d", "--detailed").action(Arguments.storeTrue())
858 .help("List members of each group");
859 parserListGroups.help("List group name and ids");
860
861 Subparser parserListIdentities = subparsers.addParser("listIdentities");
862 parserListIdentities.addArgument("-n", "--number")
863 .help("Only show identity keys for the given phone number.");
864
865 Subparser parserTrust = subparsers.addParser("trust");
866 parserTrust.addArgument("number")
867 .help("Specify the phone number, for which to set the trust.")
868 .required(true);
869 MutuallyExclusiveGroup mutTrust = parserTrust.addMutuallyExclusiveGroup();
870 mutTrust.addArgument("-a", "--trust-all-known-keys")
871 .help("Trust all known keys of this user, only use this for testing.")
872 .action(Arguments.storeTrue());
873 mutTrust.addArgument("-v", "--verified-fingerprint")
874 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
875
876 Subparser parserReceive = subparsers.addParser("receive");
877 parserReceive.addArgument("-t", "--timeout")
878 .type(double.class)
879 .help("Number of seconds to wait for new messages (negative values disable timeout)");
880 parserReceive.addArgument("--ignore-attachments")
881 .help("Don’t download attachments of received messages.")
882 .action(Arguments.storeTrue());
883 parserReceive.addArgument("--json")
884 .help("Output received messages in json format, one json object per line.")
885 .action(Arguments.storeTrue());
886
887 Subparser parserDaemon = subparsers.addParser("daemon");
888 parserDaemon.addArgument("--system")
889 .action(Arguments.storeTrue())
890 .help("Use DBus system bus instead of user bus.");
891 parserDaemon.addArgument("--ignore-attachments")
892 .help("Don’t download attachments of received messages.")
893 .action(Arguments.storeTrue());
894 parserDaemon.addArgument("--json")
895 .help("Output received messages in json format, one json object per line.")
896 .action(Arguments.storeTrue());
897
898 try {
899 Namespace ns = parser.parseArgs(args);
900 if ("link".equals(ns.getString("command"))) {
901 if (ns.getString("username") != null) {
902 parser.printUsage();
903 System.err.println("You cannot specify a username (phone number) when linking");
904 System.exit(2);
905 }
906 } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) {
907 if (ns.getString("username") == null) {
908 parser.printUsage();
909 System.err.println("You need to specify a username (phone number)");
910 System.exit(2);
911 }
912 if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"))) {
913 System.err.println("Invalid username (phone number), make sure you include the country code.");
914 System.exit(2);
915 }
916 }
917 if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
918 System.err.println("You cannot specify recipients by phone number and groups a the same time");
919 System.exit(2);
920 }
921 return ns;
922 } catch (ArgumentParserException e) {
923 parser.handleError(e);
924 return null;
925 }
926 }
927
928 private static void handleAssertionError(AssertionError e) {
929 System.err.println("Failed to send/receive message (Assertion): " + e.getMessage());
930 e.printStackTrace();
931 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
932 }
933
934 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e) {
935 System.err.println("Failed to send (some) messages:");
936 for (NetworkFailureException n : e.getNetworkExceptions()) {
937 System.err.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage());
938 }
939 for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) {
940 System.err.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage());
941 }
942 for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) {
943 System.err.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage());
944 }
945 }
946
947 private static void handleIOException(IOException e) {
948 System.err.println("Failed to send message: " + e.getMessage());
949 }
950
951 private static class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
952 final Manager m;
953
954 public ReceiveMessageHandler(Manager m) {
955 this.m = m;
956 }
957
958 @Override
959 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
960 SignalServiceAddress source = envelope.getSourceAddress();
961 ContactInfo sourceContact = m.getContact(source.getNumber());
962 System.out.println(String.format("Envelope from: %s (device: %d)", (sourceContact == null ? "" : "“" + sourceContact.name + "” ") + source.getNumber(), envelope.getSourceDevice()));
963 if (source.getRelay().isPresent()) {
964 System.out.println("Relayed by: " + source.getRelay().get());
965 }
966 System.out.println("Timestamp: " + DateUtils.formatTimestamp(envelope.getTimestamp()));
967 if (envelope.isUnidentifiedSender()) {
968 System.out.println("Sent by unidentified/sealed sender");
969 }
970
971 if (envelope.isReceipt()) {
972 System.out.println("Got receipt.");
973 } else if (envelope.isSignalMessage() | envelope.isPreKeySignalMessage()) {
974 if (exception != null) {
975 if (exception instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
976 org.whispersystems.libsignal.UntrustedIdentityException e = (org.whispersystems.libsignal.UntrustedIdentityException) exception;
977 System.out.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
978 System.out.println("Use 'signal-cli -u " + m.getUsername() + " listIdentities -n " + e.getName() + "', verify the key and run 'signal-cli -u " + m.getUsername() + " trust -v \"FINGER_PRINT\" " + e.getName() + "' to mark it as trusted");
979 System.out.println("If you don't care about security, use 'signal-cli -u " + m.getUsername() + " trust -a " + e.getName() + "' to trust it without verification");
980 } else {
981 System.out.println("Exception: " + exception.getMessage() + " (" + exception.getClass().getSimpleName() + ")");
982 }
983 }
984 if (content == null) {
985 System.out.println("Failed to decrypt message.");
986 } else {
987 if (content.getDataMessage().isPresent()) {
988 SignalServiceDataMessage message = content.getDataMessage().get();
989 handleSignalServiceDataMessage(message);
990 }
991 if (content.getSyncMessage().isPresent()) {
992 System.out.println("Received a sync message");
993 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
994
995 if (syncMessage.getContacts().isPresent()) {
996 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
997 if (contactsMessage.isComplete()) {
998 System.out.println("Received complete sync contacts");
999 } else {
1000 System.out.println("Received sync contacts");
1001 }
1002 printAttachment(contactsMessage.getContactsStream());
1003 }
1004 if (syncMessage.getGroups().isPresent()) {
1005 System.out.println("Received sync groups");
1006 printAttachment(syncMessage.getGroups().get());
1007 }
1008 if (syncMessage.getRead().isPresent()) {
1009 System.out.println("Received sync read messages list");
1010 for (ReadMessage rm : syncMessage.getRead().get()) {
1011 ContactInfo fromContact = m.getContact(rm.getSender());
1012 System.out.println("From: " + (fromContact == null ? "" : "“" + fromContact.name + "” ") + rm.getSender() + " Message timestamp: " + DateUtils.formatTimestamp(rm.getTimestamp()));
1013 }
1014 }
1015 if (syncMessage.getRequest().isPresent()) {
1016 System.out.println("Received sync request");
1017 if (syncMessage.getRequest().get().isContactsRequest()) {
1018 System.out.println(" - contacts request");
1019 }
1020 if (syncMessage.getRequest().get().isGroupsRequest()) {
1021 System.out.println(" - groups request");
1022 }
1023 }
1024 if (syncMessage.getSent().isPresent()) {
1025 System.out.println("Received sync sent message");
1026 final SentTranscriptMessage sentTranscriptMessage = syncMessage.getSent().get();
1027 String to;
1028 if (sentTranscriptMessage.getDestination().isPresent()) {
1029 String dest = sentTranscriptMessage.getDestination().get();
1030 ContactInfo destContact = m.getContact(dest);
1031 to = (destContact == null ? "" : "“" + destContact.name + "” ") + dest;
1032 } else {
1033 to = "Unknown";
1034 }
1035 System.out.println("To: " + to + " , Message timestamp: " + DateUtils.formatTimestamp(sentTranscriptMessage.getTimestamp()));
1036 if (sentTranscriptMessage.getExpirationStartTimestamp() > 0) {
1037 System.out.println("Expiration started at: " + DateUtils.formatTimestamp(sentTranscriptMessage.getExpirationStartTimestamp()));
1038 }
1039 SignalServiceDataMessage message = sentTranscriptMessage.getMessage();
1040 handleSignalServiceDataMessage(message);
1041 }
1042 if (syncMessage.getBlockedList().isPresent()) {
1043 System.out.println("Received sync message with block list");
1044 System.out.println("Blocked numbers:");
1045 final BlockedListMessage blockedList = syncMessage.getBlockedList().get();
1046 for (String number : blockedList.getNumbers()) {
1047 System.out.println(" - " + number);
1048 }
1049 }
1050 if (syncMessage.getVerified().isPresent()) {
1051 System.out.println("Received sync message with verified identities:");
1052 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
1053 System.out.println(" - " + verifiedMessage.getDestination() + ": " + verifiedMessage.getVerified());
1054 String safetyNumber = Util.formatSafetyNumber(m.computeSafetyNumber(verifiedMessage.getDestination(), verifiedMessage.getIdentityKey()));
1055 System.out.println(" " + safetyNumber);
1056 }
1057 if (syncMessage.getConfiguration().isPresent()) {
1058 System.out.println("Received sync message with configuration:");
1059 final ConfigurationMessage configurationMessage = syncMessage.getConfiguration().get();
1060 if (configurationMessage.getReadReceipts().isPresent()) {
1061 System.out.println(" - Read receipts: " + (configurationMessage.getReadReceipts().get() ? "enabled" : "disabled"));
1062 }
1063 }
1064 }
1065 if (content.getCallMessage().isPresent()) {
1066 System.out.println("Received a call message");
1067 SignalServiceCallMessage callMessage = content.getCallMessage().get();
1068 if (callMessage.getAnswerMessage().isPresent()) {
1069 AnswerMessage answerMessage = callMessage.getAnswerMessage().get();
1070 System.out.println("Answer message: " + answerMessage.getId() + ": " + answerMessage.getDescription());
1071 }
1072 if (callMessage.getBusyMessage().isPresent()) {
1073 BusyMessage busyMessage = callMessage.getBusyMessage().get();
1074 System.out.println("Busy message: " + busyMessage.getId());
1075 }
1076 if (callMessage.getHangupMessage().isPresent()) {
1077 HangupMessage hangupMessage = callMessage.getHangupMessage().get();
1078 System.out.println("Hangup message: " + hangupMessage.getId());
1079 }
1080 if (callMessage.getIceUpdateMessages().isPresent()) {
1081 List<IceUpdateMessage> iceUpdateMessages = callMessage.getIceUpdateMessages().get();
1082 for (IceUpdateMessage iceUpdateMessage : iceUpdateMessages) {
1083 System.out.println("Ice update message: " + iceUpdateMessage.getId() + ", sdp: " + iceUpdateMessage.getSdp());
1084 }
1085 }
1086 if (callMessage.getOfferMessage().isPresent()) {
1087 OfferMessage offerMessage = callMessage.getOfferMessage().get();
1088 System.out.println("Offer message: " + offerMessage.getId() + ": " + offerMessage.getDescription());
1089 }
1090 }
1091 if (content.getReceiptMessage().isPresent()) {
1092 System.out.println("Received a receipt message");
1093 SignalServiceReceiptMessage receiptMessage = content.getReceiptMessage().get();
1094 System.out.println(" - When: " + DateUtils.formatTimestamp(receiptMessage.getWhen()));
1095 if (receiptMessage.isDeliveryReceipt()) {
1096 System.out.println(" - Is delivery receipt");
1097 }
1098 if (receiptMessage.isReadReceipt()) {
1099 System.out.println(" - Is read receipt");
1100 }
1101 System.out.println(" - Timestamps:");
1102 for (long timestamp : receiptMessage.getTimestamps()) {
1103 System.out.println(" " + DateUtils.formatTimestamp(timestamp));
1104 }
1105 }
1106 if (content.getTypingMessage().isPresent()) {
1107 System.out.println("Received a typing message");
1108 SignalServiceTypingMessage typingMessage = content.getTypingMessage().get();
1109 System.out.println(" - Action: " + typingMessage.getAction());
1110 System.out.println(" - Timestamp: " + DateUtils.formatTimestamp(typingMessage.getTimestamp()));
1111 if (typingMessage.getGroupId().isPresent()) {
1112 GroupInfo group = m.getGroup(typingMessage.getGroupId().get());
1113 if (group != null) {
1114 System.out.println(" Name: " + group.name);
1115 } else {
1116 System.out.println(" Name: <Unknown group>");
1117 }
1118 }
1119 }
1120 }
1121 } else {
1122 System.out.println("Unknown message received.");
1123 }
1124 System.out.println();
1125 }
1126
1127 private void handleSignalServiceDataMessage(SignalServiceDataMessage message) {
1128 System.out.println("Message timestamp: " + DateUtils.formatTimestamp(message.getTimestamp()));
1129
1130 if (message.getBody().isPresent()) {
1131 System.out.println("Body: " + message.getBody().get());
1132 }
1133 if (message.getGroupInfo().isPresent()) {
1134 SignalServiceGroup groupInfo = message.getGroupInfo().get();
1135 System.out.println("Group info:");
1136 System.out.println(" Id: " + Base64.encodeBytes(groupInfo.getGroupId()));
1137 if (groupInfo.getType() == SignalServiceGroup.Type.UPDATE && groupInfo.getName().isPresent()) {
1138 System.out.println(" Name: " + groupInfo.getName().get());
1139 } else {
1140 GroupInfo group = m.getGroup(groupInfo.getGroupId());
1141 if (group != null) {
1142 System.out.println(" Name: " + group.name);
1143 } else {
1144 System.out.println(" Name: <Unknown group>");
1145 }
1146 }
1147 System.out.println(" Type: " + groupInfo.getType());
1148 if (groupInfo.getMembers().isPresent()) {
1149 for (String member : groupInfo.getMembers().get()) {
1150 System.out.println(" Member: " + member);
1151 }
1152 }
1153 if (groupInfo.getAvatar().isPresent()) {
1154 System.out.println(" Avatar:");
1155 printAttachment(groupInfo.getAvatar().get());
1156 }
1157 }
1158 if (message.isEndSession()) {
1159 System.out.println("Is end session");
1160 }
1161 if (message.isExpirationUpdate()) {
1162 System.out.println("Is Expiration update: " + message.isExpirationUpdate());
1163 }
1164 if (message.getExpiresInSeconds() > 0) {
1165 System.out.println("Expires in: " + message.getExpiresInSeconds() + " seconds");
1166 }
1167 if (message.getProfileKey().isPresent()) {
1168 System.out.println("Profile key update, key length:" + message.getProfileKey().get().length);
1169 }
1170
1171 if (message.getQuote().isPresent()) {
1172 SignalServiceDataMessage.Quote quote = message.getQuote().get();
1173 System.out.println("Quote: (" + quote.getId() + ")");
1174 System.out.println(" Author: " + quote.getAuthor().getNumber());
1175 System.out.println(" Text: " + quote.getText());
1176 if (quote.getAttachments().size() > 0) {
1177 System.out.println(" Attachments: ");
1178 for (SignalServiceDataMessage.Quote.QuotedAttachment attachment : quote.getAttachments()) {
1179 System.out.println(" Filename: " + attachment.getFileName());
1180 System.out.println(" Type: " + attachment.getContentType());
1181 System.out.println(" Thumbnail:");
1182 if (attachment.getThumbnail() != null) {
1183 printAttachment(attachment.getThumbnail());
1184 }
1185 }
1186 }
1187 }
1188
1189 if (message.getAttachments().isPresent()) {
1190 System.out.println("Attachments: ");
1191 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1192 printAttachment(attachment);
1193 }
1194 }
1195 }
1196
1197 private void printAttachment(SignalServiceAttachment attachment) {
1198 System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
1199 if (attachment.isPointer()) {
1200 final SignalServiceAttachmentPointer pointer = attachment.asPointer();
1201 System.out.println(" Id: " + pointer.getId() + " Key length: " + pointer.getKey().length);
1202 System.out.println(" Filename: " + (pointer.getFileName().isPresent() ? pointer.getFileName().get() : "-"));
1203 System.out.println(" Size: " + (pointer.getSize().isPresent() ? pointer.getSize().get() + " bytes" : "<unavailable>") + (pointer.getPreview().isPresent() ? " (Preview is available: " + pointer.getPreview().get().length + " bytes)" : ""));
1204 System.out.println(" Voice note: " + (pointer.getVoiceNote() ? "yes" : "no"));
1205 System.out.println(" Dimensions: " + pointer.getWidth() + "x" + pointer.getHeight());
1206 File file = m.getAttachmentFile(pointer.getId());
1207 if (file.exists()) {
1208 System.out.println(" Stored plaintext in: " + file);
1209 }
1210 }
1211 }
1212 }
1213
1214 private static class DbusReceiveMessageHandler extends ReceiveMessageHandler {
1215 final DBusConnection conn;
1216
1217 public DbusReceiveMessageHandler(Manager m, DBusConnection conn) {
1218 super(m);
1219 this.conn = conn;
1220 }
1221
1222 @Override
1223 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
1224 super.handleMessage(envelope, content, exception);
1225
1226 JsonDbusReceiveMessageHandler.sendReceivedMessageToDbus(envelope, content, conn, m);
1227 }
1228 }
1229
1230 private static class JsonReceiveMessageHandler implements Manager.ReceiveMessageHandler {
1231 final Manager m;
1232 final ObjectMapper jsonProcessor;
1233
1234 public JsonReceiveMessageHandler(Manager m) {
1235 this.m = m;
1236 this.jsonProcessor = new ObjectMapper();
1237 jsonProcessor.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // disable autodetect
1238 jsonProcessor.enable(SerializationFeature.WRITE_NULL_MAP_VALUES);
1239 jsonProcessor.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
1240 jsonProcessor.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
1241 }
1242
1243 @Override
1244 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
1245 ObjectNode result = jsonProcessor.createObjectNode();
1246 if (exception != null) {
1247 result.putPOJO("error", new JsonError(exception));
1248 }
1249 if (envelope != null) {
1250 result.putPOJO("envelope", new JsonMessageEnvelope(envelope, content));
1251 }
1252 try {
1253 jsonProcessor.writeValue(System.out, result);
1254 System.out.println();
1255 } catch (IOException e) {
1256 e.printStackTrace();
1257 }
1258 }
1259 }
1260
1261 private static class JsonDbusReceiveMessageHandler extends JsonReceiveMessageHandler {
1262 final DBusConnection conn;
1263
1264 public JsonDbusReceiveMessageHandler(Manager m, DBusConnection conn) {
1265 super(m);
1266 this.conn = conn;
1267 }
1268
1269 @Override
1270 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
1271 super.handleMessage(envelope, content, exception);
1272
1273 sendReceivedMessageToDbus(envelope, content, conn, m);
1274 }
1275
1276 private static void sendReceivedMessageToDbus(SignalServiceEnvelope envelope, SignalServiceContent content, DBusConnection conn, Manager m) {
1277 if (envelope.isReceipt()) {
1278 try {
1279 conn.sendSignal(new Signal.ReceiptReceived(
1280 SIGNAL_OBJECTPATH,
1281 envelope.getTimestamp(),
1282 envelope.getSource()
1283 ));
1284 } catch (DBusException e) {
1285 e.printStackTrace();
1286 }
1287 } else if (content != null && content.getDataMessage().isPresent()) {
1288 SignalServiceDataMessage message = content.getDataMessage().get();
1289
1290 if (!message.isEndSession() &&
1291 !(message.getGroupInfo().isPresent() &&
1292 message.getGroupInfo().get().getType() != SignalServiceGroup.Type.DELIVER)) {
1293 List<String> attachments = new ArrayList<>();
1294 if (message.getAttachments().isPresent()) {
1295 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1296 if (attachment.isPointer()) {
1297 attachments.add(m.getAttachmentFile(attachment.asPointer().getId()).getAbsolutePath());
1298 }
1299 }
1300 }
1301
1302 try {
1303 conn.sendSignal(new Signal.MessageReceived(
1304 SIGNAL_OBJECTPATH,
1305 message.getTimestamp(),
1306 envelope.getSource(),
1307 message.getGroupInfo().isPresent() ? message.getGroupInfo().get().getGroupId() : new byte[0],
1308 message.getBody().isPresent() ? message.getBody().get() : "",
1309 attachments));
1310 } catch (DBusException e) {
1311 e.printStackTrace();
1312 }
1313 }
1314 }
1315 }
1316 }
1317 }