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
, outputWriter
);
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
);
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
);
149 if (username
== null) {
150 var usernames
= Manager
.getAllLocalUsernames(dataPath
);
152 if (command
instanceof MultiLocalCommand
) {
153 handleMultiLocalCommand((MultiLocalCommand
) command
, dataPath
, serviceEnvironment
, usernames
);
157 if (usernames
.size() == 0) {
158 throw new UserErrorException("No local users found, you first need to register or link an account");
159 } else if (usernames
.size() > 1) {
160 throw new UserErrorException(
161 "Multiple users found, you need to specify a username (phone number) with -u");
164 username
= usernames
.get(0);
165 } else if (!PhoneNumberFormatter
.isValidNumber(username
, null)) {
166 throw new UserErrorException("Invalid username (phone number), make sure you include the country code.");
169 if (command
instanceof RegistrationCommand
) {
170 handleRegistrationCommand((RegistrationCommand
) command
, username
, dataPath
, serviceEnvironment
);
174 if (!(command
instanceof LocalCommand
)) {
175 throw new UserErrorException("Command only works via dbus");
178 handleLocalCommand((LocalCommand
) command
, username
, dataPath
, serviceEnvironment
);
181 private void handleProvisioningCommand(
182 final ProvisioningCommand command
, final File dataPath
, final ServiceEnvironment serviceEnvironment
183 ) throws CommandException
{
184 var pm
= ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
185 command
.handleCommand(ns
, pm
);
188 private void handleRegistrationCommand(
189 final RegistrationCommand command
,
190 final String username
,
192 final ServiceEnvironment serviceEnvironment
193 ) throws CommandException
{
194 final RegistrationManager manager
;
196 manager
= RegistrationManager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
197 } catch (Throwable e
) {
198 throw new UnexpectedErrorException("Error loading or creating state file: "
201 + e
.getClass().getSimpleName()
204 try (var m
= manager
) {
205 command
.handleCommand(ns
, m
);
206 } catch (IOException e
) {
207 logger
.warn("Cleanup failed", e
);
211 private void handleLocalCommand(
212 final LocalCommand command
,
213 final String username
,
215 final ServiceEnvironment serviceEnvironment
216 ) throws CommandException
{
217 try (var m
= loadManager(username
, dataPath
, serviceEnvironment
)) {
218 command
.handleCommand(ns
, m
);
219 } catch (IOException e
) {
220 logger
.warn("Cleanup failed", e
);
224 private void handleMultiLocalCommand(
225 final MultiLocalCommand command
,
227 final ServiceEnvironment serviceEnvironment
,
228 final List
<String
> usernames
229 ) throws CommandException
{
230 final var managers
= new ArrayList
<Manager
>();
231 for (String u
: usernames
) {
233 managers
.add(loadManager(u
, dataPath
, serviceEnvironment
));
234 } catch (CommandException e
) {
235 logger
.warn("Ignoring {}: {}", u
, e
.getMessage());
239 command
.handleCommand(ns
, managers
, new SignalCreator() {
241 public ProvisioningManager
getNewProvisioningManager() {
242 return ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
246 public RegistrationManager
getNewRegistrationManager(String username
) throws IOException
{
247 return RegistrationManager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
251 for (var m
: managers
) {
254 } catch (IOException e
) {
255 logger
.warn("Cleanup failed", e
);
260 private Manager
loadManager(
261 final String username
, final File dataPath
, final ServiceEnvironment serviceEnvironment
262 ) throws CommandException
{
265 manager
= Manager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
266 } catch (NotRegisteredException e
) {
267 throw new UserErrorException("User " + username
+ " is not registered.");
268 } catch (Throwable e
) {
269 logger
.debug("Loading state file failed", e
);
270 throw new UnexpectedErrorException("Error loading state file for user "
275 + e
.getClass().getSimpleName()
280 manager
.checkAccountState();
281 } catch (IOException e
) {
282 throw new UnexpectedErrorException("Error while checking account " + username
+ ": " + e
.getMessage());
288 private void initDbusClient(
289 final Command command
, final String username
, final boolean systemBus
290 ) throws CommandException
{
292 DBusConnection
.DBusBusType busType
;
294 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
296 busType
= DBusConnection
.DBusBusType
.SESSION
;
298 try (var dBusConn
= DBusConnection
.getConnection(busType
)) {
299 var ts
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
300 DbusConfig
.getObjectPath(username
),
303 handleCommand(command
, ts
, dBusConn
);
305 } catch (DBusException
| IOException e
) {
306 logger
.error("Dbus client failed", e
);
307 throw new UnexpectedErrorException("Dbus client failed");
311 private void handleCommand(Command command
, Signal ts
, DBusConnection dBusConn
) throws CommandException
{
312 if (command
instanceof ExtendedDbusCommand
) {
313 ((ExtendedDbusCommand
) command
).handleCommand(ns
, ts
, dBusConn
);
314 } else if (command
instanceof DbusCommand
) {
315 ((DbusCommand
) command
).handleCommand(ns
, ts
);
317 throw new UserErrorException("Command is not yet implemented via dbus");
322 * @return the default data directory to be used by signal-cli.
324 private static File
getDefaultDataPath() {
325 return new File(IOUtils
.getDataHomeDir(), "signal-cli");