Skip to content

Truly independent web browser

LibWebCommon+LibWeb: Implement MIME Sniffing in Rust

Shannon Boothdea5787ea6ff
diff --git a/Cargo.lock b/Cargo.lock
index cfc74a6f068..2839ba8e515 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -912,6 +912,16 @@ dependencies = [
"smallvec",
]
+[[package]]
+name = "libwebcommon_rust"
+version = "0.1.0"
+dependencies = [
+ "ak",
+ "cbindgen",
+ "ladybird_allocator",
+ "rustc-demangle",
+]
+
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
diff --git a/Cargo.toml b/Cargo.toml
index 6e24bac4fab..3bcf48bfccc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,6 +17,7 @@ members = [
"Libraries/LibWasm/Engine",
"Libraries/LibWasm/JIT",
"Libraries/LibWasm/Module",
+ "Libraries/LibWebCommon/Rust",
"Libraries/LibWeb/Bindings/Rust",
"Libraries/LibWeb/ContentBlocker/Rust",
"Libraries/LibWeb/Rust",
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index a12e4280b08..00e05efd300 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -768,7 +768,6 @@ set(SOURCES
MediaSourceExtensions/MediaSourceHandle.cpp
MediaSourceExtensions/SourceBuffer.cpp
MediaSourceExtensions/SourceBufferList.cpp
- MimeSniff/Resource.cpp
MixedContent/AbstractOperations.cpp
Namespace.cpp
NavigationTiming/EntryNames.cpp
diff --git a/Libraries/LibWeb/CSS/FontComputer.cpp b/Libraries/LibWeb/CSS/FontComputer.cpp
index 2d9e88cadfe..a83df9a11f0 100644
--- a/Libraries/LibWeb/CSS/FontComputer.cpp
+++ b/Libraries/LibWeb/CSS/FontComputer.cpp
@@ -30,10 +30,10 @@
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WorkerGlobalScope.h>
#include <LibWeb/Layout/RenderDocument.h>
-#include <LibWeb/MimeSniff/Resource.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Page/RenderingStats.h>
#include <LibWeb/Platform/FontPlugin.h>
+#include <LibWebCommon/MimeSniff/Resource.h>
namespace Web::CSS {
diff --git a/Libraries/LibWeb/DOM/DocumentLoading.cpp b/Libraries/LibWeb/DOM/DocumentLoading.cpp
index 327edc31689..6c7b2830460 100644
--- a/Libraries/LibWeb/DOM/DocumentLoading.cpp
+++ b/Libraries/LibWeb/DOM/DocumentLoading.cpp
@@ -38,11 +38,11 @@
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Loader/GeneratedPagesLoader.h>
-#include <LibWeb/MimeSniff/Resource.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/XML/XMLDocumentBuilder.h>
+#include <LibWebCommon/MimeSniff/Resource.h>
#include <LibXML/Parser/Parser.h>
namespace Web {
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.cpp b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
index 1d019a17ea7..72d424b50b4 100644
--- a/Libraries/LibWeb/HTML/HTMLInputElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
@@ -55,7 +55,6 @@
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Layout/Box.h>
-#include <LibWeb/MimeSniff/Resource.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Painting/BoxViews.h>
@@ -69,6 +68,7 @@
#include <LibWebCommon/HTML/SelectedFile.h>
#include <LibWebCommon/Infra/CharacterTypes.h>
#include <LibWebCommon/MimeSniff/MimeType.h>
+#include <LibWebCommon/MimeSniff/Resource.h>
namespace {
diff --git a/Libraries/LibWeb/HTML/HTMLObjectElement.cpp b/Libraries/LibWeb/HTML/HTMLObjectElement.cpp
index 1e9cc2029ea..cfff45b891b 100644
--- a/Libraries/LibWeb/HTML/HTMLObjectElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLObjectElement.cpp
@@ -37,8 +37,8 @@
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Layout/Box.h>
#include <LibWeb/Loader/ResourceLoader.h>
-#include <LibWeb/MimeSniff/Resource.h>
#include <LibWebCommon/MimeSniff/MimeType.h>
+#include <LibWebCommon/MimeSniff/Resource.h>
namespace Web::HTML {
diff --git a/Libraries/LibWeb/MimeSniff/Resource.cpp b/Libraries/LibWeb/MimeSniff/Resource.cpp
deleted file mode 100644
index df69b79d376..00000000000
--- a/Libraries/LibWeb/MimeSniff/Resource.cpp
+++ /dev/null
@@ -1,987 +0,0 @@
-/*
- * Copyright (c) 2023-2024, Kemal Zebari <[email protected]>.
- * Copyright (c) 2025, Ben Eidson <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/Fetch/Infrastructure/URL.h>
-#include <LibWeb/MimeSniff/Resource.h>
-
-namespace {
-
-using namespace Web::MimeSniff;
-
-struct BytePatternTableRow {
- StringView byte_pattern;
- StringView pattern_mask;
- ReadonlyBytes ignored_leading_bytes;
- StringView mime_type;
-
- // NOTE: If the byte pattern has a tag-terminating byte, add a byte where this byte should be. The value itself is ignored in
- // the pattern_matching_algorithm() (see the NOTE in this algorithm for more details).
- bool is_tag_terminated { false };
-};
-
-// https://mimesniff.spec.whatwg.org/#tag-terminating-byte
-bool is_tag_terminating_byte(u8 byte)
-{
- // A tag-terminating byte (abbreviated 0xTT) is any one of the following bytes: 0x20 (SP), 0x3E (">").
- return byte == 0x20 || byte == 0x3E;
-}
-
-// https://mimesniff.spec.whatwg.org/#binary-data-byte
-bool is_binary_data_byte(u8 byte)
-{
- // A binary data byte is a byte in the range 0x00 to 0x08 (NUL to BS), the byte 0x0B (VT), a byte in
- // the range 0x0E to 0x1A (SO to SUB), or a byte in the range 0x1C to 0x1F (FS to US).
- return (byte <= 0x08) || byte == 0x0B || (byte >= 0x0E && byte <= 0x1A) || (byte >= 0x1C && byte <= 0x1F);
-}
-
-// https://mimesniff.spec.whatwg.org/#pattern-matching-algorithm
-bool pattern_matching_algorithm(ReadonlyBytes input, ReadonlyBytes pattern, ReadonlyBytes mask, ReadonlyBytes ignored, bool is_tag_terminated = false)
-{
- // 1. Assert: pattern’s length is equal to mask’s length.
- VERIFY(pattern.size() == mask.size());
-
- // 2. If input’s length is less than pattern’s length, return false.
- if (input.size() < pattern.size())
- return false;
-
- // 3. Let s be 0.
- size_t s = 0;
-
- // 4. While s < input’s length:
- while (s < input.size()) {
- // 1. If ignored does not contain input[s], break.
- if (!ignored.contains_slow(input[s]))
- break;
-
- // 2. Set s to s + 1.
- s++;
- }
-
- // 5. Let p be 0.
- size_t p = 0;
-
- // 6. While p < pattern’s length:
- while (p < pattern.size()) {
- // 1. Let maskedData be the result of applying the bitwise AND operator to input[s] and mask[p].
- u8 masked_data = input[s] & mask[p];
-
- // NOTE: This non-standard branch exists to avoid having to create 2 byte patterns just so that
- // they can only differ by their tag-terminating byte (which could be a 0x20 or 0x3E byte).
- if (is_tag_terminated && p + 1 == pattern.size())
- return is_tag_terminating_byte(masked_data);
-
- // 2. If maskedData is not equal to pattern[p], return false.
- if (masked_data != pattern[p])
- return false;
-
- // 3. Set s to s + 1.
- s++;
-
- // 4. Set p to p + 1.
- p++;
- }
-
- // 7. Return true.
- return true;
-}
-
-ReadonlyBytes constexpr no_ignored_bytes;
-
-// https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern
-Optional<MimeType> match_an_image_type_pattern(ReadonlyBytes input)
-{
- // 1. Execute the following steps for each row row in the following table:
- static Array<BytePatternTableRow, 8> constexpr pattern_table {
- // A Windows Icon signature.
- BytePatternTableRow { "\x00\x00\x01\x00"sv, "\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "image/x-icon"sv },
-
- // A Windows Cursor signature.
- BytePatternTableRow { "\x00\x00\x02\x00"sv, "\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "image/x-icon"sv },
-
- // The string "BM", a BMP signature.
- BytePatternTableRow { "\x42\x4D"sv, "\xFF\xFF"sv, no_ignored_bytes, "image/bmp"sv },
-
- // The string "GIF87a", a GIF signature.
- BytePatternTableRow { "\x47\x49\x46\x38\x37\x61"sv, "\xFF\xFF\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "image/gif"sv },
-
- // The string "GIF89a", a GIF signature.
- BytePatternTableRow { "\x47\x49\x46\x38\x39\x61"sv, "\xFF\xFF\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "image/gif"sv },
-
- // The string "RIFF" followed by four bytes followed by the string "WEBPVP".
- BytePatternTableRow { "\x52\x49\x46\x46\x00\x00\x00\x00\x57\x45\x42\x50\x56\x50"sv,
- "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "image/webp"sv },
-
- // An error-checking byte followed by the string "PNG" followed by CR LF SUB LF, the PNG signature.
- BytePatternTableRow { "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"sv, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "image/png"sv },
-
- // The JPEG Start of Image marker followed by the indicator byte of another marker.
- BytePatternTableRow { "\xFF\xD8\xFF"sv, "\xFF\xFF\xFF"sv, no_ignored_bytes, "image/jpeg"sv },
- };
-
- for (auto const& row : pattern_table) {
- // 1. Let patternMatched be the result of the pattern matching algorithm given input, the value in
- // the first column of row, the value in the second column of row, and the value in the third
- // column of row.
- auto pattern_matched = pattern_matching_algorithm(input, row.byte_pattern.bytes(), row.pattern_mask.bytes(), row.ignored_leading_bytes);
-
- // 2. If patternMatched is true, return the value in the fourth column of row.
- if (pattern_matched)
- return MimeType::parse(row.mime_type);
- }
-
- // 2. Return undefined.
- return OptionalNone {};
-}
-
-// https://mimesniff.spec.whatwg.org/#signature-for-mp4
-bool matches_mp4_signature(ReadonlyBytes sequence)
-{
- // 1. Let sequence be the byte sequence to be matched, where sequence[s] is byte s in sequence and sequence[0] is the first byte in sequence.
-
- // 2. Let length be the number of bytes in sequence.
- auto length = sequence.size();
-
- // 3. If length is less than 12, return false.
- if (length < 12)
- return false;
-
- // 4. Let box-size be the four bytes from sequence[0] to sequence[3], interpreted as a 32-bit unsigned big-endian integer.
- u32 box_size = 0;
- box_size |= static_cast<u32>(sequence[0] << 24);
- box_size |= static_cast<u32>(sequence[1] << 16);
- box_size |= static_cast<u32>(sequence[2] << 8);
- box_size |= sequence[3];
-
- // 5. If length is less than box-size or if box-size modulo 4 is not equal to 0, return false.
- if ((length < box_size) || (box_size % 4 != 0))
- return false;
-
- // 6. If the four bytes from sequence[4] to sequence[7] are not equal to 0x66 0x74 0x79 0x70 ("ftyp"), return false.
- if (sequence.slice(4, 4) != "\x66\x74\x79\x70"sv.bytes())
- return false;
-
- // 7. If the three bytes from sequence[8] to sequence[10] are equal to 0x6D 0x70 0x34 ("mp4"), return true.
- if (sequence.slice(8, 3) == "\x6D\x70\x34"sv.bytes())
- return true;
-
- // 8. Let bytes-read be 16.
- u32 bytes_read = 16;
-
- // 9. While bytes-read is less than box-size, continuously loop through these steps:
- // 1. If the three bytes from sequence[bytes-read] to sequence[bytes-read + 2] are equal to 0x6D 0x70 0x34 ("mp4"), return true.
- // 2. Increment bytes-read by 4.
- while (bytes_read < box_size) {
- if (sequence.slice(bytes_read, 3) == "\x6D\x70\x34"sv.bytes())
- return true;
- bytes_read += 4;
- }
-
- // 10. Return false.
- return false;
-}
-
-struct VintResult {
- u64 value;
- size_t length;
-};
-
-// https://mimesniff.spec.whatwg.org/#parse-a-vint
-VintResult parse_a_vint(ReadonlyBytes sequence, size_t iter)
-{
- // To parse a vint on a byte sequence sequence of size length, starting at index iter use the following steps:
- sequence = sequence.slice(iter);
- auto length = sequence.size();
-
- // 1. let mask be 128.
- u8 mask = 128;
-
- // 2. Let max vint length be 8.
- size_t const max_vint_length = 8;
-
- // 3. Let number size be 1.
- size_t number_size = 1;
-
- // 5. Let index be 0.
- // NOTE: spec declares this after step four, but it is needed before to use in the loop.
- size_t index = 0;
-
- // 4. While number size is less than max vint length, and less than length, continuously loop through these steps:
- while (number_size < max_vint_length && number_size < length) {
- // 1. If the sequence[index] & mask is not zero, abort these steps.
- if (sequence[index] & mask)
- break;
-
- // 2. Let mask be the value of mask >> 1.
- mask >>= 1;
-
- // 3. Increment number size by one.
- number_size++;
- }
-
- // 6. Let parsed number be sequence[index] & ~mask.
- u64 parsed_number = sequence[index] & ~mask;
-
- // 7. Increment index by one.
- index++;
-
- // 8. Let bytes remaining be the value of number size - 1.
- auto bytes_remaining = number_size - 1;
-
- // 9. While bytes remaining is not zero, execute there steps:
- while (bytes_remaining != 0) {
- // 1. Let parsed number be parsed number << 8.
- parsed_number <<= 8;
-
- // 2. Let parsed number be parsed number | sequence[index].
- parsed_number |= sequence[index];
-
- // 3. Increment index by one.
- index++;
-
- // 4. If index is greater or equal than length, abort these steps.
- if (index >= length)
- break;
-
- // 5. Decrement bytes remaining by one.
- bytes_remaining--;
- }
-
- // 10. Return parsed number and number size
- return { parsed_number, number_size };
-}
-
-// https://mimesniff.spec.whatwg.org/#signature-for-webm
-bool matches_webm_signature(ReadonlyBytes sequence)
-{
- // 1. Let sequence be the byte sequence to be matched, where sequence[s] is byte s in sequence and sequence[0] is the first byte in sequence.
-
- // 2. Let length be the number of bytes in sequence.
- auto length = sequence.size();
-
- // 3. If length is less than 4, return false.
- if (length < 4)
- return false;
-
- // 4. If the four bytes from sequence[0] to sequence[3], are not equal to 0x1A 0x45 0xDF 0xA3, return false.
- static auto constexpr webm_signature = "\x1A\x45\xDF\xA3"sv;
- if (!sequence.starts_with(webm_signature.bytes()))
- return false;
-
- // 5. let iter be 4.
- size_t iter = 4;
-
- // 6. While iter is less than length and iter is less than 38, continuously loop through these steps:
- while (iter < length && iter < 38) {
- // before slicing 2 bytes, ensure there are at least 2 bytes
- if (iter + 1 >= length)
- break;
-
- // 1. If the two bytes from sequence[iter] to sequence[iter + 1] are equal to 0x42 0x82,
- if (sequence.slice(iter, 2) == "\x42\x82"sv.bytes()) {
- // 1. increment iter by 2.
- iter += 2;
-
- // 2. If iter is greater or equal than length, abort these steps.
- if (iter >= length)
- break;
-
- // 3. Let number size be the result of parsing a vint starting at sequence[iter].
-
- auto const number_size = parse_a_vint(sequence, iter).length;
-
- // 4. Increment iter by number size.
- iter += number_size;
-
- // 5. If iter is greater than or equal to length - 4, abort these steps.
- if (iter >= length - 4)
- break;
-
- // 6. Let matched be the result of matching a padded sequence 0x77 0x65 0x62 0x6D ("webm") on sequence at offset iter.
- bool matched = sequence.slice(iter, 4) == "\x77\x65\x62\x6D"sv.bytes();
-
- // 7. If matched is true, abort these steps and return true.
- if (matched)
- return true;
- }
-
- // 2. Increment iter by 1.
- iter += 1;
- }
-
- // 7. Return false.
- return false;
-}
-
-// https://mimesniff.spec.whatwg.org/#match-an-mp3-header
-bool match_mp3_header(ReadonlyBytes sequence, size_t s)
-{
- // To match an mp3 header, using a byte sequence sequence of length length at offset s execute these steps:
- size_t length = sequence.size();
-
- // 1. If length is less than 4, return false.
- if (length - s < 4)
- return false;
-
- // 2. If sequence[s] is not equal to 0xff and sequence[s + 1] & 0xe0 is not equal to 0xe0, return false.
- // NOTE: spec is wrong here, should be or.
- if (sequence[s] != 0xff || (sequence[s + 1] & 0xe0) != 0xe0)
- return false;
-
- // 3. Let layer be the result of sequence[s + 1] & 0x06 >> 1.
- u8 layer = (sequence[s + 1] & 0x06) >> 1;
-
- // 4. If layer is 0, return false.
- if (layer == 0)
- return false;
-
- // 5. Let bit-rate be sequence[s + 2] & 0xf0 >> 4.
- u8 bit_rate = (sequence[s + 2] & 0xf0) >> 4;
-
- // 6. If bit-rate is 15, return false.
- if (bit_rate == 15)
- return false;
-
- // 7. Let sample-rate be sequence[s + 2] & 0x0c >> 2.
- u8 sample_rate = (sequence[s + 2] & 0x0c) >> 2;
-
- // 8. If sample-rate is 3, return false.
- if (sample_rate == 3)
- return false;
-
- // FIXME: 9. Let freq be the value given by sample-rate in the table sample-rate.
-
- // FIXME: 10. Let final-layer be the result of 4 - (sequence[s + 1]).
-
- // FIXME: 11. If final-layer & 0x06 >> 1 is not 3, return false.
-
- // 12. Return true.
- return true;
-}
-
-// https://mimesniff.spec.whatwg.org/#matches-the-signature-for-mp3-without-id3
-// FIXME: Instead of implementing full spec, only matches single-frame mp3 header due to the issues stated at (https://github.com/whatwg/mimesniff/issues/70)
-bool matches_mp3_no_id3_signature(ReadonlyBytes sequence)
-{
- // 1. Let sequence be the byte sequence to be matched, where sequence[s] is byte s in sequence and sequence[0] is the first byte in sequence.
-
- // FIXME: 2. Let length be the number of bytes in sequence.
-
- // FIXME: 3. Initialize s to 0.
-
- // 4. If the result of the operation match mp3 header is false, return false.
- bool result = match_mp3_header(sequence, 0);
- if (!result)
- return false;
-
- // FIXME: 5. Parse an mp3 frame on sequence at offset s
-
- // FIXME: 6. Let skipped-bytes the return value of the execution of mp3 framesize computation
-
- // FIXME: 7. If skipped-bytes is less than 4, or skipped-bytes is greater than s - length, return false.
-
- // FIXME: 8. Increment s by skipped-bytes.
-
- // FIXME: 9. If the result of the operation match mp3 header operation is false, return false, else, return true.
- return true;
-}
-
-// https://mimesniff.spec.whatwg.org/#matching-an-audio-or-video-type-pattern
-Optional<MimeType> match_an_audio_or_video_type_pattern(ReadonlyBytes input)
-{
- // 1. Execute the following steps for each row row in the following table:
- static Array<BytePatternTableRow, 6> constexpr pattern_table {
- // The string "FORM" followed by four bytes followed by the string "AIFF", the AIFF signature.
- BytePatternTableRow { "\x46\x4F\x52\x4D\x00\x00\x00\x00\x41\x49\x46\x46"sv,
- "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "audio/aiff"sv },
-
- // The string "ID3", the ID3v2-tagged MP3 signature.
- BytePatternTableRow { "\x49\x44\x33"sv, "\xFF\xFF\xFF"sv, no_ignored_bytes, "audio/mpeg"sv },
-
- // The string "OggS" followed by NUL, the Ogg container signature.
- BytePatternTableRow { "\x4F\x67\x67\x53\x00"sv, "\xFF\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "application/ogg"sv },
-
- // The string "MThd" followed by four bytes representing the number 6 in 32 bits (big-endian), the MIDI signature.
- BytePatternTableRow { "\x4D\x54\x68\x64\x00\x00\x00\x06"sv, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "audio/midi"sv },
-
- // The string "RIFF" followed by four bytes followed by the string "AVI ", the AVI signature.
- BytePatternTableRow { "\x52\x49\x46\x46\x00\x00\x00\x00\x41\x56\x49\x20"sv,
- "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "video/avi"sv },
-
- // The string "RIFF" followed by four bytes followed by the string "WAVE", the WAVE signature.
- BytePatternTableRow { "\x52\x49\x46\x46\x00\x00\x00\x00\x57\x41\x56\x45"sv,
- "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "audio/wave"sv }
- };
-
- for (auto const& row : pattern_table) {
- // 1. Let patternMatched be the result of the pattern matching algorithm given input, the
- // value in the first column of row, the value in the second column of row, and the
- // value in the third column of row.
- auto pattern_matched = pattern_matching_algorithm(input, row.byte_pattern.bytes(), row.pattern_mask.bytes(), row.ignored_leading_bytes);
-
- // 2. If patternMatched is true, return the value in the fourth column of row.
- if (pattern_matched)
- return MimeType::parse(row.mime_type);
- }
-
- // 2. If input matches the signature for MP4, return "video/mp4".
- if (matches_mp4_signature(input))
- return MimeType::create("video"_string, "mp4"_string);
-
- // 3. If input matches the signature for WebM, return "video/webm".
- if (matches_webm_signature(input))
- return MimeType::create("video"_string, "webm"_string);
-
- // 4. If input matches the signature for MP3 without ID3, return "audio/mpeg".
- if (matches_mp3_no_id3_signature(input))
- return MimeType::create("audio"_string, "mpeg"_string);
-
- // 5. Return undefined.
- return OptionalNone {};
-}
-
-// https://mimesniff.spec.whatwg.org/#matching-a-font-type-pattern
-Optional<MimeType> match_a_font_type_pattern(ReadonlyBytes input)
-{
- // 1. Execute the following steps for each row row in the following table:
- static Array<BytePatternTableRow, 6> constexpr pattern_table {
- // 34 bytes followed by the string "LP", the Embedded OpenType signature.
- BytePatternTableRow {
- .byte_pattern = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x4C\x50"sv,
- .pattern_mask = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF"sv,
- .ignored_leading_bytes = no_ignored_bytes,
- .mime_type = "application/vnd.ms-fontobject"sv,
- },
-
- // 4 bytes representing the version number 1.0, a TrueType signature.
- BytePatternTableRow { "\x00\x01\x00\x00"sv, "\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "font/ttf"sv },
-
- // The string "OTTO", the OpenType signature.
- BytePatternTableRow { "\x4F\x54\x54\x4F"sv, "\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "font/otf"sv },
-
- // The string "ttcf", the TrueType Collection signature.
- BytePatternTableRow { "\x74\x74\x63\x66"sv, "\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "font/collection"sv },
-
- // The string "wOFF", the Web Open Font Format 1.0 signature.
- BytePatternTableRow { "\x77\x4F\x46\x46"sv, "\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "font/woff"sv },
-
- // The string "wOF2", the Web Open Font Format 2.0 signature.
- BytePatternTableRow { "\x77\x4F\x46\x32"sv, "\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "font/woff2"sv },
- };
-
- for (auto const& row : pattern_table) {
- // 1. Let patternMatched be the result of the pattern matching algorithm given input, the
- // value in the first column of row, the value in the second column of row, and the
- // value in the third column of row.
- auto pattern_matched = pattern_matching_algorithm(input, row.byte_pattern.bytes(), row.pattern_mask.bytes(), row.ignored_leading_bytes);
-
- // 2. If patternMatched is true, return the value in the fourth column of row.
- if (pattern_matched)
- return MimeType::parse(row.mime_type);
- }
-
- // 2. Return undefined.
- return OptionalNone {};
-}
-
-// https://mimesniff.spec.whatwg.org/#matching-an-archive-type-pattern
-Optional<MimeType> match_an_archive_type_pattern(ReadonlyBytes input)
-{
- // 1. Execute the following steps for each row row in the following table:
- static Array<BytePatternTableRow, 3> constexpr pattern_table {
- // The GZIP archive signature.
- BytePatternTableRow { "\x1F\x8B\x08"sv, "\xFF\xFF\xFF"sv, no_ignored_bytes, "application/x-gzip"sv },
-
- // The string "PK" followed by ETX EOT, the ZIP archive signature.
- BytePatternTableRow { "\x50\x4B\x03\x04"sv, "\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "application/zip"sv },
-
- // The string "Rar!" followed by SUB BEL NUL, the RAR 4.x archive signature.
- BytePatternTableRow { "\x52\x61\x72\x21\x1A\x07\x00"sv, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "application/x-rar-compressed"sv },
- };
-
- for (auto const& row : pattern_table) {
- // 1. Let patternMatched be the result of the pattern matching algorithm given input, the
- // value in the first column of row, the value in the second column of row, and the
- // value in the third column of row.
- auto pattern_matched = pattern_matching_algorithm(input, row.byte_pattern.bytes(), row.pattern_mask.bytes(), row.ignored_leading_bytes);
-
- // 2. If patternMatched is true, return the value in the fourth column of row.
- if (pattern_matched)
- return MimeType::parse(row.mime_type);
- }
-
- // 2. Return undefined.
- return OptionalNone {};
-}
-
-// https://mimesniff.spec.whatwg.org/#rules-for-identifying-an-unknown-mime-type
-MimeType rules_for_identifying_an_unknown_mime_type(Resource const& resource, bool sniff_scriptable = false)
-{
- // 1. If the sniff-scriptable flag is set, execute the following steps for each row row in the following table:
- if (sniff_scriptable) {
- static auto constexpr text_html_mime_type = "text/html"sv;
-
- // https://mimesniff.spec.whatwg.org/#whitespace-byte
- // A whitespace byte (abbreviated 0xWS) is any one of the following bytes: 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP).
- static Array<u8, 5> constexpr ignored_whitespace_bytes { 0x09, 0x0A, 0x0C, 0x0D, 0x20 };
- static Array<BytePatternTableRow, 19> constexpr pattern_table {
- // The case-insensitive string "<!DOCTYPE HTML" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x21\x44\x4F\x43\x54\x59\x50\x45\x20\x48\x54\x4D\x4C\x00"sv,
- "\xFF\xFF\xDF\xDF\xDF\xDF\xDF\xDF\xDF\xFF\xDF\xDF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<HTML" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x48\x54\x4D\x4C\x00"sv, "\xFF\xDF\xDF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<HEAD" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x48\x45\x41\x44\x00"sv, "\xFF\xDF\xDF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<SCRIPT" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x53\x43\x52\x49\x50\x54\x00"sv,
- "\xFF\xDF\xDF\xDF\xDF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<IFRAME" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x49\x46\x52\x41\x4D\x45\x00"sv,
- "\xFF\xDF\xDF\xDF\xDF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<H1" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x48\x31\x00"sv, "\xFF\xDF\xFF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<DIV" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x44\x49\x56\x00"sv, "\xFF\xDF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<FONT" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x46\x4F\x4E\x54\x00"sv, "\xFF\xDF\xDF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<TABLE" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x54\x41\x42\x4C\x45\x00"sv, "\xFF\xDF\xDF\xDF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<A" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x41\x00"sv, "\xFF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<STYLE" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x53\x54\x59\x4C\x45\x00"sv,
- "\xFF\xDF\xDF\xDF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<TITLE" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x54\x49\x54\x4C\x45\x00"sv,
- "\xFF\xDF\xDF\xDF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<B" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x42\x00"sv, "\xFF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<BODY" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x42\x4F\x44\x59\x00"sv, "\xFF\xDF\xDF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<BR" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x42\x52\x00"sv, "\xFF\xDF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The case-insensitive string "<P" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x50\x00"sv, "\xFF\xDF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The string "<!--" followed by a tag-terminating byte.
- BytePatternTableRow { "\x3C\x21\x2D\x2D\x00"sv, "\xFF\xFF\xFF\xFF\xFF"sv, ignored_whitespace_bytes, text_html_mime_type, true },
-
- // The string "<?xml".
- BytePatternTableRow { "\x3C\x3F\x78\x6D\x6C"sv, "\xFF\xFF\xFF\xFF\xFF"sv, ignored_whitespace_bytes, "text/xml"sv },
-
- // The string "%PDF-", the PDF signature.
- BytePatternTableRow { "\x25\x50\x44\x46\x2D"sv, "\xFF\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "application/pdf"sv },
- };
-
- for (auto const& row : pattern_table) {
- // 1. Let patternMatched be the result of the pattern matching algorithm given resource’s resource header,
- // the value in the first column of row, the value in the second column of row, and the value in the
- // third column of row.
- auto pattern_matched = pattern_matching_algorithm(resource.resource_header(), row.byte_pattern.bytes(), row.pattern_mask.bytes(), row.ignored_leading_bytes, row.is_tag_terminated);
-
- // 2. If patternMatched is true, return the value in the fourth column of row.
- if (pattern_matched) {
- if (auto maybe_type = MimeType::parse(row.mime_type); maybe_type.has_value())
- return maybe_type.release_value();
- }
- }
- }
-
- // 2. Execute the following steps for each row row in the following table:
- static auto constexpr text_plain_mime_type = "text/plain"sv;
- static Array<BytePatternTableRow, 4> constexpr pattern_table {
- // The string "%!PS-Adobe-", the PostScript signature.
- BytePatternTableRow { "\x25\x21\x50\x53\x2D\x41\x64\x6F\x62\x65\x2D"sv,
- "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"sv, no_ignored_bytes, "application/postscript"sv },
-
- // UTF-16BE BOM
- BytePatternTableRow { "\xFE\xFF\x00\x00"sv, "\xFF\xFF\x00\x00"sv, no_ignored_bytes, text_plain_mime_type },
-
- // UTF-16LE BOM
- BytePatternTableRow { "\xFF\xFE\x00\x00"sv, "\xFF\xFF\x00\x00"sv, no_ignored_bytes, text_plain_mime_type },
-
- // UTF-8 BOM
- BytePatternTableRow { "\xEF\xBB\xBF\x00"sv, "\xFF\xFF\xFF\x00"sv, no_ignored_bytes, text_plain_mime_type },
- };
-
- for (auto const& row : pattern_table) {
- // 1. Let patternMatched be the result of the pattern matching algorithm given resource’s resource header,
- // the value in the first column of row, the value in the second column of row, and the value in the
- // third column of row.
- auto pattern_matched = pattern_matching_algorithm(resource.resource_header(), row.byte_pattern.bytes(), row.pattern_mask.bytes(), row.ignored_leading_bytes);
-
- // 2. If patternMatched is true, return the value in the fourth column of row.
- if (pattern_matched) {
- if (auto maybe_type = MimeType::parse(row.mime_type); maybe_type.has_value())
- return maybe_type.release_value();
- }
- }
-
- // 3. Let matchedType be the result of executing the image type pattern matching algorithm given resource’s resource header.
- auto matched_type = match_an_image_type_pattern(resource.resource_header());
-
- // 4. If matchedType is not undefined, return matchedType.
- if (matched_type.has_value())
- return matched_type.release_value();
-
- // 5. Set matchedType to the result of executing the audio or video type pattern matching algorithm given resource’s resource header.
- matched_type = match_an_audio_or_video_type_pattern(resource.resource_header());
-
- // 6. If matchedType is not undefined, return matchedType.
- if (matched_type.has_value())
- return matched_type.release_value();
-
- // 7. Set matchedType to the result of executing the archive type pattern matching algorithm given resource’s resource header.
- matched_type = match_an_archive_type_pattern(resource.resource_header());
-
- // 8. If matchedType is not undefined, return matchedType.
- if (matched_type.has_value())
- return matched_type.release_value();
-
- // 9. If resource’s resource header contains no binary data bytes, return "text/plain".
- if (!any_of(resource.resource_header(), is_binary_data_byte))
- return MimeType::create("text"_string, "plain"_string);
-
- // 10. Return "application/octet-stream".
- return MimeType::create("application"_string, "octet-stream"_string);
-}
-
-}
-
-namespace Web::MimeSniff {
-
-Resource Resource::create(ReadonlyBytes data, SniffingConfiguration configuration)
-{
- // NOTE: Non-standard but for cases where pattern matching fails, let's fall back to the safest MIME type.
- auto default_computed_mime_type = MimeType::create("application"_string, "octet-stream"_string);
- auto resource = Resource { data, configuration.no_sniff, move(default_computed_mime_type) };
-
- resource.supplied_mime_type_detection_algorithm(configuration.scheme, move(configuration.supplied_type));
- resource.context_specific_sniffing_algorithm(configuration.sniffing_context);
-
- return resource;
-}
-
-MimeType Resource::sniff(ReadonlyBytes data, SniffingConfiguration configuration)
-{
- auto resource = create(data, move(configuration));
- return move(resource.m_computed_mime_type);
-}
-
-Resource::Resource(ReadonlyBytes data, bool no_sniff, MimeType&& default_computed_mime_type)
- : m_no_sniff(no_sniff)
- , m_computed_mime_type(move(default_computed_mime_type))
-{
- read_the_resource_header(data);
-}
-
-Resource::~Resource() = default;
-
-// https://mimesniff.spec.whatwg.org/#supplied-mime-type-detection-algorithm
-// NOTE: Parameters are non-standard.
-void Resource::supplied_mime_type_detection_algorithm(StringView scheme, Optional<MimeType> supplied_type)
-{
- // 1. Let supplied-type be null.
- // 2. If the resource is retrieved via HTTP, execute the following steps:
- // 1. If one or more Content-Type headers are associated with the resource, execute the following steps:
- // 1. Set supplied-type to the value of the last Content-Type header associated with the resource.
- // 2. Set the check-for-apache-bug flag if supplied-type is exactly equal to one of the values in the following table:
- // NOTE: Non-standard but this algorithm expects the caller to handle step 2.1.1.
- if (supplied_type.has_value()) {
- if (Fetch::Infrastructure::is_http_or_https_scheme(scheme)) {
- // NOTE: The spec expects a space between the semicolon and the start of the charset parameter. However, we will lose this
- // space because MimeType::parse() ignores any spaces found there.
- static Array<StringView, 4> constexpr apache_bug_mime_types = {
- "text/plain"sv,
- "text/plain;charset=ISO-8859-1"sv,
- "text/plain;charset=iso-8859-1"sv,
- "text/plain;charset=UTF-8"sv
- };
-
- auto serialized_supplied_type = supplied_type->serialized();
- for (auto apache_bug_mime_type : apache_bug_mime_types) {
- if (serialized_supplied_type == apache_bug_mime_type) {
- m_check_for_apache_bug_flag = true;
- break;
- }
- }
- }
- }
-
- // 3. If the resource is retrieved directly from the file system, set supplied-type
- // to the MIME type provided by the file system.
- // 4. If the resource is retrieved via another protocol (such as FTP), set
- // supplied-type to the MIME type as determined by that protocol, if any.
- // 5. If supplied-type is not a MIME type, the supplied MIME type is undefined.
- // Abort these steps.
- // 6. The supplied MIME type is supplied-type.
- // NOTE: The expectation is for the caller to handle these spec steps.
- m_supplied_mime_type = supplied_type;
-}
-
-// https://mimesniff.spec.whatwg.org/#read-the-resource-header
-void Resource::read_the_resource_header(ReadonlyBytes data)
-{
- // 1. Let buffer be a byte sequence.
- ByteBuffer buffer;
-
- // 2. Read bytes of the resource into buffer until one of the following conditions is met:
- // - the end of the resource is reached.
- // - the number of bytes in buffer is greater than or equal to 1445.
- // - a reasonable amount of time has elapsed, as determined by the user agent.
- // FIXME: The spec expects us to be reading from a stream. Reimplement this spec step once
- // we have greater support for streaming in areas that calls on this API.
- static size_t constexpr MAX_SNIFF_SIZE = 1445;
- buffer.append(data.slice(0, min(data.size(), MAX_SNIFF_SIZE)));
-
- // 3. The resource header is buffer.
- m_resource_header = move(buffer);
-}
-
-// https://mimesniff.spec.whatwg.org/#mime-type-sniffing-algorithm
-void Resource::mime_type_sniffing_algorithm()
-{
- // 1. If the supplied MIME type is an XML MIME type or HTML MIME type, the computed MIME type is the supplied MIME type.
- // Abort these steps.
- if (m_supplied_mime_type.has_value() && (m_supplied_mime_type->is_xml() || m_supplied_mime_type->is_html())) {
- m_computed_mime_type = m_supplied_mime_type.value();
- return;
- }
-
- // 2. If the supplied MIME type is undefined or if the supplied MIME type’s essence
- // is "unknown/unknown", "application/unknown", or "*/*", execute the rules for
- // identifying an unknown MIME type with the sniff-scriptable flag equal to the
- // inverse of the no-sniff flag and abort these steps.
- if (!m_supplied_mime_type.has_value() || m_supplied_mime_type->essence().is_one_of("unknown/unknown", "application/unknown", "*/*")) {
- m_computed_mime_type = rules_for_identifying_an_unknown_mime_type(*this, !m_no_sniff);
- return;
- }
-
- // 3. If the no-sniff flag is set, the computed MIME type is the supplied MIME type.
- // Abort these steps.
- if (m_no_sniff) {
- m_computed_mime_type = m_supplied_mime_type.value();
- return;
- }
-
- // 4. If the check-for-apache-bug flag is set, execute the rules for distinguishing
- // if a resource is text or binary and abort these steps.
- if (m_check_for_apache_bug_flag) {
- rules_for_distinguishing_if_a_resource_is_text_or_binary();
- return;
- }
-
- // FIXME: 5. If the supplied MIME type is an image MIME type supported by the user agent, let matched-type be
- // the result of executing the image type pattern matching algorithm with the resource header as
- // the byte sequence to be matched.
- Optional<MimeType> matched_type;
-
- // 6. If matched-type is not undefined, the computed MIME type is matched-type.
- // Abort these steps.
- if (matched_type.has_value()) {
- m_computed_mime_type = matched_type.release_value();
- return;
- }
-
- // FIXME: 7. If the supplied MIME type is an audio or video MIME type supported by the user agent, let matched-type be
- // the result of executing the audio or video type pattern matching algorithm with the resource header as
- // the byte sequence to be matched.
-
- // 8. If matched-type is not undefined, the computed MIME type is matched-type.
- // Abort these steps.
- if (matched_type.has_value()) {
- m_computed_mime_type = matched_type.release_value();
- return;
- }
-
- // 9. The computed MIME type is the supplied MIME type.
- m_computed_mime_type = m_supplied_mime_type.value();
-
- return;
-}
-
-// https://mimesniff.spec.whatwg.org/#sniffing-a-mislabeled-binary-resource
-void Resource::rules_for_distinguishing_if_a_resource_is_text_or_binary()
-{
- // 1. Let length be the number of bytes in the resource header.
- auto length = m_resource_header.size();
-
- // 2. If length is greater than or equal to 2 and the first 2 bytes of the
- // resource header are equal to 0xFE 0xFF (UTF-16BE BOM) or 0xFF 0xFE (UTF-16LE BOM), the computed MIME type is "text/plain".
- // Abort these steps.
- auto resource_header_span = m_resource_header.span();
- auto utf_16_be_bom = "\xFE\xFF"sv.bytes();
- auto utf_16_le_bom = "\xFF\xFE"sv.bytes();
- if (length >= 2
- && (resource_header_span.starts_with(utf_16_be_bom)
- || resource_header_span.starts_with(utf_16_le_bom))) {
- m_computed_mime_type = MimeType::create("text"_string, "plain"_string);
- return;
- }
-
- // 3. If length is greater than or equal to 3 and the first 3 bytes of the resource header are equal to 0xEF 0xBB 0xBF (UTF-8 BOM),
- // the computed MIME type is "text/plain".
- // Abort these steps.
- auto utf_8_bom = "\xEF\xBB\xBF"sv.bytes();
- if (length >= 3 && resource_header_span.starts_with(utf_8_bom)) {
- m_computed_mime_type = MimeType::create("text"_string, "plain"_string);
- return;
- }
-
- // 4. If the resource header contains no binary data bytes, the computed MIME type is "text/plain".
- // Abort these steps.
- if (!any_of(resource_header(), is_binary_data_byte)) {
- m_computed_mime_type = MimeType::create("text"_string, "plain"_string);
- return;
- }
-
- // 5. The computed MIME type is "application/octet-stream".
- // NOTE: This is the default MIME type of the computed MIME type.
- return;
-}
-
-// https://mimesniff.spec.whatwg.org/#context-specific-sniffing-algorithm
-void Resource::context_specific_sniffing_algorithm(SniffingContext sniffing_context)
-{
- // A context-specific sniffing algorithm determines the computed MIME type of a resource only if
- // the resource is a MIME type relevant to a particular context.
- if (sniffing_context == SniffingContext::None || sniffing_context == SniffingContext::Browsing) {
- // https://mimesniff.spec.whatwg.org/#sniffing-in-a-browsing-context
- // Use the MIME type sniffing algorithm.
- return mime_type_sniffing_algorithm();
- }
-
- // NOTE: Non-standard but if the client expects us to not sniff, we shouldn't be doing any
- // context-specific sniffing if we don't have to.
- if (m_no_sniff && m_supplied_mime_type.has_value()) {
- m_computed_mime_type = m_supplied_mime_type.value();
- return;
- }
-
- if (sniffing_context == SniffingContext::Image)
- return rules_for_sniffing_images_specifically();
- if (sniffing_context == SniffingContext::AudioOrVideo)
- return rules_for_sniffing_audio_or_video_specifically();
- if (sniffing_context == SniffingContext::Font)
- return rules_for_sniffing_fonts_specifically();
- if (sniffing_context == SniffingContext::TextOrBinary)
- return rules_for_distinguishing_if_a_resource_is_text_or_binary();
-
- return;
-}
-
-// https://mimesniff.spec.whatwg.org/#sniffing-in-an-image-context
-void Resource::rules_for_sniffing_images_specifically()
-{
- // 1. If the supplied MIME type is an XML MIME type, the computed MIME type is the supplied MIME type.
- // Abort these steps.
- // NOTE: Non-standard but due to the mime type detection algorithm we need this sanity check.
- if (m_supplied_mime_type.has_value() && m_supplied_mime_type->is_xml()) {
- m_computed_mime_type = m_supplied_mime_type.value();
- return;
- }
-
- // 2. Let image-type-matched be the result of executing the image type pattern matching algorithm with
- // the resource header as the byte sequence to be matched.
- auto image_type_matched = match_an_image_type_pattern(resource_header());
-
- // 3. If image-type-matched is not undefined, the computed MIME type is image-type-matched.
- // Abort these steps.
- if (image_type_matched.has_value()) {
- m_computed_mime_type = image_type_matched.release_value();
- return;
- }
-
- // 4. The computed MIME type is the supplied MIME type.
- // NOTE: Non-standard but due to the mime type detection algorithm we need this sanity check.
- if (m_supplied_mime_type.has_value()) {
- m_computed_mime_type = m_supplied_mime_type.value();
- }
-
- // NOTE: Non-standard but if the supplied mime type is undefined, we use computed mime type's default value.
- return;
-}
-
-// https://mimesniff.spec.whatwg.org/#sniffing-in-an-audio-or-video-context
-void Resource::rules_for_sniffing_audio_or_video_specifically()
-{
- // 1. If the supplied MIME type is an XML MIME type, the computed MIME type is the supplied MIME type.
- // Abort these steps.
- // NOTE: Non-standard but due to the mime type detection algorithm we need this sanity check.
- if (m_supplied_mime_type.has_value() && m_supplied_mime_type->is_xml()) {
- m_computed_mime_type = m_supplied_mime_type.value();
- return;
- }
-
- // 2. Let audio-or-video-type-matched be the result of executing the audio or video type pattern matching
- // algorithm with the resource header as the byte sequence to be matched.
- auto audio_or_video_type_matched = match_an_audio_or_video_type_pattern(resource_header());
-
- // 3. If audio-or-video-type-matched is not undefined, the computed MIME type is audio-or-video-type-matched.
- // Abort these steps.
- if (audio_or_video_type_matched.has_value()) {
- m_computed_mime_type = audio_or_video_type_matched.release_value();
- return;
- }
-
- // 4. The computed MIME type is the supplied MIME type.
- // NOTE: Non-standard but due to the mime type detection algorithm we need this sanity check.
- if (m_supplied_mime_type.has_value()) {
- m_computed_mime_type = m_supplied_mime_type.value();
- }
-
- // NOTE: Non-standard but if the supplied mime type is undefined, we use computed mime type's default value.
- return;
-}
-
-// https://mimesniff.spec.whatwg.org/#sniffing-in-a-font-context
-void Resource::rules_for_sniffing_fonts_specifically()
-{
- // 1. If the supplied MIME type is an XML MIME type, the computed MIME type is the supplied MIME type.
- // Abort these steps.
- // NOTE: Non-standard but due to the mime type detection algorithm we need this sanity check.
- if (m_supplied_mime_type.has_value() && m_supplied_mime_type->is_xml()) {
- m_computed_mime_type = m_supplied_mime_type.value();
- return;
- }
-
- // 2. Let font-type-matched be the result of executing the font type pattern matching algorithm with the
- // resource header as the byte sequence to be matched.
- auto font_type_matched = match_a_font_type_pattern(resource_header());
-
- // 3. If font-type-matched is not undefined, the computed MIME type is font-type-matched.
- // Abort these steps.
- if (font_type_matched.has_value()) {
- m_computed_mime_type = font_type_matched.release_value();
- return;
- }
-
- // 4. The computed MIME type is the supplied MIME type.
- // NOTE: Non-standard but due to the mime type detection algorithm we need this sanity check.
- if (m_supplied_mime_type.has_value()) {
- m_computed_mime_type = m_supplied_mime_type.value();
- }
-
- // NOTE: Non-standard but if the supplied mime type is undefined, we use computed mime type's default value.
- return;
-}
-
-}
diff --git a/Libraries/LibWeb/MimeSniff/Resource.h b/Libraries/LibWeb/MimeSniff/Resource.h
deleted file mode 100644
index 94c8ff7f98f..00000000000
--- a/Libraries/LibWeb/MimeSniff/Resource.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (c) 2023, Kemal Zebari <[email protected]>.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Export.h>
-#include <LibWebCommon/MimeSniff/MimeType.h>
-
-namespace Web::MimeSniff {
-
-enum class SniffingContext {
- None,
- Browsing,
- Image,
- AudioOrVideo,
- Font,
-
- // Non-standard but used in cases where the spec expects us to only run
- // https://mimesniff.spec.whatwg.org/#sniffing-a-mislabeled-binary-resource
- TextOrBinary,
-};
-
-struct SniffingConfiguration {
- SniffingContext sniffing_context { SniffingContext::None };
- StringView scheme { ""sv };
- Optional<MimeType> supplied_type = {};
- bool no_sniff { false };
-};
-
-// https://mimesniff.spec.whatwg.org/#resource
-class WEB_API Resource {
-public:
- static Resource create(ReadonlyBytes data, SniffingConfiguration configuration = {});
- static MimeType sniff(ReadonlyBytes data, SniffingConfiguration configuration = {});
-
- ~Resource();
-
- MimeType const& computed_mime_type() const { return m_computed_mime_type; }
- ReadonlyBytes resource_header() const LIFETIME_BOUND { return m_resource_header; }
-
-private:
- Resource(ReadonlyBytes data, bool no_sniff, MimeType&& default_computed_mime_type);
-
- void read_the_resource_header(ReadonlyBytes data);
- void supplied_mime_type_detection_algorithm(StringView scheme, Optional<MimeType> supplied_type);
- void mime_type_sniffing_algorithm();
-
- void rules_for_distinguishing_if_a_resource_is_text_or_binary();
-
- void context_specific_sniffing_algorithm(SniffingContext sniffing_context);
- void rules_for_sniffing_images_specifically();
- void rules_for_sniffing_audio_or_video_specifically();
- void rules_for_sniffing_fonts_specifically();
-
- // https://mimesniff.spec.whatwg.org/#supplied-mime-type
- // A supplied MIME type, the MIME type determined by the supplied MIME type detection algorithm.
- Optional<MimeType> m_supplied_mime_type;
-
- // https://mimesniff.spec.whatwg.org/#check-for-apache-bug-flag
- // A check-for-apache-bug flag, which defaults to unset.
- bool m_check_for_apache_bug_flag { false };
-
- // https://mimesniff.spec.whatwg.org/#no-sniff-flag
- // A no-sniff flag, which defaults to set if the user agent does not wish to perform sniffing on the resource and unset otherwise.
- bool m_no_sniff { false };
-
- // https://mimesniff.spec.whatwg.org/#computed-mime-type
- // A computed MIME type, the MIME type determined by the MIME type sniffing algorithm.
- MimeType m_computed_mime_type;
-
- // https://mimesniff.spec.whatwg.org/#resource-header
- // A resource header is the byte sequence at the beginning of a resource, as determined by reading the resource header.
- ByteBuffer m_resource_header;
-};
-
-}
diff --git a/Libraries/LibWeb/Page/DragAndDropEventHandler.cpp b/Libraries/LibWeb/Page/DragAndDropEventHandler.cpp
index b6abf687bbc..bf5c079dbbb 100644
--- a/Libraries/LibWeb/Page/DragAndDropEventHandler.cpp
+++ b/Libraries/LibWeb/Page/DragAndDropEventHandler.cpp
@@ -19,9 +19,9 @@
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/WindowProxy.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
-#include <LibWeb/MimeSniff/Resource.h>
#include <LibWeb/Page/DragAndDropEventHandler.h>
#include <LibWebCommon/HTML/SelectedFile.h>
+#include <LibWebCommon/MimeSniff/Resource.h>
#include <LibWebCommon/UIEvents/KeyCode.h>
namespace Web {
diff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txt
index e5b5cf16b5b..ed261f572e3 100644
--- a/Libraries/LibWebCommon/CMakeLists.txt
+++ b/Libraries/LibWebCommon/CMakeLists.txt
@@ -44,6 +44,7 @@ set(SOURCES
Loader/DownloadFilename.cpp
Loader/SiteCompatibility.cpp
MimeSniff/MimeType.cpp
+ MimeSniff/Resource.cpp
Page/AsyncScrollNodeStableID.cpp
Page/DragEvent.cpp
Page/InputEvent.cpp
@@ -144,6 +145,12 @@ ladybird_lib(LibWebCommon webcommon EXPLICIT_SYMBOL_EXPORT)
add_dependencies(LibWebCommon generate_bindings)
target_link_libraries(LibWebCommon PRIVATE LibCore LibCrypto LibFileSystem LibGfx LibHTTP LibIPC LibRequests LibURL)
+import_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libwebcommon_rust FEATURES allocator FFI_HEADER RustFFI.h)
+target_link_libraries(LibWebCommon PRIVATE libwebcommon_rust)
+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})
+test_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libwebcommon_rust)
+
if (ENABLE_INSTALL_HEADERS)
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/CSS/PropertyList.h" "${CMAKE_CURRENT_BINARY_DIR}/CSS/PseudoElement.h" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/LibWebCommon/CSS")
diff --git a/Libraries/LibWebCommon/MimeSniff/MimeType.cpp b/Libraries/LibWebCommon/MimeSniff/MimeType.cpp
index f7e1a5c482e..374070ab487 100644
--- a/Libraries/LibWebCommon/MimeSniff/MimeType.cpp
+++ b/Libraries/LibWebCommon/MimeSniff/MimeType.cpp
@@ -10,36 +10,39 @@
#include <AK/CharacterTypes.h>
#include <AK/GenericLexer.h>
#include <AK/String.h>
-#include <AK/StringBuilder.h>
-#include <AK/Utf16StringBuilder.h>
#include <AK/Utf8View.h>
-#include <LibHTTP/HTTP.h>
-#include <LibHTTP/Header.h>
-#include <LibWebCommon/Infra/Strings.h>
#include <LibWebCommon/MimeSniff/MimeType.h>
+#include <LibWebCommon/RustFFI.h>
namespace Web::MimeSniff {
-static bool equals_ignoring_ascii_case(Utf16View string, StringView ascii_string)
+static FFI::FfiStringInput ffi_string_input(StringView string)
{
- return string.equals_ignoring_ascii_case(ascii_string);
+ return { reinterpret_cast<u8 const*>(string.characters_without_null_termination()), nullptr, string.length() };
}
-static void append_utf8_as_utf16(Utf16StringBuilder& builder, StringView string)
+static FFI::FfiStringInput ffi_string_input(Utf16View string)
{
- for (auto code_point : Utf8View { string })
- builder.append_code_point(code_point);
+ return {
+ string.has_ascii_storage() ? reinterpret_cast<u8 const*>(string.ascii_span().data()) : nullptr,
+ string.has_ascii_storage() ? nullptr : reinterpret_cast<u16 const*>(string.utf16_span().data()),
+ string.length_in_code_units(),
+ };
+}
+
+static String string_from_ffi(ReadonlyBytes bytes)
+{
+ return String::from_utf8_without_validation(bytes);
+}
+
+static void set_string_from_ffi(void* ctx, ReadonlyBytes string)
+{
+ *static_cast<String*>(ctx) = string_from_ffi(string);
}
-// https://mimesniff.spec.whatwg.org/#javascript-mime-type-essence-match
bool is_javascript_mime_type_essence_match(Utf16View string)
{
- // A string is a JavaScript MIME type essence match if it is an ASCII case-insensitive match for one of the JavaScript MIME type essence strings.
- for (auto const& javascript_essence : s_javascript_mime_type_essence_strings) {
- if (equals_ignoring_ascii_case(string, javascript_essence))
- return true;
- }
- return false;
+ return FFI::mime_sniff_is_javascript_mime_type_essence_match(ffi_string_input(string));
}
static bool contains_only_http_quoted_string_token_code_points(StringView string)
@@ -67,88 +70,6 @@ static bool contains_only_http_token_code_points(StringView string)
return true;
}
-static bool contains_only_http_token_code_points(Utf16View string)
-{
- // https://mimesniff.spec.whatwg.org/#http-token-code-point
- // An HTTP token code point is U+0021 (!), U+0023 (#), U+0024 ($), U+0025 (%), U+0026 (&), U+0027 ('), U+002A (*),
- // U+002B (+), U+002D (-), U+002E (.), U+005E (^), U+005F (_), U+0060 (`), U+007C (|), U+007E (~), or an ASCII alphanumeric.
- for (auto ch : string) {
- if (!HTTP::is_http_token_code_point(ch))
- return false;
- }
- return true;
-}
-
-static String http_token_to_ascii_lowercase_string(Utf16View string)
-{
- StringBuilder builder;
- for (auto ch : string) {
- VERIFY(HTTP::is_http_token_code_point(ch));
- builder.append(static_cast<char>(to_ascii_lowercase(ch)));
- }
- return MUST(builder.to_string());
-}
-
-static String collect_an_http_quoted_string(Utf16GenericLexer& lexer)
-{
- // 1. Let positionStart be position.
- // NOTE: Skipped, as MIME type parsing uses the extract-value flag.
-
- // 2. Let value be the empty string.
- StringBuilder value;
-
- // 3. Assert: the code point at position within input is U+0022 (").
- VERIFY(lexer.peek() == '"');
-
- // 4. Advance position by 1.
- lexer.ignore(1);
-
- // 5. While true:
- while (true) {
- // 1. Append the result of collecting a sequence of code points that are not U+0022 (") or U+005C (\) from
- // input, given position, to value.
- auto value_part = lexer.consume_until([](char16_t ch) {
- return ch == '"' || ch == '\\';
- });
-
- for (auto ch : value_part)
- value.append_code_point(ch);
-
- // 2. If position is past the end of input, then break.
- if (lexer.is_eof())
- break;
-
- // 3. Let quoteOrBackslash be the code point at position within input.
- // 4. Advance position by 1.
- auto quote_or_backslash = lexer.consume();
-
- // 5. If quoteOrBackslash is U+005C (\), then:
- if (quote_or_backslash == '\\') {
- // 1. If position is past the end of input, then append U+005C (\) to value and break.
- if (lexer.is_eof()) {
- value.append('\\');
- break;
- }
-
- // 2. Append the code point at position within input to value.
- // 3. Advance position by 1.
- value.append_code_point(lexer.consume());
- }
-
- // 6. Otherwise:
- else {
- // 1. Assert: quoteOrBackslash is U+0022 (").
- VERIFY(quote_or_backslash == '"');
-
- // 2. Break.
- break;
- }
- }
-
- // 6. If the extract-value flag is set, then return value.
- return MUST(value.to_string());
-}
-
MimeType::MimeType(String type, String subtype)
: m_type(move(type))
, m_subtype(move(subtype))
@@ -175,231 +96,45 @@ MimeType MimeType::create(String type, String subtype)
return mime_type;
}
-// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
-Optional<MimeType> MimeType::parse(StringView string)
+MimeType MimeType::from_ffi(FFI::FfiMimeType const& ffi_mime_type)
{
- // Verify that the input string is valid UTF-8 first, so we don't have to think about it anymore.
- if (!Utf8View(string).validate())
- return OptionalNone {};
-
- // 1. Remove any leading and trailing HTTP whitespace from input.
- auto trimmed_string = string.trim(HTTP::HTTP_WHITESPACE, TrimMode::Both);
-
- // 2. Let position be a position variable for input, initially pointing at the start of input.
- GenericLexer lexer(trimmed_string);
-
- // 3. Let type be the result of collecting a sequence of code points that are not U+002F (/) from input, given position.
- auto type = lexer.consume_until('/');
-
- // 4. If type is the empty string or does not solely contain HTTP token code points, then return failure.
- if (type.is_empty() || !contains_only_http_token_code_points(type))
- return OptionalNone {};
-
- // 5. If position is past the end of input, then return failure.
- if (lexer.is_eof())
- return OptionalNone {};
-
- // 6. Advance position by 1. (This skips past U+002F (/).)
- lexer.ignore(1);
-
- // 7. Let subtype be the result of collecting a sequence of code points that are not U+003B (;) from input, given position.
- auto subtype = lexer.consume_until(';');
-
- // 8. Remove any trailing HTTP whitespace from subtype.
- subtype = subtype.trim(HTTP::HTTP_WHITESPACE, TrimMode::Right);
-
- // 9. If subtype is the empty string or does not solely contain HTTP token code points, then return failure.
- if (subtype.is_empty() || !contains_only_http_token_code_points(subtype))
- return OptionalNone {};
-
- // 10. Let mimeType be a new MIME type record whose type is type, in ASCII lowercase, and subtype is subtype, in ASCII lowercase.
- auto mime_type = MimeType::create(type.to_ascii_lowercase_string(), subtype.to_ascii_lowercase_string());
-
- // 11. While position is not past the end of input:
- while (!lexer.is_eof()) {
- // 1. Advance position by 1. (This skips past U+003B (;).)
- lexer.ignore(1);
-
- // 2. Collect a sequence of code points that are HTTP whitespace from input given position.
- lexer.ignore_while(is_any_of(HTTP::HTTP_WHITESPACE));
-
- // 3. Let parameterName be the result of collecting a sequence of code points that are not U+003B (;) or U+003D (=) from input, given position.
- auto parameter_name_view = lexer.consume_until([](char ch) {
- return ch == ';' || ch == '=';
- });
-
- // 4. Set parameterName to parameterName, in ASCII lowercase.
- auto parameter_name = parameter_name_view.to_ascii_lowercase_string();
-
- // 5. If position is not past the end of input, then:
- if (!lexer.is_eof()) {
- // 1. If the code point at position within input is U+003B (;), then continue.
- if (lexer.peek() == ';')
- continue;
-
- // 2. Advance position by 1. (This skips past U+003D (=).)
- lexer.ignore(1);
- }
-
- // 6. If position is past the end of input, then break.
- // NOTE: This is not an `else` because the ignore on step 11.5.2 could put us past the end of the input.
- if (lexer.is_eof())
- break;
-
- // 7. Let parameterValue be null.
- String parameter_value;
-
- // 8. If the code point at position within input is U+0022 ("), then:
- if (lexer.peek() == '"') {
- // 1. Set parameterValue to the result of collecting an HTTP quoted string from input, given position and the extract-value flag.
- parameter_value = HTTP::collect_an_http_quoted_string(lexer, HTTP::HttpQuotedStringExtractValue::Yes);
-
- // 2. Collect a sequence of code points that are not U+003B (;) from input, given position.
- lexer.ignore_until(';');
- }
-
- // 9. Otherwise:
- else {
- // 1. Set parameterValue to the result of collecting a sequence of code points that are not U+003B (;) from input, given position.
- parameter_value = String::from_utf8_without_validation(lexer.consume_until(';').bytes());
-
- // 2. Remove any trailing HTTP whitespace from parameterValue.
- parameter_value = MUST(parameter_value.trim(HTTP::HTTP_WHITESPACE, TrimMode::Right));
-
- // 3. If parameterValue is the empty string, then continue.
- if (parameter_value.is_empty())
- continue;
- }
-
- // 10. If all of the following are true
- if (
- // - parameterName is not the empty string
- !parameter_name.is_empty()
- // - parameterName solely contains HTTP token code points
- && contains_only_http_token_code_points(parameter_name)
- // - parameterValue solely contains HTTP quoted-string token code points
- && contains_only_http_quoted_string_token_code_points(parameter_value)
- // - mimeType’s parameters[parameterName] does not exist
- && !mime_type.m_parameters.contains(parameter_name)) {
- // then set mimeType’s parameters[parameterName] to parameterValue.
- mime_type.m_parameters.set(move(parameter_name), move(parameter_value));
- }
- }
+ auto mime_type = create(string_from_ffi(ffi_mime_type.type_), string_from_ffi(ffi_mime_type.subtype));
+ for (auto const& parameter : ffi_mime_type.parameters)
+ mime_type.m_parameters.set(string_from_ffi(parameter.name), string_from_ffi(parameter.value));
+ return mime_type;
+}
+
+void MimeType::lend_to_ffi(Function<void(FFI::FfiMimeType const&)> const& callback) const
+{
+ Vector<FFI::FfiMimeTypeParameter> parameters;
+ parameters.ensure_capacity(m_parameters.size());
+ for (auto const& [name, value] : m_parameters)
+ parameters.unchecked_append({ name.bytes(), value.bytes() });
+ callback({ m_type.bytes(), m_subtype.bytes(), parameters.span() });
+}
+
+static void set_mime_type_from_ffi(void* ctx, FFI::FfiMimeType const* ffi_mime_type)
+{
+ *static_cast<Optional<MimeType>*>(ctx) = MimeType::from_ffi(*ffi_mime_type);
+}
- // 12. Return mimeType.
+static Optional<MimeType> parse_mime_type(FFI::FfiStringInput input)
+{
+ Optional<MimeType> mime_type;
+ FFI::mime_sniff_parse_mime_type(input, &mime_type, set_mime_type_from_ffi);
return mime_type;
}
// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
-Optional<MimeType> MimeType::parse(Utf16View string)
+Optional<MimeType> MimeType::parse(StringView string)
{
- // 1. Remove any leading and trailing HTTP whitespace from input.
- auto trimmed_string = string.trim(HTTP::HTTP_WHITESPACE, TrimMode::Both);
-
- // 2. Let position be a position variable for input, initially pointing at the start of input.
- Utf16GenericLexer lexer(trimmed_string);
-
- // 3. Let type be the result of collecting a sequence of code points that are not U+002F (/) from input, given position.
- auto type = lexer.consume_until('/');
-
- // 4. If type is the empty string or does not solely contain HTTP token code points, then return failure.
- if (type.is_empty() || !contains_only_http_token_code_points(type))
- return OptionalNone {};
-
- // 5. If position is past the end of input, then return failure.
- if (lexer.is_eof())
- return OptionalNone {};
-
- // 6. Advance position by 1. (This skips past U+002F (/).)
- lexer.ignore(1);
-
- // 7. Let subtype be the result of collecting a sequence of code points that are not U+003B (;) from input, given position.
- auto subtype = lexer.consume_until(';');
-
- // 8. Remove any trailing HTTP whitespace from subtype.
- subtype = subtype.trim(HTTP::HTTP_WHITESPACE, TrimMode::Right);
-
- // 9. If subtype is the empty string or does not solely contain HTTP token code points, then return failure.
- if (subtype.is_empty() || !contains_only_http_token_code_points(subtype))
- return OptionalNone {};
-
- // 10. Let mimeType be a new MIME type record whose type is type, in ASCII lowercase, and subtype is subtype, in ASCII lowercase.
- auto mime_type = MimeType::create(http_token_to_ascii_lowercase_string(type), http_token_to_ascii_lowercase_string(subtype));
-
- // 11. While position is not past the end of input:
- while (!lexer.is_eof()) {
- // 1. Advance position by 1. (This skips past U+003B (;).)
- lexer.ignore(1);
-
- // 2. Collect a sequence of code points that are HTTP whitespace from input given position.
- lexer.ignore_while([](auto ch) { return HTTP::HTTP_WHITESPACE.contains(static_cast<u32>(ch)); });
-
- // 3. Let parameterName be the result of collecting a sequence of code points that are not U+003B (;) or U+003D (=) from input, given position.
- auto parameter_name_view = lexer.consume_until([](char16_t ch) {
- return ch == ';' || ch == '=';
- });
-
- // 4. Set parameterName to parameterName, in ASCII lowercase.
- Optional<String> parameter_name;
- if (contains_only_http_token_code_points(parameter_name_view))
- parameter_name = http_token_to_ascii_lowercase_string(parameter_name_view);
-
- // 5. If position is not past the end of input, then:
- if (!lexer.is_eof()) {
- // 1. If the code point at position within input is U+003B (;), then continue.
- if (lexer.peek() == ';')
- continue;
-
- // 2. Advance position by 1. (This skips past U+003D (=).)
- lexer.ignore(1);
- }
-
- // 6. If position is past the end of input, then break.
- // NOTE: This is not an `else` because the ignore on step 11.5.2 could put us past the end of the input.
- if (lexer.is_eof())
- break;
-
- // 7. Let parameterValue be null.
- String parameter_value;
-
- // 8. If the code point at position within input is U+0022 ("), then:
- if (lexer.peek() == '"') {
- // 1. Set parameterValue to the result of collecting an HTTP quoted string from input, given position and the extract-value flag.
- parameter_value = collect_an_http_quoted_string(lexer);
-
- // 2. Collect a sequence of code points that are not U+003B (;) from input, given position.
- lexer.ignore_until(';');
- }
-
- // 9. Otherwise:
- else {
- // 1. Set parameterValue to the result of collecting a sequence of code points that are not U+003B (;) from input, given position.
- auto parameter_value_view = lexer.consume_until(';');
-
- // 2. Remove any trailing HTTP whitespace from parameterValue.
- parameter_value_view = parameter_value_view.trim(HTTP::HTTP_WHITESPACE, TrimMode::Right);
- parameter_value = MUST(parameter_value_view.to_utf8());
-
- // 3. If parameterValue is the empty string, then continue.
- if (parameter_value.is_empty())
- continue;
- }
-
- // 10. If all of the following are true
- if (
- // - parameterName is not the empty string
- parameter_name.has_value() && !parameter_name->is_empty()
- // - parameterValue solely contains HTTP quoted-string token code points
- && contains_only_http_quoted_string_token_code_points(parameter_value)
- // - mimeType’s parameters[parameterName] does not exist
- && !mime_type.m_parameters.contains(*parameter_name)) {
- // then set mimeType’s parameters[parameterName] to parameterValue.
- mime_type.m_parameters.set(parameter_name.release_value(), move(parameter_value));
- }
- }
+ return parse_mime_type(ffi_string_input(string));
+}
- // 12. Return mimeType.
- return mime_type;
+// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
+Optional<MimeType> MimeType::parse(Utf16View string)
+{
+ return parse_mime_type(ffi_string_input(string));
}
// https://mimesniff.spec.whatwg.org/#mime-type-essence
@@ -412,84 +147,17 @@ String const& MimeType::essence() const
// https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
String MimeType::serialized() const
{
- // 1. Let serialization be the concatenation of mimeType’s type, U+002F (/), and mimeType’s subtype.
- StringBuilder serialization;
- serialization.append(m_type);
- serialization.append('/');
- serialization.append(m_subtype);
-
- // 2. For each name → value of mimeType’s parameters:
- for (auto [name, value] : m_parameters) {
- // 1. Append U+003B (;) to serialization.
- serialization.append(';');
-
- // 2. Append name to serialization.
- serialization.append(name);
-
- // 3. Append U+003D (=) to serialization.
- serialization.append('=');
-
- // 4. If value does not solely contain HTTP token code points or value is the empty string, then:
- if (!contains_only_http_token_code_points(value) || value.is_empty()) {
- // 1. Precede each occurrence of U+0022 (") or U+005C (\) in value with U+005C (\).
- value = MUST(value.replace("\\"sv, "\\\\"sv, ReplaceMode::All));
- value = MUST(value.replace("\""sv, "\\\""sv, ReplaceMode::All));
-
- // 2. Prepend U+0022 (") to value.
- // 3. Append U+0022 (") to value.
- value = MUST(String::formatted("\"{}\"", value));
- }
-
- // 5. Append value to serialization.
- serialization.append(value);
- }
-
- // 3. Return serialization.
- return serialization.to_string_without_validation();
+ String serialization;
+ lend_to_ffi([&](FFI::FfiMimeType const& ffi_mime_type) {
+ FFI::mime_sniff_serialize_mime_type(&ffi_mime_type, &serialization, set_string_from_ffi);
+ });
+ return serialization;
}
// https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
Utf16String MimeType::serialized_as_utf16() const
{
- // 1. Let serialization be the concatenation of mimeType’s type, U+002F (/), and mimeType’s subtype.
- Utf16StringBuilder serialization;
- append_utf8_as_utf16(serialization, m_type);
- serialization.append_ascii('/');
- append_utf8_as_utf16(serialization, m_subtype);
-
- // 2. For each name → value of mimeType’s parameters:
- for (auto [name, value] : m_parameters) {
- // 1. Append U+003B (;) to serialization.
- serialization.append_ascii(';');
-
- // 2. Append name to serialization.
- append_utf8_as_utf16(serialization, name);
-
- // 3. Append U+003D (=) to serialization.
- serialization.append_ascii('=');
-
- // 4. If value does not solely contain HTTP token code points or value is the empty string, then:
- if (!contains_only_http_token_code_points(value) || value.is_empty()) {
- // 1. Precede each occurrence of U+0022 (") or U+005C (\) in value with U+005C (\).
- // 2. Prepend U+0022 (") to value.
- serialization.append_ascii('"');
- for (auto code_point : Utf8View { value }) {
- if (code_point == '"' || code_point == '\\')
- serialization.append_ascii('\\');
- serialization.append_code_point(code_point);
- }
-
- // 3. Append U+0022 (") to value.
- serialization.append_ascii('"');
- continue;
- }
-
- // 5. Append value to serialization.
- append_utf8_as_utf16(serialization, value);
- }
-
- // 3. Return serialization.
- return serialization.to_string();
+ return Utf16String::from_utf8_without_validation(serialized());
}
void MimeType::set_parameter(String name, String value)
@@ -504,91 +172,51 @@ void MimeType::set_parameter(String name, String value)
// https://mimesniff.spec.whatwg.org/#image-mime-type
bool MimeType::is_image() const
{
- // An image MIME type is a MIME type whose type is "image".
- return type() == "image"sv;
+ return FFI::mime_sniff_mime_type_is_in_group(FFI::MimeTypeGroup::Image, m_type.bytes(), m_subtype.bytes());
}
// https://mimesniff.spec.whatwg.org/#audio-or-video-mime-type
bool MimeType::is_audio_or_video() const
{
- // An audio or video MIME type is any MIME type whose type is "audio" or "video", or whose essence is "application/ogg".
- return type().is_one_of("audio"sv, "video"sv) || essence() == "application/ogg"sv;
+ return FFI::mime_sniff_mime_type_is_in_group(FFI::MimeTypeGroup::AudioOrVideo, m_type.bytes(), m_subtype.bytes());
}
// https://mimesniff.spec.whatwg.org/#font-mime-type
bool MimeType::is_font() const
{
- // A font MIME type is any MIME type whose type is "font", or whose essence is one of the following:
- // - application/font-cff
- // - application/font-otf
- // - application/font-sfnt
- // - application/font-ttf
- // - application/font-woff
- // - application/vnd.ms-fontobject
- // - application/vnd.ms-opentype
- if (type() == "font"sv)
- return true;
-
- return essence().is_one_of(
- "application/font-cff"sv,
- "application/font-otf"sv,
- "application/font-sfnt"sv,
- "application/font-ttf"sv,
- "application/font-woff"sv,
- "application/vnd.ms-fontobject"sv,
- "application/vnd.ms-opentype"sv);
+ return FFI::mime_sniff_mime_type_is_in_group(FFI::MimeTypeGroup::Font, m_type.bytes(), m_subtype.bytes());
}
// https://mimesniff.spec.whatwg.org/#xml-mime-type
bool MimeType::is_xml() const
{
- // An XML MIME type is any MIME type whose subtype ends in "+xml" or whose essence is "text/xml" or "application/xml". [RFC7303]
- return m_subtype.ends_with_bytes("+xml"sv) || essence().is_one_of("text/xml"sv, "application/xml"sv);
+ return FFI::mime_sniff_mime_type_is_in_group(FFI::MimeTypeGroup::Xml, m_type.bytes(), m_subtype.bytes());
}
// https://mimesniff.spec.whatwg.org/#html-mime-type
bool MimeType::is_html() const
{
- // An HTML MIME type is any MIME type whose essence is "text/html".
- return essence().is_one_of("text/html"sv);
+ return FFI::mime_sniff_mime_type_is_in_group(FFI::MimeTypeGroup::Html, m_type.bytes(), m_subtype.bytes());
}
// https://mimesniff.spec.whatwg.org/#javascript-mime-type
bool MimeType::is_javascript() const
{
- return s_javascript_mime_type_essence_strings.contains_slow(essence());
+ return FFI::mime_sniff_mime_type_is_in_group(FFI::MimeTypeGroup::JavaScript, m_type.bytes(), m_subtype.bytes());
}
// https://mimesniff.spec.whatwg.org/#json-mime-type
bool MimeType::is_json() const
{
- // A JSON MIME type is any MIME type whose subtype ends in "+json" or whose essence is "application/json" or "text/json".
- return subtype().ends_with_bytes("+json"sv) || essence().is_one_of("application/json"sv, "text/json"sv);
+ return FFI::mime_sniff_mime_type_is_in_group(FFI::MimeTypeGroup::Json, m_type.bytes(), m_subtype.bytes());
}
// https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type
String minimise_a_supported_mime_type(MimeType const& mime_type)
{
- // 1. If mimeType is a JavaScript MIME type, then return "text/javascript".
- if (mime_type.is_javascript())
- return "text/javascript"_string;
-
- // 2. If mimeType is a JSON MIME type, then return "application/json".
- if (mime_type.is_json())
- return "application/json"_string;
-
- // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml".
- if (mime_type.essence() == "image/svg+xml")
- return "image/svg+xml"_string;
-
- // 4. If mimeType is an XML MIME type, then return "application/xml".
- if (mime_type.is_xml())
- return "application/xml"_string;
-
- // FIXME: 5. If mimeType is supported by the user agent, then return mimeType’s essence.
-
- // 6. Return the empty string.
- return {};
+ String minimized;
+ FFI::mime_sniff_minimize_a_supported_mime_type(mime_type.type().bytes(), mime_type.subtype().bytes(), &minimized, set_string_from_ffi);
+ return minimized;
}
}
diff --git a/Libraries/LibWebCommon/MimeSniff/MimeType.h b/Libraries/LibWebCommon/MimeSniff/MimeType.h
index c6512ea640b..aa81dd292c6 100644
--- a/Libraries/LibWebCommon/MimeSniff/MimeType.h
+++ b/Libraries/LibWebCommon/MimeSniff/MimeType.h
@@ -7,37 +7,23 @@
#pragma once
+#include <AK/Function.h>
#include <AK/HashMap.h>
#include <AK/String.h>
#include <AK/Utf16String.h>
#include <AK/Utf16View.h>
#include <LibWebCommon/Export.h>
+namespace Web::FFI {
+
+struct FfiMimeType;
+
+}
+
namespace Web::MimeSniff {
WEBCOMMON_API bool is_javascript_mime_type_essence_match(Utf16View);
-// https://mimesniff.spec.whatwg.org/#javascript-mime-type
-// A JavaScript MIME type is any MIME type whose essence is one of the following:
-static constexpr Array s_javascript_mime_type_essence_strings = {
- "application/ecmascript"sv,
- "application/javascript"sv,
- "application/x-ecmascript"sv,
- "application/x-javascript"sv,
- "text/ecmascript"sv,
- "text/javascript"sv,
- "text/javascript1.0"sv,
- "text/javascript1.1"sv,
- "text/javascript1.2"sv,
- "text/javascript1.3"sv,
- "text/javascript1.4"sv,
- "text/javascript1.5"sv,
- "text/jscript"sv,
- "text/livescript"sv,
- "text/x-ecmascript"sv,
- "text/x-javascript"sv
-};
-
// https://mimesniff.spec.whatwg.org/#mime-type
class WEBCOMMON_API MimeType {
public:
@@ -71,6 +57,9 @@ public:
[[nodiscard]] String serialized() const;
[[nodiscard]] Utf16String serialized_as_utf16() const;
+ static MimeType from_ffi(FFI::FfiMimeType const&);
+ void lend_to_ffi(Function<void(FFI::FfiMimeType const&)> const&) const;
+
private:
MimeType(String type, String subtype);
diff --git a/Libraries/LibWebCommon/MimeSniff/Resource.cpp b/Libraries/LibWebCommon/MimeSniff/Resource.cpp
new file mode 100644
index 00000000000..5cf38d175bc
--- /dev/null
+++ b/Libraries/LibWebCommon/MimeSniff/Resource.cpp
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2023-2024, Kemal Zebari <[email protected]>.
+ * Copyright (c) 2025, Ben Eidson <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWebCommon/MimeSniff/Resource.h>
+#include <LibWebCommon/RustFFI.h>
+
+namespace Web::MimeSniff {
+
+static FFI::SniffingContext to_ffi(SniffingContext sniffing_context)
+{
+ switch (sniffing_context) {
+ case SniffingContext::None:
+ return FFI::SniffingContext::None;
+ case SniffingContext::Browsing:
+ return FFI::SniffingContext::Browsing;
+ case SniffingContext::Image:
+ return FFI::SniffingContext::Image;
+ case SniffingContext::AudioOrVideo:
+ return FFI::SniffingContext::AudioOrVideo;
+ case SniffingContext::Font:
+ return FFI::SniffingContext::Font;
+ case SniffingContext::TextOrBinary:
+ return FFI::SniffingContext::TextOrBinary;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+MimeType Resource::sniff(ReadonlyBytes data, SniffingConfiguration configuration)
+{
+ Optional<MimeType> computed_mime_type;
+ auto sniff = [&](FFI::FfiMimeType const* supplied_type) {
+ FFI::mime_sniff_sniff(data, to_ffi(configuration.sniffing_context), configuration.scheme.bytes(), supplied_type, configuration.no_sniff, &computed_mime_type, [](void* ctx, FFI::FfiMimeType const* mime_type) {
+ *static_cast<Optional<MimeType>*>(ctx) = MimeType::from_ffi(*mime_type);
+ });
+ };
+
+ if (configuration.supplied_type.has_value())
+ configuration.supplied_type->lend_to_ffi([&](FFI::FfiMimeType const& supplied_type) { sniff(&supplied_type); });
+ else
+ sniff(nullptr);
+
+ return computed_mime_type.release_value();
+}
+
+}
diff --git a/Libraries/LibWebCommon/MimeSniff/Resource.h b/Libraries/LibWebCommon/MimeSniff/Resource.h
new file mode 100644
index 00000000000..c2e7c4b89d1
--- /dev/null
+++ b/Libraries/LibWebCommon/MimeSniff/Resource.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2023, Kemal Zebari <[email protected]>.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWebCommon/Export.h>
+#include <LibWebCommon/MimeSniff/MimeType.h>
+
+namespace Web::MimeSniff {
+
+enum class SniffingContext {
+ None,
+ Browsing,
+ Image,
+ AudioOrVideo,
+ Font,
+
+ // Non-standard but used in cases where the spec expects us to only run
+ // https://mimesniff.spec.whatwg.org/#sniffing-a-mislabeled-binary-resource
+ TextOrBinary,
+};
+
+struct SniffingConfiguration {
+ SniffingContext sniffing_context { SniffingContext::None };
+ StringView scheme { ""sv };
+ Optional<MimeType> supplied_type = {};
+ bool no_sniff { false };
+};
+
+// https://mimesniff.spec.whatwg.org/#resource
+class WEBCOMMON_API Resource {
+public:
+ static MimeType sniff(ReadonlyBytes data, SniffingConfiguration configuration = {});
+};
+
+}
diff --git a/Libraries/LibWebCommon/Rust/Cargo.toml b/Libraries/LibWebCommon/Rust/Cargo.toml
new file mode 100644
index 00000000000..22851e2adf6
--- /dev/null
+++ b/Libraries/LibWebCommon/Rust/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "libwebcommon_rust"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+crate-type = ["staticlib"]
+
+[dependencies]
+ak = { path = "../../../AK/Rust" }
+ladybird_allocator = { path = "../../RustAllocator", optional = true }
+rustc-demangle = "0.1"
+
+[features]
+default = []
+allocator = ["dep:ladybird_allocator"]
+
+[build-dependencies]
+cbindgen = "0.29"
+
+[lints]
+workspace = true
diff --git a/Libraries/LibWebCommon/Rust/build.rs b/Libraries/LibWebCommon/Rust/build.rs
new file mode 100644
index 00000000000..5c6f8f8c952
--- /dev/null
+++ b/Libraries/LibWebCommon/Rust/build.rs
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::env;
+use std::error::Error;
+use std::path::PathBuf;
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);
+ let out_dir = PathBuf::from(env::var("OUT_DIR")?);
+
+ println!("cargo:rerun-if-changed=build.rs");
+ println!("cargo:rerun-if-changed=cbindgen.toml");
+ println!("cargo:rerun-if-changed=src");
+
+ cbindgen::generate(manifest_dir).map_or_else(
+ |error| match error {
+ cbindgen::Error::ParseSyntaxError { .. } => {}
+ e => panic!("{e:?}"),
+ },
+ |bindings| {
+ let header_path = out_dir.join("RustFFI.h");
+ bindings.write_to_file(&header_path);
+ },
+ );
+
+ Ok(())
+}
diff --git a/Libraries/LibWebCommon/Rust/cbindgen.toml b/Libraries/LibWebCommon/Rust/cbindgen.toml
new file mode 100644
index 00000000000..5d296441af8
--- /dev/null
+++ b/Libraries/LibWebCommon/Rust/cbindgen.toml
@@ -0,0 +1,24 @@
+language = "C++"
+header = """/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */"""
+pragma_once = true
+include_version = true
+namespaces = ["Web", "FFI"]
+line_length = 120
+tab_width = 4
+no_includes = true
+sys_includes = ["stdint.h", "stddef.h"]
+includes = ["AK/Span.h"]
+usize_is_size_t = true
+
+[parse]
+parse_deps = false
+
+[export.rename]
+"Span" = "AK::ReadonlySpan"
+
+[export.mangle]
+rename_types = "PascalCase"
diff --git a/Libraries/LibWebCommon/Rust/src/lib.rs b/Libraries/LibWebCommon/Rust/src/lib.rs
new file mode 100644
index 00000000000..10e46de960b
--- /dev/null
+++ b/Libraries/LibWebCommon/Rust/src/lib.rs
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#[cfg(feature = "allocator")]
+extern crate ladybird_allocator;
+
+#[path = "../../../RustDemangle.rs"]
+mod rust_demangle;
+
+#[path = "../../../RustPanic.rs"]
+mod rust_panic;
+
+pub mod mime_sniff;
diff --git a/Libraries/LibWebCommon/Rust/src/mime_sniff/ffi.rs b/Libraries/LibWebCommon/Rust/src/mime_sniff/ffi.rs
new file mode 100644
index 00000000000..960819f80a2
--- /dev/null
+++ b/Libraries/LibWebCommon/Rust/src/mime_sniff/ffi.rs
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The C ABI through which LibWebCommon's MimeSniff::MimeType and MimeSniff::Resource reach the crate. C++ lends its
+//! MIME types to the crate as a [`FfiMimeType`] of spans into its strings, and the crate lends its own back to a
+//! callback the same way.
+
+use core::ffi::c_void;
+
+use ak::Span;
+
+use super::mime_type::{Essence, MimeType, is_javascript_mime_type_essence_match};
+use super::resource::{SniffingContext, sniff};
+use crate::rust_panic::abort_on_panic;
+
+/// A string that C++ lends as UTF-8 or as UTF-16, of `length` code units.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct FfiStringInput {
+ pub utf8: *const u8,
+ pub utf16: *const u16,
+ pub length: usize,
+}
+
+impl FfiStringInput {
+ /// The code points of the string, with each unpaired surrogate replaced by U+FFFD, or `None` for bytes that are
+ /// not UTF-8.
+ ///
+ /// # Safety
+ ///
+ /// The pointer that is not null must lend `length` code units.
+ unsafe fn code_points(self) -> Option<Vec<char>> {
+ if self.length == 0 {
+ return Some(Vec::new());
+ }
+ if !self.utf16.is_null() {
+ // SAFETY: The caller lends `length` UTF-16 code units.
+ let units = unsafe { ak::slice_from_raw_parts(self.utf16, self.length) };
+ return Some(
+ char::decode_utf16(units.iter().copied())
+ .map(|code_point| code_point.unwrap_or(char::REPLACEMENT_CHARACTER))
+ .collect(),
+ );
+ }
+ // SAFETY: The caller lends `length` bytes.
+ let bytes = unsafe { ak::slice_from_raw_parts(self.utf8, self.length) };
+ Some(std::str::from_utf8(bytes).ok()?.chars().collect())
+ }
+}
+
+#[repr(C)]
+pub struct FfiMimeTypeParameter<'a> {
+ pub name: Span<'a, u8>,
+ pub value: Span<'a, u8>,
+}
+
+/// A MIME type whose strings, which are UTF-8, its lender keeps alive.
+#[repr(C)]
+pub struct FfiMimeType<'a> {
+ pub type_: Span<'a, u8>,
+ pub subtype: Span<'a, u8>,
+ pub parameters: Span<'a, FfiMimeTypeParameter<'a>>,
+}
+
+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)]
+pub enum MimeTypeGroup {
+ Image,
+ AudioOrVideo,
+ Font,
+ Xml,
+ Html,
+ JavaScript,
+ Json,
+}
+
+fn str_from_span(span: Span<'_, u8>) -> &str {
+ std::str::from_utf8(span.as_slice()).expect("C++ lends UTF-8 strings")
+}
+
+fn essence<'a>(type_: Span<'a, u8>, subtype: Span<'a, u8>) -> Essence<'a> {
+ Essence {
+ type_: str_from_span(type_),
+ subtype: str_from_span(subtype),
+ }
+}
+
+impl FfiMimeType<'_> {
+ fn to_mime_type(&self) -> MimeType {
+ let mut mime_type = MimeType::new(
+ str_from_span(self.type_).to_owned(),
+ str_from_span(self.subtype).to_owned(),
+ );
+ for parameter in self.parameters.as_slice() {
+ mime_type.set_parameter(
+ str_from_span(parameter.name).to_owned(),
+ str_from_span(parameter.value).to_owned(),
+ );
+ }
+ mime_type
+ }
+}
+
+/// # 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) {
+ let parameters: Vec<_> = mime_type
+ .parameters()
+ .map(|(name, value)| FfiMimeTypeParameter {
+ name: Span::new(name.as_bytes()),
+ value: Span::new(value.as_bytes()),
+ })
+ .collect();
+ let ffi_mime_type = FfiMimeType {
+ type_: Span::new(mime_type.type_().as_bytes()),
+ subtype: Span::new(mime_type.subtype().as_bytes()),
+ parameters: Span::new(&parameters),
+ };
+ // SAFETY: The caller passes a callback for `ctx`, and the MIME type outlives the call.
+ unsafe { on_mime_type(ctx, &raw const ffi_mime_type) };
+}
+
+/// Parses the input as a MIME type, and calls `on_mime_type` with the MIME type if that succeeds. Returns whether it
+/// succeeded.
+///
+/// # Safety
+///
+/// `input` must lend its code units for the call, and `on_mime_type` must be safe to call with `ctx`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn mime_sniff_parse_mime_type(
+ input: FfiStringInput,
+ ctx: *mut c_void,
+ on_mime_type: OnMimeType,
+) -> bool {
+ abort_on_panic(|| {
+ // SAFETY: The caller lends the code units of the input.
+ let Some(mime_type) = unsafe { input.code_points() }.as_deref().and_then(MimeType::parse) else {
+ return false;
+ };
+ // SAFETY: The caller passes a callback for `ctx`.
+ unsafe { lend_mime_type(&mime_type, ctx, on_mime_type) };
+ true
+ })
+}
+
+/// Calls `on_serialization` with the serialization of the MIME type.
+///
+/// # Safety
+///
+/// `mime_type` must be a valid MIME type for the call, and `on_serialization` must be safe to call with `ctx`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn mime_sniff_serialize_mime_type(
+ mime_type: *const FfiMimeType<'_>,
+ ctx: *mut c_void,
+ on_serialization: OnString,
+) {
+ abort_on_panic(|| {
+ // SAFETY: The caller lends a MIME type for the call.
+ let serialization = unsafe { &*mime_type }.to_mime_type().serialize();
+ // SAFETY: The caller passes a callback for `ctx`.
+ unsafe { on_serialization(ctx, Span::new(serialization.as_bytes())) };
+ });
+}
+
+/// Whether the MIME type with the type and subtype belongs to the group.
+#[unsafe(no_mangle)]
+pub extern "C" fn mime_sniff_mime_type_is_in_group(
+ group: MimeTypeGroup,
+ type_: Span<'_, u8>,
+ subtype: Span<'_, u8>,
+) -> bool {
+ abort_on_panic(|| {
+ let essence = essence(type_, subtype);
+ match group {
+ MimeTypeGroup::Image => essence.is_image(),
+ MimeTypeGroup::AudioOrVideo => essence.is_audio_or_video(),
+ MimeTypeGroup::Font => essence.is_font(),
+ MimeTypeGroup::Xml => essence.is_xml(),
+ MimeTypeGroup::Html => essence.is_html(),
+ MimeTypeGroup::JavaScript => essence.is_javascript(),
+ MimeTypeGroup::Json => essence.is_json(),
+ }
+ })
+}
+
+/// Calls `on_minimized` with the minimized MIME type of the MIME type with the type and subtype.
+///
+/// # Safety
+///
+/// `on_minimized` must be safe to call with `ctx`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn mime_sniff_minimize_a_supported_mime_type(
+ type_: Span<'_, u8>,
+ subtype: Span<'_, u8>,
+ ctx: *mut c_void,
+ on_minimized: OnString,
+) {
+ abort_on_panic(|| {
+ let minimized = essence(type_, subtype).minimize_a_supported_mime_type();
+ // SAFETY: The caller passes a callback for `ctx`.
+ unsafe { on_minimized(ctx, Span::new(minimized.as_bytes())) };
+ });
+}
+
+/// # Safety
+///
+/// `string` must lend its code units for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn mime_sniff_is_javascript_mime_type_essence_match(string: FfiStringInput) -> bool {
+ abort_on_panic(|| {
+ // SAFETY: The caller lends the code units of the string.
+ unsafe { string.code_points() }.is_some_and(|code_points| is_javascript_mime_type_essence_match(&code_points))
+ })
+}
+
+/// Calls `on_mime_type` with the computed MIME type of the resource whose data is `data`. `supplied_type` is null if
+/// there is no supplied MIME type.
+///
+/// # Safety
+///
+/// `supplied_type` must be null or a valid MIME type for the call, `scheme` must be UTF-8, and `on_mime_type` must be
+/// safe to call with `ctx`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn mime_sniff_sniff(
+ data: Span<'_, u8>,
+ sniffing_context: SniffingContext,
+ scheme: Span<'_, u8>,
+ supplied_type: *const FfiMimeType<'_>,
+ no_sniff: bool,
+ ctx: *mut c_void,
+ on_mime_type: OnMimeType,
+) {
+ abort_on_panic(|| {
+ // SAFETY: The caller lends a MIME type for the call, if any.
+ let supplied_type = unsafe { supplied_type.as_ref() }.map(FfiMimeType::to_mime_type);
+ let computed_mime_type = sniff(
+ data.as_slice(),
+ sniffing_context,
+ str_from_span(scheme),
+ supplied_type,
+ no_sniff,
+ );
+ // SAFETY: The caller passes a callback for `ctx`.
+ unsafe { lend_mime_type(&computed_mime_type, ctx, on_mime_type) };
+ });
+}
diff --git a/Libraries/LibWebCommon/Rust/src/mime_sniff/mime_type.rs b/Libraries/LibWebCommon/Rust/src/mime_sniff/mime_type.rs
new file mode 100644
index 00000000000..667a81ed894
--- /dev/null
+++ b/Libraries/LibWebCommon/Rust/src/mime_sniff/mime_type.rs
@@ -0,0 +1,511 @@
+/*
+ * Copyright (c) 2022, Luke Wilde <[email protected]>
+ * Copyright (c) 2022-2023, Linus Groh <[email protected]>
+ * Copyright (c) 2022, networkException <[email protected]>
+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+// https://mimesniff.spec.whatwg.org/#javascript-mime-type
+// A JavaScript MIME type is any MIME type whose essence is one of the following:
+const JAVASCRIPT_MIME_TYPE_ESSENCE_STRINGS: [&str; 16] = [
+ "application/ecmascript",
+ "application/javascript",
+ "application/x-ecmascript",
+ "application/x-javascript",
+ "text/ecmascript",
+ "text/javascript",
+ "text/javascript1.0",
+ "text/javascript1.1",
+ "text/javascript1.2",
+ "text/javascript1.3",
+ "text/javascript1.4",
+ "text/javascript1.5",
+ "text/jscript",
+ "text/livescript",
+ "text/x-ecmascript",
+ "text/x-javascript",
+];
+
+// https://fetch.spec.whatwg.org/#http-whitespace
+// HTTP whitespace is U+000A LF, U+000D CR, or an HTTP tab or space.
+fn is_http_whitespace(code_point: char) -> bool {
+ matches!(code_point, '\n' | '\r' | '\t' | ' ')
+}
+
+// https://mimesniff.spec.whatwg.org/#http-token-code-point
+// An HTTP token code point is U+0021 (!), U+0023 (#), U+0024 ($), U+0025 (%), U+0026 (&), U+0027 ('), U+002A (*),
+// U+002B (+), U+002D (-), U+002E (.), U+005E (^), U+005F (_), U+0060 (`), U+007C (|), U+007E (~), or an ASCII alphanumeric.
+fn is_http_token_code_point(code_point: char) -> bool {
+ matches!(
+ code_point,
+ '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | '-' | '.' | '^' | '_' | '`' | '|' | '~'
+ ) || code_point.is_ascii_alphanumeric()
+}
+
+// https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
+// An HTTP quoted-string token code point is U+0009 TAB, a code point in the range U+0020 SPACE to U+007E (~), inclusive,
+// or a code point in the range U+0080 through U+00FF (ÿ), inclusive.
+fn is_http_quoted_string_token_code_point(code_point: char) -> bool {
+ matches!(code_point, '\t' | '\u{20}'..='\u{7E}' | '\u{80}'..='\u{FF}')
+}
+
+fn solely_contains_http_token_code_points(string: &str) -> bool {
+ string.chars().all(is_http_token_code_point)
+}
+
+fn trim_trailing_http_whitespace(code_points: &[char]) -> &[char] {
+ let end = code_points
+ .iter()
+ .rposition(|&code_point| !is_http_whitespace(code_point))
+ .map_or(0, |index| index + 1);
+ &code_points[..end]
+}
+
+// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
+fn collect_a_sequence_of_code_points<'a>(
+ input: &'a [char],
+ position: &mut usize,
+ condition: impl Fn(char) -> bool,
+) -> &'a [char] {
+ let start = *position;
+ while *position < input.len() && condition(input[*position]) {
+ *position += 1;
+ }
+ &input[start..*position]
+}
+
+// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
+fn collect_an_http_quoted_string_extracting_the_value(input: &[char], position: &mut usize) -> String {
+ // 1. Let positionStart be position.
+ // NB: Skipped, as MIME type parsing uses the extract-value flag.
+
+ // 2. Let value be the empty string.
+ let mut value = String::new();
+
+ // 3. Assert: the code point at position within input is U+0022 (").
+ assert_eq!(input[*position], '"');
+
+ // 4. Advance position by 1.
+ *position += 1;
+
+ // 5. While true:
+ loop {
+ // 1. Append the result of collecting a sequence of code points that are not U+0022 (") or U+005C (\) from
+ // input, given position, to value.
+ value.extend(collect_a_sequence_of_code_points(input, position, |code_point| {
+ code_point != '"' && code_point != '\\'
+ }));
+
+ // 2. If position is past the end of input, then break.
+ if *position >= input.len() {
+ break;
+ }
+
+ // 3. Let quoteOrBackslash be the code point at position within input.
+ let quote_or_backslash = input[*position];
+
+ // 4. Advance position by 1.
+ *position += 1;
+
+ // 5. If quoteOrBackslash is U+005C (\), then:
+ if quote_or_backslash == '\\' {
+ // 1. If position is past the end of input, then append U+005C (\) to value and break.
+ if *position >= input.len() {
+ value.push('\\');
+ break;
+ }
+
+ // 2. Append the code point at position within input to value.
+ value.push(input[*position]);
+
+ // 3. Advance position by 1.
+ *position += 1;
+ }
+ // 6. Otherwise:
+ else {
+ // 1. Assert: quoteOrBackslash is U+0022 (").
+ assert_eq!(quote_or_backslash, '"');
+
+ // 2. Break.
+ break;
+ }
+ }
+
+ // 6. If the extract-value flag is set, then return value.
+ value
+}
+
+/// The type and subtype of a MIME type, which say which groups of MIME types it belongs to.
+#[derive(Clone, Copy)]
+pub struct Essence<'a> {
+ pub type_: &'a str,
+ pub subtype: &'a str,
+}
+
+impl Essence<'_> {
+ fn is(self, essence: &str) -> bool {
+ essence.split_once('/') == Some((self.type_, self.subtype))
+ }
+
+ // https://mimesniff.spec.whatwg.org/#image-mime-type
+ pub fn is_image(self) -> bool {
+ // An image MIME type is a MIME type whose type is "image".
+ self.type_ == "image"
+ }
+
+ // https://mimesniff.spec.whatwg.org/#audio-or-video-mime-type
+ pub fn is_audio_or_video(self) -> bool {
+ // An audio or video MIME type is any MIME type whose type is "audio" or "video", or whose essence is "application/ogg".
+ matches!(self.type_, "audio" | "video") || self.is("application/ogg")
+ }
+
+ // https://mimesniff.spec.whatwg.org/#font-mime-type
+ pub fn is_font(self) -> bool {
+ // A font MIME type is any MIME type whose type is "font", or whose essence is one of the following:
+ // - application/font-cff
+ // - application/font-otf
+ // - application/font-sfnt
+ // - application/font-ttf
+ // - application/font-woff
+ // - application/vnd.ms-fontobject
+ // - application/vnd.ms-opentype
+ self.type_ == "font"
+ || (self.type_ == "application"
+ && matches!(
+ self.subtype,
+ "font-cff"
+ | "font-otf"
+ | "font-sfnt"
+ | "font-ttf"
+ | "font-woff"
+ | "vnd.ms-fontobject"
+ | "vnd.ms-opentype"
+ ))
+ }
+
+ // https://mimesniff.spec.whatwg.org/#xml-mime-type
+ pub fn is_xml(self) -> bool {
+ // An XML MIME type is any MIME type whose subtype ends in "+xml" or whose essence is "text/xml" or "application/xml". [RFC7303]
+ self.subtype.ends_with("+xml") || self.is("text/xml") || self.is("application/xml")
+ }
+
+ // https://mimesniff.spec.whatwg.org/#html-mime-type
+ pub fn is_html(self) -> bool {
+ // An HTML MIME type is any MIME type whose essence is "text/html".
+ self.is("text/html")
+ }
+
+ // https://mimesniff.spec.whatwg.org/#javascript-mime-type
+ pub fn is_javascript(self) -> bool {
+ JAVASCRIPT_MIME_TYPE_ESSENCE_STRINGS
+ .iter()
+ .any(|&essence| self.is(essence))
+ }
+
+ // https://mimesniff.spec.whatwg.org/#json-mime-type
+ pub fn is_json(self) -> bool {
+ // A JSON MIME type is any MIME type whose subtype ends in "+json" or whose essence is "application/json" or "text/json".
+ self.subtype.ends_with("+json") || self.is("application/json") || self.is("text/json")
+ }
+
+ // https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type
+ pub fn minimize_a_supported_mime_type(self) -> &'static str {
+ // 1. If mimeType is a JavaScript MIME type, then return "text/javascript".
+ if self.is_javascript() {
+ return "text/javascript";
+ }
+
+ // 2. If mimeType is a JSON MIME type, then return "application/json".
+ if self.is_json() {
+ return "application/json";
+ }
+
+ // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml".
+ if self.is("image/svg+xml") {
+ return "image/svg+xml";
+ }
+
+ // 4. If mimeType is an XML MIME type, then return "application/xml".
+ if self.is_xml() {
+ return "application/xml";
+ }
+
+ // FIXME: 5. If mimeType is supported by the user agent, then return mimeType’s essence.
+
+ // 6. Return the empty string.
+ ""
+ }
+}
+
+// https://mimesniff.spec.whatwg.org/#javascript-mime-type-essence-match
+pub fn is_javascript_mime_type_essence_match(string: &[char]) -> bool {
+ // A string is a JavaScript MIME type essence match if it is an ASCII case-insensitive match for one of the JavaScript MIME type essence strings.
+ JAVASCRIPT_MIME_TYPE_ESSENCE_STRINGS.iter().any(|essence| {
+ essence.len() == string.len()
+ && essence
+ .chars()
+ .zip(string)
+ .all(|(essence_code_point, &code_point)| essence_code_point.eq_ignore_ascii_case(&code_point))
+ })
+}
+
+// https://mimesniff.spec.whatwg.org/#mime-type
+#[derive(Clone)]
+pub struct MimeType {
+ // https://mimesniff.spec.whatwg.org/#type
+ // A MIME type’s type is a non-empty ASCII string.
+ type_: String,
+
+ // https://mimesniff.spec.whatwg.org/#subtype
+ // A MIME type’s subtype is a non-empty ASCII string.
+ subtype: String,
+
+ // https://mimesniff.spec.whatwg.org/#parameters
+ // A MIME type’s parameters is an ordered map whose keys are ASCII strings and values are strings limited to HTTP quoted-string token code points. It is initially empty.
+ parameters: Vec<(String, String)>,
+}
+
+impl MimeType {
+ pub fn new(type_: String, subtype: String) -> Self {
+ assert!(!type_.is_empty() && solely_contains_http_token_code_points(&type_));
+ assert!(!subtype.is_empty() && solely_contains_http_token_code_points(&subtype));
+ Self {
+ type_,
+ subtype,
+ parameters: Vec::new(),
+ }
+ }
+
+ pub fn type_(&self) -> &str {
+ &self.type_
+ }
+
+ pub fn subtype(&self) -> &str {
+ &self.subtype
+ }
+
+ pub fn parameters(&self) -> impl Iterator<Item = (&str, &str)> {
+ self.parameters
+ .iter()
+ .map(|(name, value)| (name.as_str(), value.as_str()))
+ }
+
+ pub fn set_parameter(&mut self, name: String, value: String) {
+ assert!(name.chars().all(is_http_quoted_string_token_code_point));
+ assert!(value.chars().all(is_http_quoted_string_token_code_point));
+ match self
+ .parameters
+ .iter_mut()
+ .find(|(existing_name, _)| *existing_name == name)
+ {
+ Some((_, existing_value)) => *existing_value = value,
+ None => self.parameters.push((name, value)),
+ }
+ }
+
+ pub fn essence(&self) -> Essence<'_> {
+ Essence {
+ type_: &self.type_,
+ subtype: &self.subtype,
+ }
+ }
+
+ // https://mimesniff.spec.whatwg.org/#parse-a-mime-type
+ pub fn parse(input: &[char]) -> Option<Self> {
+ // 1. Remove any leading and trailing HTTP whitespace from input.
+ let start = input
+ .iter()
+ .position(|&code_point| !is_http_whitespace(code_point))
+ .unwrap_or(input.len());
+ let input = trim_trailing_http_whitespace(&input[start..]);
+
+ // 2. Let position be a position variable for input, initially pointing at the start of input.
+ let mut position = 0;
+
+ // 3. Let type be the result of collecting a sequence of code points that are not U+002F (/) from input, given position.
+ let type_ = collect_a_sequence_of_code_points(input, &mut position, |code_point| code_point != '/');
+
+ // 4. If type is the empty string or does not solely contain HTTP token code points, then return failure.
+ if type_.is_empty() || !type_.iter().copied().all(is_http_token_code_point) {
+ return None;
+ }
+
+ // 5. If position is past the end of input, then return failure.
+ if position >= input.len() {
+ return None;
+ }
+
+ // 6. Advance position by 1. (This skips past U+002F (/).)
+ position += 1;
+
+ // 7. Let subtype be the result of collecting a sequence of code points that are not U+003B (;) from input, given position.
+ let subtype = collect_a_sequence_of_code_points(input, &mut position, |code_point| code_point != ';');
+
+ // 8. Remove any trailing HTTP whitespace from subtype.
+ let subtype = trim_trailing_http_whitespace(subtype);
+
+ // 9. If subtype is the empty string or does not solely contain HTTP token code points, then return failure.
+ if subtype.is_empty() || !subtype.iter().copied().all(is_http_token_code_point) {
+ return None;
+ }
+
+ // 10. Let mimeType be a new MIME type record whose type is type, in ASCII lowercase, and subtype is subtype, in ASCII lowercase.
+ let mut mime_type = Self {
+ type_: type_.iter().map(char::to_ascii_lowercase).collect(),
+ subtype: subtype.iter().map(char::to_ascii_lowercase).collect(),
+ parameters: Vec::new(),
+ };
+
+ // 11. While position is not past the end of input:
+ while position < input.len() {
+ // 1. Advance position by 1. (This skips past U+003B (;).)
+ position += 1;
+
+ // 2. Collect a sequence of code points that are HTTP whitespace from input given position.
+ collect_a_sequence_of_code_points(input, &mut position, is_http_whitespace);
+
+ // 3. Let parameterName be the result of collecting a sequence of code points that are not U+003B (;) or U+003D (=) from input, given position.
+ let parameter_name = collect_a_sequence_of_code_points(input, &mut position, |code_point| {
+ code_point != ';' && code_point != '='
+ });
+
+ // 4. Set parameterName to parameterName, in ASCII lowercase.
+ let parameter_name: String = parameter_name.iter().map(char::to_ascii_lowercase).collect();
+
+ // 5. If position is not past the end of input, then:
+ if position < input.len() {
+ // 1. If the code point at position within input is U+003B (;), then continue.
+ if input[position] == ';' {
+ continue;
+ }
+
+ // 2. Advance position by 1. (This skips past U+003D (=).)
+ position += 1;
+ }
+
+ // 6. If position is past the end of input, then break.
+ if position >= input.len() {
+ break;
+ }
+
+ // 7. Let parameterValue be null.
+ let parameter_value;
+
+ // 8. If the code point at position within input is U+0022 ("), then:
+ if input[position] == '"' {
+ // 1. Set parameterValue to the result of collecting an HTTP quoted string from input, given position and the extract-value flag.
+ parameter_value = collect_an_http_quoted_string_extracting_the_value(input, &mut position);
+
+ // 2. Collect a sequence of code points that are not U+003B (;) from input, given position.
+ collect_a_sequence_of_code_points(input, &mut position, |code_point| code_point != ';');
+ }
+ // 9. Otherwise:
+ else {
+ // 1. Set parameterValue to the result of collecting a sequence of code points that are not U+003B (;) from input, given position.
+ let value = collect_a_sequence_of_code_points(input, &mut position, |code_point| code_point != ';');
+
+ // 2. Remove any trailing HTTP whitespace from parameterValue.
+ let value = trim_trailing_http_whitespace(value);
+
+ // 3. If parameterValue is the empty string, then continue.
+ if value.is_empty() {
+ continue;
+ }
+ parameter_value = value.iter().collect();
+ }
+
+ // 10. If all of the following are true
+ // - parameterName is not the empty string
+ // - parameterName solely contains HTTP token code points
+ // - parameterValue solely contains HTTP quoted-string token code points
+ // - mimeType’s parameters[parameterName] does not exist
+ // then set mimeType’s parameters[parameterName] to parameterValue.
+ if !parameter_name.is_empty()
+ && solely_contains_http_token_code_points(&parameter_name)
+ && parameter_value.chars().all(is_http_quoted_string_token_code_point)
+ && !mime_type.parameters.iter().any(|(name, _)| *name == parameter_name)
+ {
+ mime_type.parameters.push((parameter_name, parameter_value));
+ }
+ }
+
+ // 12. Return mimeType.
+ Some(mime_type)
+ }
+
+ // https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
+ pub fn serialize(&self) -> String {
+ // 1. Let serialization be the concatenation of mimeType’s type, U+002F (/), and mimeType’s subtype.
+ let mut serialization = format!("{}/{}", self.type_, self.subtype);
+
+ // 2. For each name → value of mimeType’s parameters:
+ for (name, value) in &self.parameters {
+ // 1. Append U+003B (;) to serialization.
+ serialization.push(';');
+
+ // 2. Append name to serialization.
+ serialization.push_str(name);
+
+ // 3. Append U+003D (=) to serialization.
+ serialization.push('=');
+
+ // 4. If value does not solely contain HTTP token code points or value is the empty string, then:
+ if !solely_contains_http_token_code_points(value) || value.is_empty() {
+ // 1. Precede each occurrence of U+0022 (") or U+005C (\) in value with U+005C (\).
+ // 2. Prepend U+0022 (") to value.
+ // 3. Append U+0022 (") to value.
+ serialization.push('"');
+ for code_point in value.chars() {
+ if code_point == '"' || code_point == '\\' {
+ serialization.push('\\');
+ }
+ serialization.push(code_point);
+ }
+ serialization.push('"');
+ continue;
+ }
+
+ // 5. Append value to serialization.
+ serialization.push_str(value);
+ }
+
+ // 3. Return serialization.
+ serialization
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn parse(input: &str) -> Option<MimeType> {
+ MimeType::parse(&input.chars().collect::<Vec<_>>())
+ }
+
+ #[test]
+ fn parses_and_serializes() {
+ let mime_type = parse(" Text/HTML ; Charset=\"utf-8\" ; charset=ignored;flag;x=\"a\\\"b\"").unwrap();
+ assert_eq!(mime_type.type_(), "text");
+ assert_eq!(mime_type.subtype(), "html");
+ assert_eq!(mime_type.serialize(), "text/html;charset=utf-8;x=\"a\\\"b\"");
+ assert!(mime_type.essence().is_html());
+ }
+
+ #[test]
+ fn rejects_invalid_types() {
+ assert!(parse("").is_none());
+ assert!(parse("text").is_none());
+ assert!(parse("text/").is_none());
+ assert!(parse("te xt/html").is_none());
+ assert!(parse("text/html\u{FFFD}").is_none());
+ }
+
+ #[test]
+ fn drops_parameters_outside_the_quoted_string_token_code_points() {
+ let mime_type = parse("text/plain;a=\u{100};b=\u{FF}").unwrap();
+ assert_eq!(mime_type.serialize(), "text/plain;b=\"\u{FF}\"");
+ }
+}
diff --git a/Libraries/LibWebCommon/Rust/src/mime_sniff/mod.rs b/Libraries/LibWebCommon/Rust/src/mime_sniff/mod.rs
new file mode 100644
index 00000000000..190214416bf
--- /dev/null
+++ b/Libraries/LibWebCommon/Rust/src/mime_sniff/mod.rs
@@ -0,0 +1,11 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! MIME Sniffing, https://mimesniff.spec.whatwg.org/
+
+pub mod ffi;
+pub mod mime_type;
+pub mod resource;
diff --git a/Libraries/LibWebCommon/Rust/src/mime_sniff/resource.rs b/Libraries/LibWebCommon/Rust/src/mime_sniff/resource.rs
new file mode 100644
index 00000000000..40f999c6f4a
--- /dev/null
+++ b/Libraries/LibWebCommon/Rust/src/mime_sniff/resource.rs
@@ -0,0 +1,1072 @@
+/*
+ * Copyright (c) 2023-2024, Kemal Zebari <[email protected]>.
+ * Copyright (c) 2025, Ben Eidson <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::mime_type::MimeType;
+
+#[repr(u8)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum SniffingContext {
+ None,
+ Browsing,
+ Image,
+ AudioOrVideo,
+ Font,
+
+ // Non-standard but used in cases where the spec expects us to only run
+ // https://mimesniff.spec.whatwg.org/#sniffing-a-mislabeled-binary-resource
+ TextOrBinary,
+}
+
+struct BytePatternTableRow {
+ byte_pattern: &'static [u8],
+ pattern_mask: &'static [u8],
+ ignored_leading_bytes: &'static [u8],
+ mime_type: &'static str,
+
+ // NB: If the byte pattern has a tag-terminating byte, add a byte where this byte should be. The value itself is
+ // ignored in pattern_matching_algorithm() (see the NB in that algorithm for more details).
+ is_tag_terminated: bool,
+}
+
+const fn row(
+ byte_pattern: &'static [u8],
+ pattern_mask: &'static [u8],
+ ignored_leading_bytes: &'static [u8],
+ mime_type: &'static str,
+) -> BytePatternTableRow {
+ BytePatternTableRow {
+ byte_pattern,
+ pattern_mask,
+ ignored_leading_bytes,
+ mime_type,
+ is_tag_terminated: false,
+ }
+}
+
+const fn tag_terminated_row(
+ byte_pattern: &'static [u8],
+ pattern_mask: &'static [u8],
+ ignored_leading_bytes: &'static [u8],
+ mime_type: &'static str,
+) -> BytePatternTableRow {
+ BytePatternTableRow {
+ is_tag_terminated: true,
+ ..row(byte_pattern, pattern_mask, ignored_leading_bytes, mime_type)
+ }
+}
+
+const NO_IGNORED_BYTES: &[u8] = &[];
+
+// https://mimesniff.spec.whatwg.org/#whitespace-byte
+// A whitespace byte (abbreviated 0xWS) is any one of the following bytes: 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP).
+const WHITESPACE_BYTES: &[u8] = &[0x09, 0x0A, 0x0C, 0x0D, 0x20];
+
+fn mime_type(essence: &str) -> MimeType {
+ let (type_, subtype) = essence
+ .split_once('/')
+ .expect("the MIME types of the tables are essences");
+ MimeType::new(type_.to_owned(), subtype.to_owned())
+}
+
+// https://mimesniff.spec.whatwg.org/#tag-terminating-byte
+fn is_tag_terminating_byte(byte: u8) -> bool {
+ // A tag-terminating byte (abbreviated 0xTT) is any one of the following bytes: 0x20 (SP), 0x3E (">").
+ byte == 0x20 || byte == 0x3E
+}
+
+// https://mimesniff.spec.whatwg.org/#binary-data-byte
+fn is_binary_data_byte(byte: u8) -> bool {
+ // A binary data byte is a byte in the range 0x00 to 0x08 (NUL to BS), the byte 0x0B (VT), a byte in
+ // the range 0x0E to 0x1A (SO to SUB), or a byte in the range 0x1C to 0x1F (FS to US).
+ matches!(byte, 0x00..=0x08 | 0x0B | 0x0E..=0x1A | 0x1C..=0x1F)
+}
+
+// https://mimesniff.spec.whatwg.org/#pattern-matching-algorithm
+fn pattern_matching_algorithm(input: &[u8], row: &BytePatternTableRow) -> bool {
+ let pattern = row.byte_pattern;
+ let mask = row.pattern_mask;
+ let ignored = row.ignored_leading_bytes;
+
+ // 1. Assert: pattern’s length is equal to mask’s length.
+ assert_eq!(pattern.len(), mask.len());
+
+ // 2. If input’s length is less than pattern’s length, return false.
+ if input.len() < pattern.len() {
+ return false;
+ }
+
+ // 3. Let s be 0.
+ let mut s = 0;
+
+ // 4. While s < input’s length:
+ while s < input.len() {
+ // 1. If ignored does not contain input[s], break.
+ if !ignored.contains(&input[s]) {
+ break;
+ }
+
+ // 2. Set s to s + 1.
+ s += 1;
+ }
+
+ // 5. Let p be 0.
+ let mut p = 0;
+
+ // 6. While p < pattern’s length:
+ while p < pattern.len() {
+ // NB: Leading ignored bytes can leave fewer bytes of input than the pattern has.
+ let Some(&byte) = input.get(s) else {
+ return false;
+ };
+
+ // 1. Let maskedData be the result of applying the bitwise AND operator to input[s] and mask[p].
+ let masked_data = byte & mask[p];
+
+ // NB: This non-standard branch exists to avoid having to create 2 byte patterns just so that
+ // they can only differ by their tag-terminating byte (which could be a 0x20 or 0x3E byte).
+ if row.is_tag_terminated && p + 1 == pattern.len() {
+ return is_tag_terminating_byte(masked_data);
+ }
+
+ // 2. If maskedData is not equal to pattern[p], return false.
+ if masked_data != pattern[p] {
+ return false;
+ }
+
+ // 3. Set s to s + 1.
+ s += 1;
+
+ // 4. Set p to p + 1.
+ p += 1;
+ }
+
+ // 7. Return true.
+ true
+}
+
+fn match_a_pattern_table(input: &[u8], pattern_table: &[BytePatternTableRow]) -> Option<MimeType> {
+ // 1. Execute the following steps for each row row in the following table:
+ for row in pattern_table {
+ // 1. Let patternMatched be the result of the pattern matching algorithm given input, the value in
+ // the first column of row, the value in the second column of row, and the value in the third
+ // column of row.
+ let pattern_matched = pattern_matching_algorithm(input, row);
+
+ // 2. If patternMatched is true, return the value in the fourth column of row.
+ if pattern_matched {
+ return Some(mime_type(row.mime_type));
+ }
+ }
+
+ // 2. Return undefined.
+ None
+}
+
+// https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern
+fn match_an_image_type_pattern(input: &[u8]) -> Option<MimeType> {
+ const PATTERN_TABLE: [BytePatternTableRow; 8] = [
+ // A Windows Icon signature.
+ row(
+ b"\x00\x00\x01\x00",
+ b"\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "image/x-icon",
+ ),
+ // A Windows Cursor signature.
+ row(
+ b"\x00\x00\x02\x00",
+ b"\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "image/x-icon",
+ ),
+ // The string "BM", a BMP signature.
+ row(b"\x42\x4D", b"\xFF\xFF", NO_IGNORED_BYTES, "image/bmp"),
+ // The string "GIF87a", a GIF signature.
+ row(
+ b"\x47\x49\x46\x38\x37\x61",
+ b"\xFF\xFF\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "image/gif",
+ ),
+ // The string "GIF89a", a GIF signature.
+ row(
+ b"\x47\x49\x46\x38\x39\x61",
+ b"\xFF\xFF\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "image/gif",
+ ),
+ // The string "RIFF" followed by four bytes followed by the string "WEBPVP".
+ row(
+ b"\x52\x49\x46\x46\x00\x00\x00\x00\x57\x45\x42\x50\x56\x50",
+ b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "image/webp",
+ ),
+ // An error-checking byte followed by the string "PNG" followed by CR LF SUB LF, the PNG signature.
+ row(
+ b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A",
+ b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "image/png",
+ ),
+ // The JPEG Start of Image marker followed by the indicator byte of another marker.
+ row(b"\xFF\xD8\xFF", b"\xFF\xFF\xFF", NO_IGNORED_BYTES, "image/jpeg"),
+ ];
+ match_a_pattern_table(input, &PATTERN_TABLE)
+}
+
+// https://mimesniff.spec.whatwg.org/#signature-for-mp4
+fn matches_mp4_signature(sequence: &[u8]) -> bool {
+ // 1. Let sequence be the byte sequence to be matched, where sequence[s] is byte s in sequence and sequence[0] is the first byte in sequence.
+
+ // 2. Let length be the number of bytes in sequence.
+ let length = sequence.len();
+
+ // 3. If length is less than 12, return false.
+ if length < 12 {
+ return false;
+ }
+
+ // 4. Let box-size be the four bytes from sequence[0] to sequence[3], interpreted as a 32-bit unsigned big-endian integer.
+ let box_size = u32::from_be_bytes([sequence[0], sequence[1], sequence[2], sequence[3]]) as usize;
+
+ // 5. If length is less than box-size or if box-size modulo 4 is not equal to 0, return false.
+ if length < box_size || !box_size.is_multiple_of(4) {
+ return false;
+ }
+
+ // 6. If the four bytes from sequence[4] to sequence[7] are not equal to 0x66 0x74 0x79 0x70 ("ftyp"), return false.
+ if &sequence[4..8] != b"\x66\x74\x79\x70" {
+ return false;
+ }
+
+ // 7. If the three bytes from sequence[8] to sequence[10] are equal to 0x6D 0x70 0x34 ("mp4"), return true.
+ if &sequence[8..11] == b"\x6D\x70\x34" {
+ return true;
+ }
+
+ // 8. Let bytes-read be 16.
+ let mut bytes_read = 16;
+
+ // 9. While bytes-read is less than box-size, continuously loop through these steps:
+ while bytes_read < box_size {
+ // 1. If the three bytes from sequence[bytes-read] to sequence[bytes-read + 2] are equal to 0x6D 0x70 0x34 ("mp4"), return true.
+ if sequence.get(bytes_read..bytes_read + 3) == Some(b"\x6D\x70\x34") {
+ return true;
+ }
+
+ // 2. Increment bytes-read by 4.
+ bytes_read += 4;
+ }
+
+ // 10. Return false.
+ false
+}
+
+struct VintResult {
+ #[allow(dead_code)]
+ value: u64,
+ length: usize,
+}
+
+// https://mimesniff.spec.whatwg.org/#parse-a-vint
+fn parse_a_vint(sequence: &[u8], iter: usize) -> VintResult {
+ // To parse a vint on a byte sequence sequence of size length, starting at index iter use the following steps:
+ let sequence = &sequence[iter..];
+ let length = sequence.len();
+
+ // 1. let mask be 128.
+ let mut mask: u8 = 128;
+
+ // 2. Let max vint length be 8.
+ let max_vint_length = 8;
+
+ // 3. Let number size be 1.
+ let mut number_size = 1;
+
+ // 5. Let index be 0.
+ // NB: The spec declares this after step four, but it is needed before to use in the loop.
+ let mut index = 0;
+
+ // 4. While number size is less than max vint length, and less than length, continuously loop through these steps:
+ while number_size < max_vint_length && number_size < length {
+ // 1. If the sequence[index] & mask is not zero, abort these steps.
+ if sequence[index] & mask != 0 {
+ break;
+ }
+
+ // 2. Let mask be the value of mask >> 1.
+ mask >>= 1;
+
+ // 3. Increment number size by one.
+ number_size += 1;
+ }
+
+ // 6. Let parsed number be sequence[index] & ~mask.
+ let mut parsed_number = u64::from(sequence[index] & !mask);
+
+ // 7. Increment index by one.
+ index += 1;
+
+ // 8. Let bytes remaining be the value of number size - 1.
+ let mut bytes_remaining = number_size - 1;
+
+ // 9. While bytes remaining is not zero, execute there steps:
+ while bytes_remaining != 0 {
+ // 1. Let parsed number be parsed number << 8.
+ parsed_number <<= 8;
+
+ // 2. Let parsed number be parsed number | sequence[index].
+ parsed_number |= u64::from(sequence[index]);
+
+ // 3. Increment index by one.
+ index += 1;
+
+ // 4. If index is greater or equal than length, abort these steps.
+ if index >= length {
+ break;
+ }
+
+ // 5. Decrement bytes remaining by one.
+ bytes_remaining -= 1;
+ }
+
+ // 10. Return parsed number and number size
+ VintResult {
+ value: parsed_number,
+ length: number_size,
+ }
+}
+
+// https://mimesniff.spec.whatwg.org/#signature-for-webm
+fn matches_webm_signature(sequence: &[u8]) -> bool {
+ // 1. Let sequence be the byte sequence to be matched, where sequence[s] is byte s in sequence and sequence[0] is the first byte in sequence.
+
+ // 2. Let length be the number of bytes in sequence.
+ let length = sequence.len();
+
+ // 3. If length is less than 4, return false.
+ if length < 4 {
+ return false;
+ }
+
+ // 4. If the four bytes from sequence[0] to sequence[3], are not equal to 0x1A 0x45 0xDF 0xA3, return false.
+ if !sequence.starts_with(b"\x1A\x45\xDF\xA3") {
+ return false;
+ }
+
+ // 5. let iter be 4.
+ let mut iter = 4;
+
+ // 6. While iter is less than length and iter is less than 38, continuously loop through these steps:
+ while iter < length && iter < 38 {
+ // 1. If the two bytes from sequence[iter] to sequence[iter + 1] are equal to 0x42 0x82,
+ if sequence.get(iter..iter + 2) == Some(b"\x42\x82") {
+ // 1. increment iter by 2.
+ iter += 2;
+
+ // 2. If iter is greater or equal than length, abort these steps.
+ if iter >= length {
+ break;
+ }
+
+ // 3. Let number size be the result of parsing a vint starting at sequence[iter].
+ let number_size = parse_a_vint(sequence, iter).length;
+
+ // 4. Increment iter by number size.
+ iter += number_size;
+
+ // 5. If iter is greater than or equal to length - 4, abort these steps.
+ if iter >= length - 4 {
+ break;
+ }
+
+ // 6. Let matched be the result of matching a padded sequence 0x77 0x65 0x62 0x6D ("webm") on sequence at offset iter.
+ let matched = &sequence[iter..iter + 4] == b"\x77\x65\x62\x6D";
+
+ // 7. If matched is true, abort these steps and return true.
+ if matched {
+ return true;
+ }
+ }
+
+ // 2. Increment iter by 1.
+ iter += 1;
+ }
+
+ // 7. Return false.
+ false
+}
+
+// https://mimesniff.spec.whatwg.org/#match-an-mp3-header
+fn match_mp3_header(sequence: &[u8], s: usize) -> bool {
+ // To match an mp3 header, using a byte sequence sequence of length length at offset s execute these steps:
+ let length = sequence.len();
+
+ // 1. If length is less than 4, return false.
+ if length - s < 4 {
+ return false;
+ }
+
+ // 2. If sequence[s] is not equal to 0xff and sequence[s + 1] & 0xe0 is not equal to 0xe0, return false.
+ // NB: The spec is wrong here, this should be or.
+ if sequence[s] != 0xff || sequence[s + 1] & 0xe0 != 0xe0 {
+ return false;
+ }
+
+ // 3. Let layer be the result of sequence[s + 1] & 0x06 >> 1.
+ let layer = (sequence[s + 1] & 0x06) >> 1;
+
+ // 4. If layer is 0, return false.
+ if layer == 0 {
+ return false;
+ }
+
+ // 5. Let bit-rate be sequence[s + 2] & 0xf0 >> 4.
+ let bit_rate = (sequence[s + 2] & 0xf0) >> 4;
+
+ // 6. If bit-rate is 15, return false.
+ if bit_rate == 15 {
+ return false;
+ }
+
+ // 7. Let sample-rate be sequence[s + 2] & 0x0c >> 2.
+ let sample_rate = (sequence[s + 2] & 0x0c) >> 2;
+
+ // 8. If sample-rate is 3, return false.
+ if sample_rate == 3 {
+ return false;
+ }
+
+ // FIXME: 9. Let freq be the value given by sample-rate in the table sample-rate.
+
+ // FIXME: 10. Let final-layer be the result of 4 - (sequence[s + 1]).
+
+ // FIXME: 11. If final-layer & 0x06 >> 1 is not 3, return false.
+
+ // 12. Return true.
+ true
+}
+
+// https://mimesniff.spec.whatwg.org/#matches-the-signature-for-mp3-without-id3
+// FIXME: Instead of implementing full spec, only matches single-frame mp3 header due to the issues stated at (https://github.com/whatwg/mimesniff/issues/70)
+fn matches_mp3_no_id3_signature(sequence: &[u8]) -> bool {
+ // 1. Let sequence be the byte sequence to be matched, where sequence[s] is byte s in sequence and sequence[0] is the first byte in sequence.
+
+ // FIXME: 2. Let length be the number of bytes in sequence.
+
+ // FIXME: 3. Initialize s to 0.
+
+ // 4. If the result of the operation match mp3 header is false, return false.
+ if !match_mp3_header(sequence, 0) {
+ return false;
+ }
+
+ // FIXME: 5. Parse an mp3 frame on sequence at offset s
+
+ // FIXME: 6. Let skipped-bytes the return value of the execution of mp3 framesize computation
+
+ // FIXME: 7. If skipped-bytes is less than 4, or skipped-bytes is greater than s - length, return false.
+
+ // FIXME: 8. Increment s by skipped-bytes.
+
+ // FIXME: 9. If the result of the operation match mp3 header operation is false, return false, else, return true.
+ true
+}
+
+// https://mimesniff.spec.whatwg.org/#matching-an-audio-or-video-type-pattern
+fn match_an_audio_or_video_type_pattern(input: &[u8]) -> Option<MimeType> {
+ // 1. Execute the following steps for each row row in the following table:
+ const PATTERN_TABLE: [BytePatternTableRow; 6] = [
+ // The string "FORM" followed by four bytes followed by the string "AIFF", the AIFF signature.
+ row(
+ b"\x46\x4F\x52\x4D\x00\x00\x00\x00\x41\x49\x46\x46",
+ b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "audio/aiff",
+ ),
+ // The string "ID3", the ID3v2-tagged MP3 signature.
+ row(b"\x49\x44\x33", b"\xFF\xFF\xFF", NO_IGNORED_BYTES, "audio/mpeg"),
+ // The string "OggS" followed by NUL, the Ogg container signature.
+ row(
+ b"\x4F\x67\x67\x53\x00",
+ b"\xFF\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "application/ogg",
+ ),
+ // The string "MThd" followed by four bytes representing the number 6 in 32 bits (big-endian), the MIDI signature.
+ row(
+ b"\x4D\x54\x68\x64\x00\x00\x00\x06",
+ b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "audio/midi",
+ ),
+ // The string "RIFF" followed by four bytes followed by the string "AVI ", the AVI signature.
+ row(
+ b"\x52\x49\x46\x46\x00\x00\x00\x00\x41\x56\x49\x20",
+ b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "video/avi",
+ ),
+ // The string "RIFF" followed by four bytes followed by the string "WAVE", the WAVE signature.
+ row(
+ b"\x52\x49\x46\x46\x00\x00\x00\x00\x57\x41\x56\x45",
+ b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "audio/wave",
+ ),
+ ];
+ if let Some(matched_type) = match_a_pattern_table(input, &PATTERN_TABLE) {
+ return Some(matched_type);
+ }
+
+ // 2. If input matches the signature for MP4, return "video/mp4".
+ if matches_mp4_signature(input) {
+ return Some(mime_type("video/mp4"));
+ }
+
+ // 3. If input matches the signature for WebM, return "video/webm".
+ if matches_webm_signature(input) {
+ return Some(mime_type("video/webm"));
+ }
+
+ // 4. If input matches the signature for MP3 without ID3, return "audio/mpeg".
+ if matches_mp3_no_id3_signature(input) {
+ return Some(mime_type("audio/mpeg"));
+ }
+
+ // 5. Return undefined.
+ None
+}
+
+// https://mimesniff.spec.whatwg.org/#matching-a-font-type-pattern
+fn match_a_font_type_pattern(input: &[u8]) -> Option<MimeType> {
+ const PATTERN_TABLE: [BytePatternTableRow; 6] = [
+ // 34 bytes followed by the string "LP", the Embedded OpenType signature.
+ row(
+ b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x4C\x50",
+ b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "application/vnd.ms-fontobject",
+ ),
+ // 4 bytes representing the version number 1.0, a TrueType signature.
+ row(b"\x00\x01\x00\x00", b"\xFF\xFF\xFF\xFF", NO_IGNORED_BYTES, "font/ttf"),
+ // The string "OTTO", the OpenType signature.
+ row(b"\x4F\x54\x54\x4F", b"\xFF\xFF\xFF\xFF", NO_IGNORED_BYTES, "font/otf"),
+ // The string "ttcf", the TrueType Collection signature.
+ row(b"\x74\x74\x63\x66", b"\xFF\xFF\xFF\xFF", NO_IGNORED_BYTES, "font/collection"),
+ // The string "wOFF", the Web Open Font Format 1.0 signature.
+ row(b"\x77\x4F\x46\x46", b"\xFF\xFF\xFF\xFF", NO_IGNORED_BYTES, "font/woff"),
+ // The string "wOF2", the Web Open Font Format 2.0 signature.
+ row(b"\x77\x4F\x46\x32", b"\xFF\xFF\xFF\xFF", NO_IGNORED_BYTES, "font/woff2"),
+ ];
+ match_a_pattern_table(input, &PATTERN_TABLE)
+}
+
+// https://mimesniff.spec.whatwg.org/#matching-an-archive-type-pattern
+fn match_an_archive_type_pattern(input: &[u8]) -> Option<MimeType> {
+ const PATTERN_TABLE: [BytePatternTableRow; 3] = [
+ // The GZIP archive signature.
+ row(b"\x1F\x8B\x08", b"\xFF\xFF\xFF", NO_IGNORED_BYTES, "application/x-gzip"),
+ // The string "PK" followed by ETX EOT, the ZIP archive signature.
+ row(
+ b"\x50\x4B\x03\x04",
+ b"\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "application/zip",
+ ),
+ // The string "Rar!" followed by SUB BEL NUL, the RAR 4.x archive signature.
+ row(
+ b"\x52\x61\x72\x21\x1A\x07\x00",
+ b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "application/x-rar-compressed",
+ ),
+ ];
+ match_a_pattern_table(input, &PATTERN_TABLE)
+}
+
+// https://mimesniff.spec.whatwg.org/#resource
+struct Resource<'a> {
+ // https://mimesniff.spec.whatwg.org/#supplied-mime-type
+ // A supplied MIME type, the MIME type determined by the supplied MIME type detection algorithm.
+ supplied_mime_type: Option<MimeType>,
+
+ // https://mimesniff.spec.whatwg.org/#check-for-apache-bug-flag
+ // A check-for-apache-bug flag, which defaults to unset.
+ check_for_apache_bug_flag: bool,
+
+ // https://mimesniff.spec.whatwg.org/#no-sniff-flag
+ // A no-sniff flag, which defaults to set if the user agent does not wish to perform sniffing on the resource and unset otherwise.
+ no_sniff: bool,
+
+ // https://mimesniff.spec.whatwg.org/#computed-mime-type
+ // A computed MIME type, the MIME type determined by the MIME type sniffing algorithm.
+ computed_mime_type: MimeType,
+
+ // https://mimesniff.spec.whatwg.org/#resource-header
+ // A resource header is the byte sequence at the beginning of a resource, as determined by reading the resource header.
+ resource_header: &'a [u8],
+}
+
+/// The computed MIME type of the resource whose data is `data`.
+pub fn sniff(
+ data: &[u8],
+ sniffing_context: SniffingContext,
+ scheme: &str,
+ supplied_type: Option<MimeType>,
+ no_sniff: bool,
+) -> MimeType {
+ let mut resource = Resource {
+ supplied_mime_type: None,
+ check_for_apache_bug_flag: false,
+ no_sniff,
+ // NB: Non-standard but for cases where pattern matching fails, let's fall back to the safest MIME type.
+ computed_mime_type: mime_type("application/octet-stream"),
+ resource_header: read_the_resource_header(data),
+ };
+ resource.supplied_mime_type_detection_algorithm(scheme, supplied_type);
+ resource.context_specific_sniffing_algorithm(sniffing_context);
+ resource.computed_mime_type
+}
+
+// https://mimesniff.spec.whatwg.org/#read-the-resource-header
+fn read_the_resource_header(data: &[u8]) -> &[u8] {
+ // 1. Let buffer be a byte sequence.
+ // 2. Read bytes of the resource into buffer until one of the following conditions is met:
+ // - the end of the resource is reached.
+ // - the number of bytes in buffer is greater than or equal to 1445.
+ // - a reasonable amount of time has elapsed, as determined by the user agent.
+ // FIXME: The spec expects us to be reading from a stream. Reimplement this spec step once
+ // we have greater support for streaming in areas that calls on this API.
+ const MAX_SNIFF_SIZE: usize = 1445;
+
+ // 3. The resource header is buffer.
+ &data[..data.len().min(MAX_SNIFF_SIZE)]
+}
+
+impl Resource<'_> {
+ // https://mimesniff.spec.whatwg.org/#supplied-mime-type-detection-algorithm
+ // NB: Parameters are non-standard.
+ fn supplied_mime_type_detection_algorithm(&mut self, scheme: &str, supplied_type: Option<MimeType>) {
+ // 1. Let supplied-type be null.
+ // 2. If the resource is retrieved via HTTP, execute the following steps:
+ // 1. If one or more Content-Type headers are associated with the resource, execute the following steps:
+ // 1. Set supplied-type to the value of the last Content-Type header associated with the resource.
+ // 2. Set the check-for-apache-bug flag if supplied-type is exactly equal to one of the values in the following table:
+ // NB: Non-standard but this algorithm expects the caller to handle step 2.1.1.
+ if let Some(supplied_type) = &supplied_type
+ && matches!(scheme, "http" | "https")
+ {
+ // NB: The spec expects a space between the semicolon and the start of the charset parameter. However, we will
+ // lose this space because MimeType::parse() ignores any spaces found there.
+ const APACHE_BUG_MIME_TYPES: [&str; 4] = [
+ "text/plain",
+ "text/plain;charset=ISO-8859-1",
+ "text/plain;charset=iso-8859-1",
+ "text/plain;charset=UTF-8",
+ ];
+
+ let serialized_supplied_type = supplied_type.serialize();
+ self.check_for_apache_bug_flag = APACHE_BUG_MIME_TYPES.contains(&serialized_supplied_type.as_str());
+ }
+
+ // 3. If the resource is retrieved directly from the file system, set supplied-type
+ // to the MIME type provided by the file system.
+ // 4. If the resource is retrieved via another protocol (such as FTP), set
+ // supplied-type to the MIME type as determined by that protocol, if any.
+ // 5. If supplied-type is not a MIME type, the supplied MIME type is undefined.
+ // Abort these steps.
+ // 6. The supplied MIME type is supplied-type.
+ // NB: The expectation is for the caller to handle these spec steps.
+ self.supplied_mime_type = supplied_type;
+ }
+
+ // https://mimesniff.spec.whatwg.org/#mime-type-sniffing-algorithm
+ fn mime_type_sniffing_algorithm(&mut self) {
+ // 1. If the supplied MIME type is an XML MIME type or HTML MIME type, the computed MIME type is the supplied MIME type.
+ // Abort these steps.
+ if let Some(supplied_mime_type) = &self.supplied_mime_type
+ && (supplied_mime_type.essence().is_xml() || supplied_mime_type.essence().is_html())
+ {
+ self.computed_mime_type = supplied_mime_type.clone();
+ return;
+ }
+
+ // 2. If the supplied MIME type is undefined or if the supplied MIME type’s essence
+ // is "unknown/unknown", "application/unknown", or "*/*", execute the rules for
+ // identifying an unknown MIME type with the sniff-scriptable flag equal to the
+ // inverse of the no-sniff flag and abort these steps.
+ let Some(supplied_mime_type) = self.supplied_mime_type.clone().filter(|supplied_mime_type| {
+ let essence = supplied_mime_type.essence();
+ !matches!(
+ (essence.type_, essence.subtype),
+ ("unknown" | "application", "unknown") | ("*", "*")
+ )
+ }) else {
+ self.computed_mime_type = self.rules_for_identifying_an_unknown_mime_type(!self.no_sniff);
+ return;
+ };
+
+ // 3. If the no-sniff flag is set, the computed MIME type is the supplied MIME type.
+ // Abort these steps.
+ if self.no_sniff {
+ self.computed_mime_type = supplied_mime_type;
+ return;
+ }
+
+ // 4. If the check-for-apache-bug flag is set, execute the rules for distinguishing
+ // if a resource is text or binary and abort these steps.
+ if self.check_for_apache_bug_flag {
+ self.rules_for_distinguishing_if_a_resource_is_text_or_binary();
+ return;
+ }
+
+ // FIXME: 5. If the supplied MIME type is an image MIME type supported by the user agent, let matched-type be
+ // the result of executing the image type pattern matching algorithm with the resource header as
+ // the byte sequence to be matched.
+
+ // 6. If matched-type is not undefined, the computed MIME type is matched-type.
+ // Abort these steps.
+
+ // FIXME: 7. If the supplied MIME type is an audio or video MIME type supported by the user agent, let matched-type be
+ // the result of executing the audio or video type pattern matching algorithm with the resource header as
+ // the byte sequence to be matched.
+
+ // 8. If matched-type is not undefined, the computed MIME type is matched-type.
+ // Abort these steps.
+
+ // 9. The computed MIME type is the supplied MIME type.
+ self.computed_mime_type = supplied_mime_type;
+ }
+
+ // https://mimesniff.spec.whatwg.org/#rules-for-identifying-an-unknown-mime-type
+ fn rules_for_identifying_an_unknown_mime_type(&self, sniff_scriptable: bool) -> MimeType {
+ // 1. If the sniff-scriptable flag is set, execute the following steps for each row row in the following table:
+ if sniff_scriptable {
+ const PATTERN_TABLE: [BytePatternTableRow; 19] = [
+ // The case-insensitive string "<!DOCTYPE HTML" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x21\x44\x4F\x43\x54\x59\x50\x45\x20\x48\x54\x4D\x4C\x00",
+ b"\xFF\xFF\xDF\xDF\xDF\xDF\xDF\xDF\xDF\xFF\xDF\xDF\xDF\xDF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The case-insensitive string "<HTML" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x48\x54\x4D\x4C\x00",
+ b"\xFF\xDF\xDF\xDF\xDF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The case-insensitive string "<HEAD" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x48\x45\x41\x44\x00",
+ b"\xFF\xDF\xDF\xDF\xDF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The case-insensitive string "<SCRIPT" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x53\x43\x52\x49\x50\x54\x00",
+ b"\xFF\xDF\xDF\xDF\xDF\xDF\xDF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The case-insensitive string "<IFRAME" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x49\x46\x52\x41\x4D\x45\x00",
+ b"\xFF\xDF\xDF\xDF\xDF\xDF\xDF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The case-insensitive string "<H1" followed by a tag-terminating byte.
+ tag_terminated_row(b"\x3C\x48\x31\x00", b"\xFF\xDF\xFF\xFF", WHITESPACE_BYTES, "text/html"),
+ // The case-insensitive string "<DIV" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x44\x49\x56\x00",
+ b"\xFF\xDF\xDF\xDF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The case-insensitive string "<FONT" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x46\x4F\x4E\x54\x00",
+ b"\xFF\xDF\xDF\xDF\xDF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The case-insensitive string "<TABLE" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x54\x41\x42\x4C\x45\x00",
+ b"\xFF\xDF\xDF\xDF\xDF\xDF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The case-insensitive string "<A" followed by a tag-terminating byte.
+ tag_terminated_row(b"\x3C\x41\x00", b"\xFF\xDF\xFF", WHITESPACE_BYTES, "text/html"),
+ // The case-insensitive string "<STYLE" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x53\x54\x59\x4C\x45\x00",
+ b"\xFF\xDF\xDF\xDF\xDF\xDF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The case-insensitive string "<TITLE" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x54\x49\x54\x4C\x45\x00",
+ b"\xFF\xDF\xDF\xDF\xDF\xDF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The case-insensitive string "<B" followed by a tag-terminating byte.
+ tag_terminated_row(b"\x3C\x42\x00", b"\xFF\xDF\xFF", WHITESPACE_BYTES, "text/html"),
+ // The case-insensitive string "<BODY" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x42\x4F\x44\x59\x00",
+ b"\xFF\xDF\xDF\xDF\xDF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The case-insensitive string "<BR" followed by a tag-terminating byte.
+ tag_terminated_row(b"\x3C\x42\x52\x00", b"\xFF\xDF\xDF\xFF", WHITESPACE_BYTES, "text/html"),
+ // The case-insensitive string "<P" followed by a tag-terminating byte.
+ tag_terminated_row(b"\x3C\x50\x00", b"\xFF\xDF\xFF", WHITESPACE_BYTES, "text/html"),
+ // The string "<!--" followed by a tag-terminating byte.
+ tag_terminated_row(
+ b"\x3C\x21\x2D\x2D\x00",
+ b"\xFF\xFF\xFF\xFF\xFF",
+ WHITESPACE_BYTES,
+ "text/html",
+ ),
+ // The string "<?xml".
+ row(
+ b"\x3C\x3F\x78\x6D\x6C",
+ b"\xFF\xFF\xFF\xFF\xFF",
+ WHITESPACE_BYTES,
+ "text/xml",
+ ),
+ // The string "%PDF-", the PDF signature.
+ row(
+ b"\x25\x50\x44\x46\x2D",
+ b"\xFF\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "application/pdf",
+ ),
+ ];
+
+ // 1. Let patternMatched be the result of the pattern matching algorithm given resource’s resource header,
+ // the value in the first column of row, the value in the second column of row, and the value in the
+ // third column of row.
+ // 2. If patternMatched is true, return the value in the fourth column of row.
+ if let Some(matched_type) = match_a_pattern_table(self.resource_header, &PATTERN_TABLE) {
+ return matched_type;
+ }
+ }
+
+ // 2. Execute the following steps for each row row in the following table:
+ const PATTERN_TABLE: [BytePatternTableRow; 4] = [
+ // The string "%!PS-Adobe-", the PostScript signature.
+ row(
+ b"\x25\x21\x50\x53\x2D\x41\x64\x6F\x62\x65\x2D",
+ b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF",
+ NO_IGNORED_BYTES,
+ "application/postscript",
+ ),
+ // UTF-16BE BOM
+ row(b"\xFE\xFF\x00\x00", b"\xFF\xFF\x00\x00", NO_IGNORED_BYTES, "text/plain"),
+ // UTF-16LE BOM
+ row(b"\xFF\xFE\x00\x00", b"\xFF\xFF\x00\x00", NO_IGNORED_BYTES, "text/plain"),
+ // UTF-8 BOM
+ row(b"\xEF\xBB\xBF\x00", b"\xFF\xFF\xFF\x00", NO_IGNORED_BYTES, "text/plain"),
+ ];
+
+ // 1. Let patternMatched be the result of the pattern matching algorithm given resource’s resource header,
+ // the value in the first column of row, the value in the second column of row, and the value in the
+ // third column of row.
+ // 2. If patternMatched is true, return the value in the fourth column of row.
+ if let Some(matched_type) = match_a_pattern_table(self.resource_header, &PATTERN_TABLE) {
+ return matched_type;
+ }
+
+ // 3. Let matchedType be the result of executing the image type pattern matching algorithm given resource’s resource header.
+ // 4. If matchedType is not undefined, return matchedType.
+ if let Some(matched_type) = match_an_image_type_pattern(self.resource_header) {
+ return matched_type;
+ }
+
+ // 5. Set matchedType to the result of executing the audio or video type pattern matching algorithm given resource’s resource header.
+ // 6. If matchedType is not undefined, return matchedType.
+ if let Some(matched_type) = match_an_audio_or_video_type_pattern(self.resource_header) {
+ return matched_type;
+ }
+
+ // 7. Set matchedType to the result of executing the archive type pattern matching algorithm given resource’s resource header.
+ // 8. If matchedType is not undefined, return matchedType.
+ if let Some(matched_type) = match_an_archive_type_pattern(self.resource_header) {
+ return matched_type;
+ }
+
+ // 9. If resource’s resource header contains no binary data bytes, return "text/plain".
+ if !self.resource_header.iter().copied().any(is_binary_data_byte) {
+ return mime_type("text/plain");
+ }
+
+ // 10. Return "application/octet-stream".
+ mime_type("application/octet-stream")
+ }
+
+ // https://mimesniff.spec.whatwg.org/#sniffing-a-mislabeled-binary-resource
+ fn rules_for_distinguishing_if_a_resource_is_text_or_binary(&mut self) {
+ // 1. Let length be the number of bytes in the resource header.
+ let length = self.resource_header.len();
+
+ // 2. If length is greater than or equal to 2 and the first 2 bytes of the
+ // resource header are equal to 0xFE 0xFF (UTF-16BE BOM) or 0xFF 0xFE (UTF-16LE BOM), the computed MIME type is "text/plain".
+ // Abort these steps.
+ if length >= 2
+ && (self.resource_header.starts_with(b"\xFE\xFF") || self.resource_header.starts_with(b"\xFF\xFE"))
+ {
+ self.computed_mime_type = mime_type("text/plain");
+ return;
+ }
+
+ // 3. If length is greater than or equal to 3 and the first 3 bytes of the resource header are equal to 0xEF 0xBB 0xBF (UTF-8 BOM),
+ // the computed MIME type is "text/plain".
+ // Abort these steps.
+ if length >= 3 && self.resource_header.starts_with(b"\xEF\xBB\xBF") {
+ self.computed_mime_type = mime_type("text/plain");
+ return;
+ }
+
+ // 4. If the resource header contains no binary data bytes, the computed MIME type is "text/plain".
+ // Abort these steps.
+ if !self.resource_header.iter().copied().any(is_binary_data_byte) {
+ self.computed_mime_type = mime_type("text/plain");
+ }
+
+ // 5. The computed MIME type is "application/octet-stream".
+ // NB: This is the default MIME type of the computed MIME type.
+ }
+
+ // https://mimesniff.spec.whatwg.org/#context-specific-sniffing-algorithm
+ fn context_specific_sniffing_algorithm(&mut self, sniffing_context: SniffingContext) {
+ // A context-specific sniffing algorithm determines the computed MIME type of a resource only if
+ // the resource is a MIME type relevant to a particular context.
+ if matches!(sniffing_context, SniffingContext::None | SniffingContext::Browsing) {
+ // https://mimesniff.spec.whatwg.org/#sniffing-in-a-browsing-context
+ // Use the MIME type sniffing algorithm.
+ self.mime_type_sniffing_algorithm();
+ return;
+ }
+
+ // NB: Non-standard but if the client expects us to not sniff, we shouldn't be doing any
+ // context-specific sniffing if we don't have to.
+ if self.no_sniff
+ && let Some(supplied_mime_type) = &self.supplied_mime_type
+ {
+ self.computed_mime_type = supplied_mime_type.clone();
+ return;
+ }
+
+ match sniffing_context {
+ SniffingContext::Image => self.rules_for_sniffing_images_specifically(),
+ SniffingContext::AudioOrVideo => self.rules_for_sniffing_audio_or_video_specifically(),
+ SniffingContext::Font => self.rules_for_sniffing_fonts_specifically(),
+ SniffingContext::TextOrBinary => self.rules_for_distinguishing_if_a_resource_is_text_or_binary(),
+ SniffingContext::None | SniffingContext::Browsing => unreachable!(),
+ }
+ }
+
+ // https://mimesniff.spec.whatwg.org/#sniffing-in-an-image-context
+ fn rules_for_sniffing_images_specifically(&mut self) {
+ // 1. If the supplied MIME type is an XML MIME type, the computed MIME type is the supplied MIME type.
+ // Abort these steps.
+ // NB: Non-standard but due to the mime type detection algorithm we need this sanity check.
+ if let Some(supplied_mime_type) = &self.supplied_mime_type
+ && supplied_mime_type.essence().is_xml()
+ {
+ self.computed_mime_type = supplied_mime_type.clone();
+ return;
+ }
+
+ // 2. Let image-type-matched be the result of executing the image type pattern matching algorithm with
+ // the resource header as the byte sequence to be matched.
+ // 3. If image-type-matched is not undefined, the computed MIME type is image-type-matched.
+ // Abort these steps.
+ if let Some(matched_type) = match_an_image_type_pattern(self.resource_header) {
+ self.computed_mime_type = matched_type;
+ return;
+ }
+
+ // 4. The computed MIME type is the supplied MIME type.
+ // NB: Non-standard but due to the mime type detection algorithm we need this sanity check.
+ // If the supplied mime type is undefined, we use computed mime type's default value.
+ if let Some(supplied_mime_type) = &self.supplied_mime_type {
+ self.computed_mime_type = supplied_mime_type.clone();
+ }
+ }
+
+ // https://mimesniff.spec.whatwg.org/#sniffing-in-an-audio-or-video-context
+ fn rules_for_sniffing_audio_or_video_specifically(&mut self) {
+ // 1. If the supplied MIME type is an XML MIME type, the computed MIME type is the supplied MIME type.
+ // Abort these steps.
+ // NB: Non-standard but due to the mime type detection algorithm we need this sanity check.
+ if let Some(supplied_mime_type) = &self.supplied_mime_type
+ && supplied_mime_type.essence().is_xml()
+ {
+ self.computed_mime_type = supplied_mime_type.clone();
+ return;
+ }
+
+ // 2. Let audio-or-video-type-matched be the result of executing the audio or video type pattern matching
+ // algorithm with the resource header as the byte sequence to be matched.
+ // 3. If audio-or-video-type-matched is not undefined, the computed MIME type is audio-or-video-type-matched.
+ // Abort these steps.
+ if let Some(matched_type) = match_an_audio_or_video_type_pattern(self.resource_header) {
+ self.computed_mime_type = matched_type;
+ return;
+ }
+
+ // 4. The computed MIME type is the supplied MIME type.
+ // NB: Non-standard but due to the mime type detection algorithm we need this sanity check.
+ // If the supplied mime type is undefined, we use computed mime type's default value.
+ if let Some(supplied_mime_type) = &self.supplied_mime_type {
+ self.computed_mime_type = supplied_mime_type.clone();
+ }
+ }
+
+ // https://mimesniff.spec.whatwg.org/#sniffing-in-a-font-context
+ fn rules_for_sniffing_fonts_specifically(&mut self) {
+ // 1. If the supplied MIME type is an XML MIME type, the computed MIME type is the supplied MIME type.
+ // Abort these steps.
+ // NB: Non-standard but due to the mime type detection algorithm we need this sanity check.
+ if let Some(supplied_mime_type) = &self.supplied_mime_type
+ && supplied_mime_type.essence().is_xml()
+ {
+ self.computed_mime_type = supplied_mime_type.clone();
+ return;
+ }
+
+ // 2. Let font-type-matched be the result of executing the font type pattern matching algorithm with the
+ // resource header as the byte sequence to be matched.
+ // 3. If font-type-matched is not undefined, the computed MIME type is font-type-matched.
+ // Abort these steps.
+ if let Some(matched_type) = match_a_font_type_pattern(self.resource_header) {
+ self.computed_mime_type = matched_type;
+ return;
+ }
+
+ // 4. The computed MIME type is the supplied MIME type.
+ // NB: Non-standard but due to the mime type detection algorithm we need this sanity check.
+ // If the supplied mime type is undefined, we use computed mime type's default value.
+ if let Some(supplied_mime_type) = &self.supplied_mime_type {
+ self.computed_mime_type = supplied_mime_type.clone();
+ }
+ }
+}
diff --git a/Tests/LibWeb/TestMimeSniff.cpp b/Tests/LibWeb/TestMimeSniff.cpp
index a3233a6d1cc..06da60b5255 100644
--- a/Tests/LibWeb/TestMimeSniff.cpp
+++ b/Tests/LibWeb/TestMimeSniff.cpp
@@ -10,7 +10,7 @@
#include <LibTest/TestCase.h>
#include <LibWebCommon/MimeSniff/MimeType.h>
-#include <LibWeb/MimeSniff/Resource.h>
+#include <LibWebCommon/MimeSniff/Resource.h>
TEST_CASE(parse_mime_type_from_utf16)
{