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
.util
.IOUtils
;
29 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
30 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
31 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
32 import org
.slf4j
.Logger
;
33 import org
.slf4j
.LoggerFactory
;
35 import java
.io
.BufferedWriter
;
37 import java
.io
.IOException
;
38 import java
.io
.OutputStreamWriter
;
39 import java
.nio
.charset
.Charset
;
40 import java
.util
.ArrayList
;
41 import java
.util
.List
;
43 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
47 private final static Logger logger
= LoggerFactory
.getLogger(App
.class);
49 private final Namespace ns
;
51 static ArgumentParser
buildArgumentParser() {
52 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
53 .includeArgumentNamesAsKeysInResult(true)
56 .description("Commandline interface for Signal.")
57 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
59 parser
.addArgument("-v", "--version").help("Show package version.").action(Arguments
.version());
60 parser
.addArgument("--verbose")
61 .help("Raise log level and include lib signal logs.")
62 .action(Arguments
.storeTrue());
63 parser
.addArgument("--config")
64 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
66 parser
.addArgument("-a", "--account", "-u", "--username")
67 .help("Specify your phone number, that will be your identifier.");
69 var mut
= parser
.addMutuallyExclusiveGroup();
70 mut
.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
71 mut
.addArgument("--dbus-system")
72 .dest("global-dbus-system")
73 .help("Make request via system dbus.")
74 .action(Arguments
.storeTrue());
76 parser
.addArgument("-o", "--output")
77 .help("Choose to output in plain text or JSON")
78 .type(Arguments
.enumStringType(OutputType
.class));
80 parser
.addArgument("--service-environment")
81 .help("Choose the server environment to use.")
82 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
83 .setDefault(ServiceEnvironmentCli
.LIVE
);
85 parser
.addArgument("--trust-new-identities")
86 .help("Choose when to trust new identities.")
87 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
88 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
90 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
92 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
93 var subparser
= subparsers
.addParser(key
);
94 value
.attachToSubparser(subparser
);
100 public App(final Namespace ns
) {
104 public void init() throws CommandException
{
105 var commandKey
= ns
.getString("command");
106 var command
= Commands
.getCommand(commandKey
);
107 if (command
== null) {
108 throw new UserErrorException("Command not implemented!");
111 var outputTypeInput
= ns
.<OutputType
>get("output");
112 var outputType
= outputTypeInput
== null
113 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
115 var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, Charset
.defaultCharset()));
116 var outputWriter
= outputType
== null
118 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
120 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
121 throw new UserErrorException("Command doesn't support output type " + outputType
);
124 var account
= ns
.getString("account");
126 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
127 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
128 if (useDbus
|| useDbusSystem
) {
129 // If account is null, it will connect to the default object path
130 initDbusClient(command
, account
, useDbusSystem
, outputWriter
);
135 var config
= ns
.getString("config");
136 if (config
!= null) {
137 dataPath
= new File(config
);
139 dataPath
= getDefaultDataPath();
142 if (!ServiceConfig
.isZkgroupAvailable()) {
143 logger
.warn("WARNING: Support for new group V2 is disabled,"
144 + " because the required native library dependency is missing: libzkgroup");
147 if (!ServiceConfig
.isSignalClientAvailable()) {
148 throw new UserErrorException("Missing required native library dependency: libsignal-client");
151 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
152 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
153 ? ServiceEnvironment
.LIVE
154 : ServiceEnvironment
.SANDBOX
;
156 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
157 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
158 ? TrustNewIdentity
.ON_FIRST_USE
159 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
161 if (command
instanceof ProvisioningCommand provisioningCommand
) {
162 if (account
!= null) {
163 throw new UserErrorException("You cannot specify a account (phone number) when linking");
166 handleProvisioningCommand(provisioningCommand
, dataPath
, serviceEnvironment
, outputWriter
);
170 if (account
== null) {
171 var accounts
= Manager
.getAllLocalAccountNumbers(dataPath
);
173 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
174 handleMultiLocalCommand(multiLocalCommand
,
183 if (accounts
.size() == 0) {
184 throw new UserErrorException("No local users found, you first need to register or link an account");
185 } else if (accounts
.size() > 1) {
186 throw new UserErrorException(
187 "Multiple users found, you need to specify an account (phone number) with -a");
190 account
= accounts
.get(0);
191 } else if (!Manager
.isValidNumber(account
, null)) {
192 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
195 if (command
instanceof RegistrationCommand registrationCommand
) {
196 handleRegistrationCommand(registrationCommand
, account
, dataPath
, serviceEnvironment
);
200 if (!(command
instanceof LocalCommand
)) {
201 throw new UserErrorException("Command only works via dbus");
204 handleLocalCommand((LocalCommand
) command
,
212 private void handleProvisioningCommand(
213 final ProvisioningCommand command
,
215 final ServiceEnvironment serviceEnvironment
,
216 final OutputWriter outputWriter
217 ) throws CommandException
{
218 var pm
= ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
219 command
.handleCommand(ns
, pm
, outputWriter
);
222 private void handleRegistrationCommand(
223 final RegistrationCommand command
,
224 final String account
,
226 final ServiceEnvironment serviceEnvironment
227 ) throws CommandException
{
228 final RegistrationManager manager
;
230 manager
= RegistrationManager
.init(account
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
231 } catch (Throwable e
) {
232 throw new UnexpectedErrorException("Error loading or creating state file: "
235 + e
.getClass().getSimpleName()
239 command
.handleCommand(ns
, manager
);
240 } catch (IOException e
) {
241 logger
.warn("Cleanup failed", e
);
245 private void handleLocalCommand(
246 final LocalCommand command
,
247 final String account
,
249 final ServiceEnvironment serviceEnvironment
,
250 final OutputWriter outputWriter
,
251 final TrustNewIdentity trustNewIdentity
252 ) throws CommandException
{
253 try (var m
= loadManager(account
, dataPath
, serviceEnvironment
, trustNewIdentity
)) {
254 command
.handleCommand(ns
, m
, outputWriter
);
255 } catch (IOException e
) {
256 logger
.warn("Cleanup failed", e
);
260 private void handleMultiLocalCommand(
261 final MultiLocalCommand command
,
263 final ServiceEnvironment serviceEnvironment
,
264 final List
<String
> accounts
,
265 final OutputWriter outputWriter
,
266 final TrustNewIdentity trustNewIdentity
267 ) throws CommandException
{
268 final var managers
= new ArrayList
<Manager
>();
269 for (String a
: accounts
) {
271 managers
.add(loadManager(a
, dataPath
, serviceEnvironment
, trustNewIdentity
));
272 } catch (CommandException e
) {
273 logger
.warn("Ignoring {}: {}", a
, e
.getMessage());
277 try (var multiAccountManager
= new MultiAccountManagerImpl(managers
,
280 BaseConfig
.USER_AGENT
)) {
281 command
.handleCommand(ns
, multiAccountManager
, outputWriter
);
285 private Manager
loadManager(
286 final String account
,
288 final ServiceEnvironment serviceEnvironment
,
289 final TrustNewIdentity trustNewIdentity
290 ) throws CommandException
{
293 manager
= Manager
.init(account
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
, trustNewIdentity
);
294 } catch (NotRegisteredException e
) {
295 throw new UserErrorException("User " + account
+ " is not registered.");
296 } catch (Throwable e
) {
297 throw new UnexpectedErrorException("Error loading state file for user "
302 + e
.getClass().getSimpleName()
307 manager
.checkAccountState();
308 } catch (IOException e
) {
311 } catch (IOException ie
) {
312 logger
.warn("Failed to close broken account", ie
);
314 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
320 private void initDbusClient(
321 final Command command
, final String account
, final boolean systemBus
, final OutputWriter outputWriter
322 ) throws CommandException
{
324 DBusConnection
.DBusBusType busType
;
326 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
328 busType
= DBusConnection
.DBusBusType
.SESSION
;
330 try (var dBusConn
= DBusConnection
.getConnection(busType
)) {
331 var ts
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
332 DbusConfig
.getObjectPath(account
),
335 handleCommand(command
, ts
, dBusConn
, outputWriter
);
337 } catch (DBusException
| IOException e
) {
338 logger
.error("Dbus client failed", e
);
339 throw new UnexpectedErrorException("Dbus client failed", e
);
343 private void handleCommand(
344 Command command
, Signal ts
, DBusConnection dBusConn
, OutputWriter outputWriter
345 ) throws CommandException
{
346 if (command
instanceof LocalCommand localCommand
) {
347 try (final var m
= new DbusManagerImpl(ts
, dBusConn
)) {
348 localCommand
.handleCommand(ns
, m
, outputWriter
);
349 } catch (UnsupportedOperationException e
) {
350 throw new UserErrorException("Command is not yet implemented via dbus", e
);
351 } catch (IOException
| DBusExecutionException e
) {
352 throw new UnexpectedErrorException(e
.getMessage(), e
);
355 throw new UserErrorException("Command is not yet implemented via dbus");
360 * @return the default data directory to be used by signal-cli.
362 private static File
getDefaultDataPath() {
363 return new File(IOUtils
.getDataHomeDir(), "signal-cli");