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