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
.commands
.Command
;
9 import org
.asamk
.signal
.commands
.CommandHandler
;
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
.exceptions
.CommandException
;
16 import org
.asamk
.signal
.commands
.exceptions
.IOErrorException
;
17 import org
.asamk
.signal
.commands
.exceptions
.UnexpectedErrorException
;
18 import org
.asamk
.signal
.commands
.exceptions
.UserErrorException
;
19 import org
.asamk
.signal
.dbus
.DbusCommandHandler
;
20 import org
.asamk
.signal
.manager
.Manager
;
21 import org
.asamk
.signal
.manager
.RegistrationManager
;
22 import org
.asamk
.signal
.manager
.Settings
;
23 import org
.asamk
.signal
.manager
.SignalAccountFiles
;
24 import org
.asamk
.signal
.manager
.api
.AccountCheckException
;
25 import org
.asamk
.signal
.manager
.api
.NotRegisteredException
;
26 import org
.asamk
.signal
.manager
.api
.ServiceEnvironment
;
27 import org
.asamk
.signal
.manager
.api
.TrustNewIdentity
;
28 import org
.asamk
.signal
.output
.JsonWriterImpl
;
29 import org
.asamk
.signal
.output
.PlainTextWriterImpl
;
30 import org
.asamk
.signal
.util
.IOUtils
;
31 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
32 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnectionBuilder
;
33 import org
.freedesktop
.dbus
.errors
.ServiceUnknown
;
34 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
35 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
36 import org
.slf4j
.Logger
;
37 import org
.slf4j
.LoggerFactory
;
39 import java
.io
.BufferedWriter
;
41 import java
.io
.IOException
;
42 import java
.io
.OutputStreamWriter
;
45 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
49 private final static Logger logger
= LoggerFactory
.getLogger(App
.class);
51 private final Namespace ns
;
53 static ArgumentParser
buildArgumentParser() {
54 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
55 .includeArgumentNamesAsKeysInResult(true)
58 .description("Commandline interface for Signal.")
59 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
61 parser
.addArgument("--version").help("Show package version.").action(Arguments
.version());
62 parser
.addArgument("-v", "--verbose")
63 .help("Raise log level and include lib signal logs. Specify multiple times for even more logs.")
64 .action(Arguments
.count());
65 parser
.addArgument("--log-file")
67 .help("Write log output to the given file. If --verbose is also given, the detailed logs will only be written to the log file.");
68 parser
.addArgument("--scrub-log")
69 .action(Arguments
.storeTrue())
70 .help("Scrub possibly sensitive information from the log, like phone numbers and UUIDs.");
71 parser
.addArgument("-c", "--config")
72 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
74 parser
.addArgument("-a", "--account", "-u", "--username")
75 .help("Specify your phone number, that will be your identifier.");
77 var mut
= parser
.addMutuallyExclusiveGroup();
78 mut
.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
79 mut
.addArgument("--dbus-system")
80 .dest("global-dbus-system")
81 .help("Make request via system dbus.")
82 .action(Arguments
.storeTrue());
84 parser
.addArgument("-o", "--output")
85 .help("Choose to output in plain text or JSON")
86 .type(Arguments
.enumStringType(OutputType
.class));
88 parser
.addArgument("--service-environment")
89 .help("Choose the server environment to use.")
90 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
91 .setDefault(ServiceEnvironmentCli
.LIVE
);
93 parser
.addArgument("--trust-new-identities")
94 .help("Choose when to trust new identities.")
95 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
96 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
98 parser
.addArgument("--disable-send-log")
99 .help("Disable message send log (for resending messages that recipient couldn't decrypt)")
100 .action(Arguments
.storeTrue());
102 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
104 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
105 var subparser
= subparsers
.addParser(key
);
106 value
.attachToSubparser(subparser
);
112 public App(final Namespace ns
) {
116 public void init() throws CommandException
{
117 logger
.debug("Starting {}", BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
118 var commandKey
= ns
.getString("command");
119 var command
= Commands
.getCommand(commandKey
);
120 if (command
== null) {
121 throw new UserErrorException("Command not implemented!");
124 var outputTypeInput
= ns
.<OutputType
>get("output");
125 var outputType
= outputTypeInput
== null
126 ? command
.getSupportedOutputTypes().stream().findFirst().orElse(null)
128 var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, IOUtils
.getConsoleCharset()));
129 var outputWriter
= outputType
== null
131 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
133 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
134 throw new UserErrorException("Command doesn't support output type " + outputType
);
137 final var commandHandler
= new CommandHandler(ns
, outputWriter
);
139 var account
= ns
.getString("account");
141 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
142 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
143 if (useDbus
|| useDbusSystem
) {
144 // If account is null, it will connect to the default object path
145 initDbusClient(command
, account
, useDbusSystem
, commandHandler
);
149 if (!Manager
.isSignalClientAvailable()) {
150 throw new UserErrorException("Missing required native library dependency: libsignal-client");
153 final File configPath
;
154 var config
= ns
.getString("config");
155 if (config
!= null) {
156 configPath
= new File(config
);
158 configPath
= getDefaultConfigPath();
161 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
162 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
163 ? ServiceEnvironment
.LIVE
164 : ServiceEnvironment
.STAGING
;
166 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
167 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
168 ? TrustNewIdentity
.ON_FIRST_USE
169 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
171 final var disableSendLog
= Boolean
.TRUE
.equals(ns
.getBoolean("disable-send-log"));
173 final SignalAccountFiles signalAccountFiles
;
175 signalAccountFiles
= new SignalAccountFiles(configPath
,
177 BaseConfig
.USER_AGENT
,
178 new Settings(trustNewIdentity
, disableSendLog
));
179 } catch (IOException e
) {
180 throw new IOErrorException("Failed to read local accounts list", e
);
183 if (command
instanceof ProvisioningCommand provisioningCommand
) {
184 if (account
!= null) {
185 throw new UserErrorException("You cannot specify a account (phone number) when linking");
188 handleProvisioningCommand(provisioningCommand
, signalAccountFiles
, commandHandler
);
192 if (account
== null) {
193 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
194 handleMultiLocalCommand(multiLocalCommand
, signalAccountFiles
, commandHandler
);
198 Set
<String
> accounts
;
200 accounts
= signalAccountFiles
.getAllLocalAccountNumbers();
201 } catch (IOException e
) {
202 throw new IOErrorException("Failed to load local accounts file", e
);
204 if (accounts
.size() == 0) {
205 throw new UserErrorException("No local users found, you first need to register or link an account");
206 } else if (accounts
.size() > 1) {
207 throw new UserErrorException(
208 "Multiple users found, you need to specify an account (phone number) with -a");
211 account
= accounts
.stream().findFirst().get();
212 } else if (!Manager
.isValidNumber(account
, null)) {
213 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
216 if (command
instanceof RegistrationCommand registrationCommand
) {
217 handleRegistrationCommand(registrationCommand
, account
, signalAccountFiles
, commandHandler
);
221 if (!(command
instanceof LocalCommand
)) {
222 throw new UserErrorException("Command only works in multi-account mode");
225 handleLocalCommand((LocalCommand
) command
, account
, signalAccountFiles
, commandHandler
);
228 private void handleProvisioningCommand(
229 final ProvisioningCommand command
,
230 final SignalAccountFiles signalAccountFiles
,
231 final CommandHandler commandHandler
232 ) throws CommandException
{
233 var pm
= signalAccountFiles
.initProvisioningManager();
234 commandHandler
.handleProvisioningCommand(command
, pm
);
237 private void handleRegistrationCommand(
238 final RegistrationCommand command
,
239 final String account
,
240 final SignalAccountFiles signalAccountFiles
,
241 final CommandHandler commandHandler
242 ) throws CommandException
{
243 try (final var rm
= loadRegistrationManager(account
, signalAccountFiles
)) {
244 commandHandler
.handleRegistrationCommand(command
, rm
);
245 } catch (IOException e
) {
246 logger
.warn("Cleanup failed", e
);
250 private void handleLocalCommand(
251 final LocalCommand command
,
252 final String account
,
253 final SignalAccountFiles signalAccountFiles
,
254 final CommandHandler commandHandler
255 ) throws CommandException
{
256 try (var m
= loadManager(account
, signalAccountFiles
)) {
257 commandHandler
.handleLocalCommand(command
, m
);
258 } catch (IOException e
) {
259 logger
.warn("Cleanup failed", e
);
263 private void handleMultiLocalCommand(
264 final MultiLocalCommand command
,
265 final SignalAccountFiles signalAccountFiles
,
266 final CommandHandler commandHandler
267 ) throws CommandException
{
268 try (var multiAccountManager
= signalAccountFiles
.initMultiAccountManager()) {
269 commandHandler
.handleMultiLocalCommand(command
, multiAccountManager
);
270 } catch (IOException e
) {
271 throw new IOErrorException("Failed to load local accounts file", e
);
275 private RegistrationManager
loadRegistrationManager(
276 final String account
, final SignalAccountFiles signalAccountFiles
277 ) throws UnexpectedErrorException
{
279 return signalAccountFiles
.initRegistrationManager(account
);
280 } catch (Throwable e
) {
281 throw new UnexpectedErrorException("Error loading or creating state file: "
284 + e
.getClass().getSimpleName()
289 private Manager
loadManager(
290 final String account
, final SignalAccountFiles signalAccountFiles
291 ) throws CommandException
{
292 logger
.trace("Loading account file for {}", account
);
294 return signalAccountFiles
.initManager(account
);
295 } catch (NotRegisteredException e
) {
296 throw new UserErrorException("User " + account
+ " is not registered.");
297 } catch (AccountCheckException ace
) {
298 if (ace
.getCause() instanceof IOException e
) {
299 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
301 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
304 } catch (Throwable e
) {
305 throw new UnexpectedErrorException("Error loading state file for user "
310 + e
.getClass().getSimpleName()
315 private void initDbusClient(
316 final Command command
, final String account
, final boolean systemBus
, final CommandHandler commandHandler
317 ) throws CommandException
{
319 final var busType
= systemBus ? DBusConnection
.DBusBusType
.SYSTEM
: DBusConnection
.DBusBusType
.SESSION
;
320 try (var dBusConn
= DBusConnectionBuilder
.forType(busType
).build()) {
321 DbusCommandHandler
.handleCommand(command
, account
, dBusConn
, commandHandler
);
323 } catch (ServiceUnknown e
) {
324 throw new UserErrorException("signal-cli DBus daemon not running on "
325 + (systemBus ?
"system" : "session")
327 + e
.getMessage(), e
);
328 } catch (DBusExecutionException
| DBusException
| IOException e
) {
329 throw new UnexpectedErrorException("Dbus client failed: " + e
.getMessage(), e
);
334 * @return the default data directory to be used by signal-cli.
336 private static File
getDefaultConfigPath() {
337 return new File(IOUtils
.getDataHomeDir(), "signal-cli");