Truly independent web browser
LibURL+LibWebCommon+LibWeb: Process data: URLs in Rust
Shannon Booth892fb7045c2e
diff --git a/Cargo.lock b/Cargo.lockindex 2839ba8e515..805aca05215 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -919,6 +919,7 @@ dependencies = ["ak","cbindgen","ladybird_allocator",+ "liburl_rust","rustc-demangle",]diff --git a/Libraries/LibURL/Rust/src/url/mod.rs b/Libraries/LibURL/Rust/src/url/mod.rsindex 4e984a1db21..73bbad38237 100644--- a/Libraries/LibURL/Rust/src/url/mod.rs+++ b/Libraries/LibURL/Rust/src/url/mod.rs@@ -15,6 +15,7 @@ mod types;pub(crate) use self::host::parse_host_into;pub use self::input::UrlInput;+pub use self::percent_encoding::percent_decode_bytes;pub use self::scheme::SchemeType;pub(crate) use self::scheme::default_port_for_scheme;pub(crate) use self::scheme::is_special_scheme;diff --git a/Libraries/LibURL/Rust/src/url/percent_encoding.rs b/Libraries/LibURL/Rust/src/url/percent_encoding.rsindex dd0ea7ea4c9..cd21f218c5e 100644--- a/Libraries/LibURL/Rust/src/url/percent_encoding.rs+++ b/Libraries/LibURL/Rust/src/url/percent_encoding.rs@@ -137,7 +137,7 @@ pub(super) fn percent_decode_input(input: super::UrlInput<'_>) -> Vec<u8> {}// https://url.spec.whatwg.org/#percent-decode-pub(super) fn percent_decode_bytes(input: &[u8]) -> Vec<u8> {+pub fn percent_decode_bytes(input: &[u8]) -> Vec<u8> {// 1. Let output be an empty byte sequence.let mut output = Vec::with_capacity(input.len());diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 655e05dc8ed..4a6ab326b92 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -397,7 +397,6 @@ set(SOURCESFetch/Infrastructure/PortBlocking.cppFetch/Infrastructure/PreflightCache.cppFetch/Infrastructure/Task.cpp- Fetch/Infrastructure/URL.cppFetch/Request.cppFetch/Response.cppFileAPI/Blob.cppdiff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex f12eeb7a90f..2772508ddb8 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -46,7 +46,6 @@#include <LibWeb/Fetch/Infrastructure/PortBlocking.h>#include <LibWeb/Fetch/Infrastructure/PreflightCache.h>#include <LibWeb/Fetch/Infrastructure/Task.h>-#include <LibWeb/Fetch/Infrastructure/URL.h>#include <LibWeb/FileAPI/Blob.h>#include <LibWeb/FileAPI/BlobURLStore.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>@@ -74,6 +73,7 @@#include <LibWeb/Streams/TransformStreamOperations.h>#include <LibWeb/WebIDL/DOMException.h>#include <LibWeb/WebIDL/ExceptionOrUtils.h>+#include <LibWebCommon/Fetch/Infrastructure/DataURL.h>#include <LibWebCommon/Fetch/Infrastructure/HTTP/Statuses.h>#include <LibWebCommon/Fetch/Infrastructure/URL.h>#include <LibWebCommon/Loader/UserAgent.h>diff --git a/Libraries/LibWeb/Fetch/Infrastructure/URL.cpp b/Libraries/LibWeb/Fetch/Infrastructure/URL.cppdeleted file mode 100644index afcec9f9e1f..00000000000--- a/Libraries/LibWeb/Fetch/Infrastructure/URL.cpp+++ /dev/null@@ -1,93 +0,0 @@-/*- * Copyright (c) 2022, Linus Groh <[email protected]>- * Copyright (c) 2022, Andreas Kling <[email protected]>- * Copyright (c) 2023, Karol Kosek <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Base64.h>-#include <LibTextCodec/Decoder.h>-#include <LibURL/URL.h>-#include <LibWeb/Export.h>-#include <LibWeb/Fetch/Infrastructure/URL.h>-#include <LibWebCommon/MimeSniff/MimeType.h>--namespace Web::Fetch::Infrastructure {--// https://fetch.spec.whatwg.org/#data-url-processor-ErrorOr<DataURL> process_data_url(URL::URL const& data_url)-{- // 1. Assert: dataURL’s scheme is "data".- VERIFY(data_url.scheme() == "data");-- // 2. Let input be the result of running the URL serializer on dataURL with exclude fragment set to true.- auto input_serialized = data_url.serialize(URL::ExcludeFragment::Yes);- StringView input = input_serialized;-- // 3. Remove the leading "data:" from input.- input = input.substring_view("data:"sv.length());-- // 4. Let position point at the start of input.-- // 5. Let mimeType be the result of collecting a sequence of code points that are not equal to U+002C (,), given position.- auto position = input.find(',');- auto mime_type = input.substring_view(0, position.value_or(input.length()));-- // 6. Strip leading and trailing ASCII whitespace from mimeType.- mime_type = mime_type.trim_whitespace(TrimMode::Both);-- // 7. If position is past the end of input, then return failure.- if (!position.has_value())- return Error::from_string_literal("Missing a comma character");-- // 8. Advance position by 1.- position = position.value() + 1;-- // 9. Let encodedBody be the remainder of input.- auto encoded_body = input.substring_view(position.value());-- // 10. Let body be the percent-decoding of encodedBody.- auto body = URL::percent_decode(encoded_body).to_byte_buffer();-- // 11. If mimeType ends with U+003B (;), followed by zero or more U+0020 SPACE, followed by an ASCII case-insensitive match for "base64", then:- if (mime_type.ends_with("base64"sv, CaseSensitivity::CaseInsensitive)) {- auto trimmed_substring_view = mime_type.substring_view(0, mime_type.length() - 6);- trimmed_substring_view = trimmed_substring_view.trim(" "sv, TrimMode::Right);- if (trimmed_substring_view.ends_with(';')) {- // 1. Let stringBody be the isomorphic decode of body.- auto string_body = TextCodec::isomorphic_decode(body);-- // 2. Set body to the forgiving-base64 decode of stringBody.- // 3. If body is failure, then return failure.- body = TRY(decode_base64(string_body));-- // 4. Remove the last 6 code points from mimeType.- // 5. Remove trailing U+0020 SPACE code points from mimeType, if any.- // 6. Remove the last U+003B (;) from mimeType.- mime_type = trimmed_substring_view.substring_view(0, trimmed_substring_view.length() - 1);- }- }-- // 12. If mimeType starts with ";", then prepend "text/plain" to mimeType.- StringBuilder builder;- if (mime_type.starts_with(';')) {- builder.append("text/plain"sv);- builder.append(mime_type);- mime_type = builder.string_view();- }-- // 13. Let mimeTypeRecord be the result of parsing mimeType.- auto mime_type_record = MimeSniff::MimeType::parse(mime_type);-- // 14. If mimeTypeRecord is failure, then set mimeTypeRecord to text/plain;charset=US-ASCII.- if (!mime_type_record.has_value()) {- mime_type_record = MimeSniff::MimeType::create("text"_string, "plain"_string);- mime_type_record->set_parameter("charset"_string, "US-ASCII"_string);- }-- // 15. Return a new data: URL struct whose MIME type is mimeTypeRecord and body is body.- return DataURL { mime_type_record.release_value(), body };-}--}diff --git a/Libraries/LibWeb/Loader/ResourceLoader.cpp b/Libraries/LibWeb/Loader/ResourceLoader.cppindex bdf3e6e0fc6..3367c1a87ea 100644--- a/Libraries/LibWeb/Loader/ResourceLoader.cpp+++ b/Libraries/LibWeb/Loader/ResourceLoader.cpp@@ -20,7 +20,6 @@#include <LibWeb/Bindings/MainThreadVM.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>-#include <LibWeb/Fetch/Infrastructure/URL.h>#include <LibWeb/Loader/ContentBlocker.h>#include <LibWeb/Loader/GeneratedPagesLoader.h>#include <LibWeb/Loader/LoadRequest.h>diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp b/Libraries/LibWeb/WebAssembly/WebAssembly.cppindex 8c09176ab91..3c3dd238078 100644--- a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp@@ -35,7 +35,6 @@#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h>#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>-#include <LibWeb/Fetch/Infrastructure/URL.h>#include <LibWeb/Fetch/Response.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>diff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txtindex 0ae6197d402..8224d81d68d 100644--- a/Libraries/LibWebCommon/CMakeLists.txt+++ b/Libraries/LibWebCommon/CMakeLists.txt@@ -5,6 +5,7 @@ set(SOURCESCSS/PreferredColorScheme.cppCSS/StyleSheetIdentifier.cppCSS/SystemColor.cpp+ Fetch/Infrastructure/DataURL.cppFetch/Infrastructure/HTTP/Statuses.cppFetch/Infrastructure/URL.cppFileAPI/BlobURLStore.cpp@@ -150,8 +151,9 @@ target_link_libraries(LibWebCommon PRIVATE LibCore LibCrypto LibFileSystem LibGfimport_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libwebcommon_rust FEATURES allocator FFI_HEADER RustFFI.h)target_link_libraries(LibWebCommon PRIVATE libwebcommon_rust)+target_link_libraries(libwebcommon_rust INTERFACE LibUnicode LibRegex)get_target_property(_libwebcommon_rust_lib libwebcommon_rust IMPORTED_LOCATION)-set_property(SOURCE MimeSniff/MimeType.cpp MimeSniff/Resource.cpp APPEND PROPERTY OBJECT_DEPENDS ${_libwebcommon_rust_lib})+set_property(SOURCE Fetch/Infrastructure/DataURL.cpp MimeSniff/MimeType.cpp MimeSniff/Resource.cpp APPEND PROPERTY OBJECT_DEPENDS ${_libwebcommon_rust_lib})test_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libwebcommon_rust)if (ENABLE_INSTALL_HEADERS)diff --git a/Libraries/LibWebCommon/Fetch/Infrastructure/DataURL.cpp b/Libraries/LibWebCommon/Fetch/Infrastructure/DataURL.cppnew file mode 100644index 00000000000..2ea60a1b426--- /dev/null+++ b/Libraries/LibWebCommon/Fetch/Infrastructure/DataURL.cpp@@ -0,0 +1,40 @@+/*+ * Copyright (c) 2022, Linus Groh <[email protected]>+ * Copyright (c) 2022, Andreas Kling <[email protected]>+ * Copyright (c) 2023, Karol Kosek <[email protected]>+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibURL/URL.h>+#include <LibWebCommon/Fetch/Infrastructure/DataURL.h>+#include <LibWebCommon/RustFFI.h>++namespace Web::Fetch::Infrastructure {++// https://fetch.spec.whatwg.org/#data-url-processor+ErrorOr<DataURL> process_data_url(URL::URL const& data_url)+{+ // 1. Assert: dataURL’s scheme is "data".+ VERIFY(data_url.scheme() == "data");++ // 2. Let input be the result of running the URL serializer on dataURL with exclude fragment set to true.+ auto input = data_url.serialize(URL::ExcludeFragment::Yes);++ // NB: The rest of the steps are in Rust/src/fetch/data_url.rs.+ struct Result {+ ByteBuffer body;+ Optional<MimeSniff::MimeType> mime_type;+ } result;+ auto on_body = [](void* ctx, ReadonlyBytes bytes) {+ static_cast<Result*>(ctx)->body = MUST(ByteBuffer::copy(bytes));+ };+ auto on_mime_type = [](void* ctx, FFI::FfiMimeType const* mime_type) {+ static_cast<Result*>(ctx)->mime_type = MimeSniff::MimeType::from_ffi(*mime_type);+ };+ if (!FFI::fetch_process_data_url(input.bytes(), &result, on_body, on_mime_type))+ return Error::from_string_literal("Invalid data: URL");+ return DataURL { result.mime_type.release_value(), move(result.body) };+}++}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/URL.h b/Libraries/LibWebCommon/Fetch/Infrastructure/DataURL.hsimilarity index 82%rename from Libraries/LibWeb/Fetch/Infrastructure/URL.hrename to Libraries/LibWebCommon/Fetch/Infrastructure/DataURL.hindex acecc30d138..060a4042efc 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/URL.h+++ b/Libraries/LibWebCommon/Fetch/Infrastructure/DataURL.h@@ -10,7 +10,7 @@#include <AK/ByteBuffer.h>#include <AK/Error.h>#include <LibURL/Forward.h>-#include <LibWeb/Export.h>+#include <LibWebCommon/Export.h>#include <LibWebCommon/MimeSniff/MimeType.h>namespace Web::Fetch::Infrastructure {@@ -21,6 +21,6 @@ struct DataURL {ByteBuffer body;};-WEB_API ErrorOr<DataURL> process_data_url(URL::URL const&);+WEBCOMMON_API ErrorOr<DataURL> process_data_url(URL::URL const&);}diff --git a/Libraries/LibWebCommon/Rust/Cargo.toml b/Libraries/LibWebCommon/Rust/Cargo.tomlindex 22851e2adf6..5c4ba6fb552 100644--- a/Libraries/LibWebCommon/Rust/Cargo.toml+++ b/Libraries/LibWebCommon/Rust/Cargo.toml@@ -9,6 +9,7 @@ crate-type = ["staticlib"][dependencies]ak = { path = "../../../AK/Rust" }ladybird_allocator = { path = "../../RustAllocator", optional = true }+liburl_rust = { path = "../../LibURL/Rust", default-features = false }rustc-demangle = "0.1"[features]diff --git a/Libraries/LibWebCommon/Rust/src/fetch/data_url.rs b/Libraries/LibWebCommon/Rust/src/fetch/data_url.rsnew file mode 100644index 00000000000..b6bbfe7a2f9--- /dev/null+++ b/Libraries/LibWebCommon/Rust/src/fetch/data_url.rs@@ -0,0 +1,133 @@+/*+ * Copyright (c) 2022, Linus Groh <[email protected]>+ * Copyright (c) 2022, Andreas Kling <[email protected]>+ * Copyright (c) 2023, Karol Kosek <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;++use ak::{Base64Alphabet, LastChunkHandling, Span, Utf16StringUnits, decode_base64};+use liburl_rust::url::percent_decode_bytes;++use crate::mime_sniff::ffi::{OnMimeType, lend_mime_type};+use crate::mime_sniff::mime_type::MimeType;+use crate::rust_panic::abort_on_panic;++// https://fetch.spec.whatwg.org/#data-url-struct+pub struct DataUrl {+ pub mime_type: MimeType,+ pub body: Vec<u8>,+}++// https://infra.spec.whatwg.org/#forgiving-base64-decode+fn forgiving_base64_decode(string: &[u8]) -> Option<Vec<u8>> {+ // NB: A code point outside ASCII is never part of base64 data, nor ASCII whitespace.+ if !string.is_ascii() {+ return None;+ }+ let result = decode_base64(+ Utf16StringUnits::Ascii(string),+ Base64Alphabet::Base64,+ LastChunkHandling::Loose,+ None,+ );+ result.error.is_none().then_some(result.bytes)+}++// https://fetch.spec.whatwg.org/#data-url-processor+// NB: C++ runs steps 1 and 2, and passes the serialization of the URL as input.+pub fn process_data_url(input: &str) -> Option<DataUrl> {+ // 3. Remove the leading "data:" from input.+ let input = input.strip_prefix("data:").expect("the URL's scheme is data");++ // 4. Let position point at the start of input.+ // 5. Let mimeType be the result of collecting a sequence of code points that are not equal to U+002C (,), given+ // position.+ let position = input.find(',');+ let mime_type = &input[..position.unwrap_or(input.len())];++ // 6. Strip leading and trailing ASCII whitespace from mimeType.+ let mut mime_type = mime_type.trim_ascii();++ // 7. If position is past the end of input, then return failure.+ let position = position?;++ // 8. Advance position by 1.+ // 9. Let encodedBody be the remainder of input.+ let encoded_body = &input[position + 1..];++ // 10. Let body be the percent-decoding of encodedBody.+ let mut body = percent_decode_bytes(encoded_body.as_bytes());++ // 11. If mimeType ends with U+003B (;), followed by zero or more U+0020 SPACE, followed by an ASCII+ // case-insensitive match for "base64", then:+ let base64_suffix_start = mime_type.len().checked_sub("base64".len());+ if let Some(start) = base64_suffix_start+ && mime_type[start..].eq_ignore_ascii_case("base64")+ && mime_type[..start].trim_end_matches(' ').ends_with(';')+ {+ // 1. Let stringBody be the isomorphic decode of body.+ // 2. Set body to the forgiving-base64 decode of stringBody.+ // 3. If body is failure, then return failure.+ body = forgiving_base64_decode(&body)?;++ // 4. Remove the last 6 code points from mimeType.+ // 5. Remove trailing U+0020 SPACE code points from mimeType, if any.+ // 6. Remove the last U+003B (;) from mimeType.+ let without_base64 = mime_type[..start].trim_end_matches(' ');+ mime_type = &without_base64[..without_base64.len() - 1];+ }++ // 12. If mimeType starts with ";", then prepend "text/plain" to mimeType.+ let mime_type: Vec<char> = if mime_type.starts_with(';') {+ "text/plain".chars().chain(mime_type.chars()).collect()+ } else {+ mime_type.chars().collect()+ };++ // 13. Let mimeTypeRecord be the result of parsing mimeType.+ // 14. If mimeTypeRecord is failure, then set mimeTypeRecord to text/plain;charset=US-ASCII.+ let mime_type_record = MimeType::parse(&mime_type).unwrap_or_else(|| {+ let mut mime_type_record = MimeType::new("text".to_owned(), "plain".to_owned());+ mime_type_record.set_parameter("charset".to_owned(), "US-ASCII".to_owned());+ mime_type_record+ });++ // 15. Return a new data: URL struct whose MIME type is mimeTypeRecord and body is body.+ Some(DataUrl {+ mime_type: mime_type_record,+ body,+ })+}++type OnBytes = unsafe extern "C" fn(ctx: *mut c_void, bytes: Span<'_, u8>);++/// Processes the serialization of a data: URL, without its fragment. Calls `on_body` with the body of the data: URL+/// struct and `on_mime_type` with its MIME type, and returns whether it succeeded.+///+/// # Safety+///+/// `input` must be ASCII, and `on_body` and `on_mime_type` must be safe to call with `ctx`.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn fetch_process_data_url(+ input: Span<'_, u8>,+ ctx: *mut c_void,+ on_body: OnBytes,+ on_mime_type: OnMimeType,+) -> bool {+ abort_on_panic(|| {+ let input = core::str::from_utf8(input.as_slice()).expect("C++ passes a URL serialization");+ let Some(data_url) = process_data_url(input) else {+ return false;+ };+ // SAFETY: The caller passes callbacks for `ctx`.+ unsafe {+ on_body(ctx, Span::new(&data_url.body));+ lend_mime_type(&data_url.mime_type, ctx, on_mime_type);+ }+ true+ })+}diff --git a/Libraries/LibWebCommon/Rust/src/fetch/mod.rs b/Libraries/LibWebCommon/Rust/src/fetch/mod.rsnew file mode 100644index 00000000000..3a0022f92f1--- /dev/null+++ b/Libraries/LibWebCommon/Rust/src/fetch/mod.rs@@ -0,0 +1,9 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The Fetch Standard, https://fetch.spec.whatwg.org/++pub mod data_url;diff --git a/Libraries/LibWebCommon/Rust/src/lib.rs b/Libraries/LibWebCommon/Rust/src/lib.rsindex 10e46de960b..c45e00c7f77 100644--- a/Libraries/LibWebCommon/Rust/src/lib.rs+++ b/Libraries/LibWebCommon/Rust/src/lib.rs@@ -13,4 +13,5 @@ mod rust_demangle;#[path = "../../../RustPanic.rs"]mod rust_panic;+pub mod fetch;pub mod mime_sniff;diff --git a/Libraries/LibWebCommon/Rust/src/mime_sniff/ffi.rs b/Libraries/LibWebCommon/Rust/src/mime_sniff/ffi.rsindex 960819f80a2..c2034757dc8 100644--- a/Libraries/LibWebCommon/Rust/src/mime_sniff/ffi.rs+++ b/Libraries/LibWebCommon/Rust/src/mime_sniff/ffi.rs@@ -65,7 +65,7 @@ pub struct FfiMimeType<'a> {pub parameters: Span<'a, FfiMimeTypeParameter<'a>>,}-type OnMimeType = unsafe extern "C" fn(ctx: *mut c_void, mime_type: *const FfiMimeType<'_>);+pub(crate) type OnMimeType = unsafe extern "C" fn(ctx: *mut c_void, mime_type: *const FfiMimeType<'_>);type OnString = unsafe extern "C" fn(ctx: *mut c_void, string: Span<'_, u8>);#[repr(u8)]@@ -109,7 +109,7 @@ impl FfiMimeType<'_> {/// # Safety////// `on_mime_type` must be safe to call with `ctx`.-unsafe fn lend_mime_type(mime_type: &MimeType, ctx: *mut c_void, on_mime_type: OnMimeType) {+pub(crate) unsafe fn lend_mime_type(mime_type: &MimeType, ctx: *mut c_void, on_mime_type: OnMimeType) {let parameters: Vec<_> = mime_type.parameters().map(|(name, value)| FfiMimeTypeParameter {diff --git a/Tests/LibWeb/TestFetchURL.cpp b/Tests/LibWeb/TestFetchURL.cppindex 4600c8c5110..614e355c2c7 100644--- a/Tests/LibWeb/TestFetchURL.cpp+++ b/Tests/LibWeb/TestFetchURL.cpp@@ -8,7 +8,7 @@#include <LibURL/Parser.h>#include <LibURL/URL.h>-#include <LibWeb/Fetch/Infrastructure/URL.h>+#include <LibWebCommon/Fetch/Infrastructure/DataURL.h>TEST_CASE(data_url){