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