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
.Settings
;
27 import org
.asamk
.signal
.manager
.SignalAccountFiles
;
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
.connections
.impl
.DBusConnectionBuilder
;
39 import org
.freedesktop
.dbus
.errors
.ServiceUnknown
;
40 import org
.freedesktop
.dbus
.errors
.UnknownMethod
;
41 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
42 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
43 import org
.slf4j
.Logger
;
44 import org
.slf4j
.LoggerFactory
;
46 import java
.io
.BufferedWriter
;
48 import java
.io
.IOException
;
49 import java
.io
.OutputStreamWriter
;
52 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
56 private final static Logger logger
= LoggerFactory
.getLogger(App
.class);
58 private final Namespace ns
;
60 static ArgumentParser
buildArgumentParser() {
61 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
62 .includeArgumentNamesAsKeysInResult(true)
65 .description("Commandline interface for Signal.")
66 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
68 parser
.addArgument("--version").help("Show package version.").action(Arguments
.version());
69 parser
.addArgument("-v", "--verbose")
70 .help("Raise log level and include lib signal logs. Specify multiple times for even more logs.")
71 .action(Arguments
.count());
72 parser
.addArgument("--log-file")
74 .help("Write log output to the given file. If --verbose is also given, the detailed logs will only be written to the log file.");
75 parser
.addArgument("--scrub-log")
76 .action(Arguments
.storeTrue())
77 .help("Scrub possibly sensitive information from the log, like phone numbers and UUIDs.");
78 parser
.addArgument("-c", "--config")
79 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
81 parser
.addArgument("-a", "--account", "-u", "--username")
82 .help("Specify your phone number, that will be your identifier.");
84 var mut
= parser
.addMutuallyExclusiveGroup();
85 mut
.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
86 mut
.addArgument("--dbus-system")
87 .dest("global-dbus-system")
88 .help("Make request via system dbus.")
89 .action(Arguments
.storeTrue());
91 parser
.addArgument("-o", "--output")
92 .help("Choose to output in plain text or JSON")
93 .type(Arguments
.enumStringType(OutputType
.class));
95 parser
.addArgument("--service-environment")
96 .help("Choose the server environment to use.")
97 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
98 .setDefault(ServiceEnvironmentCli
.LIVE
);
100 parser
.addArgument("--trust-new-identities")
101 .help("Choose when to trust new identities.")
102 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
103 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
105 parser
.addArgument("--disable-send-log")
106 .help("Disable message send log (for resending messages that recipient couldn't decrypt)")
107 .action(Arguments
.storeTrue());
109 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
111 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
112 var subparser
= subparsers
.addParser(key
);
113 value
.attachToSubparser(subparser
);
119 public App(final Namespace ns
) {
123 public void init() throws CommandException
{
124 var commandKey
= ns
.getString("command");
125 var command
= Commands
.getCommand(commandKey
);
126 if (command
== null) {
127 throw new UserErrorException("Command not implemented!");
130 var outputTypeInput
= ns
.<OutputType
>get("output");
131 var outputType
= outputTypeInput
== null
132 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
134 var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, IOUtils
.getConsoleCharset()));
135 var outputWriter
= outputType
== null
137 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
139 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
140 throw new UserErrorException("Command doesn't support output type " + outputType
);
143 var account
= ns
.getString("account");
145 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
146 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
147 if (useDbus
|| useDbusSystem
) {
148 // If account is null, it will connect to the default object path
149 initDbusClient(command
, account
, useDbusSystem
, outputWriter
);
153 if (!ServiceConfig
.isSignalClientAvailable()) {
154 throw new UserErrorException("Missing required native library dependency: libsignal-client");
157 final File configPath
;
158 var config
= ns
.getString("config");
159 if (config
!= null) {
160 configPath
= new File(config
);
162 configPath
= getDefaultConfigPath();
165 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
166 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
167 ? ServiceEnvironment
.LIVE
168 : ServiceEnvironment
.STAGING
;
170 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
171 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
172 ? TrustNewIdentity
.ON_FIRST_USE
173 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
175 final var disableSendLog
= Boolean
.TRUE
.equals(ns
.getBoolean("disable-send-log"));
177 final SignalAccountFiles signalAccountFiles
;
179 signalAccountFiles
= new SignalAccountFiles(configPath
,
181 BaseConfig
.USER_AGENT
,
182 new Settings(trustNewIdentity
, disableSendLog
));
183 } catch (IOException e
) {
184 throw new IOErrorException("Failed to read local accounts list", e
);
187 if (command
instanceof ProvisioningCommand provisioningCommand
) {
188 if (account
!= null) {
189 throw new UserErrorException("You cannot specify a account (phone number) when linking");
192 handleProvisioningCommand(provisioningCommand
, signalAccountFiles
, outputWriter
);
196 if (account
== null) {
197 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
198 handleMultiLocalCommand(multiLocalCommand
, signalAccountFiles
, outputWriter
);
202 Set
<String
> accounts
= null;
204 accounts
= signalAccountFiles
.getAllLocalAccountNumbers();
205 } catch (IOException e
) {
206 throw new IOErrorException("Failed to load local accounts file", e
);
208 if (accounts
.size() == 0) {
209 throw new UserErrorException("No local users found, you first need to register or link an account");
210 } else if (accounts
.size() > 1) {
211 throw new UserErrorException(
212 "Multiple users found, you need to specify an account (phone number) with -a");
215 account
= accounts
.stream().findFirst().get();
216 } else if (!Manager
.isValidNumber(account
, null)) {
217 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
220 if (command
instanceof RegistrationCommand registrationCommand
) {
221 handleRegistrationCommand(registrationCommand
, account
, signalAccountFiles
);
225 if (!(command
instanceof LocalCommand
)) {
226 throw new UserErrorException("Command only works in multi-account mode");
229 handleLocalCommand((LocalCommand
) command
, account
, signalAccountFiles
, outputWriter
);
232 private void handleProvisioningCommand(
233 final ProvisioningCommand command
,
234 final SignalAccountFiles signalAccountFiles
,
235 final OutputWriter outputWriter
236 ) throws CommandException
{
237 var pm
= signalAccountFiles
.initProvisioningManager();
238 command
.handleCommand(ns
, pm
, outputWriter
);
241 private void handleProvisioningCommand(
242 final ProvisioningCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
243 ) throws CommandException
, DBusException
{
244 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
245 DbusConfig
.getObjectPath(),
246 SignalControl
.class);
247 final var provisioningManager
= new DbusProvisioningManagerImpl(signalControl
, dBusConn
);
249 c
.handleCommand(ns
, provisioningManager
, outputWriter
);
250 } catch (UnsupportedOperationException e
) {
251 throw new UserErrorException("Command is not yet implemented via dbus", e
);
252 } catch (DBusExecutionException e
) {
253 throw new UnexpectedErrorException(e
.getMessage(), e
);
257 private void handleRegistrationCommand(
258 final RegistrationCommand command
, final String account
, final SignalAccountFiles signalAccountFiles
259 ) throws CommandException
{
260 try (final var manager
= loadRegistrationManager(account
, signalAccountFiles
)) {
261 command
.handleCommand(ns
, manager
);
262 } catch (IOException e
) {
263 logger
.warn("Cleanup failed", e
);
267 private void handleRegistrationCommand(
268 final RegistrationCommand c
, String account
, final DBusConnection dBusConn
, final OutputWriter outputWriter
269 ) throws CommandException
, DBusException
{
270 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
271 DbusConfig
.getObjectPath(),
272 SignalControl
.class);
273 try (final var registrationManager
= new DbusRegistrationManagerImpl(account
, signalControl
, dBusConn
)) {
274 c
.handleCommand(ns
, registrationManager
);
275 } catch (UnsupportedOperationException e
) {
276 throw new UserErrorException("Command is not yet implemented via dbus", e
);
277 } catch (DBusExecutionException e
) {
278 throw new UnexpectedErrorException(e
.getMessage(), e
);
282 private void handleLocalCommand(
283 final LocalCommand command
,
284 final String account
,
285 final SignalAccountFiles signalAccountFiles
,
286 final OutputWriter outputWriter
287 ) throws CommandException
{
288 try (var m
= loadManager(account
, signalAccountFiles
)) {
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 SignalAccountFiles signalAccountFiles
,
314 final OutputWriter outputWriter
315 ) throws CommandException
{
316 try (var multiAccountManager
= signalAccountFiles
.initMultiAccountManager()) {
317 command
.handleCommand(ns
, multiAccountManager
, outputWriter
);
318 } catch (IOException e
) {
319 throw new IOErrorException("Failed to load local accounts file", e
);
323 private void handleMultiLocalCommand(
324 final MultiLocalCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
325 ) throws CommandException
, DBusException
{
326 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
327 DbusConfig
.getObjectPath(),
328 SignalControl
.class);
329 try (final var multiAccountManager
= new DbusMultiAccountManagerImpl(signalControl
, dBusConn
)) {
330 c
.handleCommand(ns
, multiAccountManager
, outputWriter
);
331 } catch (UnsupportedOperationException e
) {
332 throw new UserErrorException("Command is not yet implemented via dbus", e
);
336 private RegistrationManager
loadRegistrationManager(
337 final String account
, final SignalAccountFiles signalAccountFiles
338 ) throws UnexpectedErrorException
{
340 return signalAccountFiles
.initRegistrationManager(account
);
341 } catch (Throwable e
) {
342 throw new UnexpectedErrorException("Error loading or creating state file: "
345 + e
.getClass().getSimpleName()
350 private Manager
loadManager(
351 final String account
, final SignalAccountFiles signalAccountFiles
352 ) throws CommandException
{
353 logger
.trace("Loading account file for {}", account
);
355 return signalAccountFiles
.initManager(account
);
356 } catch (NotRegisteredException e
) {
357 throw new UserErrorException("User " + account
+ " is not registered.");
358 } catch (AccountCheckException ace
) {
359 if (ace
.getCause() instanceof IOException e
) {
360 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
362 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
365 } catch (Throwable e
) {
366 throw new UnexpectedErrorException("Error loading state file for user "
371 + e
.getClass().getSimpleName()
376 private void initDbusClient(
377 final Command command
, final String account
, final boolean systemBus
, final OutputWriter outputWriter
378 ) throws CommandException
{
380 DBusConnection
.DBusBusType busType
;
382 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
384 busType
= DBusConnection
.DBusBusType
.SESSION
;
386 try (var dBusConn
= DBusConnectionBuilder
.forType(busType
).build()) {
387 if (command
instanceof ProvisioningCommand c
) {
388 if (account
!= null) {
389 throw new UserErrorException("You cannot specify a account (phone number) when linking");
392 handleProvisioningCommand(c
, dBusConn
, outputWriter
);
396 if (account
== null && command
instanceof MultiLocalCommand c
) {
397 handleMultiLocalCommand(c
, dBusConn
, outputWriter
);
400 if (account
!= null && command
instanceof RegistrationCommand c
) {
401 handleRegistrationCommand(c
, account
, dBusConn
, outputWriter
);
404 if (!(command
instanceof LocalCommand localCommand
)) {
405 throw new UserErrorException("Command only works in multi-account mode");
408 var accountObjectPath
= account
== null ?
tryGetSingleAccountObjectPath(dBusConn
) : null;
409 if (accountObjectPath
== null) {
410 accountObjectPath
= DbusConfig
.getObjectPath(account
);
412 handleLocalCommand(localCommand
, accountObjectPath
, dBusConn
, outputWriter
);
414 } catch (ServiceUnknown e
) {
415 throw new UserErrorException("signal-cli DBus daemon not running on "
416 + (systemBus ?
"system" : "session")
418 + e
.getMessage(), e
);
419 } catch (DBusExecutionException
| DBusException
| IOException e
) {
420 throw new UnexpectedErrorException("Dbus client failed: " + e
.getMessage(), e
);
424 private String
tryGetSingleAccountObjectPath(final DBusConnection dBusConn
) throws DBusException
, CommandException
{
425 var control
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
426 DbusConfig
.getObjectPath(),
427 SignalControl
.class);
429 final var accounts
= control
.listAccounts();
430 if (accounts
.size() == 0) {
431 throw new UserErrorException("No local users found, you first need to register or link an account");
432 } else if (accounts
.size() > 1) {
433 throw new UserErrorException(
434 "Multiple users found, you need to specify an account (phone number) with -a");
437 return accounts
.get(0).getPath();
438 } catch (UnknownMethod e
) {
439 // dbus daemon not running in multi-account mode
445 * @return the default data directory to be used by signal-cli.
447 private static File
getDefaultConfigPath() {
448 return new File(IOUtils
.getDataHomeDir(), "signal-cli");