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 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
;
51 import java
.io
.IOException
;
52 import java
.io
.InputStream
;
53 import java
.io
.StringWriter
;
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
;
61 import java
.util
.concurrent
.TimeUnit
;
62 import java
.util
.concurrent
.TimeoutException
;
66 public static final String SIGNAL_BUSNAME
= "org.asamk.Signal";
67 public static final String SIGNAL_OBJECTPATH
= "/org/asamk/Signal";
69 private static final TimeZone tzUTC
= TimeZone
.getTimeZone("UTC");
71 public static void main(String
[] args
) {
72 // Workaround for BKS truststore
73 Security
.insertProviderAt(new org
.bouncycastle
.jce
.provider
.BouncyCastleProvider(), 1);
75 Namespace ns
= parseArgs(args
);
80 int res
= handleCommands(ns
);
84 private static int handleCommands(Namespace ns
) {
85 final String username
= ns
.getString("username");
88 DBusConnection dBusConn
= null;
90 if (ns
.getBoolean("dbus") || ns
.getBoolean("dbus_system")) {
94 if (ns
.getBoolean("dbus_system")) {
95 busType
= DBusConnection
.SYSTEM
;
97 busType
= DBusConnection
.SESSION
;
99 dBusConn
= DBusConnection
.getConnection(busType
);
100 ts
= (Signal
) dBusConn
.getRemoteObject(
101 SIGNAL_BUSNAME
, SIGNAL_OBJECTPATH
,
103 } catch (UnsatisfiedLinkError e
) {
104 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
106 } catch (DBusException e
) {
108 if (dBusConn
!= null) {
109 dBusConn
.disconnect();
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
;
125 m
= new Manager(username
, settingsPath
);
127 if (m
.userExists()) {
130 } catch (Exception e
) {
131 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
137 switch (ns
.getString("command")) {
139 if (dBusConn
!= null) {
140 System
.err
.println("register is not yet implemented via dbus");
143 if (!m
.userHasKeys()) {
144 m
.createNewIdentity();
147 m
.register(ns
.getBoolean("voice"));
148 } catch (IOException e
) {
149 System
.err
.println("Request verify error: " + e
.getMessage());
154 if (dBusConn
!= null) {
155 System
.err
.println("unregister is not yet implemented via dbus");
158 if (!m
.isRegistered()) {
159 System
.err
.println("User is not registered.");
164 } catch (IOException e
) {
165 System
.err
.println("Unregister error: " + e
.getMessage());
169 case "updateAccount":
170 if (dBusConn
!= null) {
171 System
.err
.println("updateAccount is not yet implemented via dbus");
174 if (!m
.isRegistered()) {
175 System
.err
.println("User is not registered.");
179 m
.updateAccountAttributes();
180 } catch (IOException e
) {
181 System
.err
.println("UpdateAccount error: " + e
.getMessage());
186 if (dBusConn
!= null) {
187 System
.err
.println("verify is not yet implemented via dbus");
190 if (!m
.userHasKeys()) {
191 System
.err
.println("User has no keys, first call register.");
194 if (m
.isRegistered()) {
195 System
.err
.println("User registration is already verified");
199 m
.verifyAccount(ns
.getString("verificationCode"));
200 } catch (IOException e
) {
201 System
.err
.println("Verify error: " + e
.getMessage());
206 if (dBusConn
!= null) {
207 System
.err
.println("link is not yet implemented via dbus");
211 // When linking, username is null and we always have to create keys
212 m
.createNewIdentity();
214 String deviceName
= ns
.getString("name");
215 if (deviceName
== null) {
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.");
225 } catch (IOException e
) {
226 System
.err
.println("Link request error: " + e
.getMessage());
228 } catch (AssertionError e
) {
229 handleAssertionError(e
);
231 } catch (InvalidKeyException e
) {
234 } catch (UserAlreadyExists e
) {
235 System
.err
.println("The user " + e
.getUsername() + " already exists\nDelete \"" + e
.getFileName() + "\" before trying again.");
240 if (dBusConn
!= null) {
241 System
.err
.println("link is not yet implemented via dbus");
244 if (!m
.isRegistered()) {
245 System
.err
.println("User is not registered.");
249 m
.addDeviceLink(new URI(ns
.getString("uri")));
250 } catch (IOException e
) {
253 } catch (InvalidKeyException e
) {
256 } catch (AssertionError e
) {
257 handleAssertionError(e
);
259 } catch (URISyntaxException e
) {
265 if (dBusConn
!= null) {
266 System
.err
.println("listDevices is not yet implemented via dbus");
269 if (!m
.isRegistered()) {
270 System
.err
.println("User is not registered.");
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()));
281 } catch (IOException e
) {
287 if (dBusConn
!= null) {
288 System
.err
.println("removeDevice is not yet implemented via dbus");
291 if (!m
.isRegistered()) {
292 System
.err
.println("User is not registered.");
296 int deviceId
= ns
.getInt("deviceId");
297 m
.removeLinkedDevices(deviceId
);
298 } catch (IOException e
) {
304 if (dBusConn
== null && !m
.isRegistered()) {
305 System
.err
.println("User is not registered.");
309 if (ns
.getBoolean("endsession")) {
310 if (ns
.getList("recipient") == null) {
311 System
.err
.println("No recipients given");
312 System
.err
.println("Aborting sending.");
316 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
317 } catch (IOException e
) {
318 handleIOException(e
);
320 } catch (EncapsulatedExceptions e
) {
321 handleEncapsulatedExceptions(e
);
323 } catch (AssertionError e
) {
324 handleAssertionError(e
);
326 } catch (DBusExecutionException e
) {
327 handleDBusExecutionException(e
);
331 String messageText
= ns
.getString("message");
332 if (messageText
== null) {
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.");
343 List
<String
> attachments
= ns
.getList("attachment");
344 if (attachments
== null) {
345 attachments
= new ArrayList
<>();
347 if (ns
.getString("group") != null) {
348 byte[] groupId
= decodeGroupId(ns
.getString("group"));
349 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
351 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
353 } catch (IOException e
) {
354 handleIOException(e
);
356 } catch (EncapsulatedExceptions e
) {
357 handleEncapsulatedExceptions(e
);
359 } catch (AssertionError e
) {
360 handleAssertionError(e
);
362 } catch (GroupNotFoundException e
) {
363 handleGroupNotFoundException(e
);
365 } catch (NotAGroupMemberException e
) {
366 handleNotAGroupMemberException(e
);
368 } catch (AttachmentInvalidException e
) {
369 System
.err
.println("Failed to add attachment: " + e
.getMessage());
370 System
.err
.println("Aborting sending.");
372 } catch (DBusExecutionException e
) {
373 handleDBusExecutionException(e
);
380 if (dBusConn
!= null) {
382 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
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()));
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
);
397 System
.out
.println();
400 dBusConn
.addSigHandler(Signal
.ReceiptReceived
.class, new DBusSigHandler
<Signal
.ReceiptReceived
>() {
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())));
407 } catch (UnsatisfiedLinkError e
) {
408 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
410 } catch (DBusException e
) {
417 } catch (InterruptedException e
) {
422 if (!m
.isRegistered()) {
423 System
.err
.println("User is not registered.");
427 if (ns
.getDouble("timeout") != null) {
428 timeout
= ns
.getDouble("timeout");
430 boolean returnOnTimeout
= true;
432 returnOnTimeout
= false;
435 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
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());
442 } catch (AssertionError e
) {
443 handleAssertionError(e
);
448 if (dBusConn
!= null) {
449 System
.err
.println("quitGroup is not yet implemented via dbus");
452 if (!m
.isRegistered()) {
453 System
.err
.println("User is not registered.");
458 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
459 } catch (IOException e
) {
460 handleIOException(e
);
462 } catch (EncapsulatedExceptions e
) {
463 handleEncapsulatedExceptions(e
);
465 } catch (AssertionError e
) {
466 handleAssertionError(e
);
468 } catch (GroupNotFoundException e
) {
469 handleGroupNotFoundException(e
);
471 } catch (NotAGroupMemberException e
) {
472 handleNotAGroupMemberException(e
);
478 if (dBusConn
== null && !m
.isRegistered()) {
479 System
.err
.println("User is not registered.");
484 byte[] groupId
= null;
485 if (ns
.getString("group") != null) {
486 groupId
= decodeGroupId(ns
.getString("group"));
488 if (groupId
== null) {
489 groupId
= new byte[0];
491 String groupName
= ns
.getString("name");
492 if (groupName
== null) {
495 List
<String
> groupMembers
= ns
.<String
>getList("member");
496 if (groupMembers
== null) {
497 groupMembers
= new ArrayList
<String
>();
499 String groupAvatar
= ns
.getString("avatar");
500 if (groupAvatar
== null) {
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
) + "\" …");
507 } catch (IOException e
) {
508 handleIOException(e
);
510 } catch (AttachmentInvalidException e
) {
511 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
512 System
.err
.println("Aborting sending.");
514 } catch (GroupNotFoundException e
) {
515 handleGroupNotFoundException(e
);
517 } catch (NotAGroupMemberException e
) {
518 handleNotAGroupMemberException(e
);
520 } catch (EncapsulatedExceptions e
) {
521 handleEncapsulatedExceptions(e
);
527 if (dBusConn
!= null) {
528 System
.err
.println("listGroups is not yet implemented via dbus");
531 if (!m
.isRegistered()) {
532 System
.err
.println("User is not registered.");
536 List
<GroupInfo
> groups
= m
.getGroups();
537 boolean detailed
= ns
.getBoolean("detailed");
539 for (GroupInfo group
: groups
) {
540 printGroup(group
, detailed
);
543 case "listIdentities":
544 if (dBusConn
!= null) {
545 System
.err
.println("listIdentities is not yet implemented via dbus");
548 if (!m
.isRegistered()) {
549 System
.err
.println("User is not registered.");
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
);
559 String number
= ns
.getString("number");
560 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
561 printIdentityFingerprint(m
, number
, id
);
566 if (dBusConn
!= null) {
567 System
.err
.println("trust is not yet implemented via dbus");
570 if (!m
.isRegistered()) {
571 System
.err
.println("User is not registered.");
574 String number
= ns
.getString("number");
575 if (ns
.getBoolean("trust_all_known_keys")) {
576 boolean res
= m
.trustIdentityAllKeys(number
);
578 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
582 String fingerprint
= ns
.getString("verified_fingerprint");
583 if (fingerprint
!= null) {
584 fingerprint
= fingerprint
.replaceAll(" ", "");
585 if (fingerprint
.length() == 66) {
586 byte[] fingerprintBytes
;
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.");
593 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
595 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
598 } else if (fingerprint
.length() == 60) {
599 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
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.");
605 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
609 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
615 if (dBusConn
!= null) {
616 System
.err
.println("Stop it.");
619 if (!m
.isRegistered()) {
620 System
.err
.println("User is not registered.");
623 DBusConnection conn
= null;
627 if (ns
.getBoolean("system")) {
628 busType
= DBusConnection
.SYSTEM
;
630 busType
= DBusConnection
.SESSION
;
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());
638 } catch (DBusException e
) {
642 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
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());
648 } catch (AssertionError e
) {
649 handleAssertionError(e
);
662 if (dBusConn
!= null) {
663 dBusConn
.disconnect();
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
));
674 private static void printGroup(GroupInfo group
, boolean 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
));
679 System
.out
.println(String
.format("Id: %s Name: %s Active: %s", Base64
.encodeBytes(group
.groupId
),
680 group
.name
, group
.active
));
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(" ");
694 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
695 System
.err
.println("Failed to send to group: " + e
.getMessage());
696 System
.err
.println("Aborting sending.");
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.");
706 private static void handleDBusExecutionException(DBusExecutionException e
) {
707 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
708 System
.err
.println("Aborting.");
711 private static byte[] decodeGroupId(String groupId
) {
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.");
722 private static Namespace
parseArgs(String
[] args
) {
723 ArgumentParser parser
= ArgumentParsers
.newFor("signal-cli")
726 .description("Commandline interface for Signal.")
727 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
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).");
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());
745 Subparsers subparsers
= parser
.addSubparsers()
746 .title("subcommands")
748 .description("valid subcommands")
749 .help("additional help");
751 Subparser parserLink
= subparsers
.addParser("link");
752 parserLink
.addArgument("-n", "--name")
753 .help("Specify a name to describe this new device.");
755 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
756 parserAddDevice
.addArgument("--uri")
758 .help("Specify the uri contained in the QR code shown by the new device.");
760 Subparser parserDevices
= subparsers
.addParser("listDevices");
762 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
763 parserRemoveDevice
.addArgument("-d", "--deviceId")
766 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
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());
773 Subparser parserUnregister
= subparsers
.addParser("unregister");
774 parserUnregister
.help("Unregister the current device from the signal server.");
776 Subparser parserUpdateAccount
= subparsers
.addParser("updateAccount");
777 parserUpdateAccount
.help("Update the account attributes on the signal server.");
779 Subparser parserVerify
= subparsers
.addParser("verify");
780 parserVerify
.addArgument("verificationCode")
781 .help("The verification code you received via sms or voice call.");
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.")
789 parserSend
.addArgument("-m", "--message")
790 .help("Specify the message, if missing standard input is used.");
791 parserSend
.addArgument("-a", "--attachment")
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());
798 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
799 parserLeaveGroup
.addArgument("-g", "--group")
801 .help("Specify the recipient group ID.");
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")
812 .help("Specify one or more members to add to the group");
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");
819 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
820 parserListIdentities
.addArgument("-n", "--number")
821 .help("Only show identity keys for the given phone number.");
823 Subparser parserTrust
= subparsers
.addParser("trust");
824 parserTrust
.addArgument("number")
825 .help("Specify the phone number, for which to set the trust.")
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.");
834 Subparser parserReceive
= subparsers
.addParser("receive");
835 parserReceive
.addArgument("-t", "--timeout")
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());
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());
854 Namespace ns
= parser
.parseArgs(args
);
855 if ("link".equals(ns
.getString("command"))) {
856 if (ns
.getString("username") != null) {
858 System
.err
.println("You cannot specify a username (phone number) when linking");
861 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
862 if (ns
.getString("username") == null) {
864 System
.err
.println("You need to specify a username (phone number)");
867 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
868 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
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");
877 } catch (ArgumentParserException e
) {
878 parser
.handleError(e
);
883 private static void handleAssertionError(AssertionError e
) {
884 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
886 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
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());
894 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
895 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
897 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
898 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
902 private static void handleIOException(IOException e
) {
903 System
.err
.println("Failed to send message: " + e
.getMessage());
906 private static String
readAll(InputStream
in) throws IOException
{
907 StringWriter output
= new StringWriter();
908 byte[] buffer
= new byte[4096];
911 while (-1 != (n
= System
.in.read(buffer
))) {
912 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
915 return output
.toString();
918 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
921 public ReceiveMessageHandler(Manager m
) {
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());
933 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
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");
945 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
948 if (content
== null) {
949 System
.out
.println("Failed to decrypt message.");
951 if (content
.getDataMessage().isPresent()) {
952 SignalServiceDataMessage message
= content
.getDataMessage().get();
953 handleSignalServiceDataMessage(message
);
955 if (content
.getSyncMessage().isPresent()) {
956 System
.out
.println("Received a sync message");
957 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
959 if (syncMessage
.getContacts().isPresent()) {
960 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
961 if (contactsMessage
.isComplete()) {
962 System
.out
.println("Received complete sync contacts");
964 System
.out
.println("Received sync contacts");
966 printAttachment(contactsMessage
.getContactsStream());
968 if (syncMessage
.getGroups().isPresent()) {
969 System
.out
.println("Received sync groups");
970 printAttachment(syncMessage
.getGroups().get());
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()));
979 if (syncMessage
.getRequest().isPresent()) {
980 System
.out
.println("Received sync request");
981 if (syncMessage
.getRequest().get().isContactsRequest()) {
982 System
.out
.println(" - contacts request");
984 if (syncMessage
.getRequest().get().isGroupsRequest()) {
985 System
.out
.println(" - groups request");
988 if (syncMessage
.getSent().isPresent()) {
989 System
.out
.println("Received sync sent message");
990 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
992 if (sentTranscriptMessage
.getDestination().isPresent()) {
993 String dest
= sentTranscriptMessage
.getDestination().get();
994 ContactInfo destContact
= m
.getContact(dest
);
995 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
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()));
1003 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
1004 handleSignalServiceDataMessage(message
);
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
);
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
);
1024 System
.out
.println("Unknown message received.");
1026 System
.out
.println();
1029 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
1030 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
1032 if (message
.getBody().isPresent()) {
1033 System
.out
.println("Body: " + message
.getBody().get());
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());
1042 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
1043 if (group
!= null) {
1044 System
.out
.println(" Name: " + group
.name
);
1046 System
.out
.println(" Name: <Unknown group>");
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
);
1055 if (groupInfo
.getAvatar().isPresent()) {
1056 System
.out
.println(" Avatar:");
1057 printAttachment(groupInfo
.getAvatar().get());
1060 if (message
.isEndSession()) {
1061 System
.out
.println("Is end session");
1063 if (message
.isExpirationUpdate()) {
1064 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
1066 if (message
.getExpiresInSeconds() > 0) {
1067 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
1070 if (message
.getAttachments().isPresent()) {
1071 System
.out
.println("Attachments: ");
1072 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1073 printAttachment(attachment
);
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
);
1094 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
1095 final DBusConnection conn
;
1097 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1103 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1104 super.handleMessage(envelope
, content
, exception
);
1106 if (envelope
.isReceipt()) {
1108 conn
.sendSignal(new Signal
.ReceiptReceived(
1110 envelope
.getTimestamp(),
1111 envelope
.getSource()
1113 } catch (DBusException e
) {
1114 e
.printStackTrace();
1116 } else if (content
!= null && content
.getDataMessage().isPresent()) {
1117 SignalServiceDataMessage message
= content
.getDataMessage().get();
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());
1132 conn
.sendSignal(new Signal
.MessageReceived(
1134 message
.getTimestamp(),
1135 envelope
.getSource(),
1136 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1137 message
.getBody().isPresent() ? message
.getBody().get() : "",
1139 } catch (DBusException e
) {
1140 e
.printStackTrace();
1147 private static class JsonReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
1149 final ObjectMapper jsonProcessor
;
1151 public JsonReceiveMessageHandler(Manager 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
);
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
));
1166 if (envelope
!= null) {
1167 result
.putPOJO("envelope", new JsonMessageEnvelope(envelope
, content
));
1170 jsonProcessor
.writeValue(System
.out
, result
);
1171 System
.out
.println();
1172 } catch (IOException e
) {
1173 e
.printStackTrace();
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
) + ")";