]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/Main.java
40e28d25673213216af1b5bf186653c4e6f23253
[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 (NotAGroupMemberException e) {
314 handleNotAGroupMemberException(e);
315 return 1;
316 } catch (AttachmentInvalidException e) {
317 System.err.println("Failed to add attachment: " + e.getMessage());
318 System.err.println("Aborting sending.");
319 return 1;
320 } catch (DBusExecutionException e) {
321 handleDBusExecutionException(e);
322 return 1;
323 }
324 }
325
326 break;
327 case "receive":
328 if (dBusConn != null) {
329 try {
330 dBusConn.addSigHandler(Signal.MessageReceived.class, new DBusSigHandler<Signal.MessageReceived>() {
331 @Override
332 public void handle(Signal.MessageReceived s) {
333 System.out.print(String.format("Envelope from: %s\nTimestamp: %d\nBody: %s\n",
334 s.getSender(), s.getTimestamp(), s.getMessage()));
335 if (s.getGroupId().length > 0) {
336 System.out.println("Group info:");
337 System.out.println(" Id: " + Base64.encodeBytes(s.getGroupId()));
338 }
339 if (s.getAttachments().size() > 0) {
340 System.out.println("Attachments: ");
341 for (String attachment : s.getAttachments()) {
342 System.out.println("- Stored plaintext in: " + attachment);
343 }
344 }
345 System.out.println();
346 }
347 });
348 } catch (DBusException e) {
349 e.printStackTrace();
350 return 1;
351 }
352 while (true) {
353 try {
354 Thread.sleep(10000);
355 } catch (InterruptedException e) {
356 return 0;
357 }
358 }
359 }
360 if (!m.isRegistered()) {
361 System.err.println("User is not registered.");
362 return 1;
363 }
364 int timeout = 5;
365 if (ns.getInt("timeout") != null) {
366 timeout = ns.getInt("timeout");
367 }
368 boolean returnOnTimeout = true;
369 if (timeout < 0) {
370 returnOnTimeout = false;
371 timeout = 3600;
372 }
373 try {
374 m.receiveMessages(timeout, returnOnTimeout, new ReceiveMessageHandler(m));
375 } catch (IOException e) {
376 System.err.println("Error while receiving messages: " + e.getMessage());
377 return 3;
378 } catch (AssertionError e) {
379 handleAssertionError(e);
380 return 1;
381 }
382 break;
383 case "quitGroup":
384 if (dBusConn != null) {
385 System.err.println("quitGroup is not yet implemented via dbus");
386 return 1;
387 }
388 if (!m.isRegistered()) {
389 System.err.println("User is not registered.");
390 return 1;
391 }
392
393 try {
394 m.sendQuitGroupMessage(decodeGroupId(ns.getString("group")));
395 } catch (IOException e) {
396 handleIOException(e);
397 return 3;
398 } catch (EncapsulatedExceptions e) {
399 handleEncapsulatedExceptions(e);
400 return 3;
401 } catch (AssertionError e) {
402 handleAssertionError(e);
403 return 1;
404 } catch (GroupNotFoundException e) {
405 handleGroupNotFoundException(e);
406 return 1;
407 } catch (NotAGroupMemberException e) {
408 handleNotAGroupMemberException(e);
409 return 1;
410 }
411
412 break;
413 case "updateGroup":
414 if (dBusConn != null) {
415 System.err.println("updateGroup is not yet implemented via dbus");
416 return 1;
417 }
418 if (!m.isRegistered()) {
419 System.err.println("User is not registered.");
420 return 1;
421 }
422
423 try {
424 byte[] groupId = null;
425 if (ns.getString("group") != null) {
426 groupId = decodeGroupId(ns.getString("group"));
427 }
428 byte[] newGroupId = m.sendUpdateGroupMessage(groupId, ns.getString("name"), ns.<String>getList("member"), ns.getString("avatar"));
429 if (groupId == null) {
430 System.out.println("Creating new group \"" + Base64.encodeBytes(newGroupId) + "\" …");
431 }
432 } catch (IOException e) {
433 handleIOException(e);
434 return 3;
435 } catch (AttachmentInvalidException e) {
436 System.err.println("Failed to add avatar attachment for group\": " + e.getMessage());
437 System.err.println("Aborting sending.");
438 return 1;
439 } catch (GroupNotFoundException e) {
440 handleGroupNotFoundException(e);
441 return 1;
442 } catch (NotAGroupMemberException e) {
443 handleNotAGroupMemberException(e);
444 return 1;
445 } catch (EncapsulatedExceptions e) {
446 handleEncapsulatedExceptions(e);
447 return 3;
448 }
449
450 break;
451 case "listIdentities":
452 if (dBusConn != null) {
453 System.err.println("listIdentities is not yet implemented via dbus");
454 return 1;
455 }
456 if (!m.isRegistered()) {
457 System.err.println("User is not registered.");
458 return 1;
459 }
460 if (ns.get("number") == null) {
461 for (Map.Entry<String, List<JsonIdentityKeyStore.Identity>> keys : m.getIdentities().entrySet()) {
462 for (JsonIdentityKeyStore.Identity id : keys.getValue()) {
463 System.out.println(String.format("%s: %s Added: %s Fingerprint: %s", keys.getKey(), id.trustLevel, id.added, Hex.toStringCondensed(id.getFingerprint())));
464 }
465 }
466 } else {
467 String number = ns.getString("number");
468 for (JsonIdentityKeyStore.Identity id : m.getIdentities(number)) {
469 System.out.println(String.format("%s: %s Added: %s Fingerprint: %s", number, id.trustLevel, id.added, Hex.toStringCondensed(id.getFingerprint())));
470 }
471 }
472 break;
473 case "trust":
474 if (dBusConn != null) {
475 System.err.println("trust is not yet implemented via dbus");
476 return 1;
477 }
478 if (!m.isRegistered()) {
479 System.err.println("User is not registered.");
480 return 1;
481 }
482 String number = ns.getString("number");
483 if (ns.getBoolean("trust_all_known_keys")) {
484 boolean res = m.trustIdentityAllKeys(number);
485 if (!res) {
486 System.err.println("Failed to set the trust for this number, make sure the number is correct.");
487 return 1;
488 }
489 } else {
490 String fingerprint = ns.getString("verified_fingerprint");
491 if (fingerprint != null) {
492 byte[] fingerprintBytes;
493 try {
494 fingerprintBytes = Hex.toByteArray(fingerprint.replaceAll(" ", "").toLowerCase(Locale.ROOT));
495 } catch (Exception e) {
496 System.err.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
497 return 1;
498 }
499 boolean res = m.trustIdentityVerified(number, fingerprintBytes);
500 if (!res) {
501 System.err.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
502 return 1;
503 }
504 } else {
505 System.err.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
506 return 1;
507 }
508 }
509 break;
510 case "daemon":
511 if (dBusConn != null) {
512 System.err.println("Stop it.");
513 return 1;
514 }
515 if (!m.isRegistered()) {
516 System.err.println("User is not registered.");
517 return 1;
518 }
519 DBusConnection conn = null;
520 try {
521 try {
522 int busType;
523 if (ns.getBoolean("system")) {
524 busType = DBusConnection.SYSTEM;
525 } else {
526 busType = DBusConnection.SESSION;
527 }
528 conn = DBusConnection.getConnection(busType);
529 conn.exportObject(SIGNAL_OBJECTPATH, m);
530 conn.requestBusName(SIGNAL_BUSNAME);
531 } catch (DBusException e) {
532 e.printStackTrace();
533 return 2;
534 }
535 try {
536 m.receiveMessages(3600, false, new DbusReceiveMessageHandler(m, conn));
537 } catch (IOException e) {
538 System.err.println("Error while receiving messages: " + e.getMessage());
539 return 3;
540 } catch (AssertionError e) {
541 handleAssertionError(e);
542 return 1;
543 }
544 } finally {
545 if (conn != null) {
546 conn.disconnect();
547 }
548 }
549
550 break;
551 }
552 return 0;
553 } finally {
554 if (dBusConn != null) {
555 dBusConn.disconnect();
556 }
557 }
558 }
559
560 private static void handleGroupNotFoundException(GroupNotFoundException e) {
561 System.err.println("Failed to send to group: " + e.getMessage());
562 System.err.println("Aborting sending.");
563 }
564
565 private static void handleNotAGroupMemberException(NotAGroupMemberException e) {
566 System.err.println("Failed to send to group: " + e.getMessage());
567 System.err.println("Update the group on another device to readd the user to this group.");
568 System.err.println("Aborting sending.");
569 }
570
571
572 private static void handleDBusExecutionException(DBusExecutionException e) {
573 System.err.println("Cannot connect to dbus: " + e.getMessage());
574 System.err.println("Aborting.");
575 }
576
577 private static byte[] decodeGroupId(String groupId) {
578 try {
579 return Base64.decode(groupId);
580 } catch (IOException e) {
581 System.err.println("Failed to decode groupId (must be base64) \"" + groupId + "\": " + e.getMessage());
582 System.err.println("Aborting sending.");
583 System.exit(1);
584 return null;
585 }
586 }
587
588 private static Namespace parseArgs(String[] args) {
589 ArgumentParser parser = ArgumentParsers.newArgumentParser("signal-cli")
590 .defaultHelp(true)
591 .description("Commandline interface for Signal.")
592 .version(Manager.PROJECT_NAME + " " + Manager.PROJECT_VERSION);
593
594 parser.addArgument("-v", "--version")
595 .help("Show package version.")
596 .action(Arguments.version());
597 parser.addArgument("--config")
598 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
599
600 MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
601 mut.addArgument("-u", "--username")
602 .help("Specify your phone number, that will be used for verification.");
603 mut.addArgument("--dbus")
604 .help("Make request via user dbus.")
605 .action(Arguments.storeTrue());
606 mut.addArgument("--dbus-system")
607 .help("Make request via system dbus.")
608 .action(Arguments.storeTrue());
609
610 Subparsers subparsers = parser.addSubparsers()
611 .title("subcommands")
612 .dest("command")
613 .description("valid subcommands")
614 .help("additional help");
615
616 Subparser parserLink = subparsers.addParser("link");
617 parserLink.addArgument("-n", "--name")
618 .help("Specify a name to describe this new device.");
619
620 Subparser parserAddDevice = subparsers.addParser("addDevice");
621 parserAddDevice.addArgument("--uri")
622 .required(true)
623 .help("Specify the uri contained in the QR code shown by the new device.");
624
625 Subparser parserDevices = subparsers.addParser("listDevices");
626
627 Subparser parserRemoveDevice = subparsers.addParser("removeDevice");
628 parserRemoveDevice.addArgument("-d", "--deviceId")
629 .type(int.class)
630 .required(true)
631 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
632
633 Subparser parserRegister = subparsers.addParser("register");
634 parserRegister.addArgument("-v", "--voice")
635 .help("The verification should be done over voice, not sms.")
636 .action(Arguments.storeTrue());
637
638 Subparser parserVerify = subparsers.addParser("verify");
639 parserVerify.addArgument("verificationCode")
640 .help("The verification code you received via sms or voice call.");
641
642 Subparser parserSend = subparsers.addParser("send");
643 parserSend.addArgument("-g", "--group")
644 .help("Specify the recipient group ID.");
645 parserSend.addArgument("recipient")
646 .help("Specify the recipients' phone number.")
647 .nargs("*");
648 parserSend.addArgument("-m", "--message")
649 .help("Specify the message, if missing standard input is used.");
650 parserSend.addArgument("-a", "--attachment")
651 .nargs("*")
652 .help("Add file as attachment");
653 parserSend.addArgument("-e", "--endsession")
654 .help("Clear session state and send end session message.")
655 .action(Arguments.storeTrue());
656
657 Subparser parserLeaveGroup = subparsers.addParser("quitGroup");
658 parserLeaveGroup.addArgument("-g", "--group")
659 .required(true)
660 .help("Specify the recipient group ID.");
661
662 Subparser parserUpdateGroup = subparsers.addParser("updateGroup");
663 parserUpdateGroup.addArgument("-g", "--group")
664 .help("Specify the recipient group ID.");
665 parserUpdateGroup.addArgument("-n", "--name")
666 .help("Specify the new group name.");
667 parserUpdateGroup.addArgument("-a", "--avatar")
668 .help("Specify a new group avatar image file");
669 parserUpdateGroup.addArgument("-m", "--member")
670 .nargs("*")
671 .help("Specify one or more members to add to the group");
672
673 Subparser parserListIdentities = subparsers.addParser("listIdentities");
674 parserListIdentities.addArgument("-n", "--number")
675 .help("Only show identity keys for the given phone number.");
676
677 Subparser parserTrust = subparsers.addParser("trust");
678 parserTrust.addArgument("number")
679 .help("Specify the phone number, for which to set the trust.")
680 .required(true);
681 MutuallyExclusiveGroup mutTrust = parserTrust.addMutuallyExclusiveGroup();
682 mutTrust.addArgument("-a", "--trust-all-known-keys")
683 .help("Trust all known keys of this user, only use this for testing.")
684 .action(Arguments.storeTrue());
685 mutTrust.addArgument("-v", "--verified-fingerprint")
686 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
687
688 Subparser parserReceive = subparsers.addParser("receive");
689 parserReceive.addArgument("-t", "--timeout")
690 .type(int.class)
691 .help("Number of seconds to wait for new messages (negative values disable timeout)");
692
693 Subparser parserDaemon = subparsers.addParser("daemon");
694 parserDaemon.addArgument("--system")
695 .action(Arguments.storeTrue())
696 .help("Use DBus system bus instead of user bus.");
697
698 try {
699 Namespace ns = parser.parseArgs(args);
700 if ("link".equals(ns.getString("command"))) {
701 if (ns.getString("username") != null) {
702 parser.printUsage();
703 System.err.println("You cannot specify a username (phone number) when linking");
704 System.exit(2);
705 }
706 } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) {
707 if (ns.getString("username") == null) {
708 parser.printUsage();
709 System.err.println("You need to specify a username (phone number)");
710 System.exit(2);
711 }
712 if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"))) {
713 System.err.println("Invalid username (phone number), make sure you include the country code.");
714 System.exit(2);
715 }
716 }
717 if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
718 System.err.println("You cannot specify recipients by phone number and groups a the same time");
719 System.exit(2);
720 }
721 return ns;
722 } catch (ArgumentParserException e) {
723 parser.handleError(e);
724 return null;
725 }
726 }
727
728 private static void handleAssertionError(AssertionError e) {
729 System.err.println("Failed to send/receive message (Assertion): " + e.getMessage());
730 e.printStackTrace();
731 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
732 }
733
734 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e) {
735 System.err.println("Failed to send (some) messages:");
736 for (NetworkFailureException n : e.getNetworkExceptions()) {
737 System.err.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage());
738 }
739 for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) {
740 System.err.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage());
741 }
742 for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) {
743 System.err.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage());
744 }
745 }
746
747 private static void handleIOException(IOException e) {
748 System.err.println("Failed to send message: " + e.getMessage());
749 }
750
751 private static String readAll(InputStream in) throws IOException {
752 StringWriter output = new StringWriter();
753 byte[] buffer = new byte[4096];
754 long count = 0;
755 int n;
756 while (-1 != (n = System.in.read(buffer))) {
757 output.write(new String(buffer, 0, n, Charset.defaultCharset()));
758 count += n;
759 }
760 return output.toString();
761 }
762
763 private static class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
764 final Manager m;
765
766 public ReceiveMessageHandler(Manager m) {
767 this.m = m;
768 }
769
770 @Override
771 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
772 SignalServiceAddress source = envelope.getSourceAddress();
773 ContactInfo sourceContact = m.getContact(source.getNumber());
774 System.out.println(String.format("Envelope from: %s (device: %d)", (sourceContact == null ? "" : "“" + sourceContact.name + "” ") + source.getNumber(), envelope.getSourceDevice()));
775 if (source.getRelay().isPresent()) {
776 System.out.println("Relayed by: " + source.getRelay().get());
777 }
778 System.out.println("Timestamp: " + envelope.getTimestamp());
779
780 if (envelope.isReceipt()) {
781 System.out.println("Got receipt.");
782 } else if (envelope.isSignalMessage() | envelope.isPreKeySignalMessage()) {
783 if (exception != null) {
784 if (exception instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
785 org.whispersystems.libsignal.UntrustedIdentityException e = (org.whispersystems.libsignal.UntrustedIdentityException) exception;
786 System.out.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
787 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");
788 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");
789 } else {
790 System.out.println("Exception: " + exception.getMessage() + " (" + exception.getClass().getSimpleName() + ")");
791 }
792 }
793 if (content == null) {
794 System.out.println("Failed to decrypt message.");
795 } else {
796 if (content.getDataMessage().isPresent()) {
797 SignalServiceDataMessage message = content.getDataMessage().get();
798 handleSignalServiceDataMessage(message);
799 }
800 if (content.getSyncMessage().isPresent()) {
801 System.out.println("Received a sync message");
802 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
803
804 if (syncMessage.getContacts().isPresent()) {
805 System.out.println("Received sync contacts");
806 printAttachment(syncMessage.getContacts().get());
807 }
808 if (syncMessage.getGroups().isPresent()) {
809 System.out.println("Received sync groups");
810 printAttachment(syncMessage.getGroups().get());
811 }
812 if (syncMessage.getRead().isPresent()) {
813 System.out.println("Received sync read messages list");
814 for (ReadMessage rm : syncMessage.getRead().get()) {
815 ContactInfo fromContact = m.getContact(rm.getSender());
816 System.out.println("From: " + (fromContact == null ? "" : "“" + fromContact.name + "” ") + rm.getSender() + " Message timestamp: " + rm.getTimestamp());
817 }
818 }
819 if (syncMessage.getRequest().isPresent()) {
820 System.out.println("Received sync request");
821 if (syncMessage.getRequest().get().isContactsRequest()) {
822 System.out.println(" - contacts request");
823 }
824 if (syncMessage.getRequest().get().isGroupsRequest()) {
825 System.out.println(" - groups request");
826 }
827 }
828 if (syncMessage.getSent().isPresent()) {
829 System.out.println("Received sync sent message");
830 final SentTranscriptMessage sentTranscriptMessage = syncMessage.getSent().get();
831 String to;
832 if (sentTranscriptMessage.getDestination().isPresent()) {
833 String dest = sentTranscriptMessage.getDestination().get();
834 ContactInfo destContact = m.getContact(dest);
835 to = (destContact == null ? "" : "“" + destContact.name + "” ") + dest;
836 } else {
837 to = "Unknown";
838 }
839 System.out.println("To: " + to + " , Message timestamp: " + sentTranscriptMessage.getTimestamp());
840 SignalServiceDataMessage message = sentTranscriptMessage.getMessage();
841 handleSignalServiceDataMessage(message);
842 }
843 }
844 }
845 } else {
846 System.out.println("Unknown message received.");
847 }
848 System.out.println();
849 }
850
851 private void handleSignalServiceDataMessage(SignalServiceDataMessage message) {
852 System.out.println("Message timestamp: " + message.getTimestamp());
853
854 if (message.getBody().isPresent()) {
855 System.out.println("Body: " + message.getBody().get());
856 }
857 if (message.getGroupInfo().isPresent()) {
858 SignalServiceGroup groupInfo = message.getGroupInfo().get();
859 System.out.println("Group info:");
860 System.out.println(" Id: " + Base64.encodeBytes(groupInfo.getGroupId()));
861 if (groupInfo.getType() == SignalServiceGroup.Type.UPDATE && groupInfo.getName().isPresent()) {
862 System.out.println(" Name: " + groupInfo.getName().get());
863 } else {
864 GroupInfo group = m.getGroup(groupInfo.getGroupId());
865 if (group != null) {
866 System.out.println(" Name: " + group.name);
867 } else {
868 System.out.println(" Name: <Unknown group>");
869 }
870 }
871 System.out.println(" Type: " + groupInfo.getType());
872 if (groupInfo.getMembers().isPresent()) {
873 for (String member : groupInfo.getMembers().get()) {
874 System.out.println(" Member: " + member);
875 }
876 }
877 if (groupInfo.getAvatar().isPresent()) {
878 System.out.println(" Avatar:");
879 printAttachment(groupInfo.getAvatar().get());
880 }
881 }
882 if (message.isEndSession()) {
883 System.out.println("Is end session");
884 }
885
886 if (message.getAttachments().isPresent()) {
887 System.out.println("Attachments: ");
888 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
889 printAttachment(attachment);
890 }
891 }
892 }
893
894 private void printAttachment(SignalServiceAttachment attachment) {
895 System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
896 if (attachment.isPointer()) {
897 final SignalServiceAttachmentPointer pointer = attachment.asPointer();
898 System.out.println(" Id: " + pointer.getId() + " Key length: " + pointer.getKey().length + (pointer.getRelay().isPresent() ? " Relay: " + pointer.getRelay().get() : ""));
899 System.out.println(" Size: " + (pointer.getSize().isPresent() ? pointer.getSize().get() + " bytes" : "<unavailable>") + (pointer.getPreview().isPresent() ? " (Preview is available: " + pointer.getPreview().get().length + " bytes)" : ""));
900 File file = m.getAttachmentFile(pointer.getId());
901 if (file.exists()) {
902 System.out.println(" Stored plaintext in: " + file);
903 }
904 }
905 }
906 }
907
908 private static class DbusReceiveMessageHandler extends ReceiveMessageHandler {
909 final DBusConnection conn;
910
911 public DbusReceiveMessageHandler(Manager m, DBusConnection conn) {
912 super(m);
913 this.conn = conn;
914 }
915
916 @Override
917 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
918 super.handleMessage(envelope, content, exception);
919
920 if (!envelope.isReceipt() && content != null && content.getDataMessage().isPresent()) {
921 SignalServiceDataMessage message = content.getDataMessage().get();
922
923 if (!message.isEndSession() &&
924 !(message.getGroupInfo().isPresent() &&
925 message.getGroupInfo().get().getType() != SignalServiceGroup.Type.DELIVER)) {
926 List<String> attachments = new ArrayList<>();
927 if (message.getAttachments().isPresent()) {
928 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
929 if (attachment.isPointer()) {
930 attachments.add(m.getAttachmentFile(attachment.asPointer().getId()).getAbsolutePath());
931 }
932 }
933 }
934
935 try {
936 conn.sendSignal(new Signal.MessageReceived(
937 SIGNAL_OBJECTPATH,
938 message.getTimestamp(),
939 envelope.getSource(),
940 message.getGroupInfo().isPresent() ? message.getGroupInfo().get().getGroupId() : new byte[0],
941 message.getBody().isPresent() ? message.getBody().get() : "",
942 attachments));
943 } catch (DBusException e) {
944 e.printStackTrace();
945 }
946 }
947 }
948 }
949
950 }
951 }