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;
378 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
380 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, ignoreAttachments
, new ReceiveMessageHandler(m
));
381 } catch (IOException e
) {
382 System
.err
.println("Error while receiving messages: " + e
.getMessage());
384 } catch (AssertionError e
) {
385 handleAssertionError(e
);
390 if (dBusConn
!= null) {
391 System
.err
.println("quitGroup is not yet implemented via dbus");
394 if (!m
.isRegistered()) {
395 System
.err
.println("User is not registered.");
400 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
401 } catch (IOException e
) {
402 handleIOException(e
);
404 } catch (EncapsulatedExceptions e
) {
405 handleEncapsulatedExceptions(e
);
407 } catch (AssertionError e
) {
408 handleAssertionError(e
);
410 } catch (GroupNotFoundException e
) {
411 handleGroupNotFoundException(e
);
413 } catch (NotAGroupMemberException e
) {
414 handleNotAGroupMemberException(e
);
420 if (dBusConn
!= null) {
421 System
.err
.println("updateGroup is not yet implemented via dbus");
424 if (!m
.isRegistered()) {
425 System
.err
.println("User is not registered.");
430 byte[] groupId
= null;
431 if (ns
.getString("group") != null) {
432 groupId
= decodeGroupId(ns
.getString("group"));
434 byte[] newGroupId
= m
.sendUpdateGroupMessage(groupId
, ns
.getString("name"), ns
.<String
>getList("member"), ns
.getString("avatar"));
435 if (groupId
== null) {
436 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
438 } catch (IOException e
) {
439 handleIOException(e
);
441 } catch (AttachmentInvalidException e
) {
442 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
443 System
.err
.println("Aborting sending.");
445 } catch (GroupNotFoundException e
) {
446 handleGroupNotFoundException(e
);
448 } catch (NotAGroupMemberException e
) {
449 handleNotAGroupMemberException(e
);
451 } catch (EncapsulatedExceptions e
) {
452 handleEncapsulatedExceptions(e
);
457 case "listIdentities":
458 if (dBusConn
!= null) {
459 System
.err
.println("listIdentities is not yet implemented via dbus");
462 if (!m
.isRegistered()) {
463 System
.err
.println("User is not registered.");
466 if (ns
.get("number") == null) {
467 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
468 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
469 printIdentityFingerprint(m
, keys
.getKey(), id
);
473 String number
= ns
.getString("number");
474 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
475 printIdentityFingerprint(m
, number
, id
);
480 if (dBusConn
!= null) {
481 System
.err
.println("trust is not yet implemented via dbus");
484 if (!m
.isRegistered()) {
485 System
.err
.println("User is not registered.");
488 String number
= ns
.getString("number");
489 if (ns
.getBoolean("trust_all_known_keys")) {
490 boolean res
= m
.trustIdentityAllKeys(number
);
492 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
496 String fingerprint
= ns
.getString("verified_fingerprint");
497 if (fingerprint
!= null) {
498 fingerprint
= fingerprint
.replaceAll(" ", "");
499 if (fingerprint
.length() == 66) {
500 byte[] fingerprintBytes
;
502 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
503 } catch (Exception e
) {
504 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
507 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
509 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
512 } else if (fingerprint
.length() == 60) {
513 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
515 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.");
519 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
523 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
529 if (dBusConn
!= null) {
530 System
.err
.println("Stop it.");
533 if (!m
.isRegistered()) {
534 System
.err
.println("User is not registered.");
537 DBusConnection conn
= null;
541 if (ns
.getBoolean("system")) {
542 busType
= DBusConnection
.SYSTEM
;
544 busType
= DBusConnection
.SESSION
;
546 conn
= DBusConnection
.getConnection(busType
);
547 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
548 conn
.requestBusName(SIGNAL_BUSNAME
);
549 } catch (DBusException e
) {
553 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
555 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, new DbusReceiveMessageHandler(m
, conn
));
556 } catch (IOException e
) {
557 System
.err
.println("Error while receiving messages: " + e
.getMessage());
559 } catch (AssertionError e
) {
560 handleAssertionError(e
);
573 if (dBusConn
!= null) {
574 dBusConn
.disconnect();
579 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
580 String digits
= formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.identityKey
));
581 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
582 theirId
.trustLevel
, theirId
.added
, Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
585 private static String
formatSafetyNumber(String digits
) {
586 final int partCount
= 12;
587 int partSize
= digits
.length() / partCount
;
588 StringBuilder f
= new StringBuilder(digits
.length() + partCount
);
589 for (int i
= 0; i
< partCount
; i
++) {
590 f
.append(digits
.substring(i
* partSize
, (i
* partSize
) + partSize
)).append(" ");
595 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
596 System
.err
.println("Failed to send to group: " + e
.getMessage());
597 System
.err
.println("Aborting sending.");
600 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
601 System
.err
.println("Failed to send to group: " + e
.getMessage());
602 System
.err
.println("Update the group on another device to readd the user to this group.");
603 System
.err
.println("Aborting sending.");
607 private static void handleDBusExecutionException(DBusExecutionException e
) {
608 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
609 System
.err
.println("Aborting.");
612 private static byte[] decodeGroupId(String groupId
) {
614 return Base64
.decode(groupId
);
615 } catch (IOException e
) {
616 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
617 System
.err
.println("Aborting sending.");
623 private static Namespace
parseArgs(String
[] args
) {
624 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("signal-cli")
626 .description("Commandline interface for Signal.")
627 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
629 parser
.addArgument("-v", "--version")
630 .help("Show package version.")
631 .action(Arguments
.version());
632 parser
.addArgument("--config")
633 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
635 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
636 mut
.addArgument("-u", "--username")
637 .help("Specify your phone number, that will be used for verification.");
638 mut
.addArgument("--dbus")
639 .help("Make request via user dbus.")
640 .action(Arguments
.storeTrue());
641 mut
.addArgument("--dbus-system")
642 .help("Make request via system dbus.")
643 .action(Arguments
.storeTrue());
645 Subparsers subparsers
= parser
.addSubparsers()
646 .title("subcommands")
648 .description("valid subcommands")
649 .help("additional help");
651 Subparser parserLink
= subparsers
.addParser("link");
652 parserLink
.addArgument("-n", "--name")
653 .help("Specify a name to describe this new device.");
655 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
656 parserAddDevice
.addArgument("--uri")
658 .help("Specify the uri contained in the QR code shown by the new device.");
660 Subparser parserDevices
= subparsers
.addParser("listDevices");
662 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
663 parserRemoveDevice
.addArgument("-d", "--deviceId")
666 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
668 Subparser parserRegister
= subparsers
.addParser("register");
669 parserRegister
.addArgument("-v", "--voice")
670 .help("The verification should be done over voice, not sms.")
671 .action(Arguments
.storeTrue());
673 Subparser parserVerify
= subparsers
.addParser("verify");
674 parserVerify
.addArgument("verificationCode")
675 .help("The verification code you received via sms or voice call.");
677 Subparser parserSend
= subparsers
.addParser("send");
678 parserSend
.addArgument("-g", "--group")
679 .help("Specify the recipient group ID.");
680 parserSend
.addArgument("recipient")
681 .help("Specify the recipients' phone number.")
683 parserSend
.addArgument("-m", "--message")
684 .help("Specify the message, if missing standard input is used.");
685 parserSend
.addArgument("-a", "--attachment")
687 .help("Add file as attachment");
688 parserSend
.addArgument("-e", "--endsession")
689 .help("Clear session state and send end session message.")
690 .action(Arguments
.storeTrue());
692 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
693 parserLeaveGroup
.addArgument("-g", "--group")
695 .help("Specify the recipient group ID.");
697 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
698 parserUpdateGroup
.addArgument("-g", "--group")
699 .help("Specify the recipient group ID.");
700 parserUpdateGroup
.addArgument("-n", "--name")
701 .help("Specify the new group name.");
702 parserUpdateGroup
.addArgument("-a", "--avatar")
703 .help("Specify a new group avatar image file");
704 parserUpdateGroup
.addArgument("-m", "--member")
706 .help("Specify one or more members to add to the group");
708 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
709 parserListIdentities
.addArgument("-n", "--number")
710 .help("Only show identity keys for the given phone number.");
712 Subparser parserTrust
= subparsers
.addParser("trust");
713 parserTrust
.addArgument("number")
714 .help("Specify the phone number, for which to set the trust.")
716 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
717 mutTrust
.addArgument("-a", "--trust-all-known-keys")
718 .help("Trust all known keys of this user, only use this for testing.")
719 .action(Arguments
.storeTrue());
720 mutTrust
.addArgument("-v", "--verified-fingerprint")
721 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
723 Subparser parserReceive
= subparsers
.addParser("receive");
724 parserReceive
.addArgument("-t", "--timeout")
726 .help("Number of seconds to wait for new messages (negative values disable timeout)");
727 parserReceive
.addArgument("--ignore-attachments")
728 .help("Don’t download attachments of received messages.")
729 .action(Arguments
.storeTrue());
731 Subparser parserDaemon
= subparsers
.addParser("daemon");
732 parserDaemon
.addArgument("--system")
733 .action(Arguments
.storeTrue())
734 .help("Use DBus system bus instead of user bus.");
735 parserDaemon
.addArgument("--ignore-attachments")
736 .help("Don’t download attachments of received messages.")
737 .action(Arguments
.storeTrue());
740 Namespace ns
= parser
.parseArgs(args
);
741 if ("link".equals(ns
.getString("command"))) {
742 if (ns
.getString("username") != null) {
744 System
.err
.println("You cannot specify a username (phone number) when linking");
747 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
748 if (ns
.getString("username") == null) {
750 System
.err
.println("You need to specify a username (phone number)");
753 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
754 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
758 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
759 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
763 } catch (ArgumentParserException e
) {
764 parser
.handleError(e
);
769 private static void handleAssertionError(AssertionError e
) {
770 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
772 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
775 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
776 System
.err
.println("Failed to send (some) messages:");
777 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
778 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
780 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
781 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
783 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
784 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
788 private static void handleIOException(IOException e
) {
789 System
.err
.println("Failed to send message: " + e
.getMessage());
792 private static String
readAll(InputStream
in) throws IOException
{
793 StringWriter output
= new StringWriter();
794 byte[] buffer
= new byte[4096];
797 while (-1 != (n
= System
.in.read(buffer
))) {
798 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
801 return output
.toString();
804 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
807 public ReceiveMessageHandler(Manager m
) {
812 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
813 SignalServiceAddress source
= envelope
.getSourceAddress();
814 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
815 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
816 if (source
.getRelay().isPresent()) {
817 System
.out
.println("Relayed by: " + source
.getRelay().get());
819 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
821 if (envelope
.isReceipt()) {
822 System
.out
.println("Got receipt.");
823 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
824 if (exception
!= null) {
825 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
826 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
827 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
828 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");
829 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");
831 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
834 if (content
== null) {
835 System
.out
.println("Failed to decrypt message.");
837 if (content
.getDataMessage().isPresent()) {
838 SignalServiceDataMessage message
= content
.getDataMessage().get();
839 handleSignalServiceDataMessage(message
);
841 if (content
.getSyncMessage().isPresent()) {
842 System
.out
.println("Received a sync message");
843 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
845 if (syncMessage
.getContacts().isPresent()) {
846 System
.out
.println("Received sync contacts");
847 printAttachment(syncMessage
.getContacts().get());
849 if (syncMessage
.getGroups().isPresent()) {
850 System
.out
.println("Received sync groups");
851 printAttachment(syncMessage
.getGroups().get());
853 if (syncMessage
.getRead().isPresent()) {
854 System
.out
.println("Received sync read messages list");
855 for (ReadMessage rm
: syncMessage
.getRead().get()) {
856 ContactInfo fromContact
= m
.getContact(rm
.getSender());
857 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + formatTimestamp(rm
.getTimestamp()));
860 if (syncMessage
.getRequest().isPresent()) {
861 System
.out
.println("Received sync request");
862 if (syncMessage
.getRequest().get().isContactsRequest()) {
863 System
.out
.println(" - contacts request");
865 if (syncMessage
.getRequest().get().isGroupsRequest()) {
866 System
.out
.println(" - groups request");
869 if (syncMessage
.getSent().isPresent()) {
870 System
.out
.println("Received sync sent message");
871 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
873 if (sentTranscriptMessage
.getDestination().isPresent()) {
874 String dest
= sentTranscriptMessage
.getDestination().get();
875 ContactInfo destContact
= m
.getContact(dest
);
876 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
880 System
.out
.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage
.getTimestamp()));
881 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
882 System
.out
.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
884 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
885 handleSignalServiceDataMessage(message
);
887 if (syncMessage
.getBlockedList().isPresent()) {
888 System
.out
.println("Received sync message with block list");
889 System
.out
.println("Blocked numbers:");
890 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
891 for (String number
: blockedList
.getNumbers()) {
892 System
.out
.println(" - " + number
);
898 System
.out
.println("Unknown message received.");
900 System
.out
.println();
903 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
904 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
906 if (message
.getBody().isPresent()) {
907 System
.out
.println("Body: " + message
.getBody().get());
909 if (message
.getGroupInfo().isPresent()) {
910 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
911 System
.out
.println("Group info:");
912 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
913 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
914 System
.out
.println(" Name: " + groupInfo
.getName().get());
916 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
918 System
.out
.println(" Name: " + group
.name
);
920 System
.out
.println(" Name: <Unknown group>");
923 System
.out
.println(" Type: " + groupInfo
.getType());
924 if (groupInfo
.getMembers().isPresent()) {
925 for (String member
: groupInfo
.getMembers().get()) {
926 System
.out
.println(" Member: " + member
);
929 if (groupInfo
.getAvatar().isPresent()) {
930 System
.out
.println(" Avatar:");
931 printAttachment(groupInfo
.getAvatar().get());
934 if (message
.isEndSession()) {
935 System
.out
.println("Is end session");
937 if (message
.isExpirationUpdate()) {
938 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
940 if (message
.getExpiresInSeconds() > 0) {
941 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
944 if (message
.getAttachments().isPresent()) {
945 System
.out
.println("Attachments: ");
946 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
947 printAttachment(attachment
);
952 private void printAttachment(SignalServiceAttachment attachment
) {
953 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
954 if (attachment
.isPointer()) {
955 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
956 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
957 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
958 File file
= m
.getAttachmentFile(pointer
.getId());
960 System
.out
.println(" Stored plaintext in: " + file
);
966 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
967 final DBusConnection conn
;
969 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
975 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
976 super.handleMessage(envelope
, content
, exception
);
978 if (!envelope
.isReceipt() && content
!= null && content
.getDataMessage().isPresent()) {
979 SignalServiceDataMessage message
= content
.getDataMessage().get();
981 if (!message
.isEndSession() &&
982 !(message
.getGroupInfo().isPresent() &&
983 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
984 List
<String
> attachments
= new ArrayList
<>();
985 if (message
.getAttachments().isPresent()) {
986 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
987 if (attachment
.isPointer()) {
988 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
994 conn
.sendSignal(new Signal
.MessageReceived(
996 message
.getTimestamp(),
997 envelope
.getSource(),
998 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
999 message
.getBody().isPresent() ? message
.getBody().get() : "",
1001 } catch (DBusException e
) {
1002 e
.printStackTrace();
1010 private static String
formatTimestamp(long timestamp
) {
1011 Date date
= new Date(timestamp
);
1012 final DateFormat df
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
1013 df
.setTimeZone(tzUTC
);
1014 return timestamp
+ " (" + df
.format(date
) + ")";