1 package org
.asamk
.signal
;
3 import net
.sourceforge
.argparse4j
.ArgumentParsers
;
4 import net
.sourceforge
.argparse4j
.impl
.Arguments
;
5 import net
.sourceforge
.argparse4j
.inf
.ArgumentParser
;
6 import net
.sourceforge
.argparse4j
.inf
.Namespace
;
8 import org
.asamk
.Signal
;
9 import org
.asamk
.signal
.commands
.Command
;
10 import org
.asamk
.signal
.commands
.Commands
;
11 import org
.asamk
.signal
.commands
.DbusCommand
;
12 import org
.asamk
.signal
.commands
.ExtendedDbusCommand
;
13 import org
.asamk
.signal
.commands
.LocalCommand
;
14 import org
.asamk
.signal
.commands
.MultiLocalCommand
;
15 import org
.asamk
.signal
.commands
.ProvisioningCommand
;
16 import org
.asamk
.signal
.commands
.RegistrationCommand
;
17 import org
.asamk
.signal
.commands
.exceptions
.CommandException
;
18 import org
.asamk
.signal
.commands
.exceptions
.UnexpectedErrorException
;
19 import org
.asamk
.signal
.commands
.exceptions
.UserErrorException
;
20 import org
.asamk
.signal
.manager
.Manager
;
21 import org
.asamk
.signal
.manager
.NotRegisteredException
;
22 import org
.asamk
.signal
.manager
.ProvisioningManager
;
23 import org
.asamk
.signal
.manager
.RegistrationManager
;
24 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
25 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
26 import org
.asamk
.signal
.util
.IOUtils
;
27 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
28 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
29 import org
.slf4j
.Logger
;
30 import org
.slf4j
.LoggerFactory
;
31 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
34 import java
.io
.IOException
;
35 import java
.util
.ArrayList
;
36 import java
.util
.List
;
38 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
42 private final static Logger logger
= LoggerFactory
.getLogger(App
.class);
44 private final Namespace ns
;
46 static ArgumentParser
buildArgumentParser() {
47 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
48 .includeArgumentNamesAsKeysInResult(true)
51 .description("Commandline interface for Signal.")
52 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
54 parser
.addArgument("-v", "--version").help("Show package version.").action(Arguments
.version());
55 parser
.addArgument("--verbose")
56 .help("Raise log level and include lib signal logs.")
57 .action(Arguments
.storeTrue());
58 parser
.addArgument("--config")
59 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
61 parser
.addArgument("-u", "--username").help("Specify your phone number, that will be your identifier.");
63 var mut
= parser
.addMutuallyExclusiveGroup();
64 mut
.addArgument("--dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
65 mut
.addArgument("--dbus-system").help("Make request via system dbus.").action(Arguments
.storeTrue());
67 parser
.addArgument("-o", "--output")
68 .help("Choose to output in plain text or JSON")
69 .type(Arguments
.enumStringType(OutputType
.class))
70 .setDefault(OutputType
.PLAIN_TEXT
);
72 parser
.addArgument("--service-environment")
73 .help("Choose the server environment to use.")
74 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
75 .setDefault(ServiceEnvironmentCli
.LIVE
);
77 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
79 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
80 var subparser
= subparsers
.addParser(key
);
81 value
.attachToSubparser(subparser
);
87 public App(final Namespace ns
) {
91 public void init() throws CommandException
{
92 var outputType
= ns
.<OutputType
>get("output");
93 var outputWriter
= outputType
== OutputType
.JSON
94 ?
new JsonWriter(System
.out
)
95 : new PlainTextWriterImpl(System
.out
);
97 var commandKey
= ns
.getString("command");
98 var command
= Commands
.getCommand(commandKey
, outputWriter
);
99 if (command
== null) {
100 throw new UserErrorException("Command not implemented!");
103 if (!command
.getSupportedOutputTypes().contains(outputType
)) {
104 throw new UserErrorException("Command doesn't support output type " + outputType
.toString());
107 var username
= ns
.getString("username");
109 final var useDbus
= ns
.getBoolean("dbus");
110 final var useDbusSystem
= ns
.getBoolean("dbus-system");
111 if (useDbus
|| useDbusSystem
) {
112 // If username is null, it will connect to the default object path
113 initDbusClient(command
, username
, useDbusSystem
);
118 var config
= ns
.getString("config");
119 if (config
!= null) {
120 dataPath
= new File(config
);
122 dataPath
= getDefaultDataPath();
125 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
126 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
127 ? ServiceEnvironment
.LIVE
128 : ServiceEnvironment
.SANDBOX
;
130 if (!ServiceConfig
.getCapabilities().isGv2()) {
131 logger
.warn("WARNING: Support for new group V2 is disabled,"
132 + " because the required native library dependency is missing: libzkgroup");
135 if (!ServiceConfig
.isSignalClientAvailable()) {
136 throw new UserErrorException("Missing required native library dependency: libsignal-client");
139 if (command
instanceof ProvisioningCommand
) {
140 if (username
!= null) {
141 throw new UserErrorException("You cannot specify a username (phone number) when linking");
144 handleProvisioningCommand((ProvisioningCommand
) command
, dataPath
, serviceEnvironment
);
148 if (username
== null) {
149 var usernames
= Manager
.getAllLocalUsernames(dataPath
);
151 if (command
instanceof MultiLocalCommand
) {
152 handleMultiLocalCommand((MultiLocalCommand
) command
, dataPath
, serviceEnvironment
, usernames
);
156 if (usernames
.size() == 0) {
157 throw new UserErrorException("No local users found, you first need to register or link an account");
158 } else if (usernames
.size() > 1) {
159 throw new UserErrorException(
160 "Multiple users found, you need to specify a username (phone number) with -u");
163 username
= usernames
.get(0);
164 } else if (!PhoneNumberFormatter
.isValidNumber(username
, null)) {
165 throw new UserErrorException("Invalid username (phone number), make sure you include the country code.");
168 if (command
instanceof RegistrationCommand
) {
169 handleRegistrationCommand((RegistrationCommand
) command
, username
, dataPath
, serviceEnvironment
);
173 if (!(command
instanceof LocalCommand
)) {
174 throw new UserErrorException("Command only works via dbus");
177 handleLocalCommand((LocalCommand
) command
, username
, dataPath
, serviceEnvironment
);
180 private void handleProvisioningCommand(
181 final ProvisioningCommand command
, final File dataPath
, final ServiceEnvironment serviceEnvironment
182 ) throws CommandException
{
183 var pm
= ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
184 command
.handleCommand(ns
, pm
);
187 private void handleRegistrationCommand(
188 final RegistrationCommand command
,
189 final String username
,
191 final ServiceEnvironment serviceEnvironment
192 ) throws CommandException
{
193 final RegistrationManager manager
;
195 manager
= RegistrationManager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
196 } catch (Throwable e
) {
197 throw new UnexpectedErrorException("Error loading or creating state file: "
200 + e
.getClass().getSimpleName()
203 try (var m
= manager
) {
204 command
.handleCommand(ns
, m
);
205 } catch (IOException e
) {
206 logger
.warn("Cleanup failed", e
);
210 private void handleLocalCommand(
211 final LocalCommand command
,
212 final String username
,
214 final ServiceEnvironment serviceEnvironment
215 ) throws CommandException
{
216 try (var m
= loadManager(username
, dataPath
, serviceEnvironment
)) {
217 command
.handleCommand(ns
, m
);
218 } catch (IOException e
) {
219 logger
.warn("Cleanup failed", e
);
223 private void handleMultiLocalCommand(
224 final MultiLocalCommand command
,
226 final ServiceEnvironment serviceEnvironment
,
227 final List
<String
> usernames
228 ) throws CommandException
{
229 final var managers
= new ArrayList
<Manager
>();
230 for (String u
: usernames
) {
232 managers
.add(loadManager(u
, dataPath
, serviceEnvironment
));
233 } catch (CommandException e
) {
234 logger
.warn("Ignoring {}: {}", u
, e
.getMessage());
238 command
.handleCommand(ns
, managers
);
240 for (var m
: managers
) {
243 } catch (IOException e
) {
244 logger
.warn("Cleanup failed", e
);
249 private Manager
loadManager(
250 final String username
, final File dataPath
, final ServiceEnvironment serviceEnvironment
251 ) throws CommandException
{
254 manager
= Manager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
255 } catch (NotRegisteredException e
) {
256 throw new UserErrorException("User " + username
+ " is not registered.");
257 } catch (Throwable e
) {
258 logger
.debug("Loading state file failed", e
);
259 throw new UnexpectedErrorException("Error loading state file for user "
264 + e
.getClass().getSimpleName()
269 manager
.checkAccountState();
270 } catch (IOException e
) {
271 throw new UnexpectedErrorException("Error while checking account " + username
+ ": " + e
.getMessage());
277 private void initDbusClient(
278 final Command command
, final String username
, final boolean systemBus
279 ) throws CommandException
{
281 DBusConnection
.DBusBusType busType
;
283 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
285 busType
= DBusConnection
.DBusBusType
.SESSION
;
287 try (var dBusConn
= DBusConnection
.getConnection(busType
)) {
288 var ts
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
289 DbusConfig
.getObjectPath(username
),
292 handleCommand(command
, ts
, dBusConn
);
294 } catch (DBusException
| IOException e
) {
295 logger
.error("Dbus client failed", e
);
296 throw new UnexpectedErrorException("Dbus client failed");
300 private void handleCommand(Command command
, Signal ts
, DBusConnection dBusConn
) throws CommandException
{
301 if (command
instanceof ExtendedDbusCommand
) {
302 ((ExtendedDbusCommand
) command
).handleCommand(ns
, ts
, dBusConn
);
303 } else if (command
instanceof DbusCommand
) {
304 ((DbusCommand
) command
).handleCommand(ns
, ts
);
306 throw new UserErrorException("Command is not yet implemented via dbus");
311 * @return the default data directory to be used by signal-cli.
313 private static File
getDefaultDataPath() {
314 return new File(IOUtils
.getDataHomeDir(), "signal-cli");