]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/Main.java
Update libsignal-service
[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.newArgumentParser("signal-cli")
724 .defaultHelp(true)
725 .description("Commandline interface for Signal.")
726 .version(Manager.PROJECT_NAME + " " + Manager.PROJECT_VERSION);
727
728 parser.addArgument("-v", "--version")
729 .help("Show package version.")
730 .action(Arguments.version());
731 parser.addArgument("--config")
732 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
733
734 MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
735 mut.addArgument("-u", "--username")
736 .help("Specify your phone number, that will be used for verification.");
737 mut.addArgument("--dbus")
738 .help("Make request via user dbus.")
739 .action(Arguments.storeTrue());
740 mut.addArgument("--dbus-system")
741 .help("Make request via system dbus.")
742 .action(Arguments.storeTrue());
743
744 Subparsers subparsers = parser.addSubparsers()
745 .title("subcommands")
746 .dest("command")
747 .description("valid subcommands")
748 .help("additional help");
749
750 Subparser parserLink = subparsers.addParser("link");
751 parserLink.addArgument("-n", "--name")
752 .help("Specify a name to describe this new device.");
753
754 Subparser parserAddDevice = subparsers.addParser("addDevice");
755 parserAddDevice.addArgument("--uri")
756 .required(true)
757 .help("Specify the uri contained in the QR code shown by the new device.");
758
759 Subparser parserDevices = subparsers.addParser("listDevices");
760
761 Subparser parserRemoveDevice = subparsers.addParser("removeDevice");
762 parserRemoveDevice.addArgument("-d", "--deviceId")
763 .type(int.class)
764 .required(true)
765 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
766
767 Subparser parserRegister = subparsers.addParser("register");
768 parserRegister.addArgument("-v", "--voice")
769 .help("The verification should be done over voice, not sms.")
770 .action(Arguments.storeTrue());
771
772 Subparser parserUnregister = subparsers.addParser("unregister");
773 parserUnregister.help("Unregister the current device from the signal server.");
774
775 Subparser parserUpdateAccount = subparsers.addParser("updateAccount");
776 parserUpdateAccount.help("Update the account attributes on the signal server.");
777
778 Subparser parserVerify = subparsers.addParser("verify");
779 parserVerify.addArgument("verificationCode")
780 .help("The verification code you received via sms or voice call.");
781
782 Subparser parserSend = subparsers.addParser("send");
783 parserSend.addArgument("-g", "--group")
784 .help("Specify the recipient group ID.");
785 parserSend.addArgument("recipient")
786 .help("Specify the recipients' phone number.")
787 .nargs("*");
788 parserSend.addArgument("-m", "--message")
789 .help("Specify the message, if missing standard input is used.");
790 parserSend.addArgument("-a", "--attachment")
791 .nargs("*")
792 .help("Add file as attachment");
793 parserSend.addArgument("-e", "--endsession")
794 .help("Clear session state and send end session message.")
795 .action(Arguments.storeTrue());
796
797 Subparser parserLeaveGroup = subparsers.addParser("quitGroup");
798 parserLeaveGroup.addArgument("-g", "--group")
799 .required(true)
800 .help("Specify the recipient group ID.");
801
802 Subparser parserUpdateGroup = subparsers.addParser("updateGroup");
803 parserUpdateGroup.addArgument("-g", "--group")
804 .help("Specify the recipient group ID.");
805 parserUpdateGroup.addArgument("-n", "--name")
806 .help("Specify the new group name.");
807 parserUpdateGroup.addArgument("-a", "--avatar")
808 .help("Specify a new group avatar image file");
809 parserUpdateGroup.addArgument("-m", "--member")
810 .nargs("*")
811 .help("Specify one or more members to add to the group");
812
813 Subparser parserListGroups = subparsers.addParser("listGroups");
814 parserListGroups.addArgument("-d", "--detailed").action(Arguments.storeTrue())
815 .help("List members of each group");
816 parserListGroups.help("List group name and ids");
817
818 Subparser parserListIdentities = subparsers.addParser("listIdentities");
819 parserListIdentities.addArgument("-n", "--number")
820 .help("Only show identity keys for the given phone number.");
821
822 Subparser parserTrust = subparsers.addParser("trust");
823 parserTrust.addArgument("number")
824 .help("Specify the phone number, for which to set the trust.")
825 .required(true);
826 MutuallyExclusiveGroup mutTrust = parserTrust.addMutuallyExclusiveGroup();
827 mutTrust.addArgument("-a", "--trust-all-known-keys")
828 .help("Trust all known keys of this user, only use this for testing.")
829 .action(Arguments.storeTrue());
830 mutTrust.addArgument("-v", "--verified-fingerprint")
831 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
832
833 Subparser parserReceive = subparsers.addParser("receive");
834 parserReceive.addArgument("-t", "--timeout")
835 .type(double.class)
836 .help("Number of seconds to wait for new messages (negative values disable timeout)");
837 parserReceive.addArgument("--ignore-attachments")
838 .help("Don’t download attachments of received messages.")
839 .action(Arguments.storeTrue());
840 parserReceive.addArgument("--json")
841 .help("Output received messages in json format, one json object per line.")
842 .action(Arguments.storeTrue());
843
844 Subparser parserDaemon = subparsers.addParser("daemon");
845 parserDaemon.addArgument("--system")
846 .action(Arguments.storeTrue())
847 .help("Use DBus system bus instead of user bus.");
848 parserDaemon.addArgument("--ignore-attachments")
849 .help("Don’t download attachments of received messages.")
850 .action(Arguments.storeTrue());
851
852 try {
853 Namespace ns = parser.parseArgs(args);
854 if ("link".equals(ns.getString("command"))) {
855 if (ns.getString("username") != null) {
856 parser.printUsage();
857 System.err.println("You cannot specify a username (phone number) when linking");
858 System.exit(2);
859 }
860 } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) {
861 if (ns.getString("username") == null) {
862 parser.printUsage();
863 System.err.println("You need to specify a username (phone number)");
864 System.exit(2);
865 }
866 if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"))) {
867 System.err.println("Invalid username (phone number), make sure you include the country code.");
868 System.exit(2);
869 }
870 }
871 if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
872 System.err.println("You cannot specify recipients by phone number and groups a the same time");
873 System.exit(2);
874 }
875 return ns;
876 } catch (ArgumentParserException e) {
877 parser.handleError(e);
878 return null;
879 }
880 }
881
882 private static void handleAssertionError(AssertionError e) {
883 System.err.println("Failed to send/receive message (Assertion): " + e.getMessage());
884 e.printStackTrace();
885 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
886 }
887
888 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e) {
889 System.err.println("Failed to send (some) messages:");
890 for (NetworkFailureException n : e.getNetworkExceptions()) {
891 System.err.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage());
892 }
893 for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) {
894 System.err.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage());
895 }
896 for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) {
897 System.err.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage());
898 }
899 }
900
901 private static void handleIOException(IOException e) {
902 System.err.println("Failed to send message: " + e.getMessage());
903 }
904
905 private static String readAll(InputStream in) throws IOException {
906 StringWriter output = new StringWriter();
907 byte[] buffer = new byte[4096];
908 long count = 0;
909 int n;
910 while (-1 != (n = System.in.read(buffer))) {
911 output.write(new String(buffer, 0, n, Charset.defaultCharset()));
912 count += n;
913 }
914 return output.toString();
915 }
916
917 private static class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
918 final Manager m;
919
920 public ReceiveMessageHandler(Manager m) {
921 this.m = m;
922 }
923
924 @Override
925 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
926 SignalServiceAddress source = envelope.getSourceAddress();
927 ContactInfo sourceContact = m.getContact(source.getNumber());
928 System.out.println(String.format("Envelope from: %s (device: %d)", (sourceContact == null ? "" : "“" + sourceContact.name + "” ") + source.getNumber(), envelope.getSourceDevice()));
929 if (source.getRelay().isPresent()) {
930 System.out.println("Relayed by: " + source.getRelay().get());
931 }
932 System.out.println("Timestamp: " + formatTimestamp(envelope.getTimestamp()));
933
934 if (envelope.isReceipt()) {
935 System.out.println("Got receipt.");
936 } else if (envelope.isSignalMessage() | envelope.isPreKeySignalMessage()) {
937 if (exception != null) {
938 if (exception instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
939 org.whispersystems.libsignal.UntrustedIdentityException e = (org.whispersystems.libsignal.UntrustedIdentityException) exception;
940 System.out.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
941 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");
942 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");
943 } else {
944 System.out.println("Exception: " + exception.getMessage() + " (" + exception.getClass().getSimpleName() + ")");
945 }
946 }
947 if (content == null) {
948 System.out.println("Failed to decrypt message.");
949 } else {
950 if (content.getDataMessage().isPresent()) {
951 SignalServiceDataMessage message = content.getDataMessage().get();
952 handleSignalServiceDataMessage(message);
953 }
954 if (content.getSyncMessage().isPresent()) {
955 System.out.println("Received a sync message");
956 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
957
958 if (syncMessage.getContacts().isPresent()) {
959 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
960 if (contactsMessage.isComplete()) {
961 System.out.println("Received complete sync contacts");
962 } else {
963 System.out.println("Received sync contacts");
964 }
965 printAttachment(contactsMessage.getContactsStream());
966 }
967 if (syncMessage.getGroups().isPresent()) {
968 System.out.println("Received sync groups");
969 printAttachment(syncMessage.getGroups().get());
970 }
971 if (syncMessage.getRead().isPresent()) {
972 System.out.println("Received sync read messages list");
973 for (ReadMessage rm : syncMessage.getRead().get()) {
974 ContactInfo fromContact = m.getContact(rm.getSender());
975 System.out.println("From: " + (fromContact == null ? "" : "“" + fromContact.name + "” ") + rm.getSender() + " Message timestamp: " + formatTimestamp(rm.getTimestamp()));
976 }
977 }
978 if (syncMessage.getRequest().isPresent()) {
979 System.out.println("Received sync request");
980 if (syncMessage.getRequest().get().isContactsRequest()) {
981 System.out.println(" - contacts request");
982 }
983 if (syncMessage.getRequest().get().isGroupsRequest()) {
984 System.out.println(" - groups request");
985 }
986 }
987 if (syncMessage.getSent().isPresent()) {
988 System.out.println("Received sync sent message");
989 final SentTranscriptMessage sentTranscriptMessage = syncMessage.getSent().get();
990 String to;
991 if (sentTranscriptMessage.getDestination().isPresent()) {
992 String dest = sentTranscriptMessage.getDestination().get();
993 ContactInfo destContact = m.getContact(dest);
994 to = (destContact == null ? "" : "“" + destContact.name + "” ") + dest;
995 } else {
996 to = "Unknown";
997 }
998 System.out.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage.getTimestamp()));
999 if (sentTranscriptMessage.getExpirationStartTimestamp() > 0) {
1000 System.out.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage.getExpirationStartTimestamp()));
1001 }
1002 SignalServiceDataMessage message = sentTranscriptMessage.getMessage();
1003 handleSignalServiceDataMessage(message);
1004 }
1005 if (syncMessage.getBlockedList().isPresent()) {
1006 System.out.println("Received sync message with block list");
1007 System.out.println("Blocked numbers:");
1008 final BlockedListMessage blockedList = syncMessage.getBlockedList().get();
1009 for (String number : blockedList.getNumbers()) {
1010 System.out.println(" - " + number);
1011 }
1012 }
1013 if (syncMessage.getVerified().isPresent()) {
1014 System.out.println("Received sync message with verified identities:");
1015 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
1016 System.out.println(" - " + verifiedMessage.getDestination() + ": " + verifiedMessage.getVerified());
1017 String safetyNumber = formatSafetyNumber(m.computeSafetyNumber(verifiedMessage.getDestination(), verifiedMessage.getIdentityKey()));
1018 System.out.println(" " + safetyNumber);
1019 }
1020 }
1021 }
1022 } else {
1023 System.out.println("Unknown message received.");
1024 }
1025 System.out.println();
1026 }
1027
1028 private void handleSignalServiceDataMessage(SignalServiceDataMessage message) {
1029 System.out.println("Message timestamp: " + formatTimestamp(message.getTimestamp()));
1030
1031 if (message.getBody().isPresent()) {
1032 System.out.println("Body: " + message.getBody().get());
1033 }
1034 if (message.getGroupInfo().isPresent()) {
1035 SignalServiceGroup groupInfo = message.getGroupInfo().get();
1036 System.out.println("Group info:");
1037 System.out.println(" Id: " + Base64.encodeBytes(groupInfo.getGroupId()));
1038 if (groupInfo.getType() == SignalServiceGroup.Type.UPDATE && groupInfo.getName().isPresent()) {
1039 System.out.println(" Name: " + groupInfo.getName().get());
1040 } else {
1041 GroupInfo group = m.getGroup(groupInfo.getGroupId());
1042 if (group != null) {
1043 System.out.println(" Name: " + group.name);
1044 } else {
1045 System.out.println(" Name: <Unknown group>");
1046 }
1047 }
1048 System.out.println(" Type: " + groupInfo.getType());
1049 if (groupInfo.getMembers().isPresent()) {
1050 for (String member : groupInfo.getMembers().get()) {
1051 System.out.println(" Member: " + member);
1052 }
1053 }
1054 if (groupInfo.getAvatar().isPresent()) {
1055 System.out.println(" Avatar:");
1056 printAttachment(groupInfo.getAvatar().get());
1057 }
1058 }
1059 if (message.isEndSession()) {
1060 System.out.println("Is end session");
1061 }
1062 if (message.isExpirationUpdate()) {
1063 System.out.println("Is Expiration update: " + message.isExpirationUpdate());
1064 }
1065 if (message.getExpiresInSeconds() > 0) {
1066 System.out.println("Expires in: " + message.getExpiresInSeconds() + " seconds");
1067 }
1068
1069 if (message.getAttachments().isPresent()) {
1070 System.out.println("Attachments: ");
1071 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1072 printAttachment(attachment);
1073 }
1074 }
1075 }
1076
1077 private void printAttachment(SignalServiceAttachment attachment) {
1078 System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
1079 if (attachment.isPointer()) {
1080 final SignalServiceAttachmentPointer pointer = attachment.asPointer();
1081 System.out.println(" Id: " + pointer.getId() + " Key length: " + pointer.getKey().length + (pointer.getRelay().isPresent() ? " Relay: " + pointer.getRelay().get() : ""));
1082 System.out.println(" Filename: " + (pointer.getFileName().isPresent() ? pointer.getFileName().get() : "-"));
1083 System.out.println(" Size: " + (pointer.getSize().isPresent() ? pointer.getSize().get() + " bytes" : "<unavailable>") + (pointer.getPreview().isPresent() ? " (Preview is available: " + pointer.getPreview().get().length + " bytes)" : ""));
1084 System.out.println(" Voice note: " + (pointer.getVoiceNote() ? "yes" : "no"));
1085 File file = m.getAttachmentFile(pointer.getId());
1086 if (file.exists()) {
1087 System.out.println(" Stored plaintext in: " + file);
1088 }
1089 }
1090 }
1091 }
1092
1093 private static class DbusReceiveMessageHandler extends ReceiveMessageHandler {
1094 final DBusConnection conn;
1095
1096 public DbusReceiveMessageHandler(Manager m, DBusConnection conn) {
1097 super(m);
1098 this.conn = conn;
1099 }
1100
1101 @Override
1102 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
1103 super.handleMessage(envelope, content, exception);
1104
1105 if (envelope.isReceipt()) {
1106 try {
1107 conn.sendSignal(new Signal.ReceiptReceived(
1108 SIGNAL_OBJECTPATH,
1109 envelope.getTimestamp(),
1110 envelope.getSource()
1111 ));
1112 } catch (DBusException e) {
1113 e.printStackTrace();
1114 }
1115 } else if (content != null && content.getDataMessage().isPresent()) {
1116 SignalServiceDataMessage message = content.getDataMessage().get();
1117
1118 if (!message.isEndSession() &&
1119 !(message.getGroupInfo().isPresent() &&
1120 message.getGroupInfo().get().getType() != SignalServiceGroup.Type.DELIVER)) {
1121 List<String> attachments = new ArrayList<>();
1122 if (message.getAttachments().isPresent()) {
1123 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1124 if (attachment.isPointer()) {
1125 attachments.add(m.getAttachmentFile(attachment.asPointer().getId()).getAbsolutePath());
1126 }
1127 }
1128 }
1129
1130 try {
1131 conn.sendSignal(new Signal.MessageReceived(
1132 SIGNAL_OBJECTPATH,
1133 message.getTimestamp(),
1134 envelope.getSource(),
1135 message.getGroupInfo().isPresent() ? message.getGroupInfo().get().getGroupId() : new byte[0],
1136 message.getBody().isPresent() ? message.getBody().get() : "",
1137 attachments));
1138 } catch (DBusException e) {
1139 e.printStackTrace();
1140 }
1141 }
1142 }
1143 }
1144 }
1145
1146 private static class JsonReceiveMessageHandler implements Manager.ReceiveMessageHandler {
1147 final Manager m;
1148 final ObjectMapper jsonProcessor;
1149
1150 public JsonReceiveMessageHandler(Manager m) {
1151 this.m = m;
1152 this.jsonProcessor = new ObjectMapper();
1153 jsonProcessor.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // disable autodetect
1154 jsonProcessor.enable(SerializationFeature.WRITE_NULL_MAP_VALUES);
1155 jsonProcessor.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
1156 jsonProcessor.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
1157 }
1158
1159 @Override
1160 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
1161 ObjectNode result = jsonProcessor.createObjectNode();
1162 if (exception != null) {
1163 result.putPOJO("error", new JsonError(exception));
1164 }
1165 if (envelope != null) {
1166 result.putPOJO("envelope", new JsonMessageEnvelope(envelope, content));
1167 }
1168 try {
1169 jsonProcessor.writeValue(System.out, result);
1170 System.out.println();
1171 } catch (IOException e) {
1172 e.printStackTrace();
1173 }
1174 }
1175 }
1176
1177 private static String formatTimestamp(long timestamp) {
1178 Date date = new Date(timestamp);
1179 final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
1180 df.setTimeZone(tzUTC);
1181 return timestamp + " (" + df.format(date) + ")";
1182 }
1183 }