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 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s", keys
.getKey(), id
.trustLevel
, id
.added
, Hex
.toStringCondensed(id
.getFingerprint())));
465 String number
= ns
.getString("number");
466 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
467 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s", number
, id
.trustLevel
, id
.added
, Hex
.toStringCondensed(id
.getFingerprint())));
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 byte[] fingerprintBytes
;
492 fingerprintBytes
= Hex
.toByteArray(fingerprint
.replaceAll(" ", "").toLowerCase(Locale
.ROOT
));
493 } catch (Exception e
) {
494 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
497 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
499 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
503 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
509 if (dBusConn
!= null) {
510 System
.err
.println("Stop it.");
513 if (!m
.isRegistered()) {
514 System
.err
.println("User is not registered.");
517 DBusConnection conn
= null;
521 if (ns
.getBoolean("system")) {
522 busType
= DBusConnection
.SYSTEM
;
524 busType
= DBusConnection
.SESSION
;
526 conn
= DBusConnection
.getConnection(busType
);
527 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
528 conn
.requestBusName(SIGNAL_BUSNAME
);
529 } catch (DBusException e
) {
534 m
.receiveMessages(3600, false, new DbusReceiveMessageHandler(m
, conn
));
535 } catch (IOException e
) {
536 System
.err
.println("Error while receiving messages: " + e
.getMessage());
538 } catch (AssertionError e
) {
539 handleAssertionError(e
);
552 if (dBusConn
!= null) {
553 dBusConn
.disconnect();
558 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
559 System
.err
.println("Failed to send to group: " + e
.getMessage());
560 System
.err
.println("Aborting sending.");
563 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
564 System
.err
.println("Failed to send to group: " + e
.getMessage());
565 System
.err
.println("Update the group on another device to readd the user to this group.");
566 System
.err
.println("Aborting sending.");
570 private static void handleDBusExecutionException(DBusExecutionException e
) {
571 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
572 System
.err
.println("Aborting.");
575 private static byte[] decodeGroupId(String groupId
) {
577 return Base64
.decode(groupId
);
578 } catch (IOException e
) {
579 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
580 System
.err
.println("Aborting sending.");
586 private static Namespace
parseArgs(String
[] args
) {
587 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("signal-cli")
589 .description("Commandline interface for Signal.")
590 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
592 parser
.addArgument("-v", "--version")
593 .help("Show package version.")
594 .action(Arguments
.version());
595 parser
.addArgument("--config")
596 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
598 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
599 mut
.addArgument("-u", "--username")
600 .help("Specify your phone number, that will be used for verification.");
601 mut
.addArgument("--dbus")
602 .help("Make request via user dbus.")
603 .action(Arguments
.storeTrue());
604 mut
.addArgument("--dbus-system")
605 .help("Make request via system dbus.")
606 .action(Arguments
.storeTrue());
608 Subparsers subparsers
= parser
.addSubparsers()
609 .title("subcommands")
611 .description("valid subcommands")
612 .help("additional help");
614 Subparser parserLink
= subparsers
.addParser("link");
615 parserLink
.addArgument("-n", "--name")
616 .help("Specify a name to describe this new device.");
618 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
619 parserAddDevice
.addArgument("--uri")
621 .help("Specify the uri contained in the QR code shown by the new device.");
623 Subparser parserDevices
= subparsers
.addParser("listDevices");
625 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
626 parserRemoveDevice
.addArgument("-d", "--deviceId")
629 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
631 Subparser parserRegister
= subparsers
.addParser("register");
632 parserRegister
.addArgument("-v", "--voice")
633 .help("The verification should be done over voice, not sms.")
634 .action(Arguments
.storeTrue());
636 Subparser parserVerify
= subparsers
.addParser("verify");
637 parserVerify
.addArgument("verificationCode")
638 .help("The verification code you received via sms or voice call.");
640 Subparser parserSend
= subparsers
.addParser("send");
641 parserSend
.addArgument("-g", "--group")
642 .help("Specify the recipient group ID.");
643 parserSend
.addArgument("recipient")
644 .help("Specify the recipients' phone number.")
646 parserSend
.addArgument("-m", "--message")
647 .help("Specify the message, if missing standard input is used.");
648 parserSend
.addArgument("-a", "--attachment")
650 .help("Add file as attachment");
651 parserSend
.addArgument("-e", "--endsession")
652 .help("Clear session state and send end session message.")
653 .action(Arguments
.storeTrue());
655 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
656 parserLeaveGroup
.addArgument("-g", "--group")
658 .help("Specify the recipient group ID.");
660 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
661 parserUpdateGroup
.addArgument("-g", "--group")
662 .help("Specify the recipient group ID.");
663 parserUpdateGroup
.addArgument("-n", "--name")
664 .help("Specify the new group name.");
665 parserUpdateGroup
.addArgument("-a", "--avatar")
666 .help("Specify a new group avatar image file");
667 parserUpdateGroup
.addArgument("-m", "--member")
669 .help("Specify one or more members to add to the group");
671 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
672 parserListIdentities
.addArgument("-n", "--number")
673 .help("Only show identity keys for the given phone number.");
675 Subparser parserTrust
= subparsers
.addParser("trust");
676 parserTrust
.addArgument("number")
677 .help("Specify the phone number, for which to set the trust.")
679 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
680 mutTrust
.addArgument("-a", "--trust-all-known-keys")
681 .help("Trust all known keys of this user, only use this for testing.")
682 .action(Arguments
.storeTrue());
683 mutTrust
.addArgument("-v", "--verified-fingerprint")
684 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
686 Subparser parserReceive
= subparsers
.addParser("receive");
687 parserReceive
.addArgument("-t", "--timeout")
689 .help("Number of seconds to wait for new messages (negative values disable timeout)");
691 Subparser parserDaemon
= subparsers
.addParser("daemon");
692 parserDaemon
.addArgument("--system")
693 .action(Arguments
.storeTrue())
694 .help("Use DBus system bus instead of user bus.");
697 Namespace ns
= parser
.parseArgs(args
);
698 if ("link".equals(ns
.getString("command"))) {
699 if (ns
.getString("username") != null) {
701 System
.err
.println("You cannot specify a username (phone number) when linking");
704 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
705 if (ns
.getString("username") == null) {
707 System
.err
.println("You need to specify a username (phone number)");
710 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
711 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
715 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
716 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
720 } catch (ArgumentParserException e
) {
721 parser
.handleError(e
);
726 private static void handleAssertionError(AssertionError e
) {
727 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
729 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
732 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
733 System
.err
.println("Failed to send (some) messages:");
734 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
735 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
737 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
738 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
740 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
741 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
745 private static void handleIOException(IOException e
) {
746 System
.err
.println("Failed to send message: " + e
.getMessage());
749 private static String
readAll(InputStream
in) throws IOException
{
750 StringWriter output
= new StringWriter();
751 byte[] buffer
= new byte[4096];
754 while (-1 != (n
= System
.in.read(buffer
))) {
755 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
758 return output
.toString();
761 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
764 public ReceiveMessageHandler(Manager m
) {
769 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
770 SignalServiceAddress source
= envelope
.getSourceAddress();
771 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
772 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
773 if (source
.getRelay().isPresent()) {
774 System
.out
.println("Relayed by: " + source
.getRelay().get());
776 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
778 if (envelope
.isReceipt()) {
779 System
.out
.println("Got receipt.");
780 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
781 if (exception
!= null) {
782 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
783 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
784 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
785 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");
786 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");
788 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
791 if (content
== null) {
792 System
.out
.println("Failed to decrypt message.");
794 if (content
.getDataMessage().isPresent()) {
795 SignalServiceDataMessage message
= content
.getDataMessage().get();
796 handleSignalServiceDataMessage(message
);
798 if (content
.getSyncMessage().isPresent()) {
799 System
.out
.println("Received a sync message");
800 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
802 if (syncMessage
.getContacts().isPresent()) {
803 System
.out
.println("Received sync contacts");
804 printAttachment(syncMessage
.getContacts().get());
806 if (syncMessage
.getGroups().isPresent()) {
807 System
.out
.println("Received sync groups");
808 printAttachment(syncMessage
.getGroups().get());
810 if (syncMessage
.getRead().isPresent()) {
811 System
.out
.println("Received sync read messages list");
812 for (ReadMessage rm
: syncMessage
.getRead().get()) {
813 ContactInfo fromContact
= m
.getContact(rm
.getSender());
814 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + formatTimestamp(rm
.getTimestamp()));
817 if (syncMessage
.getRequest().isPresent()) {
818 System
.out
.println("Received sync request");
819 if (syncMessage
.getRequest().get().isContactsRequest()) {
820 System
.out
.println(" - contacts request");
822 if (syncMessage
.getRequest().get().isGroupsRequest()) {
823 System
.out
.println(" - groups request");
826 if (syncMessage
.getSent().isPresent()) {
827 System
.out
.println("Received sync sent message");
828 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
830 if (sentTranscriptMessage
.getDestination().isPresent()) {
831 String dest
= sentTranscriptMessage
.getDestination().get();
832 ContactInfo destContact
= m
.getContact(dest
);
833 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
837 System
.out
.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage
.getTimestamp()));
838 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
839 System
.out
.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
841 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
842 handleSignalServiceDataMessage(message
);
844 if (syncMessage
.getBlockedList().isPresent()) {
845 System
.out
.println("Received sync message with block list");
846 System
.out
.println("Blocked numbers:");
847 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
848 for (String number
: blockedList
.getNumbers()) {
849 System
.out
.println(" - " + number
);
855 System
.out
.println("Unknown message received.");
857 System
.out
.println();
860 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
861 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
863 if (message
.getBody().isPresent()) {
864 System
.out
.println("Body: " + message
.getBody().get());
866 if (message
.getGroupInfo().isPresent()) {
867 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
868 System
.out
.println("Group info:");
869 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
870 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
871 System
.out
.println(" Name: " + groupInfo
.getName().get());
873 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
875 System
.out
.println(" Name: " + group
.name
);
877 System
.out
.println(" Name: <Unknown group>");
880 System
.out
.println(" Type: " + groupInfo
.getType());
881 if (groupInfo
.getMembers().isPresent()) {
882 for (String member
: groupInfo
.getMembers().get()) {
883 System
.out
.println(" Member: " + member
);
886 if (groupInfo
.getAvatar().isPresent()) {
887 System
.out
.println(" Avatar:");
888 printAttachment(groupInfo
.getAvatar().get());
891 if (message
.isEndSession()) {
892 System
.out
.println("Is end session");
894 if (message
.isExpirationUpdate()) {
895 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
897 if (message
.getExpiresInSeconds() > 0) {
898 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
901 if (message
.getAttachments().isPresent()) {
902 System
.out
.println("Attachments: ");
903 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
904 printAttachment(attachment
);
909 private void printAttachment(SignalServiceAttachment attachment
) {
910 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
911 if (attachment
.isPointer()) {
912 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
913 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
914 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
915 File file
= m
.getAttachmentFile(pointer
.getId());
917 System
.out
.println(" Stored plaintext in: " + file
);
923 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
924 final DBusConnection conn
;
926 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
932 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
933 super.handleMessage(envelope
, content
, exception
);
935 if (!envelope
.isReceipt() && content
!= null && content
.getDataMessage().isPresent()) {
936 SignalServiceDataMessage message
= content
.getDataMessage().get();
938 if (!message
.isEndSession() &&
939 !(message
.getGroupInfo().isPresent() &&
940 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
941 List
<String
> attachments
= new ArrayList
<>();
942 if (message
.getAttachments().isPresent()) {
943 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
944 if (attachment
.isPointer()) {
945 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
951 conn
.sendSignal(new Signal
.MessageReceived(
953 message
.getTimestamp(),
954 envelope
.getSource(),
955 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
956 message
.getBody().isPresent() ? message
.getBody().get() : "",
958 } catch (DBusException e
) {
967 private static String
formatTimestamp(long timestamp
) {
968 Date date
= new Date(timestamp
);
969 final DateFormat df
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
970 df
.setTimeZone(tzUTC
);
971 return timestamp
+ " (" + df
.format(date
) + ")";