View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle;
21  
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.util.Map;
25  
26  import javax.xml.parsers.ParserConfigurationException;
27  import javax.xml.parsers.SAXParserFactory;
28  
29  import org.xml.sax.InputSource;
30  import org.xml.sax.SAXException;
31  import org.xml.sax.SAXParseException;
32  import org.xml.sax.XMLReader;
33  import org.xml.sax.helpers.DefaultHandler;
34  
35  import com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil;
36  
37  /**
38   * Contains the common implementation of a loader, for loading a configuration
39   * from an XML file.
40   * <p>
41   * The error handling policy can be described as being austere, dead set,
42   * disciplinary, dour, draconian, exacting, firm, forbidding, grim, hard, hard-
43   * boiled, harsh, harsh, in line, iron-fisted, no-nonsense, oppressive,
44   * persnickety, picky, prudish, punctilious, puritanical, rigid, rigorous,
45   * scrupulous, set, severe, square, stern, stickler, straight, strait-laced,
46   * stringent, stuffy, stuffy, tough, unpermissive, unsparing and uptight.
47   * </p>
48   *
49   * @noinspection ThisEscapedInObjectConstruction
50   * @noinspectionreason ThisEscapedInObjectConstruction - only reference is used and not
51   *      accessed until initialized
52   */
53  public class XmlLoader
54      extends DefaultHandler {
55  
56      /** Maps public id to resolve to resource name for the DTD. */
57      private final Map<String, String> publicIdToResourceNameMap;
58      /** Parser to read XML files. **/
59      private final XMLReader parser;
60  
61      /**
62       * Creates a new instance.
63       *
64       * @param publicIdToResourceNameMap maps public IDs to DTD resource names
65       * @throws SAXException if an error occurs
66       * @throws ParserConfigurationException if an error occurs
67       */
68      protected XmlLoader(Map<String, String> publicIdToResourceNameMap)
69              throws SAXException, ParserConfigurationException {
70          this.publicIdToResourceNameMap =
71                  UnmodifiableCollectionUtil.copyOfMap(publicIdToResourceNameMap);
72          parser = createXmlReader(this);
73      }
74  
75      /**
76       * Parses the specified input source.
77       *
78       * @param inputSource the input source to parse.
79       * @throws IOException if an error occurs
80       * @throws SAXException in an error occurs
81       */
82      public void parseInputSource(InputSource inputSource)
83              throws IOException, SAXException {
84          parser.parse(inputSource);
85      }
86  
87      @Override
88      public InputSource resolveEntity(String publicId, String systemId) {
89          InputSource inputSource = null;
90          if (publicId != null) {
91              final String dtdResourceName = publicIdToResourceNameMap.get(publicId);
92  
93              if (dtdResourceName != null) {
94                  final ClassLoader loader = getClass().getClassLoader();
95                  final InputStream dtdIs = loader.getResourceAsStream(dtdResourceName);
96                  inputSource = new InputSource(dtdIs);
97              }
98          }
99          return inputSource;
100     }
101 
102     @Override
103     public void error(SAXParseException exception) throws SAXException {
104         throw exception;
105     }
106 
107     /**
108      * Helper method to create {@code XMLReader}.
109      *
110      * @param handler the content handler
111      * @return new XMLReader instance
112      * @throws ParserConfigurationException if a parser cannot be created
113      * @throws SAXException for SAX errors
114      */
115     private static XMLReader createXmlReader(DefaultHandler handler)
116             throws SAXException, ParserConfigurationException {
117         final SAXParserFactory factory = SAXParserFactory.newInstance();
118         LoadExternalDtdFeatureProvider.setFeaturesBySystemProperty(factory);
119         factory.setValidating(true);
120         final XMLReader xmlReader = factory.newSAXParser().getXMLReader();
121         xmlReader.setContentHandler(handler);
122         xmlReader.setEntityResolver(handler);
123         xmlReader.setErrorHandler(handler);
124         return xmlReader;
125     }
126 
127     /**
128      * Used for setting specific for secure java installations features to SAXParserFactory.
129      * Pulled out as a separate class in order to suppress Pitest mutations.
130      */
131     public static final class LoadExternalDtdFeatureProvider {
132 
133         /** System property name to enable external DTD load. */
134         public static final String ENABLE_EXTERNAL_DTD_LOAD = "checkstyle.enableExternalDtdLoad";
135 
136         /** Feature that enables loading external DTD when loading XML files. */
137         public static final String LOAD_EXTERNAL_DTD =
138                 "http://apache.org/xml/features/nonvalidating/load-external-dtd";
139         /** Feature that enables including external general entities in XML files. */
140         public static final String EXTERNAL_GENERAL_ENTITIES =
141                 "http://xml.org/sax/features/external-general-entities";
142         /** Feature that enables including external parameter entities in XML files. */
143         public static final String EXTERNAL_PARAMETER_ENTITIES =
144                 "http://xml.org/sax/features/external-parameter-entities";
145 
146         /** Stop instances being created. **/
147         private LoadExternalDtdFeatureProvider() {
148         }
149 
150         /**
151          * Configures SAXParserFactory with features required
152          * to use external DTD file loading, this is not activated by default to no allow
153          * usage of schema files that checkstyle do not know
154          * it is even security problem to allow files from outside.
155          *
156          * @param factory factory to be configured with special features
157          * @throws SAXException if an error occurs
158          * @throws ParserConfigurationException if an error occurs
159          */
160         public static void setFeaturesBySystemProperty(SAXParserFactory factory)
161                 throws SAXException, ParserConfigurationException {
162 
163             final boolean enableExternalDtdLoad = Boolean.parseBoolean(
164                 System.getProperty(ENABLE_EXTERNAL_DTD_LOAD, "false"));
165 
166             factory.setFeature(LOAD_EXTERNAL_DTD, enableExternalDtdLoad);
167             factory.setFeature(EXTERNAL_GENERAL_ENTITIES, enableExternalDtdLoad);
168             factory.setFeature(EXTERNAL_PARAMETER_ENTITIES, enableExternalDtdLoad);
169         }
170 
171     }
172 
173 }