|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | +package org.apache.tika.sax; |
| 18 | + |
| 19 | +import java.util.ArrayDeque; |
| 20 | +import java.util.Deque; |
| 21 | +import java.util.HashSet; |
| 22 | +import java.util.Set; |
| 23 | + |
| 24 | +import org.xml.sax.Attributes; |
| 25 | +import org.xml.sax.ContentHandler; |
| 26 | +import org.xml.sax.SAXException; |
| 27 | + |
| 28 | +/** |
| 29 | + * A SAX content handler decorator that enforces XHTML well-formedness on the |
| 30 | + * incoming event stream. Any parser that emits an event sequence that would |
| 31 | + * produce malformed XHTML triggers a {@link SAXException} synchronously — the |
| 32 | + * stack trace points at the parser code that made the offending call, instead |
| 33 | + * of surfacing later as a parse error on the serialized output. |
| 34 | + * <p> |
| 35 | + * Invariants enforced: |
| 36 | + * <ul> |
| 37 | + * <li>{@code startDocument} is called at most once.</li> |
| 38 | + * <li>No SAX events arrive after {@code endDocument}.</li> |
| 39 | + * <li>Every {@code endElement} matches the topmost open {@code startElement} |
| 40 | + * (no cross-nesting like {@code <a><b></a></b>}).</li> |
| 41 | + * <li>The element stack is empty when {@code endDocument} fires (no unclosed |
| 42 | + * elements left dangling by an exception path).</li> |
| 43 | + * <li>Within a single {@code startElement}, no two attributes share the same |
| 44 | + * (namespaceURI, localName) pair (the bug class that produces |
| 45 | + * {@code <div class="x" class="y">}).</li> |
| 46 | + * </ul> |
| 47 | + * Use as a decorator wrapping the real handler. It passes every event through |
| 48 | + * to the downstream handler after validation, so any normal text/XHTML capture |
| 49 | + * still works. |
| 50 | + */ |
| 51 | +public class StrictXHTMLValidator extends ContentHandlerDecorator { |
| 52 | + |
| 53 | + private final Deque<QName> openElements = new ArrayDeque<>(); |
| 54 | + private boolean documentStarted; |
| 55 | + private boolean documentEnded; |
| 56 | + |
| 57 | + public StrictXHTMLValidator(ContentHandler handler) { |
| 58 | + super(handler); |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public void startDocument() throws SAXException { |
| 63 | + if (documentStarted) { |
| 64 | + throw new SAXException("StrictXHTMLValidator: startDocument called twice"); |
| 65 | + } |
| 66 | + if (documentEnded) { |
| 67 | + throw new SAXException( |
| 68 | + "StrictXHTMLValidator: startDocument after endDocument"); |
| 69 | + } |
| 70 | + documentStarted = true; |
| 71 | + super.startDocument(); |
| 72 | + } |
| 73 | + |
| 74 | + @Override |
| 75 | + public void endDocument() throws SAXException { |
| 76 | + if (documentEnded) { |
| 77 | + throw new SAXException("StrictXHTMLValidator: endDocument called twice"); |
| 78 | + } |
| 79 | + if (!openElements.isEmpty()) { |
| 80 | + throw new SAXException( |
| 81 | + "StrictXHTMLValidator: endDocument with " + openElements.size() |
| 82 | + + " unclosed element(s); topmost was <" |
| 83 | + + openElements.peek().qOrLocal() + ">"); |
| 84 | + } |
| 85 | + documentEnded = true; |
| 86 | + super.endDocument(); |
| 87 | + } |
| 88 | + |
| 89 | + @Override |
| 90 | + public void startElement(String uri, String localName, String qName, Attributes attrs) |
| 91 | + throws SAXException { |
| 92 | + ensureNotEnded("startElement <" + display(qName, localName) + ">"); |
| 93 | + checkAttributesUnique(qName, localName, attrs); |
| 94 | + openElements.push(new QName(uri, localName, qName)); |
| 95 | + super.startElement(uri, localName, qName, attrs); |
| 96 | + } |
| 97 | + |
| 98 | + @Override |
| 99 | + public void endElement(String uri, String localName, String qName) throws SAXException { |
| 100 | + ensureNotEnded("endElement </" + display(qName, localName) + ">"); |
| 101 | + if (openElements.isEmpty()) { |
| 102 | + throw new SAXException( |
| 103 | + "StrictXHTMLValidator: endElement </" + display(qName, localName) |
| 104 | + + "> with no matching startElement"); |
| 105 | + } |
| 106 | + QName top = openElements.pop(); |
| 107 | + if (!top.matches(uri, localName, qName)) { |
| 108 | + throw new SAXException( |
| 109 | + "StrictXHTMLValidator: endElement </" + display(qName, localName) |
| 110 | + + "> does not match topmost open element <" |
| 111 | + + top.qOrLocal() + ">"); |
| 112 | + } |
| 113 | + super.endElement(uri, localName, qName); |
| 114 | + } |
| 115 | + |
| 116 | + @Override |
| 117 | + public void characters(char[] ch, int start, int length) throws SAXException { |
| 118 | + ensureNotEnded("characters"); |
| 119 | + super.characters(ch, start, length); |
| 120 | + } |
| 121 | + |
| 122 | + @Override |
| 123 | + public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { |
| 124 | + ensureNotEnded("ignorableWhitespace"); |
| 125 | + super.ignorableWhitespace(ch, start, length); |
| 126 | + } |
| 127 | + |
| 128 | + @Override |
| 129 | + public void processingInstruction(String target, String data) throws SAXException { |
| 130 | + ensureNotEnded("processingInstruction"); |
| 131 | + super.processingInstruction(target, data); |
| 132 | + } |
| 133 | + |
| 134 | + @Override |
| 135 | + public void startPrefixMapping(String prefix, String uri) throws SAXException { |
| 136 | + ensureNotEnded("startPrefixMapping"); |
| 137 | + super.startPrefixMapping(prefix, uri); |
| 138 | + } |
| 139 | + |
| 140 | + @Override |
| 141 | + public void endPrefixMapping(String prefix) throws SAXException { |
| 142 | + ensureNotEnded("endPrefixMapping"); |
| 143 | + super.endPrefixMapping(prefix); |
| 144 | + } |
| 145 | + |
| 146 | + @Override |
| 147 | + public void skippedEntity(String name) throws SAXException { |
| 148 | + ensureNotEnded("skippedEntity"); |
| 149 | + super.skippedEntity(name); |
| 150 | + } |
| 151 | + |
| 152 | + private void ensureNotEnded(String event) throws SAXException { |
| 153 | + if (documentEnded) { |
| 154 | + throw new SAXException( |
| 155 | + "StrictXHTMLValidator: " + event + " arrived after endDocument"); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + private void checkAttributesUnique(String elementQName, String elementLocalName, |
| 160 | + Attributes attrs) throws SAXException { |
| 161 | + int n = attrs.getLength(); |
| 162 | + if (n < 2) { |
| 163 | + return; |
| 164 | + } |
| 165 | + // (uri, localName) pairs must be unique per the XML namespaces spec. |
| 166 | + // We also check raw qnames because Tika's serializers emit by qname and |
| 167 | + // duplicate qnames produce malformed XHTML even when localnames differ. |
| 168 | + Set<String> seenUriLocal = new HashSet<>(n); |
| 169 | + Set<String> seenQNames = new HashSet<>(n); |
| 170 | + for (int i = 0; i < n; i++) { |
| 171 | + String uri = nullSafe(attrs.getURI(i)); |
| 172 | + String local = nullSafe(attrs.getLocalName(i)); |
| 173 | + String qn = nullSafe(attrs.getQName(i)); |
| 174 | + // U+0001 cannot appear in a valid XML uri/localName, so it joins the |
| 175 | + // two unambiguously without risk of a key collision. |
| 176 | + String key = uri + "\u0001" + local; |
| 177 | + if (!seenUriLocal.add(key)) { |
| 178 | + throw new SAXException( |
| 179 | + "StrictXHTMLValidator: duplicate attribute on <" |
| 180 | + + display(elementQName, elementLocalName) + ">: " |
| 181 | + + (uri.isEmpty() ? local : ("{" + uri + "}" + local))); |
| 182 | + } |
| 183 | + if (!qn.isEmpty() && !seenQNames.add(qn)) { |
| 184 | + throw new SAXException( |
| 185 | + "StrictXHTMLValidator: duplicate attribute qname on <" |
| 186 | + + display(elementQName, elementLocalName) + ">: " + qn); |
| 187 | + } |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + private static String nullSafe(String s) { |
| 192 | + return s == null ? "" : s; |
| 193 | + } |
| 194 | + |
| 195 | + private static String display(String qName, String localName) { |
| 196 | + if (qName != null && !qName.isEmpty()) { |
| 197 | + return qName; |
| 198 | + } |
| 199 | + return localName == null ? "" : localName; |
| 200 | + } |
| 201 | + |
| 202 | + private static final class QName { |
| 203 | + final String uri; |
| 204 | + final String localName; |
| 205 | + final String qName; |
| 206 | + |
| 207 | + QName(String uri, String localName, String qName) { |
| 208 | + this.uri = nullSafe(uri); |
| 209 | + this.localName = nullSafe(localName); |
| 210 | + this.qName = nullSafe(qName); |
| 211 | + } |
| 212 | + |
| 213 | + boolean matches(String u, String l, String q) { |
| 214 | + // SAX parsers can vary in which fields they populate. Accept a |
| 215 | + // match on either (uri, localName) or qName, whichever is present. |
| 216 | + String otherU = nullSafe(u); |
| 217 | + String otherL = nullSafe(l); |
| 218 | + String otherQ = nullSafe(q); |
| 219 | + boolean uriLocalMatch = uri.equals(otherU) && localName.equals(otherL) |
| 220 | + && !localName.isEmpty(); |
| 221 | + boolean qNameMatch = !qName.isEmpty() && qName.equals(otherQ); |
| 222 | + return uriLocalMatch || qNameMatch; |
| 223 | + } |
| 224 | + |
| 225 | + String qOrLocal() { |
| 226 | + return qName.isEmpty() ? localName : qName; |
| 227 | + } |
| 228 | + } |
| 229 | +} |
0 commit comments