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
.manager
.Manager
;
22 import org
.asamk
.signal
.manager
.MultiAccountManagerImpl
;
23 import org
.asamk
.signal
.manager
.NotRegisteredException
;
24 import org
.asamk
.signal
.manager
.ProvisioningManager
;
25 import org
.asamk
.signal
.manager
.RegistrationManager
;
26 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
27 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
28 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
29 import org
.asamk
.signal
.output
.JsonWriterImpl
;
30 import org
.asamk
.signal
.output
.OutputWriter
;
31 import org
.asamk
.signal
.output
.PlainTextWriterImpl
;
32 import org
.asamk
.signal
.util
.IOUtils
;
33 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
34 import org
.freedesktop
.dbus
.errors
.ServiceUnknown
;
35 import org
.freedesktop
.dbus
.errors
.UnknownMethod
;
36 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
37 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
38 import org
.slf4j
.Logger
;
39 import org
.slf4j
.LoggerFactory
;
41 import java
.io
.BufferedWriter
;
43 import java
.io
.IOException
;
44 import java
.io
.OutputStreamWriter
;
45 import java
.nio
.charset
.Charset
;
46 import java
.util
.ArrayList
;
47 import java
.util
.List
;
49 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
53 private final static Logger logger
= LoggerFactory
.getLogger(App
.class);
55 private final Namespace ns
;
57 static ArgumentParser
buildArgumentParser() {
58 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
59 .includeArgumentNamesAsKeysInResult(true)
62 .description("Commandline interface for Signal.")
63 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
65 parser
.addArgument("-v", "--version").help("Show package version.").action(Arguments
.version());
66 parser
.addArgument("--verbose")
67 .help("Raise log level and include lib signal logs.")
68 .action(Arguments
.storeTrue());
69 parser
.addArgument("-c", "--config")
70 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
72 parser
.addArgument("-a", "--account", "-u", "--username")
73 .help("Specify your phone number, that will be your identifier.");
75 var mut
= parser
.addMutuallyExclusiveGroup();
76 mut
.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
77 mut
.addArgument("--dbus-system")
78 .dest("global-dbus-system")
79 .help("Make request via system dbus.")
80 .action(Arguments
.storeTrue());
82 parser
.addArgument("-o", "--output")
83 .help("Choose to output in plain text or JSON")
84 .type(Arguments
.enumStringType(OutputType
.class));
86 parser
.addArgument("--service-environment")
87 .help("Choose the server environment to use.")
88 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
89 .setDefault(ServiceEnvironmentCli
.LIVE
);
91 parser
.addArgument("--trust-new-identities")
92 .help("Choose when to trust new identities.")
93 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
94 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
96 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
98 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
99 var subparser
= subparsers
.addParser(key
);
100 value
.attachToSubparser(subparser
);
106 public App(final Namespace ns
) {
110 public void init() throws CommandException
{
111 var commandKey
= ns
.getString("command");
112 var command
= Commands
.getCommand(commandKey
);
113 if (command
== null) {
114 throw new UserErrorException("Command not implemented!");
117 var outputTypeInput
= ns
.<OutputType
>get("output");
118 var outputType
= outputTypeInput
== null
119 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
121 var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, Charset
.defaultCharset()));
122 var outputWriter
= outputType
== null
124 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
126 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
127 throw new UserErrorException("Command doesn't support output type " + outputType
);
130 var account
= ns
.getString("account");
132 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
133 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
134 if (useDbus
|| useDbusSystem
) {
135 // If account is null, it will connect to the default object path
136 initDbusClient(command
, account
, useDbusSystem
, outputWriter
);
141 var config
= ns
.getString("config");
142 if (config
!= null) {
143 dataPath
= new File(config
);
145 dataPath
= getDefaultDataPath();
148 if (!ServiceConfig
.isSignalClientAvailable()) {
149 throw new UserErrorException("Missing required native library dependency: libsignal-client");
152 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
153 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
154 ? ServiceEnvironment
.LIVE
155 : ServiceEnvironment
.SANDBOX
;
157 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
158 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
159 ? TrustNewIdentity
.ON_FIRST_USE
160 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
162 if (command
instanceof ProvisioningCommand provisioningCommand
) {
163 if (account
!= null) {
164 throw new UserErrorException("You cannot specify a account (phone number) when linking");
167 handleProvisioningCommand(provisioningCommand
, dataPath
, serviceEnvironment
, outputWriter
);
171 if (account
== null) {
172 var accounts
= Manager
.getAllLocalAccountNumbers(dataPath
);
174 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
175 handleMultiLocalCommand(multiLocalCommand
,
184 if (accounts
.size() == 0) {
185 throw new UserErrorException("No local users found, you first need to register or link an account");
186 } else if (accounts
.size() > 1) {
187 throw new UserErrorException(
188 "Multiple users found, you need to specify an account (phone number) with -a");
191 account
= accounts
.get(0);
192 } else if (!Manager
.isValidNumber(account
, null)) {
193 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
196 if (command
instanceof RegistrationCommand registrationCommand
) {
197 handleRegistrationCommand(registrationCommand
, account
, dataPath
, serviceEnvironment
);
201 if (!(command
instanceof LocalCommand
)) {
202 throw new UserErrorException("Command only works in multi-account mode");
205 handleLocalCommand((LocalCommand
) command
,
213 private void handleProvisioningCommand(
214 final ProvisioningCommand command
,
216 final ServiceEnvironment serviceEnvironment
,
217 final OutputWriter outputWriter
218 ) throws CommandException
{
219 var pm
= ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
220 command
.handleCommand(ns
, pm
, outputWriter
);
223 private void handleRegistrationCommand(
224 final RegistrationCommand command
,
225 final String account
,
227 final ServiceEnvironment serviceEnvironment
228 ) throws CommandException
{
229 final RegistrationManager manager
;
231 manager
= RegistrationManager
.init(account
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
232 } catch (Throwable e
) {
233 throw new UnexpectedErrorException("Error loading or creating state file: "
236 + e
.getClass().getSimpleName()
240 command
.handleCommand(ns
, manager
);
241 } catch (IOException e
) {
242 logger
.warn("Cleanup failed", e
);
246 private void handleLocalCommand(
247 final LocalCommand command
,
248 final String account
,
250 final ServiceEnvironment serviceEnvironment
,
251 final OutputWriter outputWriter
,
252 final TrustNewIdentity trustNewIdentity
253 ) throws CommandException
{
254 try (var m
= loadManager(account
, dataPath
, serviceEnvironment
, trustNewIdentity
)) {
255 command
.handleCommand(ns
, m
, outputWriter
);
256 } catch (IOException e
) {
257 logger
.warn("Cleanup failed", e
);
261 private void handleMultiLocalCommand(
262 final MultiLocalCommand command
,
264 final ServiceEnvironment serviceEnvironment
,
265 final List
<String
> accounts
,
266 final OutputWriter outputWriter
,
267 final TrustNewIdentity trustNewIdentity
268 ) throws CommandException
{
269 final var managers
= new ArrayList
<Manager
>();
270 for (String a
: accounts
) {
272 managers
.add(loadManager(a
, dataPath
, serviceEnvironment
, trustNewIdentity
));
273 } catch (CommandException e
) {
274 logger
.warn("Ignoring {}: {}", a
, e
.getMessage());
278 try (var multiAccountManager
= new MultiAccountManagerImpl(managers
,
281 BaseConfig
.USER_AGENT
)) {
282 command
.handleCommand(ns
, multiAccountManager
, outputWriter
);
286 private Manager
loadManager(
287 final String account
,
289 final ServiceEnvironment serviceEnvironment
,
290 final TrustNewIdentity trustNewIdentity
291 ) throws CommandException
{
293 logger
.trace("Loading account file for {}", account
);
295 manager
= Manager
.init(account
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
, trustNewIdentity
);
296 } catch (NotRegisteredException e
) {
297 throw new UserErrorException("User " + account
+ " is not registered.");
298 } catch (Throwable e
) {
299 throw new UnexpectedErrorException("Error loading state file for user "
304 + e
.getClass().getSimpleName()
308 logger
.trace("Checking account state");
310 manager
.checkAccountState();
311 } catch (IOException e
) {
314 } catch (IOException ie
) {
315 logger
.warn("Failed to close broken account", ie
);
317 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
323 private void initDbusClient(
324 final Command command
, final String account
, final boolean systemBus
, final OutputWriter outputWriter
325 ) throws CommandException
{
327 DBusConnection
.DBusBusType busType
;
329 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
331 busType
= DBusConnection
.DBusBusType
.SESSION
;
333 try (var dBusConn
= DBusConnection
.getConnection(busType
)) {
334 var accountObjectPath
= account
== null ?
tryGetSingleAccountObjectPath(dBusConn
) : null;
335 if (accountObjectPath
== null) {
336 accountObjectPath
= DbusConfig
.getObjectPath(account
);
338 var ts
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(), accountObjectPath
, Signal
.class);
340 handleCommand(command
, ts
, dBusConn
, outputWriter
);
342 } catch (ServiceUnknown e
) {
343 throw new UserErrorException("signal-cli DBus daemon not running on "
344 + (systemBus ?
"system" : "session")
346 + e
.getMessage(), e
);
347 } catch (DBusExecutionException
| DBusException
| IOException e
) {
348 throw new UnexpectedErrorException("Dbus client failed: " + e
.getMessage(), e
);
352 private String
tryGetSingleAccountObjectPath(final DBusConnection dBusConn
) throws DBusException
, CommandException
{
353 var control
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
354 DbusConfig
.getObjectPath(),
355 SignalControl
.class);
357 final var accounts
= control
.listAccounts();
358 if (accounts
.size() == 0) {
359 throw new UserErrorException("No local users found, you first need to register or link an account");
360 } else if (accounts
.size() > 1) {
361 throw new UserErrorException(
362 "Multiple users found, you need to specify an account (phone number) with -a");
365 return accounts
.get(0).getPath();
366 } catch (UnknownMethod e
) {
367 // dbus daemon not running in multi-account mode
372 private void handleCommand(
373 Command command
, Signal ts
, DBusConnection dBusConn
, OutputWriter outputWriter
374 ) throws CommandException
{
375 if (command
instanceof LocalCommand localCommand
) {
376 try (final var m
= new DbusManagerImpl(ts
, dBusConn
)) {
377 localCommand
.handleCommand(ns
, m
, outputWriter
);
378 } catch (UnsupportedOperationException e
) {
379 throw new UserErrorException("Command is not yet implemented via dbus", e
);
380 } catch (IOException
| DBusExecutionException e
) {
381 throw new UnexpectedErrorException(e
.getMessage(), e
);
384 throw new UserErrorException("Command is not yet implemented via dbus");
389 * @return the default data directory to be used by signal-cli.
391 private static File
getDefaultDataPath() {
392 return new File(IOUtils
.getDataHomeDir(), "signal-cli");