HtmlCleaner 2.29 throws a StackOverflowError when SimpleHtmlSerializer processes deeply nested HTML.
I reproduced this with 9,999 nested <div> elements. HtmlCleaner.clean() completes successfully with the default maxDepth setting of 1000, but the returned TagNode tree has a maximum depth of 10,001.
The error occurs when SimpleHtmlSerializer.getAsString() tries to serialize this tree. The stack trace shows repeated calls between SimpleHtmlSerializer.serialize() and TagNode.serialize().
Maven dependency:
<dependency>
<groupId>net.sourceforge.htmlcleaner</groupId>
<artifactId>htmlcleaner</artifactId>
<version>2.29</version>
</dependency>
Java reproducer:
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.SimpleHtmlSerializer;
import org.htmlcleaner.TagNode;
public class Repro {
public static void main(String[] args) {
int depth = 9999;
StringBuilder input = new StringBuilder(depth * 11);
for (int i = 0; i < depth; i++)
input.append("<div>");
for (int i = 0; i < depth; i++)
input.append("</div>");
HtmlCleaner cleaner = new HtmlCleaner();
TagNode root = cleaner.clean(input.toString());
System.out.println("configured maxDepth=" +
cleaner.getProperties().getMaxDepth());
java.util.ArrayDeque<Object[]> todo =
new java.util.ArrayDeque<Object[]>();
todo.push(new Object[] { root, Integer.valueOf(1) });
int maxTreeDepth = 0;
while (!todo.isEmpty()) {
Object[] item = todo.pop();
TagNode node = (TagNode) item[0];
int nodeDepth = ((Integer) item[1]).intValue();
maxTreeDepth = Math.max(maxTreeDepth, nodeDepth);
for (org.htmlcleaner.BaseToken token :
node.getAllChildren()) {
if (token instanceof TagNode) {
todo.push(new Object[] {
token, Integer.valueOf(nodeDepth + 1)
});
}
}
}
System.out.println("actual max TagNode depth=" +
maxTreeDepth);
new SimpleHtmlSerializer(
cleaner.getProperties()).getAsString(root);
}
}
configured maxDepth=1000
actual max TagNode depth=10001
Exception in thread "main" java.lang.StackOverflowError
at org.htmlcleaner.SimpleHtmlSerializer.serialize(SimpleHtmlSerializer.java:67)
at org.htmlcleaner.TagNode.serialize(TagNode.java:778)
at org.htmlcleaner.SimpleHtmlSerializer.serialize(SimpleHtmlSerializer.java:67)
at org.htmlcleaner.TagNode.serialize(TagNode.java:778)
...
The tree depth was measured using an iterative traversal, so the measurement itself does not involve recursion.
Deeply nested HTML should be handled without overflowing the Java stack. Excessive nesting should either be limited during parsing or handled safely during serialization.
Applications that use SimpleHtmlSerializer to process untrusted HTML can encounter a StackOverflowError when given a deeply nested document, potentially causing denial of service.
The current maxDepth setting does not prevent this behavior in the reproduced case.
The serializer could enforce a depth limit or use an iterative traversal instead of recursive calls. Limiting the nesting depth of input HTML before serialization would also help prevent the issue.