1   ////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code for adherence to a set of rules.
3   // Copyright (C) 2001-2019 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.HashMap;
25  import java.util.Map;
26  
27  import javax.xml.parsers.ParserConfigurationException;
28  import javax.xml.parsers.SAXParserFactory;
29  
30  import org.xml.sax.InputSource;
31  import org.xml.sax.SAXException;
32  import org.xml.sax.SAXParseException;
33  import org.xml.sax.XMLReader;
34  import org.xml.sax.helpers.DefaultHandler;
35  
36  /**
37   * Contains the common implementation of a loader, for loading a configuration
38   * from an XML file.
39   * <p>
40   * The error handling policy can be described as being austere, dead set,
41   * disciplinary, dour, draconian, exacting, firm, forbidding, grim, hard, hard-
42   * boiled, harsh, harsh, in line, iron-fisted, no-nonsense, oppressive,
43   * persnickety, picky, prudish, punctilious, puritanical, rigid, rigorous,
44   * scrupulous, set, severe, square, stern, stickler, straight, strait-laced,
45   * stringent, stuffy, stuffy, tough, unpermissive, unsparing and uptight.
46   * </p>
47   *
48   * @noinspection ThisEscapedInObjectConstruction
49   */
50  public class XmlLoader
51      extends DefaultHandler {
52  
53      /** Maps public id to resolve to resource name for the DTD. */
54      private final Map<String, String> publicIdToResourceNameMap;
55      /** Parser to read XML files. **/
56      private final XMLReader parser;
57  
58      /**
59       * Creates a new instance.
60       * @param publicIdToResourceNameMap maps public IDs to DTD resource names
61       * @throws SAXException if an error occurs
62       * @throws ParserConfigurationException if an error occurs
63       */
64      protected XmlLoader(Map<String, String> publicIdToResourceNameMap)
65              throws SAXException, ParserConfigurationException {
66          this.publicIdToResourceNameMap = new HashMap<>(publicIdToResourceNameMap);
67          final SAXParserFactory factory = SAXParserFactory.newInstance();
68          LoadExternalDtdFeatureProvider.setFeaturesBySystemProperty(factory);
69          factory.setValidating(true);
70          parser = factory.newSAXParser().getXMLReader();
71          parser.setContentHandler(this);
72          parser.setEntityResolver(this);
73          parser.setErrorHandler(this);
74      }
75  
76      /**
77       * Parses the specified input source.
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              throws SAXException, IOException {
90          final InputSource inputSource;
91          if (publicIdToResourceNameMap.keySet().contains(publicId)) {
92              final String dtdResourceName =
93                      publicIdToResourceNameMap.get(publicId);
94              final ClassLoader loader =
95                  getClass().getClassLoader();
96              final InputStream dtdIs =
97                  loader.getResourceAsStream(dtdResourceName);
98  
99              inputSource = new InputSource(dtdIs);
100         }
101         else {
102             inputSource = super.resolveEntity(publicId, systemId);
103         }
104         return inputSource;
105     }
106 
107     @Override
108     public void error(SAXParseException exception) throws SAXException {
109         throw exception;
110     }
111 
112     /**
113      * Used for setting specific for secure java installations features to SAXParserFactory.
114      * Pulled out as a separate class in order to suppress Pitest mutations.
115      */
116     public static final class LoadExternalDtdFeatureProvider {
117 
118         /** System property name to enable external DTD load. */
119         public static final String ENABLE_EXTERNAL_DTD_LOAD = "checkstyle.enableExternalDtdLoad";
120 
121         /** Feature that enables loading external DTD when loading XML files. */
122         public static final String LOAD_EXTERNAL_DTD =
123                 "http://apache.org/xml/features/nonvalidating/load-external-dtd";
124         /** Feature that enables including external general entities in XML files. */
125         public static final String EXTERNAL_GENERAL_ENTITIES =
126                 "http://xml.org/sax/features/external-general-entities";
127 
128         /** Stop instances being created. **/
129         private LoadExternalDtdFeatureProvider() {
130         }
131 
132         /**
133          * Configures SAXParserFactory with features required
134          * to use external DTD file loading, this is not activated by default to no allow
135          * usage of schema files that checkstyle do not know
136          * it is even security problem to allow files from outside.
137          * @param factory factory to be configured with special features
138          * @throws SAXException if an error occurs
139          * @throws ParserConfigurationException if an error occurs
140          */
141         public static void setFeaturesBySystemProperty(SAXParserFactory factory)
142                 throws SAXException, ParserConfigurationException {
143 
144             final boolean enableExternalDtdLoad = Boolean.valueOf(
145                 System.getProperty(ENABLE_EXTERNAL_DTD_LOAD, "false"));
146 
147             factory.setFeature(LOAD_EXTERNAL_DTD, enableExternalDtdLoad);
148             factory.setFeature(EXTERNAL_GENERAL_ENTITIES, enableExternalDtdLoad);
149         }
150 
151     }
152 
153 }