1 /* Engine -- generic getInstance method.
2    Copyright (C) 2003  Free Software Foundation, Inc.
3 
4 This file is part of GNU Classpath.
5 
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10 
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 General Public License for more details.
15 
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING.  If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
20 
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library.  Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
25 
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module.  An independent module is a module which is not derived from
33 or based on this library.  If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so.  If you do not wish to do so, delete this
36 exception statement from your version. */
37 
38 package gnu.java.security;
39 
40 import java.lang.reflect.Constructor;
41 import java.lang.reflect.InvocationTargetException;
42 
43 import java.security.NoSuchAlgorithmException;
44 import java.security.Provider;
45 
46 /**
47  * Generic implementation of the getInstance methods in the various
48  * engine classes in java.security.
49  * <p>
50  * These classes ({@link java.security.Signature} for example) can be
51  * thought of as the "chrome, upholstery, and steering wheel", and the SPI
52  * (service provider interface, e.g. {@link java.security.SignatureSpi})
53  * classes can be thought of as the "engine" -- providing the actual
54  * functionality of whatever cryptographic algorithm the instance
55  * represents.
56  *
57  * @see Provider
58  * @author Casey Marshall
59  */
60 public final class Engine
61 {
62 
63   // Constants.
64   // ------------------------------------------------------------------------
65 
66   /** Prefix for aliases. */
67   private static final String ALG_ALIAS = "Alg.Alias.";
68 
69   /** Maximum number of aliases to try. */
70   private static final int MAX_ALIASES = 5;
71 
72   /** Argument list for no-argument constructors. */
73   private static final Object[] NO_ARGS = new Object[0];
74 
75   // Constructor.
76   // ------------------------------------------------------------------------
77 
78   /** This class cannot be instantiated. */
Engine()79   private Engine() { }
80 
81   // Class method.
82   // ------------------------------------------------------------------------
83 
84   /**
85    * Get the implementation for <i>algorithm</i> for service
86    * <i>service</i> from <i>provider</i>. The service is e.g.
87    * "Signature", and the algorithm "DSA".
88    *
89    * @param service   The service name.
90    * @param algorithm The name of the algorithm to get.
91    * @param provider  The provider to get the implementation from.
92    * @return The engine class for the specified algorithm; the object
93    *         returned is typically a subclass of the SPI class for that
94    *         service, but callers should check that this is so.
95    * @throws NoSuchAlgorithmException If the implementation cannot be
96    *         found or cannot be instantiated.
97    * @throws InvocationTargetException If the SPI class's constructor
98    *         throws an exception.
99    * @throws IllegalArgumentException If any of the three arguments are null.
100    */
getInstance(String service, String algorithm, Provider provider)101   public static Object getInstance(String service, String algorithm,
102                                    Provider provider)
103     throws InvocationTargetException, NoSuchAlgorithmException
104   {
105     return getInstance(service, algorithm, provider, NO_ARGS);
106   }
107 
108   /**
109    * Get the implementation for <i>algorithm</i> for service
110    * <i>service</i> from <i>provider</i>, passing <i>initArgs</i> to the
111    * SPI class's constructor (which cannot be null; pass a zero-length
112    * array if the SPI takes no arguments). The service is e.g.
113    * "Signature", and the algorithm "DSA".
114    *
115    * @param service   The service name.
116    * @param algorithm The name of the algorithm to get.
117    * @param provider  The provider to get the implementation from.
118    * @param initArgs  The arguments to pass to the SPI class's
119    *        constructor (cannot be null).
120    * @return The engine class for the specified algorithm; the object
121    *         returned is typically a subclass of the SPI class for that
122    *         service, but callers should check that this is so.
123    * @throws NoSuchAlgorithmException If the implementation cannot be
124    *         found or cannot be instantiated.
125    * @throws InvocationTargetException If the SPI class's constructor
126    *         throws an exception.
127    * @throws IllegalArgumentException If any of the four arguments are null.
128    */
getInstance(String service, String algorithm, Provider provider, Object[] initArgs)129   public static Object getInstance(String service, String algorithm,
130                                    Provider provider, Object[] initArgs)
131     throws InvocationTargetException, NoSuchAlgorithmException
132   {
133     if (service == null || algorithm == null
134         || provider == null || initArgs == null)
135       throw new IllegalArgumentException();
136 
137     // If there is no property "service.algorithm"
138     if (provider.getProperty(service + "." + algorithm) == null)
139       {
140         // Iterate through aliases, until we find the class name or resolve
141         // too many aliases.
142         String alias = null;
143         int count = 0;
144         while ((alias = provider.getProperty(
145                 ALG_ALIAS + service + "." + algorithm)) != null)
146           {
147             if (algorithm.equals(alias))  // Refers to itself!
148               break;
149             algorithm = alias;
150             if (count++ > MAX_ALIASES)
151               throw new NoSuchAlgorithmException("too many aliases");
152           }
153         if (provider.getProperty(service + "." + algorithm) == null)
154           throw new NoSuchAlgorithmException(algorithm);
155       }
156 
157     // Find and instantiate the implementation.
158     Class clazz = null;
159     ClassLoader loader = provider.getClass().getClassLoader();
160     Constructor constructor = null;
161     String error = algorithm;
162 
163     try
164       {
165         if (loader != null)
166           clazz = loader.loadClass(provider.getProperty(service+"."+algorithm));
167         else
168           clazz = Class.forName(provider.getProperty(service+"."+algorithm));
169         constructor = getCompatibleConstructor(clazz, initArgs);
170         return constructor.newInstance(initArgs);
171       }
172     catch (ClassNotFoundException cnfe)
173       {
174         error = "class not found: " + algorithm;
175       }
176     catch (IllegalAccessException iae)
177       {
178         error = "illegal access: " + iae.getMessage();
179       }
180     catch (InstantiationException ie)
181       {
182         error = "instantiation exception: " + ie.getMessage();
183       }
184     catch (ExceptionInInitializerError eiie)
185       {
186         error = "exception in initializer: " + eiie.getMessage();
187       }
188     catch (SecurityException se)
189       {
190         error = "security exception: " + se.getMessage();
191       }
192     catch (NoSuchMethodException nsme)
193       {
194         error = "no appropriate constructor found";
195       }
196 
197     throw new NoSuchAlgorithmException(error);
198   }
199 
200   // Own methods.
201   // ------------------------------------------------------------------------
202 
203   /**
204    * Find a constructor in the given class that can take the specified
205    * argument list, allowing any of which to be null.
206    *
207    * @param clazz    The class from which to get the constructor.
208    * @param initArgs The argument list to be passed to the constructor.
209    * @return The constructor.
210    * @throws NoSuchMethodException If no constructor of the given class
211    *         can take the specified argument array.
212    */
getCompatibleConstructor(Class clazz, Object[] initArgs)213   private static Constructor getCompatibleConstructor(Class clazz,
214                                                       Object[] initArgs)
215     throws NoSuchMethodException
216   {
217     Constructor[] c = clazz.getConstructors();
218     outer:for (int i = 0; i < c.length; i++)
219       {
220         Class[] argTypes = c[i].getParameterTypes();
221         if (argTypes.length != initArgs.length)
222           continue;
223         for (int j = 0; j < argTypes.length; j++)
224           {
225             if (initArgs[j] != null &&
226                 !argTypes[j].isAssignableFrom(initArgs[j].getClass()))
227               continue outer;
228           }
229         // If we reach this point, we know this constructor (c[i]) has
230         // the same number of parameters as the target parameter list,
231         // and all our parameters are either (1) null, or (2) assignable
232         // to the target parameter type.
233         return c[i];
234       }
235     throw new NoSuchMethodException();
236   }
237 }
238