View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.html.parser.neko;
16  
17  import java.io.IOException;
18  import java.io.InputStream;
19  import java.io.StringReader;
20  import java.net.URL;
21  import java.nio.charset.Charset;
22  import java.util.ArrayList;
23  import java.util.List;
24  import java.util.Map;
25  import java.util.concurrent.ConcurrentHashMap;
26  
27  import org.htmlunit.ObjectInstantiationException;
28  import org.htmlunit.Page;
29  import org.htmlunit.SgmlPage;
30  import org.htmlunit.WebAssert;
31  import org.htmlunit.WebClient;
32  import org.htmlunit.WebResponse;
33  import org.htmlunit.cyberneko.HTMLScanner;
34  import org.htmlunit.cyberneko.HTMLTagBalancer;
35  import org.htmlunit.cyberneko.xerces.util.DefaultErrorHandler;
36  import org.htmlunit.cyberneko.xerces.xni.QName;
37  import org.htmlunit.cyberneko.xerces.xni.XNIException;
38  import org.htmlunit.cyberneko.xerces.xni.parser.XMLErrorHandler;
39  import org.htmlunit.cyberneko.xerces.xni.parser.XMLInputSource;
40  import org.htmlunit.cyberneko.xerces.xni.parser.XMLParseException;
41  import org.htmlunit.html.DefaultElementFactory;
42  import org.htmlunit.html.DomNode;
43  import org.htmlunit.html.ElementFactory;
44  import org.htmlunit.html.Html;
45  import org.htmlunit.html.HtmlPage;
46  import org.htmlunit.html.HtmlSvg;
47  import org.htmlunit.html.UnknownElementFactory;
48  import org.htmlunit.html.XHtmlPage;
49  import org.htmlunit.html.parser.HTMLParser;
50  import org.htmlunit.html.parser.HTMLParserListener;
51  import org.htmlunit.svg.SvgElementFactory;
52  import org.htmlunit.svg.SvgForeignObject;
53  import org.htmlunit.util.StringUtils;
54  import org.w3c.dom.Node;
55  import org.xml.sax.SAXException;
56  
57  /**
58   * <p>SAX parser implementation that uses the NekoHTML {@link org.htmlunit.cyberneko.HTMLConfiguration}
59   * to parse HTML into a HtmlUnit-specific DOM (HU-DOM) tree.</p>
60   *
61   * @author Christian Sell
62   * @author David K. Taylor
63   * @author Chris Erskine
64   * @author Ahmed Ashour
65   * @author Marc Guillemot
66   * @author Ethan Glasser-Camp
67   * @author Sudhan Moghe
68   * @author Ronald Brill
69   * @author Frank Danek
70   * @author Carsten Steul
71   */
72  public final class HtmlUnitNekoHtmlParser implements HTMLParser {
73  
74      /**
75       * The SVG factory.
76       */
77      public static final SvgElementFactory SVG_FACTORY = new SvgElementFactory();
78  
79      private static final Map<String, ElementFactory> ELEMENT_FACTORIES = new ConcurrentHashMap<>();
80  
81      static {
82          final DefaultElementFactory defaultElementFactory = new DefaultElementFactory();
83          for (final String tagName : DefaultElementFactory.SUPPORTED_TAGS_) {
84              ELEMENT_FACTORIES.put(tagName, defaultElementFactory);
85          }
86      }
87  
88      /**
89       * {@inheritDoc}
90       */
91      @Override
92      public void parseFragment(final WebClient webClient, final DomNode parent, final DomNode context,
93              final String source, final boolean createdByJavascript)
94          throws SAXException, IOException {
95          final Page page = parent.getPage();
96          if (!(page instanceof HtmlPage htmlPage)) {
97              return;
98          }
99          final URL url = htmlPage.getUrl();
100 
101         final HtmlUnitNekoDOMBuilder domBuilder =
102                 new HtmlUnitNekoDOMBuilder(this, webClient, parent, url, source, createdByJavascript);
103         domBuilder.setFeature("http://cyberneko.org/html/features/balance-tags/document-fragment", true);
104         // the content of an svg element (e.g. svg.innerHTML) is svg content
105         domBuilder.setInsideSvg(isSvgContext(context));
106 
107         final boolean xhtml = page instanceof XHtmlPage;
108         final boolean selfClosing = xhtml || webClient.getOptions().isHtmlFragmentSelfClosingTagsAllowed();
109         domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_TAGS, selfClosing);
110         domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_IFRAME, selfClosing);
111         domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_SCRIPT, xhtml);
112 
113         // build fragment context stack
114         DomNode node = context;
115         final List<QName> ancestors = new ArrayList<>();
116         while (node != null && node.getNodeType() != Node.DOCUMENT_NODE) {
117             ancestors.add(0, new QName(null, node.getNodeName(), null, null));
118             node = node.getParentNode();
119         }
120         if (ancestors.isEmpty() || !"html".equals(ancestors.get(0).getLocalpart())) {
121             ancestors.add(new QName(null, "html", null, null));
122             ancestors.add(new QName(null, "body", null, null));
123         }
124         else if (ancestors.size() == 1
125                 || (!"body".equals(ancestors.get(1).getLocalpart())
126                         && !"head".equals(ancestors.get(1).getLocalpart()))) {
127             ancestors.add(new QName(null, "body", null, null));
128         }
129 
130         domBuilder.setProperty(HTMLTagBalancer.FRAGMENT_CONTEXT_STACK, ancestors.toArray(new QName[0]));
131 
132         final XMLInputSource in = new XMLInputSource(null, url.toString(), null, new StringReader(source), null);
133 
134         htmlPage.registerParsingStart();
135         htmlPage.registerSnippetParsingStart();
136         try {
137             domBuilder.parse(in);
138         }
139         finally {
140             htmlPage.registerParsingEnd();
141             htmlPage.registerSnippetParsingEnd();
142         }
143     }
144 
145     /**
146      * {@inheritDoc}
147      */
148     @Override
149     public void parse(final WebClient webClient, final WebResponse webResponse, final HtmlPage page,
150             final boolean xhtml, final boolean createdByJavascript) throws IOException {
151         final URL url = webResponse.getWebRequest().getUrl();
152         final HtmlUnitNekoDOMBuilder domBuilder =
153                 new HtmlUnitNekoDOMBuilder(this, webClient, page, url, null, createdByJavascript);
154 
155         final Charset charset = webResponse.getContentCharset();
156         try {
157             if (!webResponse.wasContentCharsetTentative()) {
158                 // The charset is certain so ignore any others found in the document
159                 domBuilder.setFeature(HTMLScanner.IGNORE_SPECIFIED_CHARSET, true);
160             }
161 
162             // xml content is different
163             if (xhtml) {
164                 domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_TAGS, true);
165                 domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_IFRAME, true);
166                 domBuilder.setFeature(HTMLScanner.ALLOW_SELFCLOSING_SCRIPT, true);
167 
168                 domBuilder.setFeature(HTMLScanner.SCRIPT_STRIP_CDATA_DELIMS, true);
169                 domBuilder.setFeature(HTMLScanner.STYLE_STRIP_CDATA_DELIMS, true);
170                 domBuilder.setFeature(HTMLScanner.CDATA_SECTIONS, true);
171                 domBuilder.setFeature(HTMLScanner.CDATA_EARLY_CLOSING, false);
172             }
173 
174             final int bufferSize = webClient.getOptions().getNekoReaderBufferSize();
175             if (bufferSize > 0) {
176                 domBuilder.setProperty(HTMLScanner.READER_BUFFER_SIZE, bufferSize);
177             }
178         }
179         catch (final Exception e) {
180             throw new ObjectInstantiationException("Error setting HTML parser feature", e);
181         }
182 
183         try (InputStream content = webResponse.getContentAsStream()) {
184             final String encoding = charset.name();
185             final XMLInputSource in = new XMLInputSource(null, url.toString(), null, content, encoding);
186 
187             page.registerParsingStart();
188             try {
189                 domBuilder.parse(in);
190             }
191             catch (final XNIException e) {
192                 // extract enclosed exception
193                 final Throwable origin = extractNestedException(e);
194                 throw new RuntimeException("Failed parsing content from " + url, origin);
195             }
196         }
197         finally {
198             page.registerParsingEnd();
199         }
200     }
201 
202     /**
203      * Extract nested exception within an XNIException.
204      *
205      * @param e the original XNIException
206      * @return the cause exception
207      */
208     static Throwable extractNestedException(final Throwable e) {
209         Throwable originalException;
210         Throwable cause = e;
211         do {
212             originalException = cause;
213 
214             if (cause instanceof XNIException) {
215                 cause = cause.getCause();
216             }
217             else {
218                 cause = null;
219             }
220         }
221         while (cause != null);
222 
223         return originalException;
224     }
225 
226     /**
227      * {@inheritDoc}
228      */
229     @Override
230     public ElementFactory getSvgFactory() {
231         return SVG_FACTORY;
232     }
233 
234     /**
235      * {@inheritDoc}
236      */
237     @Override
238     public ElementFactory getFactory(final String tagName) {
239         final ElementFactory result = ELEMENT_FACTORIES.get(tagName);
240 
241         if (result != null) {
242             return result;
243         }
244         return UnknownElementFactory.INSTANCE;
245     }
246 
247     /**
248      * Checks if the content of the given context node is svg content; this is the case
249      * if the context is an svg element (or inside of one) but not inside of a foreignObject.
250      *
251      * @param context the context node of the fragment
252      * @return true if the content of the context is svg content
253      */
254     private static boolean isSvgContext(final DomNode context) {
255         DomNode node = context;
256         while (node != null) {
257             if (node instanceof SvgForeignObject) {
258                 return false;
259             }
260             if (node instanceof HtmlSvg) {
261                 return true;
262             }
263             node = node.getParentNode();
264         }
265         return false;
266     }
267 
268     /**
269      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
270      *
271      * Returns the pre-registered element factory corresponding to the specified tag, or an UnknownElementFactory.
272      * @param page the page
273      * @param namespaceURI the namespace URI
274      * @param qualifiedName the qualified name
275      * @param insideSvg is the node inside an SVG node or not
276      * @param svgSupport true if called from javascript createElementNS
277      * @return the pre-registered element factory corresponding to the specified tag, or an UnknownElementFactory
278      */
279     @Override
280     public ElementFactory getElementFactory(final SgmlPage page, final String namespaceURI,
281             final String qualifiedName, final boolean insideSvg, final boolean svgSupport) {
282         if (insideSvg) {
283             return SVG_FACTORY;
284         }
285 
286         if (namespaceURI == null || namespaceURI.isEmpty()
287             || Html.XHTML_NAMESPACE.equals(namespaceURI)
288             || Html.SVG_NAMESPACE.equals(namespaceURI)
289             || !qualifiedName.contains(":")) {
290 
291             String tagName = qualifiedName;
292             final int index = tagName.indexOf(':');
293             if (index == -1) {
294                 tagName = StringUtils.toRootLowerCase(tagName);
295             }
296             else {
297                 tagName = tagName.substring(index + 1);
298             }
299             final ElementFactory factory;
300             if (svgSupport && !"svg".equals(tagName) && Html.SVG_NAMESPACE.equals(namespaceURI)) {
301                 factory = SVG_FACTORY;
302             }
303             else {
304                 factory = ELEMENT_FACTORIES.get(tagName);
305             }
306 
307             if (factory != null) {
308                 return factory;
309             }
310         }
311         return UnknownElementFactory.INSTANCE;
312     }
313 }
314 
315 /**
316  * Utility to transmit parsing errors to a {@link HTMLParserListener}.
317  */
318 class HtmlUnitNekoHTMLErrorHandler implements XMLErrorHandler {
319     private final HTMLParserListener listener_;
320     private final URL url_;
321     private final String html_;
322 
323     HtmlUnitNekoHTMLErrorHandler(final HTMLParserListener listener, final URL url, final String htmlContent) {
324         WebAssert.notNull("listener", listener);
325         WebAssert.notNull("url", url);
326         listener_ = listener;
327         url_ = url;
328         html_ = htmlContent;
329     }
330 
331     /**
332      * {@inheritDoc}
333      * @see DefaultErrorHandler#error(String,String,XMLParseException)
334      */
335     @Override
336     public void error(final String domain, final String key,
337             final XMLParseException exception) throws XNIException {
338         listener_.error(exception.getMessage(),
339                 url_,
340                 html_,
341                 exception.getLineNumber(),
342                 exception.getColumnNumber(),
343                 key);
344     }
345 
346     /**
347      * {@inheritDoc}
348      * @see DefaultErrorHandler#warning(String,String,XMLParseException)
349      */
350     @Override
351     public void warning(final String domain, final String key,
352             final XMLParseException exception) throws XNIException {
353         listener_.warning(exception.getMessage(),
354                 url_,
355                 html_,
356                 exception.getLineNumber(),
357                 exception.getColumnNumber(),
358                 key);
359     }
360 
361     @Override
362     public void fatalError(final String domain, final String key,
363             final XMLParseException exception) throws XNIException {
364         listener_.error(exception.getMessage(),
365                 url_,
366                 html_,
367                 exception.getLineNumber(),
368                 exception.getColumnNumber(),
369                 key);
370     }
371 }