1 /*
   2  * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javax.xml.transform;
  27 
  28 import java.io.File;
  29 import java.lang.reflect.Method;
  30 import java.lang.reflect.Modifier;
  31 import java.security.AccessController;
  32 import java.security.PrivilegedAction;
  33 import java.util.Iterator;
  34 import java.util.Properties;
  35 import java.util.ServiceConfigurationError;
  36 import java.util.ServiceLoader;
  37 import java.util.function.Supplier;
  38 import jdk.xml.internal.SecuritySupport;
  39 
  40 /**
  41  * <p>Implements pluggable Datatypes.</p>
  42  *
  43  * <p>This class is duplicated for each JAXP subpackage so keep it in
  44  * sync.  It is package private for secure class loading.</p>
  45  *
  46  * @author Santiago.PericasGeertsen@sun.com
  47  * @author Huizhe.Wang@oracle.com
  48  */
  49 class FactoryFinder {
  50     private static final String DEFAULT_PACKAGE = "com.sun.org.apache.xalan.internal.";
  51 
  52     /**
  53      * Internal debug flag.
  54      */
  55     private static boolean debug = false;
  56 
  57     /**
  58      * Cache for properties in java.home/conf/jaxp.properties
  59      */
  60     private final static Properties cacheProps = new Properties();
  61 
  62     /**
  63      * Flag indicating if properties from java.home/conf/jaxp.properties
  64      * have been cached.
  65      */
  66     static volatile boolean firstTime = true;
  67 
  68     // Define system property "jaxp.debug" to get output
  69     static {
  70         // Use try/catch block to support applets, which throws
  71         // SecurityException out of this code.
  72         try {
  73             String val = SecuritySupport.getSystemProperty("jaxp.debug");
  74             // Allow simply setting the prop to turn on debug
  75             debug = val != null && !"false".equals(val);
  76         }
  77         catch (SecurityException se) {
  78             debug = false;
  79         }
  80     }
  81 
  82     private static void dPrint(Supplier<String> msgGen) {
  83         if (debug) {
  84             System.err.println("JAXP: " + msgGen.get());
  85         }
  86     }
  87 
  88     /**
  89      * Attempt to load a class using the class loader supplied. If that fails
  90      * and fall back is enabled, the current (i.e. bootstrap) class loader is
  91      * tried.
  92      *
  93      * If the class loader supplied is <code>null</code>, first try using the
  94      * context class loader followed by the current (i.e. bootstrap) class
  95      * loader.
  96      *
  97      * Use bootstrap classLoader if cl = null and useBSClsLoader is true
  98      */
  99     static private Class<?> getProviderClass(String className, ClassLoader cl,
 100             boolean doFallback, boolean useBSClsLoader) throws ClassNotFoundException
 101     {
 102         try {
 103             if (cl == null) {
 104                 if (useBSClsLoader) {
 105                     return Class.forName(className, false, FactoryFinder.class.getClassLoader());
 106                 } else {
 107                     cl = SecuritySupport.getContextClassLoader();
 108                     if (cl == null) {
 109                         throw new ClassNotFoundException();
 110                     }
 111                     else {
 112                         return Class.forName(className, false, cl);
 113                     }
 114                 }
 115             }
 116             else {
 117                 return Class.forName(className, false, cl);
 118             }
 119         }
 120         catch (ClassNotFoundException e1) {
 121             if (doFallback) {
 122                 // Use current class loader - should always be bootstrap CL
 123                 return Class.forName(className, false, FactoryFinder.class.getClassLoader());
 124             }
 125             else {
 126                 throw e1;
 127             }
 128         }
 129     }
 130 
 131     /**
 132      * Create an instance of a class. Delegates to method
 133      * <code>getProviderClass()</code> in order to load the class.
 134      *
 135      * @param type Base class / Service interface  of the factory to
 136      *             instantiate.
 137      *
 138      * @param className Name of the concrete class corresponding to the
 139      * service provider
 140      *
 141      * @param cl <code>ClassLoader</code> used to load the factory class. If <code>null</code>
 142      * current <code>Thread</code>'s context classLoader is used to load the factory class.
 143      *
 144      * @param doFallback True if the current ClassLoader should be tried as
 145      * a fallback if the class is not found using cl
 146      *
 147      * @param useServicesMechanism True use services mechanism
 148      */
 149     static <T> T newInstance(Class<T> type, String className, ClassLoader cl,
 150                              boolean doFallback, boolean useServicesMechanism)
 151         throws TransformerFactoryConfigurationError
 152     {
 153         assert type != null;
 154 
 155         boolean useBSClsLoader = false;
 156         // make sure we have access to restricted packages
 157         if (System.getSecurityManager() != null) {
 158             if (className != null && className.startsWith(DEFAULT_PACKAGE)) {
 159                 cl = null;
 160                 useBSClsLoader = true;
 161             }
 162         }
 163 
 164         try {
 165             Class<?> providerClass = getProviderClass(className, cl, doFallback, useBSClsLoader);
 166             if (!type.isAssignableFrom(providerClass)) {
 167                 throw new ClassCastException(className + " cannot be cast to " + type.getName());
 168             }
 169             Object instance = null;
 170             if (!useServicesMechanism) {
 171                 instance = newInstanceNoServiceLoader(type, providerClass);
 172             }
 173             if (instance == null) {
 174                 instance = providerClass.getConstructor().newInstance();
 175             }
 176             final ClassLoader clD = cl;
 177             dPrint(()->"created new instance of " + providerClass +
 178                        " using ClassLoader: " + clD);
 179             return type.cast(instance);
 180         }
 181         catch (ClassNotFoundException x) {
 182             throw new TransformerFactoryConfigurationError(x,
 183                 "Provider " + className + " not found");
 184         }
 185         catch (Exception x) {
 186             throw new TransformerFactoryConfigurationError(x,
 187                 "Provider " + className + " could not be instantiated: " + x);
 188         }
 189     }
 190 
 191     /**
 192      * Try to construct using newTransformerFactoryNoServiceLoader
 193      *   method if available.
 194      */
 195     private static <T> T newInstanceNoServiceLoader(Class<T> type, Class<?> providerClass) {
 196         // Retain maximum compatibility if no security manager.
 197         if (System.getSecurityManager() == null) {
 198             return null;
 199         }
 200         try {
 201             final Method creationMethod =
 202                     providerClass.getDeclaredMethod(
 203                         "newTransformerFactoryNoServiceLoader"
 204                     );
 205             final int modifiers = creationMethod.getModifiers();
 206 
 207             // Do not call the method if it's not public static.
 208             if (!Modifier.isPublic(modifiers) || !Modifier.isStatic(modifiers)) {
 209                 return null;
 210             }
 211 
 212             // Only call the method if it's declared to return an instance of
 213             // TransformerFactory
 214             final Class<?> returnType = creationMethod.getReturnType();
 215             if (type.isAssignableFrom(returnType)) {
 216                 final Object result = creationMethod.invoke(null, (Object[])null);
 217                 return type.cast(result);
 218             } else {
 219                 // This should not happen, as
 220                 // TransformerFactoryImpl.newTransformerFactoryNoServiceLoader is
 221                 // declared to return TransformerFactory.
 222                 throw new ClassCastException(returnType + " cannot be cast to " + type);
 223             }
 224         } catch (ClassCastException e) {
 225             throw new TransformerFactoryConfigurationError(e, e.getMessage());
 226         } catch (NoSuchMethodException exc) {
 227             return null;
 228         } catch (Exception exc) {
 229             return null;
 230         }
 231     }
 232 
 233     /**
 234      * Finds the implementation Class object in the specified order.  Main
 235      * entry point.
 236      * @return Class object of factory, never null
 237      *
 238      * @param type                  Base class / Service interface  of the
 239      *                              factory to find.
 240      *
 241      * @param fallbackClassName     Implementation class name, if nothing else
 242      *                              is found.  Use null to mean no fallback.
 243      *
 244      * Package private so this code can be shared.
 245      */
 246     static <T> T find(Class<T> type, String fallbackClassName)
 247         throws TransformerFactoryConfigurationError
 248     {
 249         assert type != null;
 250 
 251         final String factoryId = type.getName();
 252 
 253         dPrint(()->"find factoryId =" + factoryId);
 254         // Use the system property first
 255         try {
 256             String systemProp = SecuritySupport.getSystemProperty(factoryId);
 257             if (systemProp != null) {
 258                 dPrint(()->"found system property, value=" + systemProp);
 259                 return newInstance(type, systemProp, null, true, true);
 260             }
 261         }
 262         catch (SecurityException se) {
 263             if (debug) se.printStackTrace();
 264         }
 265 
 266         // try to read from $java.home/conf/jaxp.properties
 267         try {
 268             if (firstTime) {
 269                 synchronized (cacheProps) {
 270                     if (firstTime) {
 271                         String configFile = SecuritySupport.getSystemProperty("java.home") + File.separator +
 272                             "conf" + File.separator + "jaxp.properties";
 273                         File f = new File(configFile);
 274                         firstTime = false;
 275                         if (SecuritySupport.doesFileExist(f)) {
 276                             dPrint(()->"Read properties file "+f);
 277                             cacheProps.load(SecuritySupport.getFileInputStream(f));
 278                         }
 279                     }
 280                 }
 281             }
 282             final String factoryClassName = cacheProps.getProperty(factoryId);
 283 
 284             if (factoryClassName != null) {
 285                 dPrint(()->"found in ${java.home}/conf/jaxp.properties, value=" + factoryClassName);
 286                 return newInstance(type, factoryClassName, null, true, true);
 287             }
 288         }
 289         catch (Exception ex) {
 290             if (debug) ex.printStackTrace();
 291         }
 292 
 293         // Try Jar Service Provider Mechanism
 294         T provider = findServiceProvider(type);
 295         if (provider != null) {
 296             return provider;
 297         }
 298         if (fallbackClassName == null) {
 299             throw new TransformerFactoryConfigurationError(null,
 300                 "Provider for " + factoryId + " cannot be found");
 301         }
 302 
 303         dPrint(()->"loaded from fallback value: " + fallbackClassName);
 304         return newInstance(type, fallbackClassName, null, true, true);
 305     }
 306 
 307     /*
 308      * Try to find provider using the ServiceLoader.
 309      *
 310      * @param type Base class / Service interface  of the factory to find.
 311      *
 312      * @return instance of provider class if found or null
 313      */
 314     private static <T> T findServiceProvider(final Class<T> type)
 315         throws TransformerFactoryConfigurationError
 316     {
 317       try {
 318             return AccessController.doPrivileged(new PrivilegedAction<T>() {
 319                 public T run() {
 320                     final ServiceLoader<T> serviceLoader = ServiceLoader.load(type);
 321                     final Iterator<T> iterator = serviceLoader.iterator();
 322                     if (iterator.hasNext()) {
 323                         return iterator.next();
 324                     } else {
 325                         return null;
 326                     }
 327                  }
 328             });
 329         } catch(ServiceConfigurationError e) {
 330             // It is not possible to wrap an error directly in
 331             // FactoryConfigurationError - so we need to wrap the
 332             // ServiceConfigurationError in a RuntimeException.
 333             // The alternative would be to modify the logic in
 334             // FactoryConfigurationError to allow setting a
 335             // Throwable as the cause, but that could cause
 336             // compatibility issues down the road.
 337             final RuntimeException x = new RuntimeException(
 338                     "Provider for " + type + " cannot be created", e);
 339             final TransformerFactoryConfigurationError error =
 340                     new TransformerFactoryConfigurationError(x, x.getMessage());
 341             throw error;
 342         }
 343     }
 344 }