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
.signal
.commands
.Command
;
10 import org
.asamk
.signal
.commands
.Commands
;
11 import org
.asamk
.signal
.commands
.LocalCommand
;
12 import org
.asamk
.signal
.commands
.MultiLocalCommand
;
13 import org
.asamk
.signal
.commands
.ProvisioningCommand
;
14 import org
.asamk
.signal
.commands
.RegistrationCommand
;
15 import org
.asamk
.signal
.commands
.exceptions
.CommandException
;
16 import org
.asamk
.signal
.commands
.exceptions
.IOErrorException
;
17 import org
.asamk
.signal
.commands
.exceptions
.UnexpectedErrorException
;
18 import org
.asamk
.signal
.commands
.exceptions
.UserErrorException
;
19 import org
.asamk
.signal
.dbus
.DbusManagerImpl
;
20 import org
.asamk
.signal
.manager
.Manager
;
21 import org
.asamk
.signal
.manager
.MultiAccountManagerImpl
;
22 import org
.asamk
.signal
.manager
.NotRegisteredException
;
23 import org
.asamk
.signal
.manager
.ProvisioningManager
;
24 import org
.asamk
.signal
.manager
.RegistrationManager
;
25 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
26 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
27 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
28 import org
.asamk
.signal
.output
.JsonWriterImpl
;
29 import org
.asamk
.signal
.output
.OutputWriter
;
30 import org
.asamk
.signal
.output
.PlainTextWriterImpl
;
31 import org
.asamk
.signal
.util
.IOUtils
;
32 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
33 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
34 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
35 import org
.slf4j
.Logger
;
36 import org
.slf4j
.LoggerFactory
;
38 import java
.io
.BufferedWriter
;
40 import java
.io
.IOException
;
41 import java
.io
.OutputStreamWriter
;
42 import java
.nio
.charset
.Charset
;
43 import java
.util
.ArrayList
;
44 import java
.util
.List
;
46 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
50 private final static Logger logger
= LoggerFactory
.getLogger(App
.class);
52 private final Namespace ns
;
54 static ArgumentParser
buildArgumentParser() {
55 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
56 .includeArgumentNamesAsKeysInResult(true)
59 .description("Commandline interface for Signal.")
60 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
62 parser
.addArgument("-v", "--version").help("Show package version.").action(Arguments
.version());
63 parser
.addArgument("--verbose")
64 .help("Raise log level and include lib signal logs.")
65 .action(Arguments
.storeTrue());
66 parser
.addArgument("-c", "--config")
67 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
69 parser
.addArgument("-a", "--account", "-u", "--username")
70 .help("Specify your phone number, that will be your identifier.");
72 var mut
= parser
.addMutuallyExclusiveGroup();
73 mut
.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
74 mut
.addArgument("--dbus-system")
75 .dest("global-dbus-system")
76 .help("Make request via system dbus.")
77 .action(Arguments
.storeTrue());
79 parser
.addArgument("-o", "--output")
80 .help("Choose to output in plain text or JSON")
81 .type(Arguments
.enumStringType(OutputType
.class));
83 parser
.addArgument("--service-environment")
84 .help("Choose the server environment to use.")
85 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
86 .setDefault(ServiceEnvironmentCli
.LIVE
);
88 parser
.addArgument("--trust-new-identities")
89 .help("Choose when to trust new identities.")
90 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
91 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
93 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
95 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
96 var subparser
= subparsers
.addParser(key
);
97 value
.attachToSubparser(subparser
);
103 public App(final Namespace ns
) {
107 public void init() throws CommandException
{
108 var commandKey
= ns
.getString("command");
109 var command
= Commands
.getCommand(commandKey
);
110 if (command
== null) {
111 throw new UserErrorException("Command not implemented!");
114 var outputTypeInput
= ns
.<OutputType
>get("output");
115 var outputType
= outputTypeInput
== null
116 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
118 var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, Charset
.defaultCharset()));
119 var outputWriter
= outputType
== null
121 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
123 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
124 throw new UserErrorException("Command doesn't support output type " + outputType
);
127 var account
= ns
.getString("account");
129 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
130 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
131 if (useDbus
|| useDbusSystem
) {
132 // If account is null, it will connect to the default object path
133 initDbusClient(command
, account
, useDbusSystem
, outputWriter
);
138 var config
= ns
.getString("config");
139 if (config
!= null) {
140 dataPath
= new File(config
);
142 dataPath
= getDefaultDataPath();
145 if (!ServiceConfig
.isSignalClientAvailable()) {
146 throw new UserErrorException("Missing required native library dependency: libsignal-client");
149 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
150 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
151 ? ServiceEnvironment
.LIVE
152 : ServiceEnvironment
.SANDBOX
;
154 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
155 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
156 ? TrustNewIdentity
.ON_FIRST_USE
157 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
159 if (command
instanceof ProvisioningCommand provisioningCommand
) {
160 if (account
!= null) {
161 throw new UserErrorException("You cannot specify a account (phone number) when linking");
164 handleProvisioningCommand(provisioningCommand
, dataPath
, serviceEnvironment
, outputWriter
);
168 if (account
== null) {
169 var accounts
= Manager
.getAllLocalAccountNumbers(dataPath
);
171 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
172 handleMultiLocalCommand(multiLocalCommand
,
181 if (accounts
.size() == 0) {
182 throw new UserErrorException("No local users found, you first need to register or link an account");
183 } else if (accounts
.size() > 1) {
184 throw new UserErrorException(
185 "Multiple users found, you need to specify an account (phone number) with -a");
188 account
= accounts
.get(0);
189 } else if (!Manager
.isValidNumber(account
, null)) {
190 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
193 if (command
instanceof RegistrationCommand registrationCommand
) {
194 handleRegistrationCommand(registrationCommand
, account
, dataPath
, serviceEnvironment
);
198 if (!(command
instanceof LocalCommand
)) {
199 throw new UserErrorException("Command only works via dbus");
202 handleLocalCommand((LocalCommand
) command
,
210 private void handleProvisioningCommand(
211 final ProvisioningCommand command
,
213 final ServiceEnvironment serviceEnvironment
,
214 final OutputWriter outputWriter
215 ) throws CommandException
{
216 var pm
= ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
217 command
.handleCommand(ns
, pm
, outputWriter
);
220 private void handleRegistrationCommand(
221 final RegistrationCommand command
,
222 final String account
,
224 final ServiceEnvironment serviceEnvironment
225 ) throws CommandException
{
226 final RegistrationManager manager
;
228 manager
= RegistrationManager
.init(account
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
229 } catch (Throwable e
) {
230 throw new UnexpectedErrorException("Error loading or creating state file: "
233 + e
.getClass().getSimpleName()
237 command
.handleCommand(ns
, manager
);
238 } catch (IOException e
) {
239 logger
.warn("Cleanup failed", e
);
243 private void handleLocalCommand(
244 final LocalCommand command
,
245 final String account
,
247 final ServiceEnvironment serviceEnvironment
,
248 final OutputWriter outputWriter
,
249 final TrustNewIdentity trustNewIdentity
250 ) throws CommandException
{
251 try (var m
= loadManager(account
, dataPath
, serviceEnvironment
, trustNewIdentity
)) {
252 command
.handleCommand(ns
, m
, outputWriter
);
253 } catch (IOException e
) {
254 logger
.warn("Cleanup failed", e
);
258 private void handleMultiLocalCommand(
259 final MultiLocalCommand command
,
261 final ServiceEnvironment serviceEnvironment
,
262 final List
<String
> accounts
,
263 final OutputWriter outputWriter
,
264 final TrustNewIdentity trustNewIdentity
265 ) throws CommandException
{
266 final var managers
= new ArrayList
<Manager
>();
267 for (String a
: accounts
) {
269 managers
.add(loadManager(a
, dataPath
, serviceEnvironment
, trustNewIdentity
));
270 } catch (CommandException e
) {
271 logger
.warn("Ignoring {}: {}", a
, e
.getMessage());
275 try (var multiAccountManager
= new MultiAccountManagerImpl(managers
,
278 BaseConfig
.USER_AGENT
)) {
279 command
.handleCommand(ns
, multiAccountManager
, outputWriter
);
283 private Manager
loadManager(
284 final String account
,
286 final ServiceEnvironment serviceEnvironment
,
287 final TrustNewIdentity trustNewIdentity
288 ) throws CommandException
{
291 manager
= Manager
.init(account
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
, trustNewIdentity
);
292 } catch (NotRegisteredException e
) {
293 throw new UserErrorException("User " + account
+ " is not registered.");
294 } catch (Throwable e
) {
295 throw new UnexpectedErrorException("Error loading state file for user "
300 + e
.getClass().getSimpleName()
305 manager
.checkAccountState();
306 } catch (IOException e
) {
309 } catch (IOException ie
) {
310 logger
.warn("Failed to close broken account", ie
);
312 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
318 private void initDbusClient(
319 final Command command
, final String account
, final boolean systemBus
, final OutputWriter outputWriter
320 ) throws CommandException
{
322 DBusConnection
.DBusBusType busType
;
324 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
326 busType
= DBusConnection
.DBusBusType
.SESSION
;
328 try (var dBusConn
= DBusConnection
.getConnection(busType
)) {
329 var ts
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
330 DbusConfig
.getObjectPath(account
),
333 handleCommand(command
, ts
, dBusConn
, outputWriter
);
335 } catch (DBusException
| IOException e
) {
336 logger
.error("Dbus client failed", e
);
337 throw new UnexpectedErrorException("Dbus client failed", e
);
341 private void handleCommand(
342 Command command
, Signal ts
, DBusConnection dBusConn
, OutputWriter outputWriter
343 ) throws CommandException
{
344 if (command
instanceof LocalCommand localCommand
) {
345 try (final var m
= new DbusManagerImpl(ts
, dBusConn
)) {
346 localCommand
.handleCommand(ns
, m
, outputWriter
);
347 } catch (UnsupportedOperationException e
) {
348 throw new UserErrorException("Command is not yet implemented via dbus", e
);
349 } catch (IOException
| DBusExecutionException e
) {
350 throw new UnexpectedErrorException(e
.getMessage(), e
);
353 throw new UserErrorException("Command is not yet implemented via dbus");
358 * @return the default data directory to be used by signal-cli.
360 private static File
getDefaultDataPath() {
361 return new File(IOUtils
.getDataHomeDir(), "signal-cli");