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
.SignalControl
;
10 import org
.asamk
.signal
.commands
.Command
;
11 import org
.asamk
.signal
.commands
.Commands
;
12 import org
.asamk
.signal
.commands
.LocalCommand
;
13 import org
.asamk
.signal
.commands
.MultiLocalCommand
;
14 import org
.asamk
.signal
.commands
.ProvisioningCommand
;
15 import org
.asamk
.signal
.commands
.RegistrationCommand
;
16 import org
.asamk
.signal
.commands
.exceptions
.CommandException
;
17 import org
.asamk
.signal
.commands
.exceptions
.IOErrorException
;
18 import org
.asamk
.signal
.commands
.exceptions
.UnexpectedErrorException
;
19 import org
.asamk
.signal
.commands
.exceptions
.UserErrorException
;
20 import org
.asamk
.signal
.dbus
.DbusManagerImpl
;
21 import org
.asamk
.signal
.dbus
.DbusMultiAccountManagerImpl
;
22 import org
.asamk
.signal
.dbus
.DbusProvisioningManagerImpl
;
23 import org
.asamk
.signal
.dbus
.DbusRegistrationManagerImpl
;
24 import org
.asamk
.signal
.manager
.Manager
;
25 import org
.asamk
.signal
.manager
.MultiAccountManager
;
26 import org
.asamk
.signal
.manager
.ProvisioningManager
;
27 import org
.asamk
.signal
.manager
.RegistrationManager
;
28 import org
.asamk
.signal
.manager
.api
.AccountCheckException
;
29 import org
.asamk
.signal
.manager
.api
.NotRegisteredException
;
30 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
31 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
32 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
33 import org
.asamk
.signal
.output
.JsonWriterImpl
;
34 import org
.asamk
.signal
.output
.OutputWriter
;
35 import org
.asamk
.signal
.output
.PlainTextWriterImpl
;
36 import org
.asamk
.signal
.util
.IOUtils
;
37 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
38 import org
.freedesktop
.dbus
.errors
.ServiceUnknown
;
39 import org
.freedesktop
.dbus
.errors
.UnknownMethod
;
40 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
41 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
42 import org
.slf4j
.Logger
;
43 import org
.slf4j
.LoggerFactory
;
45 import java
.io
.BufferedWriter
;
47 import java
.io
.IOException
;
48 import java
.io
.OutputStreamWriter
;
49 import java
.nio
.charset
.Charset
;
51 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
55 private final static Logger logger
= LoggerFactory
.getLogger(App
.class);
57 private final Namespace ns
;
59 static ArgumentParser
buildArgumentParser() {
60 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
61 .includeArgumentNamesAsKeysInResult(true)
64 .description("Commandline interface for Signal.")
65 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
67 parser
.addArgument("-v", "--version").help("Show package version.").action(Arguments
.version());
68 parser
.addArgument("--verbose")
69 .help("Raise log level and include lib signal logs. Specify multiple times for even more logs.")
70 .action(Arguments
.count());
71 parser
.addArgument("--log-file")
73 .help("Write log output to the given file. If --verbose is also given, the detailed logs will only be written to the log file.");
74 parser
.addArgument("-c", "--config")
75 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
77 parser
.addArgument("-a", "--account", "-u", "--username")
78 .help("Specify your phone number, that will be your identifier.");
80 var mut
= parser
.addMutuallyExclusiveGroup();
81 mut
.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
82 mut
.addArgument("--dbus-system")
83 .dest("global-dbus-system")
84 .help("Make request via system dbus.")
85 .action(Arguments
.storeTrue());
87 parser
.addArgument("-o", "--output")
88 .help("Choose to output in plain text or JSON")
89 .type(Arguments
.enumStringType(OutputType
.class));
91 parser
.addArgument("--service-environment")
92 .help("Choose the server environment to use.")
93 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
94 .setDefault(ServiceEnvironmentCli
.LIVE
);
96 parser
.addArgument("--trust-new-identities")
97 .help("Choose when to trust new identities.")
98 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
99 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
101 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
103 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
104 var subparser
= subparsers
.addParser(key
);
105 value
.attachToSubparser(subparser
);
111 public App(final Namespace ns
) {
115 public void init() throws CommandException
{
116 var commandKey
= ns
.getString("command");
117 var command
= Commands
.getCommand(commandKey
);
118 if (command
== null) {
119 throw new UserErrorException("Command not implemented!");
122 var outputTypeInput
= ns
.<OutputType
>get("output");
123 var outputType
= outputTypeInput
== null
124 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
126 var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, Charset
.defaultCharset()));
127 var outputWriter
= outputType
== null
129 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
131 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
132 throw new UserErrorException("Command doesn't support output type " + outputType
);
135 var account
= ns
.getString("account");
137 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
138 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
139 if (useDbus
|| useDbusSystem
) {
140 // If account is null, it will connect to the default object path
141 initDbusClient(command
, account
, useDbusSystem
, outputWriter
);
145 if (!ServiceConfig
.isSignalClientAvailable()) {
146 throw new UserErrorException("Missing required native library dependency: libsignal-client");
149 final File configPath
;
150 var config
= ns
.getString("config");
151 if (config
!= null) {
152 configPath
= new File(config
);
154 configPath
= getDefaultConfigPath();
157 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
158 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
159 ? ServiceEnvironment
.LIVE
160 : ServiceEnvironment
.STAGING
;
162 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
163 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
164 ? TrustNewIdentity
.ON_FIRST_USE
165 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
167 if (command
instanceof ProvisioningCommand provisioningCommand
) {
168 if (account
!= null) {
169 throw new UserErrorException("You cannot specify a account (phone number) when linking");
172 handleProvisioningCommand(provisioningCommand
, configPath
, serviceEnvironment
, outputWriter
);
176 if (account
== null) {
177 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
178 handleMultiLocalCommand(multiLocalCommand
,
186 var accounts
= MultiAccountManager
.getAllLocalAccountNumbers(configPath
);
187 if (accounts
.size() == 0) {
188 throw new UserErrorException("No local users found, you first need to register or link an account");
189 } else if (accounts
.size() > 1) {
190 throw new UserErrorException(
191 "Multiple users found, you need to specify an account (phone number) with -a");
194 account
= accounts
.get(0);
195 } else if (!Manager
.isValidNumber(account
, null)) {
196 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
199 if (command
instanceof RegistrationCommand registrationCommand
) {
200 handleRegistrationCommand(registrationCommand
, account
, configPath
, serviceEnvironment
);
204 if (!(command
instanceof LocalCommand
)) {
205 throw new UserErrorException("Command only works in multi-account mode");
208 handleLocalCommand((LocalCommand
) command
,
216 private void handleProvisioningCommand(
217 final ProvisioningCommand command
,
218 final File configPath
,
219 final ServiceEnvironment serviceEnvironment
,
220 final OutputWriter outputWriter
221 ) throws CommandException
{
222 var pm
= ProvisioningManager
.init(configPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
223 command
.handleCommand(ns
, pm
, outputWriter
);
226 private void handleProvisioningCommand(
227 final ProvisioningCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
228 ) throws CommandException
, DBusException
{
229 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
230 DbusConfig
.getObjectPath(),
231 SignalControl
.class);
232 final var provisioningManager
= new DbusProvisioningManagerImpl(signalControl
, dBusConn
);
234 c
.handleCommand(ns
, provisioningManager
, outputWriter
);
235 } catch (UnsupportedOperationException e
) {
236 throw new UserErrorException("Command is not yet implemented via dbus", e
);
237 } catch (DBusExecutionException e
) {
238 throw new UnexpectedErrorException(e
.getMessage(), e
);
242 private void handleRegistrationCommand(
243 final RegistrationCommand command
,
244 final String account
,
245 final File configPath
,
246 final ServiceEnvironment serviceEnvironment
247 ) throws CommandException
{
248 final RegistrationManager manager
;
250 manager
= RegistrationManager
.init(account
, configPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
251 } catch (Throwable e
) {
252 throw new UnexpectedErrorException("Error loading or creating state file: "
255 + e
.getClass().getSimpleName()
259 command
.handleCommand(ns
, manager
);
260 } catch (IOException e
) {
261 logger
.warn("Cleanup failed", e
);
265 private void handleRegistrationCommand(
266 final RegistrationCommand c
, String account
, final DBusConnection dBusConn
, final OutputWriter outputWriter
267 ) throws CommandException
, DBusException
{
268 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
269 DbusConfig
.getObjectPath(),
270 SignalControl
.class);
271 try (final var registrationManager
= new DbusRegistrationManagerImpl(account
, signalControl
, dBusConn
)) {
272 c
.handleCommand(ns
, registrationManager
);
273 } catch (UnsupportedOperationException e
) {
274 throw new UserErrorException("Command is not yet implemented via dbus", e
);
275 } catch (DBusExecutionException e
) {
276 throw new UnexpectedErrorException(e
.getMessage(), e
);
280 private void handleLocalCommand(
281 final LocalCommand command
,
282 final String account
,
283 final File configPath
,
284 final ServiceEnvironment serviceEnvironment
,
285 final OutputWriter outputWriter
,
286 final TrustNewIdentity trustNewIdentity
287 ) throws CommandException
{
288 try (var m
= loadManager(account
, configPath
, serviceEnvironment
, trustNewIdentity
)) {
289 command
.handleCommand(ns
, m
, outputWriter
);
290 } catch (IOException e
) {
291 logger
.warn("Cleanup failed", e
);
295 private void handleLocalCommand(
296 final LocalCommand c
,
297 String accountObjectPath
,
298 final DBusConnection dBusConn
,
299 final OutputWriter outputWriter
300 ) throws CommandException
, DBusException
{
301 var signal
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(), accountObjectPath
, Signal
.class);
302 try (final var m
= new DbusManagerImpl(signal
, dBusConn
)) {
303 c
.handleCommand(ns
, m
, outputWriter
);
304 } catch (UnsupportedOperationException e
) {
305 throw new UserErrorException("Command is not yet implemented via dbus", e
);
306 } catch (DBusExecutionException e
) {
307 throw new UnexpectedErrorException(e
.getMessage(), e
);
311 private void handleMultiLocalCommand(
312 final MultiLocalCommand command
,
313 final File configPath
,
314 final ServiceEnvironment serviceEnvironment
,
315 final OutputWriter outputWriter
,
316 final TrustNewIdentity trustNewIdentity
317 ) throws CommandException
{
318 try (var multiAccountManager
= MultiAccountManager
.init(configPath
,
320 BaseConfig
.USER_AGENT
,
322 command
.handleCommand(ns
, multiAccountManager
, outputWriter
);
326 private void handleMultiLocalCommand(
327 final MultiLocalCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
328 ) throws CommandException
, DBusException
{
329 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
330 DbusConfig
.getObjectPath(),
331 SignalControl
.class);
332 try (final var multiAccountManager
= new DbusMultiAccountManagerImpl(signalControl
, dBusConn
)) {
333 c
.handleCommand(ns
, multiAccountManager
, outputWriter
);
334 } catch (UnsupportedOperationException e
) {
335 throw new UserErrorException("Command is not yet implemented via dbus", e
);
339 private Manager
loadManager(
340 final String account
,
341 final File configPath
,
342 final ServiceEnvironment serviceEnvironment
,
343 final TrustNewIdentity trustNewIdentity
344 ) throws CommandException
{
345 logger
.trace("Loading account file for {}", account
);
347 return Manager
.init(account
, configPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
, trustNewIdentity
);
348 } catch (NotRegisteredException e
) {
349 throw new UserErrorException("User " + account
+ " is not registered.");
350 } catch (AccountCheckException ace
) {
351 if (ace
.getCause() instanceof IOException e
) {
352 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
354 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
357 } catch (Throwable e
) {
358 throw new UnexpectedErrorException("Error loading state file for user "
363 + e
.getClass().getSimpleName()
368 private void initDbusClient(
369 final Command command
, final String account
, final boolean systemBus
, final OutputWriter outputWriter
370 ) throws CommandException
{
372 DBusConnection
.DBusBusType busType
;
374 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
376 busType
= DBusConnection
.DBusBusType
.SESSION
;
378 try (var dBusConn
= DBusConnection
.getConnection(busType
)) {
379 if (command
instanceof ProvisioningCommand c
) {
380 if (account
!= null) {
381 throw new UserErrorException("You cannot specify a account (phone number) when linking");
384 handleProvisioningCommand(c
, dBusConn
, outputWriter
);
388 if (account
== null && command
instanceof MultiLocalCommand c
) {
389 handleMultiLocalCommand(c
, dBusConn
, outputWriter
);
392 if (account
!= null && command
instanceof RegistrationCommand c
) {
393 handleRegistrationCommand(c
, account
, dBusConn
, outputWriter
);
396 if (!(command
instanceof LocalCommand localCommand
)) {
397 throw new UserErrorException("Command only works in multi-account mode");
400 var accountObjectPath
= account
== null ?
tryGetSingleAccountObjectPath(dBusConn
) : null;
401 if (accountObjectPath
== null) {
402 accountObjectPath
= DbusConfig
.getObjectPath(account
);
404 handleLocalCommand(localCommand
, accountObjectPath
, dBusConn
, outputWriter
);
406 } catch (ServiceUnknown e
) {
407 throw new UserErrorException("signal-cli DBus daemon not running on "
408 + (systemBus ?
"system" : "session")
410 + e
.getMessage(), e
);
411 } catch (DBusExecutionException
| DBusException
| IOException e
) {
412 throw new UnexpectedErrorException("Dbus client failed: " + e
.getMessage(), e
);
416 private String
tryGetSingleAccountObjectPath(final DBusConnection dBusConn
) throws DBusException
, CommandException
{
417 var control
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
418 DbusConfig
.getObjectPath(),
419 SignalControl
.class);
421 final var accounts
= control
.listAccounts();
422 if (accounts
.size() == 0) {
423 throw new UserErrorException("No local users found, you first need to register or link an account");
424 } else if (accounts
.size() > 1) {
425 throw new UserErrorException(
426 "Multiple users found, you need to specify an account (phone number) with -a");
429 return accounts
.get(0).getPath();
430 } catch (UnknownMethod e
) {
431 // dbus daemon not running in multi-account mode
437 * @return the default data directory to be used by signal-cli.
439 private static File
getDefaultConfigPath() {
440 return new File(IOUtils
.getDataHomeDir(), "signal-cli");