]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/Main.java
Make loggers private
[signal-cli] / src / main / java / org / asamk / signal / Main.java
1 /*
2 Copyright (C) 2015-2021 AsamK and contributors
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package org.asamk.signal;
18
19 import net.sourceforge.argparse4j.ArgumentParsers;
20 import net.sourceforge.argparse4j.impl.Arguments;
21 import net.sourceforge.argparse4j.inf.ArgumentParser;
22 import net.sourceforge.argparse4j.inf.ArgumentParserException;
23 import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
24 import net.sourceforge.argparse4j.inf.Namespace;
25 import net.sourceforge.argparse4j.inf.Subparser;
26 import net.sourceforge.argparse4j.inf.Subparsers;
27
28 import org.asamk.Signal;
29 import org.asamk.signal.commands.Command;
30 import org.asamk.signal.commands.Commands;
31 import org.asamk.signal.commands.DbusCommand;
32 import org.asamk.signal.commands.ExtendedDbusCommand;
33 import org.asamk.signal.commands.LocalCommand;
34 import org.asamk.signal.commands.ProvisioningCommand;
35 import org.asamk.signal.commands.RegistrationCommand;
36 import org.asamk.signal.dbus.DbusSignalImpl;
37 import org.asamk.signal.manager.Manager;
38 import org.asamk.signal.manager.NotRegisteredException;
39 import org.asamk.signal.manager.ProvisioningManager;
40 import org.asamk.signal.manager.RegistrationManager;
41 import org.asamk.signal.manager.ServiceConfig;
42 import org.asamk.signal.util.IOUtils;
43 import org.asamk.signal.util.SecurityProvider;
44 import org.bouncycastle.jce.provider.BouncyCastleProvider;
45 import org.freedesktop.dbus.connections.impl.DBusConnection;
46 import org.freedesktop.dbus.exceptions.DBusException;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
50 import org.whispersystems.signalservice.internal.configuration.SignalServiceConfiguration;
51
52 import java.io.File;
53 import java.io.IOException;
54 import java.security.Security;
55 import java.util.Map;
56
57 public class Main {
58
59 private final static Logger logger = LoggerFactory.getLogger(Main.class);
60
61 public static void main(String[] args) {
62 installSecurityProviderWorkaround();
63
64 Namespace ns = parseArgs(args);
65 if (ns == null) {
66 System.exit(1);
67 }
68
69 int res = init(ns);
70 System.exit(res);
71 }
72
73 public static void installSecurityProviderWorkaround() {
74 // Register our own security provider
75 Security.insertProviderAt(new SecurityProvider(), 1);
76 Security.addProvider(new BouncyCastleProvider());
77 }
78
79 public static int init(Namespace ns) {
80 Command command = getCommand(ns);
81 if (command == null) {
82 logger.error("Command not implemented!");
83 return 3;
84 }
85
86 if (ns.getBoolean("dbus") || ns.getBoolean("dbus_system")) {
87 return initDbusClient(command, ns, ns.getBoolean("dbus_system"));
88 }
89
90 final String username = ns.getString("username");
91
92 final File dataPath;
93 String config = ns.getString("config");
94 if (config != null) {
95 dataPath = new File(config);
96 } else {
97 dataPath = getDefaultDataPath();
98 }
99
100 final SignalServiceConfiguration serviceConfiguration = ServiceConfig.createDefaultServiceConfiguration(
101 BaseConfig.USER_AGENT);
102
103 if (!ServiceConfig.getCapabilities().isGv2()) {
104 logger.warn("WARNING: Support for new group V2 is disabled,"
105 + " because the required native library dependency is missing: libzkgroup");
106 }
107
108 if (username == null) {
109 ProvisioningManager pm = new ProvisioningManager(dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
110 return handleCommand(command, ns, pm);
111 }
112
113 if (command instanceof RegistrationCommand) {
114 final RegistrationManager manager;
115 try {
116 manager = RegistrationManager.init(username, dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
117 } catch (Throwable e) {
118 logger.error("Error loading or creating state file: {}", e.getMessage());
119 return 2;
120 }
121 try (RegistrationManager m = manager) {
122 return handleCommand(command, ns, m);
123 } catch (Exception e) {
124 logger.error("Cleanup failed", e);
125 return 3;
126 }
127 }
128
129 Manager manager;
130 try {
131 manager = Manager.init(username, dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
132 } catch (NotRegisteredException e) {
133 System.err.println("User is not registered.");
134 return 1;
135 } catch (Throwable e) {
136 logger.error("Error loading state file: {}", e.getMessage());
137 return 2;
138 }
139
140 try (Manager m = manager) {
141 try {
142 m.checkAccountState();
143 } catch (IOException e) {
144 logger.error("Error while checking account: {}", e.getMessage());
145 return 2;
146 }
147
148 return handleCommand(command, ns, m);
149 } catch (IOException e) {
150 logger.error("Cleanup failed", e);
151 return 3;
152 }
153 }
154
155 private static int initDbusClient(final Command command, final Namespace ns, final boolean systemBus) {
156 try {
157 DBusConnection.DBusBusType busType;
158 if (systemBus) {
159 busType = DBusConnection.DBusBusType.SYSTEM;
160 } else {
161 busType = DBusConnection.DBusBusType.SESSION;
162 }
163 try (DBusConnection dBusConn = DBusConnection.getConnection(busType)) {
164 Signal ts = dBusConn.getRemoteObject(DbusConfig.SIGNAL_BUSNAME,
165 DbusConfig.SIGNAL_OBJECTPATH,
166 Signal.class);
167
168 return handleCommand(command, ns, ts, dBusConn);
169 }
170 } catch (DBusException | IOException e) {
171 logger.error("Dbus client failed", e);
172 return 3;
173 }
174 }
175
176 private static Command getCommand(Namespace ns) {
177 String commandKey = ns.getString("command");
178 final Map<String, Command> commands = Commands.getCommands();
179 if (!commands.containsKey(commandKey)) {
180 return null;
181 }
182 return commands.get(commandKey);
183 }
184
185 private static int handleCommand(Command command, Namespace ns, Signal ts, DBusConnection dBusConn) {
186 if (command instanceof ExtendedDbusCommand) {
187 return ((ExtendedDbusCommand) command).handleCommand(ns, ts, dBusConn);
188 } else if (command instanceof DbusCommand) {
189 return ((DbusCommand) command).handleCommand(ns, ts);
190 } else {
191 System.err.println("Command is not yet implemented via dbus");
192 return 1;
193 }
194 }
195
196 private static int handleCommand(Command command, Namespace ns, ProvisioningManager pm) {
197 if (command instanceof ProvisioningCommand) {
198 return ((ProvisioningCommand) command).handleCommand(ns, pm);
199 } else {
200 System.err.println("Command only works with a username");
201 return 1;
202 }
203 }
204
205 private static int handleCommand(Command command, Namespace ns, RegistrationManager m) {
206 if (command instanceof RegistrationCommand) {
207 return ((RegistrationCommand) command).handleCommand(ns, m);
208 }
209 return 1;
210 }
211
212 private static int handleCommand(Command command, Namespace ns, Manager m) {
213 if (command instanceof LocalCommand) {
214 return ((LocalCommand) command).handleCommand(ns, m);
215 } else if (command instanceof DbusCommand) {
216 return ((DbusCommand) command).handleCommand(ns, new DbusSignalImpl(m));
217 } else {
218 System.err.println("Command only works via dbus");
219 return 1;
220 }
221 }
222
223 /**
224 * Uses $XDG_DATA_HOME/signal-cli if it exists, or if none of the legacy directories exist:
225 * - $HOME/.config/signal
226 * - $HOME/.config/textsecure
227 *
228 * @return the data directory to be used by signal-cli.
229 */
230 private static File getDefaultDataPath() {
231 File dataPath = new File(IOUtils.getDataHomeDir(), "signal-cli");
232 if (dataPath.exists()) {
233 return dataPath;
234 }
235
236 File configPath = new File(System.getProperty("user.home"), ".config");
237
238 File legacySettingsPath = new File(configPath, "signal");
239 if (legacySettingsPath.exists()) {
240 return legacySettingsPath;
241 }
242
243 legacySettingsPath = new File(configPath, "textsecure");
244 if (legacySettingsPath.exists()) {
245 return legacySettingsPath;
246 }
247
248 return dataPath;
249 }
250
251 private static Namespace parseArgs(String[] args) {
252 ArgumentParser parser = buildArgumentParser();
253
254 Namespace ns;
255 try {
256 ns = parser.parseArgs(args);
257 } catch (ArgumentParserException e) {
258 parser.handleError(e);
259 return null;
260 }
261
262 if ("link".equals(ns.getString("command"))) {
263 if (ns.getString("username") != null) {
264 parser.printUsage();
265 System.err.println("You cannot specify a username (phone number) when linking");
266 System.exit(2);
267 }
268 } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) {
269 if (ns.getString("username") == null) {
270 parser.printUsage();
271 System.err.println("You need to specify a username (phone number)");
272 System.exit(2);
273 }
274 if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"), null)) {
275 System.err.println("Invalid username (phone number), make sure you include the country code.");
276 System.exit(2);
277 }
278 }
279 if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
280 System.err.println("You cannot specify recipients by phone number and groups at the same time");
281 System.exit(2);
282 }
283 return ns;
284 }
285
286 private static ArgumentParser buildArgumentParser() {
287 ArgumentParser parser = ArgumentParsers.newFor("signal-cli")
288 .build()
289 .defaultHelp(true)
290 .description("Commandline interface for Signal.")
291 .version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
292
293 parser.addArgument("-v", "--version").help("Show package version.").action(Arguments.version());
294 parser.addArgument("--config")
295 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
296
297 MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
298 mut.addArgument("-u", "--username").help("Specify your phone number, that will be used for verification.");
299 mut.addArgument("--dbus").help("Make request via user dbus.").action(Arguments.storeTrue());
300 mut.addArgument("--dbus-system").help("Make request via system dbus.").action(Arguments.storeTrue());
301
302 parser.addArgument("-o", "--output").help("Choose to output in plain text or JSON")
303 .choices("plain-text", "json").setDefault("plain-text");
304
305 Subparsers subparsers = parser.addSubparsers()
306 .title("subcommands")
307 .dest("command")
308 .description("valid subcommands")
309 .help("additional help");
310
311 final Map<String, Command> commands = Commands.getCommands();
312 for (Map.Entry<String, Command> entry : commands.entrySet()) {
313 Subparser subparser = subparsers.addParser(entry.getKey());
314 entry.getValue().attachToSubparser(subparser);
315 }
316 return parser;
317 }
318 }