]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/Main.java
Use File instead of String
[signal-cli] / src / main / java / org / asamk / signal / Main.java
1 /*
2 Copyright (C) 2015-2020 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.dbus.DbusSignalImpl;
36 import org.asamk.signal.manager.Manager;
37 import org.asamk.signal.manager.ProvisioningManager;
38 import org.asamk.signal.manager.ServiceConfig;
39 import org.asamk.signal.util.IOUtils;
40 import org.asamk.signal.util.SecurityProvider;
41 import org.bouncycastle.jce.provider.BouncyCastleProvider;
42 import org.freedesktop.dbus.connections.impl.DBusConnection;
43 import org.freedesktop.dbus.exceptions.DBusException;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedException;
47 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
48 import org.whispersystems.signalservice.internal.configuration.SignalServiceConfiguration;
49
50 import java.io.File;
51 import java.io.IOException;
52 import java.security.Security;
53 import java.util.Map;
54
55 public class Main {
56
57 final static Logger logger = LoggerFactory.getLogger(Main.class);
58
59 public static void main(String[] args) {
60 installSecurityProviderWorkaround();
61
62 Namespace ns = parseArgs(args);
63 if (ns == null) {
64 System.exit(1);
65 }
66
67 int res = init(ns);
68 System.exit(res);
69 }
70
71 public static void installSecurityProviderWorkaround() {
72 // Register our own security provider
73 Security.insertProviderAt(new SecurityProvider(), 1);
74 Security.addProvider(new BouncyCastleProvider());
75 }
76
77 public static int init(Namespace ns) {
78 if (ns.getBoolean("dbus") || ns.getBoolean("dbus_system")) {
79 return initDbusClient(ns, ns.getBoolean("dbus_system"));
80 }
81
82 final String username = ns.getString("username");
83
84 final File dataPath;
85 String config = ns.getString("config");
86 if (config != null) {
87 dataPath = new File(config);
88 } else {
89 dataPath = getDefaultDataPath();
90 }
91
92 final SignalServiceConfiguration serviceConfiguration = ServiceConfig.createDefaultServiceConfiguration(
93 BaseConfig.USER_AGENT);
94
95 if (!ServiceConfig.getCapabilities().isGv2()) {
96 logger.warn("WARNING: Support for new group V2 is disabled,"
97 + " because the required native library dependency is missing: libzkgroup");
98 }
99
100 if (username == null) {
101 ProvisioningManager pm = new ProvisioningManager(dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
102 return handleCommands(ns, pm);
103 }
104
105 Manager manager;
106 try {
107 manager = Manager.init(username, dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
108 } catch (Throwable e) {
109 logger.error("Error loading state file: {}", e.getMessage());
110 return 2;
111 }
112
113 try (Manager m = manager) {
114 try {
115 m.checkAccountState();
116 } catch (AuthorizationFailedException e) {
117 if (!"register".equals(ns.getString("command"))) {
118 // Register command should still be possible, if current authorization fails
119 System.err.println("Authorization failed, was the number registered elsewhere?");
120 return 2;
121 }
122 } catch (IOException e) {
123 logger.error("Error while checking account: {}", e.getMessage());
124 return 2;
125 }
126
127 return handleCommands(ns, m);
128 } catch (IOException e) {
129 logger.error("Cleanup failed", e);
130 return 3;
131 }
132 }
133
134 private static int initDbusClient(final Namespace ns, final boolean systemBus) {
135 try {
136 DBusConnection.DBusBusType busType;
137 if (systemBus) {
138 busType = DBusConnection.DBusBusType.SYSTEM;
139 } else {
140 busType = DBusConnection.DBusBusType.SESSION;
141 }
142 try (DBusConnection dBusConn = DBusConnection.getConnection(busType)) {
143 Signal ts = dBusConn.getRemoteObject(DbusConfig.SIGNAL_BUSNAME,
144 DbusConfig.SIGNAL_OBJECTPATH,
145 Signal.class);
146
147 return handleCommands(ns, ts, dBusConn);
148 }
149 } catch (DBusException | IOException e) {
150 logger.error("Dbus client failed", e);
151 return 3;
152 }
153 }
154
155 private static int handleCommands(Namespace ns, Signal ts, DBusConnection dBusConn) {
156 String commandKey = ns.getString("command");
157 final Map<String, Command> commands = Commands.getCommands();
158 if (commands.containsKey(commandKey)) {
159 Command command = commands.get(commandKey);
160
161 if (command instanceof ExtendedDbusCommand) {
162 return ((ExtendedDbusCommand) command).handleCommand(ns, ts, dBusConn);
163 } else if (command instanceof DbusCommand) {
164 return ((DbusCommand) command).handleCommand(ns, ts);
165 } else {
166 System.err.println(commandKey + " is not yet implemented via dbus");
167 return 1;
168 }
169 }
170 return 0;
171 }
172
173 private static int handleCommands(Namespace ns, ProvisioningManager pm) {
174 String commandKey = ns.getString("command");
175 final Map<String, Command> commands = Commands.getCommands();
176 if (commands.containsKey(commandKey)) {
177 Command command = commands.get(commandKey);
178
179 if (command instanceof ProvisioningCommand) {
180 return ((ProvisioningCommand) command).handleCommand(ns, pm);
181 } else {
182 System.err.println(commandKey + " only works with a username");
183 return 1;
184 }
185 }
186 return 0;
187 }
188
189 private static int handleCommands(Namespace ns, Manager m) {
190 String commandKey = ns.getString("command");
191 final Map<String, Command> commands = Commands.getCommands();
192 if (commands.containsKey(commandKey)) {
193 Command command = commands.get(commandKey);
194
195 if (command instanceof LocalCommand) {
196 return ((LocalCommand) command).handleCommand(ns, m);
197 } else if (command instanceof DbusCommand) {
198 return ((DbusCommand) command).handleCommand(ns, new DbusSignalImpl(m));
199 } else if (command instanceof ExtendedDbusCommand) {
200 System.err.println(commandKey + " only works via dbus");
201 }
202 return 1;
203 }
204 return 0;
205 }
206
207 /**
208 * Uses $XDG_DATA_HOME/signal-cli if it exists, or if none of the legacy directories exist:
209 * - $HOME/.config/signal
210 * - $HOME/.config/textsecure
211 *
212 * @return the data directory to be used by signal-cli.
213 */
214 private static File getDefaultDataPath() {
215 File dataPath = new File(IOUtils.getDataHomeDir(), "signal-cli");
216 if (dataPath.exists()) {
217 return dataPath;
218 }
219
220 File configPath = new File(System.getProperty("user.home"), ".config");
221
222 File legacySettingsPath = new File(configPath, "signal");
223 if (legacySettingsPath.exists()) {
224 return legacySettingsPath;
225 }
226
227 legacySettingsPath = new File(configPath, "textsecure");
228 if (legacySettingsPath.exists()) {
229 return legacySettingsPath;
230 }
231
232 return dataPath;
233 }
234
235 private static Namespace parseArgs(String[] args) {
236 ArgumentParser parser = buildArgumentParser();
237
238 Namespace ns;
239 try {
240 ns = parser.parseArgs(args);
241 } catch (ArgumentParserException e) {
242 parser.handleError(e);
243 return null;
244 }
245
246 if ("link".equals(ns.getString("command"))) {
247 if (ns.getString("username") != null) {
248 parser.printUsage();
249 System.err.println("You cannot specify a username (phone number) when linking");
250 System.exit(2);
251 }
252 } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) {
253 if (ns.getString("username") == null) {
254 parser.printUsage();
255 System.err.println("You need to specify a username (phone number)");
256 System.exit(2);
257 }
258 if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"), null)) {
259 System.err.println("Invalid username (phone number), make sure you include the country code.");
260 System.exit(2);
261 }
262 }
263 if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
264 System.err.println("You cannot specify recipients by phone number and groups at the same time");
265 System.exit(2);
266 }
267 return ns;
268 }
269
270 private static ArgumentParser buildArgumentParser() {
271 ArgumentParser parser = ArgumentParsers.newFor("signal-cli")
272 .build()
273 .defaultHelp(true)
274 .description("Commandline interface for Signal.")
275 .version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
276
277 parser.addArgument("-v", "--version").help("Show package version.").action(Arguments.version());
278 parser.addArgument("--config")
279 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
280
281 MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
282 mut.addArgument("-u", "--username").help("Specify your phone number, that will be used for verification.");
283 mut.addArgument("--dbus").help("Make request via user dbus.").action(Arguments.storeTrue());
284 mut.addArgument("--dbus-system").help("Make request via system dbus.").action(Arguments.storeTrue());
285
286 Subparsers subparsers = parser.addSubparsers()
287 .title("subcommands")
288 .dest("command")
289 .description("valid subcommands")
290 .help("additional help");
291
292 final Map<String, Command> commands = Commands.getCommands();
293 for (Map.Entry<String, Command> entry : commands.entrySet()) {
294 Subparser subparser = subparsers.addParser(entry.getKey());
295 entry.getValue().attachToSubparser(subparser);
296 }
297 return parser;
298 }
299 }