2 * Copyright (C) 2015 AsamK
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.
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.
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/>.
17 package org
.asamk
.signal
;
19 import net
.sourceforge
.argparse4j
.ArgumentParsers
;
20 import net
.sourceforge
.argparse4j
.impl
.Arguments
;
21 import net
.sourceforge
.argparse4j
.inf
.ArgumentParser
;
22 import net
.sourceforge
.argparse4j
.inf
.ArgumentParserException
;
23 import net
.sourceforge
.argparse4j
.inf
.MutuallyExclusiveGroup
;
24 import net
.sourceforge
.argparse4j
.inf
.Namespace
;
25 import net
.sourceforge
.argparse4j
.inf
.Subparser
;
26 import net
.sourceforge
.argparse4j
.inf
.Subparsers
;
28 import org
.apache
.http
.util
.TextUtils
;
29 import org
.asamk
.Signal
;
30 import org
.asamk
.signal
.storage
.contacts
.ContactInfo
;
31 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
32 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
33 import org
.asamk
.signal
.util
.Base64
;
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
.SignalServiceAttachment
;
42 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
43 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
44 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
45 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
46 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
47 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
48 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
49 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ReadMessage
;
50 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
51 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
52 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
53 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
54 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
55 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
56 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
59 import java
.io
.IOException
;
60 import java
.io
.InputStream
;
61 import java
.io
.StringWriter
;
63 import java
.net
.URISyntaxException
;
64 import java
.nio
.charset
.Charset
;
65 import java
.security
.Security
;
66 import java
.text
.DateFormat
;
67 import java
.text
.SimpleDateFormat
;
68 import java
.util
.ArrayList
;
69 import java
.util
.Date
;
70 import java
.util
.List
;
71 import java
.util
.Locale
;
73 import java
.util
.TimeZone
;
74 import java
.util
.concurrent
.TimeUnit
;
75 import java
.util
.concurrent
.TimeoutException
;
79 public static final String SIGNAL_BUSNAME
= "org.asamk.Signal";
80 public static final String SIGNAL_OBJECTPATH
= "/org/asamk/Signal";
82 private static final TimeZone tzUTC
= TimeZone
.getTimeZone("UTC");
84 public static void main(String
[] args
) {
85 // Workaround for BKS truststore
86 Security
.insertProviderAt(new org
.bouncycastle
.jce
.provider
.BouncyCastleProvider(), 1);
88 Namespace ns
= parseArgs(args
);
93 int res
= handleCommands(ns
);
97 private static int handleCommands(Namespace ns
) {
98 final String username
= ns
.getString("username");
101 DBusConnection dBusConn
= null;
103 if (ns
.getBoolean("dbus") || ns
.getBoolean("dbus_system")) {
107 if (ns
.getBoolean("dbus_system")) {
108 busType
= DBusConnection
.SYSTEM
;
110 busType
= DBusConnection
.SESSION
;
112 dBusConn
= DBusConnection
.getConnection(busType
);
113 ts
= (Signal
) dBusConn
.getRemoteObject(
114 SIGNAL_BUSNAME
, SIGNAL_OBJECTPATH
,
116 } catch (UnsatisfiedLinkError e
) {
117 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
119 } catch (DBusException e
) {
121 if (dBusConn
!= null) {
122 dBusConn
.disconnect();
127 String settingsPath
= ns
.getString("config");
128 if (TextUtils
.isEmpty(settingsPath
)) {
129 settingsPath
= System
.getProperty("user.home") + "/.config/signal";
130 if (!new File(settingsPath
).exists()) {
131 String legacySettingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
132 if (new File(legacySettingsPath
).exists()) {
133 settingsPath
= legacySettingsPath
;
138 m
= new Manager(username
, settingsPath
);
140 if (m
.userExists()) {
143 } catch (Exception e
) {
144 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
150 switch (ns
.getString("command")) {
152 if (dBusConn
!= null) {
153 System
.err
.println("register is not yet implemented via dbus");
156 if (!m
.userHasKeys()) {
157 m
.createNewIdentity();
160 m
.register(ns
.getBoolean("voice"));
161 } catch (IOException e
) {
162 System
.err
.println("Request verify error: " + e
.getMessage());
167 if (dBusConn
!= null) {
168 System
.err
.println("unregister is not yet implemented via dbus");
171 if (!m
.isRegistered()) {
172 System
.err
.println("User is not registered.");
177 } catch (IOException e
) {
178 System
.err
.println("Unregister error: " + e
.getMessage());
182 case "updateAccount":
183 if (dBusConn
!= null) {
184 System
.err
.println("updateAccount is not yet implemented via dbus");
187 if (!m
.isRegistered()) {
188 System
.err
.println("User is not registered.");
192 m
.updateAccountAttributes();
193 } catch (IOException e
) {
194 System
.err
.println("UpdateAccount error: " + e
.getMessage());
199 if (dBusConn
!= null) {
200 System
.err
.println("verify is not yet implemented via dbus");
203 if (!m
.userHasKeys()) {
204 System
.err
.println("User has no keys, first call register.");
207 if (m
.isRegistered()) {
208 System
.err
.println("User registration is already verified");
212 m
.verifyAccount(ns
.getString("verificationCode"));
213 } catch (IOException e
) {
214 System
.err
.println("Verify error: " + e
.getMessage());
219 if (dBusConn
!= null) {
220 System
.err
.println("link is not yet implemented via dbus");
224 // When linking, username is null and we always have to create keys
225 m
.createNewIdentity();
227 String deviceName
= ns
.getString("name");
228 if (deviceName
== null) {
232 System
.out
.println(m
.getDeviceLinkUri());
233 m
.finishDeviceLink(deviceName
);
234 System
.out
.println("Associated with: " + m
.getUsername());
235 } catch (TimeoutException e
) {
236 System
.err
.println("Link request timed out, please try again.");
238 } catch (IOException e
) {
239 System
.err
.println("Link request error: " + e
.getMessage());
241 } catch (AssertionError e
) {
242 handleAssertionError(e
);
244 } catch (InvalidKeyException e
) {
247 } catch (UserAlreadyExists e
) {
248 System
.err
.println("The user " + e
.getUsername() + " already exists\nDelete \"" + e
.getFileName() + "\" before trying again.");
253 if (dBusConn
!= null) {
254 System
.err
.println("link is not yet implemented via dbus");
257 if (!m
.isRegistered()) {
258 System
.err
.println("User is not registered.");
262 m
.addDeviceLink(new URI(ns
.getString("uri")));
263 } catch (IOException e
) {
266 } catch (InvalidKeyException e
) {
269 } catch (AssertionError e
) {
270 handleAssertionError(e
);
272 } catch (URISyntaxException e
) {
278 if (dBusConn
!= null) {
279 System
.err
.println("listDevices is not yet implemented via dbus");
282 if (!m
.isRegistered()) {
283 System
.err
.println("User is not registered.");
287 List
<DeviceInfo
> devices
= m
.getLinkedDevices();
288 for (DeviceInfo d
: devices
) {
289 System
.out
.println("Device " + d
.getId() + (d
.getId() == m
.getDeviceId() ?
" (this device)" : "") + ":");
290 System
.out
.println(" Name: " + d
.getName());
291 System
.out
.println(" Created: " + formatTimestamp(d
.getCreated()));
292 System
.out
.println(" Last seen: " + formatTimestamp(d
.getLastSeen()));
294 } catch (IOException e
) {
300 if (dBusConn
!= null) {
301 System
.err
.println("removeDevice is not yet implemented via dbus");
304 if (!m
.isRegistered()) {
305 System
.err
.println("User is not registered.");
309 int deviceId
= ns
.getInt("deviceId");
310 m
.removeLinkedDevices(deviceId
);
311 } catch (IOException e
) {
317 if (dBusConn
== null && !m
.isRegistered()) {
318 System
.err
.println("User is not registered.");
322 if (ns
.getBoolean("endsession")) {
323 if (ns
.getList("recipient") == null) {
324 System
.err
.println("No recipients given");
325 System
.err
.println("Aborting sending.");
329 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
330 } catch (IOException e
) {
331 handleIOException(e
);
333 } catch (EncapsulatedExceptions e
) {
334 handleEncapsulatedExceptions(e
);
336 } catch (AssertionError e
) {
337 handleAssertionError(e
);
339 } catch (DBusExecutionException e
) {
340 handleDBusExecutionException(e
);
344 String messageText
= ns
.getString("message");
345 if (messageText
== null) {
347 messageText
= readAll(System
.in);
348 } catch (IOException e
) {
349 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
350 System
.err
.println("Aborting sending.");
356 List
<String
> attachments
= ns
.getList("attachment");
357 if (attachments
== null) {
358 attachments
= new ArrayList
<>();
360 if (ns
.getString("group") != null) {
361 byte[] groupId
= decodeGroupId(ns
.getString("group"));
362 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
364 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
366 } catch (IOException e
) {
367 handleIOException(e
);
369 } catch (EncapsulatedExceptions e
) {
370 handleEncapsulatedExceptions(e
);
372 } catch (AssertionError e
) {
373 handleAssertionError(e
);
375 } catch (GroupNotFoundException e
) {
376 handleGroupNotFoundException(e
);
378 } catch (NotAGroupMemberException e
) {
379 handleNotAGroupMemberException(e
);
381 } catch (AttachmentInvalidException e
) {
382 System
.err
.println("Failed to add attachment: " + e
.getMessage());
383 System
.err
.println("Aborting sending.");
385 } catch (DBusExecutionException e
) {
386 handleDBusExecutionException(e
);
393 if (dBusConn
!= null) {
395 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
397 public void handle(Signal
.MessageReceived s
) {
398 System
.out
.print(String
.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
399 s
.getSender(), formatTimestamp(s
.getTimestamp()), s
.getMessage()));
400 if (s
.getGroupId().length
> 0) {
401 System
.out
.println("Group info:");
402 System
.out
.println(" Id: " + Base64
.encodeBytes(s
.getGroupId()));
404 if (s
.getAttachments().size() > 0) {
405 System
.out
.println("Attachments: ");
406 for (String attachment
: s
.getAttachments()) {
407 System
.out
.println("- Stored plaintext in: " + attachment
);
410 System
.out
.println();
413 } catch (UnsatisfiedLinkError e
) {
414 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
416 } catch (DBusException e
) {
423 } catch (InterruptedException e
) {
428 if (!m
.isRegistered()) {
429 System
.err
.println("User is not registered.");
433 if (ns
.getDouble("timeout") != null) {
434 timeout
= ns
.getDouble("timeout");
436 boolean returnOnTimeout
= true;
438 returnOnTimeout
= false;
441 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
443 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, ignoreAttachments
, new ReceiveMessageHandler(m
));
444 } catch (IOException e
) {
445 System
.err
.println("Error while receiving messages: " + e
.getMessage());
447 } catch (AssertionError e
) {
448 handleAssertionError(e
);
453 if (dBusConn
!= null) {
454 System
.err
.println("quitGroup is not yet implemented via dbus");
457 if (!m
.isRegistered()) {
458 System
.err
.println("User is not registered.");
463 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
464 } catch (IOException e
) {
465 handleIOException(e
);
467 } catch (EncapsulatedExceptions e
) {
468 handleEncapsulatedExceptions(e
);
470 } catch (AssertionError e
) {
471 handleAssertionError(e
);
473 } catch (GroupNotFoundException e
) {
474 handleGroupNotFoundException(e
);
476 } catch (NotAGroupMemberException e
) {
477 handleNotAGroupMemberException(e
);
483 if (dBusConn
!= null) {
484 System
.err
.println("updateGroup is not yet implemented via dbus");
487 if (!m
.isRegistered()) {
488 System
.err
.println("User is not registered.");
493 byte[] groupId
= null;
494 if (ns
.getString("group") != null) {
495 groupId
= decodeGroupId(ns
.getString("group"));
497 byte[] newGroupId
= m
.sendUpdateGroupMessage(groupId
, ns
.getString("name"), ns
.<String
>getList("member"), ns
.getString("avatar"));
498 if (groupId
== null) {
499 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
501 } catch (IOException e
) {
502 handleIOException(e
);
504 } catch (AttachmentInvalidException e
) {
505 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
506 System
.err
.println("Aborting sending.");
508 } catch (GroupNotFoundException e
) {
509 handleGroupNotFoundException(e
);
511 } catch (NotAGroupMemberException e
) {
512 handleNotAGroupMemberException(e
);
514 } catch (EncapsulatedExceptions e
) {
515 handleEncapsulatedExceptions(e
);
521 if (dBusConn
!= null) {
522 System
.err
.println("listGroups is not yet implemented via dbus");
525 if (!m
.isRegistered()) {
526 System
.err
.println("User is not registered.");
530 List
<GroupInfo
> groups
= m
.getGroups();
531 boolean detailed
= ns
.getBoolean("detailed");
533 for (GroupInfo group
: groups
) {
534 printGroup(group
, detailed
);
537 case "listIdentities":
538 if (dBusConn
!= null) {
539 System
.err
.println("listIdentities is not yet implemented via dbus");
542 if (!m
.isRegistered()) {
543 System
.err
.println("User is not registered.");
546 if (ns
.get("number") == null) {
547 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
548 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
549 printIdentityFingerprint(m
, keys
.getKey(), id
);
553 String number
= ns
.getString("number");
554 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
555 printIdentityFingerprint(m
, number
, id
);
560 if (dBusConn
!= null) {
561 System
.err
.println("trust is not yet implemented via dbus");
564 if (!m
.isRegistered()) {
565 System
.err
.println("User is not registered.");
568 String number
= ns
.getString("number");
569 if (ns
.getBoolean("trust_all_known_keys")) {
570 boolean res
= m
.trustIdentityAllKeys(number
);
572 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
576 String fingerprint
= ns
.getString("verified_fingerprint");
577 if (fingerprint
!= null) {
578 fingerprint
= fingerprint
.replaceAll(" ", "");
579 if (fingerprint
.length() == 66) {
580 byte[] fingerprintBytes
;
582 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
583 } catch (Exception e
) {
584 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
587 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
589 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
592 } else if (fingerprint
.length() == 60) {
593 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
595 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.");
599 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
603 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
609 if (dBusConn
!= null) {
610 System
.err
.println("Stop it.");
613 if (!m
.isRegistered()) {
614 System
.err
.println("User is not registered.");
617 DBusConnection conn
= null;
621 if (ns
.getBoolean("system")) {
622 busType
= DBusConnection
.SYSTEM
;
624 busType
= DBusConnection
.SESSION
;
626 conn
= DBusConnection
.getConnection(busType
);
627 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
628 conn
.requestBusName(SIGNAL_BUSNAME
);
629 } catch (UnsatisfiedLinkError e
) {
630 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
632 } catch (DBusException e
) {
636 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
638 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, new DbusReceiveMessageHandler(m
, conn
));
639 } catch (IOException e
) {
640 System
.err
.println("Error while receiving messages: " + e
.getMessage());
642 } catch (AssertionError e
) {
643 handleAssertionError(e
);
656 if (dBusConn
!= null) {
657 dBusConn
.disconnect();
662 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
663 String digits
= formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.getIdentityKey()));
664 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
665 theirId
.getTrustLevel(), theirId
.getDateAdded(), Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
668 private static void printGroup(GroupInfo group
, boolean detailed
) {
670 System
.out
.println(String
.format("Id: %s Name: %s Active: %s Members: %s",
671 Base64
.encodeBytes(group
.groupId
), group
.name
, group
.active
, group
.members
));
673 System
.out
.println(String
.format("Id: %s Name: %s Active: %s", Base64
.encodeBytes(group
.groupId
),
674 group
.name
, group
.active
));
678 private static String
formatSafetyNumber(String digits
) {
679 final int partCount
= 12;
680 int partSize
= digits
.length() / partCount
;
681 StringBuilder f
= new StringBuilder(digits
.length() + partCount
);
682 for (int i
= 0; i
< partCount
; i
++) {
683 f
.append(digits
.substring(i
* partSize
, (i
* partSize
) + partSize
)).append(" ");
688 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
689 System
.err
.println("Failed to send to group: " + e
.getMessage());
690 System
.err
.println("Aborting sending.");
693 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
694 System
.err
.println("Failed to send to group: " + e
.getMessage());
695 System
.err
.println("Update the group on another device to readd the user to this group.");
696 System
.err
.println("Aborting sending.");
700 private static void handleDBusExecutionException(DBusExecutionException e
) {
701 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
702 System
.err
.println("Aborting.");
705 private static byte[] decodeGroupId(String groupId
) {
707 return Base64
.decode(groupId
);
708 } catch (IOException e
) {
709 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
710 System
.err
.println("Aborting sending.");
716 private static Namespace
parseArgs(String
[] args
) {
717 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("signal-cli")
719 .description("Commandline interface for Signal.")
720 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
722 parser
.addArgument("-v", "--version")
723 .help("Show package version.")
724 .action(Arguments
.version());
725 parser
.addArgument("--config")
726 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
728 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
729 mut
.addArgument("-u", "--username")
730 .help("Specify your phone number, that will be used for verification.");
731 mut
.addArgument("--dbus")
732 .help("Make request via user dbus.")
733 .action(Arguments
.storeTrue());
734 mut
.addArgument("--dbus-system")
735 .help("Make request via system dbus.")
736 .action(Arguments
.storeTrue());
738 Subparsers subparsers
= parser
.addSubparsers()
739 .title("subcommands")
741 .description("valid subcommands")
742 .help("additional help");
744 Subparser parserLink
= subparsers
.addParser("link");
745 parserLink
.addArgument("-n", "--name")
746 .help("Specify a name to describe this new device.");
748 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
749 parserAddDevice
.addArgument("--uri")
751 .help("Specify the uri contained in the QR code shown by the new device.");
753 Subparser parserDevices
= subparsers
.addParser("listDevices");
755 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
756 parserRemoveDevice
.addArgument("-d", "--deviceId")
759 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
761 Subparser parserRegister
= subparsers
.addParser("register");
762 parserRegister
.addArgument("-v", "--voice")
763 .help("The verification should be done over voice, not sms.")
764 .action(Arguments
.storeTrue());
766 Subparser parserUnregister
= subparsers
.addParser("unregister");
767 parserUnregister
.help("Unregister the current device from the signal server.");
769 Subparser parserUpdateAccount
= subparsers
.addParser("updateAccount");
770 parserUpdateAccount
.help("Update the account attributes on the signal server.");
772 Subparser parserVerify
= subparsers
.addParser("verify");
773 parserVerify
.addArgument("verificationCode")
774 .help("The verification code you received via sms or voice call.");
776 Subparser parserSend
= subparsers
.addParser("send");
777 parserSend
.addArgument("-g", "--group")
778 .help("Specify the recipient group ID.");
779 parserSend
.addArgument("recipient")
780 .help("Specify the recipients' phone number.")
782 parserSend
.addArgument("-m", "--message")
783 .help("Specify the message, if missing standard input is used.");
784 parserSend
.addArgument("-a", "--attachment")
786 .help("Add file as attachment");
787 parserSend
.addArgument("-e", "--endsession")
788 .help("Clear session state and send end session message.")
789 .action(Arguments
.storeTrue());
791 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
792 parserLeaveGroup
.addArgument("-g", "--group")
794 .help("Specify the recipient group ID.");
796 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
797 parserUpdateGroup
.addArgument("-g", "--group")
798 .help("Specify the recipient group ID.");
799 parserUpdateGroup
.addArgument("-n", "--name")
800 .help("Specify the new group name.");
801 parserUpdateGroup
.addArgument("-a", "--avatar")
802 .help("Specify a new group avatar image file");
803 parserUpdateGroup
.addArgument("-m", "--member")
805 .help("Specify one or more members to add to the group");
807 Subparser parserListGroups
= subparsers
.addParser("listGroups");
808 parserListGroups
.addArgument("-d", "--detailed").action(Arguments
.storeTrue())
809 .help("List members of each group");
810 parserListGroups
.help("List group name and ids");
812 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
813 parserListIdentities
.addArgument("-n", "--number")
814 .help("Only show identity keys for the given phone number.");
816 Subparser parserTrust
= subparsers
.addParser("trust");
817 parserTrust
.addArgument("number")
818 .help("Specify the phone number, for which to set the trust.")
820 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
821 mutTrust
.addArgument("-a", "--trust-all-known-keys")
822 .help("Trust all known keys of this user, only use this for testing.")
823 .action(Arguments
.storeTrue());
824 mutTrust
.addArgument("-v", "--verified-fingerprint")
825 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
827 Subparser parserReceive
= subparsers
.addParser("receive");
828 parserReceive
.addArgument("-t", "--timeout")
830 .help("Number of seconds to wait for new messages (negative values disable timeout)");
831 parserReceive
.addArgument("--ignore-attachments")
832 .help("Don’t download attachments of received messages.")
833 .action(Arguments
.storeTrue());
835 Subparser parserDaemon
= subparsers
.addParser("daemon");
836 parserDaemon
.addArgument("--system")
837 .action(Arguments
.storeTrue())
838 .help("Use DBus system bus instead of user bus.");
839 parserDaemon
.addArgument("--ignore-attachments")
840 .help("Don’t download attachments of received messages.")
841 .action(Arguments
.storeTrue());
844 Namespace ns
= parser
.parseArgs(args
);
845 if ("link".equals(ns
.getString("command"))) {
846 if (ns
.getString("username") != null) {
848 System
.err
.println("You cannot specify a username (phone number) when linking");
851 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
852 if (ns
.getString("username") == null) {
854 System
.err
.println("You need to specify a username (phone number)");
857 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
858 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
862 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
863 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
867 } catch (ArgumentParserException e
) {
868 parser
.handleError(e
);
873 private static void handleAssertionError(AssertionError e
) {
874 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
876 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
879 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
880 System
.err
.println("Failed to send (some) messages:");
881 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
882 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
884 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
885 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
887 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
888 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
892 private static void handleIOException(IOException e
) {
893 System
.err
.println("Failed to send message: " + e
.getMessage());
896 private static String
readAll(InputStream
in) throws IOException
{
897 StringWriter output
= new StringWriter();
898 byte[] buffer
= new byte[4096];
901 while (-1 != (n
= System
.in.read(buffer
))) {
902 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
905 return output
.toString();
908 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
911 public ReceiveMessageHandler(Manager m
) {
916 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
917 SignalServiceAddress source
= envelope
.getSourceAddress();
918 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
919 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
920 if (source
.getRelay().isPresent()) {
921 System
.out
.println("Relayed by: " + source
.getRelay().get());
923 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
925 if (envelope
.isReceipt()) {
926 System
.out
.println("Got receipt.");
927 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
928 if (exception
!= null) {
929 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
930 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
931 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
932 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");
933 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");
935 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
938 if (content
== null) {
939 System
.out
.println("Failed to decrypt message.");
941 if (content
.getDataMessage().isPresent()) {
942 SignalServiceDataMessage message
= content
.getDataMessage().get();
943 handleSignalServiceDataMessage(message
);
945 if (content
.getSyncMessage().isPresent()) {
946 System
.out
.println("Received a sync message");
947 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
949 if (syncMessage
.getContacts().isPresent()) {
950 System
.out
.println("Received sync contacts");
951 printAttachment(syncMessage
.getContacts().get());
953 if (syncMessage
.getGroups().isPresent()) {
954 System
.out
.println("Received sync groups");
955 printAttachment(syncMessage
.getGroups().get());
957 if (syncMessage
.getRead().isPresent()) {
958 System
.out
.println("Received sync read messages list");
959 for (ReadMessage rm
: syncMessage
.getRead().get()) {
960 ContactInfo fromContact
= m
.getContact(rm
.getSender());
961 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + formatTimestamp(rm
.getTimestamp()));
964 if (syncMessage
.getRequest().isPresent()) {
965 System
.out
.println("Received sync request");
966 if (syncMessage
.getRequest().get().isContactsRequest()) {
967 System
.out
.println(" - contacts request");
969 if (syncMessage
.getRequest().get().isGroupsRequest()) {
970 System
.out
.println(" - groups request");
973 if (syncMessage
.getSent().isPresent()) {
974 System
.out
.println("Received sync sent message");
975 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
977 if (sentTranscriptMessage
.getDestination().isPresent()) {
978 String dest
= sentTranscriptMessage
.getDestination().get();
979 ContactInfo destContact
= m
.getContact(dest
);
980 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
984 System
.out
.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage
.getTimestamp()));
985 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
986 System
.out
.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
988 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
989 handleSignalServiceDataMessage(message
);
991 if (syncMessage
.getBlockedList().isPresent()) {
992 System
.out
.println("Received sync message with block list");
993 System
.out
.println("Blocked numbers:");
994 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
995 for (String number
: blockedList
.getNumbers()) {
996 System
.out
.println(" - " + number
);
1002 System
.out
.println("Unknown message received.");
1004 System
.out
.println();
1007 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
1008 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
1010 if (message
.getBody().isPresent()) {
1011 System
.out
.println("Body: " + message
.getBody().get());
1013 if (message
.getGroupInfo().isPresent()) {
1014 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1015 System
.out
.println("Group info:");
1016 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
1017 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
1018 System
.out
.println(" Name: " + groupInfo
.getName().get());
1020 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
1021 if (group
!= null) {
1022 System
.out
.println(" Name: " + group
.name
);
1024 System
.out
.println(" Name: <Unknown group>");
1027 System
.out
.println(" Type: " + groupInfo
.getType());
1028 if (groupInfo
.getMembers().isPresent()) {
1029 for (String member
: groupInfo
.getMembers().get()) {
1030 System
.out
.println(" Member: " + member
);
1033 if (groupInfo
.getAvatar().isPresent()) {
1034 System
.out
.println(" Avatar:");
1035 printAttachment(groupInfo
.getAvatar().get());
1038 if (message
.isEndSession()) {
1039 System
.out
.println("Is end session");
1041 if (message
.isExpirationUpdate()) {
1042 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
1044 if (message
.getExpiresInSeconds() > 0) {
1045 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
1048 if (message
.getAttachments().isPresent()) {
1049 System
.out
.println("Attachments: ");
1050 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1051 printAttachment(attachment
);
1056 private void printAttachment(SignalServiceAttachment attachment
) {
1057 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
1058 if (attachment
.isPointer()) {
1059 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1060 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
1061 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
1062 File file
= m
.getAttachmentFile(pointer
.getId());
1063 if (file
.exists()) {
1064 System
.out
.println(" Stored plaintext in: " + file
);
1070 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
1071 final DBusConnection conn
;
1073 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1079 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1080 super.handleMessage(envelope
, content
, exception
);
1082 if (!envelope
.isReceipt() && content
!= null && content
.getDataMessage().isPresent()) {
1083 SignalServiceDataMessage message
= content
.getDataMessage().get();
1085 if (!message
.isEndSession() &&
1086 !(message
.getGroupInfo().isPresent() &&
1087 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
1088 List
<String
> attachments
= new ArrayList
<>();
1089 if (message
.getAttachments().isPresent()) {
1090 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1091 if (attachment
.isPointer()) {
1092 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
1098 conn
.sendSignal(new Signal
.MessageReceived(
1100 message
.getTimestamp(),
1101 envelope
.getSource(),
1102 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1103 message
.getBody().isPresent() ? message
.getBody().get() : "",
1105 } catch (DBusException e
) {
1106 e
.printStackTrace();
1114 private static String
formatTimestamp(long timestamp
) {
1115 Date date
= new Date(timestamp
);
1116 final DateFormat df
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
1117 df
.setTimeZone(tzUTC
);
1118 return timestamp
+ " (" + df
.format(date
) + ")";