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
.*;
22 import org
.apache
.http
.util
.TextUtils
;
23 import org
.asamk
.Signal
;
24 import org
.asamk
.signal
.storage
.contacts
.ContactInfo
;
25 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
26 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
27 import org
.asamk
.signal
.util
.Base64
;
28 import org
.asamk
.signal
.util
.Hex
;
29 import org
.freedesktop
.dbus
.DBusConnection
;
30 import org
.freedesktop
.dbus
.DBusSigHandler
;
31 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
32 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
33 import org
.whispersystems
.libsignal
.InvalidKeyException
;
34 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
35 import org
.whispersystems
.signalservice
.api
.messages
.*;
36 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
37 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
38 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
39 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
40 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
41 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
44 import java
.io
.IOException
;
45 import java
.io
.InputStream
;
46 import java
.io
.StringWriter
;
48 import java
.net
.URISyntaxException
;
49 import java
.nio
.charset
.Charset
;
50 import java
.security
.Security
;
51 import java
.text
.DateFormat
;
52 import java
.text
.SimpleDateFormat
;
54 import java
.util
.concurrent
.TimeUnit
;
55 import java
.util
.concurrent
.TimeoutException
;
59 public static final String SIGNAL_BUSNAME
= "org.asamk.Signal";
60 public static final String SIGNAL_OBJECTPATH
= "/org/asamk/Signal";
62 private static final TimeZone tzUTC
= TimeZone
.getTimeZone("UTC");
64 public static void main(String
[] args
) {
65 // Workaround for BKS truststore
66 Security
.insertProviderAt(new org
.bouncycastle
.jce
.provider
.BouncyCastleProvider(), 1);
68 Namespace ns
= parseArgs(args
);
73 int res
= handleCommands(ns
);
77 private static int handleCommands(Namespace ns
) {
78 final String username
= ns
.getString("username");
81 DBusConnection dBusConn
= null;
83 if (ns
.getBoolean("dbus") || ns
.getBoolean("dbus_system")) {
87 if (ns
.getBoolean("dbus_system")) {
88 busType
= DBusConnection
.SYSTEM
;
90 busType
= DBusConnection
.SESSION
;
92 dBusConn
= DBusConnection
.getConnection(busType
);
93 ts
= (Signal
) dBusConn
.getRemoteObject(
94 SIGNAL_BUSNAME
, SIGNAL_OBJECTPATH
,
96 } catch (UnsatisfiedLinkError e
) {
97 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
99 } catch (DBusException e
) {
101 if (dBusConn
!= null) {
102 dBusConn
.disconnect();
107 String settingsPath
= ns
.getString("config");
108 if (TextUtils
.isEmpty(settingsPath
)) {
109 settingsPath
= System
.getProperty("user.home") + "/.config/signal";
110 if (!new File(settingsPath
).exists()) {
111 String legacySettingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
112 if (new File(legacySettingsPath
).exists()) {
113 settingsPath
= legacySettingsPath
;
118 m
= new Manager(username
, settingsPath
);
120 if (m
.userExists()) {
123 } catch (Exception e
) {
124 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
130 switch (ns
.getString("command")) {
132 if (dBusConn
!= null) {
133 System
.err
.println("register is not yet implemented via dbus");
136 if (!m
.userHasKeys()) {
137 m
.createNewIdentity();
140 m
.register(ns
.getBoolean("voice"));
141 } catch (IOException e
) {
142 System
.err
.println("Request verify error: " + e
.getMessage());
147 if (dBusConn
!= null) {
148 System
.err
.println("unregister is not yet implemented via dbus");
151 if (!m
.isRegistered()) {
152 System
.err
.println("User is not registered.");
157 } catch (IOException e
) {
158 System
.err
.println("Unregister error: " + e
.getMessage());
162 case "updateAccount":
163 if (dBusConn
!= null) {
164 System
.err
.println("updateAccount is not yet implemented via dbus");
167 if (!m
.isRegistered()) {
168 System
.err
.println("User is not registered.");
172 m
.updateAccountAttributes();
173 } catch (IOException e
) {
174 System
.err
.println("UpdateAccount error: " + e
.getMessage());
179 if (dBusConn
!= null) {
180 System
.err
.println("verify is not yet implemented via dbus");
183 if (!m
.userHasKeys()) {
184 System
.err
.println("User has no keys, first call register.");
187 if (m
.isRegistered()) {
188 System
.err
.println("User registration is already verified");
192 m
.verifyAccount(ns
.getString("verificationCode"));
193 } catch (IOException e
) {
194 System
.err
.println("Verify error: " + e
.getMessage());
199 if (dBusConn
!= null) {
200 System
.err
.println("link is not yet implemented via dbus");
204 // When linking, username is null and we always have to create keys
205 m
.createNewIdentity();
207 String deviceName
= ns
.getString("name");
208 if (deviceName
== null) {
212 System
.out
.println(m
.getDeviceLinkUri());
213 m
.finishDeviceLink(deviceName
);
214 System
.out
.println("Associated with: " + m
.getUsername());
215 } catch (TimeoutException e
) {
216 System
.err
.println("Link request timed out, please try again.");
218 } catch (IOException e
) {
219 System
.err
.println("Link request error: " + e
.getMessage());
221 } catch (AssertionError e
) {
222 handleAssertionError(e
);
224 } catch (InvalidKeyException e
) {
227 } catch (UserAlreadyExists e
) {
228 System
.err
.println("The user " + e
.getUsername() + " already exists\nDelete \"" + e
.getFileName() + "\" before trying again.");
233 if (dBusConn
!= null) {
234 System
.err
.println("link is not yet implemented via dbus");
237 if (!m
.isRegistered()) {
238 System
.err
.println("User is not registered.");
242 m
.addDeviceLink(new URI(ns
.getString("uri")));
243 } catch (IOException e
) {
246 } catch (InvalidKeyException e
) {
249 } catch (AssertionError e
) {
250 handleAssertionError(e
);
252 } catch (URISyntaxException e
) {
258 if (dBusConn
!= null) {
259 System
.err
.println("listDevices is not yet implemented via dbus");
262 if (!m
.isRegistered()) {
263 System
.err
.println("User is not registered.");
267 List
<DeviceInfo
> devices
= m
.getLinkedDevices();
268 for (DeviceInfo d
: devices
) {
269 System
.out
.println("Device " + d
.getId() + (d
.getId() == m
.getDeviceId() ?
" (this device)" : "") + ":");
270 System
.out
.println(" Name: " + d
.getName());
271 System
.out
.println(" Created: " + formatTimestamp(d
.getCreated()));
272 System
.out
.println(" Last seen: " + formatTimestamp(d
.getLastSeen()));
274 } catch (IOException e
) {
280 if (dBusConn
!= null) {
281 System
.err
.println("removeDevice is not yet implemented via dbus");
284 if (!m
.isRegistered()) {
285 System
.err
.println("User is not registered.");
289 int deviceId
= ns
.getInt("deviceId");
290 m
.removeLinkedDevices(deviceId
);
291 } catch (IOException e
) {
297 if (dBusConn
== null && !m
.isRegistered()) {
298 System
.err
.println("User is not registered.");
302 if (ns
.getBoolean("endsession")) {
303 if (ns
.getList("recipient") == null) {
304 System
.err
.println("No recipients given");
305 System
.err
.println("Aborting sending.");
309 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
310 } catch (IOException e
) {
311 handleIOException(e
);
313 } catch (EncapsulatedExceptions e
) {
314 handleEncapsulatedExceptions(e
);
316 } catch (AssertionError e
) {
317 handleAssertionError(e
);
319 } catch (DBusExecutionException e
) {
320 handleDBusExecutionException(e
);
324 String messageText
= ns
.getString("message");
325 if (messageText
== null) {
327 messageText
= readAll(System
.in);
328 } catch (IOException e
) {
329 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
330 System
.err
.println("Aborting sending.");
336 List
<String
> attachments
= ns
.getList("attachment");
337 if (attachments
== null) {
338 attachments
= new ArrayList
<>();
340 if (ns
.getString("group") != null) {
341 byte[] groupId
= decodeGroupId(ns
.getString("group"));
342 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
344 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
346 } catch (IOException e
) {
347 handleIOException(e
);
349 } catch (EncapsulatedExceptions e
) {
350 handleEncapsulatedExceptions(e
);
352 } catch (AssertionError e
) {
353 handleAssertionError(e
);
355 } catch (GroupNotFoundException e
) {
356 handleGroupNotFoundException(e
);
358 } catch (NotAGroupMemberException e
) {
359 handleNotAGroupMemberException(e
);
361 } catch (AttachmentInvalidException e
) {
362 System
.err
.println("Failed to add attachment: " + e
.getMessage());
363 System
.err
.println("Aborting sending.");
365 } catch (DBusExecutionException e
) {
366 handleDBusExecutionException(e
);
373 if (dBusConn
!= null) {
375 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
377 public void handle(Signal
.MessageReceived s
) {
378 System
.out
.print(String
.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
379 s
.getSender(), formatTimestamp(s
.getTimestamp()), s
.getMessage()));
380 if (s
.getGroupId().length
> 0) {
381 System
.out
.println("Group info:");
382 System
.out
.println(" Id: " + Base64
.encodeBytes(s
.getGroupId()));
384 if (s
.getAttachments().size() > 0) {
385 System
.out
.println("Attachments: ");
386 for (String attachment
: s
.getAttachments()) {
387 System
.out
.println("- Stored plaintext in: " + attachment
);
390 System
.out
.println();
393 } catch (UnsatisfiedLinkError e
) {
394 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
396 } catch (DBusException e
) {
403 } catch (InterruptedException e
) {
408 if (!m
.isRegistered()) {
409 System
.err
.println("User is not registered.");
413 if (ns
.getDouble("timeout") != null) {
414 timeout
= ns
.getDouble("timeout");
416 boolean returnOnTimeout
= true;
418 returnOnTimeout
= false;
421 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
423 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, ignoreAttachments
, new ReceiveMessageHandler(m
));
424 } catch (IOException e
) {
425 System
.err
.println("Error while receiving messages: " + e
.getMessage());
427 } catch (AssertionError e
) {
428 handleAssertionError(e
);
433 if (dBusConn
!= null) {
434 System
.err
.println("quitGroup is not yet implemented via dbus");
437 if (!m
.isRegistered()) {
438 System
.err
.println("User is not registered.");
443 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
444 } catch (IOException e
) {
445 handleIOException(e
);
447 } catch (EncapsulatedExceptions e
) {
448 handleEncapsulatedExceptions(e
);
450 } catch (AssertionError e
) {
451 handleAssertionError(e
);
453 } catch (GroupNotFoundException e
) {
454 handleGroupNotFoundException(e
);
456 } catch (NotAGroupMemberException e
) {
457 handleNotAGroupMemberException(e
);
463 if (dBusConn
== null && !m
.isRegistered()) {
464 System
.err
.println("User is not registered.");
469 byte[] groupId
= null;
470 if (ns
.getString("group") != null) {
471 groupId
= decodeGroupId(ns
.getString("group"));
473 if (groupId
== null) {
474 groupId
= new byte[0];
476 String groupName
= ns
.getString("name");
477 if (groupName
== null) {
480 List
<String
> groupMembers
= ns
.<String
>getList("member");
481 if (groupMembers
== null) {
482 groupMembers
= new ArrayList
<String
>();
484 String groupAvatar
= ns
.getString("avatar");
485 if (groupAvatar
== null) {
488 byte[] newGroupId
= ts
.updateGroup(groupId
, groupName
, groupMembers
, groupAvatar
);
489 if (groupId
.length
!= newGroupId
.length
) {
490 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
492 } catch (IOException e
) {
493 handleIOException(e
);
495 } catch (AttachmentInvalidException e
) {
496 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
497 System
.err
.println("Aborting sending.");
499 } catch (GroupNotFoundException e
) {
500 handleGroupNotFoundException(e
);
502 } catch (NotAGroupMemberException e
) {
503 handleNotAGroupMemberException(e
);
505 } catch (EncapsulatedExceptions e
) {
506 handleEncapsulatedExceptions(e
);
512 if (dBusConn
!= null) {
513 System
.err
.println("listGroups is not yet implemented via dbus");
516 if (!m
.isRegistered()) {
517 System
.err
.println("User is not registered.");
521 List
<GroupInfo
> groups
= m
.getGroups();
522 boolean detailed
= ns
.getBoolean("detailed");
524 for (GroupInfo group
: groups
) {
525 printGroup(group
, detailed
);
528 case "listIdentities":
529 if (dBusConn
!= null) {
530 System
.err
.println("listIdentities is not yet implemented via dbus");
533 if (!m
.isRegistered()) {
534 System
.err
.println("User is not registered.");
537 if (ns
.get("number") == null) {
538 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
539 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
540 printIdentityFingerprint(m
, keys
.getKey(), id
);
544 String number
= ns
.getString("number");
545 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
546 printIdentityFingerprint(m
, number
, id
);
551 if (dBusConn
!= null) {
552 System
.err
.println("trust is not yet implemented via dbus");
555 if (!m
.isRegistered()) {
556 System
.err
.println("User is not registered.");
559 String number
= ns
.getString("number");
560 if (ns
.getBoolean("trust_all_known_keys")) {
561 boolean res
= m
.trustIdentityAllKeys(number
);
563 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
567 String fingerprint
= ns
.getString("verified_fingerprint");
568 if (fingerprint
!= null) {
569 fingerprint
= fingerprint
.replaceAll(" ", "");
570 if (fingerprint
.length() == 66) {
571 byte[] fingerprintBytes
;
573 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
574 } catch (Exception e
) {
575 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
578 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
580 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
583 } else if (fingerprint
.length() == 60) {
584 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
586 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.");
590 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
594 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
600 if (dBusConn
!= null) {
601 System
.err
.println("Stop it.");
604 if (!m
.isRegistered()) {
605 System
.err
.println("User is not registered.");
608 DBusConnection conn
= null;
612 if (ns
.getBoolean("system")) {
613 busType
= DBusConnection
.SYSTEM
;
615 busType
= DBusConnection
.SESSION
;
617 conn
= DBusConnection
.getConnection(busType
);
618 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
619 conn
.requestBusName(SIGNAL_BUSNAME
);
620 } catch (UnsatisfiedLinkError e
) {
621 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
623 } catch (DBusException e
) {
627 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
629 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, new DbusReceiveMessageHandler(m
, conn
));
630 } catch (IOException e
) {
631 System
.err
.println("Error while receiving messages: " + e
.getMessage());
633 } catch (AssertionError e
) {
634 handleAssertionError(e
);
647 if (dBusConn
!= null) {
648 dBusConn
.disconnect();
653 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
654 String digits
= formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.getIdentityKey()));
655 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
656 theirId
.getTrustLevel(), theirId
.getDateAdded(), Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
659 private static void printGroup(GroupInfo group
, boolean detailed
) {
661 System
.out
.println(String
.format("Id: %s Name: %s Active: %s Members: %s",
662 Base64
.encodeBytes(group
.groupId
), group
.name
, group
.active
, group
.members
));
664 System
.out
.println(String
.format("Id: %s Name: %s Active: %s", Base64
.encodeBytes(group
.groupId
),
665 group
.name
, group
.active
));
669 private static String
formatSafetyNumber(String digits
) {
670 final int partCount
= 12;
671 int partSize
= digits
.length() / partCount
;
672 StringBuilder f
= new StringBuilder(digits
.length() + partCount
);
673 for (int i
= 0; i
< partCount
; i
++) {
674 f
.append(digits
.substring(i
* partSize
, (i
* partSize
) + partSize
)).append(" ");
679 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
680 System
.err
.println("Failed to send to group: " + e
.getMessage());
681 System
.err
.println("Aborting sending.");
684 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
685 System
.err
.println("Failed to send to group: " + e
.getMessage());
686 System
.err
.println("Update the group on another device to readd the user to this group.");
687 System
.err
.println("Aborting sending.");
691 private static void handleDBusExecutionException(DBusExecutionException e
) {
692 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
693 System
.err
.println("Aborting.");
696 private static byte[] decodeGroupId(String groupId
) {
698 return Base64
.decode(groupId
);
699 } catch (IOException e
) {
700 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
701 System
.err
.println("Aborting sending.");
707 private static Namespace
parseArgs(String
[] args
) {
708 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("signal-cli")
710 .description("Commandline interface for Signal.")
711 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
713 parser
.addArgument("-v", "--version")
714 .help("Show package version.")
715 .action(Arguments
.version());
716 parser
.addArgument("--config")
717 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
719 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
720 mut
.addArgument("-u", "--username")
721 .help("Specify your phone number, that will be used for verification.");
722 mut
.addArgument("--dbus")
723 .help("Make request via user dbus.")
724 .action(Arguments
.storeTrue());
725 mut
.addArgument("--dbus-system")
726 .help("Make request via system dbus.")
727 .action(Arguments
.storeTrue());
729 Subparsers subparsers
= parser
.addSubparsers()
730 .title("subcommands")
732 .description("valid subcommands")
733 .help("additional help");
735 Subparser parserLink
= subparsers
.addParser("link");
736 parserLink
.addArgument("-n", "--name")
737 .help("Specify a name to describe this new device.");
739 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
740 parserAddDevice
.addArgument("--uri")
742 .help("Specify the uri contained in the QR code shown by the new device.");
744 Subparser parserDevices
= subparsers
.addParser("listDevices");
746 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
747 parserRemoveDevice
.addArgument("-d", "--deviceId")
750 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
752 Subparser parserRegister
= subparsers
.addParser("register");
753 parserRegister
.addArgument("-v", "--voice")
754 .help("The verification should be done over voice, not sms.")
755 .action(Arguments
.storeTrue());
757 Subparser parserUnregister
= subparsers
.addParser("unregister");
758 parserUnregister
.help("Unregister the current device from the signal server.");
760 Subparser parserUpdateAccount
= subparsers
.addParser("updateAccount");
761 parserUpdateAccount
.help("Update the account attributes on the signal server.");
763 Subparser parserVerify
= subparsers
.addParser("verify");
764 parserVerify
.addArgument("verificationCode")
765 .help("The verification code you received via sms or voice call.");
767 Subparser parserSend
= subparsers
.addParser("send");
768 parserSend
.addArgument("-g", "--group")
769 .help("Specify the recipient group ID.");
770 parserSend
.addArgument("recipient")
771 .help("Specify the recipients' phone number.")
773 parserSend
.addArgument("-m", "--message")
774 .help("Specify the message, if missing standard input is used.");
775 parserSend
.addArgument("-a", "--attachment")
777 .help("Add file as attachment");
778 parserSend
.addArgument("-e", "--endsession")
779 .help("Clear session state and send end session message.")
780 .action(Arguments
.storeTrue());
782 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
783 parserLeaveGroup
.addArgument("-g", "--group")
785 .help("Specify the recipient group ID.");
787 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
788 parserUpdateGroup
.addArgument("-g", "--group")
789 .help("Specify the recipient group ID.");
790 parserUpdateGroup
.addArgument("-n", "--name")
791 .help("Specify the new group name.");
792 parserUpdateGroup
.addArgument("-a", "--avatar")
793 .help("Specify a new group avatar image file");
794 parserUpdateGroup
.addArgument("-m", "--member")
796 .help("Specify one or more members to add to the group");
798 Subparser parserListGroups
= subparsers
.addParser("listGroups");
799 parserListGroups
.addArgument("-d", "--detailed").action(Arguments
.storeTrue())
800 .help("List members of each group");
801 parserListGroups
.help("List group name and ids");
803 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
804 parserListIdentities
.addArgument("-n", "--number")
805 .help("Only show identity keys for the given phone number.");
807 Subparser parserTrust
= subparsers
.addParser("trust");
808 parserTrust
.addArgument("number")
809 .help("Specify the phone number, for which to set the trust.")
811 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
812 mutTrust
.addArgument("-a", "--trust-all-known-keys")
813 .help("Trust all known keys of this user, only use this for testing.")
814 .action(Arguments
.storeTrue());
815 mutTrust
.addArgument("-v", "--verified-fingerprint")
816 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
818 Subparser parserReceive
= subparsers
.addParser("receive");
819 parserReceive
.addArgument("-t", "--timeout")
821 .help("Number of seconds to wait for new messages (negative values disable timeout)");
822 parserReceive
.addArgument("--ignore-attachments")
823 .help("Don’t download attachments of received messages.")
824 .action(Arguments
.storeTrue());
826 Subparser parserDaemon
= subparsers
.addParser("daemon");
827 parserDaemon
.addArgument("--system")
828 .action(Arguments
.storeTrue())
829 .help("Use DBus system bus instead of user bus.");
830 parserDaemon
.addArgument("--ignore-attachments")
831 .help("Don’t download attachments of received messages.")
832 .action(Arguments
.storeTrue());
835 Namespace ns
= parser
.parseArgs(args
);
836 if ("link".equals(ns
.getString("command"))) {
837 if (ns
.getString("username") != null) {
839 System
.err
.println("You cannot specify a username (phone number) when linking");
842 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
843 if (ns
.getString("username") == null) {
845 System
.err
.println("You need to specify a username (phone number)");
848 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
849 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
853 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
854 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
858 } catch (ArgumentParserException e
) {
859 parser
.handleError(e
);
864 private static void handleAssertionError(AssertionError e
) {
865 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
867 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
870 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
871 System
.err
.println("Failed to send (some) messages:");
872 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
873 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
875 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
876 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
878 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
879 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
883 private static void handleIOException(IOException e
) {
884 System
.err
.println("Failed to send message: " + e
.getMessage());
887 private static String
readAll(InputStream
in) throws IOException
{
888 StringWriter output
= new StringWriter();
889 byte[] buffer
= new byte[4096];
892 while (-1 != (n
= System
.in.read(buffer
))) {
893 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
896 return output
.toString();
899 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
902 public ReceiveMessageHandler(Manager m
) {
907 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
908 SignalServiceAddress source
= envelope
.getSourceAddress();
909 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
910 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
911 if (source
.getRelay().isPresent()) {
912 System
.out
.println("Relayed by: " + source
.getRelay().get());
914 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
916 if (envelope
.isReceipt()) {
917 System
.out
.println("Got receipt.");
918 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
919 if (exception
!= null) {
920 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
921 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
922 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
923 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");
924 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");
926 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
929 if (content
== null) {
930 System
.out
.println("Failed to decrypt message.");
932 if (content
.getDataMessage().isPresent()) {
933 SignalServiceDataMessage message
= content
.getDataMessage().get();
934 handleSignalServiceDataMessage(message
);
936 if (content
.getSyncMessage().isPresent()) {
937 System
.out
.println("Received a sync message");
938 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
940 if (syncMessage
.getContacts().isPresent()) {
941 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
942 if (contactsMessage
.isComplete()) {
943 System
.out
.println("Received complete sync contacts");
945 System
.out
.println("Received sync contacts");
947 printAttachment(contactsMessage
.getContactsStream());
949 if (syncMessage
.getGroups().isPresent()) {
950 System
.out
.println("Received sync groups");
951 printAttachment(syncMessage
.getGroups().get());
953 if (syncMessage
.getRead().isPresent()) {
954 System
.out
.println("Received sync read messages list");
955 for (ReadMessage rm
: syncMessage
.getRead().get()) {
956 ContactInfo fromContact
= m
.getContact(rm
.getSender());
957 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + formatTimestamp(rm
.getTimestamp()));
960 if (syncMessage
.getRequest().isPresent()) {
961 System
.out
.println("Received sync request");
962 if (syncMessage
.getRequest().get().isContactsRequest()) {
963 System
.out
.println(" - contacts request");
965 if (syncMessage
.getRequest().get().isGroupsRequest()) {
966 System
.out
.println(" - groups request");
969 if (syncMessage
.getSent().isPresent()) {
970 System
.out
.println("Received sync sent message");
971 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
973 if (sentTranscriptMessage
.getDestination().isPresent()) {
974 String dest
= sentTranscriptMessage
.getDestination().get();
975 ContactInfo destContact
= m
.getContact(dest
);
976 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
980 System
.out
.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage
.getTimestamp()));
981 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
982 System
.out
.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
984 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
985 handleSignalServiceDataMessage(message
);
987 if (syncMessage
.getBlockedList().isPresent()) {
988 System
.out
.println("Received sync message with block list");
989 System
.out
.println("Blocked numbers:");
990 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
991 for (String number
: blockedList
.getNumbers()) {
992 System
.out
.println(" - " + number
);
995 if (syncMessage
.getVerified().isPresent()) {
996 System
.out
.println("Received sync message with verified identities:");
997 final List
<VerifiedMessage
> verifiedList
= syncMessage
.getVerified().get();
998 for (VerifiedMessage v
: verifiedList
) {
999 System
.out
.println(" - " + v
.getDestination() + ": " + v
.getVerified());
1000 String safetyNumber
= formatSafetyNumber(m
.computeSafetyNumber(v
.getDestination(), v
.getIdentityKey()));
1001 System
.out
.println(" " + safetyNumber
);
1008 System
.out
.println("Unknown message received.");
1010 System
.out
.println();
1013 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
1014 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
1016 if (message
.getBody().isPresent()) {
1017 System
.out
.println("Body: " + message
.getBody().get());
1019 if (message
.getGroupInfo().isPresent()) {
1020 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1021 System
.out
.println("Group info:");
1022 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
1023 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
1024 System
.out
.println(" Name: " + groupInfo
.getName().get());
1026 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
1027 if (group
!= null) {
1028 System
.out
.println(" Name: " + group
.name
);
1030 System
.out
.println(" Name: <Unknown group>");
1033 System
.out
.println(" Type: " + groupInfo
.getType());
1034 if (groupInfo
.getMembers().isPresent()) {
1035 for (String member
: groupInfo
.getMembers().get()) {
1036 System
.out
.println(" Member: " + member
);
1039 if (groupInfo
.getAvatar().isPresent()) {
1040 System
.out
.println(" Avatar:");
1041 printAttachment(groupInfo
.getAvatar().get());
1044 if (message
.isEndSession()) {
1045 System
.out
.println("Is end session");
1047 if (message
.isExpirationUpdate()) {
1048 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
1050 if (message
.getExpiresInSeconds() > 0) {
1051 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
1054 if (message
.getAttachments().isPresent()) {
1055 System
.out
.println("Attachments: ");
1056 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1057 printAttachment(attachment
);
1062 private void printAttachment(SignalServiceAttachment attachment
) {
1063 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
1064 if (attachment
.isPointer()) {
1065 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1066 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
1067 System
.out
.println(" Filename: " + (pointer
.getFileName().isPresent() ? pointer
.getFileName().get() : "-"));
1068 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
1069 System
.out
.println(" Voice note: " + (pointer
.getVoiceNote() ?
"yes" : "no"));
1070 File file
= m
.getAttachmentFile(pointer
.getId());
1071 if (file
.exists()) {
1072 System
.out
.println(" Stored plaintext in: " + file
);
1078 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
1079 final DBusConnection conn
;
1081 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1087 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1088 super.handleMessage(envelope
, content
, exception
);
1090 if (!envelope
.isReceipt() && content
!= null && content
.getDataMessage().isPresent()) {
1091 SignalServiceDataMessage message
= content
.getDataMessage().get();
1093 if (!message
.isEndSession() &&
1094 !(message
.getGroupInfo().isPresent() &&
1095 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
1096 List
<String
> attachments
= new ArrayList
<>();
1097 if (message
.getAttachments().isPresent()) {
1098 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1099 if (attachment
.isPointer()) {
1100 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
1106 conn
.sendSignal(new Signal
.MessageReceived(
1108 message
.getTimestamp(),
1109 envelope
.getSource(),
1110 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1111 message
.getBody().isPresent() ? message
.getBody().get() : "",
1113 } catch (DBusException e
) {
1114 e
.printStackTrace();
1122 private static String
formatTimestamp(long timestamp
) {
1123 Date date
= new Date(timestamp
);
1124 final DateFormat df
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
1125 df
.setTimeZone(tzUTC
);
1126 return timestamp
+ " (" + df
.format(date
) + ")";