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