Skip to content

Truly independent web browser

13.9 KB
Raw Blame
/*
 * Copyright (c) 2022, Ali Mohammad Pur <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/AnyOf.h>
#include <LibGC/Heap.h>
#include <LibWeb/DOM/CDATASection.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/DocumentType.h>
#include <LibWeb/DOM/ProcessingInstruction.h>
#include <LibWeb/HTML/HTMLLinkElement.h>
#include <LibWeb/HTML/HTMLScriptElement.h>
#include <LibWeb/HTML/HTMLTemplateElement.h>
#include <LibWeb/HTML/Parser/Entities.h>
#include <LibWeb/HTML/Parser/NamedCharacterReferences.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/SVG/TagNames.h>
#include <LibWeb/XML/XMLDocumentBuilder.h>

namespace Web {

Optional<String> resolve_named_html_entity(StringView entity_name)
{
    HTML::NamedCharacterReferenceMatcher matcher;
    for (auto c : entity_name) {
        if (!matcher.try_consume_ascii_char(c))
            return {};
    }
    if (!matcher.try_consume_ascii_char(';'))
        return {};

    auto codepoints = matcher.code_points();
    if (!codepoints.has_value())
        return {};

    StringBuilder builder;
    builder.append_code_point(codepoints.value().first);
    auto second_codepoint = HTML::named_character_reference_second_codepoint_value(codepoints.value().second);
    if (second_codepoint.has_value())
        builder.append_code_point(second_codepoint.value());

    return builder.to_string_without_validation();
}

XMLDocumentBuilder::XMLDocumentBuilder(DOM::Document& document, XMLScriptingSupport scripting_support)
    : m_document(document)
    , m_current_node(m_document)
    , m_scripting_support(scripting_support)
{
    m_namespace_stack.append({ {}, 1 });
}

ErrorOr<void> XMLDocumentBuilder::set_source(StringView source)
{
    m_document->update_readiness(HTML::DocumentReadyState::Loading);
    m_document->set_source(Utf16String::from_utf8_with_replacement_character(source));
    return {};
}

void XMLDocumentBuilder::set_doctype(XML::Doctype doctype)
{
    if (m_document->doctype()) {
        return;
    }

    auto document_type = DOM::DocumentType::create(m_document);
    auto name = Utf16FlyString::from_utf8(doctype.type.view());
    document_type->set_name(name);

    if (doctype.external_id.has_value()) {
        auto external_id = doctype.external_id.release_value();

        auto system_id = Utf16String::from_utf8(external_id.system_id.system_literal.view());
        document_type->set_system_id(system_id);

        if (external_id.public_id.has_value()) {
            auto public_id = external_id.public_id.release_value();
            auto public_id_string = Utf16String::from_utf8(public_id.public_literal.view());
            document_type->set_public_id(public_id_string);
        }
    }

    m_document->insert_before(document_type, m_document->first_child(), false);
}

void XMLDocumentBuilder::element_start(Utf16FlyString const& name, Vector<XML::ListenerAttribute> const& attributes)
{
    if (m_has_error)
        return;

    Vector<NamespaceAndPrefix, 2> namespaces;
    for (auto const& attribute : attributes) {
        if (attribute.name == "xmlns"sv || attribute.name.starts_with("xmlns:"sv)) {
            Optional<Utf16FlyString> prefix;
            auto namespace_ = Utf16FlyString::from_utf16(attribute.value.utf16_view());
            auto colon_position = attribute.name.view().find_code_unit_offset(':');
            if (colon_position.has_value()) {
                prefix = Utf16FlyString::from_utf16(attribute.name.view().substring_view(*colon_position + 1));
            }

            if (namespaces.find_if([&](auto const& namespace_and_prefix) { return namespace_and_prefix.prefix == prefix; }) != namespaces.end())
                continue;

            namespaces.append({ namespace_, prefix });
        }
    }

    if (!namespaces.is_empty()) {
        m_namespace_stack.append({ move(namespaces), 1 });
    } else {
        m_namespace_stack.last().depth += 1;
    }

    auto qualified_name_or_error = DOM::validate_and_extract(namespace_for_name(name), name, DOM::ValidationContext::Element);

    if (qualified_name_or_error.is_error()) {
        m_has_error = true;
        return;
    }

    auto qualified_name = qualified_name_or_error.value();

    auto node_or_error = DOM::create_element(m_document, qualified_name.local_name(), qualified_name.namespace_(), qualified_name.prefix());

    if (node_or_error.is_error()) {
        m_has_error = true;
        return;
    }

    auto node = node_or_error.value();

    // When an XML parser with XML scripting support enabled creates a script element,
    // it must have its parser document set and its "force async" flag must be unset.
    // FIXME: If the parser was created as part of the XML fragment parsing algorithm, then the element must be marked as "already started" also.
    // AD-HOC: SVG script elements are processed like HTML script elements, since SVG defines them as equivalent.
    if (auto* script_element = as_if<HTML::HTMLOrSVGScriptElement>(*node); script_element && m_scripting_support == XMLScriptingSupport::Enabled) {
        script_element->set_parser_document(Badge<XMLDocumentBuilder> {}, m_document);
        script_element->set_force_async(Badge<XMLDocumentBuilder> {}, false);
    }

    // AD-HOC: Let <link> elements know which document they were originally parsed for.
    //         This is used for the script-blocking and render-blocking logic.
    if (auto* link_element = as_if<HTML::HTMLLinkElement>(*node)) {
        link_element->set_parser_document(Badge<XMLDocumentBuilder> {}, m_document);
        auto has_disabled_attribute = any_of(attributes, [](auto const& attribute) { return attribute.name == "disabled"sv; });
        link_element->set_was_enabled_when_created_by_parser(Badge<XMLDocumentBuilder> {}, !has_disabled_attribute);
    }

    HTML::HTMLOrSVGScriptElement::ParserChildrenChangeScope script_children_change { *m_current_node };
    if (m_current_node->is_html_template_element()) {
        // When an XML parser would append a node to a template element, it must instead append it to the template element's template contents (a DocumentFragment node).
        MUST(static_cast<HTML::HTMLTemplateElement&>(*m_current_node).content()->append_child(node));
    } else {
        MUST(m_current_node->append_child(node));
    }

    for (auto const& attribute : attributes) {
        if (attribute.name == "xmlns"sv || attribute.name.starts_with("xmlns:"sv)) {
            // The prefix xmlns is used only to declare namespace bindings and is by definition bound to the namespace name http://www.w3.org/2000/xmlns/.
            if (!attribute.name.is_one_of("xmlns:"sv, "xmlns:xmlns"sv)) {
                auto maybe_extracted_qualified_name = DOM::validate_and_extract(Namespace::XMLNS, attribute.name, DOM::ValidationContext::Element);
                if (!maybe_extracted_qualified_name.is_error()) {
                    auto extracted_qualified_name = maybe_extracted_qualified_name.release_value();
                    node->set_attribute_value(extracted_qualified_name.local_name(), attribute.value, extracted_qualified_name.prefix(), extracted_qualified_name.namespace_());
                    continue;
                }
            }

            m_has_error = true;
        } else if (attribute.name.view().contains(':')) {
            if (auto namespace_for_key = namespace_for_name(attribute.name); namespace_for_key.has_value()) {
                auto maybe_extracted_qualified_name = DOM::validate_and_extract(namespace_for_key, attribute.name, DOM::ValidationContext::Element);
                if (!maybe_extracted_qualified_name.is_error()) {
                    auto extracted_qualified_name = maybe_extracted_qualified_name.release_value();
                    node->set_attribute_value(extracted_qualified_name.local_name(), attribute.value, extracted_qualified_name.prefix(), extracted_qualified_name.namespace_());
                    continue;
                }
            }

            m_has_error = true;
        } else {
            node->set_attribute_value(attribute.name, attribute.value);
        }
    }

    m_open_elements.append(node);
    m_current_node = node.ptr();
}

void XMLDocumentBuilder::element_end(Utf16FlyString const& name)
{
    if (m_has_error)
        return;

    if (--m_namespace_stack.last().depth == 0) {
        m_namespace_stack.take_last();
    }

    VERIFY(m_current_node->node_name().equals_ignoring_ascii_case(name));
    // When an XML parser with XML scripting support enabled creates a script element, [...]
    // When the element's end tag is subsequently parsed,
    if (auto* script_element = as_if<HTML::HTMLOrSVGScriptElement>(*m_current_node); script_element && m_scripting_support == XMLScriptingSupport::Enabled) {
        // the user agent must perform a microtask checkpoint,
        HTML::perform_a_microtask_checkpoint();
        // and then prepare the script element.
        // AD-HOC: Set the script text value for Trusted Types as the HTML parser does, matching other engines.
        script_element->set_script_text_from_parser();
        script_element->prepare_script(Badge<XMLDocumentBuilder> {});

        // If this causes there to be a pending parsing-blocking script, then the user agent must run the following steps:
        if (auto pending_parsing_blocking_script = m_document->pending_parsing_blocking_script()) {
            // 1. Block this instance of the XML parser, such that the event loop will not run tasks that invoke it.
            // NOTE: Noop.

            // 2. Spin the event loop until the parser's Document has no style sheet that is blocking scripts and the pending parsing-blocking script's "ready to be parser-executed" flag is set.
            if (m_document->has_a_style_sheet_that_is_blocking_scripts() || !pending_parsing_blocking_script->is_ready_to_be_parser_executed()) {
                HTML::main_thread_event_loop().spin_until(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *m_document }, pending_parsing_blocking_script->as_element()), [](GC::Ref<DOM::Document>& document, DOM::Element& script) {
                    return !document->has_a_style_sheet_that_is_blocking_scripts() && as<HTML::HTMLOrSVGScriptElement>(script).is_ready_to_be_parser_executed();
                }));
            }

            // 3. Unblock this instance of the XML parser, such that tasks that invoke it can again be run.
            // NOTE: Noop.

            // 4. Execute the script element given by the pending parsing-blocking script.
            pending_parsing_blocking_script->execute_script();

            // 5. Set the pending parsing-blocking script to null.
            m_document->set_pending_parsing_blocking_script(nullptr);
        }
    }

    (void)m_open_elements.take_last();
    if (m_open_elements.is_empty()) {
        m_current_node = m_document.ptr();
    } else {
        m_current_node = m_open_elements.last().ptr();
    }
}

void XMLDocumentBuilder::text(StringView data)
{
    if (m_has_error)
        return;

    HTML::HTMLOrSVGScriptElement::ParserChildrenChangeScope script_children_change { *m_current_node };
    if (auto* last = m_current_node->last_child(); last && last->is_text()) {
        auto& text_node = static_cast<DOM::Text&>(*last);
        m_text_builder.append(text_node.data());
        m_text_builder.append(Utf16String::from_utf8(data));
        text_node.set_data(m_text_builder.to_string());
        m_text_builder.clear();
    } else if (!data.is_empty()) {
        auto node = m_document->create_text_node(Utf16String::from_utf8(data));
        MUST(m_current_node->append_child(node));
    }
}

void XMLDocumentBuilder::comment(StringView data)
{
    if (m_has_error || !m_current_node)
        return;

    HTML::HTMLOrSVGScriptElement::ParserChildrenChangeScope script_children_change { *m_current_node };
    MUST(m_current_node->append_child(m_document->create_comment(Utf16String::from_utf8(data))));
}

void XMLDocumentBuilder::cdata_section(StringView data)
{
    if (m_has_error || !m_current_node)
        return;

    auto section = MUST(m_document->create_cdata_section(Utf16String::from_utf8(data)));
    HTML::HTMLOrSVGScriptElement::ParserChildrenChangeScope script_children_change { *m_current_node };
    MUST(m_current_node->append_child(section));
}

void XMLDocumentBuilder::processing_instruction(Utf16FlyString const& target, Utf16String const& data)
{
    if (m_has_error || !m_current_node)
        return;

    auto processing_instruction = MUST(m_document->create_processing_instruction(target, data));
    HTML::HTMLOrSVGScriptElement::ParserChildrenChangeScope script_children_change { *m_current_node };
    MUST(m_current_node->append_child(processing_instruction));
}

void XMLDocumentBuilder::document_end()
{
    // When an XML parser reaches the end of its input, it must stop parsing, following the same rules as the HTML parser.
    m_open_elements.clear();
    m_current_node = nullptr;

    HTML::HTMLParser::the_end(m_document, nullptr);
}

Optional<Utf16FlyString> XMLDocumentBuilder::namespace_for_name(Utf16FlyString const& name)
{
    Optional<Utf16FlyString> prefix;

    auto view = name.view();
    auto first_colon_position = view.find_code_unit_offset(':');
    if (first_colon_position.has_value()) {
        if (view.find_code_unit_offset(':', *first_colon_position + 1).has_value())
            return {};

        if (*first_colon_position == 0 || *first_colon_position == view.length_in_code_units() - 1)
            return {};
        prefix = Utf16FlyString::from_utf16(view.substring_view(0, *first_colon_position));
    }

    // The xml prefix is bound to the XML namespace by definition (Namespaces in XML 1.0 §3), whether or not anything
    // declares it, and a declaration of it can only say the same.
    if (prefix == "xml"sv)
        return Namespace::XML;

    for (auto const& stack_entry : m_namespace_stack.in_reverse()) {
        for (auto const& namespace_and_prefix : stack_entry.namespaces) {
            if (namespace_and_prefix.prefix == prefix) {
                return namespace_and_prefix.ns;
            }
        }
    }

    return {};
}

}