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
.api
.ServiceEnvironment
;
31 import org
.asamk
.signal
.manager
.api
.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 parser
.addArgument("--disable-send-log")
105 .help("Disable message send log (for resending messages that recipient couldn't decrypt)")
106 .action(Arguments
.storeTrue());
108 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
110 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
111 var subparser
= subparsers
.addParser(key
);
112 value
.attachToSubparser(subparser
);
118 public App(final Namespace ns
) {
122 public void init() throws CommandException
{
123 var commandKey
= ns
.getString("command");
124 var command
= Commands
.getCommand(commandKey
);
125 if (command
== null) {
126 throw new UserErrorException("Command not implemented!");
129 var outputTypeInput
= ns
.<OutputType
>get("output");
130 var outputType
= outputTypeInput
== null
131 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
133 var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, IOUtils
.getConsoleCharset()));
134 var outputWriter
= outputType
== null
136 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
138 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
139 throw new UserErrorException("Command doesn't support output type " + outputType
);
142 var account
= ns
.getString("account");
144 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
145 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
146 if (useDbus
|| useDbusSystem
) {
147 // If account is null, it will connect to the default object path
148 initDbusClient(command
, account
, useDbusSystem
, outputWriter
);
152 if (!Manager
.isSignalClientAvailable()) {
153 throw new UserErrorException("Missing required native library dependency: libsignal-client");
156 final File configPath
;
157 var config
= ns
.getString("config");
158 if (config
!= null) {
159 configPath
= new File(config
);
161 configPath
= getDefaultConfigPath();
164 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
165 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
166 ? ServiceEnvironment
.LIVE
167 : ServiceEnvironment
.STAGING
;
169 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
170 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
171 ? TrustNewIdentity
.ON_FIRST_USE
172 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
174 final var disableSendLog
= Boolean
.TRUE
.equals(ns
.getBoolean("disable-send-log"));
176 final SignalAccountFiles signalAccountFiles
;
178 signalAccountFiles
= new SignalAccountFiles(configPath
,
180 BaseConfig
.USER_AGENT
,
181 new Settings(trustNewIdentity
, disableSendLog
));
182 } catch (IOException e
) {
183 throw new IOErrorException("Failed to read local accounts list", e
);
186 if (command
instanceof ProvisioningCommand provisioningCommand
) {
187 if (account
!= null) {
188 throw new UserErrorException("You cannot specify a account (phone number) when linking");
191 handleProvisioningCommand(provisioningCommand
, signalAccountFiles
, outputWriter
);
195 if (account
== null) {
196 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
197 handleMultiLocalCommand(multiLocalCommand
, signalAccountFiles
, outputWriter
);
201 Set
<String
> accounts
= null;
203 accounts
= signalAccountFiles
.getAllLocalAccountNumbers();
204 } catch (IOException e
) {
205 throw new IOErrorException("Failed to load local accounts file", e
);
207 if (accounts
.size() == 0) {
208 throw new UserErrorException("No local users found, you first need to register or link an account");
209 } else if (accounts
.size() > 1) {
210 throw new UserErrorException(
211 "Multiple users found, you need to specify an account (phone number) with -a");
214 account
= accounts
.stream().findFirst().get();
215 } else if (!Manager
.isValidNumber(account
, null)) {
216 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
219 if (command
instanceof RegistrationCommand registrationCommand
) {
220 handleRegistrationCommand(registrationCommand
, account
, signalAccountFiles
);
224 if (!(command
instanceof LocalCommand
)) {
225 throw new UserErrorException("Command only works in multi-account mode");
228 handleLocalCommand((LocalCommand
) command
, account
, signalAccountFiles
, outputWriter
);
231 private void handleProvisioningCommand(
232 final ProvisioningCommand command
,
233 final SignalAccountFiles signalAccountFiles
,
234 final OutputWriter outputWriter
235 ) throws CommandException
{
236 var pm
= signalAccountFiles
.initProvisioningManager();
237 command
.handleCommand(ns
, pm
, outputWriter
);
240 private void handleProvisioningCommand(
241 final ProvisioningCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
242 ) throws CommandException
, DBusException
{
243 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
244 DbusConfig
.getObjectPath(),
245 SignalControl
.class);
246 final var provisioningManager
= new DbusProvisioningManagerImpl(signalControl
, dBusConn
);
248 c
.handleCommand(ns
, provisioningManager
, outputWriter
);
249 } catch (UnsupportedOperationException e
) {
250 throw new UserErrorException("Command is not yet implemented via dbus", e
);
251 } catch (DBusExecutionException e
) {
252 throw new UnexpectedErrorException(e
.getMessage(), e
);
256 private void handleRegistrationCommand(
257 final RegistrationCommand command
, final String account
, final SignalAccountFiles signalAccountFiles
258 ) throws CommandException
{
259 try (final var manager
= loadRegistrationManager(account
, signalAccountFiles
)) {
260 command
.handleCommand(ns
, manager
);
261 } catch (IOException e
) {
262 logger
.warn("Cleanup failed", e
);
266 private void handleRegistrationCommand(
267 final RegistrationCommand c
, String account
, final DBusConnection dBusConn
, final OutputWriter outputWriter
268 ) throws CommandException
, DBusException
{
269 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
270 DbusConfig
.getObjectPath(),
271 SignalControl
.class);
272 try (final var registrationManager
= new DbusRegistrationManagerImpl(account
, signalControl
, dBusConn
)) {
273 c
.handleCommand(ns
, registrationManager
);
274 } catch (UnsupportedOperationException e
) {
275 throw new UserErrorException("Command is not yet implemented via dbus", e
);
276 } catch (DBusExecutionException e
) {
277 throw new UnexpectedErrorException(e
.getMessage(), e
);
281 private void handleLocalCommand(
282 final LocalCommand command
,
283 final String account
,
284 final SignalAccountFiles signalAccountFiles
,
285 final OutputWriter outputWriter
286 ) throws CommandException
{
287 try (var m
= loadManager(account
, signalAccountFiles
)) {
288 command
.handleCommand(ns
, m
, outputWriter
);
289 } catch (IOException e
) {
290 logger
.warn("Cleanup failed", e
);
294 private void handleLocalCommand(
295 final LocalCommand c
,
296 String accountObjectPath
,
297 final DBusConnection dBusConn
,
298 final OutputWriter outputWriter
299 ) throws CommandException
, DBusException
{
300 var signal
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(), accountObjectPath
, Signal
.class);
301 try (final var m
= new DbusManagerImpl(signal
, dBusConn
)) {
302 c
.handleCommand(ns
, m
, outputWriter
);
303 } catch (UnsupportedOperationException e
) {
304 throw new UserErrorException("Command is not yet implemented via dbus", e
);
305 } catch (DBusExecutionException e
) {
306 throw new UnexpectedErrorException(e
.getMessage(), e
);
310 private void handleMultiLocalCommand(
311 final MultiLocalCommand command
,
312 final SignalAccountFiles signalAccountFiles
,
313 final OutputWriter outputWriter
314 ) throws CommandException
{
315 try (var multiAccountManager
= signalAccountFiles
.initMultiAccountManager()) {
316 command
.handleCommand(ns
, multiAccountManager
, outputWriter
);
317 } catch (IOException e
) {
318 throw new IOErrorException("Failed to load local accounts file", e
);
322 private void handleMultiLocalCommand(
323 final MultiLocalCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
324 ) throws CommandException
, DBusException
{
325 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
326 DbusConfig
.getObjectPath(),
327 SignalControl
.class);
328 try (final var multiAccountManager
= new DbusMultiAccountManagerImpl(signalControl
, dBusConn
)) {
329 c
.handleCommand(ns
, multiAccountManager
, outputWriter
);
330 } catch (UnsupportedOperationException e
) {
331 throw new UserErrorException("Command is not yet implemented via dbus", e
);
335 private RegistrationManager
loadRegistrationManager(
336 final String account
, final SignalAccountFiles signalAccountFiles
337 ) throws UnexpectedErrorException
{
339 return signalAccountFiles
.initRegistrationManager(account
);
340 } catch (Throwable e
) {
341 throw new UnexpectedErrorException("Error loading or creating state file: "
344 + e
.getClass().getSimpleName()
349 private Manager
loadManager(
350 final String account
, final SignalAccountFiles signalAccountFiles
351 ) throws CommandException
{
352 logger
.trace("Loading account file for {}", account
);
354 return signalAccountFiles
.initManager(account
);
355 } catch (NotRegisteredException e
) {
356 throw new UserErrorException("User " + account
+ " is not registered.");
357 } catch (AccountCheckException ace
) {
358 if (ace
.getCause() instanceof IOException e
) {
359 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
361 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
364 } catch (Throwable e
) {
365 throw new UnexpectedErrorException("Error loading state file for user "
370 + e
.getClass().getSimpleName()
375 private void initDbusClient(
376 final Command command
, final String account
, final boolean systemBus
, final OutputWriter outputWriter
377 ) throws CommandException
{
379 DBusConnection
.DBusBusType busType
;
381 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
383 busType
= DBusConnection
.DBusBusType
.SESSION
;
385 try (var dBusConn
= DBusConnectionBuilder
.forType(busType
).build()) {
386 if (command
instanceof ProvisioningCommand c
) {
387 if (account
!= null) {
388 throw new UserErrorException("You cannot specify a account (phone number) when linking");
391 handleProvisioningCommand(c
, dBusConn
, outputWriter
);
395 if (account
== null && command
instanceof MultiLocalCommand c
) {
396 handleMultiLocalCommand(c
, dBusConn
, outputWriter
);
399 if (account
!= null && command
instanceof RegistrationCommand c
) {
400 handleRegistrationCommand(c
, account
, dBusConn
, outputWriter
);
403 if (!(command
instanceof LocalCommand localCommand
)) {
404 throw new UserErrorException("Command only works in multi-account mode");
407 var accountObjectPath
= account
== null ?
tryGetSingleAccountObjectPath(dBusConn
) : null;
408 if (accountObjectPath
== null) {
409 accountObjectPath
= DbusConfig
.getObjectPath(account
);
411 handleLocalCommand(localCommand
, accountObjectPath
, dBusConn
, outputWriter
);
413 } catch (ServiceUnknown e
) {
414 throw new UserErrorException("signal-cli DBus daemon not running on "
415 + (systemBus ?
"system" : "session")
417 + e
.getMessage(), e
);
418 } catch (DBusExecutionException
| DBusException
| IOException e
) {
419 throw new UnexpectedErrorException("Dbus client failed: " + e
.getMessage(), e
);
423 private String
tryGetSingleAccountObjectPath(final DBusConnection dBusConn
) throws DBusException
, CommandException
{
424 var control
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
425 DbusConfig
.getObjectPath(),
426 SignalControl
.class);
428 final var accounts
= control
.listAccounts();
429 if (accounts
.size() == 0) {
430 throw new UserErrorException("No local users found, you first need to register or link an account");
431 } else if (accounts
.size() > 1) {
432 throw new UserErrorException(
433 "Multiple users found, you need to specify an account (phone number) with -a");
436 return accounts
.get(0).getPath();
437 } catch (UnknownMethod e
) {
438 // dbus daemon not running in multi-account mode
444 * @return the default data directory to be used by signal-cli.
446 private static File
getDefaultConfigPath() {
447 return new File(IOUtils
.getDataHomeDir(), "signal-cli");