From a377e8d3f53c1622820eb152e1920428e6fa6be6 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Wed, 6 Nov 2019 22:37:24 +0100 Subject: LibHTML+IRCClient: Add an escape_html_entities() helper This simple helper escapes '<', '>' and '&' so they can be used in HTML text without interfering with the parser. Use this in IRCClient to prevent incoming messages from messing with the DOM :^) --- Applications/IRCClient/IRCLogBuffer.cpp | 4 ++-- Libraries/LibHTML/Parser/HTMLParser.cpp | 16 ++++++++++++++++ Libraries/LibHTML/Parser/HTMLParser.h | 1 + 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/Applications/IRCClient/IRCLogBuffer.cpp b/Applications/IRCClient/IRCLogBuffer.cpp index 782a69c6cc..63ae080033 100644 --- a/Applications/IRCClient/IRCLogBuffer.cpp +++ b/Applications/IRCClient/IRCLogBuffer.cpp @@ -54,7 +54,7 @@ void IRCLogBuffer::add_message(char prefix, const String& name, const String& te color.to_string().characters(), timestamp_string().characters(), nick_string.characters(), - text.characters()); + escape_html_entities(text).characters()); auto fragment = parse_html_fragment(*m_document, html); m_container_element->append_child(fragment->remove_child(*fragment->first_child())); m_document->force_layout(); @@ -69,7 +69,7 @@ void IRCLogBuffer::add_message(const String& text, Color color) "", color.to_string().characters(), timestamp_string().characters(), - text.characters()); + escape_html_entities(text).characters()); auto fragment = parse_html_fragment(*m_document, html); m_container_element->append_child(fragment->remove_child(*fragment->first_child())); m_document->force_layout(); diff --git a/Libraries/LibHTML/Parser/HTMLParser.cpp b/Libraries/LibHTML/Parser/HTMLParser.cpp index c8275cd33c..94dc1299f1 100644 --- a/Libraries/LibHTML/Parser/HTMLParser.cpp +++ b/Libraries/LibHTML/Parser/HTMLParser.cpp @@ -339,3 +339,19 @@ RefPtr parse_html_document(const StringView& html, const URL& url) return document; } + +String escape_html_entities(const StringView& html) +{ + StringBuilder builder; + for (int i = 0; i < html.length(); ++i) { + if (html[i] == '<') + builder.append("<"); + else if (html[i] == '>') + builder.append(">"); + else if (html[i] == '&') + builder.append("&"); + else + builder.append(html[i]); + } + return builder.to_string(); +} diff --git a/Libraries/LibHTML/Parser/HTMLParser.h b/Libraries/LibHTML/Parser/HTMLParser.h index 8b06ce2842..b3feef07f1 100644 --- a/Libraries/LibHTML/Parser/HTMLParser.h +++ b/Libraries/LibHTML/Parser/HTMLParser.h @@ -7,3 +7,4 @@ class DocumentFragment; RefPtr parse_html_document(const StringView&, const URL& = URL()); RefPtr parse_html_fragment(Document&, const StringView&); +String escape_html_entities(const StringView&); -- cgit v1.2.3