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