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 (UnsatisfiedLinkError e
) {
92 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
94 } catch (DBusException e
) {
96 if (dBusConn
!= null) {
97 dBusConn
.disconnect();
102 String settingsPath
= ns
.getString("config");
103 if (TextUtils
.isEmpty(settingsPath
)) {
104 settingsPath
= System
.getProperty("user.home") + "/.config/signal";
105 if (!new File(settingsPath
).exists()) {
106 String legacySettingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
107 if (new File(legacySettingsPath
).exists()) {
108 settingsPath
= legacySettingsPath
;
113 m
= new Manager(username
, settingsPath
);
115 if (m
.userExists()) {
118 } catch (Exception e
) {
119 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
125 switch (ns
.getString("command")) {
127 if (dBusConn
!= null) {
128 System
.err
.println("register is not yet implemented via dbus");
131 if (!m
.userHasKeys()) {
132 m
.createNewIdentity();
135 m
.register(ns
.getBoolean("voice"));
136 } catch (IOException e
) {
137 System
.err
.println("Request verify error: " + e
.getMessage());
142 if (dBusConn
!= null) {
143 System
.err
.println("verify is not yet implemented via dbus");
146 if (!m
.userHasKeys()) {
147 System
.err
.println("User has no keys, first call register.");
150 if (m
.isRegistered()) {
151 System
.err
.println("User registration is already verified");
155 m
.verifyAccount(ns
.getString("verificationCode"));
156 } catch (IOException e
) {
157 System
.err
.println("Verify error: " + e
.getMessage());
162 if (dBusConn
!= null) {
163 System
.err
.println("link is not yet implemented via dbus");
167 // When linking, username is null and we always have to create keys
168 m
.createNewIdentity();
170 String deviceName
= ns
.getString("name");
171 if (deviceName
== null) {
175 System
.out
.println(m
.getDeviceLinkUri());
176 m
.finishDeviceLink(deviceName
);
177 System
.out
.println("Associated with: " + m
.getUsername());
178 } catch (TimeoutException e
) {
179 System
.err
.println("Link request timed out, please try again.");
181 } catch (IOException e
) {
182 System
.err
.println("Link request error: " + e
.getMessage());
184 } catch (AssertionError e
) {
185 handleAssertionError(e
);
187 } catch (InvalidKeyException e
) {
190 } catch (UserAlreadyExists e
) {
191 System
.err
.println("The user " + e
.getUsername() + " already exists\nDelete \"" + e
.getFileName() + "\" before trying again.");
196 if (dBusConn
!= null) {
197 System
.err
.println("link is not yet implemented via dbus");
200 if (!m
.isRegistered()) {
201 System
.err
.println("User is not registered.");
205 m
.addDeviceLink(new URI(ns
.getString("uri")));
206 } catch (IOException e
) {
209 } catch (InvalidKeyException e
) {
212 } catch (AssertionError e
) {
213 handleAssertionError(e
);
215 } catch (URISyntaxException e
) {
221 if (dBusConn
!= null) {
222 System
.err
.println("listDevices is not yet implemented via dbus");
225 if (!m
.isRegistered()) {
226 System
.err
.println("User is not registered.");
230 List
<DeviceInfo
> devices
= m
.getLinkedDevices();
231 for (DeviceInfo d
: devices
) {
232 System
.out
.println("Device " + d
.getId() + (d
.getId() == m
.getDeviceId() ?
" (this device)" : "") + ":");
233 System
.out
.println(" Name: " + d
.getName());
234 System
.out
.println(" Created: " + formatTimestamp(d
.getCreated()));
235 System
.out
.println(" Last seen: " + formatTimestamp(d
.getLastSeen()));
237 } catch (IOException e
) {
243 if (dBusConn
!= null) {
244 System
.err
.println("removeDevice is not yet implemented via dbus");
247 if (!m
.isRegistered()) {
248 System
.err
.println("User is not registered.");
252 int deviceId
= ns
.getInt("deviceId");
253 m
.removeLinkedDevices(deviceId
);
254 } catch (IOException e
) {
260 if (dBusConn
== null && !m
.isRegistered()) {
261 System
.err
.println("User is not registered.");
265 if (ns
.getBoolean("endsession")) {
266 if (ns
.getList("recipient") == null) {
267 System
.err
.println("No recipients given");
268 System
.err
.println("Aborting sending.");
272 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
273 } catch (IOException e
) {
274 handleIOException(e
);
276 } catch (EncapsulatedExceptions e
) {
277 handleEncapsulatedExceptions(e
);
279 } catch (AssertionError e
) {
280 handleAssertionError(e
);
282 } catch (DBusExecutionException e
) {
283 handleDBusExecutionException(e
);
287 String messageText
= ns
.getString("message");
288 if (messageText
== null) {
290 messageText
= readAll(System
.in);
291 } catch (IOException e
) {
292 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
293 System
.err
.println("Aborting sending.");
299 List
<String
> attachments
= ns
.getList("attachment");
300 if (attachments
== null) {
301 attachments
= new ArrayList
<>();
303 if (ns
.getString("group") != null) {
304 byte[] groupId
= decodeGroupId(ns
.getString("group"));
305 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
307 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
309 } catch (IOException e
) {
310 handleIOException(e
);
312 } catch (EncapsulatedExceptions e
) {
313 handleEncapsulatedExceptions(e
);
315 } catch (AssertionError e
) {
316 handleAssertionError(e
);
318 } catch (GroupNotFoundException e
) {
319 handleGroupNotFoundException(e
);
321 } catch (NotAGroupMemberException e
) {
322 handleNotAGroupMemberException(e
);
324 } catch (AttachmentInvalidException e
) {
325 System
.err
.println("Failed to add attachment: " + e
.getMessage());
326 System
.err
.println("Aborting sending.");
328 } catch (DBusExecutionException e
) {
329 handleDBusExecutionException(e
);
336 if (dBusConn
!= null) {
338 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
340 public void handle(Signal
.MessageReceived s
) {
341 System
.out
.print(String
.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
342 s
.getSender(), formatTimestamp(s
.getTimestamp()), s
.getMessage()));
343 if (s
.getGroupId().length
> 0) {
344 System
.out
.println("Group info:");
345 System
.out
.println(" Id: " + Base64
.encodeBytes(s
.getGroupId()));
347 if (s
.getAttachments().size() > 0) {
348 System
.out
.println("Attachments: ");
349 for (String attachment
: s
.getAttachments()) {
350 System
.out
.println("- Stored plaintext in: " + attachment
);
353 System
.out
.println();
356 } catch (UnsatisfiedLinkError e
) {
357 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
359 } catch (DBusException e
) {
366 } catch (InterruptedException e
) {
371 if (!m
.isRegistered()) {
372 System
.err
.println("User is not registered.");
376 if (ns
.getDouble("timeout") != null) {
377 timeout
= ns
.getDouble("timeout");
379 boolean returnOnTimeout
= true;
381 returnOnTimeout
= false;
384 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
386 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, ignoreAttachments
, new ReceiveMessageHandler(m
));
387 } catch (IOException e
) {
388 System
.err
.println("Error while receiving messages: " + e
.getMessage());
390 } catch (AssertionError e
) {
391 handleAssertionError(e
);
396 if (dBusConn
!= null) {
397 System
.err
.println("quitGroup is not yet implemented via dbus");
400 if (!m
.isRegistered()) {
401 System
.err
.println("User is not registered.");
406 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
407 } catch (IOException e
) {
408 handleIOException(e
);
410 } catch (EncapsulatedExceptions e
) {
411 handleEncapsulatedExceptions(e
);
413 } catch (AssertionError e
) {
414 handleAssertionError(e
);
416 } catch (GroupNotFoundException e
) {
417 handleGroupNotFoundException(e
);
419 } catch (NotAGroupMemberException e
) {
420 handleNotAGroupMemberException(e
);
426 if (dBusConn
!= null) {
427 System
.err
.println("updateGroup is not yet implemented via dbus");
430 if (!m
.isRegistered()) {
431 System
.err
.println("User is not registered.");
436 byte[] groupId
= null;
437 if (ns
.getString("group") != null) {
438 groupId
= decodeGroupId(ns
.getString("group"));
440 byte[] newGroupId
= m
.sendUpdateGroupMessage(groupId
, ns
.getString("name"), ns
.<String
>getList("member"), ns
.getString("avatar"));
441 if (groupId
== null) {
442 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
444 } catch (IOException e
) {
445 handleIOException(e
);
447 } catch (AttachmentInvalidException e
) {
448 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
449 System
.err
.println("Aborting sending.");
451 } catch (GroupNotFoundException e
) {
452 handleGroupNotFoundException(e
);
454 } catch (NotAGroupMemberException e
) {
455 handleNotAGroupMemberException(e
);
457 } catch (EncapsulatedExceptions e
) {
458 handleEncapsulatedExceptions(e
);
463 case "listIdentities":
464 if (dBusConn
!= null) {
465 System
.err
.println("listIdentities is not yet implemented via dbus");
468 if (!m
.isRegistered()) {
469 System
.err
.println("User is not registered.");
472 if (ns
.get("number") == null) {
473 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
474 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
475 printIdentityFingerprint(m
, keys
.getKey(), id
);
479 String number
= ns
.getString("number");
480 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
481 printIdentityFingerprint(m
, number
, id
);
486 if (dBusConn
!= null) {
487 System
.err
.println("trust is not yet implemented via dbus");
490 if (!m
.isRegistered()) {
491 System
.err
.println("User is not registered.");
494 String number
= ns
.getString("number");
495 if (ns
.getBoolean("trust_all_known_keys")) {
496 boolean res
= m
.trustIdentityAllKeys(number
);
498 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
502 String fingerprint
= ns
.getString("verified_fingerprint");
503 if (fingerprint
!= null) {
504 fingerprint
= fingerprint
.replaceAll(" ", "");
505 if (fingerprint
.length() == 66) {
506 byte[] fingerprintBytes
;
508 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
509 } catch (Exception e
) {
510 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
513 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
515 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
518 } else if (fingerprint
.length() == 60) {
519 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
521 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.");
525 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
529 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
535 if (dBusConn
!= null) {
536 System
.err
.println("Stop it.");
539 if (!m
.isRegistered()) {
540 System
.err
.println("User is not registered.");
543 DBusConnection conn
= null;
547 if (ns
.getBoolean("system")) {
548 busType
= DBusConnection
.SYSTEM
;
550 busType
= DBusConnection
.SESSION
;
552 conn
= DBusConnection
.getConnection(busType
);
553 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
554 conn
.requestBusName(SIGNAL_BUSNAME
);
555 } catch (UnsatisfiedLinkError e
) {
556 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
558 } catch (DBusException e
) {
562 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
564 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, new DbusReceiveMessageHandler(m
, conn
));
565 } catch (IOException e
) {
566 System
.err
.println("Error while receiving messages: " + e
.getMessage());
568 } catch (AssertionError e
) {
569 handleAssertionError(e
);
582 if (dBusConn
!= null) {
583 dBusConn
.disconnect();
588 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
589 String digits
= formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.identityKey
));
590 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
591 theirId
.trustLevel
, theirId
.added
, Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
594 private static String
formatSafetyNumber(String digits
) {
595 final int partCount
= 12;
596 int partSize
= digits
.length() / partCount
;
597 StringBuilder f
= new StringBuilder(digits
.length() + partCount
);
598 for (int i
= 0; i
< partCount
; i
++) {
599 f
.append(digits
.substring(i
* partSize
, (i
* partSize
) + partSize
)).append(" ");
604 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
605 System
.err
.println("Failed to send to group: " + e
.getMessage());
606 System
.err
.println("Aborting sending.");
609 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
610 System
.err
.println("Failed to send to group: " + e
.getMessage());
611 System
.err
.println("Update the group on another device to readd the user to this group.");
612 System
.err
.println("Aborting sending.");
616 private static void handleDBusExecutionException(DBusExecutionException e
) {
617 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
618 System
.err
.println("Aborting.");
621 private static byte[] decodeGroupId(String groupId
) {
623 return Base64
.decode(groupId
);
624 } catch (IOException e
) {
625 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
626 System
.err
.println("Aborting sending.");
632 private static Namespace
parseArgs(String
[] args
) {
633 ArgumentParser parser
= ArgumentParsers
.newArgumentParser("signal-cli")
635 .description("Commandline interface for Signal.")
636 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
638 parser
.addArgument("-v", "--version")
639 .help("Show package version.")
640 .action(Arguments
.version());
641 parser
.addArgument("--config")
642 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
644 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
645 mut
.addArgument("-u", "--username")
646 .help("Specify your phone number, that will be used for verification.");
647 mut
.addArgument("--dbus")
648 .help("Make request via user dbus.")
649 .action(Arguments
.storeTrue());
650 mut
.addArgument("--dbus-system")
651 .help("Make request via system dbus.")
652 .action(Arguments
.storeTrue());
654 Subparsers subparsers
= parser
.addSubparsers()
655 .title("subcommands")
657 .description("valid subcommands")
658 .help("additional help");
660 Subparser parserLink
= subparsers
.addParser("link");
661 parserLink
.addArgument("-n", "--name")
662 .help("Specify a name to describe this new device.");
664 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
665 parserAddDevice
.addArgument("--uri")
667 .help("Specify the uri contained in the QR code shown by the new device.");
669 Subparser parserDevices
= subparsers
.addParser("listDevices");
671 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
672 parserRemoveDevice
.addArgument("-d", "--deviceId")
675 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
677 Subparser parserRegister
= subparsers
.addParser("register");
678 parserRegister
.addArgument("-v", "--voice")
679 .help("The verification should be done over voice, not sms.")
680 .action(Arguments
.storeTrue());
682 Subparser parserVerify
= subparsers
.addParser("verify");
683 parserVerify
.addArgument("verificationCode")
684 .help("The verification code you received via sms or voice call.");
686 Subparser parserSend
= subparsers
.addParser("send");
687 parserSend
.addArgument("-g", "--group")
688 .help("Specify the recipient group ID.");
689 parserSend
.addArgument("recipient")
690 .help("Specify the recipients' phone number.")
692 parserSend
.addArgument("-m", "--message")
693 .help("Specify the message, if missing standard input is used.");
694 parserSend
.addArgument("-a", "--attachment")
696 .help("Add file as attachment");
697 parserSend
.addArgument("-e", "--endsession")
698 .help("Clear session state and send end session message.")
699 .action(Arguments
.storeTrue());
701 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
702 parserLeaveGroup
.addArgument("-g", "--group")
704 .help("Specify the recipient group ID.");
706 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
707 parserUpdateGroup
.addArgument("-g", "--group")
708 .help("Specify the recipient group ID.");
709 parserUpdateGroup
.addArgument("-n", "--name")
710 .help("Specify the new group name.");
711 parserUpdateGroup
.addArgument("-a", "--avatar")
712 .help("Specify a new group avatar image file");
713 parserUpdateGroup
.addArgument("-m", "--member")
715 .help("Specify one or more members to add to the group");
717 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
718 parserListIdentities
.addArgument("-n", "--number")
719 .help("Only show identity keys for the given phone number.");
721 Subparser parserTrust
= subparsers
.addParser("trust");
722 parserTrust
.addArgument("number")
723 .help("Specify the phone number, for which to set the trust.")
725 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
726 mutTrust
.addArgument("-a", "--trust-all-known-keys")
727 .help("Trust all known keys of this user, only use this for testing.")
728 .action(Arguments
.storeTrue());
729 mutTrust
.addArgument("-v", "--verified-fingerprint")
730 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
732 Subparser parserReceive
= subparsers
.addParser("receive");
733 parserReceive
.addArgument("-t", "--timeout")
735 .help("Number of seconds to wait for new messages (negative values disable timeout)");
736 parserReceive
.addArgument("--ignore-attachments")
737 .help("Don’t download attachments of received messages.")
738 .action(Arguments
.storeTrue());
740 Subparser parserDaemon
= subparsers
.addParser("daemon");
741 parserDaemon
.addArgument("--system")
742 .action(Arguments
.storeTrue())
743 .help("Use DBus system bus instead of user bus.");
744 parserDaemon
.addArgument("--ignore-attachments")
745 .help("Don’t download attachments of received messages.")
746 .action(Arguments
.storeTrue());
749 Namespace ns
= parser
.parseArgs(args
);
750 if ("link".equals(ns
.getString("command"))) {
751 if (ns
.getString("username") != null) {
753 System
.err
.println("You cannot specify a username (phone number) when linking");
756 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
757 if (ns
.getString("username") == null) {
759 System
.err
.println("You need to specify a username (phone number)");
762 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
763 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
767 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
768 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
772 } catch (ArgumentParserException e
) {
773 parser
.handleError(e
);
778 private static void handleAssertionError(AssertionError e
) {
779 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
781 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
784 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
785 System
.err
.println("Failed to send (some) messages:");
786 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
787 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
789 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
790 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
792 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
793 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
797 private static void handleIOException(IOException e
) {
798 System
.err
.println("Failed to send message: " + e
.getMessage());
801 private static String
readAll(InputStream
in) throws IOException
{
802 StringWriter output
= new StringWriter();
803 byte[] buffer
= new byte[4096];
806 while (-1 != (n
= System
.in.read(buffer
))) {
807 output
.write(new String(buffer
, 0, n
, Charset
.defaultCharset()));
810 return output
.toString();
813 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
816 public ReceiveMessageHandler(Manager m
) {
821 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
822 SignalServiceAddress source
= envelope
.getSourceAddress();
823 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
824 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
825 if (source
.getRelay().isPresent()) {
826 System
.out
.println("Relayed by: " + source
.getRelay().get());
828 System
.out
.println("Timestamp: " + formatTimestamp(envelope
.getTimestamp()));
830 if (envelope
.isReceipt()) {
831 System
.out
.println("Got receipt.");
832 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
833 if (exception
!= null) {
834 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
835 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
836 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
837 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");
838 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");
840 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
843 if (content
== null) {
844 System
.out
.println("Failed to decrypt message.");
846 if (content
.getDataMessage().isPresent()) {
847 SignalServiceDataMessage message
= content
.getDataMessage().get();
848 handleSignalServiceDataMessage(message
);
850 if (content
.getSyncMessage().isPresent()) {
851 System
.out
.println("Received a sync message");
852 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
854 if (syncMessage
.getContacts().isPresent()) {
855 System
.out
.println("Received sync contacts");
856 printAttachment(syncMessage
.getContacts().get());
858 if (syncMessage
.getGroups().isPresent()) {
859 System
.out
.println("Received sync groups");
860 printAttachment(syncMessage
.getGroups().get());
862 if (syncMessage
.getRead().isPresent()) {
863 System
.out
.println("Received sync read messages list");
864 for (ReadMessage rm
: syncMessage
.getRead().get()) {
865 ContactInfo fromContact
= m
.getContact(rm
.getSender());
866 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + formatTimestamp(rm
.getTimestamp()));
869 if (syncMessage
.getRequest().isPresent()) {
870 System
.out
.println("Received sync request");
871 if (syncMessage
.getRequest().get().isContactsRequest()) {
872 System
.out
.println(" - contacts request");
874 if (syncMessage
.getRequest().get().isGroupsRequest()) {
875 System
.out
.println(" - groups request");
878 if (syncMessage
.getSent().isPresent()) {
879 System
.out
.println("Received sync sent message");
880 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
882 if (sentTranscriptMessage
.getDestination().isPresent()) {
883 String dest
= sentTranscriptMessage
.getDestination().get();
884 ContactInfo destContact
= m
.getContact(dest
);
885 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
889 System
.out
.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage
.getTimestamp()));
890 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
891 System
.out
.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
893 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
894 handleSignalServiceDataMessage(message
);
896 if (syncMessage
.getBlockedList().isPresent()) {
897 System
.out
.println("Received sync message with block list");
898 System
.out
.println("Blocked numbers:");
899 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
900 for (String number
: blockedList
.getNumbers()) {
901 System
.out
.println(" - " + number
);
907 System
.out
.println("Unknown message received.");
909 System
.out
.println();
912 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
913 System
.out
.println("Message timestamp: " + formatTimestamp(message
.getTimestamp()));
915 if (message
.getBody().isPresent()) {
916 System
.out
.println("Body: " + message
.getBody().get());
918 if (message
.getGroupInfo().isPresent()) {
919 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
920 System
.out
.println("Group info:");
921 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
922 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
923 System
.out
.println(" Name: " + groupInfo
.getName().get());
925 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
927 System
.out
.println(" Name: " + group
.name
);
929 System
.out
.println(" Name: <Unknown group>");
932 System
.out
.println(" Type: " + groupInfo
.getType());
933 if (groupInfo
.getMembers().isPresent()) {
934 for (String member
: groupInfo
.getMembers().get()) {
935 System
.out
.println(" Member: " + member
);
938 if (groupInfo
.getAvatar().isPresent()) {
939 System
.out
.println(" Avatar:");
940 printAttachment(groupInfo
.getAvatar().get());
943 if (message
.isEndSession()) {
944 System
.out
.println("Is end session");
946 if (message
.isExpirationUpdate()) {
947 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
949 if (message
.getExpiresInSeconds() > 0) {
950 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
953 if (message
.getAttachments().isPresent()) {
954 System
.out
.println("Attachments: ");
955 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
956 printAttachment(attachment
);
961 private void printAttachment(SignalServiceAttachment attachment
) {
962 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
963 if (attachment
.isPointer()) {
964 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
965 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
+ (pointer
.getRelay().isPresent() ?
" Relay: " + pointer
.getRelay().get() : ""));
966 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
967 File file
= m
.getAttachmentFile(pointer
.getId());
969 System
.out
.println(" Stored plaintext in: " + file
);
975 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
976 final DBusConnection conn
;
978 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
984 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
985 super.handleMessage(envelope
, content
, exception
);
987 if (!envelope
.isReceipt() && content
!= null && content
.getDataMessage().isPresent()) {
988 SignalServiceDataMessage message
= content
.getDataMessage().get();
990 if (!message
.isEndSession() &&
991 !(message
.getGroupInfo().isPresent() &&
992 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
993 List
<String
> attachments
= new ArrayList
<>();
994 if (message
.getAttachments().isPresent()) {
995 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
996 if (attachment
.isPointer()) {
997 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
1003 conn
.sendSignal(new Signal
.MessageReceived(
1005 message
.getTimestamp(),
1006 envelope
.getSource(),
1007 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1008 message
.getBody().isPresent() ? message
.getBody().get() : "",
1010 } catch (DBusException e
) {
1011 e
.printStackTrace();
1019 private static String
formatTimestamp(long timestamp
) {
1020 Date date
= new Date(timestamp
);
1021 final DateFormat df
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
1022 df
.setTimeZone(tzUTC
);
1023 return timestamp
+ " (" + df
.format(date
) + ")";