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