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
.ExtendedDbusCommand
;
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
.SignalCreator
;
17 import org
.asamk
.signal
.commands
.exceptions
.CommandException
;
18 import org
.asamk
.signal
.commands
.exceptions
.IOErrorException
;
19 import org
.asamk
.signal
.commands
.exceptions
.UnexpectedErrorException
;
20 import org
.asamk
.signal
.commands
.exceptions
.UserErrorException
;
21 import org
.asamk
.signal
.dbus
.DbusManagerImpl
;
22 import org
.asamk
.signal
.manager
.Manager
;
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
.util
.IOUtils
;
30 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
31 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
32 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
33 import org
.slf4j
.Logger
;
34 import org
.slf4j
.LoggerFactory
;
35 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
38 import java
.io
.IOException
;
39 import java
.util
.ArrayList
;
40 import java
.util
.List
;
42 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
46 private final static Logger logger
= LoggerFactory
.getLogger(App
.class);
48 private final Namespace ns
;
50 static ArgumentParser
buildArgumentParser() {
51 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
52 .includeArgumentNamesAsKeysInResult(true)
55 .description("Commandline interface for Signal.")
56 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
58 parser
.addArgument("-v", "--version").help("Show package version.").action(Arguments
.version());
59 parser
.addArgument("--verbose")
60 .help("Raise log level and include lib signal logs.")
61 .action(Arguments
.storeTrue());
62 parser
.addArgument("--config")
63 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
65 parser
.addArgument("-u", "--username").help("Specify your phone number, that will be your identifier.");
67 var mut
= parser
.addMutuallyExclusiveGroup();
68 mut
.addArgument("--dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
69 mut
.addArgument("--dbus-system").help("Make request via system dbus.").action(Arguments
.storeTrue());
71 parser
.addArgument("-o", "--output")
72 .help("Choose to output in plain text or JSON")
73 .type(Arguments
.enumStringType(OutputType
.class));
75 parser
.addArgument("--service-environment")
76 .help("Choose the server environment to use.")
77 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
78 .setDefault(ServiceEnvironmentCli
.LIVE
);
80 parser
.addArgument("--trust-new-identities")
81 .help("Choose when to trust new identities.")
82 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
83 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
85 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
87 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
88 var subparser
= subparsers
.addParser(key
);
89 value
.attachToSubparser(subparser
);
95 public App(final Namespace ns
) {
99 public void init() throws CommandException
{
100 var commandKey
= ns
.getString("command");
101 var command
= Commands
.getCommand(commandKey
);
102 if (command
== null) {
103 throw new UserErrorException("Command not implemented!");
106 var outputTypeInput
= ns
.<OutputType
>get("output");
107 var outputType
= outputTypeInput
== null
108 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
110 var outputWriter
= outputType
== null
112 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(System
.out
) : new PlainTextWriterImpl(System
.out
);
114 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
115 throw new UserErrorException("Command doesn't support output type " + outputType
);
118 var username
= ns
.getString("username");
120 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("dbus"));
121 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("dbus-system"));
122 if (useDbus
|| useDbusSystem
) {
123 // If username is null, it will connect to the default object path
124 initDbusClient(command
, username
, useDbusSystem
, outputWriter
);
129 var config
= ns
.getString("config");
130 if (config
!= null) {
131 dataPath
= new File(config
);
133 dataPath
= getDefaultDataPath();
136 if (!ServiceConfig
.getCapabilities().isGv2()) {
137 logger
.warn("WARNING: Support for new group V2 is disabled,"
138 + " because the required native library dependency is missing: libzkgroup");
141 if (!ServiceConfig
.isSignalClientAvailable()) {
142 throw new UserErrorException("Missing required native library dependency: libsignal-client");
145 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
146 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
147 ? ServiceEnvironment
.LIVE
148 : ServiceEnvironment
.SANDBOX
;
150 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
151 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
152 ? TrustNewIdentity
.ON_FIRST_USE
153 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
155 if (command
instanceof ProvisioningCommand
) {
156 if (username
!= null) {
157 throw new UserErrorException("You cannot specify a username (phone number) when linking");
160 handleProvisioningCommand((ProvisioningCommand
) command
, dataPath
, serviceEnvironment
, outputWriter
);
164 if (username
== null) {
165 var usernames
= Manager
.getAllLocalNumbers(dataPath
);
167 if (command
instanceof MultiLocalCommand
) {
168 handleMultiLocalCommand((MultiLocalCommand
) command
,
177 if (usernames
.size() == 0) {
178 throw new UserErrorException("No local users found, you first need to register or link an account");
179 } else if (usernames
.size() > 1) {
180 throw new UserErrorException(
181 "Multiple users found, you need to specify a username (phone number) with -u");
184 username
= usernames
.get(0);
185 } else if (!PhoneNumberFormatter
.isValidNumber(username
, null)) {
186 throw new UserErrorException("Invalid username (phone number), make sure you include the country code.");
189 if (command
instanceof RegistrationCommand
) {
190 handleRegistrationCommand((RegistrationCommand
) command
, username
, dataPath
, serviceEnvironment
);
194 if (!(command
instanceof LocalCommand
)) {
195 throw new UserErrorException("Command only works via dbus");
198 handleLocalCommand((LocalCommand
) command
,
206 private void handleProvisioningCommand(
207 final ProvisioningCommand command
,
209 final ServiceEnvironment serviceEnvironment
,
210 final OutputWriter outputWriter
211 ) throws CommandException
{
212 var pm
= ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
213 command
.handleCommand(ns
, pm
, outputWriter
);
216 private void handleRegistrationCommand(
217 final RegistrationCommand command
,
218 final String username
,
220 final ServiceEnvironment serviceEnvironment
221 ) throws CommandException
{
222 final RegistrationManager manager
;
224 manager
= RegistrationManager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
225 } catch (Throwable e
) {
226 throw new UnexpectedErrorException("Error loading or creating state file: "
229 + e
.getClass().getSimpleName()
232 try (var m
= manager
) {
233 command
.handleCommand(ns
, m
);
234 } catch (IOException e
) {
235 logger
.warn("Cleanup failed", e
);
239 private void handleLocalCommand(
240 final LocalCommand command
,
241 final String username
,
243 final ServiceEnvironment serviceEnvironment
,
244 final OutputWriter outputWriter
,
245 final TrustNewIdentity trustNewIdentity
246 ) throws CommandException
{
247 try (var m
= loadManager(username
, dataPath
, serviceEnvironment
, trustNewIdentity
)) {
248 command
.handleCommand(ns
, m
, outputWriter
);
249 } catch (IOException e
) {
250 logger
.warn("Cleanup failed", e
);
254 private void handleMultiLocalCommand(
255 final MultiLocalCommand command
,
257 final ServiceEnvironment serviceEnvironment
,
258 final List
<String
> usernames
,
259 final OutputWriter outputWriter
,
260 final TrustNewIdentity trustNewIdentity
261 ) throws CommandException
{
262 final var managers
= new ArrayList
<Manager
>();
263 for (String u
: usernames
) {
265 managers
.add(loadManager(u
, dataPath
, serviceEnvironment
, trustNewIdentity
));
266 } catch (CommandException e
) {
267 logger
.warn("Ignoring {}: {}", u
, e
.getMessage());
271 command
.handleCommand(ns
, managers
, new SignalCreator() {
273 public ProvisioningManager
getNewProvisioningManager() {
274 return ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
278 public RegistrationManager
getNewRegistrationManager(String username
) throws IOException
{
279 return RegistrationManager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
283 for (var m
: managers
) {
286 } catch (IOException e
) {
287 logger
.warn("Cleanup failed", e
);
292 private Manager
loadManager(
293 final String username
,
295 final ServiceEnvironment serviceEnvironment
,
296 final TrustNewIdentity trustNewIdentity
297 ) throws CommandException
{
300 manager
= Manager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
, trustNewIdentity
);
301 } catch (NotRegisteredException e
) {
302 throw new UserErrorException("User " + username
+ " is not registered.");
303 } catch (Throwable e
) {
304 throw new UnexpectedErrorException("Error loading state file for user "
309 + e
.getClass().getSimpleName()
314 manager
.checkAccountState();
315 } catch (IOException e
) {
316 throw new IOErrorException("Error while checking account " + username
+ ": " + e
.getMessage(), e
);
322 private void initDbusClient(
323 final Command command
, final String username
, final boolean systemBus
, final OutputWriter outputWriter
324 ) throws CommandException
{
326 DBusConnection
.DBusBusType busType
;
328 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
330 busType
= DBusConnection
.DBusBusType
.SESSION
;
332 try (var dBusConn
= DBusConnection
.getConnection(busType
)) {
333 var ts
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
334 DbusConfig
.getObjectPath(username
),
337 handleCommand(command
, ts
, dBusConn
, outputWriter
);
339 } catch (DBusException
| IOException e
) {
340 logger
.error("Dbus client failed", e
);
341 throw new UnexpectedErrorException("Dbus client failed", e
);
345 private void handleCommand(
346 Command command
, Signal ts
, DBusConnection dBusConn
, OutputWriter outputWriter
347 ) throws CommandException
{
348 if (command
instanceof ExtendedDbusCommand
) {
349 ((ExtendedDbusCommand
) command
).handleCommand(ns
, ts
, dBusConn
, outputWriter
);
350 } else if (command
instanceof LocalCommand
) {
352 ((LocalCommand
) command
).handleCommand(ns
, new DbusManagerImpl(ts
, dBusConn
), outputWriter
);
353 } catch (UnsupportedOperationException e
) {
354 throw new UserErrorException("Command is not yet implemented via dbus", e
);
355 } catch (DBusExecutionException e
) {
356 throw new UnexpectedErrorException(e
.getMessage(), e
);
359 throw new UserErrorException("Command is not yet implemented via dbus");
364 * @return the default data directory to be used by signal-cli.
366 private static File
getDefaultDataPath() {
367 return new File(IOUtils
.getDataHomeDir(), "signal-cli");