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