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
);
195 throw new UserErrorException("Command only works in multi-account mode");
198 private OutputWriter
getOutputWriter(final Command command
) throws UserErrorException
{
199 final var outputTypeInput
= ns
.<OutputType
>get("output");
200 final var outputType
= outputTypeInput
== null ? command
.getSupportedOutputTypes()
203 .orElse(null) : outputTypeInput
;
204 final var writer
= new BufferedWriter(new OutputStreamWriter(System
.out
, IOUtils
.getConsoleCharset()));
205 final var outputWriter
= outputType
== null
207 : outputType
== OutputType
.JSON ?
new JsonWriterImpl(writer
) : new PlainTextWriterImpl(writer
);
209 if (outputWriter
!= null && !command
.getSupportedOutputTypes().contains(outputType
)) {
210 throw new UserErrorException("Command doesn't support output type " + outputType
);
215 private SignalAccountFiles
loadSignalAccountFiles() throws IOErrorException
{
216 final File configPath
;
217 final var config
= ns
.getString("config");
218 if (config
!= null) {
219 configPath
= new File(config
);
221 configPath
= getDefaultConfigPath();
224 final var serviceEnvironmentCli
= ns
.<ServiceEnvironmentCli
>get("service-environment");
225 final var serviceEnvironment
= serviceEnvironmentCli
== ServiceEnvironmentCli
.LIVE
226 ? ServiceEnvironment
.LIVE
227 : ServiceEnvironment
.STAGING
;
229 final var trustNewIdentityCli
= ns
.<TrustNewIdentityCli
>get("trust-new-identities");
230 final var trustNewIdentity
= trustNewIdentityCli
== TrustNewIdentityCli
.ON_FIRST_USE
231 ? TrustNewIdentity
.ON_FIRST_USE
232 : trustNewIdentityCli
== TrustNewIdentityCli
.ALWAYS ? TrustNewIdentity
.ALWAYS
: TrustNewIdentity
.NEVER
;
234 final var disableSendLog
= Boolean
.TRUE
.equals(ns
.getBoolean("disable-send-log"));
237 return new SignalAccountFiles(configPath
,
239 BaseConfig
.USER_AGENT
,
240 new Settings(trustNewIdentity
, disableSendLog
));
241 } catch (IOException e
) {
242 throw new IOErrorException("Failed to read local accounts list", e
);
246 private void handleProvisioningCommand(
247 final ProvisioningCommand command
,
248 final SignalAccountFiles signalAccountFiles
,
249 final CommandHandler commandHandler
250 ) throws CommandException
{
251 var pm
= signalAccountFiles
.initProvisioningManager();
252 commandHandler
.handleProvisioningCommand(command
, pm
);
255 private void handleRegistrationCommand(
256 final RegistrationCommand command
,
257 final String account
,
258 final SignalAccountFiles signalAccountFiles
,
259 final CommandHandler commandHandler
260 ) throws CommandException
{
261 try (final var rm
= loadRegistrationManager(account
, signalAccountFiles
)) {
262 commandHandler
.handleRegistrationCommand(command
, rm
);
263 } catch (IOException e
) {
264 logger
.warn("Cleanup failed", e
);
268 private void handleLocalCommand(
269 final LocalCommand command
,
270 final String account
,
271 final SignalAccountFiles signalAccountFiles
,
272 final CommandHandler commandHandler
273 ) throws CommandException
{
274 try (var m
= loadManager(account
, signalAccountFiles
)) {
275 commandHandler
.handleLocalCommand(command
, m
);
276 } catch (IOException e
) {
277 logger
.warn("Cleanup failed", e
);
281 private void handleMultiLocalCommand(
282 final MultiLocalCommand command
,
283 final SignalAccountFiles signalAccountFiles
,
284 final CommandHandler commandHandler
285 ) throws CommandException
{
286 try (var multiAccountManager
= signalAccountFiles
.initMultiAccountManager()) {
287 commandHandler
.handleMultiLocalCommand(command
, multiAccountManager
);
288 } catch (IOException e
) {
289 throw new IOErrorException("Failed to load local accounts file", e
);
293 private RegistrationManager
loadRegistrationManager(
294 final String account
, final SignalAccountFiles signalAccountFiles
295 ) throws UnexpectedErrorException
{
297 return signalAccountFiles
.initRegistrationManager(account
);
298 } catch (Throwable e
) {
299 throw new UnexpectedErrorException("Error loading or creating state file: "
302 + e
.getClass().getSimpleName()
307 private Manager
loadManager(
308 final String account
, final SignalAccountFiles signalAccountFiles
309 ) throws CommandException
{
310 logger
.trace("Loading account file for {}", account
);
312 return signalAccountFiles
.initManager(account
);
313 } catch (NotRegisteredException e
) {
314 throw new UserErrorException("User " + account
+ " is not registered.");
315 } catch (AccountCheckException ace
) {
316 if (ace
.getCause() instanceof IOException e
) {
317 throw new IOErrorException("Error while checking account " + account
+ ": " + e
.getMessage(), e
);
319 throw new UnexpectedErrorException("Error while checking account " + account
+ ": " + ace
.getMessage(),
322 } catch (Throwable e
) {
323 throw new UnexpectedErrorException("Error loading state file for user "
328 + e
.getClass().getSimpleName()
333 private void initDbusClient(
334 final Command command
, final String account
, final boolean systemBus
, final CommandHandler commandHandler
335 ) throws CommandException
{
337 final var busType
= systemBus ? DBusConnection
.DBusBusType
.SYSTEM
: DBusConnection
.DBusBusType
.SESSION
;
338 try (var dBusConn
= DBusConnectionBuilder
.forType(busType
).build()) {
339 DbusCommandHandler
.handleCommand(command
, account
, dBusConn
, commandHandler
);
341 } catch (ServiceUnknown e
) {
342 throw new UserErrorException("signal-cli DBus daemon not running on "
343 + (systemBus ?
"system" : "session")
345 + e
.getMessage(), e
);
346 } catch (DBusExecutionException
| DBusException
| IOException e
) {
347 throw new UnexpectedErrorException("Dbus client failed: " + e
.getMessage(), e
);
352 * @return the default data directory to be used by signal-cli.
354 private static File
getDefaultConfigPath() {
355 return new File(IOUtils
.getDataHomeDir(), "signal-cli");