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 } catch (UnsatisfiedLinkError e
) {
401 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
403 } catch (DBusException e
) {
410 } catch (InterruptedException e
) {
415 if (!m
.isRegistered()) {
416 System
.err
.println("User is not registered.");
420 if (ns
.getDouble("timeout") != null) {
421 timeout
= ns
.getDouble("timeout");
423 boolean returnOnTimeout
= true;
425 returnOnTimeout
= false;
428 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
430 final Manager
.ReceiveMessageHandler handler
= ns
.getBoolean("json") ?
new JsonReceiveMessageHandler(m
) : new ReceiveMessageHandler(m
);
431 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, ignoreAttachments
, handler
);
432 } catch (IOException e
) {
433 System
.err
.println("Error while receiving messages: " + e
.getMessage());
435 } catch (AssertionError e
) {
436 handleAssertionError(e
);
441 if (dBusConn
!= null) {
442 System
.err
.println("quitGroup is not yet implemented via dbus");
445 if (!m
.isRegistered()) {
446 System
.err
.println("User is not registered.");
451 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
452 } catch (IOException e
) {
453 handleIOException(e
);
455 } catch (EncapsulatedExceptions e
) {
456 handleEncapsulatedExceptions(e
);
458 } catch (AssertionError e
) {
459 handleAssertionError(e
);
461 } catch (GroupNotFoundException e
) {
462 handleGroupNotFoundException(e
);
464 } catch (NotAGroupMemberException e
) {
465 handleNotAGroupMemberException(e
);
471 if (dBusConn
== null && !m
.isRegistered()) {
472 System
.err
.println("User is not registered.");
477 byte[] groupId
= null;
478 if (ns
.getString("group") != null) {
479 groupId
= decodeGroupId(ns
.getString("group"));
481 if (groupId
== null) {
482 groupId
= new byte[0];
484 String groupName
= ns
.getString("name");
485 if (groupName
== null) {
488 List
<String
> groupMembers
= ns
.<String
>getList("member");
489 if (groupMembers
== null) {
490 groupMembers
= new ArrayList
<String
>();
492 String groupAvatar
= ns
.getString("avatar");
493 if (groupAvatar
== null) {
496 byte[] newGroupId
= ts
.updateGroup(groupId
, groupName
, groupMembers
, groupAvatar
);
497 if (groupId
.length
!= newGroupId
.length
) {
498 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
500 } catch (IOException e
) {
501 handleIOException(e
);
503 } catch (AttachmentInvalidException e
) {
504 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
505 System
.err
.println("Aborting sending.");
507 } catch (GroupNotFoundException e
) {
508 handleGroupNotFoundException(e
);
510 } catch (NotAGroupMemberException e
) {
511 handleNotAGroupMemberException(e
);
513 } catch (EncapsulatedExceptions e
) {
514 handleEncapsulatedExceptions(e
);
520 if (dBusConn
!= null) {
521 System
.err
.println("listGroups is not yet implemented via dbus");
524 if (!m
.isRegistered()) {
525 System
.err
.println("User is not registered.");
529 List
<GroupInfo
> groups
= m
.getGroups();
530 boolean detailed
= ns
.getBoolean("detailed");
532 for (GroupInfo group
: groups
) {
533 printGroup(group
, detailed
);
536 case "listIdentities":
537 if (dBusConn
!= null) {
538 System
.err
.println("listIdentities is not yet implemented via dbus");
541 if (!m
.isRegistered()) {
542 System
.err
.println("User is not registered.");
545 if (ns
.get("number") == null) {
546 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
547 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
548 printIdentityFingerprint(m
, keys
.getKey(), id
);
552 String number
= ns
.getString("number");
553 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
554 printIdentityFingerprint(m
, number
, id
);
559 if (dBusConn
!= null) {
560 System
.err
.println("trust is not yet implemented via dbus");
563 if (!m
.isRegistered()) {
564 System
.err
.println("User is not registered.");
567 String number
= ns
.getString("number");
568 if (ns
.getBoolean("trust_all_known_keys")) {
569 boolean res
= m
.trustIdentityAllKeys(number
);
571 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
575 String fingerprint
= ns
.getString("verified_fingerprint");
576 if (fingerprint
!= null) {
577 fingerprint
= fingerprint
.replaceAll(" ", "");
578 if (fingerprint
.length() == 66) {
579 byte[] fingerprintBytes
;
581 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
582 } catch (Exception e
) {
583 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
586 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
588 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
591 } else if (fingerprint
.length() == 60) {
592 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
594 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.");
598 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
602 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
608 if (dBusConn
!= null) {
609 System
.err
.println("Stop it.");
612 if (!m
.isRegistered()) {
613 System
.err
.println("User is not registered.");
616 DBusConnection conn
= null;
620 if (ns
.getBoolean("system")) {
621 busType
= DBusConnection
.SYSTEM
;
623 busType
= DBusConnection
.SESSION
;
625 conn
= DBusConnection
.getConnection(busType
);
626 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
627 conn
.requestBusName(SIGNAL_BUSNAME
);
628 } catch (UnsatisfiedLinkError e
) {
629 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
631 } catch (DBusException e
) {
635 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
637 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, new DbusReceiveMessageHandler(m
, conn
));
638 } catch (IOException e
) {
639 System
.err
.println("Error while receiving messages: " + e
.getMessage());
641 } catch (AssertionError e
) {
642 handleAssertionError(e
);
655 if (dBusConn
!= null) {
656 dBusConn
.disconnect();
661 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
662 String digits
= formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.getIdentityKey()));
663 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
664 theirId
.getTrustLevel(), theirId
.getDateAdded(), Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
667 private static void printGroup(GroupInfo group
, boolean detailed
) {
669 System
.out
.println(String
.format("Id: %s Name: %s Active: %s Members: %s",
670 Base64
.encodeBytes(group
.groupId
), group
.name
, group
.active
, group
.members
));
672 System
.out
.println(String
.format("Id: %s Name: %s Active: %s", Base64
.encodeBytes(group
.groupId
),
673 group
.name
, group
.active
));
677 private static String
formatSafetyNumber(String digits
) {
678 final int partCount
= 12;
679 int partSize
= digits
.length() / partCount
;
680 StringBuilder f
= new StringBuilder(digits
.length() + partCount
);
681 for (int i
= 0; i
< partCount
; i
++) {
682 f
.append(digits
.substring(i
* partSize
, (i
* partSize
) + partSize
)).append(" ");
687 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
688 System
.err
.println("Failed to send to group: " + e
.getMessage());
689 System
.err
.println("Aborting sending.");
692 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
693 System
.err
.println("Failed to send to group: " + e
.getMessage());
694 System
.err
.println("Update the group on another device to readd the user to this group.");
695 System
.err
.println("Aborting sending.");
699 private static void handleDBusExecutionException(DBusExecutionException e
) {
700 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
701 System
.err
.println("Aborting.");
704 private static byte[] decodeGroupId(String groupId
) {
706 return Base64
.decode(groupId
);
707 } catch (IOException e
) {
708 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
709 System
.err
.println("Aborting sending.");
715 private static Namespace
parseArgs(String
[] args
) {
716 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("signal-cli")
718 .description("Commandline interface for Signal.")
719 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
721 parser
.addArgument("-v", "--version")
722 .help("Show package version.")
723 .action(Arguments
.version());
724 parser
.addArgument("--config")
725 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
727 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
728 mut
.addArgument("-u", "--username")
729 .help("Specify your phone number, that will be used for verification.");
730 mut
.addArgument("--dbus")
731 .help("Make request via user dbus.")
732 .action(Arguments
.storeTrue());
733 mut
.addArgument("--dbus-system")
734 .help("Make request via system dbus.")
735 .action(Arguments
.storeTrue());
737 Subparsers subparsers
= parser
.addSubparsers()
738 .title("subcommands")
740 .description("valid subcommands")
741 .help("additional help");
743 Subparser parserLink
= subparsers
.addParser("link");
744 parserLink
.addArgument("-n", "--name")
745 .help("Specify a name to describe this new device.");
747 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
748 parserAddDevice
.addArgument("--uri")
750 .help("Specify the uri contained in the QR code shown by the new device.");
752 Subparser parserDevices
= subparsers
.addParser("listDevices");
754 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
755 parserRemoveDevice
.addArgument("-d", "--deviceId")
758 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
760 Subparser parserRegister
= subparsers
.addParser("register");
761 parserRegister
.addArgument("-v", "--voice")
762 .help("The verification should be done over voice, not sms.")
763 .action(Arguments
.storeTrue());
765 Subparser parserUnregister
= subparsers
.addParser("unregister");
766 parserUnregister
.help("Unregister the current device from the signal server.");
768 Subparser parserUpdateAccount
= subparsers
.addParser("updateAccount");
769 parserUpdateAccount
.help("Update the account attributes on the signal server.");
771 Subparser parserVerify
= subparsers
.addParser("verify");
772 parserVerify
.addArgument("verificationCode")
773 .help("The verification code you received via sms or voice call.");
775 Subparser parserSend
= subparsers
.addParser("send");
776 parserSend
.addArgument("-g", "--group")
777 .help("Specify the recipient group ID.");
778 parserSend
.addArgument("recipient")
779 .help("Specify the recipients' phone number.")
781 parserSend
.addArgument("-m", "--message")
782 .help("Specify the message, if missing standard input is used.");
783 parserSend
.addArgument("-a", "--attachment")
785 .help("Add file as attachment");
786 parserSend
.addArgument("-e", "--endsession")
787 .help("Clear session state and send end session message.")
788 .action(Arguments
.storeTrue());
790 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
791 parserLeaveGroup
.addArgument("-g", "--group")
793 .help("Specify the recipient group ID.");
795 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
796 parserUpdateGroup
.addArgument("-g", "--group")
797 .help("Specify the recipient group ID.");
798 parserUpdateGroup
.addArgument("-n", "--name")
799 .help("Specify the new group name.");
800 parserUpdateGroup
.addArgument("-a", "--avatar")
801 .help("Specify a new group avatar image file");
802 parserUpdateGroup
.addArgument("-m", "--member")
804 .help("Specify one or more members to add to the group");
806 Subparser parserListGroups
= subparsers
.addParser("listGroups");
807 parserListGroups
.addArgument("-d", "--detailed").action(Arguments
.storeTrue())
808 .help("List members of each group");
809 parserListGroups
.help("List group name and ids");
811 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
812 parserListIdentities
.addArgument("-n", "--number")
813 .help("Only show identity keys for the given phone number.");
815 Subparser parserTrust
= subparsers
.addParser("trust");
816 parserTrust
.addArgument("number")
817 .help("Specify the phone number, for which to set the trust.")
819 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
820 mutTrust
.addArgument("-a", "--trust-all-known-keys")
821 .help("Trust all known keys of this user, only use this for testing.")
822 .action(Arguments
.storeTrue());
823 mutTrust
.addArgument("-v", "--verified-fingerprint")
824 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
826 Subparser parserReceive
= subparsers
.addParser("receive");
827 parserReceive
.addArgument("-t", "--timeout")
829 .help("Number of seconds to wait for new messages (negative values disable timeout)");
830 parserReceive
.addArgument("--ignore-attachments")
831 .help("Don’t download attachments of received messages.")
832 .action(Arguments
.storeTrue());
833 parserReceive
.addArgument("--json")
834 .help("Output received messages in json format, one json object per line.")
835 .action(Arguments
.storeTrue());
837 Subparser parserDaemon
= subparsers
.addParser("daemon");
838 parserDaemon
.addArgument("--system")
839 .action(Arguments
.storeTrue())
840 .help("Use DBus system bus instead of user bus.");
841 parserDaemon
.addArgument("--ignore-attachments")
842 .help("Don’t download attachments of received messages.")
843 .action(Arguments
.storeTrue());
846 Namespace ns
= parser
.parseArgs(args
);
847 if ("link".equals(ns
.getString("command"))) {
848 if (ns
.getString("username") != null) {
850 System
.err
.println("You cannot specify a username (phone number) when linking");
853 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
854 if (ns
.getString("username") == null) {
856 System
.err
.println("You need to specify a username (phone number)");
859 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
860 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
864 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
865 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
869 } catch (ArgumentParserException e
) {
870 parser
.handleError(e
);
875 private static void handleAssertionError(AssertionError e
) {
876 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
878 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
881 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
882 System
.err
.println("Failed to send (some) messages:");
883 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
884 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
886 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
887 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
889 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
890 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
894 private static void handleIOException(IOException e
) {
895 System
.err
.println("Failed to send message: " + e
.getMessage());
898 private static String
readAll(InputStream
in) throws IOException
{
899 StringWriter output
= new StringWriter();
900 byte[] buffer
= new byte[4096];
903 while (-1 != (n
= System
.in.read(buffer
))) {
904 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
907 return output
.toString();
910 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
913 public ReceiveMessageHandler(Manager m
) {
918 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
919 SignalServiceAddress source
= envelope
.getSourceAddress();
920 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
921 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
922 if (source
.getRelay().isPresent()) {
923 System
.out
.println("Relayed by: " + source
.getRelay().get());
925 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
927 if (envelope
.isReceipt()) {
928 System
.out
.println("Got receipt.");
929 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
930 if (exception
!= null) {
931 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
932 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
933 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
934 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");
935 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");
937 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
940 if (content
== null) {
941 System
.out
.println("Failed to decrypt message.");
943 if (content
.getDataMessage().isPresent()) {
944 SignalServiceDataMessage message
= content
.getDataMessage().get();
945 handleSignalServiceDataMessage(message
);
947 if (content
.getSyncMessage().isPresent()) {
948 System
.out
.println("Received a sync message");
949 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
951 if (syncMessage
.getContacts().isPresent()) {
952 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
953 if (contactsMessage
.isComplete()) {
954 System
.out
.println("Received complete sync contacts");
956 System
.out
.println("Received sync contacts");
958 printAttachment(contactsMessage
.getContactsStream());
960 if (syncMessage
.getGroups().isPresent()) {
961 System
.out
.println("Received sync groups");
962 printAttachment(syncMessage
.getGroups().get());
964 if (syncMessage
.getRead().isPresent()) {
965 System
.out
.println("Received sync read messages list");
966 for (ReadMessage rm
: syncMessage
.getRead().get()) {
967 ContactInfo fromContact
= m
.getContact(rm
.getSender());
968 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + formatTimestamp(rm
.getTimestamp()));
971 if (syncMessage
.getRequest().isPresent()) {
972 System
.out
.println("Received sync request");
973 if (syncMessage
.getRequest().get().isContactsRequest()) {
974 System
.out
.println(" - contacts request");
976 if (syncMessage
.getRequest().get().isGroupsRequest()) {
977 System
.out
.println(" - groups request");
980 if (syncMessage
.getSent().isPresent()) {
981 System
.out
.println("Received sync sent message");
982 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
984 if (sentTranscriptMessage
.getDestination().isPresent()) {
985 String dest
= sentTranscriptMessage
.getDestination().get();
986 ContactInfo destContact
= m
.getContact(dest
);
987 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
991 System
.out
.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage
.getTimestamp()));
992 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
993 System
.out
.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
995 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
996 handleSignalServiceDataMessage(message
);
998 if (syncMessage
.getBlockedList().isPresent()) {
999 System
.out
.println("Received sync message with block list");
1000 System
.out
.println("Blocked numbers:");
1001 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
1002 for (String number
: blockedList
.getNumbers()) {
1003 System
.out
.println(" - " + number
);
1006 if (syncMessage
.getVerified().isPresent()) {
1007 System
.out
.println("Received sync message with verified identities:");
1008 final List
<VerifiedMessage
> verifiedList
= syncMessage
.getVerified().get();
1009 for (VerifiedMessage v
: verifiedList
) {
1010 System
.out
.println(" - " + v
.getDestination() + ": " + v
.getVerified());
1011 String safetyNumber
= formatSafetyNumber(m
.computeSafetyNumber(v
.getDestination(), v
.getIdentityKey()));
1012 System
.out
.println(" " + safetyNumber
);
1019 System
.out
.println("Unknown message received.");
1021 System
.out
.println();
1024 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
1025 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
1027 if (message
.getBody().isPresent()) {
1028 System
.out
.println("Body: " + message
.getBody().get());
1030 if (message
.getGroupInfo().isPresent()) {
1031 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1032 System
.out
.println("Group info:");
1033 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
1034 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
1035 System
.out
.println(" Name: " + groupInfo
.getName().get());
1037 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
1038 if (group
!= null) {
1039 System
.out
.println(" Name: " + group
.name
);
1041 System
.out
.println(" Name: <Unknown group>");
1044 System
.out
.println(" Type: " + groupInfo
.getType());
1045 if (groupInfo
.getMembers().isPresent()) {
1046 for (String member
: groupInfo
.getMembers().get()) {
1047 System
.out
.println(" Member: " + member
);
1050 if (groupInfo
.getAvatar().isPresent()) {
1051 System
.out
.println(" Avatar:");
1052 printAttachment(groupInfo
.getAvatar().get());
1055 if (message
.isEndSession()) {
1056 System
.out
.println("Is end session");
1058 if (message
.isExpirationUpdate()) {
1059 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
1061 if (message
.getExpiresInSeconds() > 0) {
1062 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
1065 if (message
.getAttachments().isPresent()) {
1066 System
.out
.println("Attachments: ");
1067 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1068 printAttachment(attachment
);
1073 private void printAttachment(SignalServiceAttachment attachment
) {
1074 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
1075 if (attachment
.isPointer()) {
1076 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1077 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
1078 System
.out
.println(" Filename: " + (pointer
.getFileName().isPresent() ? pointer
.getFileName().get() : "-"));
1079 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
1080 System
.out
.println(" Voice note: " + (pointer
.getVoiceNote() ?
"yes" : "no"));
1081 File file
= m
.getAttachmentFile(pointer
.getId());
1082 if (file
.exists()) {
1083 System
.out
.println(" Stored plaintext in: " + file
);
1089 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
1090 final DBusConnection conn
;
1092 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1098 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1099 super.handleMessage(envelope
, content
, exception
);
1101 if (!envelope
.isReceipt() && content
!= null && content
.getDataMessage().isPresent()) {
1102 SignalServiceDataMessage message
= content
.getDataMessage().get();
1104 if (!message
.isEndSession() &&
1105 !(message
.getGroupInfo().isPresent() &&
1106 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
1107 List
<String
> attachments
= new ArrayList
<>();
1108 if (message
.getAttachments().isPresent()) {
1109 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1110 if (attachment
.isPointer()) {
1111 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
1117 conn
.sendSignal(new Signal
.MessageReceived(
1119 message
.getTimestamp(),
1120 envelope
.getSource(),
1121 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1122 message
.getBody().isPresent() ? message
.getBody().get() : "",
1124 } catch (DBusException e
) {
1125 e
.printStackTrace();
1132 private static class JsonReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
1134 final ObjectMapper jsonProcessor
;
1136 public JsonReceiveMessageHandler(Manager m
) {
1138 this.jsonProcessor
= new ObjectMapper();
1139 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.ANY
); // disable autodetect
1140 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
1141 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
1142 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
1146 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1147 ObjectNode result
= jsonProcessor
.createObjectNode();
1148 if (exception
!= null) {
1149 result
.putPOJO("error", new JsonError(exception
));
1151 if (envelope
!= null) {
1152 result
.putPOJO("envelope", new JsonMessageEnvelope(envelope
, content
));
1155 jsonProcessor
.writeValue(System
.out
, result
);
1156 System
.out
.println();
1157 } catch (IOException e
) {
1158 e
.printStackTrace();
1163 private static String
formatTimestamp(long timestamp
) {
1164 Date date
= new Date(timestamp
);
1165 final DateFormat df
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
1166 df
.setTimeZone(tzUTC
);
1167 return timestamp
+ " (" + df
.format(date
) + ")";