2 * Copyright (C) 2015 AsamK
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
;
19 import 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
.storage
.contacts
.ContactInfo
;
32 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
33 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
34 import org
.asamk
.signal
.util
.DateUtils
;
35 import org
.asamk
.signal
.util
.Hex
;
36 import org
.asamk
.signal
.util
.IOUtils
;
37 import org
.asamk
.signal
.util
.Util
;
38 import org
.freedesktop
.dbus
.DBusConnection
;
39 import org
.freedesktop
.dbus
.DBusSigHandler
;
40 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
41 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
42 import org
.whispersystems
.libsignal
.InvalidKeyException
;
43 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
44 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
45 import org
.whispersystems
.signalservice
.api
.messages
.*;
46 import org
.whispersystems
.signalservice
.api
.messages
.calls
.*;
47 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
48 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
49 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
50 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
51 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
52 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
53 import org
.whispersystems
.signalservice
.internal
.push
.LockedException
;
54 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
57 import java
.io
.IOException
;
59 import java
.net
.URISyntaxException
;
60 import java
.nio
.charset
.Charset
;
61 import java
.security
.Security
;
62 import java
.util
.ArrayList
;
63 import java
.util
.List
;
64 import java
.util
.Locale
;
66 import java
.util
.concurrent
.TimeUnit
;
67 import java
.util
.concurrent
.TimeoutException
;
71 public static final String SIGNAL_BUSNAME
= "org.asamk.Signal";
72 public static final String SIGNAL_OBJECTPATH
= "/org/asamk/Signal";
74 public static void main(String
[] args
) {
75 // Workaround for BKS truststore
76 Security
.insertProviderAt(new org
.bouncycastle
.jce
.provider
.BouncyCastleProvider(), 1);
78 Namespace ns
= parseArgs(args
);
83 int res
= handleCommands(ns
);
87 private static int handleCommands(Namespace ns
) {
88 final String username
= ns
.getString("username");
91 DBusConnection dBusConn
= null;
93 if (ns
.getBoolean("dbus") || ns
.getBoolean("dbus_system")) {
97 if (ns
.getBoolean("dbus_system")) {
98 busType
= DBusConnection
.SYSTEM
;
100 busType
= DBusConnection
.SESSION
;
102 dBusConn
= DBusConnection
.getConnection(busType
);
103 ts
= dBusConn
.getRemoteObject(
104 SIGNAL_BUSNAME
, SIGNAL_OBJECTPATH
,
106 } catch (UnsatisfiedLinkError e
) {
107 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
109 } catch (DBusException e
) {
111 if (dBusConn
!= null) {
112 dBusConn
.disconnect();
117 String settingsPath
= ns
.getString("config");
118 if (TextUtils
.isEmpty(settingsPath
)) {
119 settingsPath
= System
.getProperty("user.home") + "/.config/signal";
120 if (!new File(settingsPath
).exists()) {
121 String legacySettingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
122 if (new File(legacySettingsPath
).exists()) {
123 settingsPath
= legacySettingsPath
;
128 m
= new Manager(username
, settingsPath
);
130 if (m
.userExists()) {
133 } catch (Exception e
) {
134 System
.err
.println("Error loading state file \"" + m
.getFileName() + "\": " + e
.getMessage());
140 switch (ns
.getString("command")) {
142 if (dBusConn
!= null) {
143 System
.err
.println("register is not yet implemented via dbus");
146 if (!m
.userHasKeys()) {
147 m
.createNewIdentity();
150 m
.register(ns
.getBoolean("voice"));
151 } catch (IOException e
) {
152 System
.err
.println("Request verify error: " + e
.getMessage());
157 if (dBusConn
!= null) {
158 System
.err
.println("unregister is not yet implemented via dbus");
161 if (!m
.isRegistered()) {
162 System
.err
.println("User is not registered.");
167 } catch (IOException e
) {
168 System
.err
.println("Unregister error: " + e
.getMessage());
172 case "updateAccount":
173 if (dBusConn
!= null) {
174 System
.err
.println("updateAccount is not yet implemented via dbus");
177 if (!m
.isRegistered()) {
178 System
.err
.println("User is not registered.");
182 m
.updateAccountAttributes();
183 } catch (IOException e
) {
184 System
.err
.println("UpdateAccount error: " + e
.getMessage());
189 if (dBusConn
!= null) {
190 System
.err
.println("setPin is not yet implemented via dbus");
193 if (!m
.isRegistered()) {
194 System
.err
.println("User is not registered.");
198 String registrationLockPin
= ns
.getString("registrationLockPin");
199 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
200 } catch (IOException e
) {
201 System
.err
.println("Set pin error: " + e
.getMessage());
206 if (dBusConn
!= null) {
207 System
.err
.println("removePin is not yet implemented via dbus");
210 if (!m
.isRegistered()) {
211 System
.err
.println("User is not registered.");
215 m
.setRegistrationLockPin(Optional
.<String
>absent());
216 } catch (IOException e
) {
217 System
.err
.println("Remove pin error: " + e
.getMessage());
222 if (dBusConn
!= null) {
223 System
.err
.println("verify is not yet implemented via dbus");
226 if (!m
.userHasKeys()) {
227 System
.err
.println("User has no keys, first call register.");
230 if (m
.isRegistered()) {
231 System
.err
.println("User registration is already verified");
235 String verificationCode
= ns
.getString("verificationCode");
236 String pin
= ns
.getString("pin");
237 m
.verifyAccount(verificationCode
, pin
);
238 } catch (LockedException e
) {
239 System
.err
.println("Verification failed! This number is locked with a pin. Hours remaining until reset: " + (e
.getTimeRemaining() / 1000 / 60 / 60));
240 System
.err
.println("Use '--pin PIN_CODE' to specify the registration lock PIN");
242 } catch (IOException e
) {
243 System
.err
.println("Verify error: " + e
.getMessage());
248 if (dBusConn
!= null) {
249 System
.err
.println("link is not yet implemented via dbus");
253 // When linking, username is null and we always have to create keys
254 m
.createNewIdentity();
256 String deviceName
= ns
.getString("name");
257 if (deviceName
== null) {
261 System
.out
.println(m
.getDeviceLinkUri());
262 m
.finishDeviceLink(deviceName
);
263 System
.out
.println("Associated with: " + m
.getUsername());
264 } catch (TimeoutException e
) {
265 System
.err
.println("Link request timed out, please try again.");
267 } catch (IOException e
) {
268 System
.err
.println("Link request error: " + e
.getMessage());
270 } catch (AssertionError e
) {
271 handleAssertionError(e
);
273 } catch (InvalidKeyException e
) {
276 } catch (UserAlreadyExists e
) {
277 System
.err
.println("The user " + e
.getUsername() + " already exists\nDelete \"" + e
.getFileName() + "\" before trying again.");
282 if (dBusConn
!= null) {
283 System
.err
.println("link is not yet implemented via dbus");
286 if (!m
.isRegistered()) {
287 System
.err
.println("User is not registered.");
291 m
.addDeviceLink(new URI(ns
.getString("uri")));
292 } catch (IOException e
) {
295 } catch (InvalidKeyException e
) {
298 } catch (AssertionError e
) {
299 handleAssertionError(e
);
301 } catch (URISyntaxException e
) {
307 if (dBusConn
!= null) {
308 System
.err
.println("listDevices is not yet implemented via dbus");
311 if (!m
.isRegistered()) {
312 System
.err
.println("User is not registered.");
316 List
<DeviceInfo
> devices
= m
.getLinkedDevices();
317 for (DeviceInfo d
: devices
) {
318 System
.out
.println("Device " + d
.getId() + (d
.getId() == m
.getDeviceId() ?
" (this device)" : "") + ":");
319 System
.out
.println(" Name: " + d
.getName());
320 System
.out
.println(" Created: " + DateUtils
.formatTimestamp(d
.getCreated()));
321 System
.out
.println(" Last seen: " + DateUtils
.formatTimestamp(d
.getLastSeen()));
323 } catch (IOException e
) {
329 if (dBusConn
!= null) {
330 System
.err
.println("removeDevice is not yet implemented via dbus");
333 if (!m
.isRegistered()) {
334 System
.err
.println("User is not registered.");
338 int deviceId
= ns
.getInt("deviceId");
339 m
.removeLinkedDevices(deviceId
);
340 } catch (IOException e
) {
346 if (dBusConn
== null && !m
.isRegistered()) {
347 System
.err
.println("User is not registered.");
351 if (ns
.getBoolean("endsession")) {
352 if (ns
.getList("recipient") == null) {
353 System
.err
.println("No recipients given");
354 System
.err
.println("Aborting sending.");
358 ts
.sendEndSessionMessage(ns
.<String
>getList("recipient"));
359 } catch (IOException e
) {
360 handleIOException(e
);
362 } catch (EncapsulatedExceptions e
) {
363 handleEncapsulatedExceptions(e
);
365 } catch (AssertionError e
) {
366 handleAssertionError(e
);
368 } catch (DBusExecutionException e
) {
369 handleDBusExecutionException(e
);
373 String messageText
= ns
.getString("message");
374 if (messageText
== null) {
376 messageText
= IOUtils
.readAll(System
.in, Charset
.defaultCharset());
377 } catch (IOException e
) {
378 System
.err
.println("Failed to read message from stdin: " + e
.getMessage());
379 System
.err
.println("Aborting sending.");
385 List
<String
> attachments
= ns
.getList("attachment");
386 if (attachments
== null) {
387 attachments
= new ArrayList
<>();
389 if (ns
.getString("group") != null) {
390 byte[] groupId
= decodeGroupId(ns
.getString("group"));
391 ts
.sendGroupMessage(messageText
, attachments
, groupId
);
393 ts
.sendMessage(messageText
, attachments
, ns
.<String
>getList("recipient"));
395 } catch (IOException e
) {
396 handleIOException(e
);
398 } catch (EncapsulatedExceptions e
) {
399 handleEncapsulatedExceptions(e
);
401 } catch (AssertionError e
) {
402 handleAssertionError(e
);
404 } catch (GroupNotFoundException e
) {
405 handleGroupNotFoundException(e
);
407 } catch (NotAGroupMemberException e
) {
408 handleNotAGroupMemberException(e
);
410 } catch (AttachmentInvalidException e
) {
411 System
.err
.println("Failed to add attachment: " + e
.getMessage());
412 System
.err
.println("Aborting sending.");
414 } catch (DBusExecutionException e
) {
415 handleDBusExecutionException(e
);
422 if (dBusConn
!= null) {
424 dBusConn
.addSigHandler(Signal
.MessageReceived
.class, new DBusSigHandler
<Signal
.MessageReceived
>() {
426 public void handle(Signal
.MessageReceived s
) {
427 System
.out
.print(String
.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
428 s
.getSender(), DateUtils
.formatTimestamp(s
.getTimestamp()), s
.getMessage()));
429 if (s
.getGroupId().length
> 0) {
430 System
.out
.println("Group info:");
431 System
.out
.println(" Id: " + Base64
.encodeBytes(s
.getGroupId()));
433 if (s
.getAttachments().size() > 0) {
434 System
.out
.println("Attachments: ");
435 for (String attachment
: s
.getAttachments()) {
436 System
.out
.println("- Stored plaintext in: " + attachment
);
439 System
.out
.println();
442 dBusConn
.addSigHandler(Signal
.ReceiptReceived
.class, new DBusSigHandler
<Signal
.ReceiptReceived
>() {
444 public void handle(Signal
.ReceiptReceived s
) {
445 System
.out
.print(String
.format("Receipt from: %s\nTimestamp: %s\n",
446 s
.getSender(), DateUtils
.formatTimestamp(s
.getTimestamp())));
449 } catch (UnsatisfiedLinkError e
) {
450 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
452 } catch (DBusException e
) {
459 } catch (InterruptedException e
) {
464 if (!m
.isRegistered()) {
465 System
.err
.println("User is not registered.");
469 if (ns
.getDouble("timeout") != null) {
470 timeout
= ns
.getDouble("timeout");
472 boolean returnOnTimeout
= true;
474 returnOnTimeout
= false;
477 boolean ignoreAttachments
= ns
.getBoolean("ignore_attachments");
479 final Manager
.ReceiveMessageHandler handler
= ns
.getBoolean("json") ?
new JsonReceiveMessageHandler(m
) : new ReceiveMessageHandler(m
);
480 m
.receiveMessages((long) (timeout
* 1000), TimeUnit
.MILLISECONDS
, returnOnTimeout
, ignoreAttachments
, handler
);
481 } catch (IOException e
) {
482 System
.err
.println("Error while receiving messages: " + e
.getMessage());
484 } catch (AssertionError e
) {
485 handleAssertionError(e
);
490 if (dBusConn
!= null) {
491 System
.err
.println("quitGroup is not yet implemented via dbus");
494 if (!m
.isRegistered()) {
495 System
.err
.println("User is not registered.");
500 m
.sendQuitGroupMessage(decodeGroupId(ns
.getString("group")));
501 } catch (IOException e
) {
502 handleIOException(e
);
504 } catch (EncapsulatedExceptions e
) {
505 handleEncapsulatedExceptions(e
);
507 } catch (AssertionError e
) {
508 handleAssertionError(e
);
510 } catch (GroupNotFoundException e
) {
511 handleGroupNotFoundException(e
);
513 } catch (NotAGroupMemberException e
) {
514 handleNotAGroupMemberException(e
);
520 if (dBusConn
== null && !m
.isRegistered()) {
521 System
.err
.println("User is not registered.");
526 byte[] groupId
= null;
527 if (ns
.getString("group") != null) {
528 groupId
= decodeGroupId(ns
.getString("group"));
530 if (groupId
== null) {
531 groupId
= new byte[0];
533 String groupName
= ns
.getString("name");
534 if (groupName
== null) {
537 List
<String
> groupMembers
= ns
.<String
>getList("member");
538 if (groupMembers
== null) {
539 groupMembers
= new ArrayList
<String
>();
541 String groupAvatar
= ns
.getString("avatar");
542 if (groupAvatar
== null) {
545 byte[] newGroupId
= ts
.updateGroup(groupId
, groupName
, groupMembers
, groupAvatar
);
546 if (groupId
.length
!= newGroupId
.length
) {
547 System
.out
.println("Creating new group \"" + Base64
.encodeBytes(newGroupId
) + "\" …");
549 } catch (IOException e
) {
550 handleIOException(e
);
552 } catch (AttachmentInvalidException e
) {
553 System
.err
.println("Failed to add avatar attachment for group\": " + e
.getMessage());
554 System
.err
.println("Aborting sending.");
556 } catch (GroupNotFoundException e
) {
557 handleGroupNotFoundException(e
);
559 } catch (NotAGroupMemberException e
) {
560 handleNotAGroupMemberException(e
);
562 } catch (EncapsulatedExceptions e
) {
563 handleEncapsulatedExceptions(e
);
569 if (dBusConn
!= null) {
570 System
.err
.println("listGroups is not yet implemented via dbus");
573 if (!m
.isRegistered()) {
574 System
.err
.println("User is not registered.");
578 List
<GroupInfo
> groups
= m
.getGroups();
579 boolean detailed
= ns
.getBoolean("detailed");
581 for (GroupInfo group
: groups
) {
582 printGroup(group
, detailed
);
585 case "listIdentities":
586 if (dBusConn
!= null) {
587 System
.err
.println("listIdentities is not yet implemented via dbus");
590 if (!m
.isRegistered()) {
591 System
.err
.println("User is not registered.");
594 if (ns
.get("number") == null) {
595 for (Map
.Entry
<String
, List
<JsonIdentityKeyStore
.Identity
>> keys
: m
.getIdentities().entrySet()) {
596 for (JsonIdentityKeyStore
.Identity id
: keys
.getValue()) {
597 printIdentityFingerprint(m
, keys
.getKey(), id
);
601 String number
= ns
.getString("number");
602 for (JsonIdentityKeyStore
.Identity id
: m
.getIdentities(number
)) {
603 printIdentityFingerprint(m
, number
, id
);
608 if (dBusConn
!= null) {
609 System
.err
.println("trust is not yet implemented via dbus");
612 if (!m
.isRegistered()) {
613 System
.err
.println("User is not registered.");
616 String number
= ns
.getString("number");
617 if (ns
.getBoolean("trust_all_known_keys")) {
618 boolean res
= m
.trustIdentityAllKeys(number
);
620 System
.err
.println("Failed to set the trust for this number, make sure the number is correct.");
624 String fingerprint
= ns
.getString("verified_fingerprint");
625 if (fingerprint
!= null) {
626 fingerprint
= fingerprint
.replaceAll(" ", "");
627 if (fingerprint
.length() == 66) {
628 byte[] fingerprintBytes
;
630 fingerprintBytes
= Hex
.toByteArray(fingerprint
.toLowerCase(Locale
.ROOT
));
631 } catch (Exception e
) {
632 System
.err
.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
635 boolean res
= m
.trustIdentityVerified(number
, fingerprintBytes
);
637 System
.err
.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
640 } else if (fingerprint
.length() == 60) {
641 boolean res
= m
.trustIdentityVerifiedSafetyNumber(number
, fingerprint
);
643 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.");
647 System
.err
.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
651 System
.err
.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
657 if (dBusConn
!= null) {
658 System
.err
.println("Stop it.");
661 if (!m
.isRegistered()) {
662 System
.err
.println("User is not registered.");
665 DBusConnection conn
= null;
669 if (ns
.getBoolean("system")) {
670 busType
= DBusConnection
.SYSTEM
;
672 busType
= DBusConnection
.SESSION
;
674 conn
= DBusConnection
.getConnection(busType
);
675 conn
.exportObject(SIGNAL_OBJECTPATH
, m
);
676 conn
.requestBusName(SIGNAL_BUSNAME
);
677 } catch (UnsatisfiedLinkError e
) {
678 System
.err
.println("Missing native library dependency for dbus service: " + e
.getMessage());
680 } catch (DBusException e
) {
684 ignoreAttachments
= ns
.getBoolean("ignore_attachments");
686 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, ns
.getBoolean("json") ?
new JsonDbusReceiveMessageHandler(m
, conn
) : new DbusReceiveMessageHandler(m
, conn
));
687 } catch (IOException e
) {
688 System
.err
.println("Error while receiving messages: " + e
.getMessage());
690 } catch (AssertionError e
) {
691 handleAssertionError(e
);
704 if (dBusConn
!= null) {
705 dBusConn
.disconnect();
710 private static void printIdentityFingerprint(Manager m
, String theirUsername
, JsonIdentityKeyStore
.Identity theirId
) {
711 String digits
= Util
.formatSafetyNumber(m
.computeSafetyNumber(theirUsername
, theirId
.getIdentityKey()));
712 System
.out
.println(String
.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername
,
713 theirId
.getTrustLevel(), theirId
.getDateAdded(), Hex
.toStringCondensed(theirId
.getFingerprint()), digits
));
716 private static void printGroup(GroupInfo group
, boolean detailed
) {
718 System
.out
.println(String
.format("Id: %s Name: %s Active: %s Members: %s",
719 Base64
.encodeBytes(group
.groupId
), group
.name
, group
.active
, group
.members
));
721 System
.out
.println(String
.format("Id: %s Name: %s Active: %s", Base64
.encodeBytes(group
.groupId
),
722 group
.name
, group
.active
));
726 private static void handleGroupNotFoundException(GroupNotFoundException e
) {
727 System
.err
.println("Failed to send to group: " + e
.getMessage());
728 System
.err
.println("Aborting sending.");
731 private static void handleNotAGroupMemberException(NotAGroupMemberException e
) {
732 System
.err
.println("Failed to send to group: " + e
.getMessage());
733 System
.err
.println("Update the group on another device to readd the user to this group.");
734 System
.err
.println("Aborting sending.");
738 private static void handleDBusExecutionException(DBusExecutionException e
) {
739 System
.err
.println("Cannot connect to dbus: " + e
.getMessage());
740 System
.err
.println("Aborting.");
743 private static byte[] decodeGroupId(String groupId
) {
745 return Base64
.decode(groupId
);
746 } catch (IOException e
) {
747 System
.err
.println("Failed to decode groupId (must be base64) \"" + groupId
+ "\": " + e
.getMessage());
748 System
.err
.println("Aborting sending.");
754 private static Namespace
parseArgs(String
[] args
) {
755 ArgumentParser parser
= ArgumentParsers
.newFor("signal-cli")
758 .description("Commandline interface for Signal.")
759 .version(Manager
.PROJECT_NAME
+ " " + Manager
.PROJECT_VERSION
);
761 parser
.addArgument("-v", "--version")
762 .help("Show package version.")
763 .action(Arguments
.version());
764 parser
.addArgument("--config")
765 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
767 MutuallyExclusiveGroup mut
= parser
.addMutuallyExclusiveGroup();
768 mut
.addArgument("-u", "--username")
769 .help("Specify your phone number, that will be used for verification.");
770 mut
.addArgument("--dbus")
771 .help("Make request via user dbus.")
772 .action(Arguments
.storeTrue());
773 mut
.addArgument("--dbus-system")
774 .help("Make request via system dbus.")
775 .action(Arguments
.storeTrue());
777 Subparsers subparsers
= parser
.addSubparsers()
778 .title("subcommands")
780 .description("valid subcommands")
781 .help("additional help");
783 Subparser parserLink
= subparsers
.addParser("link");
784 parserLink
.addArgument("-n", "--name")
785 .help("Specify a name to describe this new device.");
787 Subparser parserAddDevice
= subparsers
.addParser("addDevice");
788 parserAddDevice
.addArgument("--uri")
790 .help("Specify the uri contained in the QR code shown by the new device.");
792 Subparser parserDevices
= subparsers
.addParser("listDevices");
794 Subparser parserRemoveDevice
= subparsers
.addParser("removeDevice");
795 parserRemoveDevice
.addArgument("-d", "--deviceId")
798 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
800 Subparser parserRegister
= subparsers
.addParser("register");
801 parserRegister
.addArgument("-v", "--voice")
802 .help("The verification should be done over voice, not sms.")
803 .action(Arguments
.storeTrue());
805 Subparser parserUnregister
= subparsers
.addParser("unregister");
806 parserUnregister
.help("Unregister the current device from the signal server.");
808 Subparser parserUpdateAccount
= subparsers
.addParser("updateAccount");
809 parserUpdateAccount
.help("Update the account attributes on the signal server.");
811 Subparser parserSetPin
= subparsers
.addParser("setPin");
812 parserSetPin
.addArgument("registrationLockPin")
813 .help("The registration lock PIN, that will be required for new registrations (resets after 7 days of inactivity)");
815 Subparser parserRemovePin
= subparsers
.addParser("removePin");
817 Subparser parserVerify
= subparsers
.addParser("verify");
818 parserVerify
.addArgument("verificationCode")
819 .help("The verification code you received via sms or voice call.");
820 parserVerify
.addArgument("-p", "--pin")
821 .help("The registration lock PIN, that was set by the user (Optional)");
823 Subparser parserSend
= subparsers
.addParser("send");
824 parserSend
.addArgument("-g", "--group")
825 .help("Specify the recipient group ID.");
826 parserSend
.addArgument("recipient")
827 .help("Specify the recipients' phone number.")
829 parserSend
.addArgument("-m", "--message")
830 .help("Specify the message, if missing standard input is used.");
831 parserSend
.addArgument("-a", "--attachment")
833 .help("Add file as attachment");
834 parserSend
.addArgument("-e", "--endsession")
835 .help("Clear session state and send end session message.")
836 .action(Arguments
.storeTrue());
838 Subparser parserLeaveGroup
= subparsers
.addParser("quitGroup");
839 parserLeaveGroup
.addArgument("-g", "--group")
841 .help("Specify the recipient group ID.");
843 Subparser parserUpdateGroup
= subparsers
.addParser("updateGroup");
844 parserUpdateGroup
.addArgument("-g", "--group")
845 .help("Specify the recipient group ID.");
846 parserUpdateGroup
.addArgument("-n", "--name")
847 .help("Specify the new group name.");
848 parserUpdateGroup
.addArgument("-a", "--avatar")
849 .help("Specify a new group avatar image file");
850 parserUpdateGroup
.addArgument("-m", "--member")
852 .help("Specify one or more members to add to the group");
854 Subparser parserListGroups
= subparsers
.addParser("listGroups");
855 parserListGroups
.addArgument("-d", "--detailed").action(Arguments
.storeTrue())
856 .help("List members of each group");
857 parserListGroups
.help("List group name and ids");
859 Subparser parserListIdentities
= subparsers
.addParser("listIdentities");
860 parserListIdentities
.addArgument("-n", "--number")
861 .help("Only show identity keys for the given phone number.");
863 Subparser parserTrust
= subparsers
.addParser("trust");
864 parserTrust
.addArgument("number")
865 .help("Specify the phone number, for which to set the trust.")
867 MutuallyExclusiveGroup mutTrust
= parserTrust
.addMutuallyExclusiveGroup();
868 mutTrust
.addArgument("-a", "--trust-all-known-keys")
869 .help("Trust all known keys of this user, only use this for testing.")
870 .action(Arguments
.storeTrue());
871 mutTrust
.addArgument("-v", "--verified-fingerprint")
872 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
874 Subparser parserReceive
= subparsers
.addParser("receive");
875 parserReceive
.addArgument("-t", "--timeout")
877 .help("Number of seconds to wait for new messages (negative values disable timeout)");
878 parserReceive
.addArgument("--ignore-attachments")
879 .help("Don’t download attachments of received messages.")
880 .action(Arguments
.storeTrue());
881 parserReceive
.addArgument("--json")
882 .help("Output received messages in json format, one json object per line.")
883 .action(Arguments
.storeTrue());
885 Subparser parserDaemon
= subparsers
.addParser("daemon");
886 parserDaemon
.addArgument("--system")
887 .action(Arguments
.storeTrue())
888 .help("Use DBus system bus instead of user bus.");
889 parserDaemon
.addArgument("--ignore-attachments")
890 .help("Don’t download attachments of received messages.")
891 .action(Arguments
.storeTrue());
892 parserDaemon
.addArgument("--json")
893 .help("Output received messages in json format, one json object per line.")
894 .action(Arguments
.storeTrue());
897 Namespace ns
= parser
.parseArgs(args
);
898 if ("link".equals(ns
.getString("command"))) {
899 if (ns
.getString("username") != null) {
901 System
.err
.println("You cannot specify a username (phone number) when linking");
904 } else if (!ns
.getBoolean("dbus") && !ns
.getBoolean("dbus_system")) {
905 if (ns
.getString("username") == null) {
907 System
.err
.println("You need to specify a username (phone number)");
910 if (!PhoneNumberFormatter
.isValidNumber(ns
.getString("username"))) {
911 System
.err
.println("Invalid username (phone number), make sure you include the country code.");
915 if (ns
.getList("recipient") != null && !ns
.getList("recipient").isEmpty() && ns
.getString("group") != null) {
916 System
.err
.println("You cannot specify recipients by phone number and groups a the same time");
920 } catch (ArgumentParserException e
) {
921 parser
.handleError(e
);
926 private static void handleAssertionError(AssertionError e
) {
927 System
.err
.println("Failed to send/receive message (Assertion): " + e
.getMessage());
929 System
.err
.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
932 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e
) {
933 System
.err
.println("Failed to send (some) messages:");
934 for (NetworkFailureException n
: e
.getNetworkExceptions()) {
935 System
.err
.println("Network failure for \"" + n
.getE164number() + "\": " + n
.getMessage());
937 for (UnregisteredUserException n
: e
.getUnregisteredUserExceptions()) {
938 System
.err
.println("Unregistered user \"" + n
.getE164Number() + "\": " + n
.getMessage());
940 for (UntrustedIdentityException n
: e
.getUntrustedIdentityExceptions()) {
941 System
.err
.println("Untrusted Identity for \"" + n
.getE164Number() + "\": " + n
.getMessage());
945 private static void handleIOException(IOException e
) {
946 System
.err
.println("Failed to send message: " + e
.getMessage());
949 private static class ReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
952 public ReceiveMessageHandler(Manager m
) {
957 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
958 SignalServiceAddress source
= envelope
.getSourceAddress();
959 ContactInfo sourceContact
= m
.getContact(source
.getNumber());
960 System
.out
.println(String
.format("Envelope from: %s (device: %d)", (sourceContact
== null ?
"" : "“" + sourceContact
.name
+ "” ") + source
.getNumber(), envelope
.getSourceDevice()));
961 if (source
.getRelay().isPresent()) {
962 System
.out
.println("Relayed by: " + source
.getRelay().get());
964 System
.out
.println("Timestamp: " + DateUtils
.formatTimestamp(envelope
.getTimestamp()));
965 if (envelope
.isUnidentifiedSender()) {
966 System
.out
.println("Sent by unidentified/sealed sender");
969 if (envelope
.isReceipt()) {
970 System
.out
.println("Got receipt.");
971 } else if (envelope
.isSignalMessage() | envelope
.isPreKeySignalMessage()) {
972 if (exception
!= null) {
973 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
974 org
.whispersystems
.libsignal
.UntrustedIdentityException e
= (org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
;
975 System
.out
.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
976 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");
977 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");
979 System
.out
.println("Exception: " + exception
.getMessage() + " (" + exception
.getClass().getSimpleName() + ")");
982 if (content
== null) {
983 System
.out
.println("Failed to decrypt message.");
985 if (content
.getDataMessage().isPresent()) {
986 SignalServiceDataMessage message
= content
.getDataMessage().get();
987 handleSignalServiceDataMessage(message
);
989 if (content
.getSyncMessage().isPresent()) {
990 System
.out
.println("Received a sync message");
991 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
993 if (syncMessage
.getContacts().isPresent()) {
994 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
995 if (contactsMessage
.isComplete()) {
996 System
.out
.println("Received complete sync contacts");
998 System
.out
.println("Received sync contacts");
1000 printAttachment(contactsMessage
.getContactsStream());
1002 if (syncMessage
.getGroups().isPresent()) {
1003 System
.out
.println("Received sync groups");
1004 printAttachment(syncMessage
.getGroups().get());
1006 if (syncMessage
.getRead().isPresent()) {
1007 System
.out
.println("Received sync read messages list");
1008 for (ReadMessage rm
: syncMessage
.getRead().get()) {
1009 ContactInfo fromContact
= m
.getContact(rm
.getSender());
1010 System
.out
.println("From: " + (fromContact
== null ?
"" : "“" + fromContact
.name
+ "” ") + rm
.getSender() + " Message timestamp: " + DateUtils
.formatTimestamp(rm
.getTimestamp()));
1013 if (syncMessage
.getRequest().isPresent()) {
1014 System
.out
.println("Received sync request");
1015 if (syncMessage
.getRequest().get().isContactsRequest()) {
1016 System
.out
.println(" - contacts request");
1018 if (syncMessage
.getRequest().get().isGroupsRequest()) {
1019 System
.out
.println(" - groups request");
1022 if (syncMessage
.getSent().isPresent()) {
1023 System
.out
.println("Received sync sent message");
1024 final SentTranscriptMessage sentTranscriptMessage
= syncMessage
.getSent().get();
1026 if (sentTranscriptMessage
.getDestination().isPresent()) {
1027 String dest
= sentTranscriptMessage
.getDestination().get();
1028 ContactInfo destContact
= m
.getContact(dest
);
1029 to = (destContact
== null ?
"" : "“" + destContact
.name
+ "” ") + dest
;
1033 System
.out
.println("To: " + to + " , Message timestamp: " + DateUtils
.formatTimestamp(sentTranscriptMessage
.getTimestamp()));
1034 if (sentTranscriptMessage
.getExpirationStartTimestamp() > 0) {
1035 System
.out
.println("Expiration started at: " + DateUtils
.formatTimestamp(sentTranscriptMessage
.getExpirationStartTimestamp()));
1037 SignalServiceDataMessage message
= sentTranscriptMessage
.getMessage();
1038 handleSignalServiceDataMessage(message
);
1040 if (syncMessage
.getBlockedList().isPresent()) {
1041 System
.out
.println("Received sync message with block list");
1042 System
.out
.println("Blocked numbers:");
1043 final BlockedListMessage blockedList
= syncMessage
.getBlockedList().get();
1044 for (String number
: blockedList
.getNumbers()) {
1045 System
.out
.println(" - " + number
);
1048 if (syncMessage
.getVerified().isPresent()) {
1049 System
.out
.println("Received sync message with verified identities:");
1050 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1051 System
.out
.println(" - " + verifiedMessage
.getDestination() + ": " + verifiedMessage
.getVerified());
1052 String safetyNumber
= Util
.formatSafetyNumber(m
.computeSafetyNumber(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey()));
1053 System
.out
.println(" " + safetyNumber
);
1055 if (syncMessage
.getConfiguration().isPresent()) {
1056 System
.out
.println("Received sync message with configuration:");
1057 final ConfigurationMessage configurationMessage
= syncMessage
.getConfiguration().get();
1058 if (configurationMessage
.getReadReceipts().isPresent()) {
1059 System
.out
.println(" - Read receipts: " + (configurationMessage
.getReadReceipts().get() ?
"enabled" : "disabled"));
1063 if (content
.getCallMessage().isPresent()) {
1064 System
.out
.println("Received a call message");
1065 SignalServiceCallMessage callMessage
= content
.getCallMessage().get();
1066 if (callMessage
.getAnswerMessage().isPresent()) {
1067 AnswerMessage answerMessage
= callMessage
.getAnswerMessage().get();
1068 System
.out
.println("Answer message: " + answerMessage
.getId() + ": " + answerMessage
.getDescription());
1070 if (callMessage
.getBusyMessage().isPresent()) {
1071 BusyMessage busyMessage
= callMessage
.getBusyMessage().get();
1072 System
.out
.println("Busy message: " + busyMessage
.getId());
1074 if (callMessage
.getHangupMessage().isPresent()) {
1075 HangupMessage hangupMessage
= callMessage
.getHangupMessage().get();
1076 System
.out
.println("Hangup message: " + hangupMessage
.getId());
1078 if (callMessage
.getIceUpdateMessages().isPresent()) {
1079 List
<IceUpdateMessage
> iceUpdateMessages
= callMessage
.getIceUpdateMessages().get();
1080 for (IceUpdateMessage iceUpdateMessage
: iceUpdateMessages
) {
1081 System
.out
.println("Ice update message: " + iceUpdateMessage
.getId() + ", sdp: " + iceUpdateMessage
.getSdp());
1084 if (callMessage
.getOfferMessage().isPresent()) {
1085 OfferMessage offerMessage
= callMessage
.getOfferMessage().get();
1086 System
.out
.println("Offer message: " + offerMessage
.getId() + ": " + offerMessage
.getDescription());
1089 if (content
.getReceiptMessage().isPresent()) {
1090 System
.out
.println("Received a receipt message");
1091 SignalServiceReceiptMessage receiptMessage
= content
.getReceiptMessage().get();
1092 System
.out
.println(" - When: " + DateUtils
.formatTimestamp(receiptMessage
.getWhen()));
1093 if (receiptMessage
.isDeliveryReceipt()) {
1094 System
.out
.println(" - Is delivery receipt");
1096 if (receiptMessage
.isReadReceipt()) {
1097 System
.out
.println(" - Is read receipt");
1099 System
.out
.println(" - Timestamps:");
1100 for (long timestamp
: receiptMessage
.getTimestamps()) {
1101 System
.out
.println(" " + DateUtils
.formatTimestamp(timestamp
));
1104 if (content
.getTypingMessage().isPresent()) {
1105 System
.out
.println("Received a typing message");
1106 SignalServiceTypingMessage typingMessage
= content
.getTypingMessage().get();
1107 System
.out
.println(" - Action: " + typingMessage
.getAction());
1108 System
.out
.println(" - Timestamp: " + DateUtils
.formatTimestamp(typingMessage
.getTimestamp()));
1109 if (typingMessage
.getGroupId().isPresent()) {
1110 GroupInfo group
= m
.getGroup(typingMessage
.getGroupId().get());
1111 if (group
!= null) {
1112 System
.out
.println(" Name: " + group
.name
);
1114 System
.out
.println(" Name: <Unknown group>");
1120 System
.out
.println("Unknown message received.");
1122 System
.out
.println();
1125 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
) {
1126 System
.out
.println("Message timestamp: " + DateUtils
.formatTimestamp(message
.getTimestamp()));
1128 if (message
.getBody().isPresent()) {
1129 System
.out
.println("Body: " + message
.getBody().get());
1131 if (message
.getGroupInfo().isPresent()) {
1132 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1133 System
.out
.println("Group info:");
1134 System
.out
.println(" Id: " + Base64
.encodeBytes(groupInfo
.getGroupId()));
1135 if (groupInfo
.getType() == SignalServiceGroup
.Type
.UPDATE
&& groupInfo
.getName().isPresent()) {
1136 System
.out
.println(" Name: " + groupInfo
.getName().get());
1138 GroupInfo group
= m
.getGroup(groupInfo
.getGroupId());
1139 if (group
!= null) {
1140 System
.out
.println(" Name: " + group
.name
);
1142 System
.out
.println(" Name: <Unknown group>");
1145 System
.out
.println(" Type: " + groupInfo
.getType());
1146 if (groupInfo
.getMembers().isPresent()) {
1147 for (String member
: groupInfo
.getMembers().get()) {
1148 System
.out
.println(" Member: " + member
);
1151 if (groupInfo
.getAvatar().isPresent()) {
1152 System
.out
.println(" Avatar:");
1153 printAttachment(groupInfo
.getAvatar().get());
1156 if (message
.isEndSession()) {
1157 System
.out
.println("Is end session");
1159 if (message
.isExpirationUpdate()) {
1160 System
.out
.println("Is Expiration update: " + message
.isExpirationUpdate());
1162 if (message
.getExpiresInSeconds() > 0) {
1163 System
.out
.println("Expires in: " + message
.getExpiresInSeconds() + " seconds");
1165 if (message
.getProfileKey().isPresent()) {
1166 System
.out
.println("Profile key update, key length:" + message
.getProfileKey().get().length
);
1169 if (message
.getQuote().isPresent()) {
1170 SignalServiceDataMessage
.Quote quote
= message
.getQuote().get();
1171 System
.out
.println("Quote: (" + quote
.getId() + ")");
1172 System
.out
.println(" Author: " + quote
.getAuthor().getNumber());
1173 System
.out
.println(" Text: " + quote
.getText());
1174 if (quote
.getAttachments().size() > 0) {
1175 System
.out
.println(" Attachments: ");
1176 for (SignalServiceDataMessage
.Quote
.QuotedAttachment attachment
: quote
.getAttachments()) {
1177 System
.out
.println(" Filename: " + attachment
.getFileName());
1178 System
.out
.println(" Type: " + attachment
.getContentType());
1179 System
.out
.println(" Thumbnail:");
1180 if (attachment
.getThumbnail() != null) {
1181 printAttachment(attachment
.getThumbnail());
1187 if (message
.getAttachments().isPresent()) {
1188 System
.out
.println("Attachments: ");
1189 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1190 printAttachment(attachment
);
1195 private void printAttachment(SignalServiceAttachment attachment
) {
1196 System
.out
.println("- " + attachment
.getContentType() + " (" + (attachment
.isPointer() ?
"Pointer" : "") + (attachment
.isStream() ?
"Stream" : "") + ")");
1197 if (attachment
.isPointer()) {
1198 final SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1199 System
.out
.println(" Id: " + pointer
.getId() + " Key length: " + pointer
.getKey().length
);
1200 System
.out
.println(" Filename: " + (pointer
.getFileName().isPresent() ? pointer
.getFileName().get() : "-"));
1201 System
.out
.println(" Size: " + (pointer
.getSize().isPresent() ? pointer
.getSize().get() + " bytes" : "<unavailable>") + (pointer
.getPreview().isPresent() ?
" (Preview is available: " + pointer
.getPreview().get().length
+ " bytes)" : ""));
1202 System
.out
.println(" Voice note: " + (pointer
.getVoiceNote() ?
"yes" : "no"));
1203 System
.out
.println(" Dimensions: " + pointer
.getWidth() + "x" + pointer
.getHeight());
1204 File file
= m
.getAttachmentFile(pointer
.getId());
1205 if (file
.exists()) {
1206 System
.out
.println(" Stored plaintext in: " + file
);
1212 private static class DbusReceiveMessageHandler
extends ReceiveMessageHandler
{
1213 final DBusConnection conn
;
1215 public DbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1221 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1222 super.handleMessage(envelope
, content
, exception
);
1224 JsonDbusReceiveMessageHandler
.sendReceivedMessageToDbus(envelope
, content
, conn
, m
);
1228 private static class JsonReceiveMessageHandler
implements Manager
.ReceiveMessageHandler
{
1230 final ObjectMapper jsonProcessor
;
1232 public JsonReceiveMessageHandler(Manager m
) {
1234 this.jsonProcessor
= new ObjectMapper();
1235 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.ANY
); // disable autodetect
1236 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
1237 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
1238 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
1242 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1243 ObjectNode result
= jsonProcessor
.createObjectNode();
1244 if (exception
!= null) {
1245 result
.putPOJO("error", new JsonError(exception
));
1247 if (envelope
!= null) {
1248 result
.putPOJO("envelope", new JsonMessageEnvelope(envelope
, content
));
1251 jsonProcessor
.writeValue(System
.out
, result
);
1252 System
.out
.println();
1253 } catch (IOException e
) {
1254 e
.printStackTrace();
1259 private static class JsonDbusReceiveMessageHandler
extends JsonReceiveMessageHandler
{
1260 final DBusConnection conn
;
1262 public JsonDbusReceiveMessageHandler(Manager m
, DBusConnection conn
) {
1268 public void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, Throwable exception
) {
1269 super.handleMessage(envelope
, content
, exception
);
1271 sendReceivedMessageToDbus(envelope
, content
, conn
, m
);
1274 private static void sendReceivedMessageToDbus(SignalServiceEnvelope envelope
, SignalServiceContent content
, DBusConnection conn
, Manager m
) {
1275 if (envelope
.isReceipt()) {
1277 conn
.sendSignal(new Signal
.ReceiptReceived(
1279 envelope
.getTimestamp(),
1280 envelope
.getSource()
1282 } catch (DBusException e
) {
1283 e
.printStackTrace();
1285 } else if (content
!= null && content
.getDataMessage().isPresent()) {
1286 SignalServiceDataMessage message
= content
.getDataMessage().get();
1288 if (!message
.isEndSession() &&
1289 !(message
.getGroupInfo().isPresent() &&
1290 message
.getGroupInfo().get().getType() != SignalServiceGroup
.Type
.DELIVER
)) {
1291 List
<String
> attachments
= new ArrayList
<>();
1292 if (message
.getAttachments().isPresent()) {
1293 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1294 if (attachment
.isPointer()) {
1295 attachments
.add(m
.getAttachmentFile(attachment
.asPointer().getId()).getAbsolutePath());
1301 conn
.sendSignal(new Signal
.MessageReceived(
1303 message
.getTimestamp(),
1304 envelope
.getSource(),
1305 message
.getGroupInfo().isPresent() ? message
.getGroupInfo().get().getGroupId() : new byte[0],
1306 message
.getBody().isPresent() ? message
.getBody().get() : "",
1308 } catch (DBusException e
) {
1309 e
.printStackTrace();