S006: YouTube loads (HTTP/2 header limit), basics smoke, Escape leaves page full screen

servo-net 0.7.0 keeps hyper's 16 KiB HTTP/2 header list limit; YouTube sends
~19 KiB, so the stream was reset and Servo showed SendRequest. vendor/servo-net
raises it to 256 KiB (D-012).
Escape went to the page only in full screen (inverted check): keys::page_gets_key.
tests/smoke/basics.txt: tabs, navigation, address bar, find, zoom, full screen,
_blank, pop-up, new window. Selftest expect/locate, pagetype {escape}.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-12 08:20:51 -06:00
commit a915040a0a
63 changed files with 30792 additions and 15 deletions

2
Cargo.lock generated
View file

@ -8051,8 +8051,6 @@ dependencies = [
[[package]]
name = "servo-net"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98af1ef87ba1355f3fae135c4b4ff26b52b75bf5eea1802751ecf3ba5ce65f15"
dependencies = [
"async-compression",
"async-recursion",

View file

@ -92,5 +92,8 @@ opt-level = 2
# epaint 0.37.0 panics when Servo's canvas enables vello_cpu/multithreading; the vendored copy renders glyphs
# single-threaded (vendor/epaint/src/text/font_face.rs, end of file). Drop when egui ships a fix.
# servo-net 0.7.0 keeps hyper's 16 KiB HTTP/2 header limit, which breaks YouTube; the vendored copy raises it
# (vendor/servo-net/connector.rs, create_http_client). Drop when Servo sets it.
[patch.crates-io]
epaint = { path = "vendor/epaint" }
servo-net = { path = "vendor/servo-net" }

View file

@ -13,12 +13,12 @@ Check every row of FEATURES.md "Browser basics" works in the real app, fix what
## Steps
- [x] R4-05 CRITICAL first: web content takes no clicks/keys/context menu (DuckDuckGo); fix input forwarding to the WebView; regression smoke clicking a link and typing in a field on a local page
- [ ] Write smoke scripts covering: open/close/pin/mute/duplicate/reorder tabs, reopen closed, back/forward/reload/home, address bar URL vs search, find in page, zoom per site, full screen, new window
- [x] Write smoke scripts covering: open/close/pin/mute/duplicate/reorder tabs, reopen closed, back/forward/reload/home, address bar URL vs search, find in page, zoom per site, full screen, new window
- [ ] Add scripts for context menu, page dialogs (alert/confirm/prompt/select/file via local test pages), pop-ups/target=_blank, session restore across restart, single instance link forwarding
- [ ] Run them; for each failure fix the code in place and add a regression unit test where the logic is pure
- [ ] Check keyboard shortcuts from `keys.rs` with `do <action>` lines
- [ ] Mark each row in FEATURES.md `verified` or `broken: <why>` (with a PROGRESS 'Later' line for broken ones)
- [ ] R1-03/R1-12 YouTube: find why https://www.youtube.com/ fails with `client error (SendRequest)` (start in `src/net/` fetch/bridge path, not page JS), fix, regression test where pure
- [x] R1-03/R1-12 YouTube: find why https://www.youtube.com/ fails with `client error (SendRequest)` (start in `src/net/` fetch/bridge path, not page JS), fix, regression test where pure
- [ ] R1-14 user agent: set a mainstream Firefox/Chrome-like UA through Servo prefs, check per-site overrides
- [ ] R1-13 DuckDuckGo dark mode icons: check site `prefers-color-scheme`/`color-scheme` handling vs Nacre chrome icon colours, fix the side that's wrong
- [ ] R1-04/R1-14 site doctor checklist (no Tor/proxies): YouTube, Google sign-in page, captchas, DuckDuckGo, Reddit, GitHub, HTTP caching; fix in place or log as Servo limit; result list in PROGRESS

View file

@ -14,3 +14,4 @@
- D-009 — 2026-11-11 — Smoke runs open visibly on the user's screen (`SMOKE_VISIBLE=1 tools/smoke.sh …`, niri monitor DP-1, real GPU) while the user wants to watch; hidden Xvfb (D-005) stays the default and the fallback when no Wayland session is there. Visible runs still use a throwaway home/runtime dir and share only the Wayland socket. — The user asked to see what the sessions test. Bonus: real-GPU coverage. Shots are narrower (niri tiling), so don't compare pixel sizes with Xvfb shots. — every plan that runs smoke scripts
- D-010 — 2026-11-11 — egui's delayed repaints are honoured (repaint observer → `BrowserWindow::redraw_at` → `about_to_wait`) instead of every request redrawing at once; animations that want frames ask with `request_repaint` (every frame) or `request_repaint_after` (paced). The new tab page's settings sub-page is no longer linked from General; Customize on the page replaces it (the sub-page stays for editing shortcuts, opened by "Add shortcut"). — The NTP clock alone kept the window at the display rate; the user's reference has Customize on the page. — S019–S021 and anything that animates
- D-011 — 2026-11-12 — Privacy mode (R1-16: anti-fingerprinting, strict cookies, tracker blocking, Cover Your Tracks check, auto-on in incognito) and cookie theft protection (R1-19: Nacre-held cookies encrypted at rest with an OS-keyring key) get their own privacy plan, generated after S021 with /plan-generate; not part of S007. — The user chose it; both are large and touch hub, inject and store. — S007, the new privacy plan
- D-012 — 2026-11-12 — servo-net is vendored (`vendor/servo-net`, 0.7.0 + `http2_max_header_list_size(256 KiB)` in `connector.rs` `create_http_client`) via `[patch.crates-io]`. — hyper's 16 KiB HTTP/2 default rejects YouTube's ~19 KiB response headers; Servo can't configure it from the embedder. — any plan that upgrades Servo: drop the patch when servo-net sets the limit, re-run `tests/smoke/heavy-web.txt`

View file

@ -28,7 +28,7 @@ State tags: `[open]`, `[fixed <commit>]`, `[wontfix: reason]`. Severity: high /
- R1-01 [fixed 7b7e0ce] Every UI icon (tab close, toolbar buttons, NTP "Add" tile) renders as an empty box: icon font glyphs missing. Seen in smoke screenshots (tests/smoke/launch.txt). Severity: high. (from S003)
- R1-02 [fixed 7b7e0ce] New-tab clock text almost invisible (very light text on white). Severity: medium. (from S003)
- R1-03 [open] YouTube fails to load ("maybe javascript or something is missing"). Where: any youtube.com page. Reproduce: open https://www.youtube.com. Severity: high. Cause not investigated; goes to S006 (basics pass).
- R1-03 [fixed S006] YouTube fails to load ("maybe javascript or something is missing"). Where: any youtube.com page. Reproduce: open https://www.youtube.com. Severity: high. Cause not investigated; goes to S006 (basics pass). Fixed (S006): YouTube's HTTP/2 response headers (~19 KiB) were over hyper's 16 KiB default, which servo-net 0.7.0 keeps; the stream was reset (`REQUEST_HEADER_FIELDS_TOO_LARGE`) and Servo reported `SendRequest`. `vendor/servo-net` raises the limit to 256 KiB (D-012). Same failure without the bridge, so the bridge was not the cause.
- R1-04 [open] Captchas, proper caching "and everything" must work on real sites. Severity: medium. Verify in S006/S007.
- R1-05 [open] UI is "really basic"; the new-tab page isn't what the user was going for. Severity: medium. Phase 4 redesign; target in docs/UI-BRIEF.md.
- R1-06 [open] Wants the feel of the old Python Nacre (`nacre` in ~/.local/bin: dark Material-style lists of nacre:// pages, outlined icons), improved with animations and an "unslop" look, very user friendly. Severity: medium. Input for the Phase 4 redesign.
@ -38,7 +38,7 @@ State tags: `[open]`, `[fixed <commit>]`, `[wontfix: reason]`. Severity: high /
- R1-10 [fixed 773fc7d] Tab loading indicator: while a tab loads, its favicon spot shows a cookie-shaped (scalloped, M3 Expressive) progress ring, like the original Python Nacre's that the user liked: the stroke draws forward around the cookie outline, then retracts backwards, and keeps repeating while the whole shape spins smoothly; it morphs back into the favicon when loading ends. Motion setting respected (Motion off = static indicator). Here the original IS the reference: `draw_spinner` in `~/Documents/Apps/Nacre/nacre/widgets.py`, used by `tabs.py` (read only). Severity: medium. (user, after S020) → chrome follow-up with R1-09, before S021.
- R1-11 [fixed f99500f] Colours can't be changed after the welcome setup: once the user finished nacre://welcome, changing the browser colours (Settings → Appearance colour source / palette / custom) had no visible effect. Reproduce: fresh profile, finish the welcome flow, then change colours in Settings. Severity: high. (user, after S020) → first fix before S021 if quick, else S012. Cause found: an internal page typed into a web tab kept that site's theme-color, which won over palette picks under the Website source; the user's exact welcome path didn't reproduce (welcome + every Appearance control works in smoke).
- R1-11 detail [fixed S016 follow-up] "System accent" differed from the desktop on niri + caelestia-niri: Nacre read kdeglobals `AccentColor` (none there), then GNOME `accent-color` (`'red'`, also what the portal reports: #E62D42), which Caelestia never updates. The desktop's real colours are in `~/.local/state/caelestia/scheme.json` (primary `#e6b6f1`). Nacre now reads that file's `colours.primary` first. Nothing missing on the desktop side; optional: set the GNOME/portal accent too for other apps. Still read once at start: a new wallpaper needs a Nacre restart (Later).
- R1-12 [open] YouTube still doesn't open (same as R1-03; reconfirmed after the redesign). Severity: high. → S006.
- R1-12 [fixed S006] YouTube still doesn't open (same as R1-03; reconfirmed after the redesign). Severity: high. → S006.
- R1-13 [open] Dark mode: icons on DuckDuckGo (the page opened in the user's test) don't use the right colours. Unclear whether it's the site's own icons under dark mode (prefers-color-scheme / colour-scheme handling) or Nacre's chrome icons; check both. Severity: medium. (user) → S006.
- R1-14 [open] Site compatibility pass: "more things for sites to actually work right": a proper user agent (Servo 0.7 can set the UA through its preferences even though it can't add request headers; pick a mainstream Firefox/Chrome-like UA string, check per-site overrides), JavaScript features sites expect, and a general "doctor" pass over common sites (YouTube, Google sign-in, captchas, DuckDuckGo, Reddit, GitHub). Severity: high. (user) → S006/S007; extend S006 with a site-doctor checklist.
- R1-12 detail: the YouTube error page shows `client error (SendRequest)` for https://www.youtube.com/ (the request fails in Nacre's fetch/bridge path, not in page JS); start there.

View file

@ -52,7 +52,7 @@ Format: `R4-NN [state] what. Where. How to reproduce. Severity.`
R4-01 [wontfix: user's niri dotfiles do not export a KDE/GNOME scheme; Nacre keeps reading Caelestia, KDE, GNOME and the portal] System accent reported "can't find colour profile". Where: Settings → Appearance → System accent. Reproduce: throwaway profile, source System accent. Severity: low. The user will fix their desktop.
R4-02 [fixed fc0df2a] Duplicate toolbar icons: the shield and the globe (VPN) sat side by side. Where: right toolbar (screenshot 1.png). Fix: the VPN button is gone (also from Settings → toolbar choices); VPN state and switch are in the Protection flyout. Severity: low.
R4-03 [open] YouTube still does not load (= R1-12, R1-03). Where: https://www.youtube.com. Severity: high. → S006.
R4-03 [fixed S006] YouTube still does not load (= R1-12, R1-03). Where: https://www.youtube.com. Severity: high. → S006. Fixed: HTTP/2 header limit, see R1-12 in phase1.md.
R4-04 [open] Address bar has no inline autofill: typing "wikipe" should complete to "wikipedia.org" in the field with the rest selected; Right arrow or Enter accepts it; with no completion Enter goes to what was typed. Today only a dropdown (screenshot 2.png). Where: address bar. Severity: medium.
R4-05 [fixed S006] CRITICAL: websites do not work. DuckDuckGo loads but nothing can be clicked and there is no right-click menu on pages; input to web content seems broken. Where: any web page. Reproduce: open https://duckduckgo.com, click the search box or a link. Severity: critical. → S006 first. Fix: `window_input` used `is_pointer_over_egui`, which is true over the page (it sits in egui's central panel), so clicks and wheel never reached the WebView; now only floating layers (flyouts, menus, toasts) count. Selftest `click`/`rclick`/`pagescroll` now go through `window_input`; `tests/smoke/input.txt` fails on the old code.
R4-06 [open] Nacre's own right-click (context) menu on pages: nice icons, rounded, coloured (Material You). Where: web pages (and links, images, text, fields). Severity: medium.

View file

@ -1945,7 +1945,7 @@ impl App {
let typing_ui = egui_wants_keys && !win.page_focused;
let plain = !win.modifiers.control_key() && !win.modifiers.alt_key() && !win.modifiers.super_key();
let skip = typing_ui && plain || (action == crate::keys::Action::Stop && (dialog_open || win.ui.has_popup() || typing_ui));
if !skip && (crate::keys::reserved(action) || !(win.page_focused && plain && action == crate::keys::Action::Stop && win.fullscreen)) {
if !skip && !crate::keys::page_gets_key(action, win.page_focused && plain, win.fullscreen) {
if key.state == ElementState::Pressed {
self.run_in(window_id, Command::Action(action));
}

View file

@ -329,10 +329,25 @@ pub fn reserved(action: Action) -> bool {
matches!(action, Action::NewTab | Action::NewWindow | Action::NewIncognito | Action::CloseTab | Action::CloseWindow | Action::ReopenClosed | Action::NextTab | Action::PrevTab | Action::Quit | Action::FocusAddress | Action::Fullscreen)
}
/// A plain Escape (Stop) on a focused page goes to the page, so sites can close their own pop-ups, except in
/// full screen, where it leaves full screen as in other browsers. Every other shortcut stays the browser's.
pub fn page_gets_key(action: Action, page_focused_plain: bool, fullscreen: bool) -> bool {
!reserved(action) && action == Action::Stop && page_focused_plain && !fullscreen
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escape_on_page() {
assert!(page_gets_key(Action::Stop, true, false));
assert!(!page_gets_key(Action::Stop, true, true), "Escape leaves page full screen");
assert!(!page_gets_key(Action::Stop, false, false));
assert!(!page_gets_key(Action::Find, true, false));
assert!(!page_gets_key(Action::NewTab, true, false));
}
#[test]
fn parse_and_label() {
let s = Shortcut::parse("Ctrl+Shift+T").unwrap();

View file

@ -21,11 +21,14 @@
//! find <text>, download <url>, navigate <typed text>, mute, pin
//! js <script> run JavaScript in the current tab; the result goes to the log
//! assert <js expression> the expression must give true, else `ASSERT FAILED` in the log fails the smoke run
//! expect <pointer> <json> a value of the `status` JSON must equal json (e.g. `expect /tabs/1/pinned true`;
//! `/active/...` is the active tab, `/tab_count` the number of tabs)
//! click <x> <y> click in the page at CSS-ish pixel x,y (from the page's top left), through the
//! window's input path; `rclick` the same with the right button (context menu)
//! locate <css selector> find an element, scroll it into view; `click @` / `rclick @` then click its centre
//! pagescroll <x> <y> <dy> turn the wheel over the page at x,y (as `click`) by dy pixels (positive: down)
//! pagetype <text> type text into the page, if it has keyboard focus (after a `click` in a field);
//! `{enter}` in the text presses Enter
//! `{enter}` / `{escape}` in the text press Enter / Escape
//! pointer <x> <y> | off move the interface's pointer to x,y in the page area (new tab backgrounds follow it)
//! key <name> press and release a key in the interface: enter, escape, tab, space or a letter
//! tap <x> <y> click the interface (not the web page) at x,y in the window (logical px, as in a
@ -62,6 +65,8 @@ pub struct SelfTest {
pending_release: Option<egui::Pos2>,
/// `press` holds the button down; `drag` moves it, `release` lets it go here.
held: Option<egui::Pos2>,
/// The centre of the element the last `locate` found (page pixels), for `click @`.
located: std::sync::Arc<std::sync::Mutex<Option<(f64, f64)>>>,
}
impl SelfTest {
@ -70,7 +75,7 @@ impl SelfTest {
let text = std::fs::read_to_string(&path).ok()?;
let dir = path.parent().map(|p| p.to_owned()).unwrap_or_else(|| PathBuf::from("."));
let lines = text.lines().map(|l| l.trim().to_owned()).filter(|l| !l.is_empty() && !l.starts_with('#')).collect();
Some(SelfTest { lines, next: 0, wait_until: None, wait_load_until: None, dir, pending_shot: false, pending_release: None, held: None })
Some(SelfTest { lines, next: 0, wait_until: None, wait_load_until: None, dir, pending_shot: false, pending_release: None, held: None, located: Default::default() })
}
fn log(&self, text: &str) {
@ -188,6 +193,23 @@ impl App {
let text = serde_json::to_string_pretty(&self.selftest_status(window)).unwrap_or_default();
let _ = std::fs::write(dir.join(format!("{rest}.json")), text);
},
"expect" => {
// Compare one value of the `status` JSON, e.g. `expect /tabs/1/pinned true`; a mismatch fails the run.
let (pointer, want) = rest.split_once(char::is_whitespace).unwrap_or((rest, "null"));
let want: serde_json::Value = serde_json::from_str(want.trim()).unwrap_or_else(|_| serde_json::Value::String(want.trim().to_owned()));
let status = self.selftest_status(window);
// `/active/...` is the active tab.
let pointer = match pointer.strip_prefix("/active/") {
Some(tail) => format!("/tabs/{}/{tail}", status["active_index"]),
None => pointer.to_owned(),
};
let got = status.pointer(&pointer).cloned().unwrap_or(serde_json::Value::Null);
if got == want {
self.selftest_log(&format!("expect ok: {pointer} = {got}"));
} else {
self.selftest_log(&format!("ASSERT FAILED: {pointer} is {got}, expected {want}"));
}
},
"set" => {
let (pointer, value) = rest.split_once(char::is_whitespace).unwrap_or((rest, "null"));
let result = (|| -> Result<(), String> {
@ -311,10 +333,43 @@ impl App {
self.selftest_log("pagescroll: no web page in this tab");
}
},
"locate" => {
// Find the first element matching a CSS selector and scroll it into view, for `click @`.
let Some(web) = self.windows.get(&window).and_then(|w| w.active_webview()).cloned() else { return };
let Some(located) = self.selftest.as_ref().map(|t| t.located.clone()) else { return };
if let Ok(mut l) = located.lock() {
*l = None;
}
let log_path = dir.join("selftest.log");
let selector = serde_json::to_string(rest).unwrap_or_default();
let script = format!("(() => {{ const e = document.querySelector({selector}); if (!e) return null; e.scrollIntoView({{block: 'center'}}); const r = e.getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; }})()");
web.evaluate_javascript(script, move |result| {
use std::io::Write as _;
let point = match &result {
Ok(servo::JSValue::Array(v)) => match v.as_slice() {
[servo::JSValue::Number(x), servo::JSValue::Number(y)] => Some((*x, *y)),
_ => None,
},
_ => None,
};
if let Ok(mut l) = located.lock() {
*l = point;
}
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&log_path) {
let _ = writeln!(f, "locate -> {point:?}");
}
});
},
"click" | "rclick" => {
// Through the window's real input path (pointer over UI, dialogs, focus), as a user's click would.
// `click @` clicks where the last `locate` found its element.
let located = if rest.trim() == "@" { self.selftest.as_ref().and_then(|t| t.located.lock().ok().and_then(|l| *l)) } else { None };
if rest.trim() == "@" && located.is_none() {
self.selftest_log("ASSERT FAILED: click @ without a located element");
return;
}
let mut parts = rest.split_whitespace().filter_map(|p| p.parse::<f64>().ok());
let (x, y) = (parts.next().unwrap_or(0.0), parts.next().unwrap_or(0.0));
let (x, y) = located.unwrap_or((parts.next().unwrap_or(0.0), parts.next().unwrap_or(0.0)));
let pos = self.windows.get(&window).and_then(|win| {
let rect = win.page_rect?;
let scale = win.egui.egui_ctx.pixels_per_point() as f64;
@ -339,11 +394,17 @@ impl App {
match (takes, win.active_webview()) {
(true, Some(web)) => {
let mut keys: Vec<(keyboard_types::Key, keyboard_types::Code)> = Vec::new();
for (i, part) in rest.split("{enter}").enumerate() {
if i > 0 {
keys.push((keyboard_types::Key::Named(keyboard_types::NamedKey::Enter), keyboard_types::Code::Enter));
let mut text = rest;
while !text.is_empty() {
let named = [("{enter}", keyboard_types::NamedKey::Enter, keyboard_types::Code::Enter), ("{escape}", keyboard_types::NamedKey::Escape, keyboard_types::Code::Escape)];
if let Some((tag, key, code)) = named.iter().find(|(tag, ..)| text.starts_with(tag)) {
keys.push((keyboard_types::Key::Named(*key), *code));
text = &text[tag.len()..];
} else {
let c = text.chars().next().unwrap_or_default();
keys.push((keyboard_types::Key::Character(c.to_string()), keyboard_types::Code::Unidentified));
text = &text[c.len_utf8()..];
}
keys.extend(part.chars().map(|c| (keyboard_types::Key::Character(c.to_string()), keyboard_types::Code::Unidentified)));
}
for (key, code) in keys {
for state in [keyboard_types::KeyState::Down, keyboard_types::KeyState::Up] {
@ -534,6 +595,9 @@ impl App {
});
serde_json::json!({
"windows": self.windows.len(),
"tab_count": tabs.len(),
"active_index": self.windows.get(&window).map(|w| w.active),
"fullscreen": self.windows.get(&window).map(|w| w.fullscreen),
"frames": frames,
"painters": self.windows.values().flat_map(|w| &w.tabs).filter(|t| t.web.is_some()).count(),
"window_kinds": self.windows.values().map(|w| format!("{:?}", w.kind)).collect::<Vec<_>>(),

137
tests/smoke/basics.txt Normal file
View file

@ -0,0 +1,137 @@
# Browser basics (S006): tabs, navigation, address bar, find, zoom, full screen, new window, pop-ups. Offline.
# Run with tools/smoke.sh; every check is an `expect` / `assert`, so a failure fails the run.
# Layout of pages/basics.html: _blank link y 20..50, pop-up button y 70..100, full screen button y 120..150.
wait 3
open @PAGES@/hello.html
waitload
expect /tab_count 1
# Tabs: new, duplicate, pin, mute, reorder, close, reopen.
do new_tab
wait 0.5
expect /tab_count 2
open @PAGES@/basics.html
waitload
expect /active/title "Basics"
do duplicate_tab
wait 1
expect /tab_count 3
expect /active/title "Basics"
do pin_tab
wait 0.5
# Pinning moves the tab to the front; unpinning leaves it there.
expect /active_index 0
expect /active/pinned true
do pin_tab
wait 0.5
expect /active/pinned false
do mute_tab
wait 0.5
expect /active/muted true
do mute_tab
wait 0.5
expect /active/muted false
# Order now: Basics (duplicate, active), Smoke page, Basics.
do move_tab_right
wait 0.5
expect /active_index 1
do move_tab_left
wait 0.5
expect /active_index 0
do move_tab_right
wait 0.5
do tab_1
wait 0.5
expect /active_index 0
expect /active/title "Smoke page"
do last_tab
wait 0.5
expect /active_index 2
do close_tab
wait 0.5
expect /tab_count 2
do reopen_closed
wait 1.5
expect /tab_count 3
do next_tab
do prev_tab
wait 0.5
shot tabs
# Navigation: back, forward, reload, home.
do tab_1
wait 0.5
open @PAGES@/basics.html
waitload
expect /active/can_back true
do back
waitload
wait 0.5
expect /active/title "Smoke page"
expect /active/can_forward true
do forward
waitload
wait 0.5
expect /active/title "Basics"
js window.marker = 1
do reload
waitload
wait 0.5
assert window.marker === undefined
# Address bar: a URL loads, plain words become a search.
cmd navigate @PAGES@/hello.html
waitload
expect /active/title "Smoke page"
cmd navigate nacre smoke words
wait 1
status search
# Find in page: 3 matches, 2 with match case is the bar's job (count only here).
open @PAGES@/basics.html
waitload
cmd find needle
wait 1
expect /active/find [1,3]
do find_next
wait 0.5
expect /active/find [2,3]
shot find
key Escape
wait 0.3
# Zoom.
do zoom_in
wait 0.5
status zoom-in
do zoom_reset
wait 0.5
expect /active/zoom 1.0
# Full screen: F11 and the page's own request.
do fullscreen
wait 1
expect /fullscreen true
shot fullscreen
do fullscreen
wait 1
expect /fullscreen false
click 60 135
wait 1
expect /fullscreen true
# Escape in full screen is the browser's Stop (leave full screen), not the page's key.
do stop
wait 1
expect /fullscreen false
# target=_blank opens a tab; window.open a pop-up (as a tab or blocked by the pop-up permission).
click 60 35
wait 1.5
expect /tab_count 4
expect /active/title "Smoke page"
do tab_1
wait 0.5
click 60 85
wait 1.5
expect /tab_count 5
status popup
shot popup
# New window.
do new_window
wait 2
expect /windows 2
status done
quit

View file

@ -0,0 +1,12 @@
<!doctype html>
<html>
<!-- Browser basics (S006): find text, a target=_blank link, a window.open pop-up, page full screen. -->
<head><meta charset="utf-8"><title>Basics</title>
<style>body { margin: 0; padding: 20px; font: 16px sans-serif } a, button { display: block; margin: 0 0 20px; height: 30px; width: 300px; font-size: 16px }</style></head>
<body>
<a id="blank" href="hello.html" target="_blank">Open in a new tab</a>
<button id="popup" onclick="window.open('hello.html', 'pop', 'width=400,height=300')">Pop-up</button>
<button id="full" onclick="document.documentElement.requestFullscreen()">Full screen</button>
<p>needle one, needle two, Needle three.</p>
</body>
</html>

6217
vendor/servo-net/Cargo.lock generated vendored Normal file

File diff suppressed because it is too large Load diff

404
vendor/servo-net/Cargo.toml vendored Normal file
View file

@ -0,0 +1,404 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
rust-version = "1.88.0"
name = "servo-net"
version = "0.7.0"
authors = ["The Servo Project Developers"]
build = false
publish = true
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "A component of the servo web-engine."
readme = false
license = "MPL-2.0"
repository = "https://github.com/servo/servo"
resolver = "2"
[features]
test-util = [
"hyper-util/server-graceful",
"dep:servo-default-resources",
"net_traits/test-util",
]
tracing = ["dep:tracing"]
[lib]
name = "net"
path = "lib.rs"
test = false
doctest = false
[[test]]
name = "main"
path = "tests/main.rs"
[dependencies.async-compression]
version = "0.4.12"
features = [
"brotli",
"gzip",
"tokio",
"zlib",
"zstd",
]
default-features = false
[dependencies.async-recursion]
version = "1.1"
[dependencies.async-tungstenite]
version = "0.35"
features = ["tokio-rustls-webpki-roots"]
[dependencies.aws-lc-rs]
version = "1.17"
features = ["aws-lc-sys"]
default-features = false
[dependencies.base64]
version = "0.23.0"
[dependencies.bytes]
version = "1.0"
features = ["serde"]
[dependencies.chrono]
version = "0.4"
features = ["serde"]
[dependencies.content-security-policy]
version = "0.9"
features = ["serde"]
[dependencies.cookie]
version = "0.18"
package = "cookie"
[dependencies.crossbeam-channel]
version = "0.5"
[dependencies.data-url]
version = "0.3"
[dependencies.devtools_traits]
version = "=0.7.0"
package = "servo-devtools-traits"
[dependencies.embedder_traits]
version = "=0.7.0"
package = "servo-embedder-traits"
[dependencies.fonts]
version = "=0.7.0"
package = "servo-fonts"
[dependencies.fst]
version = "0.4"
[dependencies.futures]
version = "0.3"
default-features = false
[dependencies.futures-core]
version = "0.3"
default-features = false
[dependencies.futures-util]
version = "0.3"
default-features = false
[dependencies.headers]
version = "0.4"
[dependencies.http]
version = "1.4"
[dependencies.http-body-util]
version = "0.1"
[dependencies.hyper]
version = "1.10"
features = [
"client",
"http1",
"http2",
]
[dependencies.hyper-rustls]
version = "0.27"
features = [
"http1",
"http2",
"logging",
"tls12",
"webpki-tokio",
]
default-features = false
[dependencies.hyper-util]
version = "0.1"
features = [
"client-legacy",
"client-proxy",
"http2",
"tokio",
]
[dependencies.hyper_serde]
version = "=0.7.0"
package = "servo-hyper-serde"
[dependencies.imsz]
version = "0.4"
[dependencies.ipc-channel]
version = "0.23"
[dependencies.itertools]
version = "0.15"
[dependencies.log]
version = "0.4.32"
[dependencies.malloc_size_of]
version = "=0.7.0"
package = "servo-malloc-size-of"
[dependencies.malloc_size_of_derive]
version = "0.1"
[dependencies.mime]
version = "0.3.13"
[dependencies.mime_guess]
version = "2.0.5"
[dependencies.net_traits]
version = "=0.7.0"
package = "servo-net-traits"
[dependencies.nom]
version = "8.0.0"
[dependencies.paint_api]
version = "=0.7.0"
package = "servo-paint-api"
[dependencies.parking_lot]
version = "0.12"
features = ["serde"]
[dependencies.pixels]
version = "=0.7.0"
package = "servo-pixels"
[dependencies.postcard]
version = "1.1.3"
features = ["use-std"]
default-features = false
[dependencies.profile_traits]
version = "=0.7.0"
package = "servo-profile-traits"
[dependencies.quick_cache]
version = "0.7.0"
features = ["custom-hasher"]
default-features = false
[dependencies.rand]
version = "0.10"
[dependencies.regex]
version = "1.12"
[dependencies.resvg]
version = "0.48.1"
[dependencies.rusqlite]
version = "0.38"
features = ["bundled"]
[dependencies.rustc-hash]
version = "2.1.2"
[dependencies.rustls]
version = "0.23"
features = [
"logging",
"std",
"tls12",
"aws-lc-rs",
]
default-features = false
[dependencies.rustls-pki-types]
version = "1.14"
[dependencies.rustls-platform-verifier]
version = "0.7.0"
[dependencies.sea-query]
version = "1.0.1"
features = [
"backend-sqlite",
"derive",
]
default-features = false
[dependencies.sea-query-rusqlite]
version = "0.8.0"
[dependencies.serde]
version = "1.0.228"
[dependencies.servo-base]
version = "=0.7.0"
[dependencies.servo-config]
version = "=0.7.0"
[dependencies.servo-default-resources]
version = "=0.7.0"
optional = true
[dependencies.servo-tracing]
version = "=0.7.0"
[dependencies.servo-url]
version = "=0.7.0"
[dependencies.servo_arc]
version = "0.5.0"
[dependencies.smallvec]
version = "1.15"
features = [
"serde",
"union",
]
[dependencies.tempfile]
version = "3"
[dependencies.time]
version = "0.3"
features = [
"large-dates",
"local-offset",
"serde",
]
package = "time"
[dependencies.tokio]
version = "1"
features = [
"fs",
"macros",
"rt-multi-thread",
"sync",
]
[dependencies.tokio-rustls]
version = "0.26"
features = ["logging"]
default-features = false
[dependencies.tokio-stream]
version = "0.1"
[dependencies.tokio-util]
version = "0.7.18"
features = [
"codec",
"io",
]
default-features = false
[dependencies.tower]
version = "0.5"
features = ["util"]
default-features = false
[dependencies.tracing]
version = "0.1.44"
optional = true
[dependencies.tungstenite]
version = "0.30"
[dependencies.url]
version = "2.5"
[dependencies.uuid]
version = "1.23.3"
features = [
"v4",
"v5",
]
[dependencies.webpki-roots]
version = "1.0"
[dependencies.webrender_api]
version = "0.70"
[dev-dependencies.flate2]
version = "1.1"
[dev-dependencies.fst]
version = "0.4"
[dev-dependencies.hyper]
version = "1.10"
features = ["full"]
[dev-dependencies.hyper-util]
version = "0.1"
features = [
"client-legacy",
"client-proxy",
"http2",
"tokio",
"server-graceful",
]
[dev-dependencies.rustls]
version = "0.23"
features = [
"logging",
"std",
"tls12",
"aws-lc-rs",
]
default-features = false
[dev-dependencies.servo-default-resources]
version = "=0.7.0"
[lints.clippy]
manual_string_new = "warn"
[lints.rust.unexpected_cfgs]
level = "warn"
priority = 0
check-cfg = [
"cfg(crown)",
"cfg(coverage)",
"cfg(llvm_pgo)",
"cfg(ohos_mock)",
]

113
vendor/servo-net/Cargo.toml.orig generated vendored Normal file
View file

@ -0,0 +1,113 @@
[package]
name = "servo-net"
version.workspace = true
authors.workspace = true
license.workspace = true
edition.workspace = true
publish.workspace = true
rust-version.workspace = true
repository.workspace = true
description.workspace = true
autotests = false # Inhibit lookup for tests/*.rs without [[test]] sections
[lib]
name = "net"
path = "lib.rs"
test = false
doctest = false
[features]
test-util = ["hyper-util/server-graceful", "dep:servo-default-resources", "net_traits/test-util"]
tracing = ["dep:tracing"]
[dependencies]
aws-lc-rs = { workspace = true }
async-compression = { workspace = true, features = ["brotli", "gzip", "tokio", "zlib", "zstd"] }
async-recursion = { workspace = true }
async-tungstenite = { workspace = true }
base64 = { workspace = true }
bytes = { workspace = true }
chrono = { workspace = true }
content-security-policy = { workspace = true }
cookie = { workspace = true }
crossbeam-channel = { workspace = true }
data-url = { workspace = true }
devtools_traits = { workspace = true }
embedder_traits = { workspace = true }
fst = { workspace = true }
fonts = { workspace = true }
futures = { workspace = true }
futures-core = { workspace = true }
futures-util = { workspace = true }
headers = { workspace = true }
http = { workspace = true }
http-body-util = { workspace = true }
hyper = { workspace = true, features = ["client", "http1", "http2"] }
hyper-rustls = { workspace = true }
hyper-util = { workspace = true }
hyper_serde = { workspace = true }
imsz = { workspace = true }
ipc-channel = { workspace = true }
itertools = { workspace = true }
log = { workspace = true }
malloc_size_of = { workspace = true }
malloc_size_of_derive = { workspace = true }
mime = { workspace = true }
mime_guess = { workspace = true }
net_traits = { workspace = true }
nom = { workspace = true }
paint_api = { workspace = true }
parking_lot = { workspace = true }
pixels = { workspace = true }
profile_traits = { workspace = true }
postcard = { workspace = true }
quick_cache = { workspace = true }
rand = { workspace = true }
regex = { workspace = true }
resvg = { workspace = true }
rustc-hash = { workspace = true }
rustls = { workspace = true, features = ["aws-lc-rs"] }
rustls-pki-types = { workspace = true }
rustls-platform-verifier = { workspace = true }
rusqlite = { workspace = true }
serde = { workspace = true }
servo-base = { workspace = true }
servo-config = { workspace = true }
servo-default-resources = { workspace = true, optional = true }
servo-tracing = { workspace = true }
servo-url = { workspace = true }
servo_arc = { workspace = true }
sea-query = { workspace = true }
sea-query-rusqlite = { workspace = true }
smallvec = { workspace = true }
tempfile = { workspace = true }
time = { workspace = true }
tokio = { workspace = true, features = ["fs", "macros", "rt-multi-thread", "sync"] }
tokio-rustls = { workspace = true }
tokio-stream = { workspace = true }
tokio-util = { workspace = true, features = ["codec", "io"] }
tower = { workspace = true }
tracing = { workspace = true, optional = true }
tungstenite = { workspace = true }
url = { workspace = true }
uuid = { workspace = true }
webpki-roots = { workspace = true }
webrender_api = { workspace = true }
[dev-dependencies]
flate2 = { workspace = true }
fst = { workspace = true }
hyper = { workspace = true, features = ["full"] }
hyper-util = { workspace = true, features = ["server-graceful"] }
# This must always be a path dependency, we don't want to add a dependency on a
# crates.io version of ourselves - we want to enable a feature of ourselves.
net = { package = "servo-net", path = ".", features = ["test-util"] }
rustls = { workspace = true, features = ["aws-lc-rs"] }
servo-default-resources = { workspace = true }
[lints]
workspace = true
[[test]]
name = "main"
path = "tests/main.rs"

93
vendor/servo-net/async_runtime.rs vendored Normal file
View file

@ -0,0 +1,93 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::sync::OnceLock;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use std::time::Duration;
use futures::Future;
use net_traits::AsyncRuntime;
use tokio::runtime::{Builder, Handle, Runtime};
/// The actual runtime,
/// to be used as part of shut-down.
pub struct AsyncRuntimeHolder {
runtime: Option<Runtime>,
}
impl AsyncRuntimeHolder {
pub(crate) fn new(runtime: Runtime) -> Self {
Self {
runtime: Some(runtime),
}
}
}
impl AsyncRuntime for AsyncRuntimeHolder {
fn shutdown(&mut self) {
self.runtime
.take()
.expect("Runtime should have been initialized on start-up.")
.shutdown_timeout(Duration::from_millis(100))
}
}
/// A shared handle to the runtime,
/// to be initialized on start-up.
static ASYNC_RUNTIME_HANDLE: OnceLock<Handle> = OnceLock::new();
pub fn init_async_runtime() -> Box<dyn AsyncRuntime> {
// Initialize a tokio runtime.
let runtime = Builder::new_multi_thread()
.thread_name_fn(|| {
static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
let id = ATOMIC_ID.fetch_add(1, Ordering::Relaxed);
format!("tokio-runtime-{}", id)
})
.worker_threads(
thread::available_parallelism()
.map(|i| i.get())
.unwrap_or(servo_config::pref!(thread_pool_fallback_workers) as usize)
.min(servo_config::pref!(thread_pool_async_runtime_workers_max).max(1) as usize),
)
.enable_io()
.enable_time()
.build()
.expect("Unable to build tokio-runtime runtime");
// Make the runtime available to users inside this crate.
ASYNC_RUNTIME_HANDLE
.set(runtime.handle().clone())
.expect("Runtime handle should be initialized once on start-up");
// Return an async runtime for use in shutdown.
Box::new(AsyncRuntimeHolder::new(runtime))
}
pub fn async_runtime_initialized() -> bool {
ASYNC_RUNTIME_HANDLE.get().is_some()
}
/// Spawn a task using the handle to the runtime.
pub fn spawn_task<F>(task: F)
where
F: Future + 'static + std::marker::Send,
F::Output: Send + 'static,
{
ASYNC_RUNTIME_HANDLE
.get()
.expect("Runtime handle should be initialized on start-up")
.spawn(task);
}
/// Spawn a blocking task using the handle to the runtime.
pub fn spawn_blocking_task<F>(task: F) -> F::Output
where
F: Future,
{
ASYNC_RUNTIME_HANDLE
.get()
.expect("Runtime handle should be initialized on start-up")
.block_on(task)
}

666
vendor/servo-net/connector.rs vendored Normal file
View file

@ -0,0 +1,666 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::collections::hash_map::HashMap;
use std::convert::TryFrom;
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use std::{fmt, io};
use futures::task::{Context, Poll};
use futures::{Future, TryFutureExt};
use http::uri::{Authority, Uri as Destination};
use http_body_util::combinators::BoxBody;
use hyper::body::Bytes;
use hyper::rt::Executor;
use hyper_rustls::{HttpsConnector as HyperRustlsHttpsConnector, MaybeHttpsStream};
use hyper_util::client::legacy::Client;
use hyper_util::client::legacy::connect::proxy::Tunnel;
use hyper_util::client::legacy::connect::{
Connected, Connection, HttpConnector as HyperHttpConnector,
};
use hyper_util::rt::TokioIo;
use log::warn;
use parking_lot::Mutex;
use rustls::client::danger::ServerCertVerifier;
use rustls::client::{ClientConnection, EchStatus};
use rustls::crypto::{CryptoProvider, aws_lc_rs};
use rustls::{CipherSuite, ClientConfig, NamedGroup, ProtocolVersion};
use rustls_pki_types::{CertificateDer, ServerName, UnixTime};
use servo_config::pref;
use tokio::net::TcpStream;
use tower::Service;
use crate::async_runtime::spawn_task;
use crate::hosts::replace_host;
pub const BUF_SIZE: usize = 32768;
/// ALPN identifier for HTTP/2 (RFC 7540 §3.1).
pub const ALPN_H2: &str = "h2";
#[derive(Clone)]
pub struct ServoHttpConnector {
inner: HyperHttpConnector,
}
impl ServoHttpConnector {
fn new() -> ServoHttpConnector {
let mut inner = HyperHttpConnector::new();
inner.enforce_http(false);
inner.set_happy_eyeballs_timeout(None);
inner.set_connect_timeout(Some(Duration::from_secs(pref!(network_connection_timeout))));
ServoHttpConnector { inner }
}
}
impl Service<Destination> for ServoHttpConnector {
type Response = TokioIo<TcpStream>;
type Error = ConnectionError;
type Future =
std::pin::Pin<Box<dyn Future<Output = Result<TokioIo<TcpStream>, ConnectionError>> + Send>>;
fn call(&mut self, dest: Destination) -> Self::Future {
// Perform host replacement when making the actual TCP connection.
let mut new_dest = dest.clone();
let mut parts = dest.into_parts();
if let Some(auth) = parts.authority {
let host = auth.host();
let host = replace_host(host);
let authority = if let Some(port) = auth.port() {
format!("{}:{}", host, port.as_str())
} else {
(*host).to_string()
};
if let Ok(authority) = Authority::from_maybe_shared(authority) {
parts.authority = Some(authority);
if let Ok(dest) = Destination::from_parts(parts) {
new_dest = dest
}
}
}
Box::pin(
self.inner
.call(new_dest)
.map_err(|e| ConnectionError::HttpError(format!("{e}"))),
)
}
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Ok(()).into()
}
}
type BoxError = Box<dyn std::error::Error + Send + Sync>;
#[derive(Clone)]
pub struct InstrumentedConnector<T> {
inner: HyperRustlsHttpsConnector<T>,
}
impl<T> InstrumentedConnector<T> {
fn new(inner: HyperRustlsHttpsConnector<T>) -> Self {
Self { inner }
}
}
impl<T> From<HyperRustlsHttpsConnector<T>> for InstrumentedConnector<T> {
fn from(inner: HyperRustlsHttpsConnector<T>) -> Self {
Self::new(inner)
}
}
pub struct InstrumentedStream<T> {
inner: MaybeHttpsStream<T>,
tls_info: Option<TlsHandshakeInfo>,
}
impl<T: Unpin> Unpin for InstrumentedStream<T> {}
impl<T> fmt::Debug for InstrumentedStream<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("InstrumentedStream")
.field("tls_info", &self.tls_info)
.finish()
}
}
#[derive(Clone, Debug)]
pub struct TlsHandshakeInfo {
pub protocol_version: Option<ProtocolVersion>,
pub cipher_suite: Option<CipherSuite>,
pub kea_group_name: Option<NamedGroup>,
pub signature_scheme_name: Option<String>,
pub alpn_protocol: Option<String>,
pub certificate_chain_der: Vec<Vec<u8>>,
pub used_ech: bool,
}
impl TlsHandshakeInfo {
fn from_connection(conn: &ClientConnection) -> Self {
let protocol_version = conn.protocol_version();
let cipher_suite = conn.negotiated_cipher_suite().map(|suite| suite.suite());
let kea_group_name = conn
.negotiated_key_exchange_group()
.map(|group| group.name());
let certificate_chain_der = conn
.peer_certificates()
.map(|certs| certs.iter().map(|cert| cert.as_ref().to_vec()).collect())
.unwrap_or_default();
let alpn_protocol = conn
.alpn_protocol()
.map(|proto| String::from_utf8_lossy(proto).into_owned());
let used_ech = matches!(conn.ech_status(), EchStatus::Accepted);
Self {
protocol_version,
cipher_suite,
kea_group_name,
signature_scheme_name: None,
alpn_protocol,
certificate_chain_der,
used_ech,
}
}
}
impl<T> InstrumentedStream<T>
where
T: Connection + hyper::rt::Read + hyper::rt::Write + Unpin,
{
fn from_maybe_https_stream(stream: MaybeHttpsStream<T>) -> Self {
match stream {
MaybeHttpsStream::Http(inner) => Self {
inner: MaybeHttpsStream::Http(inner),
tls_info: None,
},
MaybeHttpsStream::Https(tls_stream) => {
let (_tcp, tls) = tls_stream.inner().get_ref();
let tls_info = TlsHandshakeInfo::from_connection(tls);
Self {
inner: MaybeHttpsStream::Https(tls_stream),
tls_info: Some(tls_info),
}
},
}
}
}
impl<T> Connection for InstrumentedStream<T>
where
T: Connection + hyper::rt::Read + hyper::rt::Write + Unpin,
{
fn connected(&self) -> Connected {
let connected = match &self.inner {
MaybeHttpsStream::Http(stream) => stream.connected(),
MaybeHttpsStream::Https(stream) => {
let (tcp, tls) = stream.inner().get_ref();
if tls.alpn_protocol() == Some(ALPN_H2.as_bytes()) {
tcp.inner().connected().negotiated_h2()
} else {
tcp.inner().connected()
}
},
};
if let Some(info) = &self.tls_info {
connected.extra(info.clone())
} else {
connected
}
}
}
impl<T> hyper::rt::Read for InstrumentedStream<T>
where
T: Connection + hyper::rt::Read + hyper::rt::Write + Unpin,
{
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
buf: hyper::rt::ReadBufCursor<'_>,
) -> Poll<Result<(), io::Error>> {
std::pin::Pin::new(&mut self.get_mut().inner).poll_read(cx, buf)
}
}
impl<T> hyper::rt::Write for InstrumentedStream<T>
where
T: Connection + hyper::rt::Read + hyper::rt::Write + Unpin,
{
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
std::pin::Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), io::Error>> {
std::pin::Pin::new(&mut self.get_mut().inner).poll_flush(cx)
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), io::Error>> {
std::pin::Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
}
fn is_write_vectored(&self) -> bool {
self.inner.is_write_vectored()
}
fn poll_write_vectored(
self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[io::IoSlice<'_>],
) -> Poll<Result<usize, io::Error>> {
std::pin::Pin::new(&mut self.get_mut().inner).poll_write_vectored(cx, bufs)
}
}
impl<T> Service<Destination> for InstrumentedConnector<T>
where
T: Service<Destination>,
T::Response: Connection + hyper::rt::Read + hyper::rt::Write + Send + Unpin + 'static,
T::Future: Send + 'static,
T::Error: Into<BoxError>,
{
type Response = InstrumentedStream<T::Response>;
type Error = BoxError;
type Future = std::pin::Pin<
Box<dyn Future<Output = Result<InstrumentedStream<T::Response>, BoxError>> + Send>,
>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx).map_err(Into::into)
}
fn call(&mut self, dst: Destination) -> Self::Future {
let future = self.inner.call(dst);
Box::pin(async move {
let stream = future.await.map_err(|error| -> BoxError { error })?;
Ok(InstrumentedStream::from_maybe_https_stream(stream))
})
}
}
pub type Connector = InstrumentedConnector<ServoHttpConnector>;
pub type TlsConfig = ClientConfig;
#[derive(Clone, Debug, Default)]
struct CertificateErrorOverrideManagerInternal {
/// A mapping of certificates and their hosts, which have seen certificate errors.
/// This is used to later create an override in this [CertificateErrorOverrideManager].
certificates_failing_to_verify: HashMap<ServerName<'static>, CertificateDer<'static>>,
/// A list of certificates that should be accepted despite encountering verification
/// errors.
overrides: Vec<CertificateDer<'static>>,
}
/// This data structure is used to track certificate verification errors and overrides.
/// It tracks:
/// - A list of [Certificate]s with verification errors mapped by their [ServerName]
/// - A list of [Certificate]s for which to ignore verification errors.
#[derive(Clone, Debug, Default)]
pub struct CertificateErrorOverrideManager(Arc<Mutex<CertificateErrorOverrideManagerInternal>>);
impl CertificateErrorOverrideManager {
pub fn new() -> Self {
Self(Default::default())
}
/// Add a certificate to this manager's list of certificates for which to ignore
/// validation errors.
pub fn add_override(&self, certificate: &CertificateDer<'static>) {
self.0.lock().overrides.push(certificate.clone());
}
/// Given the a string representation of a sever host name, remove information about
/// a [Certificate] with verification errors. If a certificate with
/// verification errors was found, return it, otherwise None.
pub(crate) fn remove_certificate_failing_verification(
&self,
host: &str,
) -> Option<CertificateDer<'static>> {
let server_name = match ServerName::try_from(host) {
Ok(name) => name.to_owned(),
Err(error) => {
warn!("Could not convert host string into RustTLS ServerName: {error:?}");
return None;
},
};
self.0
.lock()
.certificates_failing_to_verify
.remove(&server_name)
}
}
#[derive(Clone, Debug, Default)]
pub enum CACertificates<'de> {
#[default]
Default,
Override(Vec<CertificateDer<'de>>),
}
/// Create a [TlsConfig] to use for managing a HTTP connection. This currently creates
/// a rustls [ClientConfig].
///
/// FIXME: The `ignore_certificate_errors` argument ignores all certificate errors. This
/// is used when running the WPT tests, because rustls currently rejects the WPT certificiate.
/// See <https://github.com/servo/servo/issues/30080>
#[servo_tracing::instrument(skip_all)]
pub fn create_tls_config(
ca_certificates: CACertificates<'static>,
ignore_certificate_errors: bool,
override_manager: CertificateErrorOverrideManager,
) -> TlsConfig {
let verifier = CertificateVerificationOverrideVerifier::new(
ca_certificates,
ignore_certificate_errors,
override_manager,
);
// TODO: After <https://github.com/rustls/rustls-platform-verifier/pull/204> is merged,
// `dangerous` can be removed.
rustls::ClientConfig::builder()
.dangerous()
.with_custom_certificate_verifier(Arc::new(verifier))
.with_no_client_auth()
}
#[derive(Clone)]
struct TokioExecutor {}
impl<F> Executor<F> for TokioExecutor
where
F: Future<Output = ()> + 'static + std::marker::Send,
{
fn execute(&self, fut: F) {
spawn_task(fut);
}
}
static CRYPTO_PROVIDER_CACHE: LazyLock<Arc<CryptoProvider>> = LazyLock::new(|| {
CryptoProvider::get_default()
.cloned()
// The embedder should have initialized the default crypto provider before
// initializing servo, so this should never fail.
.unwrap_or_else(|| {
warn!("Default crypto provider not initialized before first access in connector.");
Arc::new(aws_lc_rs::default_provider())
})
});
/// A cache for the default rustls platform verifier.
///
/// Instantiating a new verifier can be expensive, since it can read through all certificates:
/// <https://github.com/rustls/rustls-platform-verifier/blob/996b1c903491641b17b3c9afb65d1352f6fc6b76/rustls-platform-verifier/src/verification/others.rs#L92>
static RUSTLS_PLATFORM_VERIFIER_CACHE: LazyLock<Arc<rustls_platform_verifier::Verifier>> =
LazyLock::new(|| {
Arc::new(
rustls_platform_verifier::Verifier::new(CRYPTO_PROVIDER_CACHE.clone())
.expect("Could not initialize platform certificate verifier"),
)
});
/// Prewarm the TLS stack to speed up the first connection
///
/// Currently, this force-seeds the crypto provider (from aws_lc_rs),
/// which on my system takes around 30-50ms according to samply, spent in
/// `tree_jitter_initialize_once`. If we don't call this function, then
/// the initialization will happen much later, on a tokio runtime thread.
#[inline]
pub fn prewarm_tls() {
#[servo_tracing::instrument]
fn prewarm_tls_impl() {
let mut sink = [0u8; 32];
// The first access can be slow, if the provider needs to gather entropy.
let _ = CRYPTO_PROVIDER_CACHE.secure_random.fill(&mut sink);
// Note: We don't need to explicitly force initialize RUSTLS_PLATFORM_VERIFIER_CACHE,
// since the resource manager thread will do that during startup.
}
if let Err(error) = std::thread::Builder::new()
.name("Net-TLS-prewarm".into())
.spawn(prewarm_tls_impl)
{
warn!("Failed to spawn thread to prewarm TLS: {error:?}");
}
}
#[derive(Debug)]
struct CertificateVerificationOverrideVerifier {
main_verifier: Arc<dyn ServerCertVerifier>,
ignore_certificate_errors: bool,
override_manager: CertificateErrorOverrideManager,
}
impl CertificateVerificationOverrideVerifier {
fn new(
ca_certficates: CACertificates<'static>,
ignore_certificate_errors: bool,
override_manager: CertificateErrorOverrideManager,
) -> Self {
// From <https://github.com/rustls/rustls-platform-verifier/blob/main/README.md>:
// > Some manual setup is required, outside of cargo, to use this crate on
// > Android. In order to use Android's certificate verifier, the crate needs to
// > call into the JVM. A small Kotlin component must be included in your app's
// > build to support rustls-platform-verifier.
//
// Since we cannot count on embedders to do this setup, just stick with webpki roots
// on Android.
let use_webpki_roots = cfg!(target_os = "android") || pref!(network_use_webpki_roots);
let main_verifier = if !use_webpki_roots {
let verifier = match ca_certficates {
CACertificates::Default => RUSTLS_PLATFORM_VERIFIER_CACHE.clone(),
// Android doesn't support `Verifier::new_with_extra_roots`, but currently Android
// never uses the platform verifier at all.
CACertificates::Override(_certificates) => {
#[cfg(target_os = "android")]
unreachable!("Android should always use the WebPKI verifier.");
#[cfg(not(target_os = "android"))]
{
let verifier = rustls_platform_verifier::Verifier::new_with_extra_roots(
_certificates,
CRYPTO_PROVIDER_CACHE.clone(),
)
.expect("Could not initialize platform certificate verifier");
Arc::new(verifier)
}
},
};
verifier as Arc<dyn ServerCertVerifier>
} else {
let mut root_store =
rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
match ca_certficates {
CACertificates::Default => {},
CACertificates::Override(certificates) => {
for certificate in certificates {
if root_store.add(certificate).is_err() {
log::error!("Could not add an override certificate.");
}
}
},
}
rustls::client::WebPkiServerVerifier::builder(root_store.into())
.build()
.expect("Could not initialize platform certificate verifier.")
as Arc<dyn ServerCertVerifier>
};
Self {
main_verifier,
ignore_certificate_errors,
override_manager,
}
}
}
impl rustls::client::danger::ServerCertVerifier for CertificateVerificationOverrideVerifier {
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
self.main_verifier
.verify_tls12_signature(message, cert, dss)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
self.main_verifier
.verify_tls13_signature(message, cert, dss)
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
self.main_verifier.supported_verify_schemes()
}
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
server_name: &ServerName<'_>,
ocsp_response: &[u8],
now: UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
let error = match self.main_verifier.verify_server_cert(
end_entity,
intermediates,
server_name,
ocsp_response,
now,
) {
Ok(result) => return Ok(result),
Err(error) => error,
};
if self.ignore_certificate_errors {
warn!("Ignoring certficate error: {error:?}");
return Ok(rustls::client::danger::ServerCertVerified::assertion());
}
// If there's an override for this certificate, just accept it.
for cert_with_exception in &*self.override_manager.0.lock().overrides {
if *end_entity == *cert_with_exception {
return Ok(rustls::client::danger::ServerCertVerified::assertion());
}
}
self.override_manager
.0
.lock()
.certificates_failing_to_verify
.insert(server_name.to_owned(), end_entity.clone().into_owned());
Err(error)
}
}
pub type BoxedBody = BoxBody<Bytes, hyper::Error>;
#[derive(Debug)]
/// The error type for the MaybeProxyConnector
pub enum ConnectionError {
HttpError(String),
// It looks like currently the type is not exported.
ProxyError(String),
}
impl std::fmt::Display for ConnectionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for ConnectionError {}
#[derive(Clone)]
/// A proxy connector. This will automatically open a proxy connection if the uri matches the proxy uri.
/// Also respects 'no_proxy'.
pub struct ProxyConnector {
/// A client without proxy for `no_proxy` matches.
client: ServoHttpConnector,
/// Matcher to see if we should forward to the proxy or not.
matcher: std::sync::Arc<hyper_util::client::proxy::matcher::Matcher>,
}
impl ProxyConnector {
fn new() -> Self {
let matcher_builder = hyper_util::client::proxy::matcher::Matcher::builder()
.http(servo_config::pref!(network_http_proxy_uri))
.https(servo_config::pref!(network_https_proxy_uri))
.no(servo_config::pref!(network_http_no_proxy));
ProxyConnector {
client: ServoHttpConnector::new(),
matcher: std::sync::Arc::new(matcher_builder.build()),
}
}
}
// Just forward everything to the inner type except that we modify the errors returned.
impl Service<Destination> for ProxyConnector {
type Response = TokioIo<TcpStream>;
type Error = ConnectionError;
type Future =
std::pin::Pin<Box<dyn Future<Output = Result<TokioIo<TcpStream>, ConnectionError>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.client
.poll_ready(cx)
.map_err(|e| ConnectionError::ProxyError(format!("{e}")))
}
fn call(&mut self, req: Destination) -> Self::Future {
match self.matcher.intercept(&req) {
Some(intercept) => {
let mut tunnel = Tunnel::new(intercept.uri().clone(), self.client.clone());
let final_tunnel = if let Some(auth) = intercept.basic_auth() {
tunnel.with_auth(auth.clone())
} else {
tunnel
}
.call(req)
.map_err(|e| ConnectionError::ProxyError(format!("{e}")));
Box::pin(final_tunnel)
},
None => Box::pin(
self.client
.call(req)
.map_err(|e| ConnectionError::ProxyError(format!("{e}"))),
),
}
}
}
pub type ServoClient = Client<InstrumentedConnector<ProxyConnector>, BoxedBody>;
pub fn create_http_client(tls_config: TlsConfig) -> ServoClient {
let connector = hyper_rustls::HttpsConnectorBuilder::new()
.with_tls_config(tls_config)
.https_or_http()
.enable_http1()
.enable_http2()
.wrap_connector(ProxyConnector::new());
Client::builder(TokioExecutor {})
.http1_title_case_headers(true)
// Nacre patch: hyper's HTTP/2 default (16 KiB) refuses sites with large response headers,
// e.g. YouTube (~19 KiB). Browsers accept far more; Chromium allows 256 KiB.
.http2_max_header_list_size(256 * 1024)
.build(InstrumentedConnector::from(connector))
}

633
vendor/servo-net/cookie.rs vendored Normal file
View file

@ -0,0 +1,633 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Implementation of cookie creation and matching as specified by
//! <http://tools.ietf.org/html/rfc6265>
use std::borrow::ToOwned;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::time::SystemTime;
use cookie::Cookie;
use log::{Level, debug, log_enabled};
use malloc_size_of_derive::MallocSizeOf;
use net_traits::pub_domains::is_pub_domain;
use net_traits::{CookieSource, ends_with_ignore_ascii_case};
use nom::branch::alt;
use nom::bytes::complete::{tag, tag_no_case, take, take_while_m_n};
use nom::combinator::{opt, recognize, value};
use nom::multi::{many0, many1, separated_list1};
use nom::sequence::{delimited, preceded, terminated};
use nom::{IResult, Parser};
use serde::{Deserialize, Serialize};
use servo_url::ServoUrl;
use time::{Date, Duration, Month, OffsetDateTime, Time};
/// A stored cookie that wraps the definition in cookie-rs. This is used to implement
/// various behaviours defined in the spec that rely on an associated request URL,
/// which cookie-rs and hyper's header parsing do not support.
#[derive(Clone, Debug, Deserialize, Serialize, MallocSizeOf)]
pub struct ServoCookie {
#[serde(
deserialize_with = "hyper_serde::deserialize",
serialize_with = "hyper_serde::serialize"
)]
pub cookie: Cookie<'static>,
pub host_only: bool,
pub persistent: bool,
pub creation_time: SystemTime,
pub last_access: SystemTime,
pub expiry_time: Option<SystemTime>,
}
impl ServoCookie {
pub fn from_cookie_string(
cookie_str: &str,
request: &ServoUrl,
source: CookieSource,
) -> Option<ServoCookie> {
let mut cookie = Cookie::parse(cookie_str.to_owned()).ok()?;
// Cookie::parse uses RFC 2616 <http://tools.ietf.org/html/rfc2616#section-3.3.1> to parse
// cookie expiry date. If it fails to parse the expiry date, try to parse again with
// less strict algorithm from RFC6265.
// TODO: We can remove this code and the ServoCookie::parse_date function if cookie-rs
// library fixes this upstream.
if cookie.expires_datetime().is_none() {
let expiry_date_str = cookie_str
.split(';')
.filter_map(|key_value| {
key_value
.find('=')
.map(|i| (key_value[..i].trim(), key_value[(i + 1)..].trim()))
})
.find_map(|(key, value)| key.eq_ignore_ascii_case("expires").then_some(value));
if let Some(date_str) = expiry_date_str {
cookie.set_expires(Self::parse_date(date_str));
}
}
ServoCookie::new_wrapped(cookie, request, source)
}
/// Steps 6-22 from <https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#name-storage-model>
pub fn new_wrapped(
mut cookie: Cookie<'static>,
request: &ServoUrl,
source: CookieSource,
) -> Option<ServoCookie> {
let persistent;
let expiry_time;
// Step 6. If the cookie-attribute-list contains an attribute with an attribute-name of "Max-Age":
if let Some(max_age) = cookie.max_age() {
// 1. Set the cookie's persistent-flag to true.
persistent = true;
// The user agent MUST limit the maximum value of the Max-Age attribute.
// The limit SHOULD NOT be greater than 400 days (34560000 seconds) in the future.
let clamped_max_age = max_age.min(Duration::seconds(34_560_000));
// 2. Set the cookie's expiry-time to attribute-value of the last
// attribute in the cookie-attribute-list with an attribute-name of "Max-Age".
expiry_time = Some(SystemTime::now() + clamped_max_age);
cookie.set_max_age(clamped_max_age);
// cookie-rs doesn't seem to mirror the max-age value to expiry and vice versa so we do explicitly
cookie.set_expires(Some(OffsetDateTime::now_utc() + clamped_max_age));
}
// Otherwise, if the cookie-attribute-list contains an attribute with an attribute-name of "Expires":
else if let Some(date_time) = cookie.expires_datetime() {
// 1. Set the cookie's persistent-flag to true.
persistent = true;
// The user agent MUST limit the maximum value of the Expires attribute.
// The limit SHOULD NOT be greater than 400 days (34560000 seconds) in the future.
let clamped_date_time =
date_time.min(OffsetDateTime::now_utc() + Duration::seconds(34_560_000));
// 2. Set the cookie's expiry-time to attribute-value of the last attribute in the
// cookie-attribute-list with an attribute-name of "Expires".
expiry_time = Some(clamped_date_time.into());
cookie.set_expires(Some(clamped_date_time));
// cookie-rs doesn't seem to mirror the max-age value to expiry and vice versa so we do explicitly
cookie.set_max_age(Some(clamped_date_time - OffsetDateTime::now_utc()));
}
// Otherwise:
else {
// 1. Set the cookie's persistent-flag to false.
persistent = false;
// 2. Set the cookie's expiry-time to the latest representable date.
expiry_time = None;
}
let url_host = request.host_str().unwrap_or("").to_owned();
// Step 7. If the cookie-attribute-list contains an attribute with an attribute-name of "Domain":
let mut domain = if let Some(domain) = cookie.domain() {
// 1. Let the domain-attribute be the attribute-value of the last attribute in the
// cookie-attribute-list [..]
// NOTE: This is done by the cookie crate
domain.to_owned()
}
// Otherwise:
else {
// 1. Let the domain-attribute be the empty string.
String::new()
};
// TODO Step 8. If the domain-attribute contains a character that is not in the range of [USASCII] characters,
// abort these steps and ignore the cookie entirely.
// NOTE: (is this done by the cookies crate?)
// Step 9. If the user agent is configured to reject "public suffixes" and the domain-attribute
// is a public suffix:
if is_pub_domain(&domain) {
// 1. If the domain-attribute is identical to the canonicalized request-host:
if domain == url_host {
// 1. Let the domain-attribute be the empty string.
domain = String::new();
}
// Otherwise:
else {
// 1.Abort these steps and ignore the cookie entirely.
return None;
}
}
// Step 10. If the domain-attribute is non-empty:
let host_only;
if !domain.is_empty() {
// 1. If the canonicalized request-host does not domain-match the domain-attribute:
if !ServoCookie::domain_match(&url_host, &domain) {
// 1. Abort these steps and ignore the cookie entirely.
return None;
} else {
// 1. Set the cookie's host-only-flag to false.
host_only = false;
// 2. Set the cookie's domain to the domain-attribute.
cookie.set_domain(domain);
}
}
// Otherwise:
else {
// 1. Set the cookie's host-only-flag to true.
host_only = true;
// 2. Set the cookie's domain to the canonicalized request-host.
cookie.set_domain(url_host);
};
// Step 11. If the cookie-attribute-list contains an attribute with an attribute-name of "Path",
// set the cookie's path to attribute-value of the last attribute in the cookie-attribute-list
// with both an attribute-name of "Path" and an attribute-value whose length is no more than 1024 octets.
// Otherwise, set the cookie's path to the default-path of the request-uri.
let mut has_path_specified = true;
let mut path = cookie
.path()
.unwrap_or_else(|| {
has_path_specified = false;
""
})
.to_owned();
// TODO: Why do we do this?
if !path.starts_with('/') {
path = ServoCookie::default_path(request.path()).to_string();
}
cookie.set_path(path);
// Step 12. If the cookie-attribute-list contains an attribute with an attribute-name of "Secure",
// set the cookie's secure-only-flag to true. Otherwise, set the cookie's secure-only-flag to false.
let secure_only = cookie.secure().unwrap_or(false);
// Step 13. If the request-uri does not denote a "secure" connection (as defined by the user agent),
// and the cookie's secure-only-flag is true, then abort these steps and ignore the cookie entirely.
if secure_only && !request.is_secure_scheme() {
return None;
}
// Step 14. If the cookie-attribute-list contains an attribute with an attribute-name of "HttpOnly",
// set the cookie's http-only-flag to true. Otherwise, set the cookie's http-only-flag to false.
let http_only = cookie.http_only().unwrap_or(false);
// Step 15. If the cookie was received from a "non-HTTP" API and the cookie's
// http-only-flag is true, abort these steps and ignore the cookie entirely.
if http_only && source == CookieSource::NonHTTP {
return None;
}
// TODO: Step 16, Ignore cookies from insecure request uris based on existing cookies
// TODO: Steps 17-19, same-site-flag
// Step 20. If the cookie-name begins with a case-insensitive match for the string "__Secure-",
// abort these steps and ignore the cookie entirely unless the cookie's secure-only-flag is true.
let has_case_insensitive_prefix = |value: &str, prefix: &str| {
value
.get(..prefix.len())
.is_some_and(|p| p.eq_ignore_ascii_case(prefix))
};
if has_case_insensitive_prefix(cookie.name(), "__Secure-") &&
!cookie.secure().unwrap_or(false)
{
return None;
}
// Step 21. If the cookie-name begins with a case-insensitive match for the string "__Host-",
// abort these steps and ignore the cookie entirely unless the cookie meets all the following criteria:
if has_case_insensitive_prefix(cookie.name(), "__Host-") {
// 1. The cookie's secure-only-flag is true.
if !secure_only {
return None;
}
// 2. The cookie's host-only-flag is true.
if !host_only {
return None;
}
// 3. The cookie-attribute-list contains an attribute with an attribute-name of "Path",
// and the cookie's path is /.
if !has_path_specified || !cookie.path().is_some_and(|path| path == "/") {
return None;
}
}
// Step 22. If the cookie-name is empty and either of the following conditions are true,
// abort these steps and ignore the cookie entirely:
if cookie.name().is_empty() {
// 1. the cookie-value begins with a case-insensitive match for the string "__Secure-"
if has_case_insensitive_prefix(cookie.value(), "__Secure-") {
return None;
}
// 2. the cookie-value begins with a case-insensitive match for the string "__Host-"
if has_case_insensitive_prefix(cookie.value(), "__Host-") {
return None;
}
}
Some(ServoCookie {
cookie,
host_only,
persistent,
creation_time: SystemTime::now(),
last_access: SystemTime::now(),
expiry_time,
})
}
pub fn touch(&mut self) {
self.last_access = SystemTime::now();
}
pub fn set_expiry_time_in_past(&mut self) {
self.expiry_time = Some(SystemTime::UNIX_EPOCH)
}
/// <http://tools.ietf.org/html/rfc6265#section-5.1.4>
pub fn default_path(request_path: &str) -> &str {
// Step 2
if !request_path.starts_with('/') {
return "/";
}
// Step 3
let rightmost_slash_idx = request_path.rfind('/').unwrap();
if rightmost_slash_idx == 0 {
// There's only one slash; it's the first character
return "/";
}
// Step 4
&request_path[..rightmost_slash_idx]
}
/// <http://tools.ietf.org/html/rfc6265#section-5.1.4>
pub fn path_match(request_path: &str, cookie_path: &str) -> bool {
// A request-path path-matches a given cookie-path if at least one of
// the following conditions holds:
// The cookie-path and the request-path are identical.
request_path == cookie_path ||
(request_path.starts_with(cookie_path) &&
(
// The cookie-path is a prefix of the request-path, and the last
// character of the cookie-path is %x2F ("/").
cookie_path.ends_with('/') ||
// The cookie-path is a prefix of the request-path, and the first
// character of the request-path that is not included in the cookie-
// path is a %x2F ("/") character.
request_path[cookie_path.len()..].starts_with('/')
))
}
/// <http://tools.ietf.org/html/rfc6265#section-5.1.3>
pub fn domain_match(string: &str, domain_string: &str) -> bool {
string.eq_ignore_ascii_case(domain_string) ||
(ends_with_ignore_ascii_case(string, domain_string) &&
string.as_bytes()[string.len() - domain_string.len() - 1] == b'.' &&
string.parse::<Ipv4Addr>().is_err() &&
string.parse::<Ipv6Addr>().is_err())
}
/// <http://tools.ietf.org/html/rfc6265#section-5.4> step 1
pub fn appropriate_for_url(&self, url: &ServoUrl, source: CookieSource) -> bool {
if log_enabled!(Level::Debug) {
debug!(
" === SENT COOKIE : {} {} {:?} {:?}",
self.cookie.name(),
self.cookie.value(),
self.cookie.domain(),
self.cookie.path()
);
}
let domain = url.host_str();
// Either: The cookie's host-only-flag is true and the canonicalized host of the
// retrieval's URI is identical to the cookie's domain
// Or: The cookie's host-only-flag is false and the canonicalized host of the
// retrieval's URI domain-matches the cookie's domain
if self.host_only {
if self.cookie.domain() != domain {
return false;
}
} else if let (Some(domain), Some(cookie_domain)) = (domain, &self.cookie.domain()) &&
!ServoCookie::domain_match(domain, cookie_domain)
{
return false;
}
// The retrieval's URI's path path-matches the cookie's path.
if let Some(cookie_path) = self.cookie.path() &&
!ServoCookie::path_match(url.path(), cookie_path)
{
return false;
}
// If the cookie's secure-only-flag is true, then the retrieval's URI must denote a "secure" connection
if self.cookie.secure().unwrap_or(false) && !url.is_secure_scheme() {
return false;
}
// If the cookie's http-only-flag is true, then exclude the cookie if the retrieval's type is "non-HTTP"
if self.cookie.http_only().unwrap_or(false) && source == CookieSource::NonHTTP {
return false;
}
// TODO: Apply same site checks
// TOOD: Apply Partitioning checks
true
}
/// <https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-20.html#name-dates>
pub fn parse_date(string: &str) -> Option<OffsetDateTime> {
let string_in_bytes = string.as_bytes();
// Helper closures
let parse_ascii_u8 =
|bytes: &[u8]| -> Option<u8> { std::str::from_utf8(bytes).ok()?.parse::<u8>().ok() };
let parse_ascii_i32 =
|bytes: &[u8]| -> Option<i32> { std::str::from_utf8(bytes).ok()?.parse::<i32>().ok() };
// Step 1. Using the grammar below, divide the cookie-date into date-tokens.
// *OCTET
let any_octets = |input| Ok(("".as_bytes(), input));
// delimiter = %x09 / %x20-2F / %x3B-40 / %x5B-60 / %x7B-7E
let delimiter: fn(&[u8]) -> IResult<&[u8], u8> = |input| {
let (input, bytes) = take(1usize)(input)?;
if matches!(bytes[0], 0x09 | 0x20..=0x2F | 0x3B..=0x40 | 0x5B..=0x60 | 0x7B..=0x7E) {
Ok((input, bytes[0]))
} else {
Err(nom::Err::Error(nom::error::Error::new(
input,
nom::error::ErrorKind::Verify,
)))
}
};
// non-delimiter = %x00-08 / %x0A-1F / DIGIT / ":" / ALPHA / %x7F-FF
let non_delimiter: fn(&[u8]) -> IResult<&[u8], u8> = |input| {
let (input, bytes) = take(1usize)(input)?;
if matches!(bytes[0],
0x00..=0x08 | 0x0A..=0x1F | b'0'..=b'9' | b':' | b'A'..=b'Z' | b'a'..=b'z' | 0x7F..=0xFF)
{
Ok((input, bytes[0]))
} else {
Err(nom::Err::Error(nom::error::Error::new(
input,
nom::error::ErrorKind::Verify,
)))
}
};
// non-digit = %x00-2F / %x3A-FF
let non_digit: fn(&[u8]) -> IResult<&[u8], u8> = |input| {
let (input, bytes) = take(1usize)(input)?;
if matches!(bytes[0], 0x00..=0x2F | 0x3A..=0xFF) {
Ok((input, bytes[0]))
} else {
Err(nom::Err::Error(nom::error::Error::new(
input,
nom::error::ErrorKind::Verify,
)))
}
};
// time-field = 1*2DIGIT
let time_field =
|input| take_while_m_n(1, 2, |byte: u8| byte.is_ascii_digit()).parse(input);
// hms-time = time-field ":" time-field ":" time-field
let hms_time = |input| {
(
time_field,
preceded(tag(":"), time_field),
preceded(tag(":"), time_field),
)
.parse(input)
};
// time = hms-time [ non-digit *OCTET ]
let time = |input| terminated(hms_time, opt((non_digit, any_octets))).parse(input);
// year = 2*4DIGIT [ non-digit *OCTET ]
let year = |input| {
terminated(
take_while_m_n(2, 4, |byte: u8| byte.is_ascii_digit()),
opt((non_digit, any_octets)),
)
.parse(input)
};
// month = ( "jan" / "feb" / "mar" / "apr" /
// "may" / "jun" / "jul" / "aug" /
// "sep" / "oct" / "nov" / "dec" ) *OCTET
let month = |input| {
terminated(
alt((
value(Month::January, tag_no_case("jan")),
value(Month::February, tag_no_case("feb")),
value(Month::March, tag_no_case("mar")),
value(Month::April, tag_no_case("apr")),
value(Month::May, tag_no_case("may")),
value(Month::June, tag_no_case("jun")),
value(Month::July, tag_no_case("jul")),
value(Month::August, tag_no_case("aug")),
value(Month::September, tag_no_case("sep")),
value(Month::October, tag_no_case("oct")),
value(Month::November, tag_no_case("nov")),
value(Month::December, tag_no_case("dec")),
)),
any_octets,
)
.parse(input)
};
// day-of-month = 1*2DIGIT [ non-digit *OCTET ]
let day_of_month = |input| {
terminated(
take_while_m_n(1, 2, |byte: u8| byte.is_ascii_digit()),
opt((non_digit, any_octets)),
)
.parse(input)
};
// date-token = 1*non-delimiter
let date_token = |input| recognize(many1(non_delimiter)).parse(input);
// date-token-list = date-token *( 1*delimiter date-token )
let date_token_list = |input| separated_list1(delimiter, date_token).parse(input);
// cookie-date = *delimiter date-token-list *delimiter
let cookie_date =
|input| delimited(many0(delimiter), date_token_list, many0(delimiter)).parse(input);
// Step 2. Process each date-token sequentially in the order the date-tokens appear in the cookie-date:
let mut time_value: Option<(u8, u8, u8)> = None; // Also represents found-time flag.
let mut day_of_month_value: Option<u8> = None; // Also represents found-day-of-month flag.
let mut month_value: Option<Month> = None; // Also represents found-month flag.
let mut year_value: Option<i32> = None; // Also represents found-year flag.
let (_, date_tokens) = cookie_date(string_in_bytes).ok()?;
for date_token in date_tokens {
// Step 2.1. If the found-time flag is not set and the token matches the time production,
if time_value.is_none() &&
let Ok((_, result)) = time(date_token)
{
// set the found-time flag and set the hour-value, minute-value, and
// second-value to the numbers denoted by the digits in the date-token,
// respectively.
if let (Some(hour), Some(minute), Some(second)) = (
parse_ascii_u8(result.0),
parse_ascii_u8(result.1),
parse_ascii_u8(result.2),
) {
time_value = Some((hour, minute, second));
}
// Skip the remaining sub-steps and continue to the next date-token.
continue;
}
// Step 2.2. If the found-day-of-month flag is not set and the date-token matches the
// day-of-month production,
if day_of_month_value.is_none() &&
let Ok((_, result)) = day_of_month(date_token)
{
// set the found-day-of-month flag and set the day-of-month-value to the number
// denoted by the date-token.
day_of_month_value = parse_ascii_u8(result);
// Skip the remaining sub-steps and continue to the next date-token.
continue;
}
// Step 2.3. If the found-month flag is not set and the date-token matches the month production,
if month_value.is_none() &&
let Ok((_, result)) = month(date_token)
{
// set the found-month flag and set the month-value to the month denoted by the date-token.
month_value = Some(result);
// Skip the remaining sub-steps and continue to the next date-token.
continue;
}
// Step 2.4. If the found-year flag is not set and the date-token matches the year production,
if year_value.is_none() &&
let Ok((_, result)) = year(date_token)
{
// set the found-year flag and set the year-value to the number denoted by the date-token.
year_value = parse_ascii_i32(result);
// Skip the remaining sub-steps and continue to the next date-token.
continue;
}
}
// Step 3. If the year-value is greater than or equal to 70 and less than or equal to 99,
// increment the year-value by 1900.
if let Some(value) = year_value &&
(70..=99).contains(&value)
{
year_value = Some(value + 1900);
}
// Step 4. If the year-value is greater than or equal to 0 and less than or equal to 69,
// increment the year-value by 2000.
if let Some(value) = year_value &&
(0..=69).contains(&value)
{
year_value = Some(value + 2000);
}
// Step 5. Abort these steps and fail to parse the cookie-date if:
// * at least one of the found-day-of-month, found-month, found-year, or found-time flags is not set,
if day_of_month_value.is_none() ||
month_value.is_none() ||
year_value.is_none() ||
time_value.is_none()
{
return None;
}
// * the day-of-month-value is less than 1 or greater than 31,
if let Some(value) = day_of_month_value &&
!(1..=31).contains(&value)
{
return None;
}
// * the year-value is less than 1601,
if let Some(value) = year_value &&
value < 1601
{
return None;
}
// * the hour-value is greater than 23,
// * the minute-value is greater than 59, or
// * the second-value is greater than 59.
if let Some((hour_value, minute_value, second_value)) = time_value &&
(hour_value > 23 || minute_value > 59 || second_value > 59)
{
return None;
}
// Step 6. Let the parsed-cookie-date be the date whose day-of-month, month, year, hour,
// minute, and second (in UTC) are the day-of-month-value, the month-value, the year-value,
// the hour-value, the minute-value, and the second-value, respectively. If no such date
// exists, abort these steps and fail to parse the cookie-date.
let parsed_cookie_date = OffsetDateTime::new_utc(
Date::from_calendar_date(
year_value.unwrap(),
month_value.unwrap(),
day_of_month_value.unwrap(),
)
.ok()?,
Time::from_hms(
time_value.unwrap().0,
time_value.unwrap().1,
time_value.unwrap().2,
)
.ok()?,
);
// Step 7. Return the parsed-cookie-date as the result of this algorithm.
Some(parsed_cookie_date)
}
/// Returns true if the slice only contains bytes that are safe to use in cookie strings.
/// Rejects 0x7f, and values < 0x1f except 0x09
/// <https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6-6>
pub fn is_valid_name_or_value(bytes: &[u8]) -> bool {
!bytes
.iter()
.any(|c| *c == 0x7f || (*c <= 0x1f && *c != 0x09))
}
}

353
vendor/servo-net/cookie_storage.rs vendored Normal file
View file

@ -0,0 +1,353 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Implementation of cookie storage as specified in
//! <http://tools.ietf.org/html/rfc6265>
use std::cmp::Ordering;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::net::IpAddr;
use std::time::SystemTime;
use cookie::Cookie;
use itertools::Itertools;
use log::info;
use malloc_size_of_derive::MallocSizeOf;
use net_traits::pub_domains::reg_suffix;
use net_traits::{CookieSource, SiteDescriptor};
use serde::{Deserialize, Serialize};
use servo_url::ServoUrl;
use crate::cookie::ServoCookie;
#[derive(Clone, Debug, Deserialize, Serialize, MallocSizeOf)]
pub struct CookieStorage {
version: u32,
cookies_map: HashMap<String, Vec<ServoCookie>>,
max_per_host: usize,
}
#[derive(Debug)]
pub enum RemoveCookieError {
Overlapping,
NonHTTP,
}
impl CookieStorage {
pub fn new(max_cookies: usize) -> CookieStorage {
CookieStorage {
version: 1,
cookies_map: HashMap::new(),
max_per_host: max_cookies,
}
}
// http://tools.ietf.org/html/rfc6265#section-5.3
pub fn remove(
&mut self,
cookie: &ServoCookie,
url: &ServoUrl,
source: CookieSource,
) -> Result<Option<ServoCookie>, RemoveCookieError> {
let domain = reg_host(cookie.cookie.domain().as_ref().unwrap_or(&""));
let cookies = self.cookies_map.entry(domain).or_default();
// https://www.ietf.org/id/draft-ietf-httpbis-cookie-alone-01.txt Step 2
if !cookie.cookie.secure().unwrap_or(false) && !url.is_secure_scheme() {
let new_domain = cookie.cookie.domain().as_ref().unwrap().to_owned();
let new_path = cookie.cookie.path().as_ref().unwrap().to_owned();
let any_overlapping = cookies.iter().any(|c| {
let existing_domain = c.cookie.domain().as_ref().unwrap().to_owned();
let existing_path = c.cookie.path().as_ref().unwrap().to_owned();
c.cookie.name() == cookie.cookie.name() &&
c.cookie.secure().unwrap_or(false) &&
(ServoCookie::domain_match(new_domain, existing_domain) ||
ServoCookie::domain_match(existing_domain, new_domain)) &&
ServoCookie::path_match(new_path, existing_path)
});
if any_overlapping {
return Err(RemoveCookieError::Overlapping);
}
}
// Step 11.1
let position = cookies.iter().position(|c| {
c.cookie.domain() == cookie.cookie.domain() &&
c.cookie.path() == cookie.cookie.path() &&
c.cookie.name() == cookie.cookie.name()
});
if let Some(ind) = position {
// Step 11.4
let c = cookies.remove(ind);
// http://tools.ietf.org/html/rfc6265#section-5.3 step 11.2
if c.cookie.http_only().unwrap_or(false) && source == CookieSource::NonHTTP {
// Undo the removal.
cookies.push(c);
Err(RemoveCookieError::NonHTTP)
} else {
Ok(Some(c))
}
} else {
Ok(None)
}
}
pub fn delete_cookies_for_sites(&mut self, sites: &Vec<String>) {
// Note: We assume the number of sites is smaller than the number of
// entries in the cookies map. If this assumption stops holding in
// practice, this implementation can be revised to use `retain`
// together with a temporary `HashSet` of sites.
for site in sites {
// TODO: We currently mark cookies as expired instead of removing
// them immediately (same behavior as in the functions below).
// This is safe because higher-level cookie accessors always call
// `remove_expired_cookies_for_url` / `remove_all_expired_cookies`.
// Consider whether we should instead delete the entries directly.
if let Some(cookies) = self.cookies_map.get_mut(site) {
for cookie in cookies.iter_mut() {
cookie.set_expiry_time_in_past();
}
}
}
}
pub fn clear_session_cookies(&mut self) {
self.cookies_map
.values_mut()
.flat_map(|cookies| cookies.iter_mut())
.filter(|cookie| !cookie.persistent)
.for_each(|cookie| cookie.set_expiry_time_in_past());
}
pub fn clear_storage(&mut self, url: Option<&ServoUrl>) {
if let Some(url) = url {
let domain = reg_host(url.host_str().unwrap_or(""));
if let Some(cookies) = self.cookies_map.get_mut(&domain) {
for cookie in cookies.iter_mut() {
cookie.set_expiry_time_in_past();
}
}
} else {
self.cookies_map.clear();
}
}
pub fn delete_cookie_with_name(&mut self, url: &ServoUrl, name: String) {
let domain = reg_host(url.host_str().unwrap_or(""));
if let Some(cookies) = self.cookies_map.get_mut(&domain) {
for cookie in cookies.iter_mut() {
if cookie.cookie.name() == name {
cookie.set_expiry_time_in_past();
}
}
}
}
// http://tools.ietf.org/html/rfc6265#section-5.3
pub fn push(&mut self, mut cookie: ServoCookie, url: &ServoUrl, source: CookieSource) {
// https://www.ietf.org/id/draft-ietf-httpbis-cookie-alone-01.txt Step 1
if cookie.cookie.secure().unwrap_or(false) && !url.is_secure_scheme() {
return;
}
let old_cookie = self.remove(&cookie, url, source);
if old_cookie.is_err() {
// This new cookie is not allowed to overwrite an existing one.
return;
}
// Step 11
if let Some(old_cookie) = old_cookie.unwrap() {
// Step 11.3
cookie.creation_time = old_cookie.creation_time;
}
// Step 12
let domain = reg_host(cookie.cookie.domain().as_ref().unwrap_or(&""));
let cookies = self.cookies_map.entry(domain).or_default();
if cookies.len() == self.max_per_host {
let old_len = cookies.len();
cookies.retain(|c| !is_cookie_expired(c));
let new_len = cookies.len();
// https://www.ietf.org/id/draft-ietf-httpbis-cookie-alone-01.txt
if new_len == old_len &&
!evict_one_cookie(cookie.cookie.secure().unwrap_or(false), cookies)
{
return;
}
}
cookies.push(cookie);
}
pub fn cookie_comparator(a: &ServoCookie, b: &ServoCookie) -> Ordering {
let a_path_len = a.cookie.path().as_ref().map_or(0, |p| p.len());
let b_path_len = b.cookie.path().as_ref().map_or(0, |p| p.len());
match a_path_len.cmp(&b_path_len) {
Ordering::Equal => a.creation_time.cmp(&b.creation_time),
// Ensure that longer paths are sorted earlier than shorter paths
Ordering::Greater => Ordering::Less,
Ordering::Less => Ordering::Greater,
}
}
pub fn remove_expired_cookies_for_url(&mut self, url: &ServoUrl) {
let domain = reg_host(url.host_str().unwrap_or(""));
if let Entry::Occupied(mut entry) = self.cookies_map.entry(domain) {
let cookies = entry.get_mut();
cookies.retain(|c| !is_cookie_expired(c));
if cookies.is_empty() {
entry.remove_entry();
}
}
}
pub fn remove_all_expired_cookies(&mut self) {
self.cookies_map.retain(|_, cookies| {
cookies.retain(|c| !is_cookie_expired(c));
!cookies.is_empty()
});
}
// http://tools.ietf.org/html/rfc6265#section-5.4
pub fn cookies_for_url(&mut self, url: &ServoUrl, source: CookieSource) -> Option<String> {
// Let cookie-list be the set of cookies from the cookie store
let cookie_list = self.cookies_data_for_url(url, source);
let reducer = |acc: String, cookie: Cookie<'static>| -> String {
// Serialize the cookie-list into a cookie-string by processing each cookie in the cookie-list in order:
// If the cookies' name is not empty, output the cookie's name followed by the %x3D ("=") character.
// If the cookies' value is not empty, output the cookie's value.
// If there is an unprocessed cookie in the cookie-list, output the characters %x3B and %x20 ("; ").
// Security: the above steps allow for "nameless" cookies which have proved to be a security footgun
// especially with the new cookie name prefix proposals
(match acc.len() {
0 => acc,
_ => acc + "; ",
}) + cookie.name() +
"=" +
cookie.value()
};
// Serialize the cookie-list into a cookie-string by processing each cookie in the cookie-list in order
let result = cookie_list.fold(String::new(), reducer);
info!(" === COOKIES SENT: {}", result);
match result.len() {
0 => None,
_ => Some(result),
}
}
/// <https://cookiestore.spec.whatwg.org/#query-cookies>
pub fn query_cookies(&mut self, url: &ServoUrl, name: Option<String>) -> Vec<Cookie<'static>> {
// 1. Retrieve cookie-list given request-uri and "non-HTTP" source
let cookie_list = self.cookies_data_for_url(url, CookieSource::NonHTTP);
// 3. For each cookie in cookie-list, run these steps:
// 3.2. If name is given, then run these steps:
if let Some(name) = name {
// Let cookieName be the result of running UTF-8 decode without BOM on cookie’s name.
// If cookieName does not equal name, then continue.
cookie_list.filter(|cookie| cookie.name() == name).collect()
} else {
cookie_list.collect()
}
// Note: we do not convert the list into CookieListItem's here, we do that in script to not not have to define
// the binding types in net.
// Return list
}
pub fn cookies_data_for_url<'a>(
&'a mut self,
url: &'a ServoUrl,
source: CookieSource,
) -> impl Iterator<Item = cookie::Cookie<'static>> + 'a {
let domain = reg_host(url.host_str().unwrap_or(""));
let cookies = self.cookies_map.entry(domain).or_default();
cookies
.iter_mut()
.filter(move |c| c.appropriate_for_url(url, source))
.sorted_by(|a: &&mut ServoCookie, b: &&mut ServoCookie| {
// The user agent SHOULD sort the cookie-list
CookieStorage::cookie_comparator(a, b)
})
.map(|c| {
// Update the last-access-time of each cookie in the cookie-list to the current date and time
c.touch();
c.cookie.clone()
})
}
pub fn cookie_site_descriptors(&self) -> Vec<SiteDescriptor> {
self.cookies_map
.keys()
.cloned()
.map(SiteDescriptor::new)
.collect()
}
}
fn reg_host(url: &str) -> String {
let host_for_ip_parse = url
.strip_prefix('[')
.and_then(|url| url.strip_suffix(']'))
.unwrap_or(url);
if let Ok(address) = host_for_ip_parse.parse::<IpAddr>() {
debug_assert!(address.to_string() == address.to_string().to_lowercase());
return address.to_string();
}
reg_suffix(url).to_lowercase()
}
fn is_cookie_expired(cookie: &ServoCookie) -> bool {
matches!(cookie.expiry_time, Some(date_time) if date_time <= SystemTime::now())
}
fn evict_one_cookie(is_secure_cookie: bool, cookies: &mut Vec<ServoCookie>) -> bool {
// Remove non-secure cookie with oldest access time
let oldest_accessed = get_oldest_accessed(false, cookies);
if let Some((index, _)) = oldest_accessed {
cookies.remove(index);
} else {
// All secure cookies were found
if !is_secure_cookie {
return false;
}
let oldest_accessed = get_oldest_accessed(true, cookies);
if let Some((index, _)) = oldest_accessed {
cookies.remove(index);
}
}
true
}
fn get_oldest_accessed(
is_secure_cookie: bool,
cookies: &mut [ServoCookie],
) -> Option<(usize, SystemTime)> {
let mut oldest_accessed = None;
for (i, c) in cookies.iter().enumerate() {
if (c.cookie.secure().unwrap_or(false) == is_secure_cookie) &&
oldest_accessed
.as_ref()
.is_none_or(|(_, current_oldest_time)| c.last_access < *current_oldest_time)
{
oldest_accessed = Some((i, c.last_access));
}
}
oldest_accessed
}

352
vendor/servo-net/decoder.rs vendored Normal file
View file

@ -0,0 +1,352 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Adapted from an implementation in reqwest.
/*!
A non-blocking response decoder.
The decoder wraps a stream of bytes and produces a new stream of decompressed bytes.
The decompressed bytes aren't guaranteed to align to the compressed ones.
If the response is plaintext then no additional work is carried out.
Bytes are just passed along.
If the response is gzip, deflate or brotli then the bytes are decompressed.
*/
use std::error::Error;
use std::fmt;
use std::io::{self};
use std::pin::Pin;
use async_compression::tokio::bufread::{BrotliDecoder, GzipDecoder, ZlibDecoder, ZstdDecoder};
use bytes::Bytes;
use futures::stream::Peekable;
use futures::task::{Context, Poll};
use futures::{Future, Stream};
use futures_util::StreamExt;
use headers::{ContentLength, HeaderMapExt};
use http_body_util::BodyExt;
use hyper::Response;
use hyper::body::Body;
use hyper::header::{CONTENT_ENCODING, HeaderValue, TRANSFER_ENCODING};
use tokio_util::codec::{BytesCodec, FramedRead};
use tokio_util::io::StreamReader;
use crate::connector::BoxedBody;
pub const DECODER_BUFFER_SIZE: usize = 8192;
/// Marker wrapper for errors that originate from the network body stream
#[derive(Debug)]
pub struct BodyStreamError(pub Box<dyn Error + Send + Sync>);
impl fmt::Display for BodyStreamError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl Error for BodyStreamError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(self.0.as_ref())
}
}
/// Normalize errors produced by the decompressors to `ErrorKind::InvalidData`
/// so that `http_loader` reports them as `NetworkError::DecompressionError`.
pub fn map_decode_error(err: io::Error) -> io::Error {
if err.kind() == io::ErrorKind::InvalidData {
return err;
}
let mut source: Option<&(dyn Error + 'static)> = err.get_ref().map(|e| e as _);
while let Some(e) = source {
if e.is::<BodyStreamError>() {
return err;
}
source = match e.downcast_ref::<io::Error>() {
Some(io_error) => io_error.get_ref().map(|e| e as _),
None => e.source(),
};
}
io::Error::new(io::ErrorKind::InvalidData, err)
}
/// A response decompressor over a non-blocking stream of bytes.
///
/// The inner decoder may be constructed asynchronously.
pub struct Decoder {
inner: Inner,
}
#[derive(PartialEq)]
enum DecoderType {
Gzip,
Brotli,
Deflate,
Zstd,
}
enum Inner {
/// A `PlainText` decoder just returns the response content as is.
PlainText(BodyStream),
/// A `Gzip` decoder will uncompress the gzipped response content before returning it.
Gzip(FramedRead<GzipDecoder<StreamReader<Peekable<BodyStream>, Bytes>>, BytesCodec>),
/// A `Delfate` decoder will uncompress the inflated response content before returning it.
Deflate(FramedRead<ZlibDecoder<StreamReader<Peekable<BodyStream>, Bytes>>, BytesCodec>),
/// A `Brotli` decoder will uncompress the brotli-encoded response content before returning it.
Brotli(FramedRead<BrotliDecoder<StreamReader<Peekable<BodyStream>, Bytes>>, BytesCodec>),
/// A `Zstd` decoder will uncompress the zstd-encoded response content before returning it.
Zstd(FramedRead<ZstdDecoder<StreamReader<Peekable<BodyStream>, Bytes>>, BytesCodec>),
/// A decoder that doesn't have a value yet.
Pending(Pending),
}
/// A future attempt to poll the response body for EOF so we know whether to use gzip or not.
struct Pending {
body: Peekable<BodyStream>,
type_: DecoderType,
}
impl fmt::Debug for Decoder {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Decoder").finish()
}
}
impl Decoder {
/// A plain text decoder.
///
/// This decoder will emit the underlying bytes as-is.
#[inline]
fn plain_text(
body: BoxedBody,
is_secure_scheme: bool,
content_length: Option<ContentLength>,
) -> Decoder {
Decoder {
inner: Inner::PlainText(BodyStream::new(body, is_secure_scheme, content_length)),
}
}
/// A pending decoder.
///
/// This decoder will buffer and decompress bytes that are encoded in the expected format.
#[inline]
fn pending(
body: BoxedBody,
type_: DecoderType,
is_secure_scheme: bool,
content_length: Option<ContentLength>,
) -> Decoder {
Decoder {
inner: Inner::Pending(Pending {
body: BodyStream::new(body, is_secure_scheme, content_length).peekable(),
type_,
}),
}
}
/// Returns true if the content is encoded
pub fn is_encoded(&self) -> bool {
!matches!(self.inner, Inner::PlainText(_))
}
/// Constructs a Decoder from a hyper response.
///
/// A decoder is just a wrapper around the hyper response that knows
/// how to decode the content body of the response.
///
/// Uses the correct variant by inspecting the Content-Encoding header.
pub fn detect(response: Response<BoxedBody>, is_secure_scheme: bool) -> Response<Decoder> {
let values = response
.headers()
.get_all(CONTENT_ENCODING)
.iter()
.chain(response.headers().get_all(TRANSFER_ENCODING).iter());
let decoder = values.fold(None, |acc, enc| {
acc.or_else(|| {
if enc == HeaderValue::from_static("gzip") {
Some(DecoderType::Gzip)
} else if enc == HeaderValue::from_static("br") {
Some(DecoderType::Brotli)
} else if enc == HeaderValue::from_static("deflate") {
Some(DecoderType::Deflate)
} else if enc == HeaderValue::from_static("zstd") {
Some(DecoderType::Zstd)
} else {
None
}
})
});
let content_length = response.headers().typed_get::<ContentLength>();
match decoder {
Some(type_) => {
response.map(|r| Decoder::pending(r, type_, is_secure_scheme, content_length))
},
None => response.map(|r| Decoder::plain_text(r, is_secure_scheme, content_length)),
}
}
}
impl Stream for Decoder {
type Item = Result<Bytes, io::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
// Do a read or poll for a pending decoder value.
match self.inner {
Inner::Pending(ref mut future) => match futures_core::ready!(Pin::new(future).poll(cx))
{
Ok(inner) => {
self.inner = inner;
self.poll_next(cx)
},
Err(e) => Poll::Ready(Some(Err(e))),
},
Inner::PlainText(ref mut body) => Pin::new(body).poll_next(cx),
Inner::Gzip(ref mut decoder) => {
match futures_core::ready!(Pin::new(decoder).poll_next(cx)) {
Some(Ok(bytes)) => Poll::Ready(Some(Ok(bytes.freeze()))),
Some(Err(err)) => Poll::Ready(Some(Err(map_decode_error(err)))),
None => Poll::Ready(None),
}
},
Inner::Brotli(ref mut decoder) => {
match futures_core::ready!(Pin::new(decoder).poll_next(cx)) {
Some(Ok(bytes)) => Poll::Ready(Some(Ok(bytes.freeze()))),
Some(Err(err)) => Poll::Ready(Some(Err(map_decode_error(err)))),
None => Poll::Ready(None),
}
},
Inner::Deflate(ref mut decoder) => {
match futures_core::ready!(Pin::new(decoder).poll_next(cx)) {
Some(Ok(bytes)) => Poll::Ready(Some(Ok(bytes.freeze()))),
Some(Err(err)) => Poll::Ready(Some(Err(map_decode_error(err)))),
None => Poll::Ready(None),
}
},
Inner::Zstd(ref mut decoder) => {
match futures_core::ready!(Pin::new(decoder).poll_next(cx)) {
Some(Ok(bytes)) => Poll::Ready(Some(Ok(bytes.freeze()))),
Some(Err(err)) => Poll::Ready(Some(Err(map_decode_error(err)))),
None => Poll::Ready(None),
}
},
}
}
}
impl Future for Pending {
type Output = Result<Inner, io::Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match futures_core::ready!(Pin::new(&mut self.body).poll_peek(cx)) {
Some(Ok(_)) => {
// fallthrough
},
Some(Err(_e)) => {
// error was just a ref, so we need to really poll to move it
return Poll::Ready(Err(futures_core::ready!(
Pin::new(&mut self.body).poll_next(cx)
)
.expect("just peeked Some")
.unwrap_err()));
},
None => return Poll::Ready(Ok(Inner::PlainText(BodyStream::empty()))),
};
let body = std::mem::replace(&mut self.body, BodyStream::empty().peekable());
match self.type_ {
DecoderType::Brotli => Poll::Ready(Ok(Inner::Brotli(FramedRead::with_capacity(
BrotliDecoder::new(StreamReader::new(body)),
BytesCodec::new(),
DECODER_BUFFER_SIZE,
)))),
DecoderType::Gzip => Poll::Ready(Ok(Inner::Gzip(FramedRead::with_capacity(
GzipDecoder::new(StreamReader::new(body)),
BytesCodec::new(),
DECODER_BUFFER_SIZE,
)))),
DecoderType::Deflate => Poll::Ready(Ok(Inner::Deflate(FramedRead::with_capacity(
ZlibDecoder::new(StreamReader::new(body)),
BytesCodec::new(),
DECODER_BUFFER_SIZE,
)))),
DecoderType::Zstd => Poll::Ready(Ok(Inner::Zstd(FramedRead::with_capacity(
ZstdDecoder::new(StreamReader::new(body)),
BytesCodec::new(),
DECODER_BUFFER_SIZE,
)))),
}
}
}
struct BodyStream {
body: BoxedBody,
is_secure_scheme: bool,
content_length: Option<ContentLength>,
total_read: u64,
}
impl BodyStream {
fn empty() -> Self {
BodyStream {
body: http_body_util::Empty::new()
.map_err(|_| unreachable!())
.boxed(),
is_secure_scheme: false,
content_length: None,
total_read: 0,
}
}
fn new(body: BoxedBody, is_secure_scheme: bool, content_length: Option<ContentLength>) -> Self {
BodyStream {
body,
is_secure_scheme,
content_length,
total_read: 0,
}
}
}
impl Stream for BodyStream {
type Item = Result<Bytes, io::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
match futures_core::ready!(Pin::new(&mut self.body).poll_frame(cx)) {
Some(Ok(bytes)) => {
let Ok(bytes) = bytes.into_data() else {
return Poll::Ready(None);
};
self.total_read += bytes.len() as u64;
Poll::Ready(Some(Ok(bytes)))
},
Some(Err(err)) => {
// To prevent truncation attacks rustls treats close connection without a close_notify as
// an error of type std::io::Error with ErrorKind::UnexpectedEof.
// https://docs.rs/rustls/latest/rustls/manual/_03_howto/index.html#unexpected-eof
//
// The error can be safely ignored if we known that all content was received or is explicitly
// set in preferences.
let all_content_read = self.content_length.is_some_and(|c| c.0 == self.total_read);
if self.is_secure_scheme && all_content_read {
let source = err.source();
let is_unexpected_eof = source
.and_then(|e| e.downcast_ref::<io::Error>())
.is_some_and(|e| e.kind() == io::ErrorKind::UnexpectedEof);
if is_unexpected_eof {
return Poll::Ready(None);
}
}
Poll::Ready(Some(Err(io::Error::other(BodyStreamError(err.into())))))
},
None => Poll::Ready(None),
}
}
}

195
vendor/servo-net/devtools.rs vendored Normal file
View file

@ -0,0 +1,195 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use bytes::Bytes;
use crossbeam_channel::Sender;
use devtools_traits::{
ChromeToDevtoolsControlMsg, DevtoolsControlMsg, HttpRequest as DevtoolsHttpRequest,
HttpResponse as DevtoolsHttpResponse, NetworkEvent, SecurityInfoUpdate,
};
use http::{HeaderMap, Method};
use hyper_serde::Serde;
use log::error;
use net_traits::FetchMetadata;
use net_traits::http_status::HttpStatus;
use net_traits::request::{Destination, Request};
use net_traits::response::{CacheState, Response};
use servo_base::id::{BrowsingContextId, PipelineId};
use servo_url::ServoUrl;
use crate::fetch::methods::FetchContext;
#[expect(clippy::too_many_arguments)]
pub(crate) fn prepare_devtools_request(
request_id: String,
url: ServoUrl,
method: Method,
headers: HeaderMap,
body: Option<Vec<u8>>,
pipeline_id: PipelineId,
connect_time: Duration,
send_time: Duration,
destination: Destination,
is_xhr: bool,
browsing_context_id: BrowsingContextId,
) -> ChromeToDevtoolsControlMsg {
let started_date_time = SystemTime::now();
let request = DevtoolsHttpRequest {
url,
method,
headers,
body: body.map(Bytes::from),
pipeline_id,
started_date_time,
time_stamp: started_date_time
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64,
connect_time,
send_time,
destination,
is_xhr,
browsing_context_id,
};
let net_event = NetworkEvent::HttpRequestUpdate(request);
ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event)
}
pub(crate) fn send_request_to_devtools(
msg: ChromeToDevtoolsControlMsg,
devtools_chan: &Sender<DevtoolsControlMsg>,
) {
if matches!(msg, ChromeToDevtoolsControlMsg::NetworkEvent(_, ref network_event) if !network_event.forward_to_devtools())
{
return;
}
if let Err(e) = devtools_chan.send(DevtoolsControlMsg::FromChrome(msg)) {
error!("DevTools send failed: {e}");
}
}
pub(crate) fn send_response_to_devtools(
request: &Request,
context: &FetchContext,
response: &Response,
body_data: Option<Vec<u8>>,
) {
let meta = match response.metadata() {
Ok(FetchMetadata::Unfiltered(m)) => m,
Ok(FetchMetadata::Filtered { unsafe_, .. }) => unsafe_,
Err(_) => {
log::warn!("No metadata available, skipping devtools response.");
return;
},
};
send_response_values_to_devtools(
meta.headers.map(Serde::into_inner),
meta.status,
body_data,
response.cache_state,
request,
context.devtools_chan.clone(),
);
}
pub(crate) fn send_response_values_to_devtools(
headers: Option<HeaderMap>,
status: HttpStatus,
body: Option<Vec<u8>>,
cache_state: CacheState,
request: &Request,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
) {
if let (Some(devtools_chan), Some(pipeline_id), Some(webview_id)) = (
devtools_chan,
request.pipeline_id,
request.target_webview_id,
) {
let browsing_context_id = webview_id.into();
let from_cache = matches!(cache_state, CacheState::Local | CacheState::Validated);
let devtoolsresponse = DevtoolsHttpResponse {
headers,
status,
body: body.map(Bytes::from),
from_cache,
pipeline_id,
browsing_context_id,
};
let net_event_response = NetworkEvent::HttpResponse(devtoolsresponse);
let msg =
ChromeToDevtoolsControlMsg::NetworkEvent(request.id.0.to_string(), net_event_response);
let _ = devtools_chan.send(DevtoolsControlMsg::FromChrome(msg));
}
}
pub(crate) fn send_security_info_to_devtools(
request: &Request,
context: &FetchContext,
response: &Response,
) {
let meta = match response.metadata() {
Ok(FetchMetadata::Unfiltered(m)) => m,
Ok(FetchMetadata::Filtered { unsafe_, .. }) => unsafe_,
Err(_) => {
log::warn!("No metadata available, skipping devtools security info.");
return;
},
};
if let (Some(devtools_chan), Some(security_info), Some(webview_id)) = (
context.devtools_chan.clone(),
meta.tls_security_info,
request.target_webview_id,
) {
let update = NetworkEvent::SecurityInfo(SecurityInfoUpdate {
browsing_context_id: webview_id.into(),
security_info: Some(security_info),
});
let msg = ChromeToDevtoolsControlMsg::NetworkEvent(request.id.0.to_string(), update);
let _ = devtools_chan.send(DevtoolsControlMsg::FromChrome(msg));
}
}
pub(crate) fn send_early_httprequest_to_devtools(request: &Request, context: &FetchContext) {
// Do not forward data requests to devtools
if request.url().scheme() == "data" {
return;
}
if let (Some(devtools_chan), Some(browsing_context_id), Some(pipeline_id)) = (
context.devtools_chan.as_ref(),
request.target_webview_id.map(|id| id.into()),
request.pipeline_id,
) {
// Build the partial DevtoolsHttpRequest
let devtools_request = DevtoolsHttpRequest {
url: request.current_url(),
method: request.method.clone(),
headers: request.headers.clone(),
body: None,
pipeline_id,
started_date_time: SystemTime::now(),
time_stamp: 0,
connect_time: Duration::from_millis(0),
send_time: Duration::from_millis(0),
destination: request.destination,
is_xhr: false,
browsing_context_id,
};
let msg = ChromeToDevtoolsControlMsg::NetworkEvent(
request.id.0.to_string(),
NetworkEvent::HttpRequest(devtools_request),
);
send_request_to_devtools(msg, devtools_chan);
}
}

Some files were not shown because too many files have changed in this diff Show more