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