View Javadoc

1   /*
2    * AbstractWebCommand.java
3    *
4    * Created on November 4, 2004, 10:07 AM
5    */
6   package gov.bnl.gums.command;
7   
8   
9   import javax.net.ssl.X509KeyManager;
10  import java.security.cert.X509Certificate;
11  import org.apache.axis.AxisFault;
12  
13  import org.apache.commons.cli.*;
14  import org.apache.commons.logging.Log;
15  import org.apache.commons.logging.LogFactory;
16  
17  import java.net.ConnectException;
18  
19  import gov.bnl.gums.admin.*;
20  import org.glite.security.trustmanager.ContextWrapper;
21  
22  
23  /***
24   * @author carcassi
25   */
26  public abstract class AbstractCommand {
27      protected static AbstractCommand command;
28      private Log log = LogFactory.getLog(AbstractCommand.class);
29      protected String commandName;
30      protected String syntax;
31      protected String description;
32      protected boolean failOnArguments;
33  
34      /***
35       * Creates a new AbstractWebCommand object.
36       */
37      public AbstractCommand() {
38          String className = getClass().getName();
39  
40          commandName = CommandLineToolkit.getCommandName(className);
41      }
42      
43      private String clientDN;
44      private boolean usingProxy;
45      private void initClientCred() {
46          // If DN is already found, no need to find it again...
47          if (clientDN != null) return;
48          
49          log.trace("Retrieving client credentials");
50          
51          try {
52              ContextWrapper wrapper = new ContextWrapper(System.getProperties());
53              X509KeyManager manager = wrapper.getKeyManager();
54              String[] aliases = manager.getClientAliases("RSA", null);
55              
56              if ((aliases == null) || (aliases.length == 0)) {
57                  System.err.println("\nThe user credentials loading failed");
58                  System.exit(-1);
59              }
60              
61              X509Certificate[] chain = manager.getCertificateChain(aliases[0]);
62              
63              X509Certificate cert = chain[0];
64              log.trace("Certificate retrieved: " + cert);
65              clientDN = CertToolkit.getUserDN(cert);
66              String commaDN = cert.getSubjectX500Principal().toString();
67              String certDN = CertToolkit.convertDN(commaDN);
68              log.trace("Certificate subject: " + certDN);
69              log.trace("Client DN: " + clientDN);
70              if (!clientDN.equals(certDN)) {
71                  log.trace("Using proxy");
72                  usingProxy = true;
73              } else {
74                  log.trace("Not using proxy");
75                  usingProxy = false;
76              }
77          } catch (Exception e) {
78              log.error("Couldn't retrieve client credentials", e);
79              return;
80          }
81      }
82      
83      protected String getClientDN() {
84          initClientCred();
85          return clientDN;
86      }
87      
88      protected boolean isUsingProxy() {
89          initClientCred();
90          return usingProxy;
91      }
92  
93      protected abstract GUMSAPI getGums();
94  
95      protected CommandLine parse(Options options, String[] args) {
96          CommandLineParser parser = new BasicParser();
97          CommandLine commands = null;
98  
99          try {
100             commands = parser.parse(options, args);
101 
102             if (commands.hasOption("help")) {
103                 printHelp(options);
104                 System.exit(0);
105             }
106 
107             if (failOnArguments && (commands.getArgs() != null) &&
108                     (commands.getArgs().length > 0)) {
109                 System.out.println("The command doesn't accept arguments");
110                 printHelp(options);
111                 System.exit(-1);
112             }
113         } catch (UnrecognizedOptionException e) {
114             System.out.println(e.getMessage());
115             printHelp(options);
116             log.debug("Bogus option", e);
117             System.exit(-1);
118         } catch (ParseException pe) {
119             System.out.println("Command line error:" + pe.getMessage());
120             printHelp(options);
121             log.info("Command line error", pe);
122             System.exit(-1);
123         }
124 
125         return commands;
126     }
127 
128     protected void printHelp(Options options) {
129         HelpFormatter formatter = new HelpFormatter();
130 
131         formatter.printHelp("gums " + commandName + " " + syntax,
132             description + "\n\nOptions:", options, "");
133     }
134 
135     protected void failForWrongParameters(String message) {
136         System.out.println(message);
137         System.out.println("Try `gums " + commandName +
138             " --help' for more information.");
139         System.exit(-1);
140     }
141 
142     protected abstract void execute(CommandLine cmd) throws Exception;
143 
144     protected abstract Options buildOptions();
145 
146     protected void execute(String[] args) {
147         Options options = buildOptions();
148         Option help = OptionBuilder.withLongOpt("help")
149                                    .withDescription("print this message")
150                                    .create();
151 
152         //new Option("?", "help",false,"print this message");
153         options.addOption(help);
154 
155         CommandLine cmd = parse(options, args);
156 
157         try {
158             execute(cmd);
159         } catch (AxisFault e) {
160             if (e.getCause() != null) {
161                 log.info("An error accoured when connection to GUMS", e);
162 
163                 if (e.getCause() instanceof ConnectException) {
164                     System.err.println(
165                         "Couldn't connect to the GUMS server. " +
166                         "Check that your gums-client.properties configuration is pointing to the correct server, " +
167                         "that there are no firewall or network problem, and that the server is up.");
168                     System.err.println(
169                         "[Error message: " +
170                         e.getCause().getMessage() + "]");
171                 } else if (e.getCause() instanceof java.security.cert.CertificateExpiredException) {
172                     System.err.println("Please renew your proxy, or renew your certificate if expired.");
173                     System.err.println(
174                         "[Error message: " +
175                         e.getCause().getMessage() + "]");
176                 } else if ((e.getCause() instanceof java.security.cert.CertificateException) && 
177                            (e.getCause().getMessage().indexOf("(No such file or directory)") != -1) &&
178                            (e.getCause().getMessage().indexOf("/tmp/x509up_u") != -1)) {
179                     System.err.println("Couldn't find your proxy: please generate your proxy");
180                     System.err.println(
181                         "[Error message: " +
182                         e.getCause().getMessage() + "]");
183                 } else if ((e.getCause() instanceof java.security.cert.CertificateException) &&
184                            (e.getCause().getMessage().indexOf("(Permission denied)") != -1) &&
185                            (e.getCause().getMessage().indexOf("key.pem") != -1)) {
186                     System.err.println("Couldn't read the private key: check that you are running as the correct user and check private key file ownership");
187                     System.err.println(
188                         "[Error message: " +
189                         e.getCause().getMessage() + "]");
190                 } else {
191                     System.err.println(
192                         "An error accoured when connection to GUMS: " +
193                         e.getCause().getMessage());
194                 }
195                 
196             } else {
197                 if (e.getFaultString().indexOf("(0)null") != -1) {
198                     System.err.println("There was a problem connecting to the GUMS server.");
199                     System.err.println("Try using an old-style proxy (i.e. 'grid-proxy-init -old').");
200                     System.err.println(
201                         "[Error message: " +
202                         e.getMessage() + "]");
203                 } else {
204                     System.err.println(
205                         "An error accoured when connecting to GUMS: " +
206                         e.getMessage());
207                     log.info("An error accoured when connecting to GUMS", e);
208                 }
209             }
210             System.exit(-1);
211         } catch (Exception e) {
212             System.out.println("Unexpected error: " + e.getMessage());
213             System.out.println("Full stack trace follows (give it to support):");
214             System.out.println("-------------------------");
215             e.printStackTrace(System.out);
216             log.error("Unexpected error", e);
217             System.exit(-1);
218         }
219     }
220 
221     /***
222      * TODO: write doc
223      *
224      * @param args TODO: write doc
225      */
226     public static void main(String[] args) {
227         command.execute(args);
228     }
229 }