Fix crash when converting malformed HTML with unmatched closing tag

This commit is contained in:
Shadowfacts 2024-02-06 18:53:47 -05:00
parent aed61d84d3
commit 1bfacb8fe9
4 changed files with 18 additions and 6 deletions

View File

@ -75,10 +75,12 @@ public struct AttributedStringConverter<Callbacks: HTMLConversionCallbacks> {
case .endTag(let name): case .endTag(let name):
handleEndTag(name) handleEndTag(name)
// if we have a non-default action for the current element, the run finishes here // if we have a non-default action for the current element, the run finishes here
if actionStack.last != .default { if let action = actionStack.last {
finishRun() if action != .default {
finishRun()
}
actionStack.removeLast()
} }
actionStack.removeLast()
case .doctype: case .doctype:
// ignored // ignored
continue continue

View File

@ -55,10 +55,12 @@ public struct TextConverter<Callbacks: HTMLConversionCallbacks> {
handleStartTag(name, selfClosing: selfClosing, attributes: attributes) handleStartTag(name, selfClosing: selfClosing, attributes: attributes)
case .endTag(let name): case .endTag(let name):
handleEndTag(name) handleEndTag(name)
if actionStack.last != .default { if let action = actionStack.last {
finishRun() if action != .default {
finishRun()
}
actionStack.removeLast()
} }
actionStack.removeLast()
case .comment, .doctype: case .comment, .doctype:
break break
} }

View File

@ -352,4 +352,8 @@ final class AttributedStringConverterTests: XCTestCase {
XCTAssertEqual(convert(#"<a href="https://example.com"><span class="invisible">https://</span><span>example.com</span><span class="invisible"></span></a>"#, callbacks: Callbacks.self), result) XCTAssertEqual(convert(#"<a href="https://example.com"><span class="invisible">https://</span><span>example.com</span><span class="invisible"></span></a>"#, callbacks: Callbacks.self), result)
} }
func testMalformedOnlyClosingTag() {
XCTAssertEqual(convert("</span>"), .init())
}
} }

View File

@ -83,4 +83,8 @@ final class TextConverterTests: XCTestCase {
XCTAssertEqual(convert(#"<a href="https://example.com"><span class="invisible">https://</span><span>example.com</span><span class="invisible"></span></a>"#, callbacks: Callbacks.self), "example.com") XCTAssertEqual(convert(#"<a href="https://example.com"><span class="invisible">https://</span><span>example.com</span><span class="invisible"></span></a>"#, callbacks: Callbacks.self), "example.com")
} }
func testMalformedOnlyClosingTag() {
XCTAssertEqual(convert("</span>"), "")
}
} }