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))
71 .setDefault(OutputType
.PLAIN_TEXT
);
73 parser
.addArgument("--service-environment")
74 .help("Choose the server environment to use.")
75 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
76 .setDefault(ServiceEnvironmentCli
.LIVE
);
78 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
80 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
81 var subparser
= subparsers
.addParser(key
);
82 value
.attachToSubparser(subparser
);
88 public App(final Namespace ns
) {
92 public void init() throws CommandException
{
93 var outputType
= ns
.<OutputType
>get("output");
94 var outputWriter
= outputType
== OutputType
.JSON
95 ?
new JsonWriterImpl(System
.out
)
96 : new PlainTextWriterImpl(System
.out
);
98 var commandKey
= ns
.getString("command");
99 var command
= Commands
.getCommand(commandKey
);
100 if (command
== null) {
101 throw new UserErrorException("Command not implemented!");
104 if (!command
.getSupportedOutputTypes().contains(outputType
)) {
105 throw new UserErrorException("Command doesn't support output type " + outputType
.toString());
108 var username
= ns
.getString("username");
110 final var useDbus
= ns
.getBoolean("dbus");
111 final var useDbusSystem
= ns
.getBoolean("dbus-system");
112 if (useDbus
|| useDbusSystem
) {
113 // If username is null, it will connect to the default object path
114 initDbusClient(command
, username
, useDbusSystem
, outputWriter
);
119 var config
= ns
.getString("config");
120 if (config
!= null) {
121 dataPath
= new File(config
);
123 dataPath
= getDefaultDataPath();
126 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
127 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
128 ? ServiceEnvironment
.LIVE
129 : ServiceEnvironment
.SANDBOX
;
131 if (!ServiceConfig
.getCapabilities().isGv2()) {
132 logger
.warn("WARNING: Support for new group V2 is disabled,"
133 + " because the required native library dependency is missing: libzkgroup");
136 if (!ServiceConfig
.isSignalClientAvailable()) {
137 throw new UserErrorException("Missing required native library dependency: libsignal-client");
140 if (command
instanceof ProvisioningCommand
) {
141 if (username
!= null) {
142 throw new UserErrorException("You cannot specify a username (phone number) when linking");
145 handleProvisioningCommand((ProvisioningCommand
) command
, dataPath
, serviceEnvironment
, outputWriter
);
149 if (username
== null) {
150 var usernames
= Manager
.getAllLocalUsernames(dataPath
);
152 if (command
instanceof MultiLocalCommand
) {
153 handleMultiLocalCommand((MultiLocalCommand
) command
,
161 if (usernames
.size() == 0) {
162 throw new UserErrorException("No local users found, you first need to register or link an account");
163 } else if (usernames
.size() > 1) {
164 throw new UserErrorException(
165 "Multiple users found, you need to specify a username (phone number) with -u");
168 username
= usernames
.get(0);
169 } else if (!PhoneNumberFormatter
.isValidNumber(username
, null)) {
170 throw new UserErrorException("Invalid username (phone number), make sure you include the country code.");
173 if (command
instanceof RegistrationCommand
) {
174 handleRegistrationCommand((RegistrationCommand
) command
, username
, dataPath
, serviceEnvironment
);
178 if (!(command
instanceof LocalCommand
)) {
179 throw new UserErrorException("Command only works via dbus");
182 handleLocalCommand((LocalCommand
) command
, username
, dataPath
, serviceEnvironment
, outputWriter
);
185 private void handleProvisioningCommand(
186 final ProvisioningCommand command
,
188 final ServiceEnvironment serviceEnvironment
,
189 final OutputWriter outputWriter
190 ) throws CommandException
{
191 var pm
= ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
192 command
.handleCommand(ns
, pm
, outputWriter
);
195 private void handleRegistrationCommand(
196 final RegistrationCommand command
,
197 final String username
,
199 final ServiceEnvironment serviceEnvironment
200 ) throws CommandException
{
201 final RegistrationManager manager
;
203 manager
= RegistrationManager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
204 } catch (Throwable e
) {
205 throw new UnexpectedErrorException("Error loading or creating state file: "
208 + e
.getClass().getSimpleName()
211 try (var m
= manager
) {
212 command
.handleCommand(ns
, m
);
213 } catch (IOException e
) {
214 logger
.warn("Cleanup failed", e
);
218 private void handleLocalCommand(
219 final LocalCommand command
,
220 final String username
,
222 final ServiceEnvironment serviceEnvironment
,
223 final OutputWriter outputWriter
224 ) throws CommandException
{
225 try (var m
= loadManager(username
, dataPath
, serviceEnvironment
)) {
226 command
.handleCommand(ns
, m
, outputWriter
);
227 } catch (IOException e
) {
228 logger
.warn("Cleanup failed", e
);
232 private void handleMultiLocalCommand(
233 final MultiLocalCommand command
,
235 final ServiceEnvironment serviceEnvironment
,
236 final List
<String
> usernames
,
237 final OutputWriter outputWriter
238 ) throws CommandException
{
239 final var managers
= new ArrayList
<Manager
>();
240 for (String u
: usernames
) {
242 managers
.add(loadManager(u
, dataPath
, serviceEnvironment
));
243 } catch (CommandException e
) {
244 logger
.warn("Ignoring {}: {}", u
, e
.getMessage());
248 command
.handleCommand(ns
, managers
, new SignalCreator() {
250 public ProvisioningManager
getNewProvisioningManager() {
251 return ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
255 public RegistrationManager
getNewRegistrationManager(String username
) throws IOException
{
256 return RegistrationManager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
260 for (var m
: managers
) {
263 } catch (IOException e
) {
264 logger
.warn("Cleanup failed", e
);
269 private Manager
loadManager(
270 final String username
, final File dataPath
, final ServiceEnvironment serviceEnvironment
271 ) throws CommandException
{
274 manager
= Manager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
275 } catch (NotRegisteredException e
) {
276 throw new UserErrorException("User " + username
+ " is not registered.");
277 } catch (Throwable e
) {
278 logger
.debug("Loading state file failed", e
);
279 throw new UnexpectedErrorException("Error loading state file for user "
284 + e
.getClass().getSimpleName()
289 manager
.checkAccountState();
290 } catch (IOException e
) {
291 throw new UnexpectedErrorException("Error while checking account " + username
+ ": " + e
.getMessage());
297 private void initDbusClient(
298 final Command command
, final String username
, final boolean systemBus
, final OutputWriter outputWriter
299 ) throws CommandException
{
301 DBusConnection
.DBusBusType busType
;
303 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
305 busType
= DBusConnection
.DBusBusType
.SESSION
;
307 try (var dBusConn
= DBusConnection
.getConnection(busType
)) {
308 var ts
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
309 DbusConfig
.getObjectPath(username
),
312 handleCommand(command
, ts
, dBusConn
, outputWriter
);
314 } catch (DBusException
| IOException e
) {
315 logger
.error("Dbus client failed", e
);
316 throw new UnexpectedErrorException("Dbus client failed");
320 private void handleCommand(
321 Command command
, Signal ts
, DBusConnection dBusConn
, OutputWriter outputWriter
322 ) throws CommandException
{
323 if (command
instanceof ExtendedDbusCommand
) {
324 ((ExtendedDbusCommand
) command
).handleCommand(ns
, ts
, dBusConn
, outputWriter
);
325 } else if (command
instanceof DbusCommand
) {
326 ((DbusCommand
) command
).handleCommand(ns
, ts
, outputWriter
);
328 throw new UserErrorException("Command is not yet implemented via dbus");
333 * @return the default data directory to be used by signal-cli.
335 private static File
getDefaultDataPath() {
336 return new File(IOUtils
.getDataHomeDir(), "signal-cli");