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