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