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 from an XML file.
037 *
038 * <p>
039 * The error handling policy can be described as being austere, dead set,
040 * disciplinary, dour, draconian, exacting, firm, forbidding, grim, hard, hard-
041 * boiled, harsh, harsh, in line, iron-fisted, no-nonsense, oppressive,
042 * persnickety, picky, prudish, punctilious, puritanical, rigid, rigorous,
043 * scrupulous, set, severe, square, stern, stickler, straight, strait-laced,
044 * stringent, stuffy, stuffy, tough, unpermissive, unsparing and uptight.
045 * </p>
046 *
047 * @noinspection ThisEscapedInObjectConstruction
048 * @noinspectionreason ThisEscapedInObjectConstruction - only reference is used and not
049 *      accessed until initialized
050 */
051public class XmlLoader 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 ParserConfigurationException if an error occurs
063     * @throws SAXException if an error occurs
064     */
065    protected XmlLoader(Map<String, String> publicIdToResourceNameMap)
066            throws SAXException, ParserConfigurationException {
067        this.publicIdToResourceNameMap = Map.copyOf(publicIdToResourceNameMap);
068        parser = createXmlReader(this);
069    }
070
071    /**
072     * Parses the specified input source.
073     *
074     * @param inputSource the input source to parse.
075     * @throws IOException if an error occurs
076     * @throws SAXException in an error occurs
077     */
078    public void parseInputSource(InputSource inputSource)
079            throws IOException, SAXException {
080        parser.parse(inputSource);
081    }
082
083    @Override
084    public InputSource resolveEntity(String publicId, String systemId) {
085        InputSource inputSource = null;
086        if (publicId != null) {
087            final String dtdResourceName = publicIdToResourceNameMap.get(publicId);
088
089            if (dtdResourceName != null) {
090                final ClassLoader loader = getClass().getClassLoader();
091                final InputStream dtdIs = loader.getResourceAsStream(dtdResourceName);
092                inputSource = new InputSource(dtdIs);
093            }
094        }
095        return inputSource;
096    }
097
098    @Override
099    public void error(SAXParseException exception) throws SAXException {
100        throw exception;
101    }
102
103    /**
104     * Helper method to create {@code XMLReader}.
105     *
106     * @param handler the content handler
107     * @return new XMLReader instance
108     * @throws ParserConfigurationException if a parser cannot be created
109     * @throws SAXException for SAX errors
110     */
111    private static XMLReader createXmlReader(DefaultHandler handler)
112            throws SAXException, ParserConfigurationException {
113        final SAXParserFactory factory = SAXParserFactory.newInstance();
114        LoadExternalDtdFeatureProvider.setFeaturesBySystemProperty(factory);
115        factory.setValidating(true);
116        final XMLReader xmlReader = factory.newSAXParser().getXMLReader();
117        xmlReader.setContentHandler(handler);
118        xmlReader.setEntityResolver(handler);
119        xmlReader.setErrorHandler(handler);
120        return xmlReader;
121    }
122
123    /**
124     * Used for setting specific for secure java installations features to SAXParserFactory.
125     * Pulled out as a separate class in order to suppress Pitest mutations.
126     */
127    public static final class LoadExternalDtdFeatureProvider {
128
129        /** System property name to enable external DTD load. */
130        public static final String ENABLE_EXTERNAL_DTD_LOAD = "checkstyle.enableExternalDtdLoad";
131
132        /** Feature that enables loading external DTD when loading XML files. */
133        public static final String LOAD_EXTERNAL_DTD =
134                "http://apache.org/xml/features/nonvalidating/load-external-dtd";
135        /** Feature that enables including external general entities in XML files. */
136        public static final String EXTERNAL_GENERAL_ENTITIES =
137                "http://xml.org/sax/features/external-general-entities";
138        /** Feature that enables including external parameter entities in XML files. */
139        public static final String EXTERNAL_PARAMETER_ENTITIES =
140                "http://xml.org/sax/features/external-parameter-entities";
141
142        /** Stop instances being created. */
143        private LoadExternalDtdFeatureProvider() {
144        }
145
146        /**
147         * Configures SAXParserFactory with features required
148         * to use external DTD file loading, this is not activated by default to no allow
149         * usage of schema files that checkstyle do not know
150         * it is even security problem to allow files from outside.
151         *
152         * @param factory factory to be configured with special features
153         * @throws ParserConfigurationException if an error occurs
154         * @throws SAXException if an error occurs
155         */
156        public static void setFeaturesBySystemProperty(SAXParserFactory factory)
157                throws SAXException, ParserConfigurationException {
158
159            final boolean enableExternalDtdLoad = Boolean.parseBoolean(
160                System.getProperty(ENABLE_EXTERNAL_DTD_LOAD, "false"));
161
162            factory.setFeature(LOAD_EXTERNAL_DTD, enableExternalDtdLoad);
163            factory.setFeature(EXTERNAL_GENERAL_ENTITIES, enableExternalDtdLoad);
164            factory.setFeature(EXTERNAL_PARAMETER_ENTITIES, enableExternalDtdLoad);
165        }
166
167    }
168
169}