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) {
464 System
.err
.println("updateGroup is not yet implemented via dbus");
467 if (!m
.isRegistered()) {
468 System
.err
.println("User is not registered.");
473 byte[] groupId
= null;
474 if (ns
.getString("group") != null) {
475 groupId
= decodeGroupId(ns
.getString("group"));
477 byte[] newGroupId
= m
.sendUpdateGroupMessage(groupId
, ns
.getString("name"), ns
.<String
>getList("member"), ns
.getString("avatar"));
478 if (groupId
== null) {
479 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
481 } catch (IOException e
) {
482 handleIOException(e
);
484 } catch (AttachmentInvalidException e
) {
485 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
486 System
.err
.println("Aborting sending.");
488 } catch (GroupNotFoundException e
) {
489 handleGroupNotFoundException(e
);
491 } catch (NotAGroupMemberException e
) {
492 handleNotAGroupMemberException(e
);
494 } catch (EncapsulatedExceptions e
) {
495 handleEncapsulatedExceptions(e
);
501 if (dBusConn
!= null) {
502 System
.err
.println("listGroups is not yet implemented via dbus");
505 if (!m
.isRegistered()) {
506 System
.err
.println("User is not registered.");
510 List
<GroupInfo
> groups
= m
.getGroups();
511 boolean detailed
= ns
.getBoolean("detailed");
513 for (GroupInfo group
: groups
) {
514 printGroup(group
, detailed
);
517 case "listIdentities":
518 if (dBusConn
!= null) {
519 System
.err
.println("listIdentities is not yet implemented via dbus");
522 if (!m
.isRegistered()) {
523 System
.err
.println("User is not registered.");
526 if (ns
.get("number") == null) {
527 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
528 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
529 printIdentityFingerprint(m
, keys
.getKey(), id
);
533 String number
= ns
.getString("number");
534 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
535 printIdentityFingerprint(m
, number
, id
);
540 if (dBusConn
!= null) {
541 System
.err
.println("trust is not yet implemented via dbus");
544 if (!m
.isRegistered()) {
545 System
.err
.println("User is not registered.");
548 String number
= ns
.getString("number");
549 if (ns
.getBoolean("trust_all_known_keys")) {
550 boolean res
= m
.trustIdentityAllKeys(number
);
552 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
556 String fingerprint
= ns
.getString("verified_fingerprint");
557 if (fingerprint
!= null) {
558 fingerprint
= fingerprint
.replaceAll(" ", "");
559 if (fingerprint
.length() == 66) {
560 byte[] fingerprintBytes
;
562 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
563 } catch (Exception e
) {
564 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
567 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
569 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
572 } else if (fingerprint
.length() == 60) {
573 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
575 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.");
579 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
583 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
589 if (dBusConn
!= null) {
590 System
.err
.println("Stop it.");
593 if (!m
.isRegistered()) {
594 System
.err
.println("User is not registered.");
597 DBusConnection conn
= null;
601 if (ns
.getBoolean("system")) {
602 busType
= DBusConnection
.SYSTEM
;
604 busType
= DBusConnection
.SESSION
;
606 conn
= DBusConnection
.getConnection(busType
);
607 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
608 conn
.requestBusName(SIGNAL_BUSNAME
);
609 } catch (UnsatisfiedLinkError e
) {
610 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
612 } catch (DBusException e
) {
616 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
618 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, new DbusReceiveMessageHandler(m
, conn
));
619 } catch (IOException e
) {
620 System
.err
.println("Error while receiving messages: " + e
.getMessage());
622 } catch (AssertionError e
) {
623 handleAssertionError(e
);
636 if (dBusConn
!= null) {
637 dBusConn
.disconnect();
642 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
643 String digits
= formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.getIdentityKey()));
644 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
645 theirId
.getTrustLevel(), theirId
.getDateAdded(), Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
648 private static void printGroup(GroupInfo group
, boolean detailed
) {
650 System
.out
.println(String
.format("Id: %s Name: %s Active: %s Members: %s",
651 Base64
.encodeBytes(group
.groupId
), group
.name
, group
.active
, group
.members
));
653 System
.out
.println(String
.format("Id: %s Name: %s Active: %s", Base64
.encodeBytes(group
.groupId
),
654 group
.name
, group
.active
));
658 private static String
formatSafetyNumber(String digits
) {
659 final int partCount
= 12;
660 int partSize
= digits
.length() / partCount
;
661 StringBuilder f
= new StringBuilder(digits
.length() + partCount
);
662 for (int i
= 0; i
< partCount
; i
++) {
663 f
.append(digits
.substring(i
* partSize
, (i
* partSize
) + partSize
)).append(" ");
668 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
669 System
.err
.println("Failed to send to group: " + e
.getMessage());
670 System
.err
.println("Aborting sending.");
673 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
674 System
.err
.println("Failed to send to group: " + e
.getMessage());
675 System
.err
.println("Update the group on another device to readd the user to this group.");
676 System
.err
.println("Aborting sending.");
680 private static void handleDBusExecutionException(DBusExecutionException e
) {
681 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
682 System
.err
.println("Aborting.");
685 private static byte[] decodeGroupId(String groupId
) {
687 return Base64
.decode(groupId
);
688 } catch (IOException e
) {
689 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
690 System
.err
.println("Aborting sending.");
696 private static Namespace
parseArgs(String
[] args
) {
697 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("signal-cli")
699 .description("Commandline interface for Signal.")
700 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
702 parser
.addArgument("-v", "--version")
703 .help("Show package version.")
704 .action(Arguments
.version());
705 parser
.addArgument("--config")
706 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
708 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
709 mut
.addArgument("-u", "--username")
710 .help("Specify your phone number, that will be used for verification.");
711 mut
.addArgument("--dbus")
712 .help("Make request via user dbus.")
713 .action(Arguments
.storeTrue());
714 mut
.addArgument("--dbus-system")
715 .help("Make request via system dbus.")
716 .action(Arguments
.storeTrue());
718 Subparsers subparsers
= parser
.addSubparsers()
719 .title("subcommands")
721 .description("valid subcommands")
722 .help("additional help");
724 Subparser parserLink
= subparsers
.addParser("link");
725 parserLink
.addArgument("-n", "--name")
726 .help("Specify a name to describe this new device.");
728 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
729 parserAddDevice
.addArgument("--uri")
731 .help("Specify the uri contained in the QR code shown by the new device.");
733 Subparser parserDevices
= subparsers
.addParser("listDevices");
735 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
736 parserRemoveDevice
.addArgument("-d", "--deviceId")
739 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
741 Subparser parserRegister
= subparsers
.addParser("register");
742 parserRegister
.addArgument("-v", "--voice")
743 .help("The verification should be done over voice, not sms.")
744 .action(Arguments
.storeTrue());
746 Subparser parserUnregister
= subparsers
.addParser("unregister");
747 parserUnregister
.help("Unregister the current device from the signal server.");
749 Subparser parserUpdateAccount
= subparsers
.addParser("updateAccount");
750 parserUpdateAccount
.help("Update the account attributes on the signal server.");
752 Subparser parserVerify
= subparsers
.addParser("verify");
753 parserVerify
.addArgument("verificationCode")
754 .help("The verification code you received via sms or voice call.");
756 Subparser parserSend
= subparsers
.addParser("send");
757 parserSend
.addArgument("-g", "--group")
758 .help("Specify the recipient group ID.");
759 parserSend
.addArgument("recipient")
760 .help("Specify the recipients' phone number.")
762 parserSend
.addArgument("-m", "--message")
763 .help("Specify the message, if missing standard input is used.");
764 parserSend
.addArgument("-a", "--attachment")
766 .help("Add file as attachment");
767 parserSend
.addArgument("-e", "--endsession")
768 .help("Clear session state and send end session message.")
769 .action(Arguments
.storeTrue());
771 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
772 parserLeaveGroup
.addArgument("-g", "--group")
774 .help("Specify the recipient group ID.");
776 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
777 parserUpdateGroup
.addArgument("-g", "--group")
778 .help("Specify the recipient group ID.");
779 parserUpdateGroup
.addArgument("-n", "--name")
780 .help("Specify the new group name.");
781 parserUpdateGroup
.addArgument("-a", "--avatar")
782 .help("Specify a new group avatar image file");
783 parserUpdateGroup
.addArgument("-m", "--member")
785 .help("Specify one or more members to add to the group");
787 Subparser parserListGroups
= subparsers
.addParser("listGroups");
788 parserListGroups
.addArgument("-d", "--detailed").action(Arguments
.storeTrue())
789 .help("List members of each group");
790 parserListGroups
.help("List group name and ids");
792 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
793 parserListIdentities
.addArgument("-n", "--number")
794 .help("Only show identity keys for the given phone number.");
796 Subparser parserTrust
= subparsers
.addParser("trust");
797 parserTrust
.addArgument("number")
798 .help("Specify the phone number, for which to set the trust.")
800 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
801 mutTrust
.addArgument("-a", "--trust-all-known-keys")
802 .help("Trust all known keys of this user, only use this for testing.")
803 .action(Arguments
.storeTrue());
804 mutTrust
.addArgument("-v", "--verified-fingerprint")
805 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
807 Subparser parserReceive
= subparsers
.addParser("receive");
808 parserReceive
.addArgument("-t", "--timeout")
810 .help("Number of seconds to wait for new messages (negative values disable timeout)");
811 parserReceive
.addArgument("--ignore-attachments")
812 .help("Don’t download attachments of received messages.")
813 .action(Arguments
.storeTrue());
815 Subparser parserDaemon
= subparsers
.addParser("daemon");
816 parserDaemon
.addArgument("--system")
817 .action(Arguments
.storeTrue())
818 .help("Use DBus system bus instead of user bus.");
819 parserDaemon
.addArgument("--ignore-attachments")
820 .help("Don’t download attachments of received messages.")
821 .action(Arguments
.storeTrue());
824 Namespace ns
= parser
.parseArgs(args
);
825 if ("link".equals(ns
.getString("command"))) {
826 if (ns
.getString("username") != null) {
828 System
.err
.println("You cannot specify a username (phone number) when linking");
831 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
832 if (ns
.getString("username") == null) {
834 System
.err
.println("You need to specify a username (phone number)");
837 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
838 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
842 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
843 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
847 } catch (ArgumentParserException e
) {
848 parser
.handleError(e
);
853 private static void handleAssertionError(AssertionError e
) {
854 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
856 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
859 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
860 System
.err
.println("Failed to send (some) messages:");
861 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
862 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
864 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
865 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
867 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
868 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
872 private static void handleIOException(IOException e
) {
873 System
.err
.println("Failed to send message: " + e
.getMessage());
876 private static String
readAll(InputStream
in) throws IOException
{
877 StringWriter output
= new StringWriter();
878 byte[] buffer
= new byte[4096];
881 while (-1 != (n
= System
.in.read(buffer
))) {
882 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
885 return output
.toString();
888 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
891 public ReceiveMessageHandler(Manager m
) {
896 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
897 SignalServiceAddress source
= envelope
.getSourceAddress();
898 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
899 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
900 if (source
.getRelay().isPresent()) {
901 System
.out
.println("Relayed by: " + source
.getRelay().get());
903 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
905 if (envelope
.isReceipt()) {
906 System
.out
.println("Got receipt.");
907 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
908 if (exception
!= null) {
909 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
910 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
911 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
912 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");
913 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");
915 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
918 if (content
== null) {
919 System
.out
.println("Failed to decrypt message.");
921 if (content
.getDataMessage().isPresent()) {
922 SignalServiceDataMessage message
= content
.getDataMessage().get();
923 handleSignalServiceDataMessage(message
);
925 if (content
.getSyncMessage().isPresent()) {
926 System
.out
.println("Received a sync message");
927 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
929 if (syncMessage
.getContacts().isPresent()) {
930 System
.out
.println("Received sync contacts");
931 printAttachment(syncMessage
.getContacts().get());
933 if (syncMessage
.getGroups().isPresent()) {
934 System
.out
.println("Received sync groups");
935 printAttachment(syncMessage
.getGroups().get());
937 if (syncMessage
.getRead().isPresent()) {
938 System
.out
.println("Received sync read messages list");
939 for (ReadMessage rm
: syncMessage
.getRead().get()) {
940 ContactInfo fromContact
= m
.getContact(rm
.getSender());
941 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + formatTimestamp(rm
.getTimestamp()));
944 if (syncMessage
.getRequest().isPresent()) {
945 System
.out
.println("Received sync request");
946 if (syncMessage
.getRequest().get().isContactsRequest()) {
947 System
.out
.println(" - contacts request");
949 if (syncMessage
.getRequest().get().isGroupsRequest()) {
950 System
.out
.println(" - groups request");
953 if (syncMessage
.getSent().isPresent()) {
954 System
.out
.println("Received sync sent message");
955 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
957 if (sentTranscriptMessage
.getDestination().isPresent()) {
958 String dest
= sentTranscriptMessage
.getDestination().get();
959 ContactInfo destContact
= m
.getContact(dest
);
960 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
964 System
.out
.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage
.getTimestamp()));
965 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
966 System
.out
.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
968 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
969 handleSignalServiceDataMessage(message
);
971 if (syncMessage
.getBlockedList().isPresent()) {
972 System
.out
.println("Received sync message with block list");
973 System
.out
.println("Blocked numbers:");
974 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
975 for (String number
: blockedList
.getNumbers()) {
976 System
.out
.println(" - " + number
);
982 System
.out
.println("Unknown message received.");
984 System
.out
.println();
987 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
988 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
990 if (message
.getBody().isPresent()) {
991 System
.out
.println("Body: " + message
.getBody().get());
993 if (message
.getGroupInfo().isPresent()) {
994 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
995 System
.out
.println("Group info:");
996 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
997 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
998 System
.out
.println(" Name: " + groupInfo
.getName().get());
1000 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
1001 if (group
!= null) {
1002 System
.out
.println(" Name: " + group
.name
);
1004 System
.out
.println(" Name: <Unknown group>");
1007 System
.out
.println(" Type: " + groupInfo
.getType());
1008 if (groupInfo
.getMembers().isPresent()) {
1009 for (String member
: groupInfo
.getMembers().get()) {
1010 System
.out
.println(" Member: " + member
);
1013 if (groupInfo
.getAvatar().isPresent()) {
1014 System
.out
.println(" Avatar:");
1015 printAttachment(groupInfo
.getAvatar().get());
1018 if (message
.isEndSession()) {
1019 System
.out
.println("Is end session");
1021 if (message
.isExpirationUpdate()) {
1022 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
1024 if (message
.getExpiresInSeconds() > 0) {
1025 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
1028 if (message
.getAttachments().isPresent()) {
1029 System
.out
.println("Attachments: ");
1030 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1031 printAttachment(attachment
);
1036 private void printAttachment(SignalServiceAttachment attachment
) {
1037 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
1038 if (attachment
.isPointer()) {
1039 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1040 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
1041 System
.out
.println(" Filename: " + (pointer
.getFileName().isPresent() ? pointer
.getFileName().get() : "-"));
1042 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
1043 File file
= m
.getAttachmentFile(pointer
.getId());
1044 if (file
.exists()) {
1045 System
.out
.println(" Stored plaintext in: " + file
);
1051 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
1052 final DBusConnection conn
;
1054 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1060 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1061 super.handleMessage(envelope
, content
, exception
);
1063 if (!envelope
.isReceipt() && content
!= null && content
.getDataMessage().isPresent()) {
1064 SignalServiceDataMessage message
= content
.getDataMessage().get();
1066 if (!message
.isEndSession() &&
1067 !(message
.getGroupInfo().isPresent() &&
1068 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
1069 List
<String
> attachments
= new ArrayList
<>();
1070 if (message
.getAttachments().isPresent()) {
1071 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1072 if (attachment
.isPointer()) {
1073 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
1079 conn
.sendSignal(new Signal
.MessageReceived(
1081 message
.getTimestamp(),
1082 envelope
.getSource(),
1083 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1084 message
.getBody().isPresent() ? message
.getBody().get() : "",
1086 } catch (DBusException e
) {
1087 e
.printStackTrace();
1095 private static String
formatTimestamp(long timestamp
) {
1096 Date date
= new Date(timestamp
);
1097 final DateFormat df
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
1098 df
.setTimeZone(tzUTC
);
1099 return timestamp
+ " (" + df
.format(date
) + ")";