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
.freedesktop
.dbus
.DBusConnection
;
25 import org
.freedesktop
.dbus
.DBusSigHandler
;
26 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
27 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
28 import org
.whispersystems
.libsignal
.InvalidKeyException
;
29 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
30 import org
.whispersystems
.signalservice
.api
.messages
.*;
31 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
32 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
33 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
34 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
35 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
36 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
39 import java
.io
.IOException
;
40 import java
.io
.InputStream
;
41 import java
.io
.StringWriter
;
43 import java
.net
.URISyntaxException
;
44 import java
.nio
.charset
.Charset
;
45 import java
.security
.Security
;
46 import java
.text
.DateFormat
;
47 import java
.text
.SimpleDateFormat
;
49 import java
.util
.concurrent
.TimeUnit
;
50 import java
.util
.concurrent
.TimeoutException
;
54 public static final String SIGNAL_BUSNAME
= "org.asamk.Signal";
55 public static final String SIGNAL_OBJECTPATH
= "/org/asamk/Signal";
57 private static final TimeZone tzUTC
= TimeZone
.getTimeZone("UTC");
59 public static void main(String
[] args
) {
60 // Workaround for BKS truststore
61 Security
.insertProviderAt(new org
.bouncycastle
.jce
.provider
.BouncyCastleProvider(), 1);
63 Namespace ns
= parseArgs(args
);
68 int res
= handleCommands(ns
);
72 private static int handleCommands(Namespace ns
) {
73 final String username
= ns
.getString("username");
76 DBusConnection dBusConn
= null;
78 if (ns
.getBoolean("dbus") || ns
.getBoolean("dbus_system")) {
82 if (ns
.getBoolean("dbus_system")) {
83 busType
= DBusConnection
.SYSTEM
;
85 busType
= DBusConnection
.SESSION
;
87 dBusConn
= DBusConnection
.getConnection(busType
);
88 ts
= (Signal
) dBusConn
.getRemoteObject(
89 SIGNAL_BUSNAME
, SIGNAL_OBJECTPATH
,
91 } catch (UnsatisfiedLinkError e
) {
92 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
94 } catch (DBusException e
) {
96 if (dBusConn
!= null) {
97 dBusConn
.disconnect();
102 String settingsPath
= ns
.getString("config");
103 if (TextUtils
.isEmpty(settingsPath
)) {
104 settingsPath
= System
.getProperty("user.home") + "/.config/signal";
105 if (!new File(settingsPath
).exists()) {
106 String legacySettingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
107 if (new File(legacySettingsPath
).exists()) {
108 settingsPath
= legacySettingsPath
;
113 m
= new Manager(username
, settingsPath
);
115 if (m
.userExists()) {
118 } catch (Exception e
) {
119 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
125 switch (ns
.getString("command")) {
127 if (dBusConn
!= null) {
128 System
.err
.println("register is not yet implemented via dbus");
131 if (!m
.userHasKeys()) {
132 m
.createNewIdentity();
135 m
.register(ns
.getBoolean("voice"));
136 } catch (IOException e
) {
137 System
.err
.println("Request verify error: " + e
.getMessage());
142 if (dBusConn
!= null) {
143 System
.err
.println("unregister is not yet implemented via dbus");
146 if (!m
.isRegistered()) {
147 System
.err
.println("User is not registered.");
152 } catch (IOException e
) {
153 System
.err
.println("Unregister error: " + e
.getMessage());
157 case "updateAccount":
158 if (dBusConn
!= null) {
159 System
.err
.println("updateAccount is not yet implemented via dbus");
162 if (!m
.isRegistered()) {
163 System
.err
.println("User is not registered.");
167 m
.updateAccountAttributes();
168 } catch (IOException e
) {
169 System
.err
.println("UpdateAccount error: " + e
.getMessage());
174 if (dBusConn
!= null) {
175 System
.err
.println("verify is not yet implemented via dbus");
178 if (!m
.userHasKeys()) {
179 System
.err
.println("User has no keys, first call register.");
182 if (m
.isRegistered()) {
183 System
.err
.println("User registration is already verified");
187 m
.verifyAccount(ns
.getString("verificationCode"));
188 } catch (IOException e
) {
189 System
.err
.println("Verify error: " + e
.getMessage());
194 if (dBusConn
!= null) {
195 System
.err
.println("link is not yet implemented via dbus");
199 // When linking, username is null and we always have to create keys
200 m
.createNewIdentity();
202 String deviceName
= ns
.getString("name");
203 if (deviceName
== null) {
207 System
.out
.println(m
.getDeviceLinkUri());
208 m
.finishDeviceLink(deviceName
);
209 System
.out
.println("Associated with: " + m
.getUsername());
210 } catch (TimeoutException e
) {
211 System
.err
.println("Link request timed out, please try again.");
213 } catch (IOException e
) {
214 System
.err
.println("Link request error: " + e
.getMessage());
216 } catch (AssertionError e
) {
217 handleAssertionError(e
);
219 } catch (InvalidKeyException e
) {
222 } catch (UserAlreadyExists e
) {
223 System
.err
.println("The user " + e
.getUsername() + " already exists\nDelete \"" + e
.getFileName() + "\" before trying again.");
228 if (dBusConn
!= null) {
229 System
.err
.println("link is not yet implemented via dbus");
232 if (!m
.isRegistered()) {
233 System
.err
.println("User is not registered.");
237 m
.addDeviceLink(new URI(ns
.getString("uri")));
238 } catch (IOException e
) {
241 } catch (InvalidKeyException e
) {
244 } catch (AssertionError e
) {
245 handleAssertionError(e
);
247 } catch (URISyntaxException e
) {
253 if (dBusConn
!= null) {
254 System
.err
.println("listDevices is not yet implemented via dbus");
257 if (!m
.isRegistered()) {
258 System
.err
.println("User is not registered.");
262 List
<DeviceInfo
> devices
= m
.getLinkedDevices();
263 for (DeviceInfo d
: devices
) {
264 System
.out
.println("Device " + d
.getId() + (d
.getId() == m
.getDeviceId() ?
" (this device)" : "") + ":");
265 System
.out
.println(" Name: " + d
.getName());
266 System
.out
.println(" Created: " + formatTimestamp(d
.getCreated()));
267 System
.out
.println(" Last seen: " + formatTimestamp(d
.getLastSeen()));
269 } catch (IOException e
) {
275 if (dBusConn
!= null) {
276 System
.err
.println("removeDevice is not yet implemented via dbus");
279 if (!m
.isRegistered()) {
280 System
.err
.println("User is not registered.");
284 int deviceId
= ns
.getInt("deviceId");
285 m
.removeLinkedDevices(deviceId
);
286 } catch (IOException e
) {
292 if (dBusConn
== null && !m
.isRegistered()) {
293 System
.err
.println("User is not registered.");
297 if (ns
.getBoolean("endsession")) {
298 if (ns
.getList("recipient") == null) {
299 System
.err
.println("No recipients given");
300 System
.err
.println("Aborting sending.");
304 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
305 } catch (IOException e
) {
306 handleIOException(e
);
308 } catch (EncapsulatedExceptions e
) {
309 handleEncapsulatedExceptions(e
);
311 } catch (AssertionError e
) {
312 handleAssertionError(e
);
314 } catch (DBusExecutionException e
) {
315 handleDBusExecutionException(e
);
319 String messageText
= ns
.getString("message");
320 if (messageText
== null) {
322 messageText
= readAll(System
.in);
323 } catch (IOException e
) {
324 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
325 System
.err
.println("Aborting sending.");
331 List
<String
> attachments
= ns
.getList("attachment");
332 if (attachments
== null) {
333 attachments
= new ArrayList
<>();
335 if (ns
.getString("group") != null) {
336 byte[] groupId
= decodeGroupId(ns
.getString("group"));
337 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
339 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
341 } catch (IOException e
) {
342 handleIOException(e
);
344 } catch (EncapsulatedExceptions e
) {
345 handleEncapsulatedExceptions(e
);
347 } catch (AssertionError e
) {
348 handleAssertionError(e
);
350 } catch (GroupNotFoundException e
) {
351 handleGroupNotFoundException(e
);
353 } catch (NotAGroupMemberException e
) {
354 handleNotAGroupMemberException(e
);
356 } catch (AttachmentInvalidException e
) {
357 System
.err
.println("Failed to add attachment: " + e
.getMessage());
358 System
.err
.println("Aborting sending.");
360 } catch (DBusExecutionException e
) {
361 handleDBusExecutionException(e
);
368 if (dBusConn
!= null) {
370 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
372 public void handle(Signal
.MessageReceived s
) {
373 System
.out
.print(String
.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
374 s
.getSender(), formatTimestamp(s
.getTimestamp()), s
.getMessage()));
375 if (s
.getGroupId().length
> 0) {
376 System
.out
.println("Group info:");
377 System
.out
.println(" Id: " + Base64
.encodeBytes(s
.getGroupId()));
379 if (s
.getAttachments().size() > 0) {
380 System
.out
.println("Attachments: ");
381 for (String attachment
: s
.getAttachments()) {
382 System
.out
.println("- Stored plaintext in: " + attachment
);
385 System
.out
.println();
388 } catch (UnsatisfiedLinkError e
) {
389 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
391 } catch (DBusException e
) {
398 } catch (InterruptedException e
) {
403 if (!m
.isRegistered()) {
404 System
.err
.println("User is not registered.");
408 if (ns
.getDouble("timeout") != null) {
409 timeout
= ns
.getDouble("timeout");
411 boolean returnOnTimeout
= true;
413 returnOnTimeout
= false;
416 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
418 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, ignoreAttachments
, new ReceiveMessageHandler(m
));
419 } catch (IOException e
) {
420 System
.err
.println("Error while receiving messages: " + e
.getMessage());
422 } catch (AssertionError e
) {
423 handleAssertionError(e
);
428 if (dBusConn
!= null) {
429 System
.err
.println("quitGroup is not yet implemented via dbus");
432 if (!m
.isRegistered()) {
433 System
.err
.println("User is not registered.");
438 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
439 } catch (IOException e
) {
440 handleIOException(e
);
442 } catch (EncapsulatedExceptions e
) {
443 handleEncapsulatedExceptions(e
);
445 } catch (AssertionError e
) {
446 handleAssertionError(e
);
448 } catch (GroupNotFoundException e
) {
449 handleGroupNotFoundException(e
);
451 } catch (NotAGroupMemberException e
) {
452 handleNotAGroupMemberException(e
);
458 if (dBusConn
!= null) {
459 System
.err
.println("updateGroup is not yet implemented via dbus");
462 if (!m
.isRegistered()) {
463 System
.err
.println("User is not registered.");
468 byte[] groupId
= null;
469 if (ns
.getString("group") != null) {
470 groupId
= decodeGroupId(ns
.getString("group"));
472 byte[] newGroupId
= m
.sendUpdateGroupMessage(groupId
, ns
.getString("name"), ns
.<String
>getList("member"), ns
.getString("avatar"));
473 if (groupId
== null) {
474 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
476 } catch (IOException e
) {
477 handleIOException(e
);
479 } catch (AttachmentInvalidException e
) {
480 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
481 System
.err
.println("Aborting sending.");
483 } catch (GroupNotFoundException e
) {
484 handleGroupNotFoundException(e
);
486 } catch (NotAGroupMemberException e
) {
487 handleNotAGroupMemberException(e
);
489 } catch (EncapsulatedExceptions e
) {
490 handleEncapsulatedExceptions(e
);
496 if (dBusConn
!= null) {
497 System
.err
.println("listGroups is not yet implemented via dbus");
500 if (!m
.isRegistered()) {
501 System
.err
.println("User is not registered.");
505 List
<GroupInfo
> groups
= m
.getGroups();
506 boolean detailed
= ns
.getBoolean("detailed");
508 for (GroupInfo group
: groups
) {
509 printGroup(group
, detailed
);
512 case "listIdentities":
513 if (dBusConn
!= null) {
514 System
.err
.println("listIdentities is not yet implemented via dbus");
517 if (!m
.isRegistered()) {
518 System
.err
.println("User is not registered.");
521 if (ns
.get("number") == null) {
522 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
523 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
524 printIdentityFingerprint(m
, keys
.getKey(), id
);
528 String number
= ns
.getString("number");
529 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
530 printIdentityFingerprint(m
, number
, id
);
535 if (dBusConn
!= null) {
536 System
.err
.println("trust is not yet implemented via dbus");
539 if (!m
.isRegistered()) {
540 System
.err
.println("User is not registered.");
543 String number
= ns
.getString("number");
544 if (ns
.getBoolean("trust_all_known_keys")) {
545 boolean res
= m
.trustIdentityAllKeys(number
);
547 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
551 String fingerprint
= ns
.getString("verified_fingerprint");
552 if (fingerprint
!= null) {
553 fingerprint
= fingerprint
.replaceAll(" ", "");
554 if (fingerprint
.length() == 66) {
555 byte[] fingerprintBytes
;
557 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
558 } catch (Exception e
) {
559 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
562 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
564 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
567 } else if (fingerprint
.length() == 60) {
568 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
570 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.");
574 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
578 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
584 if (dBusConn
!= null) {
585 System
.err
.println("Stop it.");
588 if (!m
.isRegistered()) {
589 System
.err
.println("User is not registered.");
592 DBusConnection conn
= null;
596 if (ns
.getBoolean("system")) {
597 busType
= DBusConnection
.SYSTEM
;
599 busType
= DBusConnection
.SESSION
;
601 conn
= DBusConnection
.getConnection(busType
);
602 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
603 conn
.requestBusName(SIGNAL_BUSNAME
);
604 } catch (UnsatisfiedLinkError e
) {
605 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
607 } catch (DBusException e
) {
611 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
613 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, new DbusReceiveMessageHandler(m
, conn
));
614 } catch (IOException e
) {
615 System
.err
.println("Error while receiving messages: " + e
.getMessage());
617 } catch (AssertionError e
) {
618 handleAssertionError(e
);
631 if (dBusConn
!= null) {
632 dBusConn
.disconnect();
637 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
638 String digits
= formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.identityKey
));
639 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
640 theirId
.trustLevel
, theirId
.added
, Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
643 private static void printGroup(GroupInfo group
, boolean detailed
) {
645 System
.out
.println(String
.format("Id: %s Name: %s Active: %s Members: %s",
646 Base64
.encodeBytes(group
.groupId
), group
.name
, group
.active
, group
.members
));
648 System
.out
.println(String
.format("Id: %s Name: %s Active: %s", Base64
.encodeBytes(group
.groupId
),
649 group
.name
, group
.active
));
653 private static String
formatSafetyNumber(String digits
) {
654 final int partCount
= 12;
655 int partSize
= digits
.length() / partCount
;
656 StringBuilder f
= new StringBuilder(digits
.length() + partCount
);
657 for (int i
= 0; i
< partCount
; i
++) {
658 f
.append(digits
.substring(i
* partSize
, (i
* partSize
) + partSize
)).append(" ");
663 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
664 System
.err
.println("Failed to send to group: " + e
.getMessage());
665 System
.err
.println("Aborting sending.");
668 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
669 System
.err
.println("Failed to send to group: " + e
.getMessage());
670 System
.err
.println("Update the group on another device to readd the user to this group.");
671 System
.err
.println("Aborting sending.");
675 private static void handleDBusExecutionException(DBusExecutionException e
) {
676 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
677 System
.err
.println("Aborting.");
680 private static byte[] decodeGroupId(String groupId
) {
682 return Base64
.decode(groupId
);
683 } catch (IOException e
) {
684 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
685 System
.err
.println("Aborting sending.");
691 private static Namespace
parseArgs(String
[] args
) {
692 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("signal-cli")
694 .description("Commandline interface for Signal.")
695 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
697 parser
.addArgument("-v", "--version")
698 .help("Show package version.")
699 .action(Arguments
.version());
700 parser
.addArgument("--config")
701 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
703 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
704 mut
.addArgument("-u", "--username")
705 .help("Specify your phone number, that will be used for verification.");
706 mut
.addArgument("--dbus")
707 .help("Make request via user dbus.")
708 .action(Arguments
.storeTrue());
709 mut
.addArgument("--dbus-system")
710 .help("Make request via system dbus.")
711 .action(Arguments
.storeTrue());
713 Subparsers subparsers
= parser
.addSubparsers()
714 .title("subcommands")
716 .description("valid subcommands")
717 .help("additional help");
719 Subparser parserLink
= subparsers
.addParser("link");
720 parserLink
.addArgument("-n", "--name")
721 .help("Specify a name to describe this new device.");
723 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
724 parserAddDevice
.addArgument("--uri")
726 .help("Specify the uri contained in the QR code shown by the new device.");
728 Subparser parserDevices
= subparsers
.addParser("listDevices");
730 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
731 parserRemoveDevice
.addArgument("-d", "--deviceId")
734 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
736 Subparser parserRegister
= subparsers
.addParser("register");
737 parserRegister
.addArgument("-v", "--voice")
738 .help("The verification should be done over voice, not sms.")
739 .action(Arguments
.storeTrue());
741 Subparser parserUnregister
= subparsers
.addParser("unregister");
742 parserUnregister
.help("Unregister the current device from the signal server.");
744 Subparser parserUpdateAccount
= subparsers
.addParser("updateAccount");
745 parserUpdateAccount
.help("Update the account attributes on the signal server.");
747 Subparser parserVerify
= subparsers
.addParser("verify");
748 parserVerify
.addArgument("verificationCode")
749 .help("The verification code you received via sms or voice call.");
751 Subparser parserSend
= subparsers
.addParser("send");
752 parserSend
.addArgument("-g", "--group")
753 .help("Specify the recipient group ID.");
754 parserSend
.addArgument("recipient")
755 .help("Specify the recipients' phone number.")
757 parserSend
.addArgument("-m", "--message")
758 .help("Specify the message, if missing standard input is used.");
759 parserSend
.addArgument("-a", "--attachment")
761 .help("Add file as attachment");
762 parserSend
.addArgument("-e", "--endsession")
763 .help("Clear session state and send end session message.")
764 .action(Arguments
.storeTrue());
766 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
767 parserLeaveGroup
.addArgument("-g", "--group")
769 .help("Specify the recipient group ID.");
771 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
772 parserUpdateGroup
.addArgument("-g", "--group")
773 .help("Specify the recipient group ID.");
774 parserUpdateGroup
.addArgument("-n", "--name")
775 .help("Specify the new group name.");
776 parserUpdateGroup
.addArgument("-a", "--avatar")
777 .help("Specify a new group avatar image file");
778 parserUpdateGroup
.addArgument("-m", "--member")
780 .help("Specify one or more members to add to the group");
782 Subparser parserListGroups
= subparsers
.addParser("listGroups");
783 parserListGroups
.addArgument("-d", "--detailed").action(Arguments
.storeTrue())
784 .help("List members of each group");
785 parserListGroups
.help("List group name and ids");
787 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
788 parserListIdentities
.addArgument("-n", "--number")
789 .help("Only show identity keys for the given phone number.");
791 Subparser parserTrust
= subparsers
.addParser("trust");
792 parserTrust
.addArgument("number")
793 .help("Specify the phone number, for which to set the trust.")
795 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
796 mutTrust
.addArgument("-a", "--trust-all-known-keys")
797 .help("Trust all known keys of this user, only use this for testing.")
798 .action(Arguments
.storeTrue());
799 mutTrust
.addArgument("-v", "--verified-fingerprint")
800 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
802 Subparser parserReceive
= subparsers
.addParser("receive");
803 parserReceive
.addArgument("-t", "--timeout")
805 .help("Number of seconds to wait for new messages (negative values disable timeout)");
806 parserReceive
.addArgument("--ignore-attachments")
807 .help("Don’t download attachments of received messages.")
808 .action(Arguments
.storeTrue());
810 Subparser parserDaemon
= subparsers
.addParser("daemon");
811 parserDaemon
.addArgument("--system")
812 .action(Arguments
.storeTrue())
813 .help("Use DBus system bus instead of user bus.");
814 parserDaemon
.addArgument("--ignore-attachments")
815 .help("Don’t download attachments of received messages.")
816 .action(Arguments
.storeTrue());
819 Namespace ns
= parser
.parseArgs(args
);
820 if ("link".equals(ns
.getString("command"))) {
821 if (ns
.getString("username") != null) {
823 System
.err
.println("You cannot specify a username (phone number) when linking");
826 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
827 if (ns
.getString("username") == null) {
829 System
.err
.println("You need to specify a username (phone number)");
832 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
833 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
837 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
838 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
842 } catch (ArgumentParserException e
) {
843 parser
.handleError(e
);
848 private static void handleAssertionError(AssertionError e
) {
849 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
851 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
854 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
855 System
.err
.println("Failed to send (some) messages:");
856 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
857 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
859 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
860 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
862 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
863 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
867 private static void handleIOException(IOException e
) {
868 System
.err
.println("Failed to send message: " + e
.getMessage());
871 private static String
readAll(InputStream
in) throws IOException
{
872 StringWriter output
= new StringWriter();
873 byte[] buffer
= new byte[4096];
876 while (-1 != (n
= System
.in.read(buffer
))) {
877 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
880 return output
.toString();
883 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
886 public ReceiveMessageHandler(Manager m
) {
891 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
892 SignalServiceAddress source
= envelope
.getSourceAddress();
893 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
894 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
895 if (source
.getRelay().isPresent()) {
896 System
.out
.println("Relayed by: " + source
.getRelay().get());
898 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
900 if (envelope
.isReceipt()) {
901 System
.out
.println("Got receipt.");
902 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
903 if (exception
!= null) {
904 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
905 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
906 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
907 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");
908 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");
910 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
913 if (content
== null) {
914 System
.out
.println("Failed to decrypt message.");
916 if (content
.getDataMessage().isPresent()) {
917 SignalServiceDataMessage message
= content
.getDataMessage().get();
918 handleSignalServiceDataMessage(message
);
920 if (content
.getSyncMessage().isPresent()) {
921 System
.out
.println("Received a sync message");
922 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
924 if (syncMessage
.getContacts().isPresent()) {
925 System
.out
.println("Received sync contacts");
926 printAttachment(syncMessage
.getContacts().get());
928 if (syncMessage
.getGroups().isPresent()) {
929 System
.out
.println("Received sync groups");
930 printAttachment(syncMessage
.getGroups().get());
932 if (syncMessage
.getRead().isPresent()) {
933 System
.out
.println("Received sync read messages list");
934 for (ReadMessage rm
: syncMessage
.getRead().get()) {
935 ContactInfo fromContact
= m
.getContact(rm
.getSender());
936 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + formatTimestamp(rm
.getTimestamp()));
939 if (syncMessage
.getRequest().isPresent()) {
940 System
.out
.println("Received sync request");
941 if (syncMessage
.getRequest().get().isContactsRequest()) {
942 System
.out
.println(" - contacts request");
944 if (syncMessage
.getRequest().get().isGroupsRequest()) {
945 System
.out
.println(" - groups request");
948 if (syncMessage
.getSent().isPresent()) {
949 System
.out
.println("Received sync sent message");
950 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
952 if (sentTranscriptMessage
.getDestination().isPresent()) {
953 String dest
= sentTranscriptMessage
.getDestination().get();
954 ContactInfo destContact
= m
.getContact(dest
);
955 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
959 System
.out
.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage
.getTimestamp()));
960 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
961 System
.out
.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
963 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
964 handleSignalServiceDataMessage(message
);
966 if (syncMessage
.getBlockedList().isPresent()) {
967 System
.out
.println("Received sync message with block list");
968 System
.out
.println("Blocked numbers:");
969 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
970 for (String number
: blockedList
.getNumbers()) {
971 System
.out
.println(" - " + number
);
977 System
.out
.println("Unknown message received.");
979 System
.out
.println();
982 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
983 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
985 if (message
.getBody().isPresent()) {
986 System
.out
.println("Body: " + message
.getBody().get());
988 if (message
.getGroupInfo().isPresent()) {
989 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
990 System
.out
.println("Group info:");
991 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
992 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
993 System
.out
.println(" Name: " + groupInfo
.getName().get());
995 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
997 System
.out
.println(" Name: " + group
.name
);
999 System
.out
.println(" Name: <Unknown group>");
1002 System
.out
.println(" Type: " + groupInfo
.getType());
1003 if (groupInfo
.getMembers().isPresent()) {
1004 for (String member
: groupInfo
.getMembers().get()) {
1005 System
.out
.println(" Member: " + member
);
1008 if (groupInfo
.getAvatar().isPresent()) {
1009 System
.out
.println(" Avatar:");
1010 printAttachment(groupInfo
.getAvatar().get());
1013 if (message
.isEndSession()) {
1014 System
.out
.println("Is end session");
1016 if (message
.isExpirationUpdate()) {
1017 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
1019 if (message
.getExpiresInSeconds() > 0) {
1020 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
1023 if (message
.getAttachments().isPresent()) {
1024 System
.out
.println("Attachments: ");
1025 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1026 printAttachment(attachment
);
1031 private void printAttachment(SignalServiceAttachment attachment
) {
1032 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
1033 if (attachment
.isPointer()) {
1034 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1035 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
1036 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
1037 File file
= m
.getAttachmentFile(pointer
.getId());
1038 if (file
.exists()) {
1039 System
.out
.println(" Stored plaintext in: " + file
);
1045 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
1046 final DBusConnection conn
;
1048 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1054 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1055 super.handleMessage(envelope
, content
, exception
);
1057 if (!envelope
.isReceipt() && content
!= null && content
.getDataMessage().isPresent()) {
1058 SignalServiceDataMessage message
= content
.getDataMessage().get();
1060 if (!message
.isEndSession() &&
1061 !(message
.getGroupInfo().isPresent() &&
1062 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
1063 List
<String
> attachments
= new ArrayList
<>();
1064 if (message
.getAttachments().isPresent()) {
1065 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1066 if (attachment
.isPointer()) {
1067 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
1073 conn
.sendSignal(new Signal
.MessageReceived(
1075 message
.getTimestamp(),
1076 envelope
.getSource(),
1077 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1078 message
.getBody().isPresent() ? message
.getBody().get() : "",
1080 } catch (DBusException e
) {
1081 e
.printStackTrace();
1089 private static String
formatTimestamp(long timestamp
) {
1090 Date date
= new Date(timestamp
);
1091 final DateFormat df
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
1092 df
.setTimeZone(tzUTC
);
1093 return timestamp
+ " (" + df
.format(date
) + ")";