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