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