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
);
132 if (m
.userExists()) {
135 } catch (Exception e
) {
136 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
142 switch (ns
.getString("command")) {
144 if (dBusConn
!= null) {
145 System
.err
.println("register is not yet implemented via dbus");
148 if (!m
.userHasKeys()) {
149 m
.createNewIdentity();
152 m
.register(ns
.getBoolean("voice"));
153 } catch (IOException e
) {
154 System
.err
.println("Request verify error: " + e
.getMessage());
159 if (dBusConn
!= null) {
160 System
.err
.println("unregister is not yet implemented via dbus");
163 if (!m
.isRegistered()) {
164 System
.err
.println("User is not registered.");
169 } catch (IOException e
) {
170 System
.err
.println("Unregister error: " + e
.getMessage());
174 case "updateAccount":
175 if (dBusConn
!= null) {
176 System
.err
.println("updateAccount is not yet implemented via dbus");
179 if (!m
.isRegistered()) {
180 System
.err
.println("User is not registered.");
184 m
.updateAccountAttributes();
185 } catch (IOException e
) {
186 System
.err
.println("UpdateAccount error: " + e
.getMessage());
191 if (dBusConn
!= null) {
192 System
.err
.println("setPin is not yet implemented via dbus");
195 if (!m
.isRegistered()) {
196 System
.err
.println("User is not registered.");
200 String registrationLockPin
= ns
.getString("registrationLockPin");
201 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
202 } catch (IOException e
) {
203 System
.err
.println("Set pin error: " + e
.getMessage());
208 if (dBusConn
!= null) {
209 System
.err
.println("removePin is not yet implemented via dbus");
212 if (!m
.isRegistered()) {
213 System
.err
.println("User is not registered.");
217 m
.setRegistrationLockPin(Optional
.<String
>absent());
218 } catch (IOException e
) {
219 System
.err
.println("Remove pin error: " + e
.getMessage());
224 if (dBusConn
!= null) {
225 System
.err
.println("verify is not yet implemented via dbus");
228 if (!m
.userHasKeys()) {
229 System
.err
.println("User has no keys, first call register.");
232 if (m
.isRegistered()) {
233 System
.err
.println("User registration is already verified");
237 String verificationCode
= ns
.getString("verificationCode");
238 String pin
= ns
.getString("pin");
239 m
.verifyAccount(verificationCode
, pin
);
240 } catch (LockedException e
) {
241 System
.err
.println("Verification failed! This number is locked with a pin. Hours remaining until reset: " + (e
.getTimeRemaining() / 1000 / 60 / 60));
242 System
.err
.println("Use '--pin PIN_CODE' to specify the registration lock PIN");
244 } catch (IOException e
) {
245 System
.err
.println("Verify error: " + e
.getMessage());
250 if (dBusConn
!= null) {
251 System
.err
.println("link is not yet implemented via dbus");
255 // When linking, username is null and we always have to create keys
256 m
.createNewIdentity();
258 String deviceName
= ns
.getString("name");
259 if (deviceName
== null) {
263 System
.out
.println(m
.getDeviceLinkUri());
264 m
.finishDeviceLink(deviceName
);
265 System
.out
.println("Associated with: " + m
.getUsername());
266 } catch (TimeoutException e
) {
267 System
.err
.println("Link request timed out, please try again.");
269 } catch (IOException e
) {
270 System
.err
.println("Link request error: " + e
.getMessage());
272 } catch (AssertionError e
) {
273 handleAssertionError(e
);
275 } catch (InvalidKeyException e
) {
278 } catch (UserAlreadyExists e
) {
279 System
.err
.println("The user " + e
.getUsername() + " already exists\nDelete \"" + e
.getFileName() + "\" before trying again.");
284 if (dBusConn
!= null) {
285 System
.err
.println("link is not yet implemented via dbus");
288 if (!m
.isRegistered()) {
289 System
.err
.println("User is not registered.");
293 m
.addDeviceLink(new URI(ns
.getString("uri")));
294 } catch (IOException e
) {
297 } catch (InvalidKeyException e
) {
300 } catch (AssertionError e
) {
301 handleAssertionError(e
);
303 } catch (URISyntaxException e
) {
309 if (dBusConn
!= null) {
310 System
.err
.println("listDevices is not yet implemented via dbus");
313 if (!m
.isRegistered()) {
314 System
.err
.println("User is not registered.");
318 List
<DeviceInfo
> devices
= m
.getLinkedDevices();
319 for (DeviceInfo d
: devices
) {
320 System
.out
.println("Device " + d
.getId() + (d
.getId() == m
.getDeviceId() ?
" (this device)" : "") + ":");
321 System
.out
.println(" Name: " + d
.getName());
322 System
.out
.println(" Created: " + DateUtils
.formatTimestamp(d
.getCreated()));
323 System
.out
.println(" Last seen: " + DateUtils
.formatTimestamp(d
.getLastSeen()));
325 } catch (IOException e
) {
331 if (dBusConn
!= null) {
332 System
.err
.println("removeDevice is not yet implemented via dbus");
335 if (!m
.isRegistered()) {
336 System
.err
.println("User is not registered.");
340 int deviceId
= ns
.getInt("deviceId");
341 m
.removeLinkedDevices(deviceId
);
342 } catch (IOException e
) {
348 if (dBusConn
== null && !m
.isRegistered()) {
349 System
.err
.println("User is not registered.");
353 if (ns
.getBoolean("endsession")) {
354 if (ns
.getList("recipient") == null) {
355 System
.err
.println("No recipients given");
356 System
.err
.println("Aborting sending.");
360 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
361 } catch (IOException e
) {
362 handleIOException(e
);
364 } catch (EncapsulatedExceptions e
) {
365 handleEncapsulatedExceptions(e
);
367 } catch (AssertionError e
) {
368 handleAssertionError(e
);
370 } catch (DBusExecutionException e
) {
371 handleDBusExecutionException(e
);
375 String messageText
= ns
.getString("message");
376 if (messageText
== null) {
378 messageText
= IOUtils
.readAll(System
.in, Charset
.defaultCharset());
379 } catch (IOException e
) {
380 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
381 System
.err
.println("Aborting sending.");
387 List
<String
> attachments
= ns
.getList("attachment");
388 if (attachments
== null) {
389 attachments
= new ArrayList
<>();
391 if (ns
.getString("group") != null) {
392 byte[] groupId
= decodeGroupId(ns
.getString("group"));
393 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
395 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
397 } catch (IOException e
) {
398 handleIOException(e
);
400 } catch (EncapsulatedExceptions e
) {
401 handleEncapsulatedExceptions(e
);
403 } catch (AssertionError e
) {
404 handleAssertionError(e
);
406 } catch (GroupNotFoundException e
) {
407 handleGroupNotFoundException(e
);
409 } catch (NotAGroupMemberException e
) {
410 handleNotAGroupMemberException(e
);
412 } catch (AttachmentInvalidException e
) {
413 System
.err
.println("Failed to add attachment: " + e
.getMessage());
414 System
.err
.println("Aborting sending.");
416 } catch (DBusExecutionException e
) {
417 handleDBusExecutionException(e
);
424 if (dBusConn
!= null) {
426 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
428 public void handle(Signal
.MessageReceived s
) {
429 System
.out
.print(String
.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
430 s
.getSender(), DateUtils
.formatTimestamp(s
.getTimestamp()), s
.getMessage()));
431 if (s
.getGroupId().length
> 0) {
432 System
.out
.println("Group info:");
433 System
.out
.println(" Id: " + Base64
.encodeBytes(s
.getGroupId()));
435 if (s
.getAttachments().size() > 0) {
436 System
.out
.println("Attachments: ");
437 for (String attachment
: s
.getAttachments()) {
438 System
.out
.println("- Stored plaintext in: " + attachment
);
441 System
.out
.println();
444 dBusConn
.addSigHandler(Signal
.ReceiptReceived
.class, new DBusSigHandler
<Signal
.ReceiptReceived
>() {
446 public void handle(Signal
.ReceiptReceived s
) {
447 System
.out
.print(String
.format("Receipt from: %s\nTimestamp: %s\n",
448 s
.getSender(), DateUtils
.formatTimestamp(s
.getTimestamp())));
451 } catch (UnsatisfiedLinkError e
) {
452 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
454 } catch (DBusException e
) {
461 } catch (InterruptedException e
) {
466 if (!m
.isRegistered()) {
467 System
.err
.println("User is not registered.");
471 if (ns
.getDouble("timeout") != null) {
472 timeout
= ns
.getDouble("timeout");
474 boolean returnOnTimeout
= true;
476 returnOnTimeout
= false;
479 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
481 final Manager
.ReceiveMessageHandler handler
= ns
.getBoolean("json") ?
new JsonReceiveMessageHandler(m
) : new ReceiveMessageHandler(m
);
482 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, ignoreAttachments
, handler
);
483 } catch (IOException e
) {
484 System
.err
.println("Error while receiving messages: " + e
.getMessage());
486 } catch (AssertionError e
) {
487 handleAssertionError(e
);
492 if (dBusConn
!= null) {
493 System
.err
.println("quitGroup is not yet implemented via dbus");
496 if (!m
.isRegistered()) {
497 System
.err
.println("User is not registered.");
502 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
503 } catch (IOException e
) {
504 handleIOException(e
);
506 } catch (EncapsulatedExceptions e
) {
507 handleEncapsulatedExceptions(e
);
509 } catch (AssertionError e
) {
510 handleAssertionError(e
);
512 } catch (GroupNotFoundException e
) {
513 handleGroupNotFoundException(e
);
515 } catch (NotAGroupMemberException e
) {
516 handleNotAGroupMemberException(e
);
522 if (dBusConn
== null && !m
.isRegistered()) {
523 System
.err
.println("User is not registered.");
528 byte[] groupId
= null;
529 if (ns
.getString("group") != null) {
530 groupId
= decodeGroupId(ns
.getString("group"));
532 if (groupId
== null) {
533 groupId
= new byte[0];
535 String groupName
= ns
.getString("name");
536 if (groupName
== null) {
539 List
<String
> groupMembers
= ns
.<String
>getList("member");
540 if (groupMembers
== null) {
541 groupMembers
= new ArrayList
<String
>();
543 String groupAvatar
= ns
.getString("avatar");
544 if (groupAvatar
== null) {
547 byte[] newGroupId
= ts
.updateGroup(groupId
, groupName
, groupMembers
, groupAvatar
);
548 if (groupId
.length
!= newGroupId
.length
) {
549 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
551 } catch (IOException e
) {
552 handleIOException(e
);
554 } catch (AttachmentInvalidException e
) {
555 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
556 System
.err
.println("Aborting sending.");
558 } catch (GroupNotFoundException e
) {
559 handleGroupNotFoundException(e
);
561 } catch (NotAGroupMemberException e
) {
562 handleNotAGroupMemberException(e
);
564 } catch (EncapsulatedExceptions e
) {
565 handleEncapsulatedExceptions(e
);
571 if (dBusConn
!= null) {
572 System
.err
.println("listGroups is not yet implemented via dbus");
575 if (!m
.isRegistered()) {
576 System
.err
.println("User is not registered.");
580 List
<GroupInfo
> groups
= m
.getGroups();
581 boolean detailed
= ns
.getBoolean("detailed");
583 for (GroupInfo group
: groups
) {
584 printGroup(group
, detailed
);
587 case "listIdentities":
588 if (dBusConn
!= null) {
589 System
.err
.println("listIdentities is not yet implemented via dbus");
592 if (!m
.isRegistered()) {
593 System
.err
.println("User is not registered.");
596 if (ns
.get("number") == null) {
597 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
598 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
599 printIdentityFingerprint(m
, keys
.getKey(), id
);
603 String number
= ns
.getString("number");
604 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
605 printIdentityFingerprint(m
, number
, id
);
610 if (dBusConn
!= null) {
611 System
.err
.println("trust is not yet implemented via dbus");
614 if (!m
.isRegistered()) {
615 System
.err
.println("User is not registered.");
618 String number
= ns
.getString("number");
619 if (ns
.getBoolean("trust_all_known_keys")) {
620 boolean res
= m
.trustIdentityAllKeys(number
);
622 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
626 String fingerprint
= ns
.getString("verified_fingerprint");
627 if (fingerprint
!= null) {
628 fingerprint
= fingerprint
.replaceAll(" ", "");
629 if (fingerprint
.length() == 66) {
630 byte[] fingerprintBytes
;
632 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
633 } catch (Exception e
) {
634 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
637 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
639 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
642 } else if (fingerprint
.length() == 60) {
643 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
645 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.");
649 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
653 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
659 if (dBusConn
!= null) {
660 System
.err
.println("Stop it.");
663 if (!m
.isRegistered()) {
664 System
.err
.println("User is not registered.");
667 DBusConnection conn
= null;
671 if (ns
.getBoolean("system")) {
672 busType
= DBusConnection
.SYSTEM
;
674 busType
= DBusConnection
.SESSION
;
676 conn
= DBusConnection
.getConnection(busType
);
677 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
678 conn
.requestBusName(SIGNAL_BUSNAME
);
679 } catch (UnsatisfiedLinkError e
) {
680 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
682 } catch (DBusException e
) {
686 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
688 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, ns
.getBoolean("json") ?
new JsonDbusReceiveMessageHandler(m
, conn
) : new DbusReceiveMessageHandler(m
, conn
));
689 } catch (IOException e
) {
690 System
.err
.println("Error while receiving messages: " + e
.getMessage());
692 } catch (AssertionError e
) {
693 handleAssertionError(e
);
706 if (dBusConn
!= null) {
707 dBusConn
.disconnect();
712 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
713 String digits
= Util
.formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.getIdentityKey()));
714 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
715 theirId
.getTrustLevel(), theirId
.getDateAdded(), Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
718 private static void printGroup(GroupInfo group
, boolean detailed
) {
720 System
.out
.println(String
.format("Id: %s Name: %s Active: %s Members: %s",
721 Base64
.encodeBytes(group
.groupId
), group
.name
, group
.active
, group
.members
));
723 System
.out
.println(String
.format("Id: %s Name: %s Active: %s", Base64
.encodeBytes(group
.groupId
),
724 group
.name
, group
.active
));
728 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
729 System
.err
.println("Failed to send to group: " + e
.getMessage());
730 System
.err
.println("Aborting sending.");
733 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
734 System
.err
.println("Failed to send to group: " + e
.getMessage());
735 System
.err
.println("Update the group on another device to readd the user to this group.");
736 System
.err
.println("Aborting sending.");
740 private static void handleDBusExecutionException(DBusExecutionException e
) {
741 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
742 System
.err
.println("Aborting.");
745 private static byte[] decodeGroupId(String groupId
) {
747 return Base64
.decode(groupId
);
748 } catch (IOException e
) {
749 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
750 System
.err
.println("Aborting sending.");
756 private static Namespace
parseArgs(String
[] args
) {
757 ArgumentParser parser
= ArgumentParsers
.newFor("signal-cli")
760 .description("Commandline interface for Signal.")
761 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
763 parser
.addArgument("-v", "--version")
764 .help("Show package version.")
765 .action(Arguments
.version());
766 parser
.addArgument("--config")
767 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
769 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
770 mut
.addArgument("-u", "--username")
771 .help("Specify your phone number, that will be used for verification.");
772 mut
.addArgument("--dbus")
773 .help("Make request via user dbus.")
774 .action(Arguments
.storeTrue());
775 mut
.addArgument("--dbus-system")
776 .help("Make request via system dbus.")
777 .action(Arguments
.storeTrue());
779 Subparsers subparsers
= parser
.addSubparsers()
780 .title("subcommands")
782 .description("valid subcommands")
783 .help("additional help");
785 Subparser parserLink
= subparsers
.addParser("link");
786 parserLink
.addArgument("-n", "--name")
787 .help("Specify a name to describe this new device.");
789 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
790 parserAddDevice
.addArgument("--uri")
792 .help("Specify the uri contained in the QR code shown by the new device.");
794 Subparser parserDevices
= subparsers
.addParser("listDevices");
796 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
797 parserRemoveDevice
.addArgument("-d", "--deviceId")
800 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
802 Subparser parserRegister
= subparsers
.addParser("register");
803 parserRegister
.addArgument("-v", "--voice")
804 .help("The verification should be done over voice, not sms.")
805 .action(Arguments
.storeTrue());
807 Subparser parserUnregister
= subparsers
.addParser("unregister");
808 parserUnregister
.help("Unregister the current device from the signal server.");
810 Subparser parserUpdateAccount
= subparsers
.addParser("updateAccount");
811 parserUpdateAccount
.help("Update the account attributes on the signal server.");
813 Subparser parserSetPin
= subparsers
.addParser("setPin");
814 parserSetPin
.addArgument("registrationLockPin")
815 .help("The registration lock PIN, that will be required for new registrations (resets after 7 days of inactivity)");
817 Subparser parserRemovePin
= subparsers
.addParser("removePin");
819 Subparser parserVerify
= subparsers
.addParser("verify");
820 parserVerify
.addArgument("verificationCode")
821 .help("The verification code you received via sms or voice call.");
822 parserVerify
.addArgument("-p", "--pin")
823 .help("The registration lock PIN, that was set by the user (Optional)");
825 Subparser parserSend
= subparsers
.addParser("send");
826 parserSend
.addArgument("-g", "--group")
827 .help("Specify the recipient group ID.");
828 parserSend
.addArgument("recipient")
829 .help("Specify the recipients' phone number.")
831 parserSend
.addArgument("-m", "--message")
832 .help("Specify the message, if missing standard input is used.");
833 parserSend
.addArgument("-a", "--attachment")
835 .help("Add file as attachment");
836 parserSend
.addArgument("-e", "--endsession")
837 .help("Clear session state and send end session message.")
838 .action(Arguments
.storeTrue());
840 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
841 parserLeaveGroup
.addArgument("-g", "--group")
843 .help("Specify the recipient group ID.");
845 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
846 parserUpdateGroup
.addArgument("-g", "--group")
847 .help("Specify the recipient group ID.");
848 parserUpdateGroup
.addArgument("-n", "--name")
849 .help("Specify the new group name.");
850 parserUpdateGroup
.addArgument("-a", "--avatar")
851 .help("Specify a new group avatar image file");
852 parserUpdateGroup
.addArgument("-m", "--member")
854 .help("Specify one or more members to add to the group");
856 Subparser parserListGroups
= subparsers
.addParser("listGroups");
857 parserListGroups
.addArgument("-d", "--detailed").action(Arguments
.storeTrue())
858 .help("List members of each group");
859 parserListGroups
.help("List group name and ids");
861 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
862 parserListIdentities
.addArgument("-n", "--number")
863 .help("Only show identity keys for the given phone number.");
865 Subparser parserTrust
= subparsers
.addParser("trust");
866 parserTrust
.addArgument("number")
867 .help("Specify the phone number, for which to set the trust.")
869 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
870 mutTrust
.addArgument("-a", "--trust-all-known-keys")
871 .help("Trust all known keys of this user, only use this for testing.")
872 .action(Arguments
.storeTrue());
873 mutTrust
.addArgument("-v", "--verified-fingerprint")
874 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
876 Subparser parserReceive
= subparsers
.addParser("receive");
877 parserReceive
.addArgument("-t", "--timeout")
879 .help("Number of seconds to wait for new messages (negative values disable timeout)");
880 parserReceive
.addArgument("--ignore-attachments")
881 .help("Don’t download attachments of received messages.")
882 .action(Arguments
.storeTrue());
883 parserReceive
.addArgument("--json")
884 .help("Output received messages in json format, one json object per line.")
885 .action(Arguments
.storeTrue());
887 Subparser parserDaemon
= subparsers
.addParser("daemon");
888 parserDaemon
.addArgument("--system")
889 .action(Arguments
.storeTrue())
890 .help("Use DBus system bus instead of user bus.");
891 parserDaemon
.addArgument("--ignore-attachments")
892 .help("Don’t download attachments of received messages.")
893 .action(Arguments
.storeTrue());
894 parserDaemon
.addArgument("--json")
895 .help("Output received messages in json format, one json object per line.")
896 .action(Arguments
.storeTrue());
899 Namespace ns
= parser
.parseArgs(args
);
900 if ("link".equals(ns
.getString("command"))) {
901 if (ns
.getString("username") != null) {
903 System
.err
.println("You cannot specify a username (phone number) when linking");
906 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
907 if (ns
.getString("username") == null) {
909 System
.err
.println("You need to specify a username (phone number)");
912 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
913 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
917 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
918 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
922 } catch (ArgumentParserException e
) {
923 parser
.handleError(e
);
928 private static void handleAssertionError(AssertionError e
) {
929 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
931 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
934 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
935 System
.err
.println("Failed to send (some) messages:");
936 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
937 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
939 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
940 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
942 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
943 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
947 private static void handleIOException(IOException e
) {
948 System
.err
.println("Failed to send message: " + e
.getMessage());
951 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
954 public ReceiveMessageHandler(Manager m
) {
959 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
960 SignalServiceAddress source
= envelope
.getSourceAddress();
961 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
962 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
963 if (source
.getRelay().isPresent()) {
964 System
.out
.println("Relayed by: " + source
.getRelay().get());
966 System
.out
.println("Timestamp: " + DateUtils
.formatTimestamp(envelope
.getTimestamp()));
967 if (envelope
.isUnidentifiedSender()) {
968 System
.out
.println("Sent by unidentified/sealed sender");
971 if (envelope
.isReceipt()) {
972 System
.out
.println("Got receipt.");
973 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
974 if (exception
!= null) {
975 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
976 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
977 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
978 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");
979 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");
981 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
984 if (content
== null) {
985 System
.out
.println("Failed to decrypt message.");
987 if (content
.getDataMessage().isPresent()) {
988 SignalServiceDataMessage message
= content
.getDataMessage().get();
989 handleSignalServiceDataMessage(message
);
991 if (content
.getSyncMessage().isPresent()) {
992 System
.out
.println("Received a sync message");
993 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
995 if (syncMessage
.getContacts().isPresent()) {
996 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
997 if (contactsMessage
.isComplete()) {
998 System
.out
.println("Received complete sync contacts");
1000 System
.out
.println("Received sync contacts");
1002 printAttachment(contactsMessage
.getContactsStream());
1004 if (syncMessage
.getGroups().isPresent()) {
1005 System
.out
.println("Received sync groups");
1006 printAttachment(syncMessage
.getGroups().get());
1008 if (syncMessage
.getRead().isPresent()) {
1009 System
.out
.println("Received sync read messages list");
1010 for (ReadMessage rm
: syncMessage
.getRead().get()) {
1011 ContactInfo fromContact
= m
.getContact(rm
.getSender());
1012 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + DateUtils
.formatTimestamp(rm
.getTimestamp()));
1015 if (syncMessage
.getRequest().isPresent()) {
1016 System
.out
.println("Received sync request");
1017 if (syncMessage
.getRequest().get().isContactsRequest()) {
1018 System
.out
.println(" - contacts request");
1020 if (syncMessage
.getRequest().get().isGroupsRequest()) {
1021 System
.out
.println(" - groups request");
1024 if (syncMessage
.getSent().isPresent()) {
1025 System
.out
.println("Received sync sent message");
1026 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
1028 if (sentTranscriptMessage
.getDestination().isPresent()) {
1029 String dest
= sentTranscriptMessage
.getDestination().get();
1030 ContactInfo destContact
= m
.getContact(dest
);
1031 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
1035 System
.out
.println("To: " + to + " , Message timestamp: " + DateUtils
.formatTimestamp(sentTranscriptMessage
.getTimestamp()));
1036 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
1037 System
.out
.println("Expiration started at: " + DateUtils
.formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
1039 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
1040 handleSignalServiceDataMessage(message
);
1042 if (syncMessage
.getBlockedList().isPresent()) {
1043 System
.out
.println("Received sync message with block list");
1044 System
.out
.println("Blocked numbers:");
1045 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
1046 for (String number
: blockedList
.getNumbers()) {
1047 System
.out
.println(" - " + number
);
1050 if (syncMessage
.getVerified().isPresent()) {
1051 System
.out
.println("Received sync message with verified identities:");
1052 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1053 System
.out
.println(" - " + verifiedMessage
.getDestination() + ": " + verifiedMessage
.getVerified());
1054 String safetyNumber
= Util
.formatSafetyNumber(m
.computeSafetyNumber(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey()));
1055 System
.out
.println(" " + safetyNumber
);
1057 if (syncMessage
.getConfiguration().isPresent()) {
1058 System
.out
.println("Received sync message with configuration:");
1059 final ConfigurationMessage configurationMessage
= syncMessage
.getConfiguration().get();
1060 if (configurationMessage
.getReadReceipts().isPresent()) {
1061 System
.out
.println(" - Read receipts: " + (configurationMessage
.getReadReceipts().get() ?
"enabled" : "disabled"));
1065 if (content
.getCallMessage().isPresent()) {
1066 System
.out
.println("Received a call message");
1067 SignalServiceCallMessage callMessage
= content
.getCallMessage().get();
1068 if (callMessage
.getAnswerMessage().isPresent()) {
1069 AnswerMessage answerMessage
= callMessage
.getAnswerMessage().get();
1070 System
.out
.println("Answer message: " + answerMessage
.getId() + ": " + answerMessage
.getDescription());
1072 if (callMessage
.getBusyMessage().isPresent()) {
1073 BusyMessage busyMessage
= callMessage
.getBusyMessage().get();
1074 System
.out
.println("Busy message: " + busyMessage
.getId());
1076 if (callMessage
.getHangupMessage().isPresent()) {
1077 HangupMessage hangupMessage
= callMessage
.getHangupMessage().get();
1078 System
.out
.println("Hangup message: " + hangupMessage
.getId());
1080 if (callMessage
.getIceUpdateMessages().isPresent()) {
1081 List
<IceUpdateMessage
> iceUpdateMessages
= callMessage
.getIceUpdateMessages().get();
1082 for (IceUpdateMessage iceUpdateMessage
: iceUpdateMessages
) {
1083 System
.out
.println("Ice update message: " + iceUpdateMessage
.getId() + ", sdp: " + iceUpdateMessage
.getSdp());
1086 if (callMessage
.getOfferMessage().isPresent()) {
1087 OfferMessage offerMessage
= callMessage
.getOfferMessage().get();
1088 System
.out
.println("Offer message: " + offerMessage
.getId() + ": " + offerMessage
.getDescription());
1091 if (content
.getReceiptMessage().isPresent()) {
1092 System
.out
.println("Received a receipt message");
1093 SignalServiceReceiptMessage receiptMessage
= content
.getReceiptMessage().get();
1094 System
.out
.println(" - When: " + DateUtils
.formatTimestamp(receiptMessage
.getWhen()));
1095 if (receiptMessage
.isDeliveryReceipt()) {
1096 System
.out
.println(" - Is delivery receipt");
1098 if (receiptMessage
.isReadReceipt()) {
1099 System
.out
.println(" - Is read receipt");
1101 System
.out
.println(" - Timestamps:");
1102 for (long timestamp
: receiptMessage
.getTimestamps()) {
1103 System
.out
.println(" " + DateUtils
.formatTimestamp(timestamp
));
1106 if (content
.getTypingMessage().isPresent()) {
1107 System
.out
.println("Received a typing message");
1108 SignalServiceTypingMessage typingMessage
= content
.getTypingMessage().get();
1109 System
.out
.println(" - Action: " + typingMessage
.getAction());
1110 System
.out
.println(" - Timestamp: " + DateUtils
.formatTimestamp(typingMessage
.getTimestamp()));
1111 if (typingMessage
.getGroupId().isPresent()) {
1112 GroupInfo group
= m
.getGroup(typingMessage
.getGroupId().get());
1113 if (group
!= null) {
1114 System
.out
.println(" Name: " + group
.name
);
1116 System
.out
.println(" Name: <Unknown group>");
1122 System
.out
.println("Unknown message received.");
1124 System
.out
.println();
1127 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
1128 System
.out
.println("Message timestamp: " + DateUtils
.formatTimestamp(message
.getTimestamp()));
1130 if (message
.getBody().isPresent()) {
1131 System
.out
.println("Body: " + message
.getBody().get());
1133 if (message
.getGroupInfo().isPresent()) {
1134 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1135 System
.out
.println("Group info:");
1136 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
1137 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
1138 System
.out
.println(" Name: " + groupInfo
.getName().get());
1140 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
1141 if (group
!= null) {
1142 System
.out
.println(" Name: " + group
.name
);
1144 System
.out
.println(" Name: <Unknown group>");
1147 System
.out
.println(" Type: " + groupInfo
.getType());
1148 if (groupInfo
.getMembers().isPresent()) {
1149 for (String member
: groupInfo
.getMembers().get()) {
1150 System
.out
.println(" Member: " + member
);
1153 if (groupInfo
.getAvatar().isPresent()) {
1154 System
.out
.println(" Avatar:");
1155 printAttachment(groupInfo
.getAvatar().get());
1158 if (message
.isEndSession()) {
1159 System
.out
.println("Is end session");
1161 if (message
.isExpirationUpdate()) {
1162 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
1164 if (message
.getExpiresInSeconds() > 0) {
1165 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
1167 if (message
.getProfileKey().isPresent()) {
1168 System
.out
.println("Profile key update, key length:" + message
.getProfileKey().get().length
);
1171 if (message
.getQuote().isPresent()) {
1172 SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1173 System
.out
.println("Quote: (" + quote
.getId() + ")");
1174 System
.out
.println(" Author: " + quote
.getAuthor().getNumber());
1175 System
.out
.println(" Text: " + quote
.getText());
1176 if (quote
.getAttachments().size() > 0) {
1177 System
.out
.println(" Attachments: ");
1178 for (SignalServiceDataMessage
.Quote
.QuotedAttachment attachment
: quote
.getAttachments()) {
1179 System
.out
.println(" Filename: " + attachment
.getFileName());
1180 System
.out
.println(" Type: " + attachment
.getContentType());
1181 System
.out
.println(" Thumbnail:");
1182 if (attachment
.getThumbnail() != null) {
1183 printAttachment(attachment
.getThumbnail());
1189 if (message
.getAttachments().isPresent()) {
1190 System
.out
.println("Attachments: ");
1191 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1192 printAttachment(attachment
);
1197 private void printAttachment(SignalServiceAttachment attachment
) {
1198 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
1199 if (attachment
.isPointer()) {
1200 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1201 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
);
1202 System
.out
.println(" Filename: " + (pointer
.getFileName().isPresent() ? pointer
.getFileName().get() : "-"));
1203 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
1204 System
.out
.println(" Voice note: " + (pointer
.getVoiceNote() ?
"yes" : "no"));
1205 System
.out
.println(" Dimensions: " + pointer
.getWidth() + "x" + pointer
.getHeight());
1206 File file
= m
.getAttachmentFile(pointer
.getId());
1207 if (file
.exists()) {
1208 System
.out
.println(" Stored plaintext in: " + file
);
1214 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
1215 final DBusConnection conn
;
1217 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1223 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1224 super.handleMessage(envelope
, content
, exception
);
1226 JsonDbusReceiveMessageHandler
.sendReceivedMessageToDbus(envelope
, content
, conn
, m
);
1230 private static class JsonReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
1232 final ObjectMapper jsonProcessor
;
1234 public JsonReceiveMessageHandler(Manager m
) {
1236 this.jsonProcessor
= new ObjectMapper();
1237 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.ANY
); // disable autodetect
1238 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
1239 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
1240 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
1244 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1245 ObjectNode result
= jsonProcessor
.createObjectNode();
1246 if (exception
!= null) {
1247 result
.putPOJO("error", new JsonError(exception
));
1249 if (envelope
!= null) {
1250 result
.putPOJO("envelope", new JsonMessageEnvelope(envelope
, content
));
1253 jsonProcessor
.writeValue(System
.out
, result
);
1254 System
.out
.println();
1255 } catch (IOException e
) {
1256 e
.printStackTrace();
1261 private static class JsonDbusReceiveMessageHandler
extends JsonReceiveMessageHandler
{
1262 final DBusConnection conn
;
1264 public JsonDbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1270 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1271 super.handleMessage(envelope
, content
, exception
);
1273 sendReceivedMessageToDbus(envelope
, content
, conn
, m
);
1276 private static void sendReceivedMessageToDbus(SignalServiceEnvelope envelope
, SignalServiceContent content
, DBusConnection conn
, Manager m
) {
1277 if (envelope
.isReceipt()) {
1279 conn
.sendSignal(new Signal
.ReceiptReceived(
1281 envelope
.getTimestamp(),
1282 envelope
.getSource()
1284 } catch (DBusException e
) {
1285 e
.printStackTrace();
1287 } else if (content
!= null && content
.getDataMessage().isPresent()) {
1288 SignalServiceDataMessage message
= content
.getDataMessage().get();
1290 if (!message
.isEndSession() &&
1291 !(message
.getGroupInfo().isPresent() &&
1292 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
1293 List
<String
> attachments
= new ArrayList
<>();
1294 if (message
.getAttachments().isPresent()) {
1295 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1296 if (attachment
.isPointer()) {
1297 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
1303 conn
.sendSignal(new Signal
.MessageReceived(
1305 message
.getTimestamp(),
1306 envelope
.getSource(),
1307 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1308 message
.getBody().isPresent() ? message
.getBody().get() : "",
1310 } catch (DBusException e
) {
1311 e
.printStackTrace();