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
;
49 import java
.nio
.charset
.Charset
;
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
, Charset
.defaultCharset()));
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 var accounts
= signalAccountFiles
.getAllLocalAccountNumbers();
193 if (accounts
.size() == 0) {
194 throw new UserErrorException("No local users found, you first need to register or link an account");
195 } else if (accounts
.size() > 1) {
196 throw new UserErrorException(
197 "Multiple users found, you need to specify an account (phone number) with -a");
200 account
= accounts
.stream().findFirst().get();
201 } else if (!Manager
.isValidNumber(account
, null)) {
202 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
205 if (command
instanceof RegistrationCommand registrationCommand
) {
206 handleRegistrationCommand(registrationCommand
, account
, signalAccountFiles
);
210 if (!(command
instanceof LocalCommand
)) {
211 throw new UserErrorException("Command only works in multi-account mode");
214 handleLocalCommand((LocalCommand
) command
, account
, signalAccountFiles
, outputWriter
);
217 private void handleProvisioningCommand(
218 final ProvisioningCommand command
,
219 final SignalAccountFiles signalAccountFiles
,
220 final OutputWriter outputWriter
221 ) throws CommandException
{
222 var pm
= signalAccountFiles
.initProvisioningManager();
223 command
.handleCommand(ns
, pm
, outputWriter
);
226 private void handleProvisioningCommand(
227 final ProvisioningCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
228 ) throws CommandException
, DBusException
{
229 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
230 DbusConfig
.getObjectPath(),
231 SignalControl
.class);
232 final var provisioningManager
= new DbusProvisioningManagerImpl(signalControl
, dBusConn
);
234 c
.handleCommand(ns
, provisioningManager
, outputWriter
);
235 } catch (UnsupportedOperationException e
) {
236 throw new UserErrorException("Command is not yet implemented via dbus", e
);
237 } catch (DBusExecutionException e
) {
238 throw new UnexpectedErrorException(e
.getMessage(), e
);
242 private void handleRegistrationCommand(
243 final RegistrationCommand command
, final String account
, final SignalAccountFiles signalAccountFiles
244 ) throws CommandException
{
245 try (final var manager
= loadRegistrationManager(account
, signalAccountFiles
)) {
246 command
.handleCommand(ns
, manager
);
247 } catch (IOException e
) {
248 logger
.warn("Cleanup failed", e
);
252 private void handleRegistrationCommand(
253 final RegistrationCommand c
, String account
, final DBusConnection dBusConn
, final OutputWriter outputWriter
254 ) throws CommandException
, DBusException
{
255 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
256 DbusConfig
.getObjectPath(),
257 SignalControl
.class);
258 try (final var registrationManager
= new DbusRegistrationManagerImpl(account
, signalControl
, dBusConn
)) {
259 c
.handleCommand(ns
, registrationManager
);
260 } catch (UnsupportedOperationException e
) {
261 throw new UserErrorException("Command is not yet implemented via dbus", e
);
262 } catch (DBusExecutionException e
) {
263 throw new UnexpectedErrorException(e
.getMessage(), e
);
267 private void handleLocalCommand(
268 final LocalCommand command
,
269 final String account
,
270 final SignalAccountFiles signalAccountFiles
,
271 final OutputWriter outputWriter
272 ) throws CommandException
{
273 try (var m
= loadManager(account
, signalAccountFiles
)) {
274 command
.handleCommand(ns
, m
, outputWriter
);
275 } catch (IOException e
) {
276 logger
.warn("Cleanup failed", e
);
280 private void handleLocalCommand(
281 final LocalCommand c
,
282 String accountObjectPath
,
283 final DBusConnection dBusConn
,
284 final OutputWriter outputWriter
285 ) throws CommandException
, DBusException
{
286 var signal
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(), accountObjectPath
, Signal
.class);
287 try (final var m
= new DbusManagerImpl(signal
, dBusConn
)) {
288 c
.handleCommand(ns
, m
, outputWriter
);
289 } catch (UnsupportedOperationException e
) {
290 throw new UserErrorException("Command is not yet implemented via dbus", e
);
291 } catch (DBusExecutionException e
) {
292 throw new UnexpectedErrorException(e
.getMessage(), e
);
296 private void handleMultiLocalCommand(
297 final MultiLocalCommand command
,
298 final SignalAccountFiles signalAccountFiles
,
299 final OutputWriter outputWriter
300 ) throws CommandException
{
301 try (var multiAccountManager
= signalAccountFiles
.initMultiAccountManager()) {
302 command
.handleCommand(ns
, multiAccountManager
, outputWriter
);
306 private void handleMultiLocalCommand(
307 final MultiLocalCommand c
, final DBusConnection dBusConn
, final OutputWriter outputWriter
308 ) throws CommandException
, DBusException
{
309 final var signalControl
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
310 DbusConfig
.getObjectPath(),
311 SignalControl
.class);
312 try (final var multiAccountManager
= new DbusMultiAccountManagerImpl(signalControl
, dBusConn
)) {
313 c
.handleCommand(ns
, multiAccountManager
, outputWriter
);
314 } catch (UnsupportedOperationException e
) {
315 throw new UserErrorException("Command is not yet implemented via dbus", e
);
319 private RegistrationManager
loadRegistrationManager(
320 final String account
, final SignalAccountFiles signalAccountFiles
321 ) throws UnexpectedErrorException
{
323 return signalAccountFiles
.initRegistrationManager(account
);
324 } catch (Throwable e
) {
325 throw new UnexpectedErrorException("Error loading or creating state file: "
328 + e
.getClass().getSimpleName()
333 private Manager
loadManager(
334 final String account
, final SignalAccountFiles signalAccountFiles
335 ) throws CommandException
{
336 logger
.trace("Loading account file for {}", account
);
338 return signalAccountFiles
.initManager(account
);
339 } catch (NotRegisteredException e
) {
340 throw new UserErrorException("User " + account
+ " is not registered.");
341 } catch (AccountCheckException ace
) {
342 if (ace
.getCause() instanceof IOException e
) {
343 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
345 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
348 } catch (Throwable e
) {
349 throw new UnexpectedErrorException("Error loading state file for user "
354 + e
.getClass().getSimpleName()
359 private void initDbusClient(
360 final Command command
, final String account
, final boolean systemBus
, final OutputWriter outputWriter
361 ) throws CommandException
{
363 DBusConnection
.DBusBusType busType
;
365 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
367 busType
= DBusConnection
.DBusBusType
.SESSION
;
369 try (var dBusConn
= DBusConnectionBuilder
.forType(busType
).build()) {
370 if (command
instanceof ProvisioningCommand c
) {
371 if (account
!= null) {
372 throw new UserErrorException("You cannot specify a account (phone number) when linking");
375 handleProvisioningCommand(c
, dBusConn
, outputWriter
);
379 if (account
== null && command
instanceof MultiLocalCommand c
) {
380 handleMultiLocalCommand(c
, dBusConn
, outputWriter
);
383 if (account
!= null && command
instanceof RegistrationCommand c
) {
384 handleRegistrationCommand(c
, account
, dBusConn
, outputWriter
);
387 if (!(command
instanceof LocalCommand localCommand
)) {
388 throw new UserErrorException("Command only works in multi-account mode");
391 var accountObjectPath
= account
== null ?
tryGetSingleAccountObjectPath(dBusConn
) : null;
392 if (accountObjectPath
== null) {
393 accountObjectPath
= DbusConfig
.getObjectPath(account
);
395 handleLocalCommand(localCommand
, accountObjectPath
, dBusConn
, outputWriter
);
397 } catch (ServiceUnknown e
) {
398 throw new UserErrorException("signal-cli DBus daemon not running on "
399 + (systemBus ?
"system" : "session")
401 + e
.getMessage(), e
);
402 } catch (DBusExecutionException
| DBusException
| IOException e
) {
403 throw new UnexpectedErrorException("Dbus client failed: " + e
.getMessage(), e
);
407 private String
tryGetSingleAccountObjectPath(final DBusConnection dBusConn
) throws DBusException
, CommandException
{
408 var control
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
409 DbusConfig
.getObjectPath(),
410 SignalControl
.class);
412 final var accounts
= control
.listAccounts();
413 if (accounts
.size() == 0) {
414 throw new UserErrorException("No local users found, you first need to register or link an account");
415 } else if (accounts
.size() > 1) {
416 throw new UserErrorException(
417 "Multiple users found, you need to specify an account (phone number) with -a");
420 return accounts
.get(0).getPath();
421 } catch (UnknownMethod e
) {
422 // dbus daemon not running in multi-account mode
428 * @return the default data directory to be used by signal-cli.
430 private static File
getDefaultConfigPath() {
431 return new File(IOUtils
.getDataHomeDir(), "signal-cli");