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