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
;
50 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
54 private final static Logger logger
= LoggerFactory
.getLogger(App
.class);
56 private final Namespace ns
;
58 static ArgumentParser
buildArgumentParser() {
59 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
60 .includeArgumentNamesAsKeysInResult(true)
63 .description("Commandline interface for Signal.")
64 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
66 parser
.addArgument("-v", "--version").help("Show package version.").action(Arguments
.version());
67 parser
.addArgument("--verbose")
68 .help("Raise log level and include lib signal logs. Specify multiple times for even more logs.")
69 .action(Arguments
.count());
70 parser
.addArgument("--log-file")
72 .help("Write log output to the given file. If --verbose is also given, the detailed logs will only be written to the log file.");
73 parser
.addArgument("-c", "--config")
74 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
76 parser
.addArgument("-a", "--account", "-u", "--username")
77 .help("Specify your phone number, that will be your identifier.");
79 var mut
= parser
.addMutuallyExclusiveGroup();
80 mut
.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
81 mut
.addArgument("--dbus-system")
82 .dest("global-dbus-system")
83 .help("Make request via system dbus.")
84 .action(Arguments
.storeTrue());
86 parser
.addArgument("-o", "--output")
87 .help("Choose to output in plain text or JSON")
88 .type(Arguments
.enumStringType(OutputType
.class));
90 parser
.addArgument("--service-environment")
91 .help("Choose the server environment to use.")
92 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
93 .setDefault(ServiceEnvironmentCli
.LIVE
);
95 parser
.addArgument("--trust-new-identities")
96 .help("Choose when to trust new identities.")
97 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
98 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
100 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
102 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
103 var subparser
= subparsers
.addParser(key
);
104 value
.attachToSubparser(subparser
);
110 public App(final Namespace ns
) {
114 public void init() throws CommandException
{
115 var commandKey
= ns
.getString("command");
116 var command
= Commands
.getCommand(commandKey
);
117 if (command
== null) {
118 throw new UserErrorException("Command not implemented!");
121 var outputTypeInput
= ns
.<OutputType
>get("output");
122 var outputType
= outputTypeInput
== null
123 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
125 var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, IOUtils
.getConsoleCharset()));
126 var outputWriter
= outputType
== null
128 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
130 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
131 throw new UserErrorException("Command doesn't support output type " + outputType
);
134 var account
= ns
.getString("account");
136 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
137 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
138 if (useDbus
|| useDbusSystem
) {
139 // If account is null, it will connect to the default object path
140 initDbusClient(command
, account
, useDbusSystem
, outputWriter
);
144 if (!ServiceConfig
.isSignalClientAvailable()) {
145 throw new UserErrorException("Missing required native library dependency: libsignal-client");
148 final File configPath
;
149 var config
= ns
.getString("config");
150 if (config
!= null) {
151 configPath
= new File(config
);
153 configPath
= getDefaultConfigPath();
156 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
157 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
158 ? ServiceEnvironment
.LIVE
159 : ServiceEnvironment
.STAGING
;
161 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
162 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
163 ? TrustNewIdentity
.ON_FIRST_USE
164 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
166 final SignalAccountFiles signalAccountFiles
;
168 signalAccountFiles
= new SignalAccountFiles(configPath
,
170 BaseConfig
.USER_AGENT
,
172 } catch (IOException e
) {
173 throw new IOErrorException("Failed to read local accounts list", e
);
176 if (command
instanceof ProvisioningCommand provisioningCommand
) {
177 if (account
!= null) {
178 throw new UserErrorException("You cannot specify a account (phone number) when linking");
181 handleProvisioningCommand(provisioningCommand
, signalAccountFiles
, outputWriter
);
185 if (account
== null) {
186 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
187 handleMultiLocalCommand(multiLocalCommand
, signalAccountFiles
, outputWriter
);
191 var accounts
= signalAccountFiles
.getAllLocalAccountNumbers();
192 if (accounts
.size() == 0) {
193 throw new UserErrorException("No local users found, you first need to register or link an account");
194 } else if (accounts
.size() > 1) {
195 throw new UserErrorException(
196 "Multiple users found, you need to specify an account (phone number) with -a");
199 account
= accounts
.stream().findFirst().get();
200 } else if (!Manager
.isValidNumber(account
, null)) {
201 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
204 if (command
instanceof RegistrationCommand registrationCommand
) {
205 handleRegistrationCommand(registrationCommand
, account
, signalAccountFiles
);
209 if (!(command
instanceof LocalCommand
)) {
210 throw new UserErrorException("Command only works in multi-account mode");
213 handleLocalCommand((LocalCommand
) command
, account
, signalAccountFiles
, outputWriter
);
216 private void handleProvisioningCommand(
217 final ProvisioningCommand command
,
218 final SignalAccountFiles signalAccountFiles
,
219 final OutputWriter outputWriter
220 ) throws CommandException
{
221 var pm
= signalAccountFiles
.initProvisioningManager();
222 command
.handleCommand(ns
, pm
, outputWriter
);
225 private void handleProvisioningCommand(
226 final ProvisioningCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
227 ) throws CommandException
, DBusException
{
228 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
229 DbusConfig
.getObjectPath(),
230 SignalControl
.class);
231 final var provisioningManager
= new DbusProvisioningManagerImpl(signalControl
, dBusConn
);
233 c
.handleCommand(ns
, provisioningManager
, outputWriter
);
234 } catch (UnsupportedOperationException e
) {
235 throw new UserErrorException("Command is not yet implemented via dbus", e
);
236 } catch (DBusExecutionException e
) {
237 throw new UnexpectedErrorException(e
.getMessage(), e
);
241 private void handleRegistrationCommand(
242 final RegistrationCommand command
, final String account
, final SignalAccountFiles signalAccountFiles
243 ) throws CommandException
{
244 try (final var manager
= loadRegistrationManager(account
, signalAccountFiles
)) {
245 command
.handleCommand(ns
, manager
);
246 } catch (IOException e
) {
247 logger
.warn("Cleanup failed", e
);
251 private void handleRegistrationCommand(
252 final RegistrationCommand c
, String account
, final DBusConnection dBusConn
, final OutputWriter outputWriter
253 ) throws CommandException
, DBusException
{
254 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
255 DbusConfig
.getObjectPath(),
256 SignalControl
.class);
257 try (final var registrationManager
= new DbusRegistrationManagerImpl(account
, signalControl
, dBusConn
)) {
258 c
.handleCommand(ns
, registrationManager
);
259 } catch (UnsupportedOperationException e
) {
260 throw new UserErrorException("Command is not yet implemented via dbus", e
);
261 } catch (DBusExecutionException e
) {
262 throw new UnexpectedErrorException(e
.getMessage(), e
);
266 private void handleLocalCommand(
267 final LocalCommand command
,
268 final String account
,
269 final SignalAccountFiles signalAccountFiles
,
270 final OutputWriter outputWriter
271 ) throws CommandException
{
272 try (var m
= loadManager(account
, signalAccountFiles
)) {
273 command
.handleCommand(ns
, m
, outputWriter
);
274 } catch (IOException e
) {
275 logger
.warn("Cleanup failed", e
);
279 private void handleLocalCommand(
280 final LocalCommand c
,
281 String accountObjectPath
,
282 final DBusConnection dBusConn
,
283 final OutputWriter outputWriter
284 ) throws CommandException
, DBusException
{
285 var signal
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(), accountObjectPath
, Signal
.class);
286 try (final var m
= new DbusManagerImpl(signal
, dBusConn
)) {
287 c
.handleCommand(ns
, m
, outputWriter
);
288 } catch (UnsupportedOperationException e
) {
289 throw new UserErrorException("Command is not yet implemented via dbus", e
);
290 } catch (DBusExecutionException e
) {
291 throw new UnexpectedErrorException(e
.getMessage(), e
);
295 private void handleMultiLocalCommand(
296 final MultiLocalCommand command
,
297 final SignalAccountFiles signalAccountFiles
,
298 final OutputWriter outputWriter
299 ) throws CommandException
{
300 try (var multiAccountManager
= signalAccountFiles
.initMultiAccountManager()) {
301 command
.handleCommand(ns
, multiAccountManager
, outputWriter
);
305 private void handleMultiLocalCommand(
306 final MultiLocalCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
307 ) throws CommandException
, DBusException
{
308 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
309 DbusConfig
.getObjectPath(),
310 SignalControl
.class);
311 try (final var multiAccountManager
= new DbusMultiAccountManagerImpl(signalControl
, dBusConn
)) {
312 c
.handleCommand(ns
, multiAccountManager
, outputWriter
);
313 } catch (UnsupportedOperationException e
) {
314 throw new UserErrorException("Command is not yet implemented via dbus", e
);
318 private RegistrationManager
loadRegistrationManager(
319 final String account
, final SignalAccountFiles signalAccountFiles
320 ) throws UnexpectedErrorException
{
322 return signalAccountFiles
.initRegistrationManager(account
);
323 } catch (Throwable e
) {
324 throw new UnexpectedErrorException("Error loading or creating state file: "
327 + e
.getClass().getSimpleName()
332 private Manager
loadManager(
333 final String account
, final SignalAccountFiles signalAccountFiles
334 ) throws CommandException
{
335 logger
.trace("Loading account file for {}", account
);
337 return signalAccountFiles
.initManager(account
);
338 } catch (NotRegisteredException e
) {
339 throw new UserErrorException("User " + account
+ " is not registered.");
340 } catch (AccountCheckException ace
) {
341 if (ace
.getCause() instanceof IOException e
) {
342 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
344 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
347 } catch (Throwable e
) {
348 throw new UnexpectedErrorException("Error loading state file for user "
353 + e
.getClass().getSimpleName()
358 private void initDbusClient(
359 final Command command
, final String account
, final boolean systemBus
, final OutputWriter outputWriter
360 ) throws CommandException
{
362 DBusConnection
.DBusBusType busType
;
364 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
366 busType
= DBusConnection
.DBusBusType
.SESSION
;
368 try (var dBusConn
= DBusConnectionBuilder
.forType(busType
).build()) {
369 if (command
instanceof ProvisioningCommand c
) {
370 if (account
!= null) {
371 throw new UserErrorException("You cannot specify a account (phone number) when linking");
374 handleProvisioningCommand(c
, dBusConn
, outputWriter
);
378 if (account
== null && command
instanceof MultiLocalCommand c
) {
379 handleMultiLocalCommand(c
, dBusConn
, outputWriter
);
382 if (account
!= null && command
instanceof RegistrationCommand c
) {
383 handleRegistrationCommand(c
, account
, dBusConn
, outputWriter
);
386 if (!(command
instanceof LocalCommand localCommand
)) {
387 throw new UserErrorException("Command only works in multi-account mode");
390 var accountObjectPath
= account
== null ?
tryGetSingleAccountObjectPath(dBusConn
) : null;
391 if (accountObjectPath
== null) {
392 accountObjectPath
= DbusConfig
.getObjectPath(account
);
394 handleLocalCommand(localCommand
, accountObjectPath
, dBusConn
, outputWriter
);
396 } catch (ServiceUnknown e
) {
397 throw new UserErrorException("signal-cli DBus daemon not running on "
398 + (systemBus ?
"system" : "session")
400 + e
.getMessage(), e
);
401 } catch (DBusExecutionException
| DBusException
| IOException e
) {
402 throw new UnexpectedErrorException("Dbus client failed: " + e
.getMessage(), e
);
406 private String
tryGetSingleAccountObjectPath(final DBusConnection dBusConn
) throws DBusException
, CommandException
{
407 var control
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
408 DbusConfig
.getObjectPath(),
409 SignalControl
.class);
411 final var accounts
= control
.listAccounts();
412 if (accounts
.size() == 0) {
413 throw new UserErrorException("No local users found, you first need to register or link an account");
414 } else if (accounts
.size() > 1) {
415 throw new UserErrorException(
416 "Multiple users found, you need to specify an account (phone number) with -a");
419 return accounts
.get(0).getPath();
420 } catch (UnknownMethod e
) {
421 // dbus daemon not running in multi-account mode
427 * @return the default data directory to be used by signal-cli.
429 private static File
getDefaultConfigPath() {
430 return new File(IOUtils
.getDataHomeDir(), "signal-cli");