001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 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.Map;
025
026import javax.xml.parsers.ParserConfigurationException;
027import javax.xml.parsers.SAXParserFactory;
028
029import org.xml.sax.InputSource;
030import org.xml.sax.SAXException;
031import org.xml.sax.SAXParseException;
032import org.xml.sax.XMLReader;
033import org.xml.sax.helpers.DefaultHandler;
034
035/**
036 * Contains the common implementation of a loader, for loading a configuration
037 * from an XML file.
038 *
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 * @noinspectionreason ThisEscapedInObjectConstruction - only reference is used and not
050 *      accessed until initialized
051 */
052public class XmlLoader
053    extends DefaultHandler {
054
055    /** Maps public id to resolve to resource name for the DTD. */
056    private final Map<String, String> publicIdToResourceNameMap;
057    /** Parser to read XML files. **/
058    private final XMLReader parser;
059
060    /**
061     * Creates a new instance.
062     *
063     * @param publicIdToResourceNameMap maps public IDs to DTD resource names
064     * @throws SAXException if an error occurs
065     * @throws ParserConfigurationException if an error occurs
066     */
067    protected XmlLoader(Map<String, String> publicIdToResourceNameMap)
068            throws SAXException, ParserConfigurationException {
069        this.publicIdToResourceNameMap = Map.copyOf(publicIdToResourceNameMap);
070        parser = createXmlReader(this);
071    }
072
073    /**
074     * Parses the specified input source.
075     *
076     * @param inputSource the input source to parse.
077     * @throws IOException if an error occurs
078     * @throws SAXException in an error occurs
079     */
080    public void parseInputSource(InputSource inputSource)
081            throws IOException, SAXException {
082        parser.parse(inputSource);
083    }
084
085    @Override
086    public InputSource resolveEntity(String publicId, String systemId) {
087        InputSource inputSource = null;
088        if (publicId != null) {
089            final String dtdResourceName = publicIdToResourceNameMap.get(publicId);
090
091            if (dtdResourceName != null) {
092                final ClassLoader loader = getClass().getClassLoader();
093                final InputStream dtdIs = loader.getResourceAsStream(dtdResourceName);
094                inputSource = new InputSource(dtdIs);
095            }
096        }
097        return inputSource;
098    }
099
100    @Override
101    public void error(SAXParseException exception) throws SAXException {
102        throw exception;
103    }
104
105    /**
106     * Helper method to create {@code XMLReader}.
107     *
108     * @param handler the content handler
109     * @return new XMLReader instance
110     * @throws ParserConfigurationException if a parser cannot be created
111     * @throws SAXException for SAX errors
112     */
113    private static XMLReader createXmlReader(DefaultHandler handler)
114            throws SAXException, ParserConfigurationException {
115        final SAXParserFactory factory = SAXParserFactory.newInstance();
116        LoadExternalDtdFeatureProvider.setFeaturesBySystemProperty(factory);
117        factory.setValidating(true);
118        final XMLReader xmlReader = factory.newSAXParser().getXMLReader();
119        xmlReader.setContentHandler(handler);
120        xmlReader.setEntityResolver(handler);
121        xmlReader.setErrorHandler(handler);
122        return xmlReader;
123    }
124
125    /**
126     * Used for setting specific for secure java installations features to SAXParserFactory.
127     * Pulled out as a separate class in order to suppress Pitest mutations.
128     */
129    public static final class LoadExternalDtdFeatureProvider {
130
131        /** System property name to enable external DTD load. */
132        public static final String ENABLE_EXTERNAL_DTD_LOAD = "checkstyle.enableExternalDtdLoad";
133
134        /** Feature that enables loading external DTD when loading XML files. */
135        public static final String LOAD_EXTERNAL_DTD =
136                "http://apache.org/xml/features/nonvalidating/load-external-dtd";
137        /** Feature that enables including external general entities in XML files. */
138        public static final String EXTERNAL_GENERAL_ENTITIES =
139                "http://xml.org/sax/features/external-general-entities";
140        /** Feature that enables including external parameter entities in XML files. */
141        public static final String EXTERNAL_PARAMETER_ENTITIES =
142                "http://xml.org/sax/features/external-parameter-entities";
143
144        /** Stop instances being created. **/
145        private LoadExternalDtdFeatureProvider() {
146        }
147
148        /**
149         * Configures SAXParserFactory with features required
150         * to use external DTD file loading, this is not activated by default to no allow
151         * usage of schema files that checkstyle do not know
152         * it is even security problem to allow files from outside.
153         *
154         * @param factory factory to be configured with special features
155         * @throws SAXException if an error occurs
156         * @throws ParserConfigurationException if an error occurs
157         */
158        public static void setFeaturesBySystemProperty(SAXParserFactory factory)
159                throws SAXException, ParserConfigurationException {
160
161            final boolean enableExternalDtdLoad = Boolean.parseBoolean(
162                System.getProperty(ENABLE_EXTERNAL_DTD_LOAD, "false"));
163
164            factory.setFeature(LOAD_EXTERNAL_DTD, enableExternalDtdLoad);
165            factory.setFeature(EXTERNAL_GENERAL_ENTITIES, enableExternalDtdLoad);
166            factory.setFeature(EXTERNAL_PARAMETER_ENTITIES, enableExternalDtdLoad);
167        }
168
169    }
170
171}