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
.SignalCreator
;
16 import org
.asamk
.signal
.commands
.exceptions
.CommandException
;
17 import org
.asamk
.signal
.commands
.exceptions
.IOErrorException
;
18 import org
.asamk
.signal
.commands
.exceptions
.UnexpectedErrorException
;
19 import org
.asamk
.signal
.commands
.exceptions
.UserErrorException
;
20 import org
.asamk
.signal
.dbus
.DbusManagerImpl
;
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
.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("-u", "--username").help("Specify your phone number, that will be your identifier.");
68 var mut
= parser
.addMutuallyExclusiveGroup();
69 mut
.addArgument("--dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
70 mut
.addArgument("--dbus-system").help("Make request via system dbus.").action(Arguments
.storeTrue());
72 parser
.addArgument("-o", "--output")
73 .help("Choose to output in plain text or JSON")
74 .type(Arguments
.enumStringType(OutputType
.class));
76 parser
.addArgument("--service-environment")
77 .help("Choose the server environment to use.")
78 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
79 .setDefault(ServiceEnvironmentCli
.LIVE
);
81 parser
.addArgument("--trust-new-identities")
82 .help("Choose when to trust new identities.")
83 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
84 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
86 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
88 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
89 var subparser
= subparsers
.addParser(key
);
90 value
.attachToSubparser(subparser
);
96 public App(final Namespace ns
) {
100 public void init() throws CommandException
{
101 var commandKey
= ns
.getString("command");
102 var command
= Commands
.getCommand(commandKey
);
103 if (command
== null) {
104 throw new UserErrorException("Command not implemented!");
107 var outputTypeInput
= ns
.<OutputType
>get("output");
108 var outputType
= outputTypeInput
== null
109 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
111 var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, Charset
.defaultCharset()));
112 var outputWriter
= outputType
== null
114 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
116 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
117 throw new UserErrorException("Command doesn't support output type " + outputType
);
120 var username
= ns
.getString("username");
122 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("dbus"));
123 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("dbus-system"));
124 if (useDbus
|| useDbusSystem
) {
125 // If username is null, it will connect to the default object path
126 initDbusClient(command
, username
, useDbusSystem
, outputWriter
);
131 var config
= ns
.getString("config");
132 if (config
!= null) {
133 dataPath
= new File(config
);
135 dataPath
= getDefaultDataPath();
138 if (!ServiceConfig
.isZkgroupAvailable()) {
139 logger
.warn("WARNING: Support for new group V2 is disabled,"
140 + " because the required native library dependency is missing: libzkgroup");
143 if (!ServiceConfig
.isSignalClientAvailable()) {
144 throw new UserErrorException("Missing required native library dependency: libsignal-client");
147 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
148 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
149 ? ServiceEnvironment
.LIVE
150 : ServiceEnvironment
.SANDBOX
;
152 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
153 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
154 ? TrustNewIdentity
.ON_FIRST_USE
155 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
157 if (command
instanceof ProvisioningCommand provisioningCommand
) {
158 if (username
!= null) {
159 throw new UserErrorException("You cannot specify a username (phone number) when linking");
162 handleProvisioningCommand(provisioningCommand
, dataPath
, serviceEnvironment
, outputWriter
);
166 if (username
== null) {
167 var usernames
= Manager
.getAllLocalNumbers(dataPath
);
169 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
170 handleMultiLocalCommand(multiLocalCommand
,
179 if (usernames
.size() == 0) {
180 throw new UserErrorException("No local users found, you first need to register or link an account");
181 } else if (usernames
.size() > 1) {
182 throw new UserErrorException(
183 "Multiple users found, you need to specify a username (phone number) with -u");
186 username
= usernames
.get(0);
187 } else if (!Manager
.isValidNumber(username
, null)) {
188 throw new UserErrorException("Invalid username (phone number), make sure you include the country code.");
191 if (command
instanceof RegistrationCommand registrationCommand
) {
192 handleRegistrationCommand(registrationCommand
, username
, dataPath
, serviceEnvironment
);
196 if (!(command
instanceof LocalCommand
)) {
197 throw new UserErrorException("Command only works via dbus");
200 handleLocalCommand((LocalCommand
) command
,
208 private void handleProvisioningCommand(
209 final ProvisioningCommand command
,
211 final ServiceEnvironment serviceEnvironment
,
212 final OutputWriter outputWriter
213 ) throws CommandException
{
214 var pm
= ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
215 command
.handleCommand(ns
, pm
, outputWriter
);
218 private void handleRegistrationCommand(
219 final RegistrationCommand command
,
220 final String username
,
222 final ServiceEnvironment serviceEnvironment
223 ) throws CommandException
{
224 final RegistrationManager manager
;
226 manager
= RegistrationManager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
227 } catch (Throwable e
) {
228 throw new UnexpectedErrorException("Error loading or creating state file: "
231 + e
.getClass().getSimpleName()
234 try (var m
= manager
) {
235 command
.handleCommand(ns
, m
);
236 } catch (IOException e
) {
237 logger
.warn("Cleanup failed", e
);
241 private void handleLocalCommand(
242 final LocalCommand command
,
243 final String username
,
245 final ServiceEnvironment serviceEnvironment
,
246 final OutputWriter outputWriter
,
247 final TrustNewIdentity trustNewIdentity
248 ) throws CommandException
{
249 try (var m
= loadManager(username
, dataPath
, serviceEnvironment
, trustNewIdentity
)) {
250 command
.handleCommand(ns
, m
, outputWriter
);
251 } catch (IOException e
) {
252 logger
.warn("Cleanup failed", e
);
256 private void handleMultiLocalCommand(
257 final MultiLocalCommand command
,
259 final ServiceEnvironment serviceEnvironment
,
260 final List
<String
> usernames
,
261 final OutputWriter outputWriter
,
262 final TrustNewIdentity trustNewIdentity
263 ) throws CommandException
{
264 final var managers
= new ArrayList
<Manager
>();
265 for (String u
: usernames
) {
267 managers
.add(loadManager(u
, dataPath
, serviceEnvironment
, trustNewIdentity
));
268 } catch (CommandException e
) {
269 logger
.warn("Ignoring {}: {}", u
, e
.getMessage());
273 command
.handleCommand(ns
, managers
, new SignalCreator() {
275 public ProvisioningManager
getNewProvisioningManager() {
276 return ProvisioningManager
.init(dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
280 public RegistrationManager
getNewRegistrationManager(String username
) throws IOException
{
281 return RegistrationManager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
);
285 for (var m
: managers
) {
288 } catch (IOException e
) {
289 logger
.warn("Cleanup failed", e
);
294 private Manager
loadManager(
295 final String username
,
297 final ServiceEnvironment serviceEnvironment
,
298 final TrustNewIdentity trustNewIdentity
299 ) throws CommandException
{
302 manager
= Manager
.init(username
, dataPath
, serviceEnvironment
, BaseConfig
.USER_AGENT
, trustNewIdentity
);
303 } catch (NotRegisteredException e
) {
304 throw new UserErrorException("User " + username
+ " is not registered.");
305 } catch (Throwable e
) {
306 throw new UnexpectedErrorException("Error loading state file for user "
311 + e
.getClass().getSimpleName()
316 manager
.checkAccountState();
317 } catch (IOException e
) {
320 } catch (IOException ie
) {
321 logger
.warn("Failed to close broken account", ie
);
323 throw new IOErrorException("Error while checking account " + username
+ ": " + e
.getMessage(), e
);
329 private void initDbusClient(
330 final Command command
, final String username
, final boolean systemBus
, final OutputWriter outputWriter
331 ) throws CommandException
{
333 DBusConnection
.DBusBusType busType
;
335 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
337 busType
= DBusConnection
.DBusBusType
.SESSION
;
339 try (var dBusConn
= DBusConnection
.getConnection(busType
)) {
340 var ts
= dBusConn
.getRemoteObject(DbusConfig
.getBusname(),
341 DbusConfig
.getObjectPath(username
),
344 handleCommand(command
, ts
, dBusConn
, outputWriter
);
346 } catch (DBusException
| IOException e
) {
347 logger
.error("Dbus client failed", e
);
348 throw new UnexpectedErrorException("Dbus client failed", e
);
352 private void handleCommand(
353 Command command
, Signal ts
, DBusConnection dBusConn
, OutputWriter outputWriter
354 ) throws CommandException
{
355 if (command
instanceof LocalCommand localCommand
) {
356 try (final var m
= new DbusManagerImpl(ts
, dBusConn
)) {
357 localCommand
.handleCommand(ns
, m
, outputWriter
);
358 } catch (UnsupportedOperationException e
) {
359 throw new UserErrorException("Command is not yet implemented via dbus", e
);
360 } catch (IOException
| DBusExecutionException e
) {
361 throw new UnexpectedErrorException(e
.getMessage(), e
);
364 throw new UserErrorException("Command is not yet implemented via dbus");
369 * @return the default data directory to be used by signal-cli.
371 private static File
getDefaultDataPath() {
372 return new File(IOUtils
.getDataHomeDir(), "signal-cli");