]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/Main.java
d70b00cbd6bea18b8a40ce6175639ad88b3b964b
[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.load();
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 System.out.println(String.format("%s: %s Added: %s Fingerprint: %s", keys.getKey(), id.trustLevel, id.added, Hex.toStringCondensed(id.getFingerprint())));
462 }
463 }
464 } else {
465 String number = ns.getString("number");
466 for (JsonIdentityKeyStore.Identity id : m.getIdentities(number)) {
467 System.out.println(String.format("%s: %s Added: %s Fingerprint: %s", number, id.trustLevel, id.added, Hex.toStringCondensed(id.getFingerprint())));
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 byte[] fingerprintBytes;
491 try {
492 fingerprintBytes = Hex.toByteArray(fingerprint.replaceAll(" ", "").toLowerCase(Locale.ROOT));
493 } catch (Exception e) {
494 System.err.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
495 return 1;
496 }
497 boolean res = m.trustIdentityVerified(number, fingerprintBytes);
498 if (!res) {
499 System.err.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
500 return 1;
501 }
502 } else {
503 System.err.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
504 return 1;
505 }
506 }
507 break;
508 case "daemon":
509 if (dBusConn != null) {
510 System.err.println("Stop it.");
511 return 1;
512 }
513 if (!m.isRegistered()) {
514 System.err.println("User is not registered.");
515 return 1;
516 }
517 DBusConnection conn = null;
518 try {
519 try {
520 int busType;
521 if (ns.getBoolean("system")) {
522 busType = DBusConnection.SYSTEM;
523 } else {
524 busType = DBusConnection.SESSION;
525 }
526 conn = DBusConnection.getConnection(busType);
527 conn.exportObject(SIGNAL_OBJECTPATH, m);
528 conn.requestBusName(SIGNAL_BUSNAME);
529 } catch (DBusException e) {
530 e.printStackTrace();
531 return 2;
532 }
533 try {
534 m.receiveMessages(3600, false, new DbusReceiveMessageHandler(m, conn));
535 } catch (IOException e) {
536 System.err.println("Error while receiving messages: " + e.getMessage());
537 return 3;
538 } catch (AssertionError e) {
539 handleAssertionError(e);
540 return 1;
541 }
542 } finally {
543 if (conn != null) {
544 conn.disconnect();
545 }
546 }
547
548 break;
549 }
550 return 0;
551 } finally {
552 if (dBusConn != null) {
553 dBusConn.disconnect();
554 }
555 }
556 }
557
558 private static void handleGroupNotFoundException(GroupNotFoundException e) {
559 System.err.println("Failed to send to group: " + e.getMessage());
560 System.err.println("Aborting sending.");
561 }
562
563 private static void handleNotAGroupMemberException(NotAGroupMemberException e) {
564 System.err.println("Failed to send to group: " + e.getMessage());
565 System.err.println("Update the group on another device to readd the user to this group.");
566 System.err.println("Aborting sending.");
567 }
568
569
570 private static void handleDBusExecutionException(DBusExecutionException e) {
571 System.err.println("Cannot connect to dbus: " + e.getMessage());
572 System.err.println("Aborting.");
573 }
574
575 private static byte[] decodeGroupId(String groupId) {
576 try {
577 return Base64.decode(groupId);
578 } catch (IOException e) {
579 System.err.println("Failed to decode groupId (must be base64) \"" + groupId + "\": " + e.getMessage());
580 System.err.println("Aborting sending.");
581 System.exit(1);
582 return null;
583 }
584 }
585
586 private static Namespace parseArgs(String[] args) {
587 ArgumentParser parser = ArgumentParsers.newArgumentParser("signal-cli")
588 .defaultHelp(true)
589 .description("Commandline interface for Signal.")
590 .version(Manager.PROJECT_NAME + " " + Manager.PROJECT_VERSION);
591
592 parser.addArgument("-v", "--version")
593 .help("Show package version.")
594 .action(Arguments.version());
595 parser.addArgument("--config")
596 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
597
598 MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
599 mut.addArgument("-u", "--username")
600 .help("Specify your phone number, that will be used for verification.");
601 mut.addArgument("--dbus")
602 .help("Make request via user dbus.")
603 .action(Arguments.storeTrue());
604 mut.addArgument("--dbus-system")
605 .help("Make request via system dbus.")
606 .action(Arguments.storeTrue());
607
608 Subparsers subparsers = parser.addSubparsers()
609 .title("subcommands")
610 .dest("command")
611 .description("valid subcommands")
612 .help("additional help");
613
614 Subparser parserLink = subparsers.addParser("link");
615 parserLink.addArgument("-n", "--name")
616 .help("Specify a name to describe this new device.");
617
618 Subparser parserAddDevice = subparsers.addParser("addDevice");
619 parserAddDevice.addArgument("--uri")
620 .required(true)
621 .help("Specify the uri contained in the QR code shown by the new device.");
622
623 Subparser parserDevices = subparsers.addParser("listDevices");
624
625 Subparser parserRemoveDevice = subparsers.addParser("removeDevice");
626 parserRemoveDevice.addArgument("-d", "--deviceId")
627 .type(int.class)
628 .required(true)
629 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
630
631 Subparser parserRegister = subparsers.addParser("register");
632 parserRegister.addArgument("-v", "--voice")
633 .help("The verification should be done over voice, not sms.")
634 .action(Arguments.storeTrue());
635
636 Subparser parserVerify = subparsers.addParser("verify");
637 parserVerify.addArgument("verificationCode")
638 .help("The verification code you received via sms or voice call.");
639
640 Subparser parserSend = subparsers.addParser("send");
641 parserSend.addArgument("-g", "--group")
642 .help("Specify the recipient group ID.");
643 parserSend.addArgument("recipient")
644 .help("Specify the recipients' phone number.")
645 .nargs("*");
646 parserSend.addArgument("-m", "--message")
647 .help("Specify the message, if missing standard input is used.");
648 parserSend.addArgument("-a", "--attachment")
649 .nargs("*")
650 .help("Add file as attachment");
651 parserSend.addArgument("-e", "--endsession")
652 .help("Clear session state and send end session message.")
653 .action(Arguments.storeTrue());
654
655 Subparser parserLeaveGroup = subparsers.addParser("quitGroup");
656 parserLeaveGroup.addArgument("-g", "--group")
657 .required(true)
658 .help("Specify the recipient group ID.");
659
660 Subparser parserUpdateGroup = subparsers.addParser("updateGroup");
661 parserUpdateGroup.addArgument("-g", "--group")
662 .help("Specify the recipient group ID.");
663 parserUpdateGroup.addArgument("-n", "--name")
664 .help("Specify the new group name.");
665 parserUpdateGroup.addArgument("-a", "--avatar")
666 .help("Specify a new group avatar image file");
667 parserUpdateGroup.addArgument("-m", "--member")
668 .nargs("*")
669 .help("Specify one or more members to add to the group");
670
671 Subparser parserListIdentities = subparsers.addParser("listIdentities");
672 parserListIdentities.addArgument("-n", "--number")
673 .help("Only show identity keys for the given phone number.");
674
675 Subparser parserTrust = subparsers.addParser("trust");
676 parserTrust.addArgument("number")
677 .help("Specify the phone number, for which to set the trust.")
678 .required(true);
679 MutuallyExclusiveGroup mutTrust = parserTrust.addMutuallyExclusiveGroup();
680 mutTrust.addArgument("-a", "--trust-all-known-keys")
681 .help("Trust all known keys of this user, only use this for testing.")
682 .action(Arguments.storeTrue());
683 mutTrust.addArgument("-v", "--verified-fingerprint")
684 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
685
686 Subparser parserReceive = subparsers.addParser("receive");
687 parserReceive.addArgument("-t", "--timeout")
688 .type(int.class)
689 .help("Number of seconds to wait for new messages (negative values disable timeout)");
690
691 Subparser parserDaemon = subparsers.addParser("daemon");
692 parserDaemon.addArgument("--system")
693 .action(Arguments.storeTrue())
694 .help("Use DBus system bus instead of user bus.");
695
696 try {
697 Namespace ns = parser.parseArgs(args);
698 if ("link".equals(ns.getString("command"))) {
699 if (ns.getString("username") != null) {
700 parser.printUsage();
701 System.err.println("You cannot specify a username (phone number) when linking");
702 System.exit(2);
703 }
704 } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) {
705 if (ns.getString("username") == null) {
706 parser.printUsage();
707 System.err.println("You need to specify a username (phone number)");
708 System.exit(2);
709 }
710 if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"))) {
711 System.err.println("Invalid username (phone number), make sure you include the country code.");
712 System.exit(2);
713 }
714 }
715 if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
716 System.err.println("You cannot specify recipients by phone number and groups a the same time");
717 System.exit(2);
718 }
719 return ns;
720 } catch (ArgumentParserException e) {
721 parser.handleError(e);
722 return null;
723 }
724 }
725
726 private static void handleAssertionError(AssertionError e) {
727 System.err.println("Failed to send/receive message (Assertion): " + e.getMessage());
728 e.printStackTrace();
729 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
730 }
731
732 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e) {
733 System.err.println("Failed to send (some) messages:");
734 for (NetworkFailureException n : e.getNetworkExceptions()) {
735 System.err.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage());
736 }
737 for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) {
738 System.err.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage());
739 }
740 for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) {
741 System.err.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage());
742 }
743 }
744
745 private static void handleIOException(IOException e) {
746 System.err.println("Failed to send message: " + e.getMessage());
747 }
748
749 private static String readAll(InputStream in) throws IOException {
750 StringWriter output = new StringWriter();
751 byte[] buffer = new byte[4096];
752 long count = 0;
753 int n;
754 while (-1 != (n = System.in.read(buffer))) {
755 output.write(new String(buffer, 0, n, Charset.defaultCharset()));
756 count += n;
757 }
758 return output.toString();
759 }
760
761 private static class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
762 final Manager m;
763
764 public ReceiveMessageHandler(Manager m) {
765 this.m = m;
766 }
767
768 @Override
769 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
770 SignalServiceAddress source = envelope.getSourceAddress();
771 ContactInfo sourceContact = m.getContact(source.getNumber());
772 System.out.println(String.format("Envelope from: %s (device: %d)", (sourceContact == null ? "" : "“" + sourceContact.name + "” ") + source.getNumber(), envelope.getSourceDevice()));
773 if (source.getRelay().isPresent()) {
774 System.out.println("Relayed by: " + source.getRelay().get());
775 }
776 System.out.println("Timestamp: " + formatTimestamp(envelope.getTimestamp()));
777
778 if (envelope.isReceipt()) {
779 System.out.println("Got receipt.");
780 } else if (envelope.isSignalMessage() | envelope.isPreKeySignalMessage()) {
781 if (exception != null) {
782 if (exception instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
783 org.whispersystems.libsignal.UntrustedIdentityException e = (org.whispersystems.libsignal.UntrustedIdentityException) exception;
784 System.out.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
785 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");
786 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");
787 } else {
788 System.out.println("Exception: " + exception.getMessage() + " (" + exception.getClass().getSimpleName() + ")");
789 }
790 }
791 if (content == null) {
792 System.out.println("Failed to decrypt message.");
793 } else {
794 if (content.getDataMessage().isPresent()) {
795 SignalServiceDataMessage message = content.getDataMessage().get();
796 handleSignalServiceDataMessage(message);
797 }
798 if (content.getSyncMessage().isPresent()) {
799 System.out.println("Received a sync message");
800 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
801
802 if (syncMessage.getContacts().isPresent()) {
803 System.out.println("Received sync contacts");
804 printAttachment(syncMessage.getContacts().get());
805 }
806 if (syncMessage.getGroups().isPresent()) {
807 System.out.println("Received sync groups");
808 printAttachment(syncMessage.getGroups().get());
809 }
810 if (syncMessage.getRead().isPresent()) {
811 System.out.println("Received sync read messages list");
812 for (ReadMessage rm : syncMessage.getRead().get()) {
813 ContactInfo fromContact = m.getContact(rm.getSender());
814 System.out.println("From: " + (fromContact == null ? "" : "“" + fromContact.name + "” ") + rm.getSender() + " Message timestamp: " + formatTimestamp(rm.getTimestamp()));
815 }
816 }
817 if (syncMessage.getRequest().isPresent()) {
818 System.out.println("Received sync request");
819 if (syncMessage.getRequest().get().isContactsRequest()) {
820 System.out.println(" - contacts request");
821 }
822 if (syncMessage.getRequest().get().isGroupsRequest()) {
823 System.out.println(" - groups request");
824 }
825 }
826 if (syncMessage.getSent().isPresent()) {
827 System.out.println("Received sync sent message");
828 final SentTranscriptMessage sentTranscriptMessage = syncMessage.getSent().get();
829 String to;
830 if (sentTranscriptMessage.getDestination().isPresent()) {
831 String dest = sentTranscriptMessage.getDestination().get();
832 ContactInfo destContact = m.getContact(dest);
833 to = (destContact == null ? "" : "“" + destContact.name + "” ") + dest;
834 } else {
835 to = "Unknown";
836 }
837 System.out.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage.getTimestamp()));
838 if (sentTranscriptMessage.getExpirationStartTimestamp() > 0) {
839 System.out.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage.getExpirationStartTimestamp()));
840 }
841 SignalServiceDataMessage message = sentTranscriptMessage.getMessage();
842 handleSignalServiceDataMessage(message);
843 }
844 if (syncMessage.getBlockedList().isPresent()) {
845 System.out.println("Received sync message with block list");
846 System.out.println("Blocked numbers:");
847 final BlockedListMessage blockedList = syncMessage.getBlockedList().get();
848 for (String number : blockedList.getNumbers()) {
849 System.out.println(" - " + number);
850 }
851 }
852 }
853 }
854 } else {
855 System.out.println("Unknown message received.");
856 }
857 System.out.println();
858 }
859
860 private void handleSignalServiceDataMessage(SignalServiceDataMessage message) {
861 System.out.println("Message timestamp: " + formatTimestamp(message.getTimestamp()));
862
863 if (message.getBody().isPresent()) {
864 System.out.println("Body: " + message.getBody().get());
865 }
866 if (message.getGroupInfo().isPresent()) {
867 SignalServiceGroup groupInfo = message.getGroupInfo().get();
868 System.out.println("Group info:");
869 System.out.println(" Id: " + Base64.encodeBytes(groupInfo.getGroupId()));
870 if (groupInfo.getType() == SignalServiceGroup.Type.UPDATE && groupInfo.getName().isPresent()) {
871 System.out.println(" Name: " + groupInfo.getName().get());
872 } else {
873 GroupInfo group = m.getGroup(groupInfo.getGroupId());
874 if (group != null) {
875 System.out.println(" Name: " + group.name);
876 } else {
877 System.out.println(" Name: <Unknown group>");
878 }
879 }
880 System.out.println(" Type: " + groupInfo.getType());
881 if (groupInfo.getMembers().isPresent()) {
882 for (String member : groupInfo.getMembers().get()) {
883 System.out.println(" Member: " + member);
884 }
885 }
886 if (groupInfo.getAvatar().isPresent()) {
887 System.out.println(" Avatar:");
888 printAttachment(groupInfo.getAvatar().get());
889 }
890 }
891 if (message.isEndSession()) {
892 System.out.println("Is end session");
893 }
894 if (message.isExpirationUpdate()) {
895 System.out.println("Is Expiration update: " + message.isExpirationUpdate());
896 }
897 if (message.getExpiresInSeconds() > 0) {
898 System.out.println("Expires in: " + message.getExpiresInSeconds() + " seconds");
899 }
900
901 if (message.getAttachments().isPresent()) {
902 System.out.println("Attachments: ");
903 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
904 printAttachment(attachment);
905 }
906 }
907 }
908
909 private void printAttachment(SignalServiceAttachment attachment) {
910 System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
911 if (attachment.isPointer()) {
912 final SignalServiceAttachmentPointer pointer = attachment.asPointer();
913 System.out.println(" Id: " + pointer.getId() + " Key length: " + pointer.getKey().length + (pointer.getRelay().isPresent() ? " Relay: " + pointer.getRelay().get() : ""));
914 System.out.println(" Size: " + (pointer.getSize().isPresent() ? pointer.getSize().get() + " bytes" : "<unavailable>") + (pointer.getPreview().isPresent() ? " (Preview is available: " + pointer.getPreview().get().length + " bytes)" : ""));
915 File file = m.getAttachmentFile(pointer.getId());
916 if (file.exists()) {
917 System.out.println(" Stored plaintext in: " + file);
918 }
919 }
920 }
921 }
922
923 private static class DbusReceiveMessageHandler extends ReceiveMessageHandler {
924 final DBusConnection conn;
925
926 public DbusReceiveMessageHandler(Manager m, DBusConnection conn) {
927 super(m);
928 this.conn = conn;
929 }
930
931 @Override
932 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
933 super.handleMessage(envelope, content, exception);
934
935 if (!envelope.isReceipt() && content != null && content.getDataMessage().isPresent()) {
936 SignalServiceDataMessage message = content.getDataMessage().get();
937
938 if (!message.isEndSession() &&
939 !(message.getGroupInfo().isPresent() &&
940 message.getGroupInfo().get().getType() != SignalServiceGroup.Type.DELIVER)) {
941 List<String> attachments = new ArrayList<>();
942 if (message.getAttachments().isPresent()) {
943 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
944 if (attachment.isPointer()) {
945 attachments.add(m.getAttachmentFile(attachment.asPointer().getId()).getAbsolutePath());
946 }
947 }
948 }
949
950 try {
951 conn.sendSignal(new Signal.MessageReceived(
952 SIGNAL_OBJECTPATH,
953 message.getTimestamp(),
954 envelope.getSource(),
955 message.getGroupInfo().isPresent() ? message.getGroupInfo().get().getGroupId() : new byte[0],
956 message.getBody().isPresent() ? message.getBody().get() : "",
957 attachments));
958 } catch (DBusException e) {
959 e.printStackTrace();
960 }
961 }
962 }
963 }
964
965 }
966
967 private static String formatTimestamp(long timestamp) {
968 Date date = new Date(timestamp);
969 final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
970 df.setTimeZone(tzUTC);
971 return timestamp + " (" + df.format(date) + ")";
972 }
973 }