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
.RegistrationManager
;
26 import org
.asamk
.signal
.manager
.SignalAccountFiles
;
27 import org
.asamk
.signal
.manager
.api
.AccountCheckException
;
28 import org
.asamk
.signal
.manager
.api
.NotRegisteredException
;
29 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
30 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
31 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
32 import org
.asamk
.signal
.output
.JsonWriterImpl
;
33 import org
.asamk
.signal
.output
.OutputWriter
;
34 import org
.asamk
.signal
.output
.PlainTextWriterImpl
;
35 import org
.asamk
.signal
.util
.IOUtils
;
36 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
37 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnectionBuilder
;
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
;
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
, IOUtils
.getConsoleCharset()));
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 final SignalAccountFiles signalAccountFiles
;
169 signalAccountFiles
= new SignalAccountFiles(configPath
,
171 BaseConfig
.USER_AGENT
,
173 } catch (IOException e
) {
174 throw new IOErrorException("Failed to read local accounts list", e
);
177 if (command
instanceof ProvisioningCommand provisioningCommand
) {
178 if (account
!= null) {
179 throw new UserErrorException("You cannot specify a account (phone number) when linking");
182 handleProvisioningCommand(provisioningCommand
, signalAccountFiles
, outputWriter
);
186 if (account
== null) {
187 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
188 handleMultiLocalCommand(multiLocalCommand
, signalAccountFiles
, outputWriter
);
192 Set
<String
> accounts
= null;
194 accounts
= signalAccountFiles
.getAllLocalAccountNumbers();
195 } catch (IOException e
) {
196 throw new IOErrorException("Failed to load local accounts file", e
);
198 if (accounts
.size() == 0) {
199 throw new UserErrorException("No local users found, you first need to register or link an account");
200 } else if (accounts
.size() > 1) {
201 throw new UserErrorException(
202 "Multiple users found, you need to specify an account (phone number) with -a");
205 account
= accounts
.stream().findFirst().get();
206 } else if (!Manager
.isValidNumber(account
, null)) {
207 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
210 if (command
instanceof RegistrationCommand registrationCommand
) {
211 handleRegistrationCommand(registrationCommand
, account
, signalAccountFiles
);
215 if (!(command
instanceof LocalCommand
)) {
216 throw new UserErrorException("Command only works in multi-account mode");
219 handleLocalCommand((LocalCommand
) command
, account
, signalAccountFiles
, outputWriter
);
222 private void handleProvisioningCommand(
223 final ProvisioningCommand command
,
224 final SignalAccountFiles signalAccountFiles
,
225 final OutputWriter outputWriter
226 ) throws CommandException
{
227 var pm
= signalAccountFiles
.initProvisioningManager();
228 command
.handleCommand(ns
, pm
, outputWriter
);
231 private void handleProvisioningCommand(
232 final ProvisioningCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
233 ) throws CommandException
, DBusException
{
234 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
235 DbusConfig
.getObjectPath(),
236 SignalControl
.class);
237 final var provisioningManager
= new DbusProvisioningManagerImpl(signalControl
, dBusConn
);
239 c
.handleCommand(ns
, provisioningManager
, outputWriter
);
240 } catch (UnsupportedOperationException e
) {
241 throw new UserErrorException("Command is not yet implemented via dbus", e
);
242 } catch (DBusExecutionException e
) {
243 throw new UnexpectedErrorException(e
.getMessage(), e
);
247 private void handleRegistrationCommand(
248 final RegistrationCommand command
, final String account
, final SignalAccountFiles signalAccountFiles
249 ) throws CommandException
{
250 try (final var manager
= loadRegistrationManager(account
, signalAccountFiles
)) {
251 command
.handleCommand(ns
, manager
);
252 } catch (IOException e
) {
253 logger
.warn("Cleanup failed", e
);
257 private void handleRegistrationCommand(
258 final RegistrationCommand c
, String account
, final DBusConnection dBusConn
, final OutputWriter outputWriter
259 ) throws CommandException
, DBusException
{
260 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
261 DbusConfig
.getObjectPath(),
262 SignalControl
.class);
263 try (final var registrationManager
= new DbusRegistrationManagerImpl(account
, signalControl
, dBusConn
)) {
264 c
.handleCommand(ns
, registrationManager
);
265 } catch (UnsupportedOperationException e
) {
266 throw new UserErrorException("Command is not yet implemented via dbus", e
);
267 } catch (DBusExecutionException e
) {
268 throw new UnexpectedErrorException(e
.getMessage(), e
);
272 private void handleLocalCommand(
273 final LocalCommand command
,
274 final String account
,
275 final SignalAccountFiles signalAccountFiles
,
276 final OutputWriter outputWriter
277 ) throws CommandException
{
278 try (var m
= loadManager(account
, signalAccountFiles
)) {
279 command
.handleCommand(ns
, m
, outputWriter
);
280 } catch (IOException e
) {
281 logger
.warn("Cleanup failed", e
);
285 private void handleLocalCommand(
286 final LocalCommand c
,
287 String accountObjectPath
,
288 final DBusConnection dBusConn
,
289 final OutputWriter outputWriter
290 ) throws CommandException
, DBusException
{
291 var signal
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(), accountObjectPath
, Signal
.class);
292 try (final var m
= new DbusManagerImpl(signal
, dBusConn
)) {
293 c
.handleCommand(ns
, m
, outputWriter
);
294 } catch (UnsupportedOperationException e
) {
295 throw new UserErrorException("Command is not yet implemented via dbus", e
);
296 } catch (DBusExecutionException e
) {
297 throw new UnexpectedErrorException(e
.getMessage(), e
);
301 private void handleMultiLocalCommand(
302 final MultiLocalCommand command
,
303 final SignalAccountFiles signalAccountFiles
,
304 final OutputWriter outputWriter
305 ) throws CommandException
{
306 try (var multiAccountManager
= signalAccountFiles
.initMultiAccountManager()) {
307 command
.handleCommand(ns
, multiAccountManager
, outputWriter
);
308 } catch (IOException e
) {
309 throw new IOErrorException("Failed to load local accounts file", e
);
313 private void handleMultiLocalCommand(
314 final MultiLocalCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
315 ) throws CommandException
, DBusException
{
316 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
317 DbusConfig
.getObjectPath(),
318 SignalControl
.class);
319 try (final var multiAccountManager
= new DbusMultiAccountManagerImpl(signalControl
, dBusConn
)) {
320 c
.handleCommand(ns
, multiAccountManager
, outputWriter
);
321 } catch (UnsupportedOperationException e
) {
322 throw new UserErrorException("Command is not yet implemented via dbus", e
);
326 private RegistrationManager
loadRegistrationManager(
327 final String account
, final SignalAccountFiles signalAccountFiles
328 ) throws UnexpectedErrorException
{
330 return signalAccountFiles
.initRegistrationManager(account
);
331 } catch (Throwable e
) {
332 throw new UnexpectedErrorException("Error loading or creating state file: "
335 + e
.getClass().getSimpleName()
340 private Manager
loadManager(
341 final String account
, final SignalAccountFiles signalAccountFiles
342 ) throws CommandException
{
343 logger
.trace("Loading account file for {}", account
);
345 return signalAccountFiles
.initManager(account
);
346 } catch (NotRegisteredException e
) {
347 throw new UserErrorException("User " + account
+ " is not registered.");
348 } catch (AccountCheckException ace
) {
349 if (ace
.getCause() instanceof IOException e
) {
350 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
352 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
355 } catch (Throwable e
) {
356 throw new UnexpectedErrorException("Error loading state file for user "
361 + e
.getClass().getSimpleName()
366 private void initDbusClient(
367 final Command command
, final String account
, final boolean systemBus
, final OutputWriter outputWriter
368 ) throws CommandException
{
370 DBusConnection
.DBusBusType busType
;
372 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
374 busType
= DBusConnection
.DBusBusType
.SESSION
;
376 try (var dBusConn
= DBusConnectionBuilder
.forType(busType
).build()) {
377 if (command
instanceof ProvisioningCommand c
) {
378 if (account
!= null) {
379 throw new UserErrorException("You cannot specify a account (phone number) when linking");
382 handleProvisioningCommand(c
, dBusConn
, outputWriter
);
386 if (account
== null && command
instanceof MultiLocalCommand c
) {
387 handleMultiLocalCommand(c
, dBusConn
, outputWriter
);
390 if (account
!= null && command
instanceof RegistrationCommand c
) {
391 handleRegistrationCommand(c
, account
, dBusConn
, outputWriter
);
394 if (!(command
instanceof LocalCommand localCommand
)) {
395 throw new UserErrorException("Command only works in multi-account mode");
398 var accountObjectPath
= account
== null ?
tryGetSingleAccountObjectPath(dBusConn
) : null;
399 if (accountObjectPath
== null) {
400 accountObjectPath
= DbusConfig
.getObjectPath(account
);
402 handleLocalCommand(localCommand
, accountObjectPath
, dBusConn
, outputWriter
);
404 } catch (ServiceUnknown e
) {
405 throw new UserErrorException("signal-cli DBus daemon not running on "
406 + (systemBus ?
"system" : "session")
408 + e
.getMessage(), e
);
409 } catch (DBusExecutionException
| DBusException
| IOException e
) {
410 throw new UnexpectedErrorException("Dbus client failed: " + e
.getMessage(), e
);
414 private String
tryGetSingleAccountObjectPath(final DBusConnection dBusConn
) throws DBusException
, CommandException
{
415 var control
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
416 DbusConfig
.getObjectPath(),
417 SignalControl
.class);
419 final var accounts
= control
.listAccounts();
420 if (accounts
.size() == 0) {
421 throw new UserErrorException("No local users found, you first need to register or link an account");
422 } else if (accounts
.size() > 1) {
423 throw new UserErrorException(
424 "Multiple users found, you need to specify an account (phone number) with -a");
427 return accounts
.get(0).getPath();
428 } catch (UnknownMethod e
) {
429 // dbus daemon not running in multi-account mode
435 * @return the default data directory to be used by signal-cli.
437 private static File
getDefaultConfigPath() {
438 return new File(IOUtils
.getDataHomeDir(), "signal-cli");