1 /*
2  * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.
3  */
4 /*
5  * Licensed to the Apache Software Foundation (ASF) under one or more
6  * contributor license agreements.  See the NOTICE file distributed with
7  * this work for additional information regarding copyright ownership.
8  * The ASF licenses this file to You under the Apache License, Version 2.0
9  * (the "License"); you may not use this file except in compliance with
10  * the License.  You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  */
20 /*
21  * $Id: TemplatesImpl.java,v 1.8 2007/03/26 20:12:27 spericas Exp $
22  */
23 
24 package com.sun.org.apache.xalan.internal.xsltc.trax;
25 
26 import com.sun.org.apache.xalan.internal.XalanConstants;
27 import com.sun.org.apache.xalan.internal.utils.ObjectFactory;
28 import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
29 import com.sun.org.apache.xalan.internal.xsltc.DOM;
30 import com.sun.org.apache.xalan.internal.xsltc.Translet;
31 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
32 import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet;
33 import java.io.IOException;
34 import java.io.NotSerializableException;
35 import java.io.ObjectInputStream;
36 import java.io.ObjectOutputStream;
37 import java.io.ObjectStreamField;
38 import java.io.Serializable;
39 import java.security.AccessController;
40 import java.security.PrivilegedAction;
41 import java.util.HashMap;
42 import java.util.Map;
43 import java.util.Properties;
44 import javax.xml.XMLConstants;
45 import javax.xml.transform.Templates;
46 import javax.xml.transform.Transformer;
47 import javax.xml.transform.TransformerConfigurationException;
48 import javax.xml.transform.URIResolver;
49 
50 /**
51  * @author Morten Jorgensen
52  * @author G. Todd Millerj
53  * @author Jochen Cordes <Jochen.Cordes@t-online.de>
54  * @author Santiago Pericas-Geertsen
55  */
56 public final class TemplatesImpl implements Templates, Serializable {
57     static final long serialVersionUID = 673094361519270707L;
58     public final static String DESERIALIZE_TRANSLET = "jdk.xml.enableTemplatesImplDeserialization";
59 
60     /**
61      * Name of the superclass of all translets. This is needed to
62      * determine which, among all classes comprising a translet,
63      * is the main one.
64      */
65     private static String ABSTRACT_TRANSLET
66         = "com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet";
67 
68     /**
69      * Name of the main class or default name if unknown.
70      */
71     private String _name = null;
72 
73     /**
74      * Contains the actual class definition for the translet class and
75      * any auxiliary classes.
76      */
77     private byte[][] _bytecodes = null;
78 
79     /**
80      * Contains the translet class definition(s). These are created when
81      * this Templates is created or when it is read back from disk.
82      */
83     private Class[] _class = null;
84 
85     /**
86      * The index of the main translet class in the arrays _class[] and
87      * _bytecodes.
88      */
89     private int _transletIndex = -1;
90 
91     /**
92      * Contains the list of auxiliary class definitions.
93      */
94     private transient Map<String, Class<?>> _auxClasses = null;
95 
96     /**
97      * Output properties of this translet.
98      */
99     private Properties _outputProperties;
100 
101     /**
102      * Number of spaces to add for output indentation.
103      */
104     private int _indentNumber;
105 
106     /**
107      * This URIResolver is passed to all Transformers.
108      * Declaring it transient to fix bug 22438
109      */
110     private transient URIResolver _uriResolver = null;
111 
112     /**
113      * Cache the DTM for the stylesheet in a thread local variable,
114      * which is used by the document('') function.
115      * Use ThreadLocal because a DTM cannot be shared between
116      * multiple threads.
117      * Declaring it transient to fix bug 22438
118      */
119     private transient ThreadLocal _sdom = new ThreadLocal();
120 
121     /**
122      * A reference to the transformer factory that this templates
123      * object belongs to.
124      */
125     private transient TransformerFactoryImpl _tfactory = null;
126 
127     /**
128      * A flag to determine whether the system-default parser may be overridden
129      */
130     private transient boolean _overrideDefaultParser;
131 
132     /**
133      * protocols allowed for external references set by the stylesheet processing instruction, Import and Include element.
134      */
135     private transient String _accessExternalStylesheet = XalanConstants.EXTERNAL_ACCESS_DEFAULT;
136 
137     /**
138      * @serialField _name String The Name of the main class
139      * @serialField _bytecodes byte[][] Class definition
140      * @serialField _class Class[] The translet class definition(s).
141      * @serialField _transletIndex int The index of the main translet class
142      * @serialField _outputProperties Properties Output properties of this translet.
143      * @serialField _indentNumber int Number of spaces to add for output indentation.
144      */
145     private static final ObjectStreamField[] serialPersistentFields =
146         new ObjectStreamField[] {
147             new ObjectStreamField("_name", String.class),
148             new ObjectStreamField("_bytecodes", byte[][].class),
149             new ObjectStreamField("_class", Class[].class),
150             new ObjectStreamField("_transletIndex", int.class),
151             new ObjectStreamField("_outputProperties", Properties.class),
152             new ObjectStreamField("_indentNumber", int.class),
153         };
154 
155     static final class TransletClassLoader extends ClassLoader {
156         private final Map<String,Class> _loadedExternalExtensionFunctions;
157 
TransletClassLoader(ClassLoader parent)158          TransletClassLoader(ClassLoader parent) {
159              super(parent);
160             _loadedExternalExtensionFunctions = null;
161         }
162 
TransletClassLoader(ClassLoader parent,Map<String, Class> mapEF)163         TransletClassLoader(ClassLoader parent,Map<String, Class> mapEF) {
164             super(parent);
165             _loadedExternalExtensionFunctions = mapEF;
166         }
167 
loadClass(String name)168         public Class<?> loadClass(String name) throws ClassNotFoundException {
169             Class<?> ret = null;
170             // The _loadedExternalExtensionFunctions will be empty when the
171             // SecurityManager is not set and the FSP is turned off
172             if (_loadedExternalExtensionFunctions != null) {
173                 ret = _loadedExternalExtensionFunctions.get(name);
174             }
175             if (ret == null) {
176                 ret = super.loadClass(name);
177             }
178             return ret;
179          }
180 
181         /**
182          * Access to final protected superclass member from outer class.
183          */
defineClass(final byte[] b)184         Class defineClass(final byte[] b) {
185             return defineClass(null, b, 0, b.length);
186         }
187     }
188 
189 
190     /**
191      * Create an XSLTC template object from the bytecodes.
192      * The bytecodes for the translet and auxiliary classes, plus the name of
193      * the main translet class, must be supplied.
194      */
TemplatesImpl(byte[][] bytecodes, String transletName, Properties outputProperties, int indentNumber, TransformerFactoryImpl tfactory)195     protected TemplatesImpl(byte[][] bytecodes, String transletName,
196         Properties outputProperties, int indentNumber,
197         TransformerFactoryImpl tfactory)
198     {
199         _bytecodes = bytecodes;
200         init(transletName, outputProperties, indentNumber, tfactory);
201     }
202 
203     /**
204      * Create an XSLTC template object from the translet class definition(s).
205      */
TemplatesImpl(Class[] transletClasses, String transletName, Properties outputProperties, int indentNumber, TransformerFactoryImpl tfactory)206     protected TemplatesImpl(Class[] transletClasses, String transletName,
207         Properties outputProperties, int indentNumber,
208         TransformerFactoryImpl tfactory)
209     {
210         _class     = transletClasses;
211         _transletIndex = 0;
212         init(transletName, outputProperties, indentNumber, tfactory);
213     }
214 
init(String transletName, Properties outputProperties, int indentNumber, TransformerFactoryImpl tfactory)215     private void init(String transletName,
216         Properties outputProperties, int indentNumber,
217         TransformerFactoryImpl tfactory) {
218         _name      = transletName;
219         _outputProperties = outputProperties;
220         _indentNumber = indentNumber;
221         _tfactory = tfactory;
222         _overrideDefaultParser = tfactory.overrideDefaultParser();
223         _accessExternalStylesheet = (String) tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
224     }
225     /**
226      * Need for de-serialization, see readObject().
227      */
TemplatesImpl()228     public TemplatesImpl() { }
229 
230     /**
231      *  Overrides the default readObject implementation since we decided
232      *  it would be cleaner not to serialize the entire tranformer
233      *  factory.  [ ref bugzilla 12317 ]
234      *  We need to check if the user defined class for URIResolver also
235      *  implemented Serializable
236      *  if yes then we need to deserialize the URIResolver
237      *  Fix for bugzilla bug 22438
238      */
239     @SuppressWarnings("unchecked")
readObject(ObjectInputStream is)240     private void  readObject(ObjectInputStream is)
241       throws IOException, ClassNotFoundException
242     {
243         SecurityManager security = System.getSecurityManager();
244         if (security != null){
245             String temp = SecuritySupport.getSystemProperty(DESERIALIZE_TRANSLET);
246             if (temp == null || !(temp.length()==0 || temp.equalsIgnoreCase("true"))) {
247                 ErrorMsg err = new ErrorMsg(ErrorMsg.DESERIALIZE_TRANSLET_ERR);
248                 throw new UnsupportedOperationException(err.toString());
249             }
250         }
251 
252         // We have to read serialized fields first.
253         ObjectInputStream.GetField gf = is.readFields();
254         _name = (String)gf.get("_name", null);
255         _bytecodes = (byte[][])gf.get("_bytecodes", null);
256         _class = (Class[])gf.get("_class", null);
257         _transletIndex = gf.get("_transletIndex", -1);
258 
259         _outputProperties = (Properties)gf.get("_outputProperties", null);
260         _indentNumber = gf.get("_indentNumber", 0);
261 
262         if (is.readBoolean()) {
263             _uriResolver = (URIResolver) is.readObject();
264         }
265 
266         _tfactory = new TransformerFactoryImpl();
267     }
268 
269 
270     /**
271      *  This is to fix bugzilla bug 22438
272      *  If the user defined class implements URIResolver and Serializable
273      *  then we want it to get serialized
274      */
writeObject(ObjectOutputStream os)275     private void writeObject(ObjectOutputStream os)
276         throws IOException, ClassNotFoundException {
277         if (_auxClasses != null) {
278             //throw with the same message as when Hashtable was used for compatibility.
279             throw new NotSerializableException(
280                     "com.sun.org.apache.xalan.internal.xsltc.runtime.Hashtable");
281         }
282 
283         // Write serialized fields
284         ObjectOutputStream.PutField pf = os.putFields();
285         pf.put("_name", _name);
286         pf.put("_bytecodes", _bytecodes);
287         pf.put("_class", _class);
288         pf.put("_transletIndex", _transletIndex);
289         pf.put("_outputProperties", _outputProperties);
290         pf.put("_indentNumber", _indentNumber);
291         os.writeFields();
292 
293         if (_uriResolver instanceof Serializable) {
294             os.writeBoolean(true);
295             os.writeObject((Serializable) _uriResolver);
296         }
297         else {
298             os.writeBoolean(false);
299         }
300     }
301 
302     /**
303      * Return the state of the services mechanism feature.
304      */
overrideDefaultParser()305     public boolean overrideDefaultParser() {
306         return _overrideDefaultParser;
307     }
308 
309      /**
310      * Store URIResolver needed for Transformers.
311      */
setURIResolver(URIResolver resolver)312     public synchronized void setURIResolver(URIResolver resolver) {
313         _uriResolver = resolver;
314     }
315 
316     /**
317      * The TransformerFactory must pass us the translet bytecodes using this
318      * method before we can create any translet instances
319      *
320      * Note: This method is private for security reasons. See
321      * CR 6537898. When merging with Apache, we must ensure
322      * that the privateness of this method is maintained (that
323      * is why it wasn't removed).
324      */
setTransletBytecodes(byte[][] bytecodes)325     private synchronized void setTransletBytecodes(byte[][] bytecodes) {
326         _bytecodes = bytecodes;
327     }
328 
329     /**
330      * Returns the translet bytecodes stored in this template
331      *
332      * Note: This method is private for security reasons. See
333      * CR 6537898. When merging with Apache, we must ensure
334      * that the privateness of this method is maintained (that
335      * is why it wasn't removed).
336      */
getTransletBytecodes()337     private synchronized byte[][] getTransletBytecodes() {
338         return _bytecodes;
339     }
340 
341     /**
342      * Returns the translet bytecodes stored in this template
343      *
344      * Note: This method is private for security reasons. See
345      * CR 6537898. When merging with Apache, we must ensure
346      * that the privateness of this method is maintained (that
347      * is why it wasn't removed).
348      */
getTransletClasses()349     private synchronized Class[] getTransletClasses() {
350         try {
351             if (_class == null) defineTransletClasses();
352         }
353         catch (TransformerConfigurationException e) {
354             // Falls through
355         }
356         return _class;
357     }
358 
359     /**
360      * Returns the index of the main class in array of bytecodes
361      */
getTransletIndex()362     public synchronized int getTransletIndex() {
363         try {
364             if (_class == null) defineTransletClasses();
365         }
366         catch (TransformerConfigurationException e) {
367             // Falls through
368         }
369         return _transletIndex;
370     }
371 
372     /**
373      * The TransformerFactory should call this method to set the translet name
374      */
setTransletName(String name)375     protected synchronized void setTransletName(String name) {
376         _name = name;
377     }
378 
379     /**
380      * Returns the name of the main translet class stored in this template
381      */
getTransletName()382     protected synchronized String getTransletName() {
383         return _name;
384     }
385 
386     /**
387      * Defines the translet class and auxiliary classes.
388      * Returns a reference to the Class object that defines the main class
389      */
defineTransletClasses()390     private void defineTransletClasses()
391         throws TransformerConfigurationException {
392 
393         if (_bytecodes == null) {
394             ErrorMsg err = new ErrorMsg(ErrorMsg.NO_TRANSLET_CLASS_ERR);
395             throw new TransformerConfigurationException(err.toString());
396         }
397 
398         TransletClassLoader loader = (TransletClassLoader)
399             AccessController.doPrivileged(new PrivilegedAction() {
400                 public Object run() {
401                     return new TransletClassLoader(ObjectFactory.findClassLoader(),_tfactory.getExternalExtensionsMap());
402                 }
403             });
404 
405         try {
406             final int classCount = _bytecodes.length;
407             _class = new Class[classCount];
408 
409             if (classCount > 1) {
410                 _auxClasses = new HashMap<>();
411             }
412 
413             for (int i = 0; i < classCount; i++) {
414                 _class[i] = loader.defineClass(_bytecodes[i]);
415                 final Class superClass = _class[i].getSuperclass();
416 
417                 // Check if this is the main class
418                 if (superClass.getName().equals(ABSTRACT_TRANSLET)) {
419                     _transletIndex = i;
420                 }
421                 else {
422                     _auxClasses.put(_class[i].getName(), _class[i]);
423                 }
424             }
425 
426             if (_transletIndex < 0) {
427                 ErrorMsg err= new ErrorMsg(ErrorMsg.NO_MAIN_TRANSLET_ERR, _name);
428                 throw new TransformerConfigurationException(err.toString());
429             }
430         }
431         catch (ClassFormatError e) {
432             ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_CLASS_ERR, _name);
433             throw new TransformerConfigurationException(err.toString());
434         }
435         catch (LinkageError e) {
436             ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_OBJECT_ERR, _name);
437             throw new TransformerConfigurationException(err.toString());
438         }
439     }
440 
441     /**
442      * This method generates an instance of the translet class that is
443      * wrapped inside this Template. The translet instance will later
444      * be wrapped inside a Transformer object.
445      */
getTransletInstance()446     private Translet getTransletInstance()
447         throws TransformerConfigurationException {
448         try {
449             if (_name == null) return null;
450 
451             if (_class == null) defineTransletClasses();
452 
453             // The translet needs to keep a reference to all its auxiliary
454             // class to prevent the GC from collecting them
455             AbstractTranslet translet = (AbstractTranslet) _class[_transletIndex].newInstance();
456             translet.postInitialization();
457             translet.setTemplates(this);
458             translet.setOverrideDefaultParser(_overrideDefaultParser);
459             translet.setAllowedProtocols(_accessExternalStylesheet);
460             if (_auxClasses != null) {
461                 translet.setAuxiliaryClasses(_auxClasses);
462             }
463 
464             return translet;
465         }
466         catch (InstantiationException e) {
467             ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_OBJECT_ERR, _name);
468             throw new TransformerConfigurationException(err.toString());
469         }
470         catch (IllegalAccessException e) {
471             ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_OBJECT_ERR, _name);
472             throw new TransformerConfigurationException(err.toString());
473         }
474     }
475 
476     /**
477      * Implements JAXP's Templates.newTransformer()
478      *
479      * @throws TransformerConfigurationException
480      */
newTransformer()481     public synchronized Transformer newTransformer()
482         throws TransformerConfigurationException
483     {
484         TransformerImpl transformer;
485 
486         transformer = new TransformerImpl(getTransletInstance(), _outputProperties,
487             _indentNumber, _tfactory);
488 
489         if (_uriResolver != null) {
490             transformer.setURIResolver(_uriResolver);
491         }
492 
493         if (_tfactory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)) {
494             transformer.setSecureProcessing(true);
495         }
496         return transformer;
497     }
498 
499     /**
500      * Implements JAXP's Templates.getOutputProperties(). We need to
501      * instanciate a translet to get the output settings, so
502      * we might as well just instanciate a Transformer and use its
503      * implementation of this method.
504      */
getOutputProperties()505     public synchronized Properties getOutputProperties() {
506         try {
507             return newTransformer().getOutputProperties();
508         }
509         catch (TransformerConfigurationException e) {
510             return null;
511         }
512     }
513 
514     /**
515      * Return the thread local copy of the stylesheet DOM.
516      */
getStylesheetDOM()517     public DOM getStylesheetDOM() {
518         return (DOM)_sdom.get();
519     }
520 
521     /**
522      * Set the thread local copy of the stylesheet DOM.
523      */
setStylesheetDOM(DOM sdom)524     public void setStylesheetDOM(DOM sdom) {
525         _sdom.set(sdom);
526     }
527 }
528