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