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