summaryrefslogtreecommitdiffstats
path: root/base/java-tools/src/com/netscape/cmstools/cli/MainCLI.java
blob: 2e661fcc6c152d9cb88c14b161b2bed0f8172223 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2012 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---

package com.netscape.cmstools.cli;

import java.io.File;
import java.net.URISyntaxException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.lang.StringUtils;
import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.crypto.CryptoToken;
import org.mozilla.jss.util.IncorrectPasswordException;
import org.mozilla.jss.util.Password;

import com.netscape.certsrv.account.AccountClient;
import com.netscape.certsrv.client.ClientConfig;
import com.netscape.certsrv.client.PKIConnection;
import com.netscape.cmstools.cert.CertCLI;
import com.netscape.cmstools.group.GroupCLI;
import com.netscape.cmstools.key.KeyCLI;
import com.netscape.cmstools.system.SecurityDomainCLI;
import com.netscape.cmstools.user.UserCLI;

/**
 * @author Endi S. Dewata
 */
public class MainCLI extends CLI {

    public ClientConfig config = new ClientConfig();

    public PKIConnection connection;
    public AccountClient accountClient;

    public MainCLI() throws Exception {
        super("pki", "PKI command-line interface");

        addModule(new CertCLI(this));
        addModule(new GroupCLI(this));
        addModule(new KeyCLI(this));
        addModule(new SecurityDomainCLI(this));
        addModule(new UserCLI(this));
    }

    public void printVersion() {
        Package pkg = MainCLI.class.getPackage();
        System.out.println("PKI Command-Line Interface "+pkg.getImplementationVersion());
    }

    public void printHelp() {

        formatter.printHelp(name+" [OPTIONS..] <command> [ARGS..]", options);

        System.out.println();
        System.out.println("Commands:");

        int leftPadding = 1;
        int rightPadding = 18;

        for (CLI plugin : modules.values()) {
            String label = plugin.getName();

            int padding = rightPadding - leftPadding - label.length();
            if (padding < 1) padding = 1;

            System.out.print(StringUtils.repeat(" ", leftPadding));
            System.out.print(label);
            System.out.print(StringUtils.repeat(" ", padding));
            System.out.println(plugin.getDescription());
        }
    }

    public void printHelpCommand(String pluginName) {
        CLI plugin = getModule(pluginName);
        plugin.printHelp();
    }

    public void createOptions(Options options) {

        Option option = new Option("U", true, "Server URI");
        option.setArgName("uri");
        options.addOption(option);

        option = new Option("P", true, "Protocol (default: http)");
        option.setArgName("protocol");
        options.addOption(option);

        option = new Option("h", true, "Hostname (default: localhost)");
        option.setArgName("hostname");
        options.addOption(option);

        option = new Option("p", true, "Port (default: 8080)");
        option.setArgName("port");
        options.addOption(option);

        option = new Option("t", true, "Subsystem type (default: ca)");
        option.setArgName("type");
        options.addOption(option);

        option = new Option("d", true, "Certificate database");
        option.setArgName("database");
        options.addOption(option);

        option = new Option("n", true, "Certificate nickname");
        option.setArgName("nickname");
        options.addOption(option);

        option = new Option("u", true, "Username");
        option.setArgName("username");
        options.addOption(option);

        option = new Option("w", true, "Password");
        option.setArgName("password");
        options.addOption(option);

        options.addOption("v", false, "Verbose");
        options.addOption(null, "help", false, "Help");
        options.addOption(null, "version", false, "Version");
    }

    public void parseOptions(CommandLine cmd) throws URISyntaxException {

        String uri = cmd.getOptionValue("U");

        String protocol = cmd.getOptionValue("P", "http");
        String hostname = cmd.getOptionValue("h", "localhost");
        String port = cmd.getOptionValue("p", "8080");
        String type = cmd.getOptionValue("t", "ca");

        if (uri == null)
            uri = protocol + "://" + hostname + ":" + port + "/" + type;

        config.setServerURI(uri);

        String certDatabase = cmd.getOptionValue("d");
        String certNickname = cmd.getOptionValue("n");
        String username = cmd.getOptionValue("u");
        String password = cmd.getOptionValue("w");

        // convert into absolute path
        if (certDatabase != null)
            config.setCertDatabase(new File(certDatabase).getAbsolutePath());

        if (certNickname != null)
            config.setCertNickname(certNickname);

        if (username != null)
            config.setUsername(username);

        if (password != null)
            config.setPassword(password);
    }

    public void connect() throws Exception {
        connection = new PKIConnection(config);
        connection.setVerbose(verbose);

        accountClient = new AccountClient(connection);
    }

    public void execute(String[] args) throws Exception {

        CLI module;
        String[] moduleArgs;

        try {
            createOptions(options);

            CommandLine cmd;
            try {
                cmd = parser.parse(options, args, true);
            } catch (Exception e) {
                throw new Error(e.getMessage(), e);
            }

            String[] cmdArgs = cmd.getArgs();

            if (cmd.hasOption("version")) {
                printVersion();
                System.exit(1);
            }

            if (cmdArgs.length == 0 || cmd.hasOption("help")) {
                printHelp();
                System.exit(1);
            }

            verbose = cmd.hasOption("v");

            if (verbose) {
                System.out.print("Command:");
                for (String arg : cmdArgs) {
                    if (arg.contains(" ")) arg = "\""+arg+"\"";
                    System.out.print(" "+arg);
                }
                System.out.println();
            }

            parseOptions(cmd);

            String command = cmdArgs[0];
            String moduleName;
            String moduleCommand;

            // If a command contains a '-' sign it will be
            // split into module name and module command.
            // Otherwise it's a single command.
            int i = command.indexOf('-');
            if (i >= 0) { // <module name>-<module command>
                moduleName = command.substring(0, i);
                moduleCommand = command.substring(i+1);

            } else { // <command>
                moduleName = command;
                moduleCommand = null;
            }

            // get command module
            module = getModule(moduleName);
            if (module == null)
                throw new Error("Invalid command \"" + command + "\".");

            // prepare module arguments
            if (moduleCommand != null) {
                moduleArgs = new String[cmdArgs.length];
                moduleArgs[0] = moduleCommand;
                System.arraycopy(cmdArgs, 1, moduleArgs, 1, cmdArgs.length-1);

            } else {
                moduleArgs = new String[cmdArgs.length-1];
                System.arraycopy(cmdArgs, 1, moduleArgs, 0, cmdArgs.length-1);
            }

        } catch (Throwable t) {
            if (verbose) {
                t.printStackTrace(System.err);
            } else {
                System.err.println(t.getClass().getSimpleName()+": "+t.getMessage());
            }
            printHelp();
            System.exit(1);
            return;
        }

        if (verbose) System.out.println("Server URI: "+config.getServerURI());

        // initialize certificate database if specified
        if (config.getCertDatabase() != null) {

            try {
                if (verbose) System.out.println("Certificate database: "+config.getCertDatabase());
                CryptoManager.initialize(config.getCertDatabase());

                if (config.getPassword() != null) {
                    try {
                        CryptoManager manager = CryptoManager.getInstance();
                        CryptoToken token = manager.getInternalKeyStorageToken();
                        Password password = new Password(config.getPassword().toCharArray());
                        token.login(password);

                    } catch (IncorrectPasswordException e) {
                        throw new Error("Incorrect certificate database password.", e);
                    }
                }

            } catch (Throwable t) {
                if (verbose) {
                    t.printStackTrace(System.err);
                } else {
                    System.err.println(t.getClass().getSimpleName()+": "+t.getMessage());
                }
                System.exit(1);
            }
        }

        // execute command
        boolean loggedIn = false;
        try {
            connect();

            // login
            if (config.getCertDatabase() != null || config.getUsername() != null) {
                accountClient.login();
                loggedIn = true;
            }

            // execute module command
            module.execute(moduleArgs);

        } catch (Throwable t) {
            if (verbose) {
                t.printStackTrace(System.err);
            } else {
                System.err.println(t.getClass().getSimpleName()+": "+t.getMessage());
            }
            System.exit(1);

        } finally {
            if (loggedIn) accountClient.logout();
        }
    }

    public static void printMessage(String message) {
        System.out.println(StringUtils.repeat("-", message.length()));
        System.out.println(message);
        System.out.println(StringUtils.repeat("-", message.length()));
    }

    public static void main(String args[]) throws Exception {
        MainCLI cli = new MainCLI();
        cli.execute(args);
    }
}