]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/App.java
Add --scrub-log flag to remove possibly sensitive information from the log
[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.SignalAccountFiles;
27 import org.asamk.signal.manager.api.AccountCheckException;
28 import org.asamk.signal.manager.api.NotRegisteredException;
29 import org.asamk.signal.manager.config.ServiceConfig;
30 import org.asamk.signal.manager.config.ServiceEnvironment;
31 import org.asamk.signal.manager.storage.identities.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 var subparsers = parser.addSubparsers().title("subcommands").dest("command");
105
106 Commands.getCommandSubparserAttachers().forEach((key, value) -> {
107 var subparser = subparsers.addParser(key);
108 value.attachToSubparser(subparser);
109 });
110
111 return parser;
112 }
113
114 public App(final Namespace ns) {
115 this.ns = ns;
116 }
117
118 public void init() throws CommandException {
119 var commandKey = ns.getString("command");
120 var command = Commands.getCommand(commandKey);
121 if (command == null) {
122 throw new UserErrorException("Command not implemented!");
123 }
124
125 var outputTypeInput = ns.<OutputType>get("output");
126 var outputType = outputTypeInput == null
127 ? command.getSupportedOutputTypes().stream().findFirst().orElse(null)
128 : outputTypeInput;
129 var writer = new BufferedWriter(new OutputStreamWriter(System.out, IOUtils.getConsoleCharset()));
130 var outputWriter = outputType == null
131 ? null
132 : outputType == OutputType.JSON ? new JsonWriterImpl(writer) : new PlainTextWriterImpl(writer);
133
134 if (outputWriter != null && !command.getSupportedOutputTypes().contains(outputType)) {
135 throw new UserErrorException("Command doesn't support output type " + outputType);
136 }
137
138 var account = ns.getString("account");
139
140 final var useDbus = Boolean.TRUE.equals(ns.getBoolean("global-dbus"));
141 final var useDbusSystem = Boolean.TRUE.equals(ns.getBoolean("global-dbus-system"));
142 if (useDbus || useDbusSystem) {
143 // If account is null, it will connect to the default object path
144 initDbusClient(command, account, useDbusSystem, outputWriter);
145 return;
146 }
147
148 if (!ServiceConfig.isSignalClientAvailable()) {
149 throw new UserErrorException("Missing required native library dependency: libsignal-client");
150 }
151
152 final File configPath;
153 var config = ns.getString("config");
154 if (config != null) {
155 configPath = new File(config);
156 } else {
157 configPath = getDefaultConfigPath();
158 }
159
160 final var serviceEnvironmentCli = ns.<ServiceEnvironmentCli>get("service-environment");
161 final var serviceEnvironment = serviceEnvironmentCli == ServiceEnvironmentCli.LIVE
162 ? ServiceEnvironment.LIVE
163 : ServiceEnvironment.STAGING;
164
165 final var trustNewIdentityCli = ns.<TrustNewIdentityCli>get("trust-new-identities");
166 final var trustNewIdentity = trustNewIdentityCli == TrustNewIdentityCli.ON_FIRST_USE
167 ? TrustNewIdentity.ON_FIRST_USE
168 : trustNewIdentityCli == TrustNewIdentityCli.ALWAYS ? TrustNewIdentity.ALWAYS : TrustNewIdentity.NEVER;
169
170 final SignalAccountFiles signalAccountFiles;
171 try {
172 signalAccountFiles = new SignalAccountFiles(configPath,
173 serviceEnvironment,
174 BaseConfig.USER_AGENT,
175 trustNewIdentity);
176 } catch (IOException e) {
177 throw new IOErrorException("Failed to read local accounts list", e);
178 }
179
180 if (command instanceof ProvisioningCommand provisioningCommand) {
181 if (account != null) {
182 throw new UserErrorException("You cannot specify a account (phone number) when linking");
183 }
184
185 handleProvisioningCommand(provisioningCommand, signalAccountFiles, outputWriter);
186 return;
187 }
188
189 if (account == null) {
190 if (command instanceof MultiLocalCommand multiLocalCommand) {
191 handleMultiLocalCommand(multiLocalCommand, signalAccountFiles, outputWriter);
192 return;
193 }
194
195 Set<String> accounts = null;
196 try {
197 accounts = signalAccountFiles.getAllLocalAccountNumbers();
198 } catch (IOException e) {
199 throw new IOErrorException("Failed to load local accounts file", e);
200 }
201 if (accounts.size() == 0) {
202 throw new UserErrorException("No local users found, you first need to register or link an account");
203 } else if (accounts.size() > 1) {
204 throw new UserErrorException(
205 "Multiple users found, you need to specify an account (phone number) with -a");
206 }
207
208 account = accounts.stream().findFirst().get();
209 } else if (!Manager.isValidNumber(account, null)) {
210 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
211 }
212
213 if (command instanceof RegistrationCommand registrationCommand) {
214 handleRegistrationCommand(registrationCommand, account, signalAccountFiles);
215 return;
216 }
217
218 if (!(command instanceof LocalCommand)) {
219 throw new UserErrorException("Command only works in multi-account mode");
220 }
221
222 handleLocalCommand((LocalCommand) command, account, signalAccountFiles, outputWriter);
223 }
224
225 private void handleProvisioningCommand(
226 final ProvisioningCommand command,
227 final SignalAccountFiles signalAccountFiles,
228 final OutputWriter outputWriter
229 ) throws CommandException {
230 var pm = signalAccountFiles.initProvisioningManager();
231 command.handleCommand(ns, pm, outputWriter);
232 }
233
234 private void handleProvisioningCommand(
235 final ProvisioningCommand c, final DBusConnection dBusConn, final OutputWriter outputWriter
236 ) throws CommandException, DBusException {
237 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
238 DbusConfig.getObjectPath(),
239 SignalControl.class);
240 final var provisioningManager = new DbusProvisioningManagerImpl(signalControl, dBusConn);
241 try {
242 c.handleCommand(ns, provisioningManager, outputWriter);
243 } catch (UnsupportedOperationException e) {
244 throw new UserErrorException("Command is not yet implemented via dbus", e);
245 } catch (DBusExecutionException e) {
246 throw new UnexpectedErrorException(e.getMessage(), e);
247 }
248 }
249
250 private void handleRegistrationCommand(
251 final RegistrationCommand command, final String account, final SignalAccountFiles signalAccountFiles
252 ) throws CommandException {
253 try (final var manager = loadRegistrationManager(account, signalAccountFiles)) {
254 command.handleCommand(ns, manager);
255 } catch (IOException e) {
256 logger.warn("Cleanup failed", e);
257 }
258 }
259
260 private void handleRegistrationCommand(
261 final RegistrationCommand c, String account, final DBusConnection dBusConn, final OutputWriter outputWriter
262 ) throws CommandException, DBusException {
263 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
264 DbusConfig.getObjectPath(),
265 SignalControl.class);
266 try (final var registrationManager = new DbusRegistrationManagerImpl(account, signalControl, dBusConn)) {
267 c.handleCommand(ns, registrationManager);
268 } catch (UnsupportedOperationException e) {
269 throw new UserErrorException("Command is not yet implemented via dbus", e);
270 } catch (DBusExecutionException e) {
271 throw new UnexpectedErrorException(e.getMessage(), e);
272 }
273 }
274
275 private void handleLocalCommand(
276 final LocalCommand command,
277 final String account,
278 final SignalAccountFiles signalAccountFiles,
279 final OutputWriter outputWriter
280 ) throws CommandException {
281 try (var m = loadManager(account, signalAccountFiles)) {
282 command.handleCommand(ns, m, outputWriter);
283 } catch (IOException e) {
284 logger.warn("Cleanup failed", e);
285 }
286 }
287
288 private void handleLocalCommand(
289 final LocalCommand c,
290 String accountObjectPath,
291 final DBusConnection dBusConn,
292 final OutputWriter outputWriter
293 ) throws CommandException, DBusException {
294 var signal = dBusConn.getRemoteObject(DbusConfig.getBusname(), accountObjectPath, Signal.class);
295 try (final var m = new DbusManagerImpl(signal, dBusConn)) {
296 c.handleCommand(ns, m, outputWriter);
297 } catch (UnsupportedOperationException e) {
298 throw new UserErrorException("Command is not yet implemented via dbus", e);
299 } catch (DBusExecutionException e) {
300 throw new UnexpectedErrorException(e.getMessage(), e);
301 }
302 }
303
304 private void handleMultiLocalCommand(
305 final MultiLocalCommand command,
306 final SignalAccountFiles signalAccountFiles,
307 final OutputWriter outputWriter
308 ) throws CommandException {
309 try (var multiAccountManager = signalAccountFiles.initMultiAccountManager()) {
310 command.handleCommand(ns, multiAccountManager, outputWriter);
311 } catch (IOException e) {
312 throw new IOErrorException("Failed to load local accounts file", e);
313 }
314 }
315
316 private void handleMultiLocalCommand(
317 final MultiLocalCommand c, final DBusConnection dBusConn, final OutputWriter outputWriter
318 ) throws CommandException, DBusException {
319 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
320 DbusConfig.getObjectPath(),
321 SignalControl.class);
322 try (final var multiAccountManager = new DbusMultiAccountManagerImpl(signalControl, dBusConn)) {
323 c.handleCommand(ns, multiAccountManager, outputWriter);
324 } catch (UnsupportedOperationException e) {
325 throw new UserErrorException("Command is not yet implemented via dbus", e);
326 }
327 }
328
329 private RegistrationManager loadRegistrationManager(
330 final String account, final SignalAccountFiles signalAccountFiles
331 ) throws UnexpectedErrorException {
332 try {
333 return signalAccountFiles.initRegistrationManager(account);
334 } catch (Throwable e) {
335 throw new UnexpectedErrorException("Error loading or creating state file: "
336 + e.getMessage()
337 + " ("
338 + e.getClass().getSimpleName()
339 + ")", e);
340 }
341 }
342
343 private Manager loadManager(
344 final String account, final SignalAccountFiles signalAccountFiles
345 ) throws CommandException {
346 logger.trace("Loading account file for {}", account);
347 try {
348 return signalAccountFiles.initManager(account);
349 } catch (NotRegisteredException e) {
350 throw new UserErrorException("User " + account + " is not registered.");
351 } catch (AccountCheckException ace) {
352 if (ace.getCause() instanceof IOException e) {
353 throw new IOErrorException("Error while checking account " + account + ": " + e.getMessage(), e);
354 } else {
355 throw new UnexpectedErrorException("Error while checking account " + account + ": " + ace.getMessage(),
356 ace);
357 }
358 } catch (Throwable e) {
359 throw new UnexpectedErrorException("Error loading state file for user "
360 + account
361 + ": "
362 + e.getMessage()
363 + " ("
364 + e.getClass().getSimpleName()
365 + ")", e);
366 }
367 }
368
369 private void initDbusClient(
370 final Command command, final String account, final boolean systemBus, final OutputWriter outputWriter
371 ) throws CommandException {
372 try {
373 DBusConnection.DBusBusType busType;
374 if (systemBus) {
375 busType = DBusConnection.DBusBusType.SYSTEM;
376 } else {
377 busType = DBusConnection.DBusBusType.SESSION;
378 }
379 try (var dBusConn = DBusConnectionBuilder.forType(busType).build()) {
380 if (command instanceof ProvisioningCommand c) {
381 if (account != null) {
382 throw new UserErrorException("You cannot specify a account (phone number) when linking");
383 }
384
385 handleProvisioningCommand(c, dBusConn, outputWriter);
386 return;
387 }
388
389 if (account == null && command instanceof MultiLocalCommand c) {
390 handleMultiLocalCommand(c, dBusConn, outputWriter);
391 return;
392 }
393 if (account != null && command instanceof RegistrationCommand c) {
394 handleRegistrationCommand(c, account, dBusConn, outputWriter);
395 return;
396 }
397 if (!(command instanceof LocalCommand localCommand)) {
398 throw new UserErrorException("Command only works in multi-account mode");
399 }
400
401 var accountObjectPath = account == null ? tryGetSingleAccountObjectPath(dBusConn) : null;
402 if (accountObjectPath == null) {
403 accountObjectPath = DbusConfig.getObjectPath(account);
404 }
405 handleLocalCommand(localCommand, accountObjectPath, dBusConn, outputWriter);
406 }
407 } catch (ServiceUnknown e) {
408 throw new UserErrorException("signal-cli DBus daemon not running on "
409 + (systemBus ? "system" : "session")
410 + " bus: "
411 + e.getMessage(), e);
412 } catch (DBusExecutionException | DBusException | IOException e) {
413 throw new UnexpectedErrorException("Dbus client failed: " + e.getMessage(), e);
414 }
415 }
416
417 private String tryGetSingleAccountObjectPath(final DBusConnection dBusConn) throws DBusException, CommandException {
418 var control = dBusConn.getRemoteObject(DbusConfig.getBusname(),
419 DbusConfig.getObjectPath(),
420 SignalControl.class);
421 try {
422 final var accounts = control.listAccounts();
423 if (accounts.size() == 0) {
424 throw new UserErrorException("No local users found, you first need to register or link an account");
425 } else if (accounts.size() > 1) {
426 throw new UserErrorException(
427 "Multiple users found, you need to specify an account (phone number) with -a");
428 }
429
430 return accounts.get(0).getPath();
431 } catch (UnknownMethod e) {
432 // dbus daemon not running in multi-account mode
433 return null;
434 }
435 }
436
437 /**
438 * @return the default data directory to be used by signal-cli.
439 */
440 private static File getDefaultConfigPath() {
441 return new File(IOUtils.getDataHomeDir(), "signal-cli");
442 }
443 }