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