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("--version").help("Show package version.").action(Arguments
.version());
68 parser
.addArgument("-v", "--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("--scrub-log")
75 .action(Arguments
.storeTrue())
76 .help("Scrub possibly sensitive information from the log, like phone numbers and UUIDs.");
77 parser
.addArgument("-c", "--config")
78 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
80 parser
.addArgument("-a", "--account", "-u", "--username")
81 .help("Specify your phone number, that will be your identifier.");
83 var mut
= parser
.addMutuallyExclusiveGroup();
84 mut
.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
85 mut
.addArgument("--dbus-system")
86 .dest("global-dbus-system")
87 .help("Make request via system dbus.")
88 .action(Arguments
.storeTrue());
90 parser
.addArgument("-o", "--output")
91 .help("Choose to output in plain text or JSON")
92 .type(Arguments
.enumStringType(OutputType
.class));
94 parser
.addArgument("--service-environment")
95 .help("Choose the server environment to use.")
96 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
97 .setDefault(ServiceEnvironmentCli
.LIVE
);
99 parser
.addArgument("--trust-new-identities")
100 .help("Choose when to trust new identities.")
101 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
102 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
104 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
106 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
107 var subparser
= subparsers
.addParser(key
);
108 value
.attachToSubparser(subparser
);
114 public App(final Namespace ns
) {
118 public void init() throws CommandException
{
119 var commandKey
= ns
.getString("command");
120 var command
= Commands
.getCommand(commandKey
);
121 if (command
== null) {
122 throw new UserErrorException("Command not implemented!");
125 var outputTypeInput
= ns
.<OutputType
>get("output");
126 var outputType
= outputTypeInput
== null
127 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
129 var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, IOUtils
.getConsoleCharset()));
130 var outputWriter
= outputType
== null
132 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
134 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
135 throw new UserErrorException("Command doesn't support output type " + outputType
);
138 var account
= ns
.getString("account");
140 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
141 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
142 if (useDbus
|| useDbusSystem
) {
143 // If account is null, it will connect to the default object path
144 initDbusClient(command
, account
, useDbusSystem
, outputWriter
);
148 if (!ServiceConfig
.isSignalClientAvailable()) {
149 throw new UserErrorException("Missing required native library dependency: libsignal-client");
152 final File configPath
;
153 var config
= ns
.getString("config");
154 if (config
!= null) {
155 configPath
= new File(config
);
157 configPath
= getDefaultConfigPath();
160 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
161 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
162 ? ServiceEnvironment
.LIVE
163 : ServiceEnvironment
.STAGING
;
165 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
166 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
167 ? TrustNewIdentity
.ON_FIRST_USE
168 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
170 final SignalAccountFiles signalAccountFiles
;
172 signalAccountFiles
= new SignalAccountFiles(configPath
,
174 BaseConfig
.USER_AGENT
,
176 } catch (IOException e
) {
177 throw new IOErrorException("Failed to read local accounts list", e
);
180 if (command
instanceof ProvisioningCommand provisioningCommand
) {
181 if (account
!= null) {
182 throw new UserErrorException("You cannot specify a account (phone number) when linking");
185 handleProvisioningCommand(provisioningCommand
, signalAccountFiles
, outputWriter
);
189 if (account
== null) {
190 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
191 handleMultiLocalCommand(multiLocalCommand
, signalAccountFiles
, outputWriter
);
195 Set
<String
> accounts
= null;
197 accounts
= signalAccountFiles
.getAllLocalAccountNumbers();
198 } catch (IOException e
) {
199 throw new IOErrorException("Failed to load local accounts file", e
);
201 if (accounts
.size() == 0) {
202 throw new UserErrorException("No local users found, you first need to register or link an account");
203 } else if (accounts
.size() > 1) {
204 throw new UserErrorException(
205 "Multiple users found, you need to specify an account (phone number) with -a");
208 account
= accounts
.stream().findFirst().get();
209 } else if (!Manager
.isValidNumber(account
, null)) {
210 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
213 if (command
instanceof RegistrationCommand registrationCommand
) {
214 handleRegistrationCommand(registrationCommand
, account
, signalAccountFiles
);
218 if (!(command
instanceof LocalCommand
)) {
219 throw new UserErrorException("Command only works in multi-account mode");
222 handleLocalCommand((LocalCommand
) command
, account
, signalAccountFiles
, outputWriter
);
225 private void handleProvisioningCommand(
226 final ProvisioningCommand command
,
227 final SignalAccountFiles signalAccountFiles
,
228 final OutputWriter outputWriter
229 ) throws CommandException
{
230 var pm
= signalAccountFiles
.initProvisioningManager();
231 command
.handleCommand(ns
, pm
, outputWriter
);
234 private void handleProvisioningCommand(
235 final ProvisioningCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
236 ) throws CommandException
, DBusException
{
237 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
238 DbusConfig
.getObjectPath(),
239 SignalControl
.class);
240 final var provisioningManager
= new DbusProvisioningManagerImpl(signalControl
, dBusConn
);
242 c
.handleCommand(ns
, provisioningManager
, outputWriter
);
243 } catch (UnsupportedOperationException e
) {
244 throw new UserErrorException("Command is not yet implemented via dbus", e
);
245 } catch (DBusExecutionException e
) {
246 throw new UnexpectedErrorException(e
.getMessage(), e
);
250 private void handleRegistrationCommand(
251 final RegistrationCommand command
, final String account
, final SignalAccountFiles signalAccountFiles
252 ) throws CommandException
{
253 try (final var manager
= loadRegistrationManager(account
, signalAccountFiles
)) {
254 command
.handleCommand(ns
, manager
);
255 } catch (IOException e
) {
256 logger
.warn("Cleanup failed", e
);
260 private void handleRegistrationCommand(
261 final RegistrationCommand c
, String account
, final DBusConnection dBusConn
, final OutputWriter outputWriter
262 ) throws CommandException
, DBusException
{
263 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
264 DbusConfig
.getObjectPath(),
265 SignalControl
.class);
266 try (final var registrationManager
= new DbusRegistrationManagerImpl(account
, signalControl
, dBusConn
)) {
267 c
.handleCommand(ns
, registrationManager
);
268 } catch (UnsupportedOperationException e
) {
269 throw new UserErrorException("Command is not yet implemented via dbus", e
);
270 } catch (DBusExecutionException e
) {
271 throw new UnexpectedErrorException(e
.getMessage(), e
);
275 private void handleLocalCommand(
276 final LocalCommand command
,
277 final String account
,
278 final SignalAccountFiles signalAccountFiles
,
279 final OutputWriter outputWriter
280 ) throws CommandException
{
281 try (var m
= loadManager(account
, signalAccountFiles
)) {
282 command
.handleCommand(ns
, m
, outputWriter
);
283 } catch (IOException e
) {
284 logger
.warn("Cleanup failed", e
);
288 private void handleLocalCommand(
289 final LocalCommand c
,
290 String accountObjectPath
,
291 final DBusConnection dBusConn
,
292 final OutputWriter outputWriter
293 ) throws CommandException
, DBusException
{
294 var signal
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(), accountObjectPath
, Signal
.class);
295 try (final var m
= new DbusManagerImpl(signal
, dBusConn
)) {
296 c
.handleCommand(ns
, m
, outputWriter
);
297 } catch (UnsupportedOperationException e
) {
298 throw new UserErrorException("Command is not yet implemented via dbus", e
);
299 } catch (DBusExecutionException e
) {
300 throw new UnexpectedErrorException(e
.getMessage(), e
);
304 private void handleMultiLocalCommand(
305 final MultiLocalCommand command
,
306 final SignalAccountFiles signalAccountFiles
,
307 final OutputWriter outputWriter
308 ) throws CommandException
{
309 try (var multiAccountManager
= signalAccountFiles
.initMultiAccountManager()) {
310 command
.handleCommand(ns
, multiAccountManager
, outputWriter
);
311 } catch (IOException e
) {
312 throw new IOErrorException("Failed to load local accounts file", e
);
316 private void handleMultiLocalCommand(
317 final MultiLocalCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
318 ) throws CommandException
, DBusException
{
319 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
320 DbusConfig
.getObjectPath(),
321 SignalControl
.class);
322 try (final var multiAccountManager
= new DbusMultiAccountManagerImpl(signalControl
, dBusConn
)) {
323 c
.handleCommand(ns
, multiAccountManager
, outputWriter
);
324 } catch (UnsupportedOperationException e
) {
325 throw new UserErrorException("Command is not yet implemented via dbus", e
);
329 private RegistrationManager
loadRegistrationManager(
330 final String account
, final SignalAccountFiles signalAccountFiles
331 ) throws UnexpectedErrorException
{
333 return signalAccountFiles
.initRegistrationManager(account
);
334 } catch (Throwable e
) {
335 throw new UnexpectedErrorException("Error loading or creating state file: "
338 + e
.getClass().getSimpleName()
343 private Manager
loadManager(
344 final String account
, final SignalAccountFiles signalAccountFiles
345 ) throws CommandException
{
346 logger
.trace("Loading account file for {}", account
);
348 return signalAccountFiles
.initManager(account
);
349 } catch (NotRegisteredException e
) {
350 throw new UserErrorException("User " + account
+ " is not registered.");
351 } catch (AccountCheckException ace
) {
352 if (ace
.getCause() instanceof IOException e
) {
353 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
355 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
358 } catch (Throwable e
) {
359 throw new UnexpectedErrorException("Error loading state file for user "
364 + e
.getClass().getSimpleName()
369 private void initDbusClient(
370 final Command command
, final String account
, final boolean systemBus
, final OutputWriter outputWriter
371 ) throws CommandException
{
373 DBusConnection
.DBusBusType busType
;
375 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
377 busType
= DBusConnection
.DBusBusType
.SESSION
;
379 try (var dBusConn
= DBusConnectionBuilder
.forType(busType
).build()) {
380 if (command
instanceof ProvisioningCommand c
) {
381 if (account
!= null) {
382 throw new UserErrorException("You cannot specify a account (phone number) when linking");
385 handleProvisioningCommand(c
, dBusConn
, outputWriter
);
389 if (account
== null && command
instanceof MultiLocalCommand c
) {
390 handleMultiLocalCommand(c
, dBusConn
, outputWriter
);
393 if (account
!= null && command
instanceof RegistrationCommand c
) {
394 handleRegistrationCommand(c
, account
, dBusConn
, outputWriter
);
397 if (!(command
instanceof LocalCommand localCommand
)) {
398 throw new UserErrorException("Command only works in multi-account mode");
401 var accountObjectPath
= account
== null ?
tryGetSingleAccountObjectPath(dBusConn
) : null;
402 if (accountObjectPath
== null) {
403 accountObjectPath
= DbusConfig
.getObjectPath(account
);
405 handleLocalCommand(localCommand
, accountObjectPath
, dBusConn
, outputWriter
);
407 } catch (ServiceUnknown e
) {
408 throw new UserErrorException("signal-cli DBus daemon not running on "
409 + (systemBus ?
"system" : "session")
411 + e
.getMessage(), e
);
412 } catch (DBusExecutionException
| DBusException
| IOException e
) {
413 throw new UnexpectedErrorException("Dbus client failed: " + e
.getMessage(), e
);
417 private String
tryGetSingleAccountObjectPath(final DBusConnection dBusConn
) throws DBusException
, CommandException
{
418 var control
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
419 DbusConfig
.getObjectPath(),
420 SignalControl
.class);
422 final var accounts
= control
.listAccounts();
423 if (accounts
.size() == 0) {
424 throw new UserErrorException("No local users found, you first need to register or link an account");
425 } else if (accounts
.size() > 1) {
426 throw new UserErrorException(
427 "Multiple users found, you need to specify an account (phone number) with -a");
430 return accounts
.get(0).getPath();
431 } catch (UnknownMethod e
) {
432 // dbus daemon not running in multi-account mode
438 * @return the default data directory to be used by signal-cli.
440 private static File
getDefaultConfigPath() {
441 return new File(IOUtils
.getDataHomeDir(), "signal-cli");