2 Copyright (C) 2015-2018 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 com
.fasterxml
.jackson
.annotation
.JsonAutoDetect
;
20 import com
.fasterxml
.jackson
.annotation
.PropertyAccessor
;
21 import com
.fasterxml
.jackson
.core
.JsonGenerator
;
22 import com
.fasterxml
.jackson
.databind
.DeserializationFeature
;
23 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
24 import com
.fasterxml
.jackson
.databind
.SerializationFeature
;
25 import com
.fasterxml
.jackson
.databind
.node
.ObjectNode
;
26 import net
.sourceforge
.argparse4j
.ArgumentParsers
;
27 import net
.sourceforge
.argparse4j
.impl
.Arguments
;
28 import net
.sourceforge
.argparse4j
.inf
.*;
29 import org
.apache
.http
.util
.TextUtils
;
30 import org
.asamk
.Signal
;
31 import org
.asamk
.signal
.manager
.BaseConfig
;
32 import org
.asamk
.signal
.manager
.Manager
;
33 import org
.asamk
.signal
.storage
.contacts
.ContactInfo
;
34 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
35 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
36 import org
.asamk
.signal
.util
.DateUtils
;
37 import org
.asamk
.signal
.util
.Hex
;
38 import org
.asamk
.signal
.util
.IOUtils
;
39 import org
.asamk
.signal
.util
.Util
;
40 import org
.freedesktop
.dbus
.DBusConnection
;
41 import org
.freedesktop
.dbus
.DBusSigHandler
;
42 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
43 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
44 import org
.whispersystems
.libsignal
.InvalidKeyException
;
45 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
46 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
47 import org
.whispersystems
.signalservice
.api
.messages
.*;
48 import org
.whispersystems
.signalservice
.api
.messages
.calls
.*;
49 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
50 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
51 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
52 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
53 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
54 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
55 import org
.whispersystems
.signalservice
.internal
.push
.LockedException
;
56 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
59 import java
.io
.IOException
;
61 import java
.net
.URISyntaxException
;
62 import java
.nio
.charset
.Charset
;
63 import java
.security
.Security
;
64 import java
.util
.ArrayList
;
65 import java
.util
.List
;
66 import java
.util
.Locale
;
68 import java
.util
.concurrent
.TimeUnit
;
69 import java
.util
.concurrent
.TimeoutException
;
73 public static final String SIGNAL_BUSNAME
= "org.asamk.Signal";
74 public static final String SIGNAL_OBJECTPATH
= "/org/asamk/Signal";
76 public static void main(String
[] args
) {
77 // Workaround for BKS truststore
78 Security
.insertProviderAt(new org
.bouncycastle
.jce
.provider
.BouncyCastleProvider(), 1);
80 Namespace ns
= parseArgs(args
);
85 int res
= handleCommands(ns
);
89 private static int handleCommands(Namespace ns
) {
90 final String username
= ns
.getString("username");
93 DBusConnection dBusConn
= null;
95 if (ns
.getBoolean("dbus") || ns
.getBoolean("dbus_system")) {
99 if (ns
.getBoolean("dbus_system")) {
100 busType
= DBusConnection
.SYSTEM
;
102 busType
= DBusConnection
.SESSION
;
104 dBusConn
= DBusConnection
.getConnection(busType
);
105 ts
= dBusConn
.getRemoteObject(
106 SIGNAL_BUSNAME
, SIGNAL_OBJECTPATH
,
108 } catch (UnsatisfiedLinkError e
) {
109 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
111 } catch (DBusException e
) {
113 if (dBusConn
!= null) {
114 dBusConn
.disconnect();
119 String settingsPath
= ns
.getString("config");
120 if (TextUtils
.isEmpty(settingsPath
)) {
121 settingsPath
= System
.getProperty("user.home") + "/.config/signal";
122 if (!new File(settingsPath
).exists()) {
123 String legacySettingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
124 if (new File(legacySettingsPath
).exists()) {
125 settingsPath
= legacySettingsPath
;
130 m
= new Manager(username
, settingsPath
);
134 } catch (Exception e
) {
135 System
.err
.println("Error loading state file: " + e
.getMessage());
140 switch (ns
.getString("command")) {
142 if (dBusConn
!= null) {
143 System
.err
.println("register is not yet implemented via dbus");
147 m
.register(ns
.getBoolean("voice"));
148 } catch (IOException e
) {
149 System
.err
.println("Request verify error: " + e
.getMessage());
154 if (dBusConn
!= null) {
155 System
.err
.println("unregister is not yet implemented via dbus");
158 if (!m
.isRegistered()) {
159 System
.err
.println("User is not registered.");
164 } catch (IOException e
) {
165 System
.err
.println("Unregister error: " + e
.getMessage());
169 case "updateAccount":
170 if (dBusConn
!= null) {
171 System
.err
.println("updateAccount is not yet implemented via dbus");
174 if (!m
.isRegistered()) {
175 System
.err
.println("User is not registered.");
179 m
.updateAccountAttributes();
180 } catch (IOException e
) {
181 System
.err
.println("UpdateAccount error: " + e
.getMessage());
186 if (dBusConn
!= null) {
187 System
.err
.println("setPin is not yet implemented via dbus");
190 if (!m
.isRegistered()) {
191 System
.err
.println("User is not registered.");
195 String registrationLockPin
= ns
.getString("registrationLockPin");
196 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
197 } catch (IOException e
) {
198 System
.err
.println("Set pin error: " + e
.getMessage());
203 if (dBusConn
!= null) {
204 System
.err
.println("removePin is not yet implemented via dbus");
207 if (!m
.isRegistered()) {
208 System
.err
.println("User is not registered.");
212 m
.setRegistrationLockPin(Optional
.<String
>absent());
213 } catch (IOException e
) {
214 System
.err
.println("Remove pin error: " + e
.getMessage());
219 if (dBusConn
!= null) {
220 System
.err
.println("verify is not yet implemented via dbus");
223 if (!m
.userHasKeys()) {
224 System
.err
.println("User has no keys, first call register.");
227 if (m
.isRegistered()) {
228 System
.err
.println("User registration is already verified");
232 String verificationCode
= ns
.getString("verificationCode");
233 String pin
= ns
.getString("pin");
234 m
.verifyAccount(verificationCode
, pin
);
235 } catch (LockedException e
) {
236 System
.err
.println("Verification failed! This number is locked with a pin. Hours remaining until reset: " + (e
.getTimeRemaining() / 1000 / 60 / 60));
237 System
.err
.println("Use '--pin PIN_CODE' to specify the registration lock PIN");
239 } catch (IOException e
) {
240 System
.err
.println("Verify error: " + e
.getMessage());
245 if (dBusConn
!= null) {
246 System
.err
.println("link is not yet implemented via dbus");
250 String deviceName
= ns
.getString("name");
251 if (deviceName
== null) {
255 System
.out
.println(m
.getDeviceLinkUri());
256 m
.finishDeviceLink(deviceName
);
257 System
.out
.println("Associated with: " + m
.getUsername());
258 } catch (TimeoutException e
) {
259 System
.err
.println("Link request timed out, please try again.");
261 } catch (IOException e
) {
262 System
.err
.println("Link request error: " + e
.getMessage());
264 } catch (AssertionError e
) {
265 handleAssertionError(e
);
267 } catch (InvalidKeyException e
) {
270 } catch (UserAlreadyExists e
) {
271 System
.err
.println("The user " + e
.getUsername() + " already exists\nDelete \"" + e
.getFileName() + "\" before trying again.");
276 if (dBusConn
!= null) {
277 System
.err
.println("link is not yet implemented via dbus");
280 if (!m
.isRegistered()) {
281 System
.err
.println("User is not registered.");
285 m
.addDeviceLink(new URI(ns
.getString("uri")));
286 } catch (IOException e
) {
289 } catch (InvalidKeyException e
) {
292 } catch (AssertionError e
) {
293 handleAssertionError(e
);
295 } catch (URISyntaxException e
) {
301 if (dBusConn
!= null) {
302 System
.err
.println("listDevices is not yet implemented via dbus");
305 if (!m
.isRegistered()) {
306 System
.err
.println("User is not registered.");
310 List
<DeviceInfo
> devices
= m
.getLinkedDevices();
311 for (DeviceInfo d
: devices
) {
312 System
.out
.println("Device " + d
.getId() + (d
.getId() == m
.getDeviceId() ?
" (this device)" : "") + ":");
313 System
.out
.println(" Name: " + d
.getName());
314 System
.out
.println(" Created: " + DateUtils
.formatTimestamp(d
.getCreated()));
315 System
.out
.println(" Last seen: " + DateUtils
.formatTimestamp(d
.getLastSeen()));
317 } catch (IOException e
) {
323 if (dBusConn
!= null) {
324 System
.err
.println("removeDevice is not yet implemented via dbus");
327 if (!m
.isRegistered()) {
328 System
.err
.println("User is not registered.");
332 int deviceId
= ns
.getInt("deviceId");
333 m
.removeLinkedDevices(deviceId
);
334 } catch (IOException e
) {
340 if (dBusConn
== null && !m
.isRegistered()) {
341 System
.err
.println("User is not registered.");
345 if (ns
.getBoolean("endsession")) {
346 if (ns
.getList("recipient") == null) {
347 System
.err
.println("No recipients given");
348 System
.err
.println("Aborting sending.");
352 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
353 } catch (IOException e
) {
354 handleIOException(e
);
356 } catch (EncapsulatedExceptions e
) {
357 handleEncapsulatedExceptions(e
);
359 } catch (AssertionError e
) {
360 handleAssertionError(e
);
362 } catch (DBusExecutionException e
) {
363 handleDBusExecutionException(e
);
367 String messageText
= ns
.getString("message");
368 if (messageText
== null) {
370 messageText
= IOUtils
.readAll(System
.in, Charset
.defaultCharset());
371 } catch (IOException e
) {
372 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
373 System
.err
.println("Aborting sending.");
379 List
<String
> attachments
= ns
.getList("attachment");
380 if (attachments
== null) {
381 attachments
= new ArrayList
<>();
383 if (ns
.getString("group") != null) {
384 byte[] groupId
= decodeGroupId(ns
.getString("group"));
385 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
387 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
389 } catch (IOException e
) {
390 handleIOException(e
);
392 } catch (EncapsulatedExceptions e
) {
393 handleEncapsulatedExceptions(e
);
395 } catch (AssertionError e
) {
396 handleAssertionError(e
);
398 } catch (GroupNotFoundException e
) {
399 handleGroupNotFoundException(e
);
401 } catch (NotAGroupMemberException e
) {
402 handleNotAGroupMemberException(e
);
404 } catch (AttachmentInvalidException e
) {
405 System
.err
.println("Failed to add attachment: " + e
.getMessage());
406 System
.err
.println("Aborting sending.");
408 } catch (DBusExecutionException e
) {
409 handleDBusExecutionException(e
);
416 if (dBusConn
!= null) {
418 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
420 public void handle(Signal
.MessageReceived s
) {
421 System
.out
.print(String
.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
422 s
.getSender(), DateUtils
.formatTimestamp(s
.getTimestamp()), s
.getMessage()));
423 if (s
.getGroupId().length
> 0) {
424 System
.out
.println("Group info:");
425 System
.out
.println(" Id: " + Base64
.encodeBytes(s
.getGroupId()));
427 if (s
.getAttachments().size() > 0) {
428 System
.out
.println("Attachments: ");
429 for (String attachment
: s
.getAttachments()) {
430 System
.out
.println("- Stored plaintext in: " + attachment
);
433 System
.out
.println();
436 dBusConn
.addSigHandler(Signal
.ReceiptReceived
.class, new DBusSigHandler
<Signal
.ReceiptReceived
>() {
438 public void handle(Signal
.ReceiptReceived s
) {
439 System
.out
.print(String
.format("Receipt from: %s\nTimestamp: %s\n",
440 s
.getSender(), DateUtils
.formatTimestamp(s
.getTimestamp())));
443 } catch (UnsatisfiedLinkError e
) {
444 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
446 } catch (DBusException e
) {
453 } catch (InterruptedException e
) {
458 if (!m
.isRegistered()) {
459 System
.err
.println("User is not registered.");
463 if (ns
.getDouble("timeout") != null) {
464 timeout
= ns
.getDouble("timeout");
466 boolean returnOnTimeout
= true;
468 returnOnTimeout
= false;
471 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
473 final Manager
.ReceiveMessageHandler handler
= ns
.getBoolean("json") ?
new JsonReceiveMessageHandler(m
) : new ReceiveMessageHandler(m
);
474 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, ignoreAttachments
, handler
);
475 } catch (IOException e
) {
476 System
.err
.println("Error while receiving messages: " + e
.getMessage());
478 } catch (AssertionError e
) {
479 handleAssertionError(e
);
484 if (dBusConn
!= null) {
485 System
.err
.println("quitGroup is not yet implemented via dbus");
488 if (!m
.isRegistered()) {
489 System
.err
.println("User is not registered.");
494 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
495 } catch (IOException e
) {
496 handleIOException(e
);
498 } catch (EncapsulatedExceptions e
) {
499 handleEncapsulatedExceptions(e
);
501 } catch (AssertionError e
) {
502 handleAssertionError(e
);
504 } catch (GroupNotFoundException e
) {
505 handleGroupNotFoundException(e
);
507 } catch (NotAGroupMemberException e
) {
508 handleNotAGroupMemberException(e
);
514 if (dBusConn
== null && !m
.isRegistered()) {
515 System
.err
.println("User is not registered.");
520 byte[] groupId
= null;
521 if (ns
.getString("group") != null) {
522 groupId
= decodeGroupId(ns
.getString("group"));
524 if (groupId
== null) {
525 groupId
= new byte[0];
527 String groupName
= ns
.getString("name");
528 if (groupName
== null) {
531 List
<String
> groupMembers
= ns
.<String
>getList("member");
532 if (groupMembers
== null) {
533 groupMembers
= new ArrayList
<String
>();
535 String groupAvatar
= ns
.getString("avatar");
536 if (groupAvatar
== null) {
539 byte[] newGroupId
= ts
.updateGroup(groupId
, groupName
, groupMembers
, groupAvatar
);
540 if (groupId
.length
!= newGroupId
.length
) {
541 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
543 } catch (IOException e
) {
544 handleIOException(e
);
546 } catch (AttachmentInvalidException e
) {
547 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
548 System
.err
.println("Aborting sending.");
550 } catch (GroupNotFoundException e
) {
551 handleGroupNotFoundException(e
);
553 } catch (NotAGroupMemberException e
) {
554 handleNotAGroupMemberException(e
);
556 } catch (EncapsulatedExceptions e
) {
557 handleEncapsulatedExceptions(e
);
563 if (dBusConn
!= null) {
564 System
.err
.println("listGroups is not yet implemented via dbus");
567 if (!m
.isRegistered()) {
568 System
.err
.println("User is not registered.");
572 List
<GroupInfo
> groups
= m
.getGroups();
573 boolean detailed
= ns
.getBoolean("detailed");
575 for (GroupInfo group
: groups
) {
576 printGroup(group
, detailed
);
579 case "listIdentities":
580 if (dBusConn
!= null) {
581 System
.err
.println("listIdentities is not yet implemented via dbus");
584 if (!m
.isRegistered()) {
585 System
.err
.println("User is not registered.");
588 if (ns
.get("number") == null) {
589 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
590 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
591 printIdentityFingerprint(m
, keys
.getKey(), id
);
595 String number
= ns
.getString("number");
596 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
597 printIdentityFingerprint(m
, number
, id
);
602 if (dBusConn
!= null) {
603 System
.err
.println("trust is not yet implemented via dbus");
606 if (!m
.isRegistered()) {
607 System
.err
.println("User is not registered.");
610 String number
= ns
.getString("number");
611 if (ns
.getBoolean("trust_all_known_keys")) {
612 boolean res
= m
.trustIdentityAllKeys(number
);
614 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
618 String fingerprint
= ns
.getString("verified_fingerprint");
619 if (fingerprint
!= null) {
620 fingerprint
= fingerprint
.replaceAll(" ", "");
621 if (fingerprint
.length() == 66) {
622 byte[] fingerprintBytes
;
624 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
625 } catch (Exception e
) {
626 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
629 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
631 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
634 } else if (fingerprint
.length() == 60) {
635 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
637 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.");
641 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
645 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
651 if (dBusConn
!= null) {
652 System
.err
.println("Stop it.");
655 if (!m
.isRegistered()) {
656 System
.err
.println("User is not registered.");
659 DBusConnection conn
= null;
663 if (ns
.getBoolean("system")) {
664 busType
= DBusConnection
.SYSTEM
;
666 busType
= DBusConnection
.SESSION
;
668 conn
= DBusConnection
.getConnection(busType
);
669 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
670 conn
.requestBusName(SIGNAL_BUSNAME
);
671 } catch (UnsatisfiedLinkError e
) {
672 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
674 } catch (DBusException e
) {
678 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
680 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, ns
.getBoolean("json") ?
new JsonDbusReceiveMessageHandler(m
, conn
) : new DbusReceiveMessageHandler(m
, conn
));
681 } catch (IOException e
) {
682 System
.err
.println("Error while receiving messages: " + e
.getMessage());
684 } catch (AssertionError e
) {
685 handleAssertionError(e
);
698 if (dBusConn
!= null) {
699 dBusConn
.disconnect();
704 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
705 String digits
= Util
.formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.getIdentityKey()));
706 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
707 theirId
.getTrustLevel(), theirId
.getDateAdded(), Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
710 private static void printGroup(GroupInfo group
, boolean detailed
) {
712 System
.out
.println(String
.format("Id: %s Name: %s Active: %s Members: %s",
713 Base64
.encodeBytes(group
.groupId
), group
.name
, group
.active
, group
.members
));
715 System
.out
.println(String
.format("Id: %s Name: %s Active: %s", Base64
.encodeBytes(group
.groupId
),
716 group
.name
, group
.active
));
720 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
721 System
.err
.println("Failed to send to group: " + e
.getMessage());
722 System
.err
.println("Aborting sending.");
725 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
726 System
.err
.println("Failed to send to group: " + e
.getMessage());
727 System
.err
.println("Update the group on another device to readd the user to this group.");
728 System
.err
.println("Aborting sending.");
731 private static void handleDBusExecutionException(DBusExecutionException e
) {
732 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
733 System
.err
.println("Aborting.");
736 private static byte[] decodeGroupId(String groupId
) {
738 return Base64
.decode(groupId
);
739 } catch (IOException e
) {
740 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
741 System
.err
.println("Aborting sending.");
747 private static Namespace
parseArgs(String
[] args
) {
748 ArgumentParser parser
= ArgumentParsers
.newFor("signal-cli")
751 .description("Commandline interface for Signal.")
752 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
754 parser
.addArgument("-v", "--version")
755 .help("Show package version.")
756 .action(Arguments
.version());
757 parser
.addArgument("--config")
758 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
760 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
761 mut
.addArgument("-u", "--username")
762 .help("Specify your phone number, that will be used for verification.");
763 mut
.addArgument("--dbus")
764 .help("Make request via user dbus.")
765 .action(Arguments
.storeTrue());
766 mut
.addArgument("--dbus-system")
767 .help("Make request via system dbus.")
768 .action(Arguments
.storeTrue());
770 Subparsers subparsers
= parser
.addSubparsers()
771 .title("subcommands")
773 .description("valid subcommands")
774 .help("additional help");
776 Subparser parserLink
= subparsers
.addParser("link");
777 parserLink
.addArgument("-n", "--name")
778 .help("Specify a name to describe this new device.");
780 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
781 parserAddDevice
.addArgument("--uri")
783 .help("Specify the uri contained in the QR code shown by the new device.");
785 Subparser parserDevices
= subparsers
.addParser("listDevices");
787 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
788 parserRemoveDevice
.addArgument("-d", "--deviceId")
791 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
793 Subparser parserRegister
= subparsers
.addParser("register");
794 parserRegister
.addArgument("-v", "--voice")
795 .help("The verification should be done over voice, not sms.")
796 .action(Arguments
.storeTrue());
798 Subparser parserUnregister
= subparsers
.addParser("unregister");
799 parserUnregister
.help("Unregister the current device from the signal server.");
801 Subparser parserUpdateAccount
= subparsers
.addParser("updateAccount");
802 parserUpdateAccount
.help("Update the account attributes on the signal server.");
804 Subparser parserSetPin
= subparsers
.addParser("setPin");
805 parserSetPin
.addArgument("registrationLockPin")
806 .help("The registration lock PIN, that will be required for new registrations (resets after 7 days of inactivity)");
808 Subparser parserRemovePin
= subparsers
.addParser("removePin");
810 Subparser parserVerify
= subparsers
.addParser("verify");
811 parserVerify
.addArgument("verificationCode")
812 .help("The verification code you received via sms or voice call.");
813 parserVerify
.addArgument("-p", "--pin")
814 .help("The registration lock PIN, that was set by the user (Optional)");
816 Subparser parserSend
= subparsers
.addParser("send");
817 parserSend
.addArgument("-g", "--group")
818 .help("Specify the recipient group ID.");
819 parserSend
.addArgument("recipient")
820 .help("Specify the recipients' phone number.")
822 parserSend
.addArgument("-m", "--message")
823 .help("Specify the message, if missing standard input is used.");
824 parserSend
.addArgument("-a", "--attachment")
826 .help("Add file as attachment");
827 parserSend
.addArgument("-e", "--endsession")
828 .help("Clear session state and send end session message.")
829 .action(Arguments
.storeTrue());
831 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
832 parserLeaveGroup
.addArgument("-g", "--group")
834 .help("Specify the recipient group ID.");
836 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
837 parserUpdateGroup
.addArgument("-g", "--group")
838 .help("Specify the recipient group ID.");
839 parserUpdateGroup
.addArgument("-n", "--name")
840 .help("Specify the new group name.");
841 parserUpdateGroup
.addArgument("-a", "--avatar")
842 .help("Specify a new group avatar image file");
843 parserUpdateGroup
.addArgument("-m", "--member")
845 .help("Specify one or more members to add to the group");
847 Subparser parserListGroups
= subparsers
.addParser("listGroups");
848 parserListGroups
.addArgument("-d", "--detailed").action(Arguments
.storeTrue())
849 .help("List members of each group");
850 parserListGroups
.help("List group name and ids");
852 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
853 parserListIdentities
.addArgument("-n", "--number")
854 .help("Only show identity keys for the given phone number.");
856 Subparser parserTrust
= subparsers
.addParser("trust");
857 parserTrust
.addArgument("number")
858 .help("Specify the phone number, for which to set the trust.")
860 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
861 mutTrust
.addArgument("-a", "--trust-all-known-keys")
862 .help("Trust all known keys of this user, only use this for testing.")
863 .action(Arguments
.storeTrue());
864 mutTrust
.addArgument("-v", "--verified-fingerprint")
865 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
867 Subparser parserReceive
= subparsers
.addParser("receive");
868 parserReceive
.addArgument("-t", "--timeout")
870 .help("Number of seconds to wait for new messages (negative values disable timeout)");
871 parserReceive
.addArgument("--ignore-attachments")
872 .help("Don’t download attachments of received messages.")
873 .action(Arguments
.storeTrue());
874 parserReceive
.addArgument("--json")
875 .help("Output received messages in json format, one json object per line.")
876 .action(Arguments
.storeTrue());
878 Subparser parserDaemon
= subparsers
.addParser("daemon");
879 parserDaemon
.addArgument("--system")
880 .action(Arguments
.storeTrue())
881 .help("Use DBus system bus instead of user bus.");
882 parserDaemon
.addArgument("--ignore-attachments")
883 .help("Don’t download attachments of received messages.")
884 .action(Arguments
.storeTrue());
885 parserDaemon
.addArgument("--json")
886 .help("Output received messages in json format, one json object per line.")
887 .action(Arguments
.storeTrue());
890 Namespace ns
= parser
.parseArgs(args
);
891 if ("link".equals(ns
.getString("command"))) {
892 if (ns
.getString("username") != null) {
894 System
.err
.println("You cannot specify a username (phone number) when linking");
897 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
898 if (ns
.getString("username") == null) {
900 System
.err
.println("You need to specify a username (phone number)");
903 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
904 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
908 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
909 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
913 } catch (ArgumentParserException e
) {
914 parser
.handleError(e
);
919 private static void handleAssertionError(AssertionError e
) {
920 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
922 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
925 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
926 System
.err
.println("Failed to send (some) messages:");
927 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
928 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
930 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
931 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
933 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
934 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
938 private static void handleIOException(IOException e
) {
939 System
.err
.println("Failed to send message: " + e
.getMessage());
942 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
946 public ReceiveMessageHandler(Manager m
) {
951 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
952 SignalServiceAddress source
= envelope
.getSourceAddress();
953 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
954 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
955 if (source
.getRelay().isPresent()) {
956 System
.out
.println("Relayed by: " + source
.getRelay().get());
958 System
.out
.println("Timestamp: " + DateUtils
.formatTimestamp(envelope
.getTimestamp()));
959 if (envelope
.isUnidentifiedSender()) {
960 System
.out
.println("Sent by unidentified/sealed sender");
963 if (envelope
.isReceipt()) {
964 System
.out
.println("Got receipt.");
965 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
966 if (exception
!= null) {
967 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
968 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
969 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
970 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");
971 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");
973 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
976 if (content
== null) {
977 System
.out
.println("Failed to decrypt message.");
979 if (content
.getDataMessage().isPresent()) {
980 SignalServiceDataMessage message
= content
.getDataMessage().get();
981 handleSignalServiceDataMessage(message
);
983 if (content
.getSyncMessage().isPresent()) {
984 System
.out
.println("Received a sync message");
985 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
987 if (syncMessage
.getContacts().isPresent()) {
988 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
989 if (contactsMessage
.isComplete()) {
990 System
.out
.println("Received complete sync contacts");
992 System
.out
.println("Received sync contacts");
994 printAttachment(contactsMessage
.getContactsStream());
996 if (syncMessage
.getGroups().isPresent()) {
997 System
.out
.println("Received sync groups");
998 printAttachment(syncMessage
.getGroups().get());
1000 if (syncMessage
.getRead().isPresent()) {
1001 System
.out
.println("Received sync read messages list");
1002 for (ReadMessage rm
: syncMessage
.getRead().get()) {
1003 ContactInfo fromContact
= m
.getContact(rm
.getSender());
1004 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + DateUtils
.formatTimestamp(rm
.getTimestamp()));
1007 if (syncMessage
.getRequest().isPresent()) {
1008 System
.out
.println("Received sync request");
1009 if (syncMessage
.getRequest().get().isContactsRequest()) {
1010 System
.out
.println(" - contacts request");
1012 if (syncMessage
.getRequest().get().isGroupsRequest()) {
1013 System
.out
.println(" - groups request");
1016 if (syncMessage
.getSent().isPresent()) {
1017 System
.out
.println("Received sync sent message");
1018 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
1020 if (sentTranscriptMessage
.getDestination().isPresent()) {
1021 String dest
= sentTranscriptMessage
.getDestination().get();
1022 ContactInfo destContact
= m
.getContact(dest
);
1023 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
1027 System
.out
.println("To: " + to + " , Message timestamp: " + DateUtils
.formatTimestamp(sentTranscriptMessage
.getTimestamp()));
1028 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
1029 System
.out
.println("Expiration started at: " + DateUtils
.formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
1031 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
1032 handleSignalServiceDataMessage(message
);
1034 if (syncMessage
.getBlockedList().isPresent()) {
1035 System
.out
.println("Received sync message with block list");
1036 System
.out
.println("Blocked numbers:");
1037 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
1038 for (String number
: blockedList
.getNumbers()) {
1039 System
.out
.println(" - " + number
);
1042 if (syncMessage
.getVerified().isPresent()) {
1043 System
.out
.println("Received sync message with verified identities:");
1044 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1045 System
.out
.println(" - " + verifiedMessage
.getDestination() + ": " + verifiedMessage
.getVerified());
1046 String safetyNumber
= Util
.formatSafetyNumber(m
.computeSafetyNumber(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey()));
1047 System
.out
.println(" " + safetyNumber
);
1049 if (syncMessage
.getConfiguration().isPresent()) {
1050 System
.out
.println("Received sync message with configuration:");
1051 final ConfigurationMessage configurationMessage
= syncMessage
.getConfiguration().get();
1052 if (configurationMessage
.getReadReceipts().isPresent()) {
1053 System
.out
.println(" - Read receipts: " + (configurationMessage
.getReadReceipts().get() ?
"enabled" : "disabled"));
1057 if (content
.getCallMessage().isPresent()) {
1058 System
.out
.println("Received a call message");
1059 SignalServiceCallMessage callMessage
= content
.getCallMessage().get();
1060 if (callMessage
.getAnswerMessage().isPresent()) {
1061 AnswerMessage answerMessage
= callMessage
.getAnswerMessage().get();
1062 System
.out
.println("Answer message: " + answerMessage
.getId() + ": " + answerMessage
.getDescription());
1064 if (callMessage
.getBusyMessage().isPresent()) {
1065 BusyMessage busyMessage
= callMessage
.getBusyMessage().get();
1066 System
.out
.println("Busy message: " + busyMessage
.getId());
1068 if (callMessage
.getHangupMessage().isPresent()) {
1069 HangupMessage hangupMessage
= callMessage
.getHangupMessage().get();
1070 System
.out
.println("Hangup message: " + hangupMessage
.getId());
1072 if (callMessage
.getIceUpdateMessages().isPresent()) {
1073 List
<IceUpdateMessage
> iceUpdateMessages
= callMessage
.getIceUpdateMessages().get();
1074 for (IceUpdateMessage iceUpdateMessage
: iceUpdateMessages
) {
1075 System
.out
.println("Ice update message: " + iceUpdateMessage
.getId() + ", sdp: " + iceUpdateMessage
.getSdp());
1078 if (callMessage
.getOfferMessage().isPresent()) {
1079 OfferMessage offerMessage
= callMessage
.getOfferMessage().get();
1080 System
.out
.println("Offer message: " + offerMessage
.getId() + ": " + offerMessage
.getDescription());
1083 if (content
.getReceiptMessage().isPresent()) {
1084 System
.out
.println("Received a receipt message");
1085 SignalServiceReceiptMessage receiptMessage
= content
.getReceiptMessage().get();
1086 System
.out
.println(" - When: " + DateUtils
.formatTimestamp(receiptMessage
.getWhen()));
1087 if (receiptMessage
.isDeliveryReceipt()) {
1088 System
.out
.println(" - Is delivery receipt");
1090 if (receiptMessage
.isReadReceipt()) {
1091 System
.out
.println(" - Is read receipt");
1093 System
.out
.println(" - Timestamps:");
1094 for (long timestamp
: receiptMessage
.getTimestamps()) {
1095 System
.out
.println(" " + DateUtils
.formatTimestamp(timestamp
));
1098 if (content
.getTypingMessage().isPresent()) {
1099 System
.out
.println("Received a typing message");
1100 SignalServiceTypingMessage typingMessage
= content
.getTypingMessage().get();
1101 System
.out
.println(" - Action: " + typingMessage
.getAction());
1102 System
.out
.println(" - Timestamp: " + DateUtils
.formatTimestamp(typingMessage
.getTimestamp()));
1103 if (typingMessage
.getGroupId().isPresent()) {
1104 GroupInfo group
= m
.getGroup(typingMessage
.getGroupId().get());
1105 if (group
!= null) {
1106 System
.out
.println(" Name: " + group
.name
);
1108 System
.out
.println(" Name: <Unknown group>");
1114 System
.out
.println("Unknown message received.");
1116 System
.out
.println();
1119 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
1120 System
.out
.println("Message timestamp: " + DateUtils
.formatTimestamp(message
.getTimestamp()));
1122 if (message
.getBody().isPresent()) {
1123 System
.out
.println("Body: " + message
.getBody().get());
1125 if (message
.getGroupInfo().isPresent()) {
1126 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1127 System
.out
.println("Group info:");
1128 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
1129 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
1130 System
.out
.println(" Name: " + groupInfo
.getName().get());
1132 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
1133 if (group
!= null) {
1134 System
.out
.println(" Name: " + group
.name
);
1136 System
.out
.println(" Name: <Unknown group>");
1139 System
.out
.println(" Type: " + groupInfo
.getType());
1140 if (groupInfo
.getMembers().isPresent()) {
1141 for (String member
: groupInfo
.getMembers().get()) {
1142 System
.out
.println(" Member: " + member
);
1145 if (groupInfo
.getAvatar().isPresent()) {
1146 System
.out
.println(" Avatar:");
1147 printAttachment(groupInfo
.getAvatar().get());
1150 if (message
.isEndSession()) {
1151 System
.out
.println("Is end session");
1153 if (message
.isExpirationUpdate()) {
1154 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
1156 if (message
.getExpiresInSeconds() > 0) {
1157 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
1159 if (message
.getProfileKey().isPresent()) {
1160 System
.out
.println("Profile key update, key length:" + message
.getProfileKey().get().length
);
1163 if (message
.getQuote().isPresent()) {
1164 SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1165 System
.out
.println("Quote: (" + quote
.getId() + ")");
1166 System
.out
.println(" Author: " + quote
.getAuthor().getNumber());
1167 System
.out
.println(" Text: " + quote
.getText());
1168 if (quote
.getAttachments().size() > 0) {
1169 System
.out
.println(" Attachments: ");
1170 for (SignalServiceDataMessage
.Quote
.QuotedAttachment attachment
: quote
.getAttachments()) {
1171 System
.out
.println(" Filename: " + attachment
.getFileName());
1172 System
.out
.println(" Type: " + attachment
.getContentType());
1173 System
.out
.println(" Thumbnail:");
1174 if (attachment
.getThumbnail() != null) {
1175 printAttachment(attachment
.getThumbnail());
1181 if (message
.getAttachments().isPresent()) {
1182 System
.out
.println("Attachments: ");
1183 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1184 printAttachment(attachment
);
1189 private void printAttachment(SignalServiceAttachment attachment
) {
1190 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
1191 if (attachment
.isPointer()) {
1192 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1193 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
);
1194 System
.out
.println(" Filename: " + (pointer
.getFileName().isPresent() ? pointer
.getFileName().get() : "-"));
1195 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
1196 System
.out
.println(" Voice note: " + (pointer
.getVoiceNote() ?
"yes" : "no"));
1197 System
.out
.println(" Dimensions: " + pointer
.getWidth() + "x" + pointer
.getHeight());
1198 File file
= m
.getAttachmentFile(pointer
.getId());
1199 if (file
.exists()) {
1200 System
.out
.println(" Stored plaintext in: " + file
);
1206 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
1208 final DBusConnection conn
;
1210 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1216 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1217 super.handleMessage(envelope
, content
, exception
);
1219 JsonDbusReceiveMessageHandler
.sendReceivedMessageToDbus(envelope
, content
, conn
, m
);
1223 private static class JsonReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
1226 final ObjectMapper jsonProcessor
;
1228 public JsonReceiveMessageHandler(Manager m
) {
1230 this.jsonProcessor
= new ObjectMapper();
1231 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.ANY
); // disable autodetect
1232 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
1233 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
1234 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
1238 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1239 ObjectNode result
= jsonProcessor
.createObjectNode();
1240 if (exception
!= null) {
1241 result
.putPOJO("error", new JsonError(exception
));
1243 if (envelope
!= null) {
1244 result
.putPOJO("envelope", new JsonMessageEnvelope(envelope
, content
));
1247 jsonProcessor
.writeValue(System
.out
, result
);
1248 System
.out
.println();
1249 } catch (IOException e
) {
1250 e
.printStackTrace();
1255 private static class JsonDbusReceiveMessageHandler
extends JsonReceiveMessageHandler
{
1257 final DBusConnection conn
;
1259 public JsonDbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1264 private static void sendReceivedMessageToDbus(SignalServiceEnvelope envelope
, SignalServiceContent content
, DBusConnection conn
, Manager m
) {
1265 if (envelope
.isReceipt()) {
1267 conn
.sendSignal(new Signal
.ReceiptReceived(
1269 envelope
.getTimestamp(),
1270 envelope
.getSource()
1272 } catch (DBusException e
) {
1273 e
.printStackTrace();
1275 } else if (content
!= null && content
.getDataMessage().isPresent()) {
1276 SignalServiceDataMessage message
= content
.getDataMessage().get();
1278 if (!message
.isEndSession() &&
1279 !(message
.getGroupInfo().isPresent() &&
1280 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
1281 List
<String
> attachments
= new ArrayList
<>();
1282 if (message
.getAttachments().isPresent()) {
1283 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1284 if (attachment
.isPointer()) {
1285 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
1291 conn
.sendSignal(new Signal
.MessageReceived(
1293 message
.getTimestamp(),
1294 envelope
.getSource(),
1295 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1296 message
.getBody().isPresent() ? message
.getBody().get() : "",
1298 } catch (DBusException e
) {
1299 e
.printStackTrace();
1306 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1307 super.handleMessage(envelope
, content
, exception
);
1309 sendReceivedMessageToDbus(envelope
, content
, conn
, m
);