2 * Copyright (C) 2015 AsamK
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
;
19 import com
.fasterxml
.jackson
.annotation
.JsonAutoDetect
;
20 import com
.fasterxml
.jackson
.annotation
.PropertyAccessor
;
21 import com
.fasterxml
.jackson
.core
.JsonGenerator
;
22 import com
.fasterxml
.jackson
.databind
.DeserializationFeature
;
23 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
24 import com
.fasterxml
.jackson
.databind
.SerializationFeature
;
25 import com
.fasterxml
.jackson
.databind
.node
.ObjectNode
;
26 import net
.sourceforge
.argparse4j
.ArgumentParsers
;
27 import net
.sourceforge
.argparse4j
.impl
.Arguments
;
28 import net
.sourceforge
.argparse4j
.inf
.*;
29 import org
.apache
.http
.util
.TextUtils
;
30 import org
.asamk
.Signal
;
31 import org
.asamk
.signal
.storage
.contacts
.ContactInfo
;
32 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
33 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
34 import org
.asamk
.signal
.util
.Hex
;
35 import org
.freedesktop
.dbus
.DBusConnection
;
36 import org
.freedesktop
.dbus
.DBusSigHandler
;
37 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
38 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
39 import org
.whispersystems
.libsignal
.InvalidKeyException
;
40 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
41 import org
.whispersystems
.signalservice
.api
.messages
.*;
42 import org
.whispersystems
.signalservice
.api
.messages
.calls
.*;
43 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
44 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
45 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
46 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
47 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
48 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
49 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
52 import java
.io
.IOException
;
53 import java
.io
.InputStream
;
54 import java
.io
.StringWriter
;
56 import java
.net
.URISyntaxException
;
57 import java
.nio
.charset
.Charset
;
58 import java
.security
.Security
;
59 import java
.text
.DateFormat
;
60 import java
.text
.SimpleDateFormat
;
62 import java
.util
.concurrent
.TimeUnit
;
63 import java
.util
.concurrent
.TimeoutException
;
67 public static final String SIGNAL_BUSNAME
= "org.asamk.Signal";
68 public static final String SIGNAL_OBJECTPATH
= "/org/asamk/Signal";
70 private static final TimeZone tzUTC
= TimeZone
.getTimeZone("UTC");
72 public static void main(String
[] args
) {
73 // Workaround for BKS truststore
74 Security
.insertProviderAt(new org
.bouncycastle
.jce
.provider
.BouncyCastleProvider(), 1);
76 Namespace ns
= parseArgs(args
);
81 int res
= handleCommands(ns
);
85 private static int handleCommands(Namespace ns
) {
86 final String username
= ns
.getString("username");
89 DBusConnection dBusConn
= null;
91 if (ns
.getBoolean("dbus") || ns
.getBoolean("dbus_system")) {
95 if (ns
.getBoolean("dbus_system")) {
96 busType
= DBusConnection
.SYSTEM
;
98 busType
= DBusConnection
.SESSION
;
100 dBusConn
= DBusConnection
.getConnection(busType
);
101 ts
= (Signal
) dBusConn
.getRemoteObject(
102 SIGNAL_BUSNAME
, SIGNAL_OBJECTPATH
,
104 } catch (UnsatisfiedLinkError e
) {
105 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
107 } catch (DBusException e
) {
109 if (dBusConn
!= null) {
110 dBusConn
.disconnect();
115 String settingsPath
= ns
.getString("config");
116 if (TextUtils
.isEmpty(settingsPath
)) {
117 settingsPath
= System
.getProperty("user.home") + "/.config/signal";
118 if (!new File(settingsPath
).exists()) {
119 String legacySettingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
120 if (new File(legacySettingsPath
).exists()) {
121 settingsPath
= legacySettingsPath
;
126 m
= new Manager(username
, settingsPath
);
128 if (m
.userExists()) {
131 } catch (Exception e
) {
132 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
138 switch (ns
.getString("command")) {
140 if (dBusConn
!= null) {
141 System
.err
.println("register is not yet implemented via dbus");
144 if (!m
.userHasKeys()) {
145 m
.createNewIdentity();
148 m
.register(ns
.getBoolean("voice"));
149 } catch (IOException e
) {
150 System
.err
.println("Request verify error: " + e
.getMessage());
155 if (dBusConn
!= null) {
156 System
.err
.println("unregister is not yet implemented via dbus");
159 if (!m
.isRegistered()) {
160 System
.err
.println("User is not registered.");
165 } catch (IOException e
) {
166 System
.err
.println("Unregister error: " + e
.getMessage());
170 case "updateAccount":
171 if (dBusConn
!= null) {
172 System
.err
.println("updateAccount is not yet implemented via dbus");
175 if (!m
.isRegistered()) {
176 System
.err
.println("User is not registered.");
180 m
.updateAccountAttributes();
181 } catch (IOException e
) {
182 System
.err
.println("UpdateAccount error: " + e
.getMessage());
187 if (dBusConn
!= null) {
188 System
.err
.println("verify is not yet implemented via dbus");
191 if (!m
.userHasKeys()) {
192 System
.err
.println("User has no keys, first call register.");
195 if (m
.isRegistered()) {
196 System
.err
.println("User registration is already verified");
200 m
.verifyAccount(ns
.getString("verificationCode"));
201 } catch (IOException e
) {
202 System
.err
.println("Verify error: " + e
.getMessage());
207 if (dBusConn
!= null) {
208 System
.err
.println("link is not yet implemented via dbus");
212 // When linking, username is null and we always have to create keys
213 m
.createNewIdentity();
215 String deviceName
= ns
.getString("name");
216 if (deviceName
== null) {
220 System
.out
.println(m
.getDeviceLinkUri());
221 m
.finishDeviceLink(deviceName
);
222 System
.out
.println("Associated with: " + m
.getUsername());
223 } catch (TimeoutException e
) {
224 System
.err
.println("Link request timed out, please try again.");
226 } catch (IOException e
) {
227 System
.err
.println("Link request error: " + e
.getMessage());
229 } catch (AssertionError e
) {
230 handleAssertionError(e
);
232 } catch (InvalidKeyException e
) {
235 } catch (UserAlreadyExists e
) {
236 System
.err
.println("The user " + e
.getUsername() + " already exists\nDelete \"" + e
.getFileName() + "\" before trying again.");
241 if (dBusConn
!= null) {
242 System
.err
.println("link is not yet implemented via dbus");
245 if (!m
.isRegistered()) {
246 System
.err
.println("User is not registered.");
250 m
.addDeviceLink(new URI(ns
.getString("uri")));
251 } catch (IOException e
) {
254 } catch (InvalidKeyException e
) {
257 } catch (AssertionError e
) {
258 handleAssertionError(e
);
260 } catch (URISyntaxException e
) {
266 if (dBusConn
!= null) {
267 System
.err
.println("listDevices is not yet implemented via dbus");
270 if (!m
.isRegistered()) {
271 System
.err
.println("User is not registered.");
275 List
<DeviceInfo
> devices
= m
.getLinkedDevices();
276 for (DeviceInfo d
: devices
) {
277 System
.out
.println("Device " + d
.getId() + (d
.getId() == m
.getDeviceId() ?
" (this device)" : "") + ":");
278 System
.out
.println(" Name: " + d
.getName());
279 System
.out
.println(" Created: " + formatTimestamp(d
.getCreated()));
280 System
.out
.println(" Last seen: " + formatTimestamp(d
.getLastSeen()));
282 } catch (IOException e
) {
288 if (dBusConn
!= null) {
289 System
.err
.println("removeDevice is not yet implemented via dbus");
292 if (!m
.isRegistered()) {
293 System
.err
.println("User is not registered.");
297 int deviceId
= ns
.getInt("deviceId");
298 m
.removeLinkedDevices(deviceId
);
299 } catch (IOException e
) {
305 if (dBusConn
== null && !m
.isRegistered()) {
306 System
.err
.println("User is not registered.");
310 if (ns
.getBoolean("endsession")) {
311 if (ns
.getList("recipient") == null) {
312 System
.err
.println("No recipients given");
313 System
.err
.println("Aborting sending.");
317 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
318 } catch (IOException e
) {
319 handleIOException(e
);
321 } catch (EncapsulatedExceptions e
) {
322 handleEncapsulatedExceptions(e
);
324 } catch (AssertionError e
) {
325 handleAssertionError(e
);
327 } catch (DBusExecutionException e
) {
328 handleDBusExecutionException(e
);
332 String messageText
= ns
.getString("message");
333 if (messageText
== null) {
335 messageText
= readAll(System
.in);
336 } catch (IOException e
) {
337 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
338 System
.err
.println("Aborting sending.");
344 List
<String
> attachments
= ns
.getList("attachment");
345 if (attachments
== null) {
346 attachments
= new ArrayList
<>();
348 if (ns
.getString("group") != null) {
349 byte[] groupId
= decodeGroupId(ns
.getString("group"));
350 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
352 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
354 } catch (IOException e
) {
355 handleIOException(e
);
357 } catch (EncapsulatedExceptions e
) {
358 handleEncapsulatedExceptions(e
);
360 } catch (AssertionError e
) {
361 handleAssertionError(e
);
363 } catch (GroupNotFoundException e
) {
364 handleGroupNotFoundException(e
);
366 } catch (NotAGroupMemberException e
) {
367 handleNotAGroupMemberException(e
);
369 } catch (AttachmentInvalidException e
) {
370 System
.err
.println("Failed to add attachment: " + e
.getMessage());
371 System
.err
.println("Aborting sending.");
373 } catch (DBusExecutionException e
) {
374 handleDBusExecutionException(e
);
381 if (dBusConn
!= null) {
383 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
385 public void handle(Signal
.MessageReceived s
) {
386 System
.out
.print(String
.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
387 s
.getSender(), formatTimestamp(s
.getTimestamp()), s
.getMessage()));
388 if (s
.getGroupId().length
> 0) {
389 System
.out
.println("Group info:");
390 System
.out
.println(" Id: " + Base64
.encodeBytes(s
.getGroupId()));
392 if (s
.getAttachments().size() > 0) {
393 System
.out
.println("Attachments: ");
394 for (String attachment
: s
.getAttachments()) {
395 System
.out
.println("- Stored plaintext in: " + attachment
);
398 System
.out
.println();
401 dBusConn
.addSigHandler(Signal
.ReceiptReceived
.class, new DBusSigHandler
<Signal
.ReceiptReceived
>() {
403 public void handle(Signal
.ReceiptReceived s
) {
404 System
.out
.print(String
.format("Receipt from: %s\nTimestamp: %s\n",
405 s
.getSender(), formatTimestamp(s
.getTimestamp())));
408 } catch (UnsatisfiedLinkError e
) {
409 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
411 } catch (DBusException e
) {
418 } catch (InterruptedException e
) {
423 if (!m
.isRegistered()) {
424 System
.err
.println("User is not registered.");
428 if (ns
.getDouble("timeout") != null) {
429 timeout
= ns
.getDouble("timeout");
431 boolean returnOnTimeout
= true;
433 returnOnTimeout
= false;
436 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
438 final Manager
.ReceiveMessageHandler handler
= ns
.getBoolean("json") ?
new JsonReceiveMessageHandler(m
) : new ReceiveMessageHandler(m
);
439 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, ignoreAttachments
, handler
);
440 } catch (IOException e
) {
441 System
.err
.println("Error while receiving messages: " + e
.getMessage());
443 } catch (AssertionError e
) {
444 handleAssertionError(e
);
449 if (dBusConn
!= null) {
450 System
.err
.println("quitGroup is not yet implemented via dbus");
453 if (!m
.isRegistered()) {
454 System
.err
.println("User is not registered.");
459 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
460 } catch (IOException e
) {
461 handleIOException(e
);
463 } catch (EncapsulatedExceptions e
) {
464 handleEncapsulatedExceptions(e
);
466 } catch (AssertionError e
) {
467 handleAssertionError(e
);
469 } catch (GroupNotFoundException e
) {
470 handleGroupNotFoundException(e
);
472 } catch (NotAGroupMemberException e
) {
473 handleNotAGroupMemberException(e
);
479 if (dBusConn
== null && !m
.isRegistered()) {
480 System
.err
.println("User is not registered.");
485 byte[] groupId
= null;
486 if (ns
.getString("group") != null) {
487 groupId
= decodeGroupId(ns
.getString("group"));
489 if (groupId
== null) {
490 groupId
= new byte[0];
492 String groupName
= ns
.getString("name");
493 if (groupName
== null) {
496 List
<String
> groupMembers
= ns
.<String
>getList("member");
497 if (groupMembers
== null) {
498 groupMembers
= new ArrayList
<String
>();
500 String groupAvatar
= ns
.getString("avatar");
501 if (groupAvatar
== null) {
504 byte[] newGroupId
= ts
.updateGroup(groupId
, groupName
, groupMembers
, groupAvatar
);
505 if (groupId
.length
!= newGroupId
.length
) {
506 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
508 } catch (IOException e
) {
509 handleIOException(e
);
511 } catch (AttachmentInvalidException e
) {
512 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
513 System
.err
.println("Aborting sending.");
515 } catch (GroupNotFoundException e
) {
516 handleGroupNotFoundException(e
);
518 } catch (NotAGroupMemberException e
) {
519 handleNotAGroupMemberException(e
);
521 } catch (EncapsulatedExceptions e
) {
522 handleEncapsulatedExceptions(e
);
528 if (dBusConn
!= null) {
529 System
.err
.println("listGroups is not yet implemented via dbus");
532 if (!m
.isRegistered()) {
533 System
.err
.println("User is not registered.");
537 List
<GroupInfo
> groups
= m
.getGroups();
538 boolean detailed
= ns
.getBoolean("detailed");
540 for (GroupInfo group
: groups
) {
541 printGroup(group
, detailed
);
544 case "listIdentities":
545 if (dBusConn
!= null) {
546 System
.err
.println("listIdentities is not yet implemented via dbus");
549 if (!m
.isRegistered()) {
550 System
.err
.println("User is not registered.");
553 if (ns
.get("number") == null) {
554 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
555 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
556 printIdentityFingerprint(m
, keys
.getKey(), id
);
560 String number
= ns
.getString("number");
561 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
562 printIdentityFingerprint(m
, number
, id
);
567 if (dBusConn
!= null) {
568 System
.err
.println("trust is not yet implemented via dbus");
571 if (!m
.isRegistered()) {
572 System
.err
.println("User is not registered.");
575 String number
= ns
.getString("number");
576 if (ns
.getBoolean("trust_all_known_keys")) {
577 boolean res
= m
.trustIdentityAllKeys(number
);
579 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
583 String fingerprint
= ns
.getString("verified_fingerprint");
584 if (fingerprint
!= null) {
585 fingerprint
= fingerprint
.replaceAll(" ", "");
586 if (fingerprint
.length() == 66) {
587 byte[] fingerprintBytes
;
589 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
590 } catch (Exception e
) {
591 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
594 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
596 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
599 } else if (fingerprint
.length() == 60) {
600 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
602 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.");
606 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
610 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
616 if (dBusConn
!= null) {
617 System
.err
.println("Stop it.");
620 if (!m
.isRegistered()) {
621 System
.err
.println("User is not registered.");
624 DBusConnection conn
= null;
628 if (ns
.getBoolean("system")) {
629 busType
= DBusConnection
.SYSTEM
;
631 busType
= DBusConnection
.SESSION
;
633 conn
= DBusConnection
.getConnection(busType
);
634 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
635 conn
.requestBusName(SIGNAL_BUSNAME
);
636 } catch (UnsatisfiedLinkError e
) {
637 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
639 } catch (DBusException e
) {
643 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
645 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, new DbusReceiveMessageHandler(m
, conn
));
646 } catch (IOException e
) {
647 System
.err
.println("Error while receiving messages: " + e
.getMessage());
649 } catch (AssertionError e
) {
650 handleAssertionError(e
);
663 if (dBusConn
!= null) {
664 dBusConn
.disconnect();
669 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
670 String digits
= formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.getIdentityKey()));
671 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
672 theirId
.getTrustLevel(), theirId
.getDateAdded(), Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
675 private static void printGroup(GroupInfo group
, boolean detailed
) {
677 System
.out
.println(String
.format("Id: %s Name: %s Active: %s Members: %s",
678 Base64
.encodeBytes(group
.groupId
), group
.name
, group
.active
, group
.members
));
680 System
.out
.println(String
.format("Id: %s Name: %s Active: %s", Base64
.encodeBytes(group
.groupId
),
681 group
.name
, group
.active
));
685 private static String
formatSafetyNumber(String digits
) {
686 final int partCount
= 12;
687 int partSize
= digits
.length() / partCount
;
688 StringBuilder f
= new StringBuilder(digits
.length() + partCount
);
689 for (int i
= 0; i
< partCount
; i
++) {
690 f
.append(digits
.substring(i
* partSize
, (i
* partSize
) + partSize
)).append(" ");
695 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
696 System
.err
.println("Failed to send to group: " + e
.getMessage());
697 System
.err
.println("Aborting sending.");
700 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
701 System
.err
.println("Failed to send to group: " + e
.getMessage());
702 System
.err
.println("Update the group on another device to readd the user to this group.");
703 System
.err
.println("Aborting sending.");
707 private static void handleDBusExecutionException(DBusExecutionException e
) {
708 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
709 System
.err
.println("Aborting.");
712 private static byte[] decodeGroupId(String groupId
) {
714 return Base64
.decode(groupId
);
715 } catch (IOException e
) {
716 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
717 System
.err
.println("Aborting sending.");
723 private static Namespace
parseArgs(String
[] args
) {
724 ArgumentParser parser
= ArgumentParsers
.newFor("signal-cli")
727 .description("Commandline interface for Signal.")
728 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
730 parser
.addArgument("-v", "--version")
731 .help("Show package version.")
732 .action(Arguments
.version());
733 parser
.addArgument("--config")
734 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
736 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
737 mut
.addArgument("-u", "--username")
738 .help("Specify your phone number, that will be used for verification.");
739 mut
.addArgument("--dbus")
740 .help("Make request via user dbus.")
741 .action(Arguments
.storeTrue());
742 mut
.addArgument("--dbus-system")
743 .help("Make request via system dbus.")
744 .action(Arguments
.storeTrue());
746 Subparsers subparsers
= parser
.addSubparsers()
747 .title("subcommands")
749 .description("valid subcommands")
750 .help("additional help");
752 Subparser parserLink
= subparsers
.addParser("link");
753 parserLink
.addArgument("-n", "--name")
754 .help("Specify a name to describe this new device.");
756 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
757 parserAddDevice
.addArgument("--uri")
759 .help("Specify the uri contained in the QR code shown by the new device.");
761 Subparser parserDevices
= subparsers
.addParser("listDevices");
763 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
764 parserRemoveDevice
.addArgument("-d", "--deviceId")
767 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
769 Subparser parserRegister
= subparsers
.addParser("register");
770 parserRegister
.addArgument("-v", "--voice")
771 .help("The verification should be done over voice, not sms.")
772 .action(Arguments
.storeTrue());
774 Subparser parserUnregister
= subparsers
.addParser("unregister");
775 parserUnregister
.help("Unregister the current device from the signal server.");
777 Subparser parserUpdateAccount
= subparsers
.addParser("updateAccount");
778 parserUpdateAccount
.help("Update the account attributes on the signal server.");
780 Subparser parserVerify
= subparsers
.addParser("verify");
781 parserVerify
.addArgument("verificationCode")
782 .help("The verification code you received via sms or voice call.");
784 Subparser parserSend
= subparsers
.addParser("send");
785 parserSend
.addArgument("-g", "--group")
786 .help("Specify the recipient group ID.");
787 parserSend
.addArgument("recipient")
788 .help("Specify the recipients' phone number.")
790 parserSend
.addArgument("-m", "--message")
791 .help("Specify the message, if missing standard input is used.");
792 parserSend
.addArgument("-a", "--attachment")
794 .help("Add file as attachment");
795 parserSend
.addArgument("-e", "--endsession")
796 .help("Clear session state and send end session message.")
797 .action(Arguments
.storeTrue());
799 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
800 parserLeaveGroup
.addArgument("-g", "--group")
802 .help("Specify the recipient group ID.");
804 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
805 parserUpdateGroup
.addArgument("-g", "--group")
806 .help("Specify the recipient group ID.");
807 parserUpdateGroup
.addArgument("-n", "--name")
808 .help("Specify the new group name.");
809 parserUpdateGroup
.addArgument("-a", "--avatar")
810 .help("Specify a new group avatar image file");
811 parserUpdateGroup
.addArgument("-m", "--member")
813 .help("Specify one or more members to add to the group");
815 Subparser parserListGroups
= subparsers
.addParser("listGroups");
816 parserListGroups
.addArgument("-d", "--detailed").action(Arguments
.storeTrue())
817 .help("List members of each group");
818 parserListGroups
.help("List group name and ids");
820 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
821 parserListIdentities
.addArgument("-n", "--number")
822 .help("Only show identity keys for the given phone number.");
824 Subparser parserTrust
= subparsers
.addParser("trust");
825 parserTrust
.addArgument("number")
826 .help("Specify the phone number, for which to set the trust.")
828 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
829 mutTrust
.addArgument("-a", "--trust-all-known-keys")
830 .help("Trust all known keys of this user, only use this for testing.")
831 .action(Arguments
.storeTrue());
832 mutTrust
.addArgument("-v", "--verified-fingerprint")
833 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
835 Subparser parserReceive
= subparsers
.addParser("receive");
836 parserReceive
.addArgument("-t", "--timeout")
838 .help("Number of seconds to wait for new messages (negative values disable timeout)");
839 parserReceive
.addArgument("--ignore-attachments")
840 .help("Don’t download attachments of received messages.")
841 .action(Arguments
.storeTrue());
842 parserReceive
.addArgument("--json")
843 .help("Output received messages in json format, one json object per line.")
844 .action(Arguments
.storeTrue());
846 Subparser parserDaemon
= subparsers
.addParser("daemon");
847 parserDaemon
.addArgument("--system")
848 .action(Arguments
.storeTrue())
849 .help("Use DBus system bus instead of user bus.");
850 parserDaemon
.addArgument("--ignore-attachments")
851 .help("Don’t download attachments of received messages.")
852 .action(Arguments
.storeTrue());
855 Namespace ns
= parser
.parseArgs(args
);
856 if ("link".equals(ns
.getString("command"))) {
857 if (ns
.getString("username") != null) {
859 System
.err
.println("You cannot specify a username (phone number) when linking");
862 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
863 if (ns
.getString("username") == null) {
865 System
.err
.println("You need to specify a username (phone number)");
868 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
869 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
873 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
874 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
878 } catch (ArgumentParserException e
) {
879 parser
.handleError(e
);
884 private static void handleAssertionError(AssertionError e
) {
885 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
887 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
890 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
891 System
.err
.println("Failed to send (some) messages:");
892 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
893 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
895 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
896 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
898 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
899 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
903 private static void handleIOException(IOException e
) {
904 System
.err
.println("Failed to send message: " + e
.getMessage());
907 private static String
readAll(InputStream
in) throws IOException
{
908 StringWriter output
= new StringWriter();
909 byte[] buffer
= new byte[4096];
912 while (-1 != (n
= System
.in.read(buffer
))) {
913 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
916 return output
.toString();
919 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
922 public ReceiveMessageHandler(Manager m
) {
927 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
928 SignalServiceAddress source
= envelope
.getSourceAddress();
929 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
930 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
931 if (source
.getRelay().isPresent()) {
932 System
.out
.println("Relayed by: " + source
.getRelay().get());
934 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
936 if (envelope
.isReceipt()) {
937 System
.out
.println("Got receipt.");
938 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
939 if (exception
!= null) {
940 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
941 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
942 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
943 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");
944 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");
946 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
949 if (content
== null) {
950 System
.out
.println("Failed to decrypt message.");
952 if (content
.getDataMessage().isPresent()) {
953 SignalServiceDataMessage message
= content
.getDataMessage().get();
954 handleSignalServiceDataMessage(message
);
956 if (content
.getSyncMessage().isPresent()) {
957 System
.out
.println("Received a sync message");
958 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
960 if (syncMessage
.getContacts().isPresent()) {
961 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
962 if (contactsMessage
.isComplete()) {
963 System
.out
.println("Received complete sync contacts");
965 System
.out
.println("Received sync contacts");
967 printAttachment(contactsMessage
.getContactsStream());
969 if (syncMessage
.getGroups().isPresent()) {
970 System
.out
.println("Received sync groups");
971 printAttachment(syncMessage
.getGroups().get());
973 if (syncMessage
.getRead().isPresent()) {
974 System
.out
.println("Received sync read messages list");
975 for (ReadMessage rm
: syncMessage
.getRead().get()) {
976 ContactInfo fromContact
= m
.getContact(rm
.getSender());
977 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + formatTimestamp(rm
.getTimestamp()));
980 if (syncMessage
.getRequest().isPresent()) {
981 System
.out
.println("Received sync request");
982 if (syncMessage
.getRequest().get().isContactsRequest()) {
983 System
.out
.println(" - contacts request");
985 if (syncMessage
.getRequest().get().isGroupsRequest()) {
986 System
.out
.println(" - groups request");
989 if (syncMessage
.getSent().isPresent()) {
990 System
.out
.println("Received sync sent message");
991 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
993 if (sentTranscriptMessage
.getDestination().isPresent()) {
994 String dest
= sentTranscriptMessage
.getDestination().get();
995 ContactInfo destContact
= m
.getContact(dest
);
996 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
1000 System
.out
.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage
.getTimestamp()));
1001 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
1002 System
.out
.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
1004 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
1005 handleSignalServiceDataMessage(message
);
1007 if (syncMessage
.getBlockedList().isPresent()) {
1008 System
.out
.println("Received sync message with block list");
1009 System
.out
.println("Blocked numbers:");
1010 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
1011 for (String number
: blockedList
.getNumbers()) {
1012 System
.out
.println(" - " + number
);
1015 if (syncMessage
.getVerified().isPresent()) {
1016 System
.out
.println("Received sync message with verified identities:");
1017 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1018 System
.out
.println(" - " + verifiedMessage
.getDestination() + ": " + verifiedMessage
.getVerified());
1019 String safetyNumber
= formatSafetyNumber(m
.computeSafetyNumber(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey()));
1020 System
.out
.println(" " + safetyNumber
);
1022 if (syncMessage
.getConfiguration().isPresent()) {
1023 System
.out
.println("Received sync message with configuration:");
1024 final ConfigurationMessage configurationMessage
= syncMessage
.getConfiguration().get();
1025 if (configurationMessage
.getReadReceipts().isPresent()) {
1026 System
.out
.println(" - Read receipts: " + (configurationMessage
.getReadReceipts().get() ?
"enabled" : "disabled"));
1030 if (content
.getCallMessage().isPresent()) {
1031 System
.out
.println("Received a call message");
1032 SignalServiceCallMessage callMessage
= content
.getCallMessage().get();
1033 if (callMessage
.getAnswerMessage().isPresent()) {
1034 AnswerMessage answerMessage
= callMessage
.getAnswerMessage().get();
1035 System
.out
.println("Answer message: " + answerMessage
.getId() + ": " + answerMessage
.getDescription());
1037 if (callMessage
.getBusyMessage().isPresent()) {
1038 BusyMessage busyMessage
= callMessage
.getBusyMessage().get();
1039 System
.out
.println("Busy message: " + busyMessage
.getId());
1041 if (callMessage
.getHangupMessage().isPresent()) {
1042 HangupMessage hangupMessage
= callMessage
.getHangupMessage().get();
1043 System
.out
.println("Hangup message: " + hangupMessage
.getId());
1045 if (callMessage
.getIceUpdateMessages().isPresent()) {
1046 List
<IceUpdateMessage
> iceUpdateMessages
= callMessage
.getIceUpdateMessages().get();
1047 for (IceUpdateMessage iceUpdateMessage
: iceUpdateMessages
) {
1048 System
.out
.println("Ice update message: " + iceUpdateMessage
.getId() + ", sdp: " + iceUpdateMessage
.getSdp());
1051 if (callMessage
.getOfferMessage().isPresent()) {
1052 OfferMessage offerMessage
= callMessage
.getOfferMessage().get();
1053 System
.out
.println("Offer message: " + offerMessage
.getId() + ": " + offerMessage
.getDescription());
1056 if (content
.getReceiptMessage().isPresent()) {
1057 System
.out
.println("Received a receipt message");
1058 SignalServiceReceiptMessage receiptMessage
= content
.getReceiptMessage().get();
1059 System
.out
.println(" - When: " + formatTimestamp(receiptMessage
.getWhen()));
1060 if (receiptMessage
.isDeliveryReceipt()) {
1061 System
.out
.println(" - Is delivery receipt");
1063 if (receiptMessage
.isReadReceipt()) {
1064 System
.out
.println(" - Is read receipt");
1066 System
.out
.println(" - Timestamps:");
1067 for (long timestamp
: receiptMessage
.getTimestamps()) {
1068 System
.out
.println(" " + formatTimestamp(timestamp
));
1073 System
.out
.println("Unknown message received.");
1075 System
.out
.println();
1078 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
1079 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
1081 if (message
.getBody().isPresent()) {
1082 System
.out
.println("Body: " + message
.getBody().get());
1084 if (message
.getGroupInfo().isPresent()) {
1085 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1086 System
.out
.println("Group info:");
1087 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
1088 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
1089 System
.out
.println(" Name: " + groupInfo
.getName().get());
1091 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
1092 if (group
!= null) {
1093 System
.out
.println(" Name: " + group
.name
);
1095 System
.out
.println(" Name: <Unknown group>");
1098 System
.out
.println(" Type: " + groupInfo
.getType());
1099 if (groupInfo
.getMembers().isPresent()) {
1100 for (String member
: groupInfo
.getMembers().get()) {
1101 System
.out
.println(" Member: " + member
);
1104 if (groupInfo
.getAvatar().isPresent()) {
1105 System
.out
.println(" Avatar:");
1106 printAttachment(groupInfo
.getAvatar().get());
1109 if (message
.isEndSession()) {
1110 System
.out
.println("Is end session");
1112 if (message
.isExpirationUpdate()) {
1113 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
1115 if (message
.getExpiresInSeconds() > 0) {
1116 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
1118 if (message
.isProfileKeyUpdate() && message
.getProfileKey().isPresent()) {
1119 System
.out
.println("Profile key update, key length:" + message
.getProfileKey().get().length
);
1122 if (message
.getAttachments().isPresent()) {
1123 System
.out
.println("Attachments: ");
1124 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1125 printAttachment(attachment
);
1130 private void printAttachment(SignalServiceAttachment attachment
) {
1131 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
1132 if (attachment
.isPointer()) {
1133 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1134 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
1135 System
.out
.println(" Filename: " + (pointer
.getFileName().isPresent() ? pointer
.getFileName().get() : "-"));
1136 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
1137 System
.out
.println(" Voice note: " + (pointer
.getVoiceNote() ?
"yes" : "no"));
1138 System
.out
.println(" Dimensions: " + pointer
.getWidth() + "x" + pointer
.getHeight());
1139 File file
= m
.getAttachmentFile(pointer
.getId());
1140 if (file
.exists()) {
1141 System
.out
.println(" Stored plaintext in: " + file
);
1147 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
1148 final DBusConnection conn
;
1150 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1156 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1157 super.handleMessage(envelope
, content
, exception
);
1159 if (envelope
.isReceipt()) {
1161 conn
.sendSignal(new Signal
.ReceiptReceived(
1163 envelope
.getTimestamp(),
1164 envelope
.getSource()
1166 } catch (DBusException e
) {
1167 e
.printStackTrace();
1169 } else if (content
!= null && content
.getDataMessage().isPresent()) {
1170 SignalServiceDataMessage message
= content
.getDataMessage().get();
1172 if (!message
.isEndSession() &&
1173 !(message
.getGroupInfo().isPresent() &&
1174 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
1175 List
<String
> attachments
= new ArrayList
<>();
1176 if (message
.getAttachments().isPresent()) {
1177 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1178 if (attachment
.isPointer()) {
1179 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
1185 conn
.sendSignal(new Signal
.MessageReceived(
1187 message
.getTimestamp(),
1188 envelope
.getSource(),
1189 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1190 message
.getBody().isPresent() ? message
.getBody().get() : "",
1192 } catch (DBusException e
) {
1193 e
.printStackTrace();
1200 private static class JsonReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
1202 final ObjectMapper jsonProcessor
;
1204 public JsonReceiveMessageHandler(Manager m
) {
1206 this.jsonProcessor
= new ObjectMapper();
1207 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.ANY
); // disable autodetect
1208 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
1209 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
1210 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
1214 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1215 ObjectNode result
= jsonProcessor
.createObjectNode();
1216 if (exception
!= null) {
1217 result
.putPOJO("error", new JsonError(exception
));
1219 if (envelope
!= null) {
1220 result
.putPOJO("envelope", new JsonMessageEnvelope(envelope
, content
));
1223 jsonProcessor
.writeValue(System
.out
, result
);
1224 System
.out
.println();
1225 } catch (IOException e
) {
1226 e
.printStackTrace();
1231 private static String
formatTimestamp(long timestamp
) {
1232 Date date
= new Date(timestamp
);
1233 final DateFormat df
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
1234 df
.setTimeZone(tzUTC
);
1235 return timestamp
+ " (" + df
.format(date
) + ")";