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());
80 parser
.addArgument("-o", "--output")
81 .help("Choose to output in plain text or JSON")
82 .type(Arguments
.enumStringType(OutputType
.class));
84 parser
.addArgument("--service-environment")
85 .help("Choose the server environment to use.")
86 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
87 .setDefault(ServiceEnvironmentCli
.LIVE
);
89 parser
.addArgument("--trust-new-identities")
90 .help("Choose when to trust new identities.")
91 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
92 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
94 parser
.addArgument("--disable-send-log")
95 .help("Disable message send log (for resending messages that recipient couldn't decrypt)")
96 .action(Arguments
.storeTrue());
98 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
100 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
101 var subparser
= subparsers
.addParser(key
);
102 value
.attachToSubparser(subparser
);
108 public App(final Namespace ns
) {
112 public void init() throws CommandException
{
113 logger
.debug("Starting {}", BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
114 var commandKey
= ns
.getString("command");
115 var command
= Commands
.getCommand(commandKey
);
116 if (command
== null) {
117 throw new UserErrorException("Command not implemented!");
120 final var outputWriter
= getOutputWriter(command
);
121 final var commandHandler
= new CommandHandler(ns
, outputWriter
);
123 var account
= ns
.getString("account");
125 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
126 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
127 if (useDbus
|| useDbusSystem
) {
128 // If account is null, it will connect to the default object path
129 initDbusClient(command
, account
, useDbusSystem
, commandHandler
);
133 if (!Manager
.isSignalClientAvailable()) {
134 throw new UserErrorException("Missing required native library dependency: libsignal-client");
137 final var signalAccountFiles
= loadSignalAccountFiles();
139 handleCommand(command
, commandHandler
, account
, signalAccountFiles
);
142 private void handleCommand(
143 final Command command
,
144 final CommandHandler commandHandler
,
146 final SignalAccountFiles signalAccountFiles
147 ) throws CommandException
{
148 if (command
instanceof ProvisioningCommand provisioningCommand
) {
149 if (account
!= null) {
150 throw new UserErrorException("You cannot specify a account (phone number) when linking");
153 handleProvisioningCommand(provisioningCommand
, signalAccountFiles
, commandHandler
);
157 if (account
== null) {
158 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
159 handleMultiLocalCommand(multiLocalCommand
, signalAccountFiles
, commandHandler
);
163 account
= getAccountIfOnlyOne(signalAccountFiles
);
164 } else if (!Manager
.isValidNumber(account
, null)) {
165 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
168 if (command
instanceof RegistrationCommand registrationCommand
) {
169 handleRegistrationCommand(registrationCommand
, account
, signalAccountFiles
, commandHandler
);
173 if (command
instanceof LocalCommand localCommand
) {
174 handleLocalCommand(localCommand
, account
, signalAccountFiles
, commandHandler
);
178 throw new UserErrorException("Command only works in multi-account mode");
181 private static String
getAccountIfOnlyOne(final SignalAccountFiles signalAccountFiles
) throws IOErrorException
, UserErrorException
{
182 Set
<String
> accounts
;
184 accounts
= signalAccountFiles
.getAllLocalAccountNumbers();
185 } catch (IOException e
) {
186 throw new IOErrorException("Failed to load local accounts file", e
);
188 if (accounts
.isEmpty()) {
189 throw new UserErrorException("No local users found, you first need to register or link an account");
190 } else if (accounts
.size() > 1) {
191 throw new UserErrorException("Multiple users found, you need to specify an account (phone number) with -a");
193 return accounts
.stream().findFirst().get();
196 private OutputWriter
getOutputWriter(final Command command
) throws UserErrorException
{
197 final var outputTypeInput
= ns
.<OutputType
>get("output");
198 final var outputType
= outputTypeInput
== null ? command
.getSupportedOutputTypes()
201 .orElse(null) : outputTypeInput
;
202 final var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, IOUtils
.getConsoleCharset()));
203 final var outputWriter
= outputType
== null
205 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
207 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
208 throw new UserErrorException("Command doesn't support output type " + outputType
);
213 private SignalAccountFiles
loadSignalAccountFiles() throws IOErrorException
{
214 final File configPath
;
215 final var config
= ns
.getString("config");
216 if (config
!= null) {
217 configPath
= new File(config
);
219 configPath
= getDefaultConfigPath();
222 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
223 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
224 ? ServiceEnvironment
.LIVE
225 : ServiceEnvironment
.STAGING
;
227 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
228 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
229 ? TrustNewIdentity
.ON_FIRST_USE
230 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
232 final var disableSendLog
= Boolean
.TRUE
.equals(ns
.getBoolean("disable-send-log"));
235 return new SignalAccountFiles(configPath
,
237 BaseConfig
.USER_AGENT
,
238 new Settings(trustNewIdentity
, disableSendLog
));
239 } catch (IOException e
) {
240 throw new IOErrorException("Failed to read local accounts list", e
);
244 private void handleProvisioningCommand(
245 final ProvisioningCommand command
,
246 final SignalAccountFiles signalAccountFiles
,
247 final CommandHandler commandHandler
248 ) throws CommandException
{
249 var pm
= signalAccountFiles
.initProvisioningManager();
250 commandHandler
.handleProvisioningCommand(command
, pm
);
253 private void handleRegistrationCommand(
254 final RegistrationCommand command
,
255 final String account
,
256 final SignalAccountFiles signalAccountFiles
,
257 final CommandHandler commandHandler
258 ) throws CommandException
{
259 try (final var rm
= loadRegistrationManager(account
, signalAccountFiles
)) {
260 commandHandler
.handleRegistrationCommand(command
, rm
);
261 } catch (IOException e
) {
262 logger
.warn("Cleanup failed", e
);
266 private void handleLocalCommand(
267 final LocalCommand command
,
268 final String account
,
269 final SignalAccountFiles signalAccountFiles
,
270 final CommandHandler commandHandler
271 ) throws CommandException
{
272 try (var m
= loadManager(account
, signalAccountFiles
)) {
273 commandHandler
.handleLocalCommand(command
, m
);
277 private void handleMultiLocalCommand(
278 final MultiLocalCommand command
,
279 final SignalAccountFiles signalAccountFiles
,
280 final CommandHandler commandHandler
281 ) throws CommandException
{
282 try (var multiAccountManager
= signalAccountFiles
.initMultiAccountManager()) {
283 commandHandler
.handleMultiLocalCommand(command
, multiAccountManager
);
284 } catch (IOException e
) {
285 throw new IOErrorException("Failed to load local accounts file", e
);
289 private RegistrationManager
loadRegistrationManager(
290 final String account
, final SignalAccountFiles signalAccountFiles
291 ) throws UnexpectedErrorException
{
293 return signalAccountFiles
.initRegistrationManager(account
);
294 } catch (Throwable e
) {
295 throw new UnexpectedErrorException("Error loading or creating state file: "
298 + e
.getClass().getSimpleName()
303 private Manager
loadManager(
304 final String account
, final SignalAccountFiles signalAccountFiles
305 ) throws CommandException
{
306 logger
.trace("Loading account file for {}", account
);
308 return signalAccountFiles
.initManager(account
);
309 } catch (NotRegisteredException e
) {
310 throw new UserErrorException("User " + account
+ " is not registered.");
311 } catch (AccountCheckException ace
) {
312 if (ace
.getCause() instanceof IOException e
) {
313 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
315 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
318 } catch (Throwable e
) {
319 throw new UnexpectedErrorException("Error loading state file for user "
324 + e
.getClass().getSimpleName()
330 * @return the default data directory to be used by signal-cli.
332 private static File
getDefaultConfigPath() {
333 return new File(IOUtils
.getDataHomeDir(), "signal-cli");