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 (DBusException e
) {
93 if (dBusConn
!= null) {
94 dBusConn
.disconnect();
99 String settingsPath
= ns
.getString("config");
100 if (TextUtils
.isEmpty(settingsPath
)) {
101 settingsPath
= System
.getProperty("user.home") + "/.config/signal";
102 if (!new File(settingsPath
).exists()) {
103 String legacySettingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
104 if (new File(legacySettingsPath
).exists()) {
105 settingsPath
= legacySettingsPath
;
110 m
= new Manager(username
, settingsPath
);
112 if (m
.userExists()) {
115 } catch (Exception e
) {
116 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
122 switch (ns
.getString("command")) {
124 if (dBusConn
!= null) {
125 System
.err
.println("register is not yet implemented via dbus");
128 if (!m
.userHasKeys()) {
129 m
.createNewIdentity();
132 m
.register(ns
.getBoolean("voice"));
133 } catch (IOException e
) {
134 System
.err
.println("Request verify error: " + e
.getMessage());
139 if (dBusConn
!= null) {
140 System
.err
.println("verify is not yet implemented via dbus");
143 if (!m
.userHasKeys()) {
144 System
.err
.println("User has no keys, first call register.");
147 if (m
.isRegistered()) {
148 System
.err
.println("User registration is already verified");
152 m
.verifyAccount(ns
.getString("verificationCode"));
153 } catch (IOException e
) {
154 System
.err
.println("Verify error: " + e
.getMessage());
159 if (dBusConn
!= null) {
160 System
.err
.println("link is not yet implemented via dbus");
164 // When linking, username is null and we always have to create keys
165 m
.createNewIdentity();
167 String deviceName
= ns
.getString("name");
168 if (deviceName
== null) {
172 System
.out
.println(m
.getDeviceLinkUri());
173 m
.finishDeviceLink(deviceName
);
174 System
.out
.println("Associated with: " + m
.getUsername());
175 } catch (TimeoutException e
) {
176 System
.err
.println("Link request timed out, please try again.");
178 } catch (IOException e
) {
179 System
.err
.println("Link request error: " + e
.getMessage());
181 } catch (AssertionError e
) {
182 handleAssertionError(e
);
184 } catch (InvalidKeyException e
) {
187 } catch (UserAlreadyExists e
) {
188 System
.err
.println("The user " + e
.getUsername() + " already exists\nDelete \"" + e
.getFileName() + "\" before trying again.");
193 if (dBusConn
!= null) {
194 System
.err
.println("link is not yet implemented via dbus");
197 if (!m
.isRegistered()) {
198 System
.err
.println("User is not registered.");
202 m
.addDeviceLink(new URI(ns
.getString("uri")));
203 } catch (IOException e
) {
206 } catch (InvalidKeyException e
) {
209 } catch (AssertionError e
) {
210 handleAssertionError(e
);
212 } catch (URISyntaxException e
) {
218 if (dBusConn
!= null) {
219 System
.err
.println("listDevices is not yet implemented via dbus");
222 if (!m
.isRegistered()) {
223 System
.err
.println("User is not registered.");
227 List
<DeviceInfo
> devices
= m
.getLinkedDevices();
228 for (DeviceInfo d
: devices
) {
229 System
.out
.println("Device " + d
.getId() + (d
.getId() == m
.getDeviceId() ?
" (this device)" : "") + ":");
230 System
.out
.println(" Name: " + d
.getName());
231 System
.out
.println(" Created: " + formatTimestamp(d
.getCreated()));
232 System
.out
.println(" Last seen: " + formatTimestamp(d
.getLastSeen()));
234 } catch (IOException e
) {
240 if (dBusConn
!= null) {
241 System
.err
.println("removeDevice is not yet implemented via dbus");
244 if (!m
.isRegistered()) {
245 System
.err
.println("User is not registered.");
249 int deviceId
= ns
.getInt("deviceId");
250 m
.removeLinkedDevices(deviceId
);
251 } catch (IOException e
) {
257 if (dBusConn
== null && !m
.isRegistered()) {
258 System
.err
.println("User is not registered.");
262 if (ns
.getBoolean("endsession")) {
263 if (ns
.getList("recipient") == null) {
264 System
.err
.println("No recipients given");
265 System
.err
.println("Aborting sending.");
269 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
270 } catch (IOException e
) {
271 handleIOException(e
);
273 } catch (EncapsulatedExceptions e
) {
274 handleEncapsulatedExceptions(e
);
276 } catch (AssertionError e
) {
277 handleAssertionError(e
);
279 } catch (DBusExecutionException e
) {
280 handleDBusExecutionException(e
);
284 String messageText
= ns
.getString("message");
285 if (messageText
== null) {
287 messageText
= readAll(System
.in);
288 } catch (IOException e
) {
289 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
290 System
.err
.println("Aborting sending.");
296 List
<String
> attachments
= ns
.getList("attachment");
297 if (attachments
== null) {
298 attachments
= new ArrayList
<>();
300 if (ns
.getString("group") != null) {
301 byte[] groupId
= decodeGroupId(ns
.getString("group"));
302 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
304 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
306 } catch (IOException e
) {
307 handleIOException(e
);
309 } catch (EncapsulatedExceptions e
) {
310 handleEncapsulatedExceptions(e
);
312 } catch (AssertionError e
) {
313 handleAssertionError(e
);
315 } catch (GroupNotFoundException e
) {
316 handleGroupNotFoundException(e
);
318 } catch (NotAGroupMemberException e
) {
319 handleNotAGroupMemberException(e
);
321 } catch (AttachmentInvalidException e
) {
322 System
.err
.println("Failed to add attachment: " + e
.getMessage());
323 System
.err
.println("Aborting sending.");
325 } catch (DBusExecutionException e
) {
326 handleDBusExecutionException(e
);
333 if (dBusConn
!= null) {
335 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
337 public void handle(Signal
.MessageReceived s
) {
338 System
.out
.print(String
.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
339 s
.getSender(), formatTimestamp(s
.getTimestamp()), s
.getMessage()));
340 if (s
.getGroupId().length
> 0) {
341 System
.out
.println("Group info:");
342 System
.out
.println(" Id: " + Base64
.encodeBytes(s
.getGroupId()));
344 if (s
.getAttachments().size() > 0) {
345 System
.out
.println("Attachments: ");
346 for (String attachment
: s
.getAttachments()) {
347 System
.out
.println("- Stored plaintext in: " + attachment
);
350 System
.out
.println();
353 } catch (DBusException e
) {
360 } catch (InterruptedException e
) {
365 if (!m
.isRegistered()) {
366 System
.err
.println("User is not registered.");
370 if (ns
.getDouble("timeout") != null) {
371 timeout
= ns
.getDouble("timeout");
373 boolean returnOnTimeout
= true;
375 returnOnTimeout
= false;
379 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, new ReceiveMessageHandler(m
));
380 } catch (IOException e
) {
381 System
.err
.println("Error while receiving messages: " + e
.getMessage());
383 } catch (AssertionError e
) {
384 handleAssertionError(e
);
389 if (dBusConn
!= null) {
390 System
.err
.println("quitGroup is not yet implemented via dbus");
393 if (!m
.isRegistered()) {
394 System
.err
.println("User is not registered.");
399 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
400 } catch (IOException e
) {
401 handleIOException(e
);
403 } catch (EncapsulatedExceptions e
) {
404 handleEncapsulatedExceptions(e
);
406 } catch (AssertionError e
) {
407 handleAssertionError(e
);
409 } catch (GroupNotFoundException e
) {
410 handleGroupNotFoundException(e
);
412 } catch (NotAGroupMemberException e
) {
413 handleNotAGroupMemberException(e
);
419 if (dBusConn
!= null) {
420 System
.err
.println("updateGroup is not yet implemented via dbus");
423 if (!m
.isRegistered()) {
424 System
.err
.println("User is not registered.");
429 byte[] groupId
= null;
430 if (ns
.getString("group") != null) {
431 groupId
= decodeGroupId(ns
.getString("group"));
433 byte[] newGroupId
= m
.sendUpdateGroupMessage(groupId
, ns
.getString("name"), ns
.<String
>getList("member"), ns
.getString("avatar"));
434 if (groupId
== null) {
435 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
437 } catch (IOException e
) {
438 handleIOException(e
);
440 } catch (AttachmentInvalidException e
) {
441 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
442 System
.err
.println("Aborting sending.");
444 } catch (GroupNotFoundException e
) {
445 handleGroupNotFoundException(e
);
447 } catch (NotAGroupMemberException e
) {
448 handleNotAGroupMemberException(e
);
450 } catch (EncapsulatedExceptions e
) {
451 handleEncapsulatedExceptions(e
);
456 case "listIdentities":
457 if (dBusConn
!= null) {
458 System
.err
.println("listIdentities is not yet implemented via dbus");
461 if (!m
.isRegistered()) {
462 System
.err
.println("User is not registered.");
465 if (ns
.get("number") == null) {
466 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
467 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
468 printIdentityFingerprint(m
, keys
.getKey(), id
);
472 String number
= ns
.getString("number");
473 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
474 printIdentityFingerprint(m
, number
, id
);
479 if (dBusConn
!= null) {
480 System
.err
.println("trust is not yet implemented via dbus");
483 if (!m
.isRegistered()) {
484 System
.err
.println("User is not registered.");
487 String number
= ns
.getString("number");
488 if (ns
.getBoolean("trust_all_known_keys")) {
489 boolean res
= m
.trustIdentityAllKeys(number
);
491 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
495 String fingerprint
= ns
.getString("verified_fingerprint");
496 if (fingerprint
!= null) {
497 fingerprint
= fingerprint
.replaceAll(" ", "");
498 if (fingerprint
.length() == 66) {
499 byte[] fingerprintBytes
;
501 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
502 } catch (Exception e
) {
503 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
506 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
508 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
511 } else if (fingerprint
.length() == 60) {
512 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
514 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.");
518 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
522 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
528 if (dBusConn
!= null) {
529 System
.err
.println("Stop it.");
532 if (!m
.isRegistered()) {
533 System
.err
.println("User is not registered.");
536 DBusConnection conn
= null;
540 if (ns
.getBoolean("system")) {
541 busType
= DBusConnection
.SYSTEM
;
543 busType
= DBusConnection
.SESSION
;
545 conn
= DBusConnection
.getConnection(busType
);
546 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
547 conn
.requestBusName(SIGNAL_BUSNAME
);
548 } catch (DBusException e
) {
553 m
.receiveMessages(1, TimeUnit
.HOURS
, false, new DbusReceiveMessageHandler(m
, conn
));
554 } catch (IOException e
) {
555 System
.err
.println("Error while receiving messages: " + e
.getMessage());
557 } catch (AssertionError e
) {
558 handleAssertionError(e
);
571 if (dBusConn
!= null) {
572 dBusConn
.disconnect();
577 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
578 String digits
= formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.identityKey
));
579 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
580 theirId
.trustLevel
, theirId
.added
, Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
583 private static String
formatSafetyNumber(String digits
) {
584 final int partCount
= 12;
585 int partSize
= digits
.length() / partCount
;
586 StringBuilder f
= new StringBuilder(digits
.length() + partCount
);
587 for (int i
= 0; i
< partCount
; i
++) {
588 f
.append(digits
.substring(i
* partSize
, (i
* partSize
) + partSize
)).append(" ");
593 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
594 System
.err
.println("Failed to send to group: " + e
.getMessage());
595 System
.err
.println("Aborting sending.");
598 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
599 System
.err
.println("Failed to send to group: " + e
.getMessage());
600 System
.err
.println("Update the group on another device to readd the user to this group.");
601 System
.err
.println("Aborting sending.");
605 private static void handleDBusExecutionException(DBusExecutionException e
) {
606 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
607 System
.err
.println("Aborting.");
610 private static byte[] decodeGroupId(String groupId
) {
612 return Base64
.decode(groupId
);
613 } catch (IOException e
) {
614 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
615 System
.err
.println("Aborting sending.");
621 private static Namespace
parseArgs(String
[] args
) {
622 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("signal-cli")
624 .description("Commandline interface for Signal.")
625 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
627 parser
.addArgument("-v", "--version")
628 .help("Show package version.")
629 .action(Arguments
.version());
630 parser
.addArgument("--config")
631 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
633 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
634 mut
.addArgument("-u", "--username")
635 .help("Specify your phone number, that will be used for verification.");
636 mut
.addArgument("--dbus")
637 .help("Make request via user dbus.")
638 .action(Arguments
.storeTrue());
639 mut
.addArgument("--dbus-system")
640 .help("Make request via system dbus.")
641 .action(Arguments
.storeTrue());
643 Subparsers subparsers
= parser
.addSubparsers()
644 .title("subcommands")
646 .description("valid subcommands")
647 .help("additional help");
649 Subparser parserLink
= subparsers
.addParser("link");
650 parserLink
.addArgument("-n", "--name")
651 .help("Specify a name to describe this new device.");
653 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
654 parserAddDevice
.addArgument("--uri")
656 .help("Specify the uri contained in the QR code shown by the new device.");
658 Subparser parserDevices
= subparsers
.addParser("listDevices");
660 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
661 parserRemoveDevice
.addArgument("-d", "--deviceId")
664 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
666 Subparser parserRegister
= subparsers
.addParser("register");
667 parserRegister
.addArgument("-v", "--voice")
668 .help("The verification should be done over voice, not sms.")
669 .action(Arguments
.storeTrue());
671 Subparser parserVerify
= subparsers
.addParser("verify");
672 parserVerify
.addArgument("verificationCode")
673 .help("The verification code you received via sms or voice call.");
675 Subparser parserSend
= subparsers
.addParser("send");
676 parserSend
.addArgument("-g", "--group")
677 .help("Specify the recipient group ID.");
678 parserSend
.addArgument("recipient")
679 .help("Specify the recipients' phone number.")
681 parserSend
.addArgument("-m", "--message")
682 .help("Specify the message, if missing standard input is used.");
683 parserSend
.addArgument("-a", "--attachment")
685 .help("Add file as attachment");
686 parserSend
.addArgument("-e", "--endsession")
687 .help("Clear session state and send end session message.")
688 .action(Arguments
.storeTrue());
690 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
691 parserLeaveGroup
.addArgument("-g", "--group")
693 .help("Specify the recipient group ID.");
695 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
696 parserUpdateGroup
.addArgument("-g", "--group")
697 .help("Specify the recipient group ID.");
698 parserUpdateGroup
.addArgument("-n", "--name")
699 .help("Specify the new group name.");
700 parserUpdateGroup
.addArgument("-a", "--avatar")
701 .help("Specify a new group avatar image file");
702 parserUpdateGroup
.addArgument("-m", "--member")
704 .help("Specify one or more members to add to the group");
706 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
707 parserListIdentities
.addArgument("-n", "--number")
708 .help("Only show identity keys for the given phone number.");
710 Subparser parserTrust
= subparsers
.addParser("trust");
711 parserTrust
.addArgument("number")
712 .help("Specify the phone number, for which to set the trust.")
714 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
715 mutTrust
.addArgument("-a", "--trust-all-known-keys")
716 .help("Trust all known keys of this user, only use this for testing.")
717 .action(Arguments
.storeTrue());
718 mutTrust
.addArgument("-v", "--verified-fingerprint")
719 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
721 Subparser parserReceive
= subparsers
.addParser("receive");
722 parserReceive
.addArgument("-t", "--timeout")
724 .help("Number of seconds to wait for new messages (negative values disable timeout)");
726 Subparser parserDaemon
= subparsers
.addParser("daemon");
727 parserDaemon
.addArgument("--system")
728 .action(Arguments
.storeTrue())
729 .help("Use DBus system bus instead of user bus.");
732 Namespace ns
= parser
.parseArgs(args
);
733 if ("link".equals(ns
.getString("command"))) {
734 if (ns
.getString("username") != null) {
736 System
.err
.println("You cannot specify a username (phone number) when linking");
739 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
740 if (ns
.getString("username") == null) {
742 System
.err
.println("You need to specify a username (phone number)");
745 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
746 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
750 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
751 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
755 } catch (ArgumentParserException e
) {
756 parser
.handleError(e
);
761 private static void handleAssertionError(AssertionError e
) {
762 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
764 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
767 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
768 System
.err
.println("Failed to send (some) messages:");
769 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
770 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
772 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
773 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
775 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
776 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
780 private static void handleIOException(IOException e
) {
781 System
.err
.println("Failed to send message: " + e
.getMessage());
784 private static String
readAll(InputStream
in) throws IOException
{
785 StringWriter output
= new StringWriter();
786 byte[] buffer
= new byte[4096];
789 while (-1 != (n
= System
.in.read(buffer
))) {
790 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
793 return output
.toString();
796 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
799 public ReceiveMessageHandler(Manager m
) {
804 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
805 SignalServiceAddress source
= envelope
.getSourceAddress();
806 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
807 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
808 if (source
.getRelay().isPresent()) {
809 System
.out
.println("Relayed by: " + source
.getRelay().get());
811 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
813 if (envelope
.isReceipt()) {
814 System
.out
.println("Got receipt.");
815 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
816 if (exception
!= null) {
817 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
818 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
819 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
820 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");
821 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");
823 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
826 if (content
== null) {
827 System
.out
.println("Failed to decrypt message.");
829 if (content
.getDataMessage().isPresent()) {
830 SignalServiceDataMessage message
= content
.getDataMessage().get();
831 handleSignalServiceDataMessage(message
);
833 if (content
.getSyncMessage().isPresent()) {
834 System
.out
.println("Received a sync message");
835 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
837 if (syncMessage
.getContacts().isPresent()) {
838 System
.out
.println("Received sync contacts");
839 printAttachment(syncMessage
.getContacts().get());
841 if (syncMessage
.getGroups().isPresent()) {
842 System
.out
.println("Received sync groups");
843 printAttachment(syncMessage
.getGroups().get());
845 if (syncMessage
.getRead().isPresent()) {
846 System
.out
.println("Received sync read messages list");
847 for (ReadMessage rm
: syncMessage
.getRead().get()) {
848 ContactInfo fromContact
= m
.getContact(rm
.getSender());
849 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + formatTimestamp(rm
.getTimestamp()));
852 if (syncMessage
.getRequest().isPresent()) {
853 System
.out
.println("Received sync request");
854 if (syncMessage
.getRequest().get().isContactsRequest()) {
855 System
.out
.println(" - contacts request");
857 if (syncMessage
.getRequest().get().isGroupsRequest()) {
858 System
.out
.println(" - groups request");
861 if (syncMessage
.getSent().isPresent()) {
862 System
.out
.println("Received sync sent message");
863 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
865 if (sentTranscriptMessage
.getDestination().isPresent()) {
866 String dest
= sentTranscriptMessage
.getDestination().get();
867 ContactInfo destContact
= m
.getContact(dest
);
868 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
872 System
.out
.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage
.getTimestamp()));
873 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
874 System
.out
.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
876 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
877 handleSignalServiceDataMessage(message
);
879 if (syncMessage
.getBlockedList().isPresent()) {
880 System
.out
.println("Received sync message with block list");
881 System
.out
.println("Blocked numbers:");
882 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
883 for (String number
: blockedList
.getNumbers()) {
884 System
.out
.println(" - " + number
);
890 System
.out
.println("Unknown message received.");
892 System
.out
.println();
895 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
896 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
898 if (message
.getBody().isPresent()) {
899 System
.out
.println("Body: " + message
.getBody().get());
901 if (message
.getGroupInfo().isPresent()) {
902 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
903 System
.out
.println("Group info:");
904 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
905 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
906 System
.out
.println(" Name: " + groupInfo
.getName().get());
908 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
910 System
.out
.println(" Name: " + group
.name
);
912 System
.out
.println(" Name: <Unknown group>");
915 System
.out
.println(" Type: " + groupInfo
.getType());
916 if (groupInfo
.getMembers().isPresent()) {
917 for (String member
: groupInfo
.getMembers().get()) {
918 System
.out
.println(" Member: " + member
);
921 if (groupInfo
.getAvatar().isPresent()) {
922 System
.out
.println(" Avatar:");
923 printAttachment(groupInfo
.getAvatar().get());
926 if (message
.isEndSession()) {
927 System
.out
.println("Is end session");
929 if (message
.isExpirationUpdate()) {
930 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
932 if (message
.getExpiresInSeconds() > 0) {
933 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
936 if (message
.getAttachments().isPresent()) {
937 System
.out
.println("Attachments: ");
938 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
939 printAttachment(attachment
);
944 private void printAttachment(SignalServiceAttachment attachment
) {
945 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
946 if (attachment
.isPointer()) {
947 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
948 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
949 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
950 File file
= m
.getAttachmentFile(pointer
.getId());
952 System
.out
.println(" Stored plaintext in: " + file
);
958 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
959 final DBusConnection conn
;
961 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
967 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
968 super.handleMessage(envelope
, content
, exception
);
970 if (!envelope
.isReceipt() && content
!= null && content
.getDataMessage().isPresent()) {
971 SignalServiceDataMessage message
= content
.getDataMessage().get();
973 if (!message
.isEndSession() &&
974 !(message
.getGroupInfo().isPresent() &&
975 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
976 List
<String
> attachments
= new ArrayList
<>();
977 if (message
.getAttachments().isPresent()) {
978 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
979 if (attachment
.isPointer()) {
980 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
986 conn
.sendSignal(new Signal
.MessageReceived(
988 message
.getTimestamp(),
989 envelope
.getSource(),
990 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
991 message
.getBody().isPresent() ? message
.getBody().get() : "",
993 } catch (DBusException e
) {
1002 private static String
formatTimestamp(long timestamp
) {
1003 Date date
= new Date(timestamp
);
1004 final DateFormat df
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
1005 df
.setTimeZone(tzUTC
);
1006 return timestamp
+ " (" + df
.format(date
) + ")";