Truly independent web browser
LibURL+LibWeb: Parse and serialize urlencoded forms in Rust
Shannon Boothc9bc05d6980c
diff --git a/Libraries/LibURL/Rust/src/ffi.rs b/Libraries/LibURL/Rust/src/ffi.rsindex 6f41782d45b..92b07b50f72 100644--- a/Libraries/LibURL/Rust/src/ffi.rs+++ b/Libraries/LibURL/Rust/src/ffi.rs@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+pub mod form_urlencoded;pub mod origin;pub mod pattern;pub mod url;diff --git a/Libraries/LibURL/Rust/src/ffi/form_urlencoded.rs b/Libraries/LibURL/Rust/src/ffi/form_urlencoded.rsnew file mode 100644index 00000000000..87a0b1769d9--- /dev/null+++ b/Libraries/LibURL/Rust/src/ffi/form_urlencoded.rs@@ -0,0 +1,84 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use std::ffi::c_void;++use encoding_rs::{Encoding, UTF_8};++use crate::ffi::url::{RustUrlByteSlice, RustUrlInput};+use crate::rust_panic::abort_on_panic;+use crate::url::form_urlencoded;++/// A name-value tuple borrowed across the FFI boundary.+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiFormTuple {+ pub name: RustUrlInput,+ pub value: RustUrlInput,+}++pub type FfiFormTupleFn = unsafe extern "C" fn(*mut c_void, RustUrlByteSlice, RustUrlByteSlice);+pub type FfiStringResultFn = unsafe extern "C" fn(*mut c_void, RustUrlByteSlice);++/// # Safety+/// `input` must borrow its bytes for the duration of this call. `on_tuple` is called once per name-value tuple, in+/// order, with UTF-8 strings that it borrows for the duration of that call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_url_form_urlencoded_parse(+ input: RustUrlByteSlice,+ ctx: *mut c_void,+ on_tuple: FfiFormTupleFn,+) {+ abort_on_panic(|| {+ let input = if input.data.is_null() {+ &[][..]+ } else {+ unsafe { ak::slice_from_raw_parts(input.data, input.length) }+ };+ for (name, value) in form_urlencoded::parse(input) {+ // SAFETY: on_tuple is a valid function pointer; ctx is caller-provided.+ unsafe {+ on_tuple(+ ctx,+ RustUrlByteSlice::from_str(&name),+ RustUrlByteSlice::from_str(&value),+ )+ };+ }+ })+}++/// # Safety+/// `tuples` must point to `tuple_count` tuples whose strings, and `encoding_label`, are borrowed for the duration of+/// this call. `on_complete` is called exactly once, with the ASCII serialization, which it borrows for the duration of+/// that call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_url_form_urlencoded_serialize(+ tuples: *const FfiFormTuple,+ tuple_count: usize,+ encoding_label: RustUrlByteSlice,+ ctx: *mut c_void,+ on_complete: FfiStringResultFn,+) {+ abort_on_panic(|| {+ let tuples = if tuples.is_null() {+ &[][..]+ } else {+ unsafe { ak::slice_from_raw_parts(tuples, tuple_count) }+ };+ let encoding = unsafe { encoding_label.borrow() }+ .and_then(|label| Encoding::for_label(label.as_bytes()))+ .unwrap_or(UTF_8);+ let serialization = form_urlencoded::serialize(+ tuples+ .iter()+ .map(|tuple| unsafe { (tuple.name.borrow(), tuple.value.borrow()) }),+ encoding,+ );+ // SAFETY: on_complete is a valid function pointer; ctx is caller-provided.+ unsafe { on_complete(ctx, RustUrlByteSlice::from_str(&serialization)) };+ })+}diff --git a/Libraries/LibURL/Rust/src/ffi/url.rs b/Libraries/LibURL/Rust/src/ffi/url.rsindex 31a429955f4..b7658844736 100644--- a/Libraries/LibURL/Rust/src/ffi/url.rs+++ b/Libraries/LibURL/Rust/src/ffi/url.rs@@ -57,7 +57,7 @@ impl RustUrlByteSlice {/// # Safety/// A non-null data pointer must borrow length bytes of valid UTF-8.- unsafe fn borrow<'a>(self) -> Option<&'a str> {+ pub(crate) unsafe fn borrow<'a>(self) -> Option<&'a str> {if self.data.is_null() {return None;}diff --git a/Libraries/LibURL/Rust/src/url/form_urlencoded.rs b/Libraries/LibURL/Rust/src/url/form_urlencoded.rsnew file mode 100644index 00000000000..7cd598143a4--- /dev/null+++ b/Libraries/LibURL/Rust/src/url/form_urlencoded.rs@@ -0,0 +1,103 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use encoding_rs::Encoding;++use super::UrlInput;+use super::percent_encoding::{PercentEncodeSet, percent_decode_bytes, percent_encode_after_encoding_into};+use crate::textcodec::get_output_encoding;++// https://url.spec.whatwg.org/#concept-urlencoded-parser+// The application/x-www-form-urlencoded parser takes a byte sequence input, and then runs these steps:+pub fn parse(input: &[u8]) -> Vec<(String, String)> {+ // 1. Let sequences be the result of splitting input on 0x26 (&).+ let sequences = input.split(|byte| *byte == b'&');++ // 2. Let output be an initially empty list of name-value tuples where both name and value hold a string.+ let mut output = Vec::new();++ // 3. For each byte sequence bytes in sequences:+ for bytes in sequences {+ // 1. If bytes is the empty byte sequence, then continue.+ if bytes.is_empty() {+ continue;+ }++ let (name, value) = match bytes.iter().position(|byte| *byte == b'=') {+ // 2. If bytes contains a 0x3D (=), then let name be the bytes from the start of bytes up to but excluding its first 0x3D (=), and let value be the bytes, if any, after the first 0x3D (=) up to the end of bytes. If 0x3D (=) is the first byte, then name will be the empty byte sequence. If it is the last, then value will be the empty byte sequence.+ Some(index) => (&bytes[..index], &bytes[index + 1..]),+ // 3. Otherwise, let name have the value of bytes and let value be the empty byte sequence.+ None => (bytes, &[][..]),+ };++ // 4. Replace any 0x2B (+) in name and value with 0x20 (SP).+ // 5. Let nameString and valueString be the result of running UTF-8 decode without BOM on the percent-decoding of name and value, respectively.+ let decode = |bytes: &[u8]| {+ let space_decoded: Vec<u8> = bytes+ .iter()+ .map(|byte| if *byte == b'+' { b' ' } else { *byte })+ .collect();+ String::from_utf8_lossy(&percent_decode_bytes(&space_decoded)).into_owned()+ };++ // 6. Append (nameString, valueString) to output.+ output.push((decode(name), decode(value)));+ }++ // 4. Return output.+ output+}++// https://url.spec.whatwg.org/#concept-urlencoded-serializer+// The application/x-www-form-urlencoded serializer takes a list of name-value tuples tuples, with an optional encoding encoding (default UTF-8), and then runs these steps. They return an ASCII string.+pub fn serialize<'a>(+ tuples: impl IntoIterator<Item = (UrlInput<'a>, UrlInput<'a>)>,+ encoding: &'static Encoding,+) -> String {+ // 1. Set encoding to the result of getting an output encoding from encoding.+ let encoding = get_output_encoding(encoding);++ // 2. Let output be the empty string.+ let mut output = String::new();++ // 3. For each tuple of tuples:+ for (name, value) in tuples {+ // 1. Assert: tuple's name and tuple's value are scalar value strings.++ // 2. Let name be the result of running percent-encode after encoding with encoding, tuple's name, and the application/x-www-form-urlencoded percent-encode set.+ let mut encoded_name = String::new();+ percent_encode_after_encoding_into(+ encoding,+ name,+ PercentEncodeSet::ApplicationXWWWFormUrlencoded,+ true,+ &mut encoded_name,+ );++ // 3. Let value be the result of running percent-encode after encoding with encoding, tuple's value, and the application/x-www-form-urlencoded percent-encode set.+ let mut encoded_value = String::new();+ percent_encode_after_encoding_into(+ encoding,+ value,+ PercentEncodeSet::ApplicationXWWWFormUrlencoded,+ true,+ &mut encoded_value,+ );++ // 4. If output is not the empty string, then append U+0026 (&) to output.+ if !output.is_empty() {+ output.push('&');+ }++ // 5. Append name, followed by U+003D (=), followed by value, to output.+ output.push_str(&encoded_name);+ output.push('=');+ output.push_str(&encoded_value);+ }++ // 4. Return output.+ output+}diff --git a/Libraries/LibURL/Rust/src/url/mod.rs b/Libraries/LibURL/Rust/src/url/mod.rsindex ac6bc157518..4e984a1db21 100644--- a/Libraries/LibURL/Rust/src/url/mod.rs+++ b/Libraries/LibURL/Rust/src/url/mod.rs@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+pub mod form_urlencoded;mod host;mod input;mod parser;diff --git a/Libraries/LibURL/Rust/src/url/percent_encoding.rs b/Libraries/LibURL/Rust/src/url/percent_encoding.rsindex 6c9d5ca156a..dd0ea7ea4c9 100644--- a/Libraries/LibURL/Rust/src/url/percent_encoding.rs+++ b/Libraries/LibURL/Rust/src/url/percent_encoding.rs@@ -136,6 +136,45 @@ pub(super) fn percent_decode_input(input: super::UrlInput<'_>) -> Vec<u8> {output}+// https://url.spec.whatwg.org/#percent-decode+pub(super) fn percent_decode_bytes(input: &[u8]) -> Vec<u8> {+ // 1. Let output be an empty byte sequence.+ let mut output = Vec::with_capacity(input.len());++ // 2. For each byte byte in input:+ let mut index = 0;+ while index < input.len() {+ let byte = input[index];+ let hex_digits = input.get(index + 1..index + 3);++ // 1. If byte is not 0x25 (%), then append byte to output.+ // 2. Otherwise, if byte is 0x25 (%) and the next two bytes after byte in input are not in the ranges 0x30 (0)+ // to 0x39 (9), 0x41 (A) to 0x46 (F), and 0x61 (a) to 0x66 (f), all inclusive, append byte to output.+ let Some(&[high, low]) = hex_digits.filter(|_| byte == b'%') else {+ output.push(byte);+ index += 1;+ continue;+ };+ if !high.is_ascii_hexdigit() || !low.is_ascii_hexdigit() {+ output.push(byte);+ index += 1;+ continue;+ }++ // 3. Otherwise:+ // 1. Let bytePoint be the two bytes after byte in input, decoded, and then interpreted as a hexadecimal+ // number.+ // 2. Append a byte whose value is bytePoint to output.+ // 3. Skip the next two bytes in input.+ let hex_value = |digit: u8| (digit as char).to_digit(16).expect("the digit is a hex digit") as u8;+ output.push((hex_value(high) << 4) | hex_value(low));+ index += 3;+ }++ // 3. Return output.+ output+}+// https://url.spec.whatwg.org/#string-percent-encode-after-encodingpub(super) fn percent_encode_after_encoding_into(encoding: &'static Encoding,diff --git a/Libraries/LibWeb/DOMURL/URLSearchParams.cpp b/Libraries/LibWeb/DOMURL/URLSearchParams.cppindex 5272a47d254..5ac0b283ed1 100644--- a/Libraries/LibWeb/DOMURL/URLSearchParams.cpp+++ b/Libraries/LibWeb/DOMURL/URLSearchParams.cpp@@ -9,9 +9,9 @@#include <AK/StringBuilder.h>#include <AK/Utf8View.h>#include <LibGC/Heap.h>-#include <LibTextCodec/Decoder.h>-#include <LibTextCodec/Encoder.h>#include <LibURL/Parser.h>+#include <LibURL/RustFFI.h>+#include <LibURL/RustIntegration.h>#include <LibWeb/DOMURL/DOMURL.h>#include <LibWeb/DOMURL/URLSearchParams.h>@@ -33,83 +33,30 @@ void URLSearchParams::visit_edges(GC::Cell::Visitor& visitor)}// https://url.spec.whatwg.org/#concept-urlencoded-serializer-// The application/x-www-form-urlencoded serializer takes a list of name-value tuples tuples, with an optional encoding encoding (default UTF-8), and then runs these steps. They return an ASCII string.String url_encode(Vector<QueryParam> const& tuples, StringView encoding){- // 1. Set encoding to the result of getting an output encoding from encoding.- encoding = TextCodec::get_output_encoding(encoding);-- auto encoder = TextCodec::encoder_for(encoding);- VERIFY(encoder.has_value());-- // 2. Let output be the empty string.- StringBuilder output;-- // 3. For each tuple of tuples:- for (auto const& tuple : tuples) {- // 1. Assert: tuple’s name and tuple’s value are scalar value strings.-- // 2. Let name be the result of running percent-encode after encoding with encoding, tuple’s name, the application/x-www-form-urlencoded percent-encode set, and true.- auto name = URL::Parser::percent_encode_after_encoding(*encoder, tuple.name.to_utf8(), URL::PercentEncodeSet::ApplicationXWWWFormUrlencoded, true);-- // 3. Let value be the result of running percent-encode after encoding with encoding, tuple’s value, the application/x-www-form-urlencoded percent-encode set, and true.- auto value = URL::Parser::percent_encode_after_encoding(*encoder, tuple.value.to_utf8(), URL::PercentEncodeSet::ApplicationXWWWFormUrlencoded, true);-- // 4. If output is not the empty string, then append U+0026 (&) to output.- if (!output.is_empty())- output.append('&');-- // 5. Append name, followed by U+003D (=), followed by value, to output.- output.append(name);- output.append('=');- output.append(value);- }-- // 4. Return output.- return MUST(output.to_string());+ Vector<URL::FFI::FfiFormTuple> ffi_tuples;+ ffi_tuples.ensure_capacity(tuples.size());+ for (auto const& tuple : tuples)+ ffi_tuples.unchecked_append({ URL::RustIntegration::rust_url_input(tuple.name.utf16_view()), URL::RustIntegration::rust_url_input(tuple.value.utf16_view()) });++ String output;+ URL::FFI::rust_url_form_urlencoded_serialize(ffi_tuples.data(), ffi_tuples.size(), { reinterpret_cast<u8 const*>(encoding.characters_without_null_termination()), encoding.length() }, &output, [](void* ctx, URL::FFI::RustUrlByteSlice serialization) {+ *static_cast<String*>(ctx) = String::from_ascii_without_validation({ serialization.data, serialization.length });+ });+ return output;}// https://url.spec.whatwg.org/#concept-urlencoded-parser-// The application/x-www-form-urlencoded parser takes a byte sequence input, and then runs these steps:Vector<QueryParam> url_decode(StringView input){- // 1. Let sequences be the result of splitting input on 0x26 (&).- auto sequences = input.split_view('&');-- // 2. Let output be an initially empty list of name-value tuples where both name and value hold a string.Vector<QueryParam> output;-- // 3. For each byte sequence bytes in sequences:- for (auto bytes : sequences) {- // 1. If bytes is the empty byte sequence, then continue.- if (bytes.is_empty())- continue;-- StringView name;- StringView value;-- // 2. If bytes contains a 0x3D (=), then let name be the bytes from the start of bytes up to but excluding its first 0x3D (=), and let value be the bytes, if any, after the first 0x3D (=) up to the end of bytes. If 0x3D (=) is the first byte, then name will be the empty byte sequence. If it is the last, then value will be the empty byte sequence.- if (auto index = bytes.find('='); index.has_value()) {- name = bytes.substring_view(0, *index);- value = bytes.substring_view(*index + 1);- }- // 3. Otherwise, let name have the value of bytes and let value be the empty byte sequence.- else {- name = bytes;- value = ""sv;- }-- // 4. Replace any 0x2B (+) in name and value with 0x20 (SP).- auto space_decoded_name = name.replace("+"sv, " "sv, ReplaceMode::All);- auto space_decoded_value = value.replace("+"sv, " "sv, ReplaceMode::All);-- // 5. Let nameString and valueString be the result of running UTF-8 decode without BOM on the percent-decoding of name and value, respectively.- auto name_string = Utf16String::from_utf8_with_replacement_character(URL::percent_decode(space_decoded_name), Utf16String::WithBOMHandling::No);- auto value_string = Utf16String::from_utf8_with_replacement_character(URL::percent_decode(space_decoded_value), Utf16String::WithBOMHandling::No);-- output.empend(move(name_string), move(value_string));- }-+ URL::FFI::rust_url_form_urlencoded_parse({ reinterpret_cast<u8 const*>(input.characters_without_null_termination()), input.length() }, &output, [](void* ctx, URL::FFI::RustUrlByteSlice name, URL::FFI::RustUrlByteSlice value) {+ auto utf16_from_ffi = [](URL::FFI::RustUrlByteSlice string) {+ return Utf16String::from_utf8({ reinterpret_cast<char const*>(string.data), string.length });+ };+ static_cast<Vector<QueryParam>*>(ctx)->empend(utf16_from_ffi(name), utf16_from_ffi(value));+ });return output;}