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