#include "HtmlParser.h" #include "LexborMemory.h" #include "Url.h" #include #include #include #include #ifdef ESP_PLATFORM #include #endif namespace web { namespace { constexpr size_t MAX_WORD_LENGTH = 128; // How much is parsed between checks of the DOM budget constexpr size_t PARSE_STEP = 1024; constexpr size_t MAX_FIELD_VALUE = 1000; constexpr size_t MAX_LABEL = 80; constexpr size_t MAX_OPTIONS = 100; #ifdef ESP_PLATFORM // What Lexbor needs to start, and some to spare for the rest of the system constexpr size_t REQUIRED_MEMORY = 1536 * 1024; #endif /** True when the name is one of the space separated words */ bool oneOf(const std::string& name, const char* words) { const char* position = words; while (*position != '\0') { const char* end = strchr(position, ' '); const size_t length = end != nullptr ? static_cast(end - position) : strlen(position); if (name.size() == length && memcmp(name.data(), position, length) == 0) return true; position += length + (end != nullptr ? 1 : 0); } return false; } bool isSpace(char c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == '\f'; } /** A width or height attribute in pixels, or 0 for anything else */ uint32_t pixels(const std::string& text) { uint32_t value = 0; for (const char c : text) { if (c < '0' || c > '9') return c == '%' ? 0 : value; value = value * 10 + (c - '0'); if (value > 20000) return 0; } return value; } char lower(char c); /** True for formats that can't be shown, going by the name: there is no point in downloading those */ bool isUnsupportedImage(const std::string& url) { std::string path = url.substr(0, url.find_first_of("?#")); for (auto& c : path) c = lower(c); const size_t dot = path.rfind('.'); return dot != std::string::npos && oneOf(path.substr(dot + 1), "gif svg webp avif ico bmp"); } char lower(char c) { return static_cast(std::tolower(static_cast(c))); } std::string attribute(lxb_dom_element_t* element, const char* name) { size_t length = 0; const lxb_char_t* value = lxb_dom_element_get_attribute(element, reinterpret_cast(name), strlen(name), &length); return value != nullptr ? std::string(reinterpret_cast(value), length) : std::string(); } bool hasAttribute(lxb_dom_element_t* element, const char* name) { return lxb_dom_element_has_attribute(element, reinterpret_cast(name), strlen(name)); } /** The next node inside @a root in document order, without recursion */ lxb_dom_node_t* following(lxb_dom_node_t* node, const lxb_dom_node_t* root) { if (node->first_child != nullptr) return node->first_child; while (node != root && node != nullptr) { if (node->next != nullptr) return node->next; node = node->parent; } return nullptr; } /** All text inside an element, cut off at @a limit bytes */ std::string textOf(lxb_dom_node_t* root, size_t limit) { std::string text; for (lxb_dom_node_t* node = root->first_child; node != nullptr && text.size() < limit; node = following(node, root)) { if (node->type != LXB_DOM_NODE_TYPE_TEXT) continue; const lexbor_str_t& data = lxb_dom_interface_text(node)->char_data.data; text.append(reinterpret_cast(data.data), data.length < limit - text.size() ? data.length : limit - text.size()); } // Not in the middle of a character size_t position = text.size(); while (position > 0 && (static_cast(text[position - 1]) & 0xC0) == 0x80) position--; if (position > 0 && static_cast(text[position - 1]) >= 0xC0) { const auto lead = static_cast(text[position - 1]); const size_t needed = lead >= 0xF0 ? 4 : lead >= 0xE0 ? 3 : 2; if (text.size() - position + 1 < needed) text.erase(position - 1); } return text; } /** With single spaces between words, and none around them */ std::string collapsed(const std::string& text) { std::string result; bool space = false; for (const char c : text) { if (isSpace(c)) { space = !result.empty(); } else { if (space) result += ' '; result += c; space = false; } } return result; } std::string lowercase(std::string text) { for (auto& c : text) c = lower(c); return text; } std::string elementName(lxb_dom_node_t* node) { size_t length = 0; const lxb_char_t* name = lxb_dom_element_local_name(lxb_dom_interface_element(node), &length); return name != nullptr ? std::string(reinterpret_cast(name), length) : std::string(); } } bool HtmlParser::begin(Document* target, const std::string& url, const std::string& charset, bool plainText, size_t domBudget) { document = target; baseUrl = url; pageUrl = url; plain = plainText; decoder.begin(charset); if (plain) { pre = 1; document->beginBlock(BlockKind::Preformatted, 0, false); return true; } budget = domBudget; #ifdef ESP_PLATFORM // Not tried when it can't work: Lexbor leaks when it runs out halfway through starting. Without external memory // this is 0. const size_t available = memory_external_free(); if (available < REQUIRED_MEMORY) return false; if (budget > available - REQUIRED_MEMORY) budget = available - REQUIRED_MEMORY; #endif setupLexborMemory(); dom = lxb_html_document_create(); if (dom != nullptr && lxb_html_document_parse_chunk_begin(dom) != LXB_STATUS_OK) release(); // Lexbor reserves about 1 MB before the first byte, which isn't part of the budget memoryBefore = lexborMemoryUsed(); return dom != nullptr; } void HtmlParser::release() { if (dom != nullptr) lxb_html_document_destroy(dom); dom = nullptr; } void HtmlParser::feed(const char* data, size_t length) { std::string decoded; decoded.reserve(length + 16); decoder.feed(data, length, decoded); if (plain) { for (const char c : decoded) character(c); return; } if (dom == nullptr) return; const std::string& html = decoded; for (size_t offset = 0; offset < html.size() && !full; offset += PARSE_STEP) { const size_t size = html.size() - offset < PARSE_STEP ? html.size() - offset : PARSE_STEP; const auto* bytes = reinterpret_cast(html.data() + offset); const size_t usedNow = lexborMemoryUsed() - memoryBefore; full = usedNow > budget || lxb_html_document_parse_chunk(dom, bytes, size) != LXB_STATUS_OK; } } void HtmlParser::finish() { if (dom != nullptr) { // Also after running out: what was parsed is shown lxb_html_document_parse_chunk_end(dom); render(); release(); } flush(); document->endBlock(); } /** Walks the tree without recursion, as pages may nest very deeply */ void HtmlParser::render() { lxb_dom_node_t* root = lxb_dom_interface_node(dom); lxb_dom_node_t* node = root->first_child; while (node != nullptr && !document->isTruncated()) { bool descend = false; if (node->type == LXB_DOM_NODE_TYPE_TEXT) { const lexbor_str_t& data = lxb_dom_interface_text(node)->char_data.data; for (size_t i = 0; i < data.length && !document->isTruncated(); i++) character(static_cast(data.data[i])); } else if (node->type == LXB_DOM_NODE_TYPE_ELEMENT) { const std::string name = elementName(node); if (name == "title") { if (node->ns == LXB_NS_HTML) readTitle(node); } else if (enter(node, name)) { descend = node->first_child != nullptr; if (!descend) closeElement(name); } } if (descend) { node = node->first_child; continue; } while (node->next == nullptr) { node = node->parent; if (node == nullptr || node == root) return; const std::string name = elementName(node); // In a table, a form is closed right away while the fields that follow it belong to it if (name == "form" && node->first_child != nullptr) form = NO_FIELD; closeElement(name); } node = node->next; } } bool HtmlParser::enter(lxb_dom_node_t* node, const std::string& name) { if (oneOf(name, "script style noembed noframes xmp iframe")) return false; if (oneOf(name, "svg template math")) { flush(); return false; } lxb_dom_element_t* source = lxb_dom_interface_element(node); std::string id = attribute(source, "id"); if (id.empty() && name == "a") id = attribute(source, "name"); if (!id.empty()) { flush(); document->addAnchor(id); } if (name == "form") { addForm(source); } else if (name == "input") { addInput(source); return false; } else if (name == "button") { addButton(node); return false; } else if (name == "select") { addSelect(node); return false; } else if (name == "textarea") { addTextArea(node); return false; } openElement(name, source); return true; } void HtmlParser::readTitle(lxb_dom_node_t* node) { if (!document->getTitle().empty()) return; std::string title; for (lxb_dom_node_t* child = node->first_child; child != nullptr; child = child->next) { if (child->type != LXB_DOM_NODE_TYPE_TEXT) continue; const lexbor_str_t& data = lxb_dom_interface_text(child)->char_data.data; for (size_t i = 0; i < data.length && title.size() < 200; i++) { const char c = static_cast(data.data[i]); title += isSpace(c) ? ' ' : c; } } setTitle(title); } void HtmlParser::setTitle(std::string title) { if (title.size() > 200) title.resize(200); // Not in the middle of a character size_t position = title.size(); while (position > 0 && (static_cast(title[position - 1]) & 0xC0) == 0x80) position--; if (position > 0 && static_cast(title[position - 1]) >= 0xC0) { const auto lead = static_cast(title[position - 1]); const size_t needed = lead >= 0xF0 ? 4 : lead >= 0xE0 ? 3 : 2; if (title.size() - position + 1 < needed) title.erase(position - 1); } while (!title.empty() && title.back() == ' ') title.pop_back(); while (!title.empty() && title.front() == ' ') title.erase(0, 1); while (!title.empty() && title.back() == ' ') title.pop_back(); while (!title.empty() && title.front() == ' ') title.erase(0, 1); document->setTitle(title); } uint8_t HtmlParser::currentStyle() const { uint8_t style = 0; if (bold > 0) style |= STYLE_BOLD; if (italic > 0) style |= STYLE_ITALIC; if (code > 0) style |= STYLE_CODE; return style; } uint8_t HtmlParser::currentIndent() const { const int depth = static_cast(lists.size()) + quoteDepth; return static_cast(depth > 6 ? 6 : depth); } void HtmlParser::emit(const std::string& text, uint8_t style) { document->append(text.data(), text.size(), style, link); } /** A space is only part of a link or style when the text on both sides is */ void HtmlParser::emitSpace() { if (pendingSpace && !document->endsWithSpace()) { const uint16_t shared = document->lastLink() == link ? link : NO_LINK; document->append(" ", 1, currentStyle() & document->lastStyle(), shared); } pendingSpace = false; } void HtmlParser::flush() { if (word.empty()) return; emitSpace(); emit(word, currentStyle()); word.clear(); } void HtmlParser::breakBlock(bool gap) { flush(); pendingSpace = false; const BlockKind kind = heading > 0 ? BlockKind::Heading : pre > 0 ? BlockKind::Preformatted : BlockKind::Text; document->beginBlock(kind, currentIndent(), gap); } void HtmlParser::codepoint(uint32_t cp) { if (cp == 0xAD || (cp >= 0x200B && cp <= 0x200F) || cp == 0xFEFF) return; if (cp < 0x80) { character(static_cast(cp)); return; } if (glyphFilter == nullptr || glyphFilter(cp, glyphUserData)) { appendUtf8(word, cp); } else { for (const char* c = asciiFallback(cp); *c != '\0'; c++) character(*c); } } /** A character of the page's text, as ASCII or a byte of a UTF-8 sequence */ void HtmlParser::character(char c) { const auto byte = static_cast(c); // Multi-byte characters are checked against the font when their last byte arrives if (byte >= 0x80) { word += c; size_t start = word.size(); while (start > 0 && (static_cast(word[start - 1]) & 0xC0) == 0x80) start--; if (start == 0) return; start--; const auto lead = static_cast(word[start]); const size_t needed = lead >= 0xF0 ? 4 : lead >= 0xE0 ? 3 : lead >= 0xC0 ? 2 : 1; if (word.size() - start == needed) { size_t position = start; const uint32_t cp = nextUtf8(word.data(), word.size(), position); word.erase(start); codepoint(cp); } return; } if (pre > 0) { if (c == '\r') return; if (c == '\t') { word += " "; } else if (byte >= ' ' || c == '\n') { word += c; } if (c == '\n' || word.size() >= MAX_WORD_LENGTH) flush(); return; } if (isSpace(c)) { flush(); pendingSpace = true; } else if (byte > ' ') { word += c; // Only splits between characters, as only ASCII gets here if (word.size() >= MAX_WORD_LENGTH) flush(); } } void HtmlParser::openElement(const std::string& name, lxb_dom_element_t* element) { if (name == "base") { const std::string base = resolveUrl(baseUrl, attribute(element, "href")); if (!base.empty()) baseUrl = base; } else if (name == "br") { flush(); if (pre > 0) character('\n'); // A second
makes an empty line else breakBlock(!document->hasOpenText()); } else if (name == "hr") { flush(); document->addRule(); } else if (name == "a") { flush(); link = NO_LINK; emitSpace(); const std::string href = attribute(element, "href"); link = href.empty() ? NO_LINK : document->addLink(resolveUrl(baseUrl, href)); } else if (name == "img" || name == "image") { addImage(element); } else if (oneOf(name, "b strong th")) { flush(); if (name == "th") pendingSpace = true; bold++; } else if (oneOf(name, "i em cite")) { flush(); italic++; } else if (oneOf(name, "code tt kbd samp")) { flush(); code++; } else if (name == "td") { flush(); pendingSpace = true; } else if (name == "pre") { pre++; breakBlock(true); } else if (name.size() == 2 && name[0] == 'h' && name[1] >= '1' && name[1] <= '6') { heading = 1; breakBlock(true); } else if (name == "blockquote") { quoteDepth++; breakBlock(true); } else if (oneOf(name, "ul ol menu")) { flush(); const bool nested = !lists.empty(); if (lists.size() < 8) lists.push_back(name == "ol" ? 1 : 0); breakBlock(!nested); } else if (name == "li") { breakBlock(false); std::string marker = "* "; if (!lists.empty() && lists.back() > 0) marker = std::to_string(lists.back()++) + ". "; const uint16_t previous = link; link = NO_LINK; emit(marker, 0); link = previous; } else if (name == "dd") { flush(); document->beginBlock(BlockKind::Text, static_cast(currentIndent() + 1), false); pendingSpace = false; } else if (oneOf(name, "p table figure dl form")) { breakBlock(true); } else if (oneOf(name, "div section article header footer nav main aside tr dt caption figcaption address center summary details fieldset")) { breakBlock(false); } } void HtmlParser::addImage(lxb_dom_element_t* element) { flush(); const uint32_t imageWidth = pixels(attribute(element, "width")); const uint32_t imageHeight = pixels(attribute(element, "height")); std::string label = hasAttribute(element, "alt") ? attribute(element, "alt") : (link != NO_LINK ? imageLabel : ""); const std::string address = images ? resolveUrl(baseUrl, attribute(element, "src")) : ""; // Tiny pictures are spacers and trackers const bool tiny = (imageWidth > 0 && imageWidth < 8) || (imageHeight > 0 && imageHeight < 8); if (!address.empty() && !tiny && !isUnsupportedImage(address)) { if (label.empty()) label = imageLabel; pendingSpace = false; // The description may need characters that the font lacks word = "["; for (const char c : label) character(c); word += "]"; const std::string text = word; word.clear(); pendingSpace = false; document->addImage({ toString(address), static_cast(imageWidth), static_cast(imageHeight) }, text, link, currentIndent()); breakBlock(false); } else if (!label.empty() && !tiny) { emitSpace(); word = "["; for (const char c : label) character(c); word += "]"; flush(); } } void HtmlParser::addForm(lxb_dom_element_t* element) { const std::string action = attribute(element, "action"); // Without an action, a form goes to its own page const std::string target = action.empty() ? withoutFragment(pageUrl) : resolveUrl(baseUrl, action); const std::string method = lowercase(attribute(element, "method")); const bool post = method == "post"; // As the standard says, any other method means GET. A dialog isn't sent anywhere, and there are no files to send. const bool unsupported = method == "dialog" || (post && lowercase(attribute(element, "enctype")) == "multipart/form-data"); form = document->addForm(target, post, unsupported); } /** A field outside of a form is of no use without JavaScript */ void HtmlParser::addField(Field field, const std::string& label) { flush(); field.form = form; // Buttons and boxes are words in the text const bool inText = field.type == FieldType::Submit || field.type == FieldType::Checkbox || field.type == FieldType::Radio; if (inText) emitSpace(); document->addField(std::move(field), label, currentIndent()); pendingSpace = inText; if (!inText && document->getBlocks().size() > 0) breakBlock(false); } void HtmlParser::addInput(lxb_dom_element_t* element) { const std::string type = lowercase(attribute(element, "type")); if (form == NO_FIELD || hasAttribute(element, "disabled") || oneOf(type, "button reset file")) return; Field field; field.name = toString(attribute(element, "name")); const std::string value = attribute(element, "value"); field.value = toString(value.substr(0, MAX_FIELD_VALUE)); std::string label; if (type == "hidden") { field.type = FieldType::Hidden; } else if (type == "submit" || type == "image") { field.type = FieldType::Submit; label = collapsed(!value.empty() ? value : attribute(element, "alt")); label = label.empty() ? submitLabel : label.substr(0, MAX_LABEL); } else if (type == "checkbox" || type == "radio") { field.type = type == "radio" ? FieldType::Radio : FieldType::Checkbox; field.checked = hasAttribute(element, "checked"); if (!hasAttribute(element, "value")) field.value = "on"; } else { field.type = type == "password" ? FieldType::Password : FieldType::Text; std::string placeholder = attribute(element, "placeholder"); if (placeholder.empty()) placeholder = attribute(element, "aria-label"); field.placeholder = toString(placeholder.substr(0, MAX_LABEL)); } addField(std::move(field), label); } void HtmlParser::addButton(lxb_dom_node_t* node) { lxb_dom_element_t* element = lxb_dom_interface_element(node); const std::string type = lowercase(attribute(element, "type")); if (form == NO_FIELD || hasAttribute(element, "disabled") || oneOf(type, "button reset")) return; Field field; field.type = FieldType::Submit; field.name = toString(attribute(element, "name")); field.value = toString(attribute(element, "value").substr(0, MAX_FIELD_VALUE)); std::string label = collapsed(textOf(node, MAX_LABEL)); if (label.empty()) label = collapsed(attribute(element, "aria-label")); addField(std::move(field), label.empty() ? submitLabel : label.substr(0, MAX_LABEL)); } void HtmlParser::addSelect(lxb_dom_node_t* node) { lxb_dom_element_t* element = lxb_dom_interface_element(node); if (form == NO_FIELD || hasAttribute(element, "disabled")) return; Field field; field.type = FieldType::Select; field.name = toString(attribute(element, "name")); for (lxb_dom_node_t* child = node->first_child; child != nullptr && field.labels.size() < MAX_OPTIONS; child = following(child, node)) { if (child->type != LXB_DOM_NODE_TYPE_ELEMENT || elementName(child) != "option") continue; lxb_dom_element_t* option = lxb_dom_interface_element(child); const std::string label = collapsed(textOf(child, MAX_LABEL)); if (hasAttribute(option, "selected")) field.selected = static_cast(field.labels.size()); field.labels.push_back(toString(label)); field.values.push_back(toString(hasAttribute(option, "value") ? attribute(option, "value").substr(0, MAX_FIELD_VALUE) : label)); } if (!field.labels.empty()) addField(std::move(field), ""); } void HtmlParser::addTextArea(lxb_dom_node_t* node) { lxb_dom_element_t* element = lxb_dom_interface_element(node); if (form == NO_FIELD || hasAttribute(element, "disabled")) return; Field field; field.name = toString(attribute(element, "name")); field.value = toString(textOf(node, MAX_FIELD_VALUE)); field.placeholder = toString(attribute(element, "placeholder").substr(0, MAX_LABEL)); addField(std::move(field), ""); } void HtmlParser::closeElement(const std::string& name) { if (name == "a") { flush(); link = NO_LINK; } else if (oneOf(name, "b strong th")) { flush(); if (bold > 0) bold--; } else if (oneOf(name, "i em cite")) { flush(); if (italic > 0) italic--; } else if (oneOf(name, "code tt kbd samp")) { flush(); if (code > 0) code--; } else if (name == "pre") { flush(); if (pre > 0) pre--; breakBlock(true); } else if (name.size() == 2 && name[0] == 'h' && name[1] >= '1' && name[1] <= '6') { flush(); heading = 0; breakBlock(true); } else if (name == "blockquote") { flush(); if (quoteDepth > 0) quoteDepth--; breakBlock(true); } else if (oneOf(name, "ul ol menu")) { flush(); if (!lists.empty()) lists.pop_back(); breakBlock(lists.empty()); } else if (oneOf(name, "p table figure dl form")) { breakBlock(true); } else if (oneOf(name, "div section article header footer nav main aside tr li dt dd caption figcaption address center summary details fieldset")) { breakBlock(false); } } }