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
.OutputWriter
;
30 import org
.asamk
.signal
.output
.PlainTextWriterImpl
;
31 import org
.asamk
.signal
.util
.IOUtils
;
32 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
33 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnectionBuilder
;
34 import org
.freedesktop
.dbus
.errors
.ServiceUnknown
;
35 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
36 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
37 import org
.slf4j
.Logger
;
38 import org
.slf4j
.LoggerFactory
;
40 import java
.io
.BufferedWriter
;
42 import java
.io
.IOException
;
43 import java
.io
.OutputStreamWriter
;
46 import static net
.sourceforge
.argparse4j
.DefaultSettings
.VERSION_0_9_0_DEFAULT_SETTINGS
;
50 private final static Logger logger
= LoggerFactory
.getLogger(App
.class);
52 private final Namespace ns
;
54 static ArgumentParser
buildArgumentParser() {
55 var parser
= ArgumentParsers
.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS
)
56 .includeArgumentNamesAsKeysInResult(true)
59 .description("Commandline interface for Signal.")
60 .version(BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
62 parser
.addArgument("--version").help("Show package version.").action(Arguments
.version());
63 parser
.addArgument("-v", "--verbose")
64 .help("Raise log level and include lib signal logs. Specify multiple times for even more logs.")
65 .action(Arguments
.count());
66 parser
.addArgument("--log-file")
68 .help("Write log output to the given file. If --verbose is also given, the detailed logs will only be written to the log file.");
69 parser
.addArgument("--scrub-log")
70 .action(Arguments
.storeTrue())
71 .help("Scrub possibly sensitive information from the log, like phone numbers and UUIDs.");
72 parser
.addArgument("-c", "--config")
73 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
75 parser
.addArgument("-a", "--account", "-u", "--username")
76 .help("Specify your phone number, that will be your identifier.");
78 var mut
= parser
.addMutuallyExclusiveGroup();
79 mut
.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments
.storeTrue());
80 mut
.addArgument("--dbus-system")
81 .dest("global-dbus-system")
82 .help("Make request via system dbus.")
83 .action(Arguments
.storeTrue());
85 parser
.addArgument("-o", "--output")
86 .help("Choose to output in plain text or JSON")
87 .type(Arguments
.enumStringType(OutputType
.class));
89 parser
.addArgument("--service-environment")
90 .help("Choose the server environment to use.")
91 .type(Arguments
.enumStringType(ServiceEnvironmentCli
.class))
92 .setDefault(ServiceEnvironmentCli
.LIVE
);
94 parser
.addArgument("--trust-new-identities")
95 .help("Choose when to trust new identities.")
96 .type(Arguments
.enumStringType(TrustNewIdentityCli
.class))
97 .setDefault(TrustNewIdentityCli
.ON_FIRST_USE
);
99 parser
.addArgument("--disable-send-log")
100 .help("Disable message send log (for resending messages that recipient couldn't decrypt)")
101 .action(Arguments
.storeTrue());
103 var subparsers
= parser
.addSubparsers().title("subcommands").dest("command");
105 Commands
.getCommandSubparserAttachers().forEach((key
, value
) -> {
106 var subparser
= subparsers
.addParser(key
);
107 value
.attachToSubparser(subparser
);
113 public App(final Namespace ns
) {
117 public void init() throws CommandException
{
118 logger
.debug("Starting {}", BaseConfig
.PROJECT_NAME
+ " " + BaseConfig
.PROJECT_VERSION
);
119 var commandKey
= ns
.getString("command");
120 var command
= Commands
.getCommand(commandKey
);
121 if (command
== null) {
122 throw new UserErrorException("Command not implemented!");
125 final var outputWriter
= getOutputWriter(command
);
126 final var commandHandler
= new CommandHandler(ns
, outputWriter
);
128 var account
= ns
.getString("account");
130 final var useDbus
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus"));
131 final var useDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("global-dbus-system"));
132 if (useDbus
|| useDbusSystem
) {
133 // If account is null, it will connect to the default object path
134 initDbusClient(command
, account
, useDbusSystem
, commandHandler
);
138 if (!Manager
.isSignalClientAvailable()) {
139 throw new UserErrorException("Missing required native library dependency: libsignal-client");
142 final var signalAccountFiles
= loadSignalAccountFiles();
144 handleCommand(command
, commandHandler
, account
, signalAccountFiles
);
147 private void handleCommand(
148 final Command command
,
149 final CommandHandler commandHandler
,
151 final SignalAccountFiles signalAccountFiles
152 ) throws CommandException
{
153 if (command
instanceof ProvisioningCommand provisioningCommand
) {
154 if (account
!= null) {
155 throw new UserErrorException("You cannot specify a account (phone number) when linking");
158 handleProvisioningCommand(provisioningCommand
, signalAccountFiles
, commandHandler
);
162 if (account
== null) {
163 if (command
instanceof MultiLocalCommand multiLocalCommand
) {
164 handleMultiLocalCommand(multiLocalCommand
, signalAccountFiles
, commandHandler
);
168 Set
<String
> accounts
;
170 accounts
= signalAccountFiles
.getAllLocalAccountNumbers();
171 } catch (IOException e
) {
172 throw new IOErrorException("Failed to load local accounts file", e
);
174 if (accounts
.size() == 0) {
175 throw new UserErrorException("No local users found, you first need to register or link an account");
176 } else if (accounts
.size() > 1) {
177 throw new UserErrorException(
178 "Multiple users found, you need to specify an account (phone number) with -a");
181 account
= accounts
.stream().findFirst().get();
182 } else if (!Manager
.isValidNumber(account
, null)) {
183 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
186 if (command
instanceof RegistrationCommand registrationCommand
) {
187 handleRegistrationCommand(registrationCommand
, account
, signalAccountFiles
, commandHandler
);
191 if (command
instanceof LocalCommand localCommand
) {
192 handleLocalCommand(localCommand
, account
, signalAccountFiles
, commandHandler
);
196 throw new UserErrorException("Command only works in multi-account mode");
199 private OutputWriter
getOutputWriter(final Command command
) throws UserErrorException
{
200 final var outputTypeInput
= ns
.<OutputType
>get("output");
201 final var outputType
= outputTypeInput
== null ? command
.getSupportedOutputTypes()
204 .orElse(null) : outputTypeInput
;
205 final var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, IOUtils
.getConsoleCharset()));
206 final var outputWriter
= outputType
== null
208 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
210 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
211 throw new UserErrorException("Command doesn't support output type " + outputType
);
216 private SignalAccountFiles
loadSignalAccountFiles() throws IOErrorException
{
217 final File configPath
;
218 final var config
= ns
.getString("config");
219 if (config
!= null) {
220 configPath
= new File(config
);
222 configPath
= getDefaultConfigPath();
225 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
226 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
227 ? ServiceEnvironment
.LIVE
228 : ServiceEnvironment
.STAGING
;
230 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
231 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
232 ? TrustNewIdentity
.ON_FIRST_USE
233 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
235 final var disableSendLog
= Boolean
.TRUE
.equals(ns
.getBoolean("disable-send-log"));
238 return new SignalAccountFiles(configPath
,
240 BaseConfig
.USER_AGENT
,
241 new Settings(trustNewIdentity
, disableSendLog
));
242 } catch (IOException e
) {
243 throw new IOErrorException("Failed to read local accounts list", e
);
247 private void handleProvisioningCommand(
248 final ProvisioningCommand command
,
249 final SignalAccountFiles signalAccountFiles
,
250 final CommandHandler commandHandler
251 ) throws CommandException
{
252 var pm
= signalAccountFiles
.initProvisioningManager();
253 commandHandler
.handleProvisioningCommand(command
, pm
);
256 private void handleRegistrationCommand(
257 final RegistrationCommand command
,
258 final String account
,
259 final SignalAccountFiles signalAccountFiles
,
260 final CommandHandler commandHandler
261 ) throws CommandException
{
262 try (final var rm
= loadRegistrationManager(account
, signalAccountFiles
)) {
263 commandHandler
.handleRegistrationCommand(command
, rm
);
264 } catch (IOException e
) {
265 logger
.warn("Cleanup failed", e
);
269 private void handleLocalCommand(
270 final LocalCommand command
,
271 final String account
,
272 final SignalAccountFiles signalAccountFiles
,
273 final CommandHandler commandHandler
274 ) throws CommandException
{
275 try (var m
= loadManager(account
, signalAccountFiles
)) {
276 commandHandler
.handleLocalCommand(command
, m
);
277 } catch (IOException e
) {
278 logger
.warn("Cleanup failed", e
);
282 private void handleMultiLocalCommand(
283 final MultiLocalCommand command
,
284 final SignalAccountFiles signalAccountFiles
,
285 final CommandHandler commandHandler
286 ) throws CommandException
{
287 try (var multiAccountManager
= signalAccountFiles
.initMultiAccountManager()) {
288 commandHandler
.handleMultiLocalCommand(command
, multiAccountManager
);
289 } catch (IOException e
) {
290 throw new IOErrorException("Failed to load local accounts file", e
);
294 private RegistrationManager
loadRegistrationManager(
295 final String account
, final SignalAccountFiles signalAccountFiles
296 ) throws UnexpectedErrorException
{
298 return signalAccountFiles
.initRegistrationManager(account
);
299 } catch (Throwable e
) {
300 throw new UnexpectedErrorException("Error loading or creating state file: "
303 + e
.getClass().getSimpleName()
308 private Manager
loadManager(
309 final String account
, final SignalAccountFiles signalAccountFiles
310 ) throws CommandException
{
311 logger
.trace("Loading account file for {}", account
);
313 return signalAccountFiles
.initManager(account
);
314 } catch (NotRegisteredException e
) {
315 throw new UserErrorException("User " + account
+ " is not registered.");
316 } catch (AccountCheckException ace
) {
317 if (ace
.getCause() instanceof IOException e
) {
318 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
320 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
323 } catch (Throwable e
) {
324 throw new UnexpectedErrorException("Error loading state file for user "
329 + e
.getClass().getSimpleName()
334 private void initDbusClient(
335 final Command command
, final String account
, final boolean systemBus
, final CommandHandler commandHandler
336 ) throws CommandException
{
338 final var busType
= systemBus ? DBusConnection
.DBusBusType
.SYSTEM
: DBusConnection
.DBusBusType
.SESSION
;
339 try (var dBusConn
= DBusConnectionBuilder
.forType(busType
).build()) {
340 DbusCommandHandler
.handleCommand(command
, account
, dBusConn
, commandHandler
);
342 } catch (ServiceUnknown e
) {
343 throw new UserErrorException("signal-cli DBus daemon not running on "
344 + (systemBus ?
"system" : "session")
346 + e
.getMessage(), e
);
347 } catch (DBusExecutionException
| DBusException
| IOException e
) {
348 throw new UnexpectedErrorException("Dbus client failed: " + e
.getMessage(), e
);
353 * @return the default data directory to be used by signal-cli.
355 private static File
getDefaultConfigPath() {
356 return new File(IOUtils
.getDataHomeDir(), "signal-cli");