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
.DbusCommand
;
12 import org
.asamk
.signal
.commands
.ExtendedDbusCommand
;
13 import org
.asamk
.signal
.commands
.LocalCommand
;
14 import org
.asamk
.signal
.commands
.MultiLocalCommand
;
15 import org
.asamk
.signal
.commands
.ProvisioningCommand
;
16 import org
.asamk
.signal
.commands
.RegistrationCommand
;
17 import org
.asamk
.signal
.commands
.SignalCreator
;
18 import org
.asamk
.signal
.commands
.exceptions
.CommandException
;
19 import org
.asamk
.signal
.commands
.exceptions
.UnexpectedErrorException
;
20 import org
.asamk
.signal
.commands
.exceptions
.UserErrorException
;
21 import org
.asamk
.signal
.manager
.Manager
;
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
.util
.IOUtils
;
28 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
29 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
30 import org
.slf4j
.Logger
;
31 import org
.slf4j
.LoggerFactory
;
32 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
35 import java
.io
.IOException
;
36 import java
.util
.ArrayList
;
37 import java
.util
.List
;
39 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
43 private final static Logger logger
= LoggerFactory
.getLogger(App
.class);
45 private final Namespace ns
;
47 static ArgumentParser
buildArgumentParser() {
48 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
49 .includeArgumentNamesAsKeysInResult(true)
52 .description("Commandline interface for Signal.")
53 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
55 parser
.addArgument("-v", "--version").help("Show package version.").action(Arguments
.version());
56 parser
.addArgument("--verbose")
57 .help("Raise log level and include lib signal logs.")
58 .action(Arguments
.storeTrue());
59 parser
.addArgument("--config")
60 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
62 parser
.addArgument("-u", "--username").help("Specify your phone number, that will be your identifier.");
64 var mut
= parser
.addMutuallyExclusiveGroup();
65 mut
.addArgument("--dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
66 mut
.addArgument("--dbus-system").help("Make request via system dbus.").action(Arguments
.storeTrue());
68 parser
.addArgument("-o", "--output")
69 .help("Choose to output in plain text or JSON")
70 .type(Arguments
.enumStringType(OutputType
.class));
72 parser
.addArgument("--service-environment")
73 .help("Choose the server environment to use.")
74 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
75 .setDefault(ServiceEnvironmentCli
.LIVE
);
77 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
79 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
80 var subparser
= subparsers
.addParser(key
);
81 value
.attachToSubparser(subparser
);
87 public App(final Namespace ns
) {
91 public void init() throws CommandException
{
92 var commandKey
= ns
.getString("command");
93 var command
= Commands
.getCommand(commandKey
);
94 if (command
== null) {
95 throw new UserErrorException("Command not implemented!");
98 var outputTypeInput
= ns
.<OutputType
>get("output");
99 var outputType
= outputTypeInput
== null
100 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
102 var outputWriter
= outputType
== null
104 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(System
.out
) : new PlainTextWriterImpl(System
.out
);
106 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
107 throw new UserErrorException("Command doesn't support output type " + outputType
);
110 var username
= ns
.getString("username");
112 final var useDbus
= ns
.getBoolean("dbus");
113 final var useDbusSystem
= ns
.getBoolean("dbus-system");
114 if (useDbus
|| useDbusSystem
) {
115 // If username is null, it will connect to the default object path
116 initDbusClient(command
, username
, useDbusSystem
, outputWriter
);
121 var config
= ns
.getString("config");
122 if (config
!= null) {
123 dataPath
= new File(config
);
125 dataPath
= getDefaultDataPath();
128 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
129 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
130 ? ServiceEnvironment
.LIVE
131 : ServiceEnvironment
.SANDBOX
;
133 if (!ServiceConfig
.getCapabilities().isGv2()) {
134 logger
.warn("WARNING: Support for new group V2 is disabled,"
135 + " because the required native library dependency is missing: libzkgroup");
138 if (!ServiceConfig
.isSignalClientAvailable()) {
139 throw new UserErrorException("Missing required native library dependency: libsignal-client");
142 if (command
instanceof ProvisioningCommand
) {
143 if (username
!= null) {
144 throw new UserErrorException("You cannot specify a username (phone number) when linking");
147 handleProvisioningCommand((ProvisioningCommand
) command
, dataPath
, serviceEnvironment
, outputWriter
);
151 if (username
== null) {
152 var usernames
= Manager
.getAllLocalUsernames(dataPath
);
154 if (command
instanceof MultiLocalCommand
) {
155 handleMultiLocalCommand((MultiLocalCommand
) command
,
163 if (usernames
.size() == 0) {
164 throw new UserErrorException("No local users found, you first need to register or link an account");
165 } else if (usernames
.size() > 1) {
166 throw new UserErrorException(
167 "Multiple users found, you need to specify a username (phone number) with -u");
170 username
= usernames
.get(0);
171 } else if (!PhoneNumberFormatter
.isValidNumber(username
, null)) {
172 throw new UserErrorException("Invalid username (phone number), make sure you include the country code.");
175 if (command
instanceof RegistrationCommand
) {
176 handleRegistrationCommand((RegistrationCommand
) command
, username
, dataPath
, serviceEnvironment
);
180 if (!(command
instanceof LocalCommand
)) {
181 throw new UserErrorException("Command only works via dbus");
184 handleLocalCommand((LocalCommand
) command
, username
, dataPath
, serviceEnvironment
, outputWriter
);
187 private void handleProvisioningCommand(
188 final ProvisioningCommand command
,
190 final ServiceEnvironment serviceEnvironment
,
191 final OutputWriter outputWriter
192 ) throws CommandException
{
193 var pm
= ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
194 command
.handleCommand(ns
, pm
, outputWriter
);
197 private void handleRegistrationCommand(
198 final RegistrationCommand command
,
199 final String username
,
201 final ServiceEnvironment serviceEnvironment
202 ) throws CommandException
{
203 final RegistrationManager manager
;
205 manager
= RegistrationManager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
206 } catch (Throwable e
) {
207 throw new UnexpectedErrorException("Error loading or creating state file: "
210 + e
.getClass().getSimpleName()
213 try (var m
= manager
) {
214 command
.handleCommand(ns
, m
);
215 } catch (IOException e
) {
216 logger
.warn("Cleanup failed", e
);
220 private void handleLocalCommand(
221 final LocalCommand command
,
222 final String username
,
224 final ServiceEnvironment serviceEnvironment
,
225 final OutputWriter outputWriter
226 ) throws CommandException
{
227 try (var m
= loadManager(username
, dataPath
, serviceEnvironment
)) {
228 command
.handleCommand(ns
, m
, outputWriter
);
229 } catch (IOException e
) {
230 logger
.warn("Cleanup failed", e
);
234 private void handleMultiLocalCommand(
235 final MultiLocalCommand command
,
237 final ServiceEnvironment serviceEnvironment
,
238 final List
<String
> usernames
,
239 final OutputWriter outputWriter
240 ) throws CommandException
{
241 final var managers
= new ArrayList
<Manager
>();
242 for (String u
: usernames
) {
244 managers
.add(loadManager(u
, dataPath
, serviceEnvironment
));
245 } catch (CommandException e
) {
246 logger
.warn("Ignoring {}: {}", u
, e
.getMessage());
250 command
.handleCommand(ns
, managers
, new SignalCreator() {
252 public ProvisioningManager
getNewProvisioningManager() {
253 return ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
257 public RegistrationManager
getNewRegistrationManager(String username
) throws IOException
{
258 return RegistrationManager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
262 for (var m
: managers
) {
265 } catch (IOException e
) {
266 logger
.warn("Cleanup failed", e
);
271 private Manager
loadManager(
272 final String username
, final File dataPath
, final ServiceEnvironment serviceEnvironment
273 ) throws CommandException
{
276 manager
= Manager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
277 } catch (NotRegisteredException e
) {
278 throw new UserErrorException("User " + username
+ " is not registered.");
279 } catch (Throwable e
) {
280 logger
.debug("Loading state file failed", e
);
281 throw new UnexpectedErrorException("Error loading state file for user "
286 + e
.getClass().getSimpleName()
291 manager
.checkAccountState();
292 } catch (IOException e
) {
293 throw new UnexpectedErrorException("Error while checking account " + username
+ ": " + e
.getMessage());
299 private void initDbusClient(
300 final Command command
, final String username
, final boolean systemBus
, final OutputWriter outputWriter
301 ) throws CommandException
{
303 DBusConnection
.DBusBusType busType
;
305 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
307 busType
= DBusConnection
.DBusBusType
.SESSION
;
309 try (var dBusConn
= DBusConnection
.getConnection(busType
)) {
310 var ts
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
311 DbusConfig
.getObjectPath(username
),
314 handleCommand(command
, ts
, dBusConn
, outputWriter
);
316 } catch (DBusException
| IOException e
) {
317 logger
.error("Dbus client failed", e
);
318 throw new UnexpectedErrorException("Dbus client failed");
322 private void handleCommand(
323 Command command
, Signal ts
, DBusConnection dBusConn
, OutputWriter outputWriter
324 ) throws CommandException
{
325 if (command
instanceof ExtendedDbusCommand
) {
326 ((ExtendedDbusCommand
) command
).handleCommand(ns
, ts
, dBusConn
, outputWriter
);
327 } else if (command
instanceof DbusCommand
) {
328 ((DbusCommand
) command
).handleCommand(ns
, ts
, outputWriter
);
330 throw new UserErrorException("Command is not yet implemented via dbus");
335 * @return the default data directory to be used by signal-cli.
337 private static File
getDefaultDataPath() {
338 return new File(IOUtils
.getDataHomeDir(), "signal-cli");