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
.TimeoutException
;
53 public static final String SIGNAL_BUSNAME
= "org.asamk.Signal";
54 public static final String SIGNAL_OBJECTPATH
= "/org/asamk/Signal";
56 private static final TimeZone tzUTC
= TimeZone
.getTimeZone("UTC");
58 public static void main(String
[] args
) {
59 // Workaround for BKS truststore
60 Security
.insertProviderAt(new org
.bouncycastle
.jce
.provider
.BouncyCastleProvider(), 1);
62 Namespace ns
= parseArgs(args
);
67 int res
= handleCommands(ns
);
71 private static int handleCommands(Namespace ns
) {
72 final String username
= ns
.getString("username");
75 DBusConnection dBusConn
= null;
77 if (ns
.getBoolean("dbus") || ns
.getBoolean("dbus_system")) {
81 if (ns
.getBoolean("dbus_system")) {
82 busType
= DBusConnection
.SYSTEM
;
84 busType
= DBusConnection
.SESSION
;
86 dBusConn
= DBusConnection
.getConnection(busType
);
87 ts
= (Signal
) dBusConn
.getRemoteObject(
88 SIGNAL_BUSNAME
, SIGNAL_OBJECTPATH
,
90 } catch (DBusException e
) {
92 if (dBusConn
!= null) {
93 dBusConn
.disconnect();
98 String settingsPath
= ns
.getString("config");
99 if (TextUtils
.isEmpty(settingsPath
)) {
100 settingsPath
= System
.getProperty("user.home") + "/.config/signal";
101 if (!new File(settingsPath
).exists()) {
102 String legacySettingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
103 if (new File(legacySettingsPath
).exists()) {
104 settingsPath
= legacySettingsPath
;
109 m
= new Manager(username
, settingsPath
);
111 if (m
.userExists()) {
114 } catch (Exception e
) {
115 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
121 switch (ns
.getString("command")) {
123 if (dBusConn
!= null) {
124 System
.err
.println("register is not yet implemented via dbus");
127 if (!m
.userHasKeys()) {
128 m
.createNewIdentity();
131 m
.register(ns
.getBoolean("voice"));
132 } catch (IOException e
) {
133 System
.err
.println("Request verify error: " + e
.getMessage());
138 if (dBusConn
!= null) {
139 System
.err
.println("verify is not yet implemented via dbus");
142 if (!m
.userHasKeys()) {
143 System
.err
.println("User has no keys, first call register.");
146 if (m
.isRegistered()) {
147 System
.err
.println("User registration is already verified");
151 m
.verifyAccount(ns
.getString("verificationCode"));
152 } catch (IOException e
) {
153 System
.err
.println("Verify error: " + e
.getMessage());
158 if (dBusConn
!= null) {
159 System
.err
.println("link is not yet implemented via dbus");
163 // When linking, username is null and we always have to create keys
164 m
.createNewIdentity();
166 String deviceName
= ns
.getString("name");
167 if (deviceName
== null) {
171 System
.out
.println(m
.getDeviceLinkUri());
172 m
.finishDeviceLink(deviceName
);
173 System
.out
.println("Associated with: " + m
.getUsername());
174 } catch (TimeoutException e
) {
175 System
.err
.println("Link request timed out, please try again.");
177 } catch (IOException e
) {
178 System
.err
.println("Link request error: " + e
.getMessage());
180 } catch (InvalidKeyException e
) {
183 } catch (UserAlreadyExists e
) {
184 System
.err
.println("The user " + e
.getUsername() + " already exists\nDelete \"" + e
.getFileName() + "\" before trying again.");
189 if (dBusConn
!= null) {
190 System
.err
.println("link is not yet implemented via dbus");
193 if (!m
.isRegistered()) {
194 System
.err
.println("User is not registered.");
198 m
.addDeviceLink(new URI(ns
.getString("uri")));
199 } catch (IOException e
) {
202 } catch (InvalidKeyException e
) {
205 } catch (URISyntaxException e
) {
211 if (dBusConn
!= null) {
212 System
.err
.println("listDevices is not yet implemented via dbus");
215 if (!m
.isRegistered()) {
216 System
.err
.println("User is not registered.");
220 List
<DeviceInfo
> devices
= m
.getLinkedDevices();
221 for (DeviceInfo d
: devices
) {
222 System
.out
.println("Device " + d
.getId() + (d
.getId() == m
.getDeviceId() ?
" (this device)" : "") + ":");
223 System
.out
.println(" Name: " + d
.getName());
224 System
.out
.println(" Created: " + d
.getCreated());
225 System
.out
.println(" Last seen: " + d
.getLastSeen());
227 } catch (IOException e
) {
233 if (dBusConn
!= null) {
234 System
.err
.println("removeDevice is not yet implemented via dbus");
237 if (!m
.isRegistered()) {
238 System
.err
.println("User is not registered.");
242 int deviceId
= ns
.getInt("deviceId");
243 m
.removeLinkedDevices(deviceId
);
244 } catch (IOException e
) {
250 if (dBusConn
== null && !m
.isRegistered()) {
251 System
.err
.println("User is not registered.");
255 if (ns
.getBoolean("endsession")) {
256 if (ns
.getList("recipient") == null) {
257 System
.err
.println("No recipients given");
258 System
.err
.println("Aborting sending.");
262 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
263 } catch (IOException e
) {
264 handleIOException(e
);
266 } catch (EncapsulatedExceptions e
) {
267 handleEncapsulatedExceptions(e
);
269 } catch (AssertionError e
) {
270 handleAssertionError(e
);
272 } catch (DBusExecutionException e
) {
273 handleDBusExecutionException(e
);
277 String messageText
= ns
.getString("message");
278 if (messageText
== null) {
280 messageText
= readAll(System
.in);
281 } catch (IOException e
) {
282 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
283 System
.err
.println("Aborting sending.");
289 List
<String
> attachments
= ns
.getList("attachment");
290 if (attachments
== null) {
291 attachments
= new ArrayList
<>();
293 if (ns
.getString("group") != null) {
294 byte[] groupId
= decodeGroupId(ns
.getString("group"));
295 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
297 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
299 } catch (IOException e
) {
300 handleIOException(e
);
302 } catch (EncapsulatedExceptions e
) {
303 handleEncapsulatedExceptions(e
);
305 } catch (AssertionError e
) {
306 handleAssertionError(e
);
308 } catch (GroupNotFoundException e
) {
309 handleGroupNotFoundException(e
);
311 } catch (NotAGroupMemberException e
) {
312 handleNotAGroupMemberException(e
);
314 } catch (AttachmentInvalidException e
) {
315 System
.err
.println("Failed to add attachment: " + e
.getMessage());
316 System
.err
.println("Aborting sending.");
318 } catch (DBusExecutionException e
) {
319 handleDBusExecutionException(e
);
326 if (dBusConn
!= null) {
328 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
330 public void handle(Signal
.MessageReceived s
) {
331 System
.out
.print(String
.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
332 s
.getSender(), formatTimestamp(s
.getTimestamp()), s
.getMessage()));
333 if (s
.getGroupId().length
> 0) {
334 System
.out
.println("Group info:");
335 System
.out
.println(" Id: " + Base64
.encodeBytes(s
.getGroupId()));
337 if (s
.getAttachments().size() > 0) {
338 System
.out
.println("Attachments: ");
339 for (String attachment
: s
.getAttachments()) {
340 System
.out
.println("- Stored plaintext in: " + attachment
);
343 System
.out
.println();
346 } catch (DBusException e
) {
353 } catch (InterruptedException e
) {
358 if (!m
.isRegistered()) {
359 System
.err
.println("User is not registered.");
363 if (ns
.getInt("timeout") != null) {
364 timeout
= ns
.getInt("timeout");
366 boolean returnOnTimeout
= true;
368 returnOnTimeout
= false;
372 m
.receiveMessages(timeout
, returnOnTimeout
, new ReceiveMessageHandler(m
));
373 } catch (IOException e
) {
374 System
.err
.println("Error while receiving messages: " + e
.getMessage());
376 } catch (AssertionError e
) {
377 handleAssertionError(e
);
382 if (dBusConn
!= null) {
383 System
.err
.println("quitGroup is not yet implemented via dbus");
386 if (!m
.isRegistered()) {
387 System
.err
.println("User is not registered.");
392 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
393 } catch (IOException e
) {
394 handleIOException(e
);
396 } catch (EncapsulatedExceptions e
) {
397 handleEncapsulatedExceptions(e
);
399 } catch (AssertionError e
) {
400 handleAssertionError(e
);
402 } catch (GroupNotFoundException e
) {
403 handleGroupNotFoundException(e
);
405 } catch (NotAGroupMemberException e
) {
406 handleNotAGroupMemberException(e
);
412 if (dBusConn
!= null) {
413 System
.err
.println("updateGroup is not yet implemented via dbus");
416 if (!m
.isRegistered()) {
417 System
.err
.println("User is not registered.");
422 byte[] groupId
= null;
423 if (ns
.getString("group") != null) {
424 groupId
= decodeGroupId(ns
.getString("group"));
426 byte[] newGroupId
= m
.sendUpdateGroupMessage(groupId
, ns
.getString("name"), ns
.<String
>getList("member"), ns
.getString("avatar"));
427 if (groupId
== null) {
428 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
430 } catch (IOException e
) {
431 handleIOException(e
);
433 } catch (AttachmentInvalidException e
) {
434 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
435 System
.err
.println("Aborting sending.");
437 } catch (GroupNotFoundException e
) {
438 handleGroupNotFoundException(e
);
440 } catch (NotAGroupMemberException e
) {
441 handleNotAGroupMemberException(e
);
443 } catch (EncapsulatedExceptions e
) {
444 handleEncapsulatedExceptions(e
);
449 case "listIdentities":
450 if (dBusConn
!= null) {
451 System
.err
.println("listIdentities is not yet implemented via dbus");
454 if (!m
.isRegistered()) {
455 System
.err
.println("User is not registered.");
458 if (ns
.get("number") == null) {
459 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
460 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
461 printIdentityFingerprint(m
, keys
.getKey(), id
);
465 String number
= ns
.getString("number");
466 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
467 printIdentityFingerprint(m
, number
, id
);
472 if (dBusConn
!= null) {
473 System
.err
.println("trust is not yet implemented via dbus");
476 if (!m
.isRegistered()) {
477 System
.err
.println("User is not registered.");
480 String number
= ns
.getString("number");
481 if (ns
.getBoolean("trust_all_known_keys")) {
482 boolean res
= m
.trustIdentityAllKeys(number
);
484 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
488 String fingerprint
= ns
.getString("verified_fingerprint");
489 if (fingerprint
!= null) {
490 fingerprint
= fingerprint
.replaceAll(" ", "");
491 if (fingerprint
.length() == 66) {
492 byte[] fingerprintBytes
;
494 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
495 } catch (Exception e
) {
496 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
499 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
501 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
504 } else if (fingerprint
.length() == 60) {
505 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
507 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.");
511 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
515 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
521 if (dBusConn
!= null) {
522 System
.err
.println("Stop it.");
525 if (!m
.isRegistered()) {
526 System
.err
.println("User is not registered.");
529 DBusConnection conn
= null;
533 if (ns
.getBoolean("system")) {
534 busType
= DBusConnection
.SYSTEM
;
536 busType
= DBusConnection
.SESSION
;
538 conn
= DBusConnection
.getConnection(busType
);
539 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
540 conn
.requestBusName(SIGNAL_BUSNAME
);
541 } catch (DBusException e
) {
546 m
.receiveMessages(3600, false, new DbusReceiveMessageHandler(m
, conn
));
547 } catch (IOException e
) {
548 System
.err
.println("Error while receiving messages: " + e
.getMessage());
550 } catch (AssertionError e
) {
551 handleAssertionError(e
);
564 if (dBusConn
!= null) {
565 dBusConn
.disconnect();
570 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
571 String digits
= formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.identityKey
));
572 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
573 theirId
.trustLevel
, theirId
.added
, Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
576 private static String
formatSafetyNumber(String digits
) {
577 final int partCount
= 12;
578 int partSize
= digits
.length() / partCount
;
579 StringBuilder f
= new StringBuilder(digits
.length() + partCount
);
580 for (int i
= 0; i
< partCount
; i
++) {
581 f
.append(digits
.substring(i
* partSize
, (i
* partSize
) + partSize
)).append(" ");
586 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
587 System
.err
.println("Failed to send to group: " + e
.getMessage());
588 System
.err
.println("Aborting sending.");
591 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
592 System
.err
.println("Failed to send to group: " + e
.getMessage());
593 System
.err
.println("Update the group on another device to readd the user to this group.");
594 System
.err
.println("Aborting sending.");
598 private static void handleDBusExecutionException(DBusExecutionException e
) {
599 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
600 System
.err
.println("Aborting.");
603 private static byte[] decodeGroupId(String groupId
) {
605 return Base64
.decode(groupId
);
606 } catch (IOException e
) {
607 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
608 System
.err
.println("Aborting sending.");
614 private static Namespace
parseArgs(String
[] args
) {
615 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("signal-cli")
617 .description("Commandline interface for Signal.")
618 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
620 parser
.addArgument("-v", "--version")
621 .help("Show package version.")
622 .action(Arguments
.version());
623 parser
.addArgument("--config")
624 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
626 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
627 mut
.addArgument("-u", "--username")
628 .help("Specify your phone number, that will be used for verification.");
629 mut
.addArgument("--dbus")
630 .help("Make request via user dbus.")
631 .action(Arguments
.storeTrue());
632 mut
.addArgument("--dbus-system")
633 .help("Make request via system dbus.")
634 .action(Arguments
.storeTrue());
636 Subparsers subparsers
= parser
.addSubparsers()
637 .title("subcommands")
639 .description("valid subcommands")
640 .help("additional help");
642 Subparser parserLink
= subparsers
.addParser("link");
643 parserLink
.addArgument("-n", "--name")
644 .help("Specify a name to describe this new device.");
646 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
647 parserAddDevice
.addArgument("--uri")
649 .help("Specify the uri contained in the QR code shown by the new device.");
651 Subparser parserDevices
= subparsers
.addParser("listDevices");
653 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
654 parserRemoveDevice
.addArgument("-d", "--deviceId")
657 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
659 Subparser parserRegister
= subparsers
.addParser("register");
660 parserRegister
.addArgument("-v", "--voice")
661 .help("The verification should be done over voice, not sms.")
662 .action(Arguments
.storeTrue());
664 Subparser parserVerify
= subparsers
.addParser("verify");
665 parserVerify
.addArgument("verificationCode")
666 .help("The verification code you received via sms or voice call.");
668 Subparser parserSend
= subparsers
.addParser("send");
669 parserSend
.addArgument("-g", "--group")
670 .help("Specify the recipient group ID.");
671 parserSend
.addArgument("recipient")
672 .help("Specify the recipients' phone number.")
674 parserSend
.addArgument("-m", "--message")
675 .help("Specify the message, if missing standard input is used.");
676 parserSend
.addArgument("-a", "--attachment")
678 .help("Add file as attachment");
679 parserSend
.addArgument("-e", "--endsession")
680 .help("Clear session state and send end session message.")
681 .action(Arguments
.storeTrue());
683 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
684 parserLeaveGroup
.addArgument("-g", "--group")
686 .help("Specify the recipient group ID.");
688 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
689 parserUpdateGroup
.addArgument("-g", "--group")
690 .help("Specify the recipient group ID.");
691 parserUpdateGroup
.addArgument("-n", "--name")
692 .help("Specify the new group name.");
693 parserUpdateGroup
.addArgument("-a", "--avatar")
694 .help("Specify a new group avatar image file");
695 parserUpdateGroup
.addArgument("-m", "--member")
697 .help("Specify one or more members to add to the group");
699 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
700 parserListIdentities
.addArgument("-n", "--number")
701 .help("Only show identity keys for the given phone number.");
703 Subparser parserTrust
= subparsers
.addParser("trust");
704 parserTrust
.addArgument("number")
705 .help("Specify the phone number, for which to set the trust.")
707 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
708 mutTrust
.addArgument("-a", "--trust-all-known-keys")
709 .help("Trust all known keys of this user, only use this for testing.")
710 .action(Arguments
.storeTrue());
711 mutTrust
.addArgument("-v", "--verified-fingerprint")
712 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
714 Subparser parserReceive
= subparsers
.addParser("receive");
715 parserReceive
.addArgument("-t", "--timeout")
717 .help("Number of seconds to wait for new messages (negative values disable timeout)");
719 Subparser parserDaemon
= subparsers
.addParser("daemon");
720 parserDaemon
.addArgument("--system")
721 .action(Arguments
.storeTrue())
722 .help("Use DBus system bus instead of user bus.");
725 Namespace ns
= parser
.parseArgs(args
);
726 if ("link".equals(ns
.getString("command"))) {
727 if (ns
.getString("username") != null) {
729 System
.err
.println("You cannot specify a username (phone number) when linking");
732 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
733 if (ns
.getString("username") == null) {
735 System
.err
.println("You need to specify a username (phone number)");
738 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
739 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
743 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
744 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
748 } catch (ArgumentParserException e
) {
749 parser
.handleError(e
);
754 private static void handleAssertionError(AssertionError e
) {
755 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
757 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
760 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
761 System
.err
.println("Failed to send (some) messages:");
762 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
763 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
765 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
766 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
768 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
769 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
773 private static void handleIOException(IOException e
) {
774 System
.err
.println("Failed to send message: " + e
.getMessage());
777 private static String
readAll(InputStream
in) throws IOException
{
778 StringWriter output
= new StringWriter();
779 byte[] buffer
= new byte[4096];
782 while (-1 != (n
= System
.in.read(buffer
))) {
783 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
786 return output
.toString();
789 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
792 public ReceiveMessageHandler(Manager m
) {
797 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
798 SignalServiceAddress source
= envelope
.getSourceAddress();
799 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
800 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
801 if (source
.getRelay().isPresent()) {
802 System
.out
.println("Relayed by: " + source
.getRelay().get());
804 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
806 if (envelope
.isReceipt()) {
807 System
.out
.println("Got receipt.");
808 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
809 if (exception
!= null) {
810 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
811 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
812 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
813 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");
814 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");
816 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
819 if (content
== null) {
820 System
.out
.println("Failed to decrypt message.");
822 if (content
.getDataMessage().isPresent()) {
823 SignalServiceDataMessage message
= content
.getDataMessage().get();
824 handleSignalServiceDataMessage(message
);
826 if (content
.getSyncMessage().isPresent()) {
827 System
.out
.println("Received a sync message");
828 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
830 if (syncMessage
.getContacts().isPresent()) {
831 System
.out
.println("Received sync contacts");
832 printAttachment(syncMessage
.getContacts().get());
834 if (syncMessage
.getGroups().isPresent()) {
835 System
.out
.println("Received sync groups");
836 printAttachment(syncMessage
.getGroups().get());
838 if (syncMessage
.getRead().isPresent()) {
839 System
.out
.println("Received sync read messages list");
840 for (ReadMessage rm
: syncMessage
.getRead().get()) {
841 ContactInfo fromContact
= m
.getContact(rm
.getSender());
842 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + formatTimestamp(rm
.getTimestamp()));
845 if (syncMessage
.getRequest().isPresent()) {
846 System
.out
.println("Received sync request");
847 if (syncMessage
.getRequest().get().isContactsRequest()) {
848 System
.out
.println(" - contacts request");
850 if (syncMessage
.getRequest().get().isGroupsRequest()) {
851 System
.out
.println(" - groups request");
854 if (syncMessage
.getSent().isPresent()) {
855 System
.out
.println("Received sync sent message");
856 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
858 if (sentTranscriptMessage
.getDestination().isPresent()) {
859 String dest
= sentTranscriptMessage
.getDestination().get();
860 ContactInfo destContact
= m
.getContact(dest
);
861 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
865 System
.out
.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage
.getTimestamp()));
866 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
867 System
.out
.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
869 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
870 handleSignalServiceDataMessage(message
);
872 if (syncMessage
.getBlockedList().isPresent()) {
873 System
.out
.println("Received sync message with block list");
874 System
.out
.println("Blocked numbers:");
875 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
876 for (String number
: blockedList
.getNumbers()) {
877 System
.out
.println(" - " + number
);
883 System
.out
.println("Unknown message received.");
885 System
.out
.println();
888 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
889 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
891 if (message
.getBody().isPresent()) {
892 System
.out
.println("Body: " + message
.getBody().get());
894 if (message
.getGroupInfo().isPresent()) {
895 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
896 System
.out
.println("Group info:");
897 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
898 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
899 System
.out
.println(" Name: " + groupInfo
.getName().get());
901 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
903 System
.out
.println(" Name: " + group
.name
);
905 System
.out
.println(" Name: <Unknown group>");
908 System
.out
.println(" Type: " + groupInfo
.getType());
909 if (groupInfo
.getMembers().isPresent()) {
910 for (String member
: groupInfo
.getMembers().get()) {
911 System
.out
.println(" Member: " + member
);
914 if (groupInfo
.getAvatar().isPresent()) {
915 System
.out
.println(" Avatar:");
916 printAttachment(groupInfo
.getAvatar().get());
919 if (message
.isEndSession()) {
920 System
.out
.println("Is end session");
922 if (message
.isExpirationUpdate()) {
923 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
925 if (message
.getExpiresInSeconds() > 0) {
926 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
929 if (message
.getAttachments().isPresent()) {
930 System
.out
.println("Attachments: ");
931 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
932 printAttachment(attachment
);
937 private void printAttachment(SignalServiceAttachment attachment
) {
938 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
939 if (attachment
.isPointer()) {
940 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
941 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
942 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
943 File file
= m
.getAttachmentFile(pointer
.getId());
945 System
.out
.println(" Stored plaintext in: " + file
);
951 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
952 final DBusConnection conn
;
954 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
960 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
961 super.handleMessage(envelope
, content
, exception
);
963 if (!envelope
.isReceipt() && content
!= null && content
.getDataMessage().isPresent()) {
964 SignalServiceDataMessage message
= content
.getDataMessage().get();
966 if (!message
.isEndSession() &&
967 !(message
.getGroupInfo().isPresent() &&
968 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
969 List
<String
> attachments
= new ArrayList
<>();
970 if (message
.getAttachments().isPresent()) {
971 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
972 if (attachment
.isPointer()) {
973 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
979 conn
.sendSignal(new Signal
.MessageReceived(
981 message
.getTimestamp(),
982 envelope
.getSource(),
983 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
984 message
.getBody().isPresent() ? message
.getBody().get() : "",
986 } catch (DBusException e
) {
995 private static String
formatTimestamp(long timestamp
) {
996 Date date
= new Date(timestamp
);
997 final DateFormat df
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
998 df
.setTimeZone(tzUTC
);
999 return timestamp
+ " (" + df
.format(date
) + ")";