]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/App.java
e8c30a97531ec7c749cbebd04919d2b47d6210c9
[signal-cli] / src / main / java / org / asamk / signal / App.java
1 package org.asamk.signal;
2
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;
7
8 import org.asamk.Signal;
9 import org.asamk.SignalControl;
10 import org.asamk.signal.commands.Command;
11 import org.asamk.signal.commands.Commands;
12 import org.asamk.signal.commands.LocalCommand;
13 import org.asamk.signal.commands.MultiLocalCommand;
14 import org.asamk.signal.commands.ProvisioningCommand;
15 import org.asamk.signal.commands.RegistrationCommand;
16 import org.asamk.signal.commands.exceptions.CommandException;
17 import org.asamk.signal.commands.exceptions.IOErrorException;
18 import org.asamk.signal.commands.exceptions.UnexpectedErrorException;
19 import org.asamk.signal.commands.exceptions.UserErrorException;
20 import org.asamk.signal.dbus.DbusManagerImpl;
21 import org.asamk.signal.dbus.DbusMultiAccountManagerImpl;
22 import org.asamk.signal.dbus.DbusProvisioningManagerImpl;
23 import org.asamk.signal.dbus.DbusRegistrationManagerImpl;
24 import org.asamk.signal.manager.Manager;
25 import org.asamk.signal.manager.RegistrationManager;
26 import org.asamk.signal.manager.Settings;
27 import org.asamk.signal.manager.SignalAccountFiles;
28 import org.asamk.signal.manager.api.AccountCheckException;
29 import org.asamk.signal.manager.api.NotRegisteredException;
30 import org.asamk.signal.manager.api.ServiceEnvironment;
31 import org.asamk.signal.manager.api.TrustNewIdentity;
32 import org.asamk.signal.output.JsonWriterImpl;
33 import org.asamk.signal.output.OutputWriter;
34 import org.asamk.signal.output.PlainTextWriterImpl;
35 import org.asamk.signal.util.IOUtils;
36 import org.freedesktop.dbus.connections.impl.DBusConnection;
37 import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder;
38 import org.freedesktop.dbus.errors.ServiceUnknown;
39 import org.freedesktop.dbus.errors.UnknownMethod;
40 import org.freedesktop.dbus.exceptions.DBusException;
41 import org.freedesktop.dbus.exceptions.DBusExecutionException;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import java.io.BufferedWriter;
46 import java.io.File;
47 import java.io.IOException;
48 import java.io.OutputStreamWriter;
49 import java.util.Set;
50
51 import static net.sourceforge.argparse4j.DefaultSettings.VERSION_0_9_0_DEFAULT_SETTINGS;
52
53 public class App {
54
55 private final static Logger logger = LoggerFactory.getLogger(App.class);
56
57 private final Namespace ns;
58
59 static ArgumentParser buildArgumentParser() {
60 var parser = ArgumentParsers.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS)
61 .includeArgumentNamesAsKeysInResult(true)
62 .build()
63 .defaultHelp(true)
64 .description("Commandline interface for Signal.")
65 .version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
66
67 parser.addArgument("--version").help("Show package version.").action(Arguments.version());
68 parser.addArgument("-v", "--verbose")
69 .help("Raise log level and include lib signal logs. Specify multiple times for even more logs.")
70 .action(Arguments.count());
71 parser.addArgument("--log-file")
72 .type(File.class)
73 .help("Write log output to the given file. If --verbose is also given, the detailed logs will only be written to the log file.");
74 parser.addArgument("--scrub-log")
75 .action(Arguments.storeTrue())
76 .help("Scrub possibly sensitive information from the log, like phone numbers and UUIDs.");
77 parser.addArgument("-c", "--config")
78 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
79
80 parser.addArgument("-a", "--account", "-u", "--username")
81 .help("Specify your phone number, that will be your identifier.");
82
83 var mut = parser.addMutuallyExclusiveGroup();
84 mut.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments.storeTrue());
85 mut.addArgument("--dbus-system")
86 .dest("global-dbus-system")
87 .help("Make request via system dbus.")
88 .action(Arguments.storeTrue());
89
90 parser.addArgument("-o", "--output")
91 .help("Choose to output in plain text or JSON")
92 .type(Arguments.enumStringType(OutputType.class));
93
94 parser.addArgument("--service-environment")
95 .help("Choose the server environment to use.")
96 .type(Arguments.enumStringType(ServiceEnvironmentCli.class))
97 .setDefault(ServiceEnvironmentCli.LIVE);
98
99 parser.addArgument("--trust-new-identities")
100 .help("Choose when to trust new identities.")
101 .type(Arguments.enumStringType(TrustNewIdentityCli.class))
102 .setDefault(TrustNewIdentityCli.ON_FIRST_USE);
103
104 parser.addArgument("--disable-send-log")
105 .help("Disable message send log (for resending messages that recipient couldn't decrypt)")
106 .action(Arguments.storeTrue());
107
108 var subparsers = parser.addSubparsers().title("subcommands").dest("command");
109
110 Commands.getCommandSubparserAttachers().forEach((key, value) -> {
111 var subparser = subparsers.addParser(key);
112 value.attachToSubparser(subparser);
113 });
114
115 return parser;
116 }
117
118 public App(final Namespace ns) {
119 this.ns = ns;
120 }
121
122 public void init() throws CommandException {
123 var commandKey = ns.getString("command");
124 var command = Commands.getCommand(commandKey);
125 if (command == null) {
126 throw new UserErrorException("Command not implemented!");
127 }
128
129 var outputTypeInput = ns.<OutputType>get("output");
130 var outputType = outputTypeInput == null
131 ? command.getSupportedOutputTypes().stream().findFirst().orElse(null)
132 : outputTypeInput;
133 var writer = new BufferedWriter(new OutputStreamWriter(System.out, IOUtils.getConsoleCharset()));
134 var outputWriter = outputType == null
135 ? null
136 : outputType == OutputType.JSON ? new JsonWriterImpl(writer) : new PlainTextWriterImpl(writer);
137
138 if (outputWriter != null && !command.getSupportedOutputTypes().contains(outputType)) {
139 throw new UserErrorException("Command doesn't support output type " + outputType);
140 }
141
142 var account = ns.getString("account");
143
144 final var useDbus = Boolean.TRUE.equals(ns.getBoolean("global-dbus"));
145 final var useDbusSystem = Boolean.TRUE.equals(ns.getBoolean("global-dbus-system"));
146 if (useDbus || useDbusSystem) {
147 // If account is null, it will connect to the default object path
148 initDbusClient(command, account, useDbusSystem, outputWriter);
149 return;
150 }
151
152 if (!Manager.isSignalClientAvailable()) {
153 throw new UserErrorException("Missing required native library dependency: libsignal-client");
154 }
155
156 final File configPath;
157 var config = ns.getString("config");
158 if (config != null) {
159 configPath = new File(config);
160 } else {
161 configPath = getDefaultConfigPath();
162 }
163
164 final var serviceEnvironmentCli = ns.<ServiceEnvironmentCli>get("service-environment");
165 final var serviceEnvironment = serviceEnvironmentCli == ServiceEnvironmentCli.LIVE
166 ? ServiceEnvironment.LIVE
167 : ServiceEnvironment.STAGING;
168
169 final var trustNewIdentityCli = ns.<TrustNewIdentityCli>get("trust-new-identities");
170 final var trustNewIdentity = trustNewIdentityCli == TrustNewIdentityCli.ON_FIRST_USE
171 ? TrustNewIdentity.ON_FIRST_USE
172 : trustNewIdentityCli == TrustNewIdentityCli.ALWAYS ? TrustNewIdentity.ALWAYS : TrustNewIdentity.NEVER;
173
174 final var disableSendLog = Boolean.TRUE.equals(ns.getBoolean("disable-send-log"));
175
176 final SignalAccountFiles signalAccountFiles;
177 try {
178 signalAccountFiles = new SignalAccountFiles(configPath,
179 serviceEnvironment,
180 BaseConfig.USER_AGENT,
181 new Settings(trustNewIdentity, disableSendLog));
182 } catch (IOException e) {
183 throw new IOErrorException("Failed to read local accounts list", e);
184 }
185
186 if (command instanceof ProvisioningCommand provisioningCommand) {
187 if (account != null) {
188 throw new UserErrorException("You cannot specify a account (phone number) when linking");
189 }
190
191 handleProvisioningCommand(provisioningCommand, signalAccountFiles, outputWriter);
192 return;
193 }
194
195 if (account == null) {
196 if (command instanceof MultiLocalCommand multiLocalCommand) {
197 handleMultiLocalCommand(multiLocalCommand, signalAccountFiles, outputWriter);
198 return;
199 }
200
201 Set<String> accounts = null;
202 try {
203 accounts = signalAccountFiles.getAllLocalAccountNumbers();
204 } catch (IOException e) {
205 throw new IOErrorException("Failed to load local accounts file", e);
206 }
207 if (accounts.size() == 0) {
208 throw new UserErrorException("No local users found, you first need to register or link an account");
209 } else if (accounts.size() > 1) {
210 throw new UserErrorException(
211 "Multiple users found, you need to specify an account (phone number) with -a");
212 }
213
214 account = accounts.stream().findFirst().get();
215 } else if (!Manager.isValidNumber(account, null)) {
216 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
217 }
218
219 if (command instanceof RegistrationCommand registrationCommand) {
220 handleRegistrationCommand(registrationCommand, account, signalAccountFiles);
221 return;
222 }
223
224 if (!(command instanceof LocalCommand)) {
225 throw new UserErrorException("Command only works in multi-account mode");
226 }
227
228 handleLocalCommand((LocalCommand) command, account, signalAccountFiles, outputWriter);
229 }
230
231 private void handleProvisioningCommand(
232 final ProvisioningCommand command,
233 final SignalAccountFiles signalAccountFiles,
234 final OutputWriter outputWriter
235 ) throws CommandException {
236 var pm = signalAccountFiles.initProvisioningManager();
237 command.handleCommand(ns, pm, outputWriter);
238 }
239
240 private void handleProvisioningCommand(
241 final ProvisioningCommand c, final DBusConnection dBusConn, final OutputWriter outputWriter
242 ) throws CommandException, DBusException {
243 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
244 DbusConfig.getObjectPath(),
245 SignalControl.class);
246 final var provisioningManager = new DbusProvisioningManagerImpl(signalControl, dBusConn);
247 try {
248 c.handleCommand(ns, provisioningManager, outputWriter);
249 } catch (UnsupportedOperationException e) {
250 throw new UserErrorException("Command is not yet implemented via dbus", e);
251 } catch (DBusExecutionException e) {
252 throw new UnexpectedErrorException(e.getMessage(), e);
253 }
254 }
255
256 private void handleRegistrationCommand(
257 final RegistrationCommand command, final String account, final SignalAccountFiles signalAccountFiles
258 ) throws CommandException {
259 try (final var manager = loadRegistrationManager(account, signalAccountFiles)) {
260 command.handleCommand(ns, manager);
261 } catch (IOException e) {
262 logger.warn("Cleanup failed", e);
263 }
264 }
265
266 private void handleRegistrationCommand(
267 final RegistrationCommand c, String account, final DBusConnection dBusConn, final OutputWriter outputWriter
268 ) throws CommandException, DBusException {
269 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
270 DbusConfig.getObjectPath(),
271 SignalControl.class);
272 try (final var registrationManager = new DbusRegistrationManagerImpl(account, signalControl, dBusConn)) {
273 c.handleCommand(ns, registrationManager);
274 } catch (UnsupportedOperationException e) {
275 throw new UserErrorException("Command is not yet implemented via dbus", e);
276 } catch (DBusExecutionException e) {
277 throw new UnexpectedErrorException(e.getMessage(), e);
278 }
279 }
280
281 private void handleLocalCommand(
282 final LocalCommand command,
283 final String account,
284 final SignalAccountFiles signalAccountFiles,
285 final OutputWriter outputWriter
286 ) throws CommandException {
287 try (var m = loadManager(account, signalAccountFiles)) {
288 command.handleCommand(ns, m, outputWriter);
289 } catch (IOException e) {
290 logger.warn("Cleanup failed", e);
291 }
292 }
293
294 private void handleLocalCommand(
295 final LocalCommand c,
296 String accountObjectPath,
297 final DBusConnection dBusConn,
298 final OutputWriter outputWriter
299 ) throws CommandException, DBusException {
300 var signal = dBusConn.getRemoteObject(DbusConfig.getBusname(), accountObjectPath, Signal.class);
301 try (final var m = new DbusManagerImpl(signal, dBusConn)) {
302 c.handleCommand(ns, m, outputWriter);
303 } catch (UnsupportedOperationException e) {
304 throw new UserErrorException("Command is not yet implemented via dbus", e);
305 } catch (DBusExecutionException e) {
306 throw new UnexpectedErrorException(e.getMessage(), e);
307 }
308 }
309
310 private void handleMultiLocalCommand(
311 final MultiLocalCommand command,
312 final SignalAccountFiles signalAccountFiles,
313 final OutputWriter outputWriter
314 ) throws CommandException {
315 try (var multiAccountManager = signalAccountFiles.initMultiAccountManager()) {
316 command.handleCommand(ns, multiAccountManager, outputWriter);
317 } catch (IOException e) {
318 throw new IOErrorException("Failed to load local accounts file", e);
319 }
320 }
321
322 private void handleMultiLocalCommand(
323 final MultiLocalCommand c, final DBusConnection dBusConn, final OutputWriter outputWriter
324 ) throws CommandException, DBusException {
325 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
326 DbusConfig.getObjectPath(),
327 SignalControl.class);
328 try (final var multiAccountManager = new DbusMultiAccountManagerImpl(signalControl, dBusConn)) {
329 c.handleCommand(ns, multiAccountManager, outputWriter);
330 } catch (UnsupportedOperationException e) {
331 throw new UserErrorException("Command is not yet implemented via dbus", e);
332 }
333 }
334
335 private RegistrationManager loadRegistrationManager(
336 final String account, final SignalAccountFiles signalAccountFiles
337 ) throws UnexpectedErrorException {
338 try {
339 return signalAccountFiles.initRegistrationManager(account);
340 } catch (Throwable e) {
341 throw new UnexpectedErrorException("Error loading or creating state file: "
342 + e.getMessage()
343 + " ("
344 + e.getClass().getSimpleName()
345 + ")", e);
346 }
347 }
348
349 private Manager loadManager(
350 final String account, final SignalAccountFiles signalAccountFiles
351 ) throws CommandException {
352 logger.trace("Loading account file for {}", account);
353 try {
354 return signalAccountFiles.initManager(account);
355 } catch (NotRegisteredException e) {
356 throw new UserErrorException("User " + account + " is not registered.");
357 } catch (AccountCheckException ace) {
358 if (ace.getCause() instanceof IOException e) {
359 throw new IOErrorException("Error while checking account " + account + ": " + e.getMessage(), e);
360 } else {
361 throw new UnexpectedErrorException("Error while checking account " + account + ": " + ace.getMessage(),
362 ace);
363 }
364 } catch (Throwable e) {
365 throw new UnexpectedErrorException("Error loading state file for user "
366 + account
367 + ": "
368 + e.getMessage()
369 + " ("
370 + e.getClass().getSimpleName()
371 + ")", e);
372 }
373 }
374
375 private void initDbusClient(
376 final Command command, final String account, final boolean systemBus, final OutputWriter outputWriter
377 ) throws CommandException {
378 try {
379 DBusConnection.DBusBusType busType;
380 if (systemBus) {
381 busType = DBusConnection.DBusBusType.SYSTEM;
382 } else {
383 busType = DBusConnection.DBusBusType.SESSION;
384 }
385 try (var dBusConn = DBusConnectionBuilder.forType(busType).build()) {
386 if (command instanceof ProvisioningCommand c) {
387 if (account != null) {
388 throw new UserErrorException("You cannot specify a account (phone number) when linking");
389 }
390
391 handleProvisioningCommand(c, dBusConn, outputWriter);
392 return;
393 }
394
395 if (account == null && command instanceof MultiLocalCommand c) {
396 handleMultiLocalCommand(c, dBusConn, outputWriter);
397 return;
398 }
399 if (account != null && command instanceof RegistrationCommand c) {
400 handleRegistrationCommand(c, account, dBusConn, outputWriter);
401 return;
402 }
403 if (!(command instanceof LocalCommand localCommand)) {
404 throw new UserErrorException("Command only works in multi-account mode");
405 }
406
407 var accountObjectPath = account == null ? tryGetSingleAccountObjectPath(dBusConn) : null;
408 if (accountObjectPath == null) {
409 accountObjectPath = DbusConfig.getObjectPath(account);
410 }
411 handleLocalCommand(localCommand, accountObjectPath, dBusConn, outputWriter);
412 }
413 } catch (ServiceUnknown e) {
414 throw new UserErrorException("signal-cli DBus daemon not running on "
415 + (systemBus ? "system" : "session")
416 + " bus: "
417 + e.getMessage(), e);
418 } catch (DBusExecutionException | DBusException | IOException e) {
419 throw new UnexpectedErrorException("Dbus client failed: " + e.getMessage(), e);
420 }
421 }
422
423 private String tryGetSingleAccountObjectPath(final DBusConnection dBusConn) throws DBusException, CommandException {
424 var control = dBusConn.getRemoteObject(DbusConfig.getBusname(),
425 DbusConfig.getObjectPath(),
426 SignalControl.class);
427 try {
428 final var accounts = control.listAccounts();
429 if (accounts.size() == 0) {
430 throw new UserErrorException("No local users found, you first need to register or link an account");
431 } else if (accounts.size() > 1) {
432 throw new UserErrorException(
433 "Multiple users found, you need to specify an account (phone number) with -a");
434 }
435
436 return accounts.get(0).getPath();
437 } catch (UnknownMethod e) {
438 // dbus daemon not running in multi-account mode
439 return null;
440 }
441 }
442
443 /**
444 * @return the default data directory to be used by signal-cli.
445 */
446 private static File getDefaultConfigPath() {
447 return new File(IOUtils.getDataHomeDir(), "signal-cli");
448 }
449 }