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