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
.manager
.Manager
;
20 import org
.asamk
.signal
.manager
.RegistrationManager
;
21 import org
.asamk
.signal
.manager
.Settings
;
22 import org
.asamk
.signal
.manager
.SignalAccountFiles
;
23 import org
.asamk
.signal
.manager
.api
.AccountCheckException
;
24 import org
.asamk
.signal
.manager
.api
.NotRegisteredException
;
25 import org
.asamk
.signal
.manager
.api
.ServiceEnvironment
;
26 import org
.asamk
.signal
.manager
.api
.TrustNewIdentity
;
27 import org
.asamk
.signal
.output
.JsonWriterImpl
;
28 import org
.asamk
.signal
.output
.OutputWriter
;
29 import org
.asamk
.signal
.output
.PlainTextWriterImpl
;
30 import org
.asamk
.signal
.util
.IOUtils
;
31 import org
.slf4j
.Logger
;
32 import org
.slf4j
.LoggerFactory
;
34 import java
.io
.BufferedWriter
;
36 import java
.io
.IOException
;
37 import java
.io
.OutputStreamWriter
;
40 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
41 import static org
.asamk
.signal
.dbus
.DbusCommandHandler
.initDbusClient
;
45 private static final Logger logger
= LoggerFactory
.getLogger(App
.class);
47 private final Namespace ns
;
49 static ArgumentParser
buildArgumentParser() {
50 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
51 .includeArgumentNamesAsKeysInResult(true)
54 .description("Commandline interface for Signal.")
55 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
57 parser
.addArgument("--version").help("Show package version.").action(Arguments
.version());
58 parser
.addArgument("-v", "--verbose")
59 .help("Raise log level and include lib signal logs. Specify multiple times for even more logs.")
60 .action(Arguments
.count());
61 parser
.addArgument("--log-file")
63 .help("Write log output to the given file. If --verbose is also given, the detailed logs will only be written to the log file.");
64 parser
.addArgument("--scrub-log")
65 .action(Arguments
.storeTrue())
66 .help("Scrub possibly sensitive information from the log, like phone numbers and UUIDs.");
67 parser
.addArgument("-c", "--config")
68 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
70 parser
.addArgument("-a", "--account", "-u", "--username")
71 .help("Specify your phone number, that will be your identifier.");
73 var mut
= parser
.addMutuallyExclusiveGroup();
74 mut
.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
75 mut
.addArgument("--dbus-system")
76 .dest("global-dbus-system")
77 .help("Make request via system dbus.")
78 .action(Arguments
.storeTrue());
79 parser
.addArgument("--bus-name")
80 .dest("global-bus-name")
81 .setDefault(DbusConfig
.getBusname())
82 .help("Specify the D-Bus bus name to connect to.");
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());
103 "The global arguments are shown with 'signal-cli -h' and need to come before the subcommand, while the subcommand-specific arguments (shown with 'signal-cli SUBCOMMAND -h') need to be given after the subcommand.");
105 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
107 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
108 var subparser
= subparsers
.addParser(key
);
109 value
.attachToSubparser(subparser
);
115 public App(final Namespace ns
) {
119 public void init() throws CommandException
{
120 logger
.debug("Starting {}", BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
121 var commandKey
= ns
.getString("command");
122 var command
= Commands
.getCommand(commandKey
);
123 if (command
== null) {
124 throw new UserErrorException("Command not implemented!");
127 final var outputWriter
= getOutputWriter(command
);
128 final var commandHandler
= new CommandHandler(ns
, outputWriter
);
130 var account
= ns
.getString("account");
132 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
133 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
134 if (useDbus
|| useDbusSystem
) {
135 final var busName
= ns
.getString("global-bus-name");
136 // If account is null, it will connect to the default object path
137 initDbusClient(command
, account
, useDbusSystem
, busName
, commandHandler
);
141 if (!Manager
.isSignalClientAvailable()) {
142 throw new UserErrorException("Missing required native library dependency: libsignal-client");
145 final var signalAccountFiles
= loadSignalAccountFiles();
147 handleCommand(command
, commandHandler
, account
, signalAccountFiles
);
150 private void handleCommand(
151 final Command command
,
152 final CommandHandler commandHandler
,
154 final SignalAccountFiles signalAccountFiles
155 ) throws CommandException
{
156 if (command
instanceof ProvisioningCommand provisioningCommand
) {
157 if (account
!= null) {
158 throw new UserErrorException("You cannot specify a account (phone number) when linking");
161 handleProvisioningCommand(provisioningCommand
, signalAccountFiles
, commandHandler
);
165 if (account
== null) {
166 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
167 handleMultiLocalCommand(multiLocalCommand
, signalAccountFiles
, commandHandler
);
171 account
= getAccountIfOnlyOne(signalAccountFiles
);
172 } else if (!Manager
.isValidNumber(account
, null)) {
173 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
176 if (command
instanceof RegistrationCommand registrationCommand
) {
177 handleRegistrationCommand(registrationCommand
, account
, signalAccountFiles
, commandHandler
);
181 if (command
instanceof LocalCommand localCommand
) {
182 handleLocalCommand(localCommand
, account
, signalAccountFiles
, commandHandler
);
186 throw new UserErrorException("Command only works in multi-account mode");
189 private static String
getAccountIfOnlyOne(final SignalAccountFiles signalAccountFiles
) throws IOErrorException
, UserErrorException
{
190 Set
<String
> accounts
;
192 accounts
= signalAccountFiles
.getAllLocalAccountNumbers();
193 } catch (IOException e
) {
194 throw new IOErrorException("Failed to load local accounts file", e
);
196 if (accounts
.isEmpty()) {
197 throw new UserErrorException("No local users found, you first need to register or link an account");
198 } else if (accounts
.size() > 1) {
199 throw new UserErrorException("Multiple users found, you need to specify an account (phone number) with -a");
201 return accounts
.stream().findFirst().get();
204 private OutputWriter
getOutputWriter(final Command command
) throws UserErrorException
{
205 final var outputTypeInput
= ns
.<OutputType
>get("output");
206 final var outputType
= outputTypeInput
== null ? command
.getSupportedOutputTypes()
209 .orElse(null) : outputTypeInput
;
210 final var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, IOUtils
.getConsoleCharset()));
211 final var outputWriter
= outputType
== null
213 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
215 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
216 throw new UserErrorException("Command doesn't support output type " + outputType
);
221 private SignalAccountFiles
loadSignalAccountFiles() throws IOErrorException
{
222 final File configPath
;
223 final var config
= ns
.getString("config");
224 if (config
!= null) {
225 configPath
= new File(config
);
227 configPath
= getDefaultConfigPath();
230 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
231 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
232 ? ServiceEnvironment
.LIVE
233 : ServiceEnvironment
.STAGING
;
235 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
236 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
237 ? TrustNewIdentity
.ON_FIRST_USE
238 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
240 final var disableSendLog
= Boolean
.TRUE
.equals(ns
.getBoolean("disable-send-log"));
243 return new SignalAccountFiles(configPath
,
245 BaseConfig
.USER_AGENT
,
246 new Settings(trustNewIdentity
, disableSendLog
));
247 } catch (IOException e
) {
248 throw new IOErrorException("Failed to read local accounts list", e
);
252 private void handleProvisioningCommand(
253 final ProvisioningCommand command
,
254 final SignalAccountFiles signalAccountFiles
,
255 final CommandHandler commandHandler
256 ) throws CommandException
{
257 var pm
= signalAccountFiles
.initProvisioningManager();
258 commandHandler
.handleProvisioningCommand(command
, pm
);
261 private void handleRegistrationCommand(
262 final RegistrationCommand command
,
263 final String account
,
264 final SignalAccountFiles signalAccountFiles
,
265 final CommandHandler commandHandler
266 ) throws CommandException
{
267 try (final var rm
= loadRegistrationManager(account
, signalAccountFiles
)) {
268 commandHandler
.handleRegistrationCommand(command
, rm
);
269 } catch (IOException e
) {
270 logger
.warn("Cleanup failed", e
);
274 private void handleLocalCommand(
275 final LocalCommand command
,
276 final String account
,
277 final SignalAccountFiles signalAccountFiles
,
278 final CommandHandler commandHandler
279 ) throws CommandException
{
280 try (var m
= loadManager(account
, signalAccountFiles
)) {
281 commandHandler
.handleLocalCommand(command
, m
);
285 private void handleMultiLocalCommand(
286 final MultiLocalCommand command
,
287 final SignalAccountFiles signalAccountFiles
,
288 final CommandHandler commandHandler
289 ) throws CommandException
{
290 try (var multiAccountManager
= signalAccountFiles
.initMultiAccountManager()) {
291 commandHandler
.handleMultiLocalCommand(command
, multiAccountManager
);
292 } catch (IOException e
) {
293 throw new IOErrorException("Failed to load local accounts file", e
);
297 private RegistrationManager
loadRegistrationManager(
298 final String account
,
299 final SignalAccountFiles signalAccountFiles
300 ) throws UnexpectedErrorException
{
302 return signalAccountFiles
.initRegistrationManager(account
);
303 } catch (Throwable e
) {
304 throw new UnexpectedErrorException("Error loading or creating state file: "
307 + e
.getClass().getSimpleName()
312 private Manager
loadManager(
313 final String account
,
314 final SignalAccountFiles signalAccountFiles
315 ) throws CommandException
{
316 logger
.trace("Loading account file for {}", account
);
318 return signalAccountFiles
.initManager(account
);
319 } catch (NotRegisteredException e
) {
320 throw new UserErrorException("User " + account
+ " is not registered.");
321 } catch (AccountCheckException ace
) {
322 if (ace
.getCause() instanceof IOException e
) {
323 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
325 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
328 } catch (Throwable e
) {
329 throw new UnexpectedErrorException("Error loading state file for user "
334 + e
.getClass().getSimpleName()
340 * @return the default data directory to be used by signal-cli.
342 private static File
getDefaultConfigPath() {
343 return new File(IOUtils
.getDataHomeDir(), "signal-cli");