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