001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2020 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle;
021
022import java.io.IOException;
023import java.io.InputStream;
024import java.util.HashMap;
025import java.util.Map;
026
027import javax.xml.parsers.ParserConfigurationException;
028import javax.xml.parsers.SAXParserFactory;
029
030import org.xml.sax.InputSource;
031import org.xml.sax.SAXException;
032import org.xml.sax.SAXParseException;
033import org.xml.sax.XMLReader;
034import org.xml.sax.helpers.DefaultHandler;
035
036/**
037 * Contains the common implementation of a loader, for loading a configuration
038 * from an XML file.
039 * <p>
040 * The error handling policy can be described as being austere, dead set,
041 * disciplinary, dour, draconian, exacting, firm, forbidding, grim, hard, hard-
042 * boiled, harsh, harsh, in line, iron-fisted, no-nonsense, oppressive,
043 * persnickety, picky, prudish, punctilious, puritanical, rigid, rigorous,
044 * scrupulous, set, severe, square, stern, stickler, straight, strait-laced,
045 * stringent, stuffy, stuffy, tough, unpermissive, unsparing and uptight.
046 * </p>
047 *
048 * @noinspection ThisEscapedInObjectConstruction
049 */
050public class XmlLoader
051    extends DefaultHandler {
052
053    /** Maps public id to resolve to resource name for the DTD. */
054    private final Map<String, String> publicIdToResourceNameMap;
055    /** Parser to read XML files. **/
056    private final XMLReader parser;
057
058    /**
059     * Creates a new instance.
060     *
061     * @param publicIdToResourceNameMap maps public IDs to DTD resource names
062     * @throws SAXException if an error occurs
063     * @throws ParserConfigurationException if an error occurs
064     */
065    protected XmlLoader(Map<String, String> publicIdToResourceNameMap)
066            throws SAXException, ParserConfigurationException {
067        this.publicIdToResourceNameMap = new HashMap<>(publicIdToResourceNameMap);
068        final SAXParserFactory factory = SAXParserFactory.newInstance();
069        LoadExternalDtdFeatureProvider.setFeaturesBySystemProperty(factory);
070        factory.setValidating(true);
071        parser = factory.newSAXParser().getXMLReader();
072        parser.setContentHandler(this);
073        parser.setEntityResolver(this);
074        parser.setErrorHandler(this);
075    }
076
077    /**
078     * Parses the specified input source.
079     *
080     * @param inputSource the input source to parse.
081     * @throws IOException if an error occurs
082     * @throws SAXException in an error occurs
083     */
084    public void parseInputSource(InputSource inputSource)
085            throws IOException, SAXException {
086        parser.parse(inputSource);
087    }
088
089    @Override
090    public InputSource resolveEntity(String publicId, String systemId)
091            throws SAXException, IOException {
092        final InputSource inputSource;
093        if (publicIdToResourceNameMap.containsKey(publicId)) {
094            final String dtdResourceName =
095                    publicIdToResourceNameMap.get(publicId);
096            final ClassLoader loader =
097                getClass().getClassLoader();
098            final InputStream dtdIs =
099                loader.getResourceAsStream(dtdResourceName);
100
101            inputSource = new InputSource(dtdIs);
102        }
103        else {
104            inputSource = super.resolveEntity(publicId, systemId);
105        }
106        return inputSource;
107    }
108
109    @Override
110    public void error(SAXParseException exception) throws SAXException {
111        throw exception;
112    }
113
114    /**
115     * Used for setting specific for secure java installations features to SAXParserFactory.
116     * Pulled out as a separate class in order to suppress Pitest mutations.
117     */
118    public static final class LoadExternalDtdFeatureProvider {
119
120        /** System property name to enable external DTD load. */
121        public static final String ENABLE_EXTERNAL_DTD_LOAD = "checkstyle.enableExternalDtdLoad";
122
123        /** Feature that enables loading external DTD when loading XML files. */
124        public static final String LOAD_EXTERNAL_DTD =
125                "http://apache.org/xml/features/nonvalidating/load-external-dtd";
126        /** Feature that enables including external general entities in XML files. */
127        public static final String EXTERNAL_GENERAL_ENTITIES =
128                "http://xml.org/sax/features/external-general-entities";
129        /** Feature that enables including external parameter entities in XML files. */
130        public static final String EXTERNAL_PARAMETER_ENTITIES =
131                "http://xml.org/sax/features/external-parameter-entities";
132
133        /** Stop instances being created. **/
134        private LoadExternalDtdFeatureProvider() {
135        }
136
137        /**
138         * Configures SAXParserFactory with features required
139         * to use external DTD file loading, this is not activated by default to no allow
140         * usage of schema files that checkstyle do not know
141         * it is even security problem to allow files from outside.
142         *
143         * @param factory factory to be configured with special features
144         * @throws SAXException if an error occurs
145         * @throws ParserConfigurationException if an error occurs
146         */
147        public static void setFeaturesBySystemProperty(SAXParserFactory factory)
148                throws SAXException, ParserConfigurationException {
149
150            final boolean enableExternalDtdLoad = Boolean.parseBoolean(
151                System.getProperty(ENABLE_EXTERNAL_DTD_LOAD, "false"));
152
153            factory.setFeature(LOAD_EXTERNAL_DTD, enableExternalDtdLoad);
154            factory.setFeature(EXTERNAL_GENERAL_ENTITIES, enableExternalDtdLoad);
155            factory.setFeature(EXTERNAL_PARAMETER_ENTITIES, enableExternalDtdLoad);
156        }
157
158    }
159
160}