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