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("--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
.isZkgroupAvailable()) {
146 logger
.warn("WARNING: Support for new group V2 is disabled,"
147 + " because the required native library dependency is missing: libzkgroup");
150 if (!ServiceConfig
.isSignalClientAvailable()) {
151 throw new UserErrorException("Missing required native library dependency: libsignal-client");
154 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
155 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
156 ? ServiceEnvironment
.LIVE
157 : ServiceEnvironment
.SANDBOX
;
159 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
160 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
161 ? TrustNewIdentity
.ON_FIRST_USE
162 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
164 if (command
instanceof ProvisioningCommand provisioningCommand
) {
165 if (account
!= null) {
166 throw new UserErrorException("You cannot specify a account (phone number) when linking");
169 handleProvisioningCommand(provisioningCommand
, dataPath
, serviceEnvironment
, outputWriter
);
173 if (account
== null) {
174 var accounts
= Manager
.getAllLocalAccountNumbers(dataPath
);
176 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
177 handleMultiLocalCommand(multiLocalCommand
,
186 if (accounts
.size() == 0) {
187 throw new UserErrorException("No local users found, you first need to register or link an account");
188 } else if (accounts
.size() > 1) {
189 throw new UserErrorException(
190 "Multiple users found, you need to specify an account (phone number) with -a");
193 account
= accounts
.get(0);
194 } else if (!Manager
.isValidNumber(account
, null)) {
195 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
198 if (command
instanceof RegistrationCommand registrationCommand
) {
199 handleRegistrationCommand(registrationCommand
, account
, dataPath
, serviceEnvironment
);
203 if (!(command
instanceof LocalCommand
)) {
204 throw new UserErrorException("Command only works via dbus");
207 handleLocalCommand((LocalCommand
) command
,
215 private void handleProvisioningCommand(
216 final ProvisioningCommand command
,
218 final ServiceEnvironment serviceEnvironment
,
219 final OutputWriter outputWriter
220 ) throws CommandException
{
221 var pm
= ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
222 command
.handleCommand(ns
, pm
, outputWriter
);
225 private void handleRegistrationCommand(
226 final RegistrationCommand command
,
227 final String account
,
229 final ServiceEnvironment serviceEnvironment
230 ) throws CommandException
{
231 final RegistrationManager manager
;
233 manager
= RegistrationManager
.init(account
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
234 } catch (Throwable e
) {
235 throw new UnexpectedErrorException("Error loading or creating state file: "
238 + e
.getClass().getSimpleName()
242 command
.handleCommand(ns
, manager
);
243 } catch (IOException e
) {
244 logger
.warn("Cleanup failed", e
);
248 private void handleLocalCommand(
249 final LocalCommand command
,
250 final String account
,
252 final ServiceEnvironment serviceEnvironment
,
253 final OutputWriter outputWriter
,
254 final TrustNewIdentity trustNewIdentity
255 ) throws CommandException
{
256 try (var m
= loadManager(account
, dataPath
, serviceEnvironment
, trustNewIdentity
)) {
257 command
.handleCommand(ns
, m
, outputWriter
);
258 } catch (IOException e
) {
259 logger
.warn("Cleanup failed", e
);
263 private void handleMultiLocalCommand(
264 final MultiLocalCommand command
,
266 final ServiceEnvironment serviceEnvironment
,
267 final List
<String
> accounts
,
268 final OutputWriter outputWriter
,
269 final TrustNewIdentity trustNewIdentity
270 ) throws CommandException
{
271 final var managers
= new ArrayList
<Manager
>();
272 for (String a
: accounts
) {
274 managers
.add(loadManager(a
, dataPath
, serviceEnvironment
, trustNewIdentity
));
275 } catch (CommandException e
) {
276 logger
.warn("Ignoring {}: {}", a
, e
.getMessage());
280 try (var multiAccountManager
= new MultiAccountManagerImpl(managers
,
283 BaseConfig
.USER_AGENT
)) {
284 command
.handleCommand(ns
, multiAccountManager
, outputWriter
);
288 private Manager
loadManager(
289 final String account
,
291 final ServiceEnvironment serviceEnvironment
,
292 final TrustNewIdentity trustNewIdentity
293 ) throws CommandException
{
296 manager
= Manager
.init(account
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
, trustNewIdentity
);
297 } catch (NotRegisteredException e
) {
298 throw new UserErrorException("User " + account
+ " is not registered.");
299 } catch (Throwable e
) {
300 throw new UnexpectedErrorException("Error loading state file for user "
305 + e
.getClass().getSimpleName()
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 ts
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
335 DbusConfig
.getObjectPath(account
),
338 handleCommand(command
, ts
, dBusConn
, outputWriter
);
340 } catch (DBusException
| IOException e
) {
341 logger
.error("Dbus client failed", e
);
342 throw new UnexpectedErrorException("Dbus client failed", e
);
346 private void handleCommand(
347 Command command
, Signal ts
, DBusConnection dBusConn
, OutputWriter outputWriter
348 ) throws CommandException
{
349 if (command
instanceof LocalCommand localCommand
) {
350 try (final var m
= new DbusManagerImpl(ts
, dBusConn
)) {
351 localCommand
.handleCommand(ns
, m
, outputWriter
);
352 } catch (UnsupportedOperationException e
) {
353 throw new UserErrorException("Command is not yet implemented via dbus", e
);
354 } catch (IOException
| DBusExecutionException e
) {
355 throw new UnexpectedErrorException(e
.getMessage(), e
);
358 throw new UserErrorException("Command is not yet implemented via dbus");
363 * @return the default data directory to be used by signal-cli.
365 private static File
getDefaultDataPath() {
366 return new File(IOUtils
.getDataHomeDir(), "signal-cli");