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 private static final String SIGNAL_BUSNAME
= "org.asamk.Signal";
74 private 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
| URISyntaxException e
) {
292 } catch (AssertionError e
) {
293 handleAssertionError(e
);
298 if (dBusConn
!= null) {
299 System
.err
.println("listDevices is not yet implemented via dbus");
302 if (!m
.isRegistered()) {
303 System
.err
.println("User is not registered.");
307 List
<DeviceInfo
> devices
= m
.getLinkedDevices();
308 for (DeviceInfo d
: devices
) {
309 System
.out
.println("Device " + d
.getId() + (d
.getId() == m
.getDeviceId() ?
" (this device)" : "") + ":");
310 System
.out
.println(" Name: " + d
.getName());
311 System
.out
.println(" Created: " + DateUtils
.formatTimestamp(d
.getCreated()));
312 System
.out
.println(" Last seen: " + DateUtils
.formatTimestamp(d
.getLastSeen()));
314 } catch (IOException e
) {
320 if (dBusConn
!= null) {
321 System
.err
.println("removeDevice is not yet implemented via dbus");
324 if (!m
.isRegistered()) {
325 System
.err
.println("User is not registered.");
329 int deviceId
= ns
.getInt("deviceId");
330 m
.removeLinkedDevices(deviceId
);
331 } catch (IOException e
) {
337 if (dBusConn
== null && !m
.isRegistered()) {
338 System
.err
.println("User is not registered.");
342 if (ns
.getBoolean("endsession")) {
343 if (ns
.getList("recipient") == null) {
344 System
.err
.println("No recipients given");
345 System
.err
.println("Aborting sending.");
349 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
350 } catch (IOException e
) {
351 handleIOException(e
);
353 } catch (EncapsulatedExceptions e
) {
354 handleEncapsulatedExceptions(e
);
356 } catch (AssertionError e
) {
357 handleAssertionError(e
);
359 } catch (DBusExecutionException e
) {
360 handleDBusExecutionException(e
);
364 String messageText
= ns
.getString("message");
365 if (messageText
== null) {
367 messageText
= IOUtils
.readAll(System
.in, Charset
.defaultCharset());
368 } catch (IOException e
) {
369 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
370 System
.err
.println("Aborting sending.");
376 List
<String
> attachments
= ns
.getList("attachment");
377 if (attachments
== null) {
378 attachments
= new ArrayList
<>();
380 if (ns
.getString("group") != null) {
381 byte[] groupId
= decodeGroupId(ns
.getString("group"));
382 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
384 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
386 } catch (IOException e
) {
387 handleIOException(e
);
389 } catch (EncapsulatedExceptions e
) {
390 handleEncapsulatedExceptions(e
);
392 } catch (AssertionError e
) {
393 handleAssertionError(e
);
395 } catch (GroupNotFoundException e
) {
396 handleGroupNotFoundException(e
);
398 } catch (NotAGroupMemberException e
) {
399 handleNotAGroupMemberException(e
);
401 } catch (AttachmentInvalidException e
) {
402 System
.err
.println("Failed to add attachment: " + e
.getMessage());
403 System
.err
.println("Aborting sending.");
405 } catch (DBusExecutionException e
) {
406 handleDBusExecutionException(e
);
413 if (dBusConn
!= null) {
415 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
417 public void handle(Signal
.MessageReceived s
) {
418 System
.out
.print(String
.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
419 s
.getSender(), DateUtils
.formatTimestamp(s
.getTimestamp()), s
.getMessage()));
420 if (s
.getGroupId().length
> 0) {
421 System
.out
.println("Group info:");
422 System
.out
.println(" Id: " + Base64
.encodeBytes(s
.getGroupId()));
424 if (s
.getAttachments().size() > 0) {
425 System
.out
.println("Attachments: ");
426 for (String attachment
: s
.getAttachments()) {
427 System
.out
.println("- Stored plaintext in: " + attachment
);
430 System
.out
.println();
433 dBusConn
.addSigHandler(Signal
.ReceiptReceived
.class, new DBusSigHandler
<Signal
.ReceiptReceived
>() {
435 public void handle(Signal
.ReceiptReceived s
) {
436 System
.out
.print(String
.format("Receipt from: %s\nTimestamp: %s\n",
437 s
.getSender(), DateUtils
.formatTimestamp(s
.getTimestamp())));
440 } catch (UnsatisfiedLinkError e
) {
441 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
443 } catch (DBusException e
) {
450 } catch (InterruptedException e
) {
455 if (!m
.isRegistered()) {
456 System
.err
.println("User is not registered.");
460 if (ns
.getDouble("timeout") != null) {
461 timeout
= ns
.getDouble("timeout");
463 boolean returnOnTimeout
= true;
465 returnOnTimeout
= false;
468 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
470 final Manager
.ReceiveMessageHandler handler
= ns
.getBoolean("json") ?
new JsonReceiveMessageHandler(m
) : new ReceiveMessageHandler(m
);
471 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, ignoreAttachments
, handler
);
472 } catch (IOException e
) {
473 System
.err
.println("Error while receiving messages: " + e
.getMessage());
475 } catch (AssertionError e
) {
476 handleAssertionError(e
);
481 if (dBusConn
!= null) {
482 System
.err
.println("quitGroup is not yet implemented via dbus");
485 if (!m
.isRegistered()) {
486 System
.err
.println("User is not registered.");
491 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
492 } catch (IOException e
) {
493 handleIOException(e
);
495 } catch (EncapsulatedExceptions e
) {
496 handleEncapsulatedExceptions(e
);
498 } catch (AssertionError e
) {
499 handleAssertionError(e
);
501 } catch (GroupNotFoundException e
) {
502 handleGroupNotFoundException(e
);
504 } catch (NotAGroupMemberException e
) {
505 handleNotAGroupMemberException(e
);
511 if (dBusConn
== null && !m
.isRegistered()) {
512 System
.err
.println("User is not registered.");
517 byte[] groupId
= null;
518 if (ns
.getString("group") != null) {
519 groupId
= decodeGroupId(ns
.getString("group"));
521 if (groupId
== null) {
522 groupId
= new byte[0];
524 String groupName
= ns
.getString("name");
525 if (groupName
== null) {
528 List
<String
> groupMembers
= ns
.getList("member");
529 if (groupMembers
== null) {
530 groupMembers
= new ArrayList
<>();
532 String groupAvatar
= ns
.getString("avatar");
533 if (groupAvatar
== null) {
536 byte[] newGroupId
= ts
.updateGroup(groupId
, groupName
, groupMembers
, groupAvatar
);
537 if (groupId
.length
!= newGroupId
.length
) {
538 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
540 } catch (IOException e
) {
541 handleIOException(e
);
543 } catch (AttachmentInvalidException e
) {
544 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
545 System
.err
.println("Aborting sending.");
547 } catch (GroupNotFoundException e
) {
548 handleGroupNotFoundException(e
);
550 } catch (NotAGroupMemberException e
) {
551 handleNotAGroupMemberException(e
);
553 } catch (EncapsulatedExceptions e
) {
554 handleEncapsulatedExceptions(e
);
560 if (dBusConn
!= null) {
561 System
.err
.println("listGroups is not yet implemented via dbus");
564 if (!m
.isRegistered()) {
565 System
.err
.println("User is not registered.");
569 List
<GroupInfo
> groups
= m
.getGroups();
570 boolean detailed
= ns
.getBoolean("detailed");
572 for (GroupInfo group
: groups
) {
573 printGroup(group
, detailed
);
576 case "listIdentities":
577 if (dBusConn
!= null) {
578 System
.err
.println("listIdentities is not yet implemented via dbus");
581 if (!m
.isRegistered()) {
582 System
.err
.println("User is not registered.");
585 if (ns
.get("number") == null) {
586 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
587 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
588 printIdentityFingerprint(m
, keys
.getKey(), id
);
592 String number
= ns
.getString("number");
593 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
594 printIdentityFingerprint(m
, number
, id
);
599 if (dBusConn
!= null) {
600 System
.err
.println("trust is not yet implemented via dbus");
603 if (!m
.isRegistered()) {
604 System
.err
.println("User is not registered.");
607 String number
= ns
.getString("number");
608 if (ns
.getBoolean("trust_all_known_keys")) {
609 boolean res
= m
.trustIdentityAllKeys(number
);
611 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
615 String fingerprint
= ns
.getString("verified_fingerprint");
616 if (fingerprint
!= null) {
617 fingerprint
= fingerprint
.replaceAll(" ", "");
618 if (fingerprint
.length() == 66) {
619 byte[] fingerprintBytes
;
621 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
622 } catch (Exception e
) {
623 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
626 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
628 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
631 } else if (fingerprint
.length() == 60) {
632 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
634 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.");
638 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
642 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
648 if (dBusConn
!= null) {
649 System
.err
.println("Stop it.");
652 if (!m
.isRegistered()) {
653 System
.err
.println("User is not registered.");
656 DBusConnection conn
= null;
660 if (ns
.getBoolean("system")) {
661 busType
= DBusConnection
.SYSTEM
;
663 busType
= DBusConnection
.SESSION
;
665 conn
= DBusConnection
.getConnection(busType
);
666 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
667 conn
.requestBusName(SIGNAL_BUSNAME
);
668 } catch (UnsatisfiedLinkError e
) {
669 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
671 } catch (DBusException e
) {
675 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
677 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, ns
.getBoolean("json") ?
new JsonDbusReceiveMessageHandler(m
, conn
) : new DbusReceiveMessageHandler(m
, conn
));
678 } catch (IOException e
) {
679 System
.err
.println("Error while receiving messages: " + e
.getMessage());
681 } catch (AssertionError e
) {
682 handleAssertionError(e
);
695 if (dBusConn
!= null) {
696 dBusConn
.disconnect();
701 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
702 String digits
= Util
.formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.getIdentityKey()));
703 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
704 theirId
.getTrustLevel(), theirId
.getDateAdded(), Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
707 private static void printGroup(GroupInfo group
, boolean detailed
) {
709 System
.out
.println(String
.format("Id: %s Name: %s Active: %s Members: %s",
710 Base64
.encodeBytes(group
.groupId
), group
.name
, group
.active
, group
.members
));
712 System
.out
.println(String
.format("Id: %s Name: %s Active: %s", Base64
.encodeBytes(group
.groupId
),
713 group
.name
, group
.active
));
717 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
718 System
.err
.println("Failed to send to group: " + e
.getMessage());
719 System
.err
.println("Aborting sending.");
722 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
723 System
.err
.println("Failed to send to group: " + e
.getMessage());
724 System
.err
.println("Update the group on another device to readd the user to this group.");
725 System
.err
.println("Aborting sending.");
728 private static void handleDBusExecutionException(DBusExecutionException e
) {
729 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
730 System
.err
.println("Aborting.");
733 private static byte[] decodeGroupId(String groupId
) {
735 return Base64
.decode(groupId
);
736 } catch (IOException e
) {
737 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
738 System
.err
.println("Aborting sending.");
744 private static Namespace
parseArgs(String
[] args
) {
745 ArgumentParser parser
= ArgumentParsers
.newFor("signal-cli")
748 .description("Commandline interface for Signal.")
749 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
751 parser
.addArgument("-v", "--version")
752 .help("Show package version.")
753 .action(Arguments
.version());
754 parser
.addArgument("--config")
755 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
757 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
758 mut
.addArgument("-u", "--username")
759 .help("Specify your phone number, that will be used for verification.");
760 mut
.addArgument("--dbus")
761 .help("Make request via user dbus.")
762 .action(Arguments
.storeTrue());
763 mut
.addArgument("--dbus-system")
764 .help("Make request via system dbus.")
765 .action(Arguments
.storeTrue());
767 Subparsers subparsers
= parser
.addSubparsers()
768 .title("subcommands")
770 .description("valid subcommands")
771 .help("additional help");
773 Subparser parserLink
= subparsers
.addParser("link");
774 parserLink
.addArgument("-n", "--name")
775 .help("Specify a name to describe this new device.");
777 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
778 parserAddDevice
.addArgument("--uri")
780 .help("Specify the uri contained in the QR code shown by the new device.");
782 Subparser parserDevices
= subparsers
.addParser("listDevices");
784 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
785 parserRemoveDevice
.addArgument("-d", "--deviceId")
788 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
790 Subparser parserRegister
= subparsers
.addParser("register");
791 parserRegister
.addArgument("-v", "--voice")
792 .help("The verification should be done over voice, not sms.")
793 .action(Arguments
.storeTrue());
795 Subparser parserUnregister
= subparsers
.addParser("unregister");
796 parserUnregister
.help("Unregister the current device from the signal server.");
798 Subparser parserUpdateAccount
= subparsers
.addParser("updateAccount");
799 parserUpdateAccount
.help("Update the account attributes on the signal server.");
801 Subparser parserSetPin
= subparsers
.addParser("setPin");
802 parserSetPin
.addArgument("registrationLockPin")
803 .help("The registration lock PIN, that will be required for new registrations (resets after 7 days of inactivity)");
805 Subparser parserRemovePin
= subparsers
.addParser("removePin");
807 Subparser parserVerify
= subparsers
.addParser("verify");
808 parserVerify
.addArgument("verificationCode")
809 .help("The verification code you received via sms or voice call.");
810 parserVerify
.addArgument("-p", "--pin")
811 .help("The registration lock PIN, that was set by the user (Optional)");
813 Subparser parserSend
= subparsers
.addParser("send");
814 parserSend
.addArgument("-g", "--group")
815 .help("Specify the recipient group ID.");
816 parserSend
.addArgument("recipient")
817 .help("Specify the recipients' phone number.")
819 parserSend
.addArgument("-m", "--message")
820 .help("Specify the message, if missing standard input is used.");
821 parserSend
.addArgument("-a", "--attachment")
823 .help("Add file as attachment");
824 parserSend
.addArgument("-e", "--endsession")
825 .help("Clear session state and send end session message.")
826 .action(Arguments
.storeTrue());
828 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
829 parserLeaveGroup
.addArgument("-g", "--group")
831 .help("Specify the recipient group ID.");
833 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
834 parserUpdateGroup
.addArgument("-g", "--group")
835 .help("Specify the recipient group ID.");
836 parserUpdateGroup
.addArgument("-n", "--name")
837 .help("Specify the new group name.");
838 parserUpdateGroup
.addArgument("-a", "--avatar")
839 .help("Specify a new group avatar image file");
840 parserUpdateGroup
.addArgument("-m", "--member")
842 .help("Specify one or more members to add to the group");
844 Subparser parserListGroups
= subparsers
.addParser("listGroups");
845 parserListGroups
.addArgument("-d", "--detailed").action(Arguments
.storeTrue())
846 .help("List members of each group");
847 parserListGroups
.help("List group name and ids");
849 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
850 parserListIdentities
.addArgument("-n", "--number")
851 .help("Only show identity keys for the given phone number.");
853 Subparser parserTrust
= subparsers
.addParser("trust");
854 parserTrust
.addArgument("number")
855 .help("Specify the phone number, for which to set the trust.")
857 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
858 mutTrust
.addArgument("-a", "--trust-all-known-keys")
859 .help("Trust all known keys of this user, only use this for testing.")
860 .action(Arguments
.storeTrue());
861 mutTrust
.addArgument("-v", "--verified-fingerprint")
862 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
864 Subparser parserReceive
= subparsers
.addParser("receive");
865 parserReceive
.addArgument("-t", "--timeout")
867 .help("Number of seconds to wait for new messages (negative values disable timeout)");
868 parserReceive
.addArgument("--ignore-attachments")
869 .help("Don’t download attachments of received messages.")
870 .action(Arguments
.storeTrue());
871 parserReceive
.addArgument("--json")
872 .help("Output received messages in json format, one json object per line.")
873 .action(Arguments
.storeTrue());
875 Subparser parserDaemon
= subparsers
.addParser("daemon");
876 parserDaemon
.addArgument("--system")
877 .action(Arguments
.storeTrue())
878 .help("Use DBus system bus instead of user bus.");
879 parserDaemon
.addArgument("--ignore-attachments")
880 .help("Don’t download attachments of received messages.")
881 .action(Arguments
.storeTrue());
882 parserDaemon
.addArgument("--json")
883 .help("Output received messages in json format, one json object per line.")
884 .action(Arguments
.storeTrue());
887 Namespace ns
= parser
.parseArgs(args
);
888 if ("link".equals(ns
.getString("command"))) {
889 if (ns
.getString("username") != null) {
891 System
.err
.println("You cannot specify a username (phone number) when linking");
894 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
895 if (ns
.getString("username") == null) {
897 System
.err
.println("You need to specify a username (phone number)");
900 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
901 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
905 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
906 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
910 } catch (ArgumentParserException e
) {
911 parser
.handleError(e
);
916 private static void handleAssertionError(AssertionError e
) {
917 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
919 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
922 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
923 System
.err
.println("Failed to send (some) messages:");
924 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
925 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
927 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
928 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
930 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
931 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
935 private static void handleIOException(IOException e
) {
936 System
.err
.println("Failed to send message: " + e
.getMessage());
939 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
943 ReceiveMessageHandler(Manager m
) {
948 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
949 SignalServiceAddress source
= envelope
.getSourceAddress();
950 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
951 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
952 if (source
.getRelay().isPresent()) {
953 System
.out
.println("Relayed by: " + source
.getRelay().get());
955 System
.out
.println("Timestamp: " + DateUtils
.formatTimestamp(envelope
.getTimestamp()));
956 if (envelope
.isUnidentifiedSender()) {
957 System
.out
.println("Sent by unidentified/sealed sender");
960 if (envelope
.isReceipt()) {
961 System
.out
.println("Got receipt.");
962 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
963 if (exception
!= null) {
964 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
965 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
966 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
967 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");
968 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");
970 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
973 if (content
== null) {
974 System
.out
.println("Failed to decrypt message.");
976 if (content
.getDataMessage().isPresent()) {
977 SignalServiceDataMessage message
= content
.getDataMessage().get();
978 handleSignalServiceDataMessage(message
);
980 if (content
.getSyncMessage().isPresent()) {
981 System
.out
.println("Received a sync message");
982 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
984 if (syncMessage
.getContacts().isPresent()) {
985 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
986 if (contactsMessage
.isComplete()) {
987 System
.out
.println("Received complete sync contacts");
989 System
.out
.println("Received sync contacts");
991 printAttachment(contactsMessage
.getContactsStream());
993 if (syncMessage
.getGroups().isPresent()) {
994 System
.out
.println("Received sync groups");
995 printAttachment(syncMessage
.getGroups().get());
997 if (syncMessage
.getRead().isPresent()) {
998 System
.out
.println("Received sync read messages list");
999 for (ReadMessage rm
: syncMessage
.getRead().get()) {
1000 ContactInfo fromContact
= m
.getContact(rm
.getSender());
1001 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + DateUtils
.formatTimestamp(rm
.getTimestamp()));
1004 if (syncMessage
.getRequest().isPresent()) {
1005 System
.out
.println("Received sync request");
1006 if (syncMessage
.getRequest().get().isContactsRequest()) {
1007 System
.out
.println(" - contacts request");
1009 if (syncMessage
.getRequest().get().isGroupsRequest()) {
1010 System
.out
.println(" - groups request");
1013 if (syncMessage
.getSent().isPresent()) {
1014 System
.out
.println("Received sync sent message");
1015 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
1017 if (sentTranscriptMessage
.getDestination().isPresent()) {
1018 String dest
= sentTranscriptMessage
.getDestination().get();
1019 ContactInfo destContact
= m
.getContact(dest
);
1020 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
1024 System
.out
.println("To: " + to + " , Message timestamp: " + DateUtils
.formatTimestamp(sentTranscriptMessage
.getTimestamp()));
1025 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
1026 System
.out
.println("Expiration started at: " + DateUtils
.formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
1028 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
1029 handleSignalServiceDataMessage(message
);
1031 if (syncMessage
.getBlockedList().isPresent()) {
1032 System
.out
.println("Received sync message with block list");
1033 System
.out
.println("Blocked numbers:");
1034 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
1035 for (String number
: blockedList
.getNumbers()) {
1036 System
.out
.println(" - " + number
);
1039 if (syncMessage
.getVerified().isPresent()) {
1040 System
.out
.println("Received sync message with verified identities:");
1041 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1042 System
.out
.println(" - " + verifiedMessage
.getDestination() + ": " + verifiedMessage
.getVerified());
1043 String safetyNumber
= Util
.formatSafetyNumber(m
.computeSafetyNumber(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey()));
1044 System
.out
.println(" " + safetyNumber
);
1046 if (syncMessage
.getConfiguration().isPresent()) {
1047 System
.out
.println("Received sync message with configuration:");
1048 final ConfigurationMessage configurationMessage
= syncMessage
.getConfiguration().get();
1049 if (configurationMessage
.getReadReceipts().isPresent()) {
1050 System
.out
.println(" - Read receipts: " + (configurationMessage
.getReadReceipts().get() ?
"enabled" : "disabled"));
1054 if (content
.getCallMessage().isPresent()) {
1055 System
.out
.println("Received a call message");
1056 SignalServiceCallMessage callMessage
= content
.getCallMessage().get();
1057 if (callMessage
.getAnswerMessage().isPresent()) {
1058 AnswerMessage answerMessage
= callMessage
.getAnswerMessage().get();
1059 System
.out
.println("Answer message: " + answerMessage
.getId() + ": " + answerMessage
.getDescription());
1061 if (callMessage
.getBusyMessage().isPresent()) {
1062 BusyMessage busyMessage
= callMessage
.getBusyMessage().get();
1063 System
.out
.println("Busy message: " + busyMessage
.getId());
1065 if (callMessage
.getHangupMessage().isPresent()) {
1066 HangupMessage hangupMessage
= callMessage
.getHangupMessage().get();
1067 System
.out
.println("Hangup message: " + hangupMessage
.getId());
1069 if (callMessage
.getIceUpdateMessages().isPresent()) {
1070 List
<IceUpdateMessage
> iceUpdateMessages
= callMessage
.getIceUpdateMessages().get();
1071 for (IceUpdateMessage iceUpdateMessage
: iceUpdateMessages
) {
1072 System
.out
.println("Ice update message: " + iceUpdateMessage
.getId() + ", sdp: " + iceUpdateMessage
.getSdp());
1075 if (callMessage
.getOfferMessage().isPresent()) {
1076 OfferMessage offerMessage
= callMessage
.getOfferMessage().get();
1077 System
.out
.println("Offer message: " + offerMessage
.getId() + ": " + offerMessage
.getDescription());
1080 if (content
.getReceiptMessage().isPresent()) {
1081 System
.out
.println("Received a receipt message");
1082 SignalServiceReceiptMessage receiptMessage
= content
.getReceiptMessage().get();
1083 System
.out
.println(" - When: " + DateUtils
.formatTimestamp(receiptMessage
.getWhen()));
1084 if (receiptMessage
.isDeliveryReceipt()) {
1085 System
.out
.println(" - Is delivery receipt");
1087 if (receiptMessage
.isReadReceipt()) {
1088 System
.out
.println(" - Is read receipt");
1090 System
.out
.println(" - Timestamps:");
1091 for (long timestamp
: receiptMessage
.getTimestamps()) {
1092 System
.out
.println(" " + DateUtils
.formatTimestamp(timestamp
));
1095 if (content
.getTypingMessage().isPresent()) {
1096 System
.out
.println("Received a typing message");
1097 SignalServiceTypingMessage typingMessage
= content
.getTypingMessage().get();
1098 System
.out
.println(" - Action: " + typingMessage
.getAction());
1099 System
.out
.println(" - Timestamp: " + DateUtils
.formatTimestamp(typingMessage
.getTimestamp()));
1100 if (typingMessage
.getGroupId().isPresent()) {
1101 GroupInfo group
= m
.getGroup(typingMessage
.getGroupId().get());
1102 if (group
!= null) {
1103 System
.out
.println(" Name: " + group
.name
);
1105 System
.out
.println(" Name: <Unknown group>");
1111 System
.out
.println("Unknown message received.");
1113 System
.out
.println();
1116 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
1117 System
.out
.println("Message timestamp: " + DateUtils
.formatTimestamp(message
.getTimestamp()));
1119 if (message
.getBody().isPresent()) {
1120 System
.out
.println("Body: " + message
.getBody().get());
1122 if (message
.getGroupInfo().isPresent()) {
1123 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1124 System
.out
.println("Group info:");
1125 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
1126 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
1127 System
.out
.println(" Name: " + groupInfo
.getName().get());
1129 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
1130 if (group
!= null) {
1131 System
.out
.println(" Name: " + group
.name
);
1133 System
.out
.println(" Name: <Unknown group>");
1136 System
.out
.println(" Type: " + groupInfo
.getType());
1137 if (groupInfo
.getMembers().isPresent()) {
1138 for (String member
: groupInfo
.getMembers().get()) {
1139 System
.out
.println(" Member: " + member
);
1142 if (groupInfo
.getAvatar().isPresent()) {
1143 System
.out
.println(" Avatar:");
1144 printAttachment(groupInfo
.getAvatar().get());
1147 if (message
.isEndSession()) {
1148 System
.out
.println("Is end session");
1150 if (message
.isExpirationUpdate()) {
1151 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
1153 if (message
.getExpiresInSeconds() > 0) {
1154 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
1156 if (message
.getProfileKey().isPresent()) {
1157 System
.out
.println("Profile key update, key length:" + message
.getProfileKey().get().length
);
1160 if (message
.getQuote().isPresent()) {
1161 SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1162 System
.out
.println("Quote: (" + quote
.getId() + ")");
1163 System
.out
.println(" Author: " + quote
.getAuthor().getNumber());
1164 System
.out
.println(" Text: " + quote
.getText());
1165 if (quote
.getAttachments().size() > 0) {
1166 System
.out
.println(" Attachments: ");
1167 for (SignalServiceDataMessage
.Quote
.QuotedAttachment attachment
: quote
.getAttachments()) {
1168 System
.out
.println(" Filename: " + attachment
.getFileName());
1169 System
.out
.println(" Type: " + attachment
.getContentType());
1170 System
.out
.println(" Thumbnail:");
1171 if (attachment
.getThumbnail() != null) {
1172 printAttachment(attachment
.getThumbnail());
1178 if (message
.getAttachments().isPresent()) {
1179 System
.out
.println("Attachments: ");
1180 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1181 printAttachment(attachment
);
1186 private void printAttachment(SignalServiceAttachment attachment
) {
1187 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
1188 if (attachment
.isPointer()) {
1189 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1190 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
);
1191 System
.out
.println(" Filename: " + (pointer
.getFileName().isPresent() ? pointer
.getFileName().get() : "-"));
1192 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
1193 System
.out
.println(" Voice note: " + (pointer
.getVoiceNote() ?
"yes" : "no"));
1194 System
.out
.println(" Dimensions: " + pointer
.getWidth() + "x" + pointer
.getHeight());
1195 File file
= m
.getAttachmentFile(pointer
.getId());
1196 if (file
.exists()) {
1197 System
.out
.println(" Stored plaintext in: " + file
);
1203 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
1205 final DBusConnection conn
;
1207 DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1213 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1214 super.handleMessage(envelope
, content
, exception
);
1216 JsonDbusReceiveMessageHandler
.sendReceivedMessageToDbus(envelope
, content
, conn
, m
);
1220 private static class JsonReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
1223 final ObjectMapper jsonProcessor
;
1225 JsonReceiveMessageHandler(Manager m
) {
1227 this.jsonProcessor
= new ObjectMapper();
1228 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.ANY
); // disable autodetect
1229 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
1230 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
1231 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
1235 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1236 ObjectNode result
= jsonProcessor
.createObjectNode();
1237 if (exception
!= null) {
1238 result
.putPOJO("error", new JsonError(exception
));
1240 if (envelope
!= null) {
1241 result
.putPOJO("envelope", new JsonMessageEnvelope(envelope
, content
));
1244 jsonProcessor
.writeValue(System
.out
, result
);
1245 System
.out
.println();
1246 } catch (IOException e
) {
1247 e
.printStackTrace();
1252 private static class JsonDbusReceiveMessageHandler
extends JsonReceiveMessageHandler
{
1254 final DBusConnection conn
;
1256 JsonDbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1261 private static void sendReceivedMessageToDbus(SignalServiceEnvelope envelope
, SignalServiceContent content
, DBusConnection conn
, Manager m
) {
1262 if (envelope
.isReceipt()) {
1264 conn
.sendSignal(new Signal
.ReceiptReceived(
1266 envelope
.getTimestamp(),
1267 envelope
.getSource()
1269 } catch (DBusException e
) {
1270 e
.printStackTrace();
1272 } else if (content
!= null && content
.getDataMessage().isPresent()) {
1273 SignalServiceDataMessage message
= content
.getDataMessage().get();
1275 if (!message
.isEndSession() &&
1276 !(message
.getGroupInfo().isPresent() &&
1277 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
1278 List
<String
> attachments
= new ArrayList
<>();
1279 if (message
.getAttachments().isPresent()) {
1280 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1281 if (attachment
.isPointer()) {
1282 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
1288 conn
.sendSignal(new Signal
.MessageReceived(
1290 message
.getTimestamp(),
1291 envelope
.getSource(),
1292 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1293 message
.getBody().isPresent() ? message
.getBody().get() : "",
1295 } catch (DBusException e
) {
1296 e
.printStackTrace();
1303 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1304 super.handleMessage(envelope
, content
, exception
);
1306 sendReceivedMessageToDbus(envelope
, content
, conn
, m
);