misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Sites that let only browsers through: one more try the way a browser connects (part of #668) (#748)
Ahmed Nefzaoui0067cd0a7a1f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 3abfa6c8..cf773ed1 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -68,13 +68,22 @@ jobs:key: ${{ runner.os }}-cargo-${{ hashFiles('Cargo.lock') }}restore-keys: ${{ runner.os }}-cargo-+ # BoringSSL, under the browser-like connection (#668, crates/engine/src/browserlike.rs), is+ # built with NASM on Windows; the runner has CMake and LLVM's libclang already.+ - name: NASM+ if: runner.os == 'Windows'+ shell: pwsh+ run: |+ choco install nasm --version 2.16.3 --no-progress -y+ "C:\Program Files\NASM" >> $env:GITHUB_PATH+- name: Linux librariesif: runner.os == 'Linux'timeout-minutes: 10run: |sudo apt-get updatesudo apt-get install -y libgtk-3-dev libxkbcommon-dev libwayland-dev libgl1-mesa-dev \- libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev+ libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev cmake libclang-dev- name: Formatif: runner.os == 'Windows'diff --git a/.github/workflows/docs-shots.yml b/.github/workflows/docs-shots.ymlindex 1b0d71ff..0d5193fc 100644--- a/.github/workflows/docs-shots.yml+++ b/.github/workflows/docs-shots.yml@@ -46,6 +46,15 @@ jobs:key: ${{ runner.os }}-cargo-${{ hashFiles('Cargo.lock') }}restore-keys: ${{ runner.os }}-cargo-+ # BoringSSL, under the browser-like connection (#668, crates/engine/src/browserlike.rs), is+ # built with NASM on Windows; the runner has CMake and LLVM's libclang already.+ - name: NASM+ if: runner.os == 'Windows'+ shell: pwsh+ run: |+ choco install nasm --version 2.16.3 --no-progress -y+ "C:\Program Files\NASM" >> $env:GITHUB_PATH+- name: Buildrun: |cargo build -p mdm-app -p mdm-labserver -p mdm-cli -p mdm-nmhostdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex e9e57992..0663be23 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -72,6 +72,15 @@ jobs:$v = [regex]::Match((Get-Content Cargo.toml -Raw), '(?m)^version\s*=\s*"([^"]+)"').Groups[1].Valueif ("v$v" -ne "${{ github.ref_name }}") { throw "tag ${{ github.ref_name }} but Cargo.toml says $v" }+ # BoringSSL, under the browser-like connection (#668, crates/engine/src/browserlike.rs), is+ # built with NASM on Windows; the runner has CMake and LLVM's libclang already.+ - name: NASM+ if: runner.os == 'Windows'+ shell: pwsh+ run: |+ choco install nasm --version 2.16.3 --no-progress -y+ "C:\Program Files\NASM" >> $env:GITHUB_PATH+- name: Testsrun: cargo test --workspace@@ -244,7 +253,8 @@ jobs:run: |sudo apt-get updatesudo apt-get install -y libgtk-3-dev libxkbcommon-dev libwayland-dev libgl1-mesa-dev \- libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev rpm python3-pil zsync+ libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev rpm python3-pil zsync \+ cmake libclang-dev- name: AppImage, tar.gz, .deb, .rpmenv:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 45785d13..98bc4e47 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see- **Deferred Rename** on a download's **Download status** tab: save a new name while a download runs (**Confirm**, **Enter**, or 3 seconds idle) to rename the finished file's stem (along with yt-dlp subtitle files) or an exclusive finished folder on completion, without touching the live stream or `.mdm.part` state; shared/save or pre-existing folders, split-archive volumes, and single-file torrents keep their original names ([#655](https://github.com/anefzaoui/misterdownloadmanager/pull/655)).- Helium: on Linux and macOS, MDM offers the extension to Helium, through Helium's own services: with them allowed, it arrives at Helium's next start (on macOS Helium asks first). It names the store as Helium does: Helium asks Google's update service without its version, and Google answers it "no update", which is why the offer MDM writes for Chrome on Windows, which Helium reads there too, never brought it the extension. On Windows MDM's window still opens the store's page in Helium. On Linux the .deb's and .rpm's helper files for everyone cover Helium too, so MDM writes none in its folder in your home. [Browser integration](docs/browser-integration.md#helium) says how to add the extension in Helium, and what to turn on when Helium says **Extension downloads are disabled** ([#685](https://github.com/anefzaoui/misterdownloadmanager/issues/685)).- Links you add by hand go with the User-Agent of your default browser, at the version you have installed (Chrome, Edge, Brave, Opera, Vivaldi, Firefox or Safari, on Windows, Linux and macOS), instead of the Internet Explorer 11 one MDM sent until now, which some sites no longer let through. MDM looks the browser up once as it starts. **Options → Downloads** shows it with **Automatic** ticked; untick it to type your own, and a User-Agent you had set stays yours. When MDM doesn't recognise your default browser, it sends a current Chrome's; when a site turns a browser's User-Agent away, it asks once more with its former one, as for downloads from the browser (part of [#668](https://github.com/anefzaoui/misterdownloadmanager/issues/668)).+- Sites that let only browsers through: when a site's bot check (Cloudflare's challenge) or its refusal of programs (FileHippo's *412 Precondition Failed*) turns MDM's own connection away, MDM asks once more connecting the way your browser does (its handshake, HTTP/2 settings and order of headers), with the download's User-Agent and your browser's cookies for that site only, and downloads on that one connection. Proxy, network adapter (it isn't tried when it can't be held to the adapter), speed limits, stop and resume apply as usual, and every other download keeps MDM's own connection. It answers no challenge: a site that still wants one solved in a browser refuses again, and MDM says so as before (Alt+click leaves the download to the browser) ([#668](https://github.com/anefzaoui/misterdownloadmanager/issues/668), [#645](https://github.com/anefzaoui/misterdownloadmanager/issues/645), [#630](https://github.com/anefzaoui/misterdownloadmanager/issues/630)).- Linux and macOS: a gallery-dl installed by the system (a package manager, Homebrew, pip) is found and used when MDM has none of its own, as yt-dlp is; **Helpers** can switch to MDM's own copy where MDM has one (Windows and Linux x86-64) ([#571](https://github.com/anefzaoui/misterdownloadmanager/issues/571)).- Videos a site sends in pieces (HLS and DASH streams, as many sites other than YouTube do) download several pieces at once, as many as **Options → Connection** gives a file (8 by default): against a test server that slows each connection, 4 at once took under a third of the time, 8 under a fifth. With a speed limit on, they still come one at a time, so the limit holds; a video in one file, as most of YouTube's are, is unchanged. The command line's `video-get` and `playlist-get` take `-c` for it ([#531](https://github.com/anefzaoui/misterdownloadmanager/issues/531)).- **TorBox** debrid accounts (experimental), in **Options → Accounts**, signed in in the browser or with your API key: file-host links, torrents and magnet links through your account ([#391](https://github.com/anefzaoui/misterdownloadmanager/issues/391)).@@ -17,6 +18,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Changed+- Building from source needs Rust 1.98 or later, CMake and libclang (and NASM on Windows): the browser-like connection is built on BoringSSL ([#668](https://github.com/anefzaoui/misterdownloadmanager/issues/668)).- Debrid accounts: signing in by code opens the page only when it is the service's own site, over https.### Fixeddiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 8dafd774..18739a4c 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -5,7 +5,9 @@ requests are all welcome.## Getting set up-You need Windows 10 or 11 and Rust stable 1.95 or later (the MSVC toolchain).+You need Windows 10 or 11 and Rust stable 1.98 or later (the MSVC toolchain), and CMake, LLVM+and NASM for BoringSSL, which the engine's browser-like connection builds from source+(`winget install Kitware.CMake LLVM.LLVM NASM.NASM`).```cargo builddiff --git a/Cargo.lock b/Cargo.lockindex ca1f0234..7db9f283 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -160,19 +160,34 @@ dependencies = ["memchr",]+[[package]]+name = "alloc-no-stdlib"+version = "2.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"+[[package]]name = "alloc-no-stdlib"version = "3.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"+[[package]]+name = "alloc-stdlib"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"+dependencies = [+ "alloc-no-stdlib 2.0.4",+]+[[package]]name = "alloc-stdlib"version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"dependencies = [- "alloc-no-stdlib",+ "alloc-no-stdlib 3.0.0",][[package]]@@ -753,6 +768,24 @@ version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "597bb81c80a54b6a4381b23faba8d7774b144c94cbd1d6fe3f1329bd776554ab"+[[package]]+name = "bindgen"+version = "0.72.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"+dependencies = [+ "bitflags 2.13.2",+ "cexpr",+ "clang-sys",+ "itertools 0.13.0",+ "proc-macro2",+ "quote",+ "regex",+ "rustc-hash 2.1.3",+ "shlex 1.3.0",+ "syn 2.0.119",+]+[[package]]name = "bit-set"version = "0.10.0"@@ -900,15 +933,36 @@ dependencies = ["tracing",]+[[package]]+name = "brotli"+version = "8.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"+dependencies = [+ "alloc-no-stdlib 2.0.4",+ "alloc-stdlib 0.2.4",+ "brotli-decompressor 5.0.3",+]+[[package]]name = "brotli"version = "9.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81"dependencies = [- "alloc-no-stdlib",- "alloc-stdlib",- "brotli-decompressor",+ "alloc-no-stdlib 3.0.0",+ "alloc-stdlib 0.3.0",+ "brotli-decompressor 6.2.0",+]++[[package]]+name = "brotli-decompressor"+version = "5.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"+dependencies = [+ "alloc-no-stdlib 2.0.4",+ "alloc-stdlib 0.2.4",][[package]]@@ -917,8 +971,8 @@ version = "6.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "34c6783f42c21c952ad7112b354f0ba2f10760e9decea5b1b60523d6e270faaf"dependencies = [- "alloc-no-stdlib",- "alloc-stdlib",+ "alloc-no-stdlib 3.0.0",+ "alloc-stdlib 0.3.0",][[package]]@@ -941,6 +995,31 @@ dependencies = ["serde_core",]+[[package]]+name = "btls"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c5e60b8c8d282c86360cab651ded04ab0335a7b5390c8d34145cbeab8cacf5f"+dependencies = [+ "bitflags 2.13.2",+ "btls-sys",+ "foreign-types",+ "libc",+ "openssl-macros",+]++[[package]]+name = "btls-sys"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b1b8638a2e1c38a5ae4efa90ae57e643baec35a30d03fc5b399b893adc4954b"+dependencies = [+ "bindgen",+ "cmake",+ "fs_extra",+ "fslock",+]+[[package]]name = "bumpalo"version = "3.20.3"@@ -1087,7 +1166,16 @@ dependencies = ["find-msvc-tools","jobserver","libc",- "shlex",+ "shlex 2.0.1",+]++[[package]]+name = "cexpr"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"+dependencies = [+ "nom 7.1.3",][[package]]@@ -1173,6 +1261,17 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b0fc239e0f6cb375d2402d48afb92f76f5404fd1df208a41930ec81eda078bea"+[[package]]+name = "clang-sys"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"+dependencies = [+ "glob",+ "libc",+ "libloading 0.8.9",+]+[[package]]name = "clap"version = "4.6.7"@@ -1286,10 +1385,12 @@ version = "0.4.46"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cae36683101b2899f48bd31f8db9839437356188e3b1ff23096e73dab09ba8fe"dependencies = [- "brotli",+ "brotli 9.1.1","compression-core","flate2","memchr",+ "zstd",+ "zstd-safe",][[package]]@@ -2409,6 +2510,16 @@ version = "1.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"+[[package]]+name = "fslock"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb"+dependencies = [+ "libc",+ "winapi",+]+[[package]]name = "funty"version = "2.0.0"@@ -2792,6 +2903,12 @@ dependencies = ["vello_common",]+[[package]]+name = "glob"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"+[[package]]name = "gloo-timers"version = "0.3.0"@@ -3233,6 +3350,25 @@ version = "0.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c"+[[package]]+name = "http2"+version = "0.5.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d3114be2f413b2e491e686b93a28cda30c355cffc8d091a57f8be4b1342896"+dependencies = [+ "atomic-waker",+ "bytes",+ "fnv",+ "futures-core",+ "futures-sink",+ "http",+ "indexmap 2.14.2",+ "slab",+ "smallvec",+ "tokio",+ "tokio-util",+]+[[package]]name = "httparse"version = "1.10.1"@@ -3648,6 +3784,15 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"+[[package]]+name = "itertools"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"+dependencies = [+ "either",+]+[[package]]name = "itertools"version = "0.14.0"@@ -4347,6 +4492,15 @@ version = "0.4.34"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"+[[package]]+name = "lru"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a9f71e3591c7ec44d3e563e87bf14ddc2bada8519dca046e5b0e560cd004e2d"+dependencies = [+ "hashbrown 0.17.1",+]+[[package]]name = "lru-slab"version = "0.1.3"@@ -4432,8 +4586,8 @@ version = "0.5.2"dependencies = ["arboard","base64 0.23.1",- "brotli",- "brotli-decompressor",+ "brotli 9.1.1",+ "brotli-decompressor 6.2.0","chrono","craft-atomic","craft-i18n",@@ -4577,6 +4731,7 @@ dependencies = ["rquickjs","rustix 1.1.6","rustls",+ "rustls-native-certs","rustls-platform-verifier","serde","serde_json",@@ -4593,7 +4748,10 @@ dependencies = ["tower-layer","tower-service","url",+ "webpki-root-certs","windows-sys 0.61.2",+ "wreq",+ "wreq-util",][[package]]@@ -4642,6 +4800,7 @@ dependencies = ["hex","http-range-header","httpdate",+ "hyper-util","percent-encoding","rcgen","reqwest 0.13.5",@@ -5759,6 +5918,17 @@ dependencies = ["libc",]+[[package]]+name = "openssl-macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "openssl-probe"version = "0.2.2"@@ -7583,6 +7753,12 @@ dependencies = ["lazy_static",]+[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+[[package]]name = "shlex"version = "2.0.1"@@ -8221,6 +8397,16 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "tokio-btls"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e1fd638ec35427faf3b8f412e0fdd6fae76591d79dba40f38fa667d22bc44dd"+dependencies = [+ "btls",+ "tokio",+]+[[package]]name = "tokio-macros"version = "2.7.2"@@ -8547,6 +8733,26 @@ dependencies = ["rustc-hash 2.1.3",]+[[package]]+name = "typed-builder"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "31aa81521b70f94402501d848ccc0ecaa8f93c8eb6999eb9747e72287757ffda"+dependencies = [+ "typed-builder-macro",+]++[[package]]+name = "typed-builder-macro"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "076a02dc54dd46795c2e9c8282ed40bcfb1e22747e955de9389a1de28190fb26"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "typed-path"version = "0.13.0"@@ -9852,6 +10058,84 @@ dependencies = ["wayland-protocols-wlr",]+[[package]]+name = "wreq"+version = "0.16.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2b11a67378558357ed083260fd0bbced0481e4d32e2fb722be9c52b42ee08d4"+dependencies = [+ "btls",+ "btls-sys",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "http2",+ "httparse",+ "ipnet",+ "libc",+ "lru",+ "percent-encoding",+ "pin-project-lite",+ "socket2",+ "sync_wrapper",+ "tokio",+ "tokio-btls",+ "tokio-socks",+ "tokio-util",+ "tower",+ "tower-http",+ "url",+ "webpki-root-certs",+ "wreq-proto",+ "wreq-rt",+]++[[package]]+name = "wreq-proto"+version = "0.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4d829f0427a5064829976fe790641ca21abb1d83d844812baf022dc0bdf2db"+dependencies = [+ "bytes",+ "futures-channel",+ "futures-util",+ "http",+ "http-body",+ "http2",+ "httparse",+ "pin-project-lite",+ "smallvec",+ "tokio",+ "tokio-util",+ "want",+]++[[package]]+name = "wreq-rt"+version = "0.2.2-rc.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "99e9bce67a3fa3dd3f1503f066d86661c9caf399a763d3bd184da7afaf886c8b"+dependencies = [+ "pin-project-lite",+ "tokio",+ "wreq-proto",+]++[[package]]+name = "wreq-util"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "636ad931b75aa030cc320899507ce8d5e44f1d9b3b44a81d2e1a225b0d4aad3b"+dependencies = [+ "brotli 8.0.4",+ "flate2",+ "typed-builder",+ "wreq",+ "zstd",+]+[[package]]name = "write16"version = "1.0.0"@@ -10269,6 +10553,34 @@ dependencies = ["simd-adler32",]+[[package]]+name = "zstd"+version = "0.14.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70"+dependencies = [+ "zstd-safe",+]++[[package]]+name = "zstd-safe"+version = "8.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b"+dependencies = [+ "zstd-sys",+]++[[package]]+name = "zstd-sys"+version = "2.1.2+zstd.1.5.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3"+dependencies = [+ "cc",+ "pkg-config",+]+[[package]]name = "zune-core"version = "0.5.3"diff --git a/Cargo.toml b/Cargo.tomlindex 939a0cbd..cd66a929 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -5,7 +5,7 @@ members = ["crates/*"][workspace.package]version = "0.5.2"edition = "2024"-rust-version = "1.95"+rust-version = "1.98"license = "GPL-3.0-or-later"authors = ["Ahmed Nefzaoui"]publish = false@@ -14,7 +14,8 @@ publish = falsemdm-cli = { path = "crates/cli" }mdm-crash = { path = "crates/crash", default-features = false }mdm-debrid = { path = "crates/debrid" }-mdm-engine = { path = "crates/engine" }+# Without its browser-like connection unless asked (the app asks: its `browser-connection`).+mdm-engine = { path = "crates/engine", default-features = false }mdm-extract = { path = "crates/extract" }mdm-geo = { path = "crates/geo" }mdm-ipc = { path = "crates/ipc" }@@ -90,6 +91,16 @@ crc32fast = "1.5.3"sysinfo = { version = "0.40.0", default-features = false, features = ["disk"] }proptest = "1.12.0"# HTTP/1.1 only: each engine worker must be one real TCP connection (notes/ENGINE.md §4).+# The browser-like connection (#668, crates/engine/src/browserlike.rs): a download whose site's+# bot check refused MDM's own connection is asked once more the way a browser connects (its TLS+# handshake, HTTP/2 settings and header order), on BoringSSL. Builds BoringSSL from source:+# CMake, a C/C++ compiler, libclang and, on Windows, NASM.+wreq = { version = "=0.16.3", default-features = false, features = ["webpki-roots", "tokio-rt", "socks", "stream", "gzip", "brotli", "zstd", "deflate"] }+wreq-util = { version = "=0.2.1", default-features = false, features = ["emulation"] }+# Its trusted certificates: Mozilla's (as wreq's own default) and the system's, which MDM's own+# connection trusts too (an antivirus's or a company's HTTPS inspection adds its own there).+rustls-native-certs = "0.8.5"+webpki-root-certs = "1.0.11"reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "stream", "system-proxy", "socks"] }# FTP and FTPS (crates/engine/src/ftp.rs), with TLS through the rustls and platform verifier# reqwest uses. "deprecated" is what enables implicit FTPS (ftps://, port 990).diff --git a/Dockerfile b/Dockerfileindex d9c7f68a..2ac4865e 100644--- a/Dockerfile+++ b/Dockerfile@@ -14,9 +14,10 @@ FROM rust:1-trixie AS buildARG PROFILE# The program links only the C library: the window's libraries (X11, Wayland, OpenGL, EGL,# xkbcommon) are loaded when a window opens, and the server opens none. So no GTK or GL here or-# in the image; cmake for the TLS library (aws-lc).+# in the image; cmake for the TLS libraries (aws-lc, and BoringSSL under the browser-like+# connection, #668) and libclang for BoringSSL's bindings.RUN apt-get update \- && apt-get install -y --no-install-recommends cmake \+ && apt-get install -y --no-install-recommends cmake libclang-dev \&& rm -rf /var/lib/apt/lists/*WORKDIR /srcCOPY . .diff --git a/README.md b/README.mdindex e0ec36f8..9b0e5bfd 100644--- a/README.md+++ b/README.md@@ -355,7 +355,12 @@ working, not a copy of anyone's software.<details><summary><b>Build from source</b></summary>-Requires Rust stable 1.95 or later (the MSVC toolchain on Windows).+Requires Rust stable 1.98 or later (the MSVC toolchain on Windows), and for the engine's+browser-like connection (BoringSSL, built from source): CMake, LLVM's libclang and, on Windows,+NASM (`winget install Kitware.CMake LLVM.LLVM NASM.NASM`; on Linux `cmake` and+`libclang-dev`; on macOS Xcode's command line tools and `cmake`).+`cargo build -p mdm-app --no-default-features` builds the app without it (a site that refuses MDM's+own connection then stays refused).```cargo build --releasediff --git a/ROADMAP.md b/ROADMAP.mdindex e5776665..b4931737 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -548,9 +548,9 @@ These ship in a later version, when they're ready.engine, which holds a torrent while its writes to the disk end([#693](https://github.com/anefzaoui/misterdownloadmanager/issues/693)): the torrents' numbersare now read beside the window; fix in review-- 🔄 Sites with bot protection (Cloudflare and similar) refusing MDM: when a site still answers- with a bot check, asking again the way a browser connects- ([#668](https://github.com/anefzaoui/misterdownloadmanager/issues/668))+- 🔄 Sites that let only browsers through (a bot check, or FileHippo's 412): one more try+ connecting the way the browser does, with its cookies for that site+ ([#668](https://github.com/anefzaoui/misterdownloadmanager/issues/668)): in review- 🔄 Download video: a sound-only choice (MP3, a playlist as sound) saved in the Music folder andlisted under Music ([#611](https://github.com/anefzaoui/misterdownloadmanager/issues/611)):in reviewdiff --git a/crates/app/Cargo.toml b/crates/app/Cargo.tomlindex 76897329..239a48d3 100644--- a/crates/app/Cargo.toml+++ b/crates/app/Cargo.toml@@ -13,6 +13,11 @@ name = "misterdownloadmanager"path = "src/main.rs"[features]+default = ["browser-connection"]+# The engine's browser-like connection (#668), for sites that refuse MDM's own as a program's.+# Built from BoringSSL's C sources: tools/dev/check-cross.ps1, which can't cross-compile those,+# checks the workspace without it.+browser-connection = ["mdm-engine/browser-connection"]# Update now's end-to-end tests only, never in a release (see mdm-tools): a test key for a fake# release (MDM_TEST_UPDATE_KEY), `/show update-now` (Update now in the window `/show updates`# opens), and MDM_TEST_UPDATE_HOLD (seconds the update waits before it's put in place, to see anddiff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.tomlindex 9f034e08..a070ed2e 100644--- a/crates/engine/Cargo.toml+++ b/crates/engine/Cargo.toml@@ -8,7 +8,17 @@ license.workspace = trueauthors.workspace = truepublish.workspace = true+[features]+default = ["browser-connection"]+# The browser-like connection for sites whose bot check refuses MDM's own (#668,+# src/browserlike.rs). Without it a bot check's refusal stands (the browser takes the download).+browser-connection = ["dep:wreq", "dep:wreq-util", "dep:rustls-native-certs", "dep:webpki-root-certs"]+[dependencies]+wreq = { workspace = true, optional = true }+wreq-util = { workspace = true, optional = true }+rustls-native-certs = { workspace = true, optional = true }+webpki-root-certs = { workspace = true, optional = true }bytes.workspace = truecraft-atomic.workspace = trueserde_json.workspace = truediff --git a/crates/engine/src/browserlike.rs b/crates/engine/src/browserlike.rsnew file mode 100644index 00000000..259e236c--- /dev/null+++ b/crates/engine/src/browserlike.rs@@ -0,0 +1,570 @@+//! The connection a browser makes (#668), for the one retry a download gets when a site refused+//! MDM's own as a program's: its bot check (`Error::BotCheck`), or a 412 to a request without+//! preconditions (`download::refused_as_a_program`).+//!+//! Bot checks (Cloudflare's and others') don't only read the User-Agent: they recognise how the+//! connection is made, its TLS handshake, its HTTP/2 settings and the order of its headers.+//! MDM's own connection (reqwest on rustls) doesn't look like a browser's, so a site that lets+//! only browsers through refuses it even when the same file downloads in the browser. This+//! connection is made the way that browser family makes it (`wreq` on BoringSSL, with+//! `wreq-util`'s profiles: Chrome's for Chrome and the Chromium browsers, Edge's, Opera's,+//! Firefox's, Safari's), with the download's own User-Agent and headers (the browser's cookies+//! for that site, handed over by the extension, scoped to it as everywhere: `scoped_headers`).+//!+//! It solves nothing: no script runs, no challenge is answered. A site that wants its challenge+//! solved still refuses, and the download fails as before (the browser can take it).+//!+//! Everything else stays the engine's: the proxy (`Options::proxy`), the DNS and the network+//! adapter (`Options::dns`, `Options::route`: a connection that can't be held to the adapter+//! isn't made), speed limits, stop and resume (`download.rs` reads its answers like reqwest's).+//! It follows redirects itself, as `get` does, so credentials never leave the site.+//!+//! Built with the `browser-connection` feature (on by default; BoringSSL needs CMake, a C+//! compiler, libclang and, on Windows, NASM to build). Without it, `AVAILABLE` is false and the+//! bot check's refusal stands.++use bytes::Bytes;+use reqwest::StatusCode;+use reqwest::header::{HeaderMap, HeaderValue};+use tokio_util::sync::CancellationToken;+use url::Url;++use crate::download::{Body, Error, Head, Options};++/// Whether this build has the browser-like connection.+pub const AVAILABLE: bool = cfg!(feature = "browser-connection");++/// Most HTTP redirects a request follows (as `download::MAX_REDIRECTS`, browsers' 20).+#[cfg_attr(not(feature = "browser-connection"), allow(dead_code))]+const MAX_REDIRECTS: usize = 20;++/// A browser-like client for one download (`Browser::new`).+pub(crate) struct Browser {+ #[cfg(feature = "browser-connection")]+ client: wreq::Client,+ /// The User-Agent its requests carry: the download's own.+ #[cfg_attr(not(feature = "browser-connection"), allow(dead_code))]+ agent: HeaderValue,+ #[cfg_attr(not(feature = "browser-connection"), allow(dead_code))]+ route: crate::net::Route,+ /// The first address is on this computer, which isn't bound to the adapter (#35): its+ /// redirects may only lead back here.+ #[cfg_attr(not(feature = "browser-connection"), allow(dead_code))]+ stay_here: bool,+}++/// An answer's body coming in through the browser-like connection.+pub(crate) struct Stream {+ #[cfg(feature = "browser-connection")]+ inner: std::pin::Pin<Box<dyn futures::Stream<Item = wreq::Result<Bytes>> + Send>>,+ len: Option<u64>,+}++impl Stream {+ /// The next bytes; None at the end.+ pub(crate) async fn chunk(&mut self) -> Result<Option<Bytes>, Error> {+ #[cfg(feature = "browser-connection")]+ {+ use futures::StreamExt;+ match self.inner.next().await {+ None => Ok(None),+ Some(Ok(b)) => Ok(Some(b)),+ Some(Err(e)) => Err(net_error(&e)),+ }+ }+ #[cfg(not(feature = "browser-connection"))]+ Ok(None)+ }++ /// The bytes it will carry, if known.+ pub(crate) fn len(&self) -> Option<u64> {+ self.len+ }+}++impl Browser {+ /// A client for `url` with `opts`' User-Agent (or the one `headers` carry, which wins as it+ /// does on MDM's own requests), proxy, DNS and network adapter. Refused when this build has+ /// none, or when the adapter can't hold its connections (the kill switch, #35).+ pub(crate) fn new(opts: &Options, url: &Url, headers: &HeaderMap) -> Result<Browser, Error> {+ let agent = headers+ .get(reqwest::header::USER_AGENT)+ .cloned()+ .or_else(|| HeaderValue::from_str(&opts.user_agent).ok())+ .filter(|a| !a.is_empty())+ .or_else(|| HeaderValue::from_str(&crate::agent::automatic()).ok())+ .unwrap_or_else(|| HeaderValue::from_static(crate::agent::IE11_USER_AGENT));+ #[cfg(feature = "browser-connection")]+ {+ let (client, stay_here) = imp::client(opts, url, agent.to_str().unwrap_or(""))?;+ Ok(Browser {+ client,+ agent,+ route: opts.route.clone(),+ stay_here,+ })+ }+ #[cfg(not(feature = "browser-connection"))]+ {+ let _ = (url, agent);+ Err(Error::BotCheck)+ }+ }++ /// `GET url` with `headers` (a `Range` among them for a range: then without compression, as+ /// browsers ask for ranges), its HTTP redirects followed with the credentials scoped to each+ /// address and the cookies a redirect sets kept for its own site (as `get` does). With the+ /// answer, the headers as they go on at the address it ended at.+ pub(crate) async fn get(+ &self,+ url: Url,+ headers: HeaderMap,+ ranged: bool,+ cancel: &CancellationToken,+ ) -> Result<(Head, Body, HeaderMap), Error> {+ #[cfg(feature = "browser-connection")]+ {+ imp::get(self, url, headers, ranged, cancel).await+ }+ #[cfg(not(feature = "browser-connection"))]+ {+ let _ = (url, headers, ranged, cancel);+ Err(Error::BotCheck)+ }+ }+}++/// The first answer through the browser-like connection is the file (or its start): 200, or+/// 206; never the site's refusal, nor a web page where a file was expected (`expects`, as `get`+/// decides it).+pub(crate) fn check_first(head: &Head, expects: bool) -> Result<(), Error> {+ use crate::download::{is_bot_check, is_web_page, named, retry_after};+ match head.status {+ StatusCode::OK | StatusCode::PARTIAL_CONTENT => {}+ s if s == StatusCode::TOO_MANY_REQUESTS || s == StatusCode::SERVICE_UNAVAILABLE => {+ return Err(Error::Throttled(s, retry_after(&head.headers)));+ }+ s if is_bot_check(s, &head.headers) => return Err(Error::BotCheck),+ s => return Err(Error::Status(s)),+ }+ let page = is_web_page(&head.headers) && !named(&head.headers);+ if page && (expects || crate::sites::expects_file(&head.url)) {+ return Err(Error::GotWebPage);+ }+ Ok(())+}++/// A failure of the browser-like connection in the engine's words (`Error::Net`).+#[cfg(feature = "browser-connection")]+fn net_error(e: &wreq::Error) -> Error {+ use crate::download::NetKind;+ let kind = if e.is_tls() {+ NetKind::Tls+ } else if e.is_timeout() {+ NetKind::Timeout+ } else if e.is_body() || e.is_decode() {+ NetKind::Lost+ } else {+ NetKind::Connect+ };+ // The adapter's refusal (#35) as itself, from wherever it was raised.+ let mut source = std::error::Error::source(e);+ let mut cause = None;+ while let Some(s) = source {+ if let Some(n) = s.downcast_ref::<crate::net::NetError>() {+ return Error::Adapter(n.clone());+ }+ cause = Some(s.to_string());+ source = s.source();+ }+ let cause = cause+ .map(|c| crate::download::strip_os_error_code(&c))+ .filter(|c| !c.contains("://"))+ .unwrap_or_default();+ Error::Net { kind, cause }+}++#[cfg(feature = "browser-connection")]+mod imp {+ use std::sync::Arc;++ use reqwest::header::{self, HeaderMap, HeaderValue};+ use tokio_util::sync::CancellationToken;+ use url::Url;+ use wreq_util::{Emulation, Platform, Profile};++ use super::{Browser, MAX_REDIRECTS, Stream, net_error};+ use crate::download::{+ Body, Error, Head, Options, Proxy, add_cookies, cancellable, scoped_headers, set_cookies,+ };+ use crate::net::{self, NetError, Route};++ /// How long an idle connection is kept (as the download client's).+ const POOL_IDLE: std::time::Duration = std::time::Duration::from_secs(15);++ /// The client, and whether its connections stay on this computer (unbound).+ pub(super) fn client(+ opts: &Options,+ url: &Url,+ agent: &str,+ ) -> Result<(wreq::Client, bool), Error> {+ let route = &opts.route;+ net::check_url(route, url)?;+ let port = url.port_or_known_default().unwrap_or(443);+ let (proxy, through_local_proxy) = proxy_for(opts, url)?;+ let mut b = wreq::Client::builder()+ .emulation(emulation_for(agent))+ // Followed in `get`, where credentials are scoped as everywhere in MDM.+ .redirect(wreq::redirect::Policy::none())+ .connect_timeout(opts.connect_timeout)+ .read_timeout(opts.read_timeout)+ .pool_idle_timeout(POOL_IDLE)+ .pool_max_idle_per_host(1)+ .tls_cert_store(cert_store(&opts.extra_roots)?)+ .dns_resolver(Arc::new(Dns(crate::dns::Resolver::new(+ &opts.hosts,+ port,+ &opts.dns,+ &opts.extra_roots,+ route,+ ))));+ b = match proxy {+ Some(p) => b.proxy(p),+ None => b.no_proxy(),+ };+ // As the download client (`download::client`): a connection to this computer isn't+ // bound, and its redirects may then only lead back here.+ let to_this_computer = through_local_proxy+ || (net::is_this_computer(url.host_str().unwrap_or_default())+ && !matches!(opts.proxy, Proxy::Manual { .. } | Proxy::Pac { .. }));+ let b = bind(b, route, to_this_computer)?;+ let client = b.build().map_err(|e| net_error(&e))?;+ Ok((+ client,+ to_this_computer && !through_local_proxy && !route.is_any(),+ ))+ }++ /// The certificates the connection trusts: Mozilla's, the system's (as MDM's own connection+ /// trusts them: an antivirus's or a company's HTTPS inspection puts its own there) and+ /// `extra` (the tests' own CA). The system's are read once.+ fn cert_store(extra: &[Vec<u8>]) -> Result<wreq::tls::trust::CertStore, Error> {+ static SYSTEM: std::sync::OnceLock<Vec<Vec<u8>>> = std::sync::OnceLock::new();+ let system = SYSTEM.get_or_init(|| {+ rustls_native_certs::load_native_certs()+ .certs+ .into_iter()+ .map(|c| c.to_vec())+ .collect()+ });+ wreq::tls::trust::CertStore::builder()+ .add_der_certs(+ webpki_root_certs::TLS_SERVER_ROOT_CERTS+ .iter()+ .map(|c| c.as_ref()),+ )+ .add_der_certs(system.iter())+ .add_der_certs(extra.iter())+ .build()+ .map_err(|e| net_error(&e))+ }++ /// `builder` held to `route`'s adapter as `net::bind_client` holds MDM's own clients: the+ /// address on Windows, the device on Linux, the interface on macOS. Elsewhere, refused.+ fn bind(+ builder: wreq::ClientBuilder,+ route: &Route,+ to_this_computer: bool,+ ) -> Result<wreq::ClientBuilder, NetError> {+ match route {+ Route::Any => Ok(builder),+ Route::Down { label } => Err(NetError::Down {+ label: label.clone(),+ }),+ Route::Bound(_) if to_this_computer => Ok(builder),+ Route::Bound(b) => {+ #[cfg(windows)]+ {+ Ok(builder.local_address(b.windows_local()))+ }+ #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos"))]+ {+ Ok(builder.interface(b.name.clone()))+ }+ // No way to hold a socket to the adapter here: no connection rather than one+ // around it.+ #[cfg(not(any(+ windows,+ target_os = "linux",+ target_os = "android",+ target_os = "macos"+ )))]+ {+ let _ = builder;+ Err(NetError::Down {+ label: b.label.clone(),+ })+ }+ }+ }+ }++ /// The proxy for `url` as `download::client` picks it (none, the system's, the manual one+ /// for its scheme, the script's first usable route), checked against the adapter the same+ /// way; and whether it is on this computer (its connections then aren't bound).+ fn proxy_for(opts: &Options, url: &Url) -> Result<(Option<wreq::Proxy>, bool), Error> {+ let (address, login) = match &opts.proxy {+ Proxy::None => (None, None),+ Proxy::System => (net::system_proxy(url), None),+ Proxy::Manual {+ url: proxy,+ login,+ http,+ https,+ } => {+ let covers = if url.scheme() == "https" {+ *https+ } else {+ *http+ };+ (covers.then(|| proxy.clone()), login.clone())+ }+ Proxy::Pac { script } => {+ let first = crate::pac::routes(script, url).ok().and_then(|routes| {+ routes.into_iter().find_map(|r| match r {+ crate::pac::Route::Direct => Some(None),+ crate::pac::Route::Proxy(p) => {+ wreq::Proxy::all(p.as_str()).ok().map(|_| Some(p))+ }+ })+ });+ (first.unwrap_or_else(|| net::system_proxy(url)), None)+ }+ };+ let Some(address) = address else {+ return Ok((None, false));+ };+ let host = Url::parse(&address)+ .ok()+ .and_then(|u| u.host_str().map(str::to_owned))+ .unwrap_or_default();+ let local = net::is_this_computer(&host);+ if !local && let Ok(ip) = host.trim_matches(['[', ']']).parse() {+ opts.route.check(ip)?;+ }+ let bad = |_| Error::Net {+ kind: crate::download::NetKind::Connect,+ cause: format!("the proxy {host} can't be used"),+ };+ let mut proxy = wreq::Proxy::all(address.as_str()).map_err(bad)?;+ if let Some((user, pass)) = login {+ proxy = proxy.basic_auth(&user, &pass);+ }+ Ok((Some(proxy), local))+ }++ /// The profile of the browser `agent` names, at its version (the newest profile up to it;+ /// the oldest when it is older than all), on its system: Edge's, Opera's, Firefox's,+ /// Safari's, else Chrome's (Chrome, Brave, Vivaldi and the other Chromium browsers name+ /// themselves Chrome; so does nothing else).+ pub(super) fn emulation_for(agent: &str) -> Emulation {+ let (profile, platform) = choose(agent);+ Emulation::builder()+ .profile(profile)+ .platform(platform)+ .build()+ }++ /// The profile and system `emulation_for` takes for `agent`.+ pub(super) fn choose(agent: &str) -> (Profile, Platform) {+ // The dotted version after `key` ("Chrome/142.0.7444.59": [142, 0, 7444, 59]).+ let version_after = |key: &str| -> Option<Vec<u32>> {+ let at = agent.find(key)? + key.len();+ let dotted: String = agent[at..]+ .chars()+ .take_while(|c| c.is_ascii_digit() || *c == '.')+ .collect();+ let parts: Vec<u32> = dotted.split('.').map_while(|d| d.parse().ok()).collect();+ (!parts.is_empty()).then_some(parts)+ };+ let (family, version) = if let Some(v) = version_after("Edg/") {+ ("Edge", Some(v))+ } else if let Some(v) = version_after("OPR/") {+ ("Opera", Some(v))+ } else if let Some(v) = version_after("Firefox/") {+ ("Firefox", Some(v))+ } else if let Some(v) = version_after("Chrome/") {+ ("Chrome", Some(v))+ } else if agent.contains("Safari/") {+ ("Safari", version_after("Version/"))+ } else {+ ("Chrome", None)+ };+ let platform = if agent.contains("Android") {+ Platform::Android+ } else if agent.contains("iPhone") || agent.contains("iPad") {+ Platform::IOS+ } else if agent.contains("Macintosh") || agent.contains("Mac OS X") {+ Platform::MacOS+ } else if agent.contains("Linux") || agent.contains("X11") || agent.contains("CrOS") {+ Platform::Linux+ } else {+ Platform::Windows+ };+ (profile(family, version), platform)+ }++ /// `family`'s profile closest to `version` from below (`emulation_for`).+ fn profile(family: &str, version: Option<Vec<u32>>) -> Profile {+ // Each profile's family and version, from its name ("Chrome142": [142], "Safari26_4":+ // [26, 4]): the plain desktop ones only (not FirefoxPrivate, SafariIos…).+ let mut ours: Vec<(Vec<u32>, Profile)> = Profile::VARIANTS+ .iter()+ .filter_map(|p| {+ let name = format!("{p:?}");+ let rest = name.strip_prefix(family)?;+ let parts: Option<Vec<u32>> = rest.split('_').map(|d| d.parse().ok()).collect();+ parts.filter(|v| !v.is_empty()).map(|v| (v, *p))+ })+ .collect();+ ours.sort_by(|a, b| a.0.cmp(&b.0));+ let pick = match version {+ Some(v) => ours+ .iter()+ .rev()+ .find(|(m, _)| *m <= v)+ .or(ours.first())+ .map(|(_, p)| *p),+ None => ours.last().map(|(_, p)| *p),+ };+ pick.unwrap_or_default()+ }++ /// MDM's resolver (`dns::Resolver`: the chosen DNS, only addresses the adapter reaches)+ /// for the browser-like client.+ struct Dns(crate::dns::Resolver);++ impl wreq::dns::Resolve for Dns {+ fn resolve(&self, name: wreq::dns::Name) -> wreq::dns::Resolving {+ match name.as_str().parse::<reqwest::dns::Name>() {+ Ok(n) => reqwest::dns::Resolve::resolve(&self.0, n),+ Err(e) => {+ Box::pin(+ async move { Err(Box::new(e) as Box<dyn std::error::Error + Send + Sync>) },+ )+ }+ }+ }+ }++ pub(super) async fn get(+ b: &Browser,+ url: Url,+ headers: HeaderMap,+ range: bool,+ cancel: &CancellationToken,+ ) -> Result<(Head, Body, HeaderMap), Error> {+ let (mut url, mut headers) = (url, headers);+ for _ in 0..=MAX_REDIRECTS {+ net::check_url(&b.route, &url)?;+ if b.stay_here && !net::is_this_computer(url.host_str().unwrap_or_default()) {+ return Err(NetError::Unbound {+ label: b.route.label().unwrap_or_default().to_owned(),+ }+ .into());+ }+ let mut req = b+ .client+ .get(url.as_str())+ .headers(headers.clone())+ .header(header::USER_AGENT, b.agent.clone());+ if range {+ // As browsers ask for a part of a file: its bytes as they are.+ req = req.header(+ header::ACCEPT_ENCODING,+ HeaderValue::from_static("identity"),+ );+ }+ let resp = cancellable(cancel, async {+ req.send().await.map_err(|e| net_error(&e))+ })+ .await?;+ if resp.status().is_redirection()+ && let Some(next) = resp+ .headers()+ .get(header::LOCATION)+ .and_then(|l| l.to_str().ok())+ .and_then(|l| url.join(l).ok())+ .filter(|n| matches!(n.scheme(), "http" | "https"))+ {+ let cookies = set_cookies(resp.headers());+ headers = scoped_headers(&headers, &url, &next);+ // Its own site's, never from https down to http (as the user's own cookies).+ let same_site =+ next.host_str() == url.host_str() || crate::sites::same_party(&url, &next);+ if same_site && !(url.scheme() == "https" && next.scheme() != "https") {+ add_cookies(&mut headers, &cookies);+ }+ url = next;+ continue;+ }+ let head = Head {+ status: resp.status(),+ headers: resp.headers().clone(),+ url: url.clone(),+ len: resp.content_length(),+ };+ let body = Body::Browser(Stream {+ len: head.len,+ inner: Box::pin(resp.bytes_stream()),+ });+ return Ok((head, body, headers));+ }+ Err(Error::Net {+ kind: crate::download::NetKind::Connect,+ cause: "too many redirects".to_owned(),+ })+ }+}++#[cfg(all(test, feature = "browser-connection"))]+mod tests {+ use super::imp::choose;++ fn profile_of(agent: &str) -> String {+ format!("{:?}", choose(agent))+ }++ #[test]+ fn the_profile_follows_the_browser_named() {+ let chrome = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36";+ let edge = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0";+ let firefox = "Mozilla/5.0 (X11; Linux x86_64; rv:145.0) Gecko/20100101 Firefox/145.0";+ let safari = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.1 Safari/605.1.15";+ let newer = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/999.0.0.0 Safari/537.36";+ assert!(+ profile_of(chrome).contains("Chrome142"),+ "{}",+ profile_of(chrome)+ );+ assert!(profile_of(chrome).contains("Windows"));+ assert!(profile_of(edge).contains("Edge140"), "{}", profile_of(edge));+ assert!(+ profile_of(firefox).contains("Firefox145"),+ "{}",+ profile_of(firefox)+ );+ assert!(profile_of(firefox).contains("Linux"));+ assert!(+ profile_of(safari).contains("Safari26_1"),+ "{}",+ profile_of(safari)+ );+ assert!(profile_of(safari).contains("MacOS"));+ assert!(+ profile_of(newer).contains("Chrome149"),+ "{}",+ profile_of(newer)+ );+ }+}diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rsindex 1e9e47f8..464c7230 100644--- a/crates/engine/src/download.rs+++ b/crates/engine/src/download.rs@@ -139,7 +139,7 @@ pub struct Options {/// FTP data connections: passive (the client connects; IDM's "Use passive mode for FTP",/// on by default), else active (the server connects back).pub ftp_passive: bool,- /// Certificates (DER) trusted besides the system's for FTPS (tests' own CA).+ /// Certificates (DER) trusted besides the system's for FTPS and HTTPS (tests' own CA).pub extra_roots: Vec<Vec<u8>>,/// Send every request as POST with this body, the Content-Type coming from the headers (a/// browser form's download). Redirects go as in browsers: 301, 302 and 303 turn it into a@@ -561,7 +561,7 @@ impl From<disk::Refusal> for Error {/// (cookies, authorization) never follow a redirect to another host or from https down to/// http — as reqwest does while it follows the redirect itself — except between one site's own/// hosts (`sites::same_party`: a Drive link's cookies go to Drive's file host).-fn scoped_headers(headers: &HeaderMap, from: &Url, to: &Url) -> HeaderMap {+pub(crate) fn scoped_headers(headers: &HeaderMap, from: &Url, to: &Url) -> HeaderMap {let mut h = headers.clone();let same_host = (from.host_str() == to.host_str()&& from.port_or_known_default() == to.port_or_known_default())@@ -796,7 +796,11 @@ pub struct KeptAnswer {url: Url,client: Client,as_get: AsGet,- resp: Response,+ head: Head,+ body: Body,+ /// The browser-like connection it came through, when only that one got past the site's+ /// bot check (#668): the download goes on with it.+ browser: Option<Arc<crate::browserlike::Browser>>,headers: HeaderMap,took: Duration,at: std::time::Instant,@@ -810,7 +814,8 @@ impl std::fmt::Debug for KeptAnswer {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {f.debug_struct("KeptAnswer").field("url", &self.url.as_str())- .field("status", &self.resp.status())+ .field("status", &self.head.status)+ .field("browser_like", &self.browser.is_some()).finish_non_exhaustive()}}@@ -850,6 +855,8 @@ pub async fn probe_kept(let seen = Arc::new(crate::server::ServerSeen::default());let client = client(opts, &target, &as_get, &seen)?;let expects = expects_other_file(opts.expected_type.as_deref(), None, &url);+ // Where the look asked, and with what: asked again there if the site refuses (#668).+ let (asked_at, asked_with) = (target.clone(), headers.clone());// A browser's User-Agent refused (#372): asked once more as MDM.let (client, asked) = match get(&client,@@ -880,18 +887,37 @@ pub async fn probe_kept(}asked => (client, asked),};- let (resp, headers, took) = asked?;- seen.answered(&resp);- let final_url = resp.url().clone();- let (size, from_zero) = match resp.status() {+ let (head, body, browser, headers, took) = match asked {+ Ok((resp, headers, took)) => {+ seen.answered(&resp);+ (Head::of(&resp), Body::Http(resp), None, headers, took)+ }+ // #668: the site refused MDM's connection as a program's (`refused_as_a_program`):+ // looked at once more the way a browser connects, its answer kept for the download+ // (which then asks no more).+ Err(e) if refused_as_a_program(&e) && unlocked.is_none() && opts.post.is_none() => {+ let cancel = CancellationToken::new();+ let (b, (head, body, headers, took)) =+ browser_ask(opts, &asked_at, &asked_with, expects, &cancel)+ .await+ .map_err(|other| match other {+ Error::Cancelled | Error::Adapter(_) => other,+ _ => e,+ })?;+ (head, body, Some(b), headers, took)+ }+ Err(e) => return Err(e),+ };+ let final_url = head.url.clone();+ let (size, from_zero) = match head.status {StatusCode::PARTIAL_CONTENT => {- let (start, _, total) = parse_content_range(resp.headers())?;+ let (start, _, total) = parse_content_range(&head.headers)?;(total, start == 0)}- StatusCode::OK => (resp.content_length(), true),- _ => (resp.content_length(), false),+ StatusCode::OK => (head.len, true),+ _ => (head.len, false),};- let cd = header_text(resp.headers(), header::CONTENT_DISPOSITION);+ let cd = header_text(&head.headers, header::CONTENT_DISPOSITION);let file_name = name_for(cd.as_deref(), &final_url, unlocked.as_ref());let info = ProbeInfo {final_url,@@ -904,7 +930,9 @@ pub async fn probe_kept(client,seen,as_get,- resp,+ head,+ body,+ browser,headers,took,at: std::time::Instant::now(),@@ -1264,12 +1292,18 @@ struct Ctx {web_page_ok: bool,/// An FTP download's server and its idle sessions (else HTTP through `client`).ftp: Option<Arc<crate::ftp::Site>>,+ /// The browser-like connection every request goes through instead of `client`, when only it+ /// got past the site's bot check (#668).+ browser: Option<Arc<crate::browserlike::Browser>>,}/// An answer's body coming in: an HTTP response, or an FTP transfer.-enum Body {+pub(crate) enum Body {Http(Response),Ftp(crate::ftp::Transfer),+ /// An answer to the browser-like connection (#668, `crate::browserlike`).+ #[cfg_attr(not(feature = "browser-connection"), allow(dead_code))]+ Browser(crate::browserlike::Stream),}impl Body {@@ -1278,6 +1312,7 @@ impl Body {match self {Body::Http(r) => Ok(r.chunk().await?),Body::Ftp(t) => t.chunk().await,+ Body::Browser(b) => b.chunk().await,}}@@ -1286,6 +1321,7 @@ impl Body {match self {Body::Http(r) => r.content_length(),Body::Ftp(t) => t.expected(),+ Body::Browser(b) => b.len(),}}@@ -1299,6 +1335,30 @@ impl Body {}}Body::Ftp(t) => t.done(at_end).await,+ // Its connection isn't pooled for another request: there is only the one.+ Body::Browser(_) => {}+ }+ }+}++/// What the engine reads of an HTTP answer's head, from either client (reqwest's, or the+/// browser-like one's, #668).+#[derive(Clone, Debug)]+pub(crate) struct Head {+ pub(crate) status: StatusCode,+ pub(crate) headers: HeaderMap,+ /// Where the answer came from, its redirects followed.+ pub(crate) url: Url,+ pub(crate) len: Option<u64>,+}++impl Head {+ fn of(resp: &Response) -> Head {+ Head {+ status: resp.status(),+ headers: resp.headers().clone(),+ url: resp.url().clone(),+ len: resp.content_length(),}}}@@ -1382,7 +1442,14 @@ fn client(// An IP address in the URL never reaches the resolver, which drops what the chosen adapter// can't reach (#35): check it here.net::check_url(route, url)?;- let builder = Client::builder();+ let mut builder = Client::builder();+ if !opts.extra_roots.is_empty() {+ builder = builder.tls_certs_merge(+ opts.extra_roots+ .iter()+ .filter_map(|der| reqwest::Certificate::from_der(der).ok()),+ );+ }// With an adapter chosen, the system's proxy is looked up now, so that it can be checked// (and a proxy on this computer recognised) like the others.let system = match (&opts.proxy, route.is_any()) {@@ -1583,16 +1650,19 @@ async fn run_fresh(let kept = kept.filter(|k| {k.url == req.url&& k.at.elapsed() < KEEP_ANSWER_FOR- && !(expects && is_web_page(k.resp.headers()) && !named(k.resp.headers()))+ && !(expects && is_web_page(&k.head.headers) && !named(&k.head.headers))});let mut unlocked = kept.as_ref().and_then(|k| k.unlocked.clone());- let (as_get, client0, (resp, headers), ttfb) = match kept {+ // The browser-like connection the download goes on with, when only it got through (#668).+ let mut browser: Option<Arc<crate::browserlike::Browser>> = None;+ let (as_get, client0, (head, body), headers, ttfb) = match kept {Some(k) => {shared.event("Connection 1: continuing from the answer the file's information window got",);let _ = shared.seen.set(k.seen);- (k.as_get, k.client, (k.resp, k.headers), k.took)+ browser = k.browser;+ (k.as_get, k.client, (k.head, k.body), k.headers, k.took)}None => {// Through a service account (#44): its direct link, without the host's cookies@@ -1606,6 +1676,9 @@ async fn run_fresh(let as_get = AsGet::default();let seen = shared.seen.get_or_init(Default::default).clone();let as_given = opts.clone();+ // The download's own User-Agent, which the browser-like connection carries (#668),+ // even when MDM's connection had to give it up (#372).+ let given_agent = opts.user_agent.clone();let ask = FirstAsk {as_get: &as_get,seen: &seen,@@ -1643,11 +1716,33 @@ async fn run_fresh(}}}- let (answer, ttfb) = first?;- seen.answered(&answer.0);- (as_get, client0, answer, ttfb)+ // #668: the site refused MDM's connection as a program's (its bot check, or a 412):+ // asked once more, the way a browser connects, at the same address with the same+ // headers. Its refusal stays the one told if that fails too.+ match first {+ Ok(((resp, headers), ttfb)) => {+ seen.answered(&resp);+ let head = Head::of(&resp);+ (as_get, client0, (head, Body::Http(resp)), headers, ttfb)+ }+ Err(e) if refused_as_a_program(&e) && unlocked.is_none() && opts.post.is_none() => {+ if asked_as_mdm {+ opts.user_agent = given_agent;+ asked_as_mdm = false;+ }+ let (b, head, body, headers, ttfb) =+ browser_first(&opts, &target, &asked, e, expects, shared, cancel).await?;+ browser = Some(b);+ (as_get, client0, (head, body), headers, ttfb)+ }+ Err(e) => return Err(e),+ }}};+ // One connection, as a browser downloads: the site let this one through.+ if browser.is_some() {+ opts.max_connections = 1;+ }// The service's own cap on connections to its link (Real-Debrid's "chunks").if let Some(cap) = unlocked.as_ref()@@ -1657,25 +1752,25 @@ async fn run_fresh(opts.max_connections = opts.max_connections.min(cap);}let preempt_after = (ttfb * PREEMPT_TTFB).max(PREEMPT_MIN);- let size = match resp.status() {- StatusCode::OK => resp.content_length(),+ let size = match head.status {+ StatusCode::OK => head.len,// Some servers answer partially even without Range; accept it if it starts at 0.- StatusCode::PARTIAL_CONTENT => match parse_content_range(resp.headers())? {+ StatusCode::PARTIAL_CONTENT => match parse_content_range(&head.headers)? {(0, _, total) => total,(start, ..) => return Err(Error::BadRange(format!("probe started at {start}"))),},s => return Err(Error::Status(s)),};- let ranges = if resp.status() == StatusCode::PARTIAL_CONTENT {+ let ranges = if head.status == StatusCode::PARTIAL_CONTENT {RANGES_YES} else {RANGES_UNKNOWN};// The first answer says the server takes ranges (`Accept-Ranges: bytes`).let advertised = ranges == RANGES_YES- || header_str(resp.headers(), header::ACCEPT_RANGES)+ || header_str(&head.headers, header::ACCEPT_RANGES).is_some_and(|v| v.split(',').any(|t| t.trim().eq_ignore_ascii_case("bytes")));- let final_url = resp.url().clone();+ let final_url = head.url.clone();shared.event(format!("Connected to {}{}: {}, size {}",final_url.host_str().unwrap_or("?"),@@ -1684,7 +1779,7 @@ async fn run_fresh(} else {""},- resp.status(),+ head.status,size.map_or("unknown".to_owned(), disk::human),));// Credentials stay with the host they were given for, with the cookies pages set on the way@@ -1695,10 +1790,10 @@ async fn run_fresh(// something each time it is posted (an export, an order).let post = post_for(&opts, as_get.contains(&final_url), &mut headers);let wait_for_ranges = post.is_some() && ranges != RANGES_YES;- let h = resp.headers();+ let h = &head.headers;// The expected hash: the user's, else what a full (200) answer announces for its content.let checksum = opts.checksum.clone().or_else(|| {- (resp.status() == StatusCode::OK)+ (head.status == StatusCode::OK).then(|| crate::verify::Hash::from_headers(h)).flatten()});@@ -1716,13 +1811,13 @@ async fn run_fresh(.flatten().and_then(|lm| httpdate::parse_http_date(lm).ok());- let content_type = resp- .headers()+ let content_type = head+ .headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).map(str::to_owned);let (dest, _reservation, file) = open_destination(&req.dest, size, &opts, || {- let cd = header_text(resp.headers(), header::CONTENT_DISPOSITION);+ let cd = header_text(&head.headers, header::CONTENT_DISPOSITION);name_for(cd.as_deref(), &final_url, unlocked.as_ref())}).await?;@@ -1744,6 +1839,7 @@ async fn run_fresh(saved.checksum = checksum.clone();saved.final_get = opts.post.is_some() && post.is_none();saved.asked_as_mdm = asked_as_mdm;+ saved.browser_like = browser.is_some();let ctx = Arc::new(Ctx {client: client0.clone(),validators: Mutex::new(validators),@@ -1753,7 +1849,10 @@ async fn run_fresh(post: post.clone(),generation: 0,}),- origin: (req.url != final_url).then(|| (req.url.clone(), req.headers.clone())),+ // Asked again through MDM's own connection, which the site's bot check refuses: a+ // browser-like download keeps the address it has (#668).+ origin: (req.url != final_url && browser.is_none())+ .then(|| (req.url.clone(), req.headers.clone())),refreshed: Default::default(),size,file: file.clone(),@@ -1769,32 +1868,41 @@ async fn run_fresh(as_get,web_page_ok: expects_web_page(&dest, content_type.as_deref()),ftp: None,+ browser: browser.clone(),});- match segmented(ctx, saved, Some(Body::Http(resp))).await {+ match segmented(ctx, saved, Some(body)).await {Ok(()) => size,// The server ignores ranges and the probe's data can't be kept: start over on// one connection.Err(Error::NoRanges) => {*shared.planner.lock().unwrap() = None;shared.view.lock().unwrap().resumable = Some(false);- let agent = opts.site_agent();- let (resp, ..) = get(- &client0,- final_url,- headers,- post.as_ref(),- agent,- expects,- cancel,- )- .await?;- let body = Body::Http(resp);+ let body = match &browser {+ Some(b) => {+ let (head, body, _) = b.get(final_url, headers, false, cancel).await?;+ crate::browserlike::check_first(&head, expects)?;+ body+ }+ None => {+ let agent = opts.site_agent();+ let (resp, ..) = get(+ &client0,+ final_url,+ headers,+ post.as_ref(),+ agent,+ expects,+ cancel,+ )+ .await?;+ Body::Http(resp)+ }+ };single_stream(body, &file, shared, opts.global.as_deref(), cancel).await?}Err(e) => return Err(e),}} else {- let body = Body::Http(resp);single_stream(body, &file, shared, opts.global.as_deref(), cancel).await?};verify_part(shared, &dest, checksum.as_ref()).await?;@@ -1971,6 +2079,7 @@ async fn run_fresh_ftp(as_get: AsGet::default(),web_page_ok: true,ftp: Some(site.clone()),+ browser: None,});match segmented(ctx, saved, Some(first)).await {Ok(()) => size,@@ -2026,32 +2135,48 @@ async fn run_resume(let as_get = AsGet::default();let seen = shared.seen.get_or_init(Default::default).clone();let client = client(&opts, &saved.url, &as_get, &seen)?;- // Through a service account (#44), the service is asked for today's link even when the- // state holds none of its links (the download went directly until now).- let refreshed = if saved.url != saved.final_url || opts.unlocker.is_some() {- let post = opts.post.as_ref();- let agent = opts.site_agent();- refresh_final_url(- &client,- &saved.url,+ // Only the browser-like connection got past the site's bot check (#668): it goes on with+ // it, on one connection, at the address it had (MDM's own connection would be refused).+ let browser = match saved.browser_like && crate::browserlike::AVAILABLE {+ true => Some(Arc::new(crate::browserlike::Browser::new(+ &opts,+ &saved.final_url,&headers,- post,- agent,- saved.size,- &cancel,- opts.unlocker.as_ref(),- &shared,- )- .await- } else {- None+ )?)),+ false => None,};+ if browser.is_some() {+ opts.max_connections = 1;+ shared.event("Going on the way a browser connects, as the site's bot check asked");+ }+ // Through a service account (#44), the service is asked for today's link even when the+ // state holds none of its links (the download went directly until now).+ let refreshed =+ if browser.is_none() && (saved.url != saved.final_url || opts.unlocker.is_some()) {+ let post = opts.post.as_ref();+ let agent = opts.site_agent();+ refresh_final_url(+ &client,+ &saved.url,+ &headers,+ post,+ agent,+ saved.size,+ &cancel,+ opts.unlocker.as_ref(),+ &shared,+ )+ .await+ } else {+ None+ };// A POST download's target is asked with GET when its redirects turned it into one.let (url, final_get, refreshed_headers) = match refreshed {Some((url, h)) => (url.clone(), as_get.contains(&url), Some(h)),None => (saved.final_url.clone(), saved.final_get, None),};- let origin = (saved.url != url).then(|| (saved.url.clone(), headers.clone()));+ let origin =+ (saved.url != url && browser.is_none()).then(|| (saved.url.clone(), headers.clone()));// Credentials stay with the host they were given for (the refresh's own way there scoped// them as it went).headers = refreshed_headers.unwrap_or_else(|| scoped_headers(&headers, &saved.url, &url));@@ -2139,6 +2264,7 @@ async fn run_resume(as_get,web_page_ok,ftp,+ browser,});let stamp = ctx.opts@@ -2501,11 +2627,88 @@ impl FirstAsk<'_> {}/// A plain 403, which a browser's User-Agent may have brought on (#372). A site's bot check-/// isn't asked again: that one stays the site's call (#376).+/// isn't asked again as MDM: it gets one try the way a browser connects (`browser_first`).fn agent_refused(e: &Error) -> bool {matches!(e, Error::Status(s) if s.as_u16() == 403)}+/// A first answer that refuses MDM's connection for not being a browser's (#668): the site's bot+/// check (`Error::BotCheck`, Cloudflare's), or 412 Precondition Failed, which MDM's first+/// request, sent without any precondition (no `If-…` header), can only get as such a refusal+/// (FileHippo's, #630).+fn refused_as_a_program(e: &Error) -> bool {+ matches!(e, Error::BotCheck) || matches!(e, Error::Status(s) if s.as_u16() == 412)+}++/// #668: the first request once more, after the site refused MDM's own connection as a+/// program's (`refused_as_a_program`, its error `refused`): through the browser-like connection+/// (`crate::browserlike`), at the same address with the same headers, once, its answer checked+/// as the first one is. When that fails too, `refused` is what is told (the error users know,+/// with its way out: the browser), the reason in the event log. With the answer, the connection+/// the download goes on with.+async fn browser_first(+ opts: &Options,+ url: &Url,+ headers: &HeaderMap,+ refused: Error,+ expects: bool,+ shared: &Shared,+ cancel: &CancellationToken,+) -> Result<+ (+ Arc<crate::browserlike::Browser>,+ Head,+ Body,+ HeaderMap,+ Duration,+ ),+ Error,+> {+ if !crate::browserlike::AVAILABLE {+ return Err(refused);+ }+ let host = url.host_str().unwrap_or("?");+ shared.event(format!(+ "{host}: {refused}; asking once more the way a browser connects"+ ));+ let (b, asked) = match browser_ask(opts, url, headers, expects, cancel).await {+ Ok(got) => got,+ Err(e @ (Error::Cancelled | Error::Adapter(_))) => return Err(e),+ Err(e) => {+ shared.event(format!("{host}, asked the way a browser connects: {e}"));+ return Err(refused);+ }+ };+ let (head, body, headers, took) = asked;+ shared.event(format!(+ "{host}: the browser-like connection got through; downloading on it, one connection"+ ));+ Ok((b, head, body, headers, took))+}++/// The browser-like connection for `url`, and its answer to the first request (`browser_first`,+/// `probe_kept`): the file's, or why not.+async fn browser_ask(+ opts: &Options,+ url: &Url,+ headers: &HeaderMap,+ expects: bool,+ cancel: &CancellationToken,+) -> Result<+ (+ Arc<crate::browserlike::Browser>,+ (Head, Body, HeaderMap, Duration),+ ),+ Error,+> {+ let b = Arc::new(crate::browserlike::Browser::new(opts, url, headers)?);+ let asked = std::time::Instant::now();+ let (head, body, headers) = b.get(url.clone(), headers.clone(), false, cancel).await?;+ let took = asked.elapsed();+ crate::browserlike::check_first(&head, expects)?;+ Ok((b, (head, body, headers, took)))+}+/// A plain `GET` (no Range), or a POST of `post`, that must answer 200 or 206. A GET follows/// the HTTP redirects (the client's policy) and then the redirects a page makes itself (#28):/// a download site's "your download starts in a moment" page, sent with a `Refresh` header or a@@ -2764,7 +2967,7 @@ fn meta_refresh(page: &[u8], base: &Url) -> Option<(Duration, Url)> {}/// The `name=value` pairs a response's `Set-Cookie` headers set.-fn set_cookies(h: &HeaderMap) -> Vec<String> {+pub(crate) fn set_cookies(h: &HeaderMap) -> Vec<String> {h.get_all(header::SET_COOKIE).iter().filter_map(|v| v.to_str().ok())@@ -2776,7 +2979,7 @@ fn set_cookies(h: &HeaderMap) -> Vec<String> {}/// `cookies` added to the request's `Cookie` header, each replacing one of the same name.-fn add_cookies(headers: &mut HeaderMap, cookies: &[String]) {+pub(crate) fn add_cookies(headers: &mut HeaderMap, cookies: &[String]) {if cookies.is_empty() {return;}@@ -3129,34 +3332,52 @@ async fn request(ctx: &Ctx, target: &Target, from: u64, to: u64) -> Result<Body,.unwrap().if_range(target.url.host_str()).and_then(|v| HeaderValue::from_str(v).ok());- let mut req = build(- &ctx.client,- target.url.clone(),- target.post.as_ref(),- &target.headers,- ctx.opts.site_agent(),- )- .header(header::RANGE, format!("bytes={from}-{}", to - 1));- if let Some(v) = &if_range {- req = req.header(header::IF_RANGE, v);- }- let resp = cancellable(&ctx.cancel, async { Ok(req.send().await?) }).await?;- if resp.status().is_success() && !ctx.web_page_ok && is_web_page(resp.headers()) {+ let range = format!("bytes={from}-{}", to - 1);+ let (head, body) = match &ctx.browser {+ // The browser-like connection's own (#668): its redirects followed as `get` does.+ Some(b) => {+ let mut headers = target.headers.clone();+ headers.insert(header::RANGE, HeaderValue::from_str(&range).expect("ascii"));+ if let Some(v) = &if_range {+ headers.insert(header::IF_RANGE, v.clone());+ }+ let (head, body, _) = b+ .get(target.url.clone(), headers, true, &ctx.cancel)+ .await?;+ (head, body)+ }+ None => {+ let mut req = build(+ &ctx.client,+ target.url.clone(),+ target.post.as_ref(),+ &target.headers,+ ctx.opts.site_agent(),+ )+ .header(header::RANGE, range);+ if let Some(v) = &if_range {+ req = req.header(header::IF_RANGE, v);+ }+ let resp = cancellable(&ctx.cancel, async { Ok(req.send().await?) }).await?;+ (Head::of(&resp), Body::Http(resp))+ }+ };+ if head.status.is_success() && !ctx.web_page_ok && is_web_page(&head.headers) {return Err(Error::GotWebPage);}- match resp.status() {+ match head.status {StatusCode::PARTIAL_CONTENT => {ctx.learn_ranges(true);ctx.range_answered.notify_one();}// The same file under another ETag (each CDN node has its own): go on with the date.- StatusCode::OK if per_node_etag(ctx, if_range.as_ref(), &resp) => {+ StatusCode::OK if per_node_etag(ctx, if_range.as_ref(), &head) => {return Err(Error::RangesUnavailable);}// A full body for a ranged request once ranges are known to work: If-Range failed (the// file changed), unless it is still the same file and this answer just lacks the range.StatusCode::OK if ctx.ranges.load(Ordering::SeqCst) == RANGES_YES => {- return Err(if same_file(ctx, &resp) {+ return Err(if same_file(ctx, &head) {Error::RangesUnavailable} else {Error::FileChanged@@ -3167,38 +3388,38 @@ async fn request(ctx: &Ctx, target: &Target, from: u64, to: u64) -> Result<Body,return Err(Error::NoRanges);}s if s == StatusCode::TOO_MANY_REQUESTS || s == StatusCode::SERVICE_UNAVAILABLE => {- return Err(Error::Throttled(s, retry_after(resp.headers())));+ return Err(Error::Throttled(s, retry_after(&head.headers)));}s => return Err(Error::Status(s)),}- let (start, _, total) = parse_content_range(resp.headers())?;+ let (start, _, total) = parse_content_range(&head.headers)?;if start != from || total.is_some_and(|t| t != ctx.size) {return Err(Error::BadRange(format!("asked {from}-{}, got {start}..",to - 1)));}- Ok(Body::Http(resp))+ Ok(body)}/// A full answer that still describes the file being downloaded: the same length and, when the/// download has validators, the same one it would send.-fn same_file(ctx: &Ctx, resp: &Response) -> bool {- let host = resp.url().host_str();+fn same_file(ctx: &Ctx, resp: &Head) -> bool {+ let host = resp.url.host_str();let v = ctx.validators.lock().unwrap();- let h = resp.headers();+ let h = &resp.headers;let theirs = match v.if_range(host) {- None => return resp.content_length() == Some(ctx.size),+ None => return resp.len == Some(ctx.size),Some(ours) if Some(ours) == v.etag.as_deref() => header_str(h, header::ETAG),Some(_) => header_str(h, header::LAST_MODIFIED),};- resp.content_length() == Some(ctx.size) && theirs.is_some() && theirs == v.if_range(host)+ resp.len == Some(ctx.size) && theirs.is_some() && theirs == v.if_range(host)}/// A full answer to an ETag `If-Range` that still matches by length and Last-Modified: the/// ETag differs per node (CDNs, mirrors), not the file. The ETag is dropped for the rest of the/// download, so the next request validates with the date (and the overlap check).-fn per_node_etag(ctx: &Ctx, sent: Option<&HeaderValue>, resp: &Response) -> bool {+fn per_node_etag(ctx: &Ctx, sent: Option<&HeaderValue>, resp: &Head) -> bool {let mut v = ctx.validators.lock().unwrap();// Sent with an ETag (dates never start with a quote) — possibly one another connection has// just dropped, so don't compare it with the current one.@@ -3206,14 +3427,14 @@ fn per_node_etag(ctx: &Ctx, sent: Option<&HeaderValue>, resp: &Response) -> bool// Another node's ETag differs from the one sent. The same ETag is that too only from a// server that advertised ranges: one that didn't, answering in full, has no ranges (#136),// and is told so at once rather than after a round of retries.- let theirs = header_str(resp.headers(), header::ETAG);+ let theirs = header_str(&resp.headers, header::ETAG);let other_node = ctx.advertised|| (theirs.is_some() && theirs.map(str::as_bytes) != sent.map(HeaderValue::as_bytes));let same = sent_etag&& other_node- && resp.content_length() == Some(ctx.size)+ && resp.len == Some(ctx.size)&& v.last_modified.is_some()- && header_str(resp.headers(), header::LAST_MODIFIED) == v.last_modified.as_deref();+ && header_str(&resp.headers, header::LAST_MODIFIED) == v.last_modified.as_deref();if same {v.etag = None;v.etag_host = None;@@ -3226,13 +3447,13 @@ fn header_str(h: &HeaderMap, name: header::HeaderName) -> Option<&str> {}/// A site's bot check turning the request away (#376), as Cloudflare marks it.-fn is_bot_check(status: StatusCode, h: &HeaderMap) -> bool {+pub(crate) fn is_bot_check(status: StatusCode, h: &HeaderMap) -> bool {status == StatusCode::FORBIDDEN&& h.get("cf-mitigated").is_some_and(|v| v.as_bytes().eq_ignore_ascii_case(b"challenge"))}-fn is_web_page(h: &HeaderMap) -> bool {+pub(crate) fn is_web_page(h: &HeaderMap) -> bool {h.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(is_web_page_type)@@ -3244,7 +3465,7 @@ fn is_web_page_type(content_type: &str) -> bool {}/// The server names what it sends (`Content-Disposition`): its own file, page or not.-fn named(h: &HeaderMap) -> bool {+pub(crate) fn named(h: &HeaderMap) -> bool {h.contains_key(header::CONTENT_DISPOSITION)}@@ -3706,7 +3927,7 @@ fn parse_content_range(h: &HeaderMap) -> Result<(u64, u64, Option<u64>), Error>}/// `Retry-After`: delay in seconds, or an HTTP date.-fn retry_after(h: &HeaderMap) -> Option<Duration> {+pub(crate) fn retry_after(h: &HeaderMap) -> Option<Duration> {let v = h.get(header::RETRY_AFTER)?.to_str().ok()?.trim();if let Ok(secs) = v.parse::<u64>() {return Some(Duration::from_secs(secs));@@ -3718,7 +3939,7 @@ fn retry_after(h: &HeaderMap) -> Option<Duration> {)}-async fn cancellable<T>(+pub(crate) async fn cancellable<T>(cancel: &CancellationToken,fut: impl Future<Output = Result<T, Error>>,) -> Result<T, Error> {diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 3abdfa24..922b701f 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -1,6 +1,7 @@//! Mister Download Manager download engine. See notes/ENGINE.md.pub mod agent;+mod browserlike;pub mod disk;pub mod dns;pub mod download;diff --git a/crates/engine/src/net.rs b/crates/engine/src/net.rsindex d94ca197..0d12f90e 100644--- a/crates/engine/src/net.rs+++ b/crates/engine/src/net.rs@@ -116,7 +116,7 @@ impl Binding {}/// The one address a Windows client binds: IPv4 when the adapter has one.- fn windows_local(&self) -> Option<IpAddr> {+ pub(crate) fn windows_local(&self) -> Option<IpAddr> {self.v4.map(IpAddr::V4).or(self.v6.map(IpAddr::V6))}diff --git a/crates/engine/src/state.rs b/crates/engine/src/state.rsindex 357782f6..2618489a 100644--- a/crates/engine/src/state.rs+++ b/crates/engine/src/state.rs@@ -47,6 +47,10 @@ pub struct ResumeState {/// a GET (301, 302, 303): `final_url` is asked with GET.#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub final_get: bool,+ /// Only the browser-like connection got past the site's bot check (#668): a resume goes on+ /// through it, on one connection.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub browser_like: bool,}impl ResumeState {@@ -64,6 +68,7 @@ impl ResumeState {checksum: None,asked_as_mdm: false,final_get: false,+ browser_like: false,}}diff --git a/crates/engine/tests/browserlike.rs b/crates/engine/tests/browserlike.rsnew file mode 100644index 00000000..56bdf1b1--- /dev/null+++ b/crates/engine/tests/browserlike.rs@@ -0,0 +1,454 @@+//! #668: a site whose bot check refuses MDM's own connection (`Error::BotCheck`) is asked once+//! more the way a browser connects, and the download goes on through that connection only. The+//! lab server's `browser_only` fault stands in for the bot check: it refuses, with Cloudflare's+//! `cf-mitigated: challenge`, every request without the headers browsers send (`Sec-Fetch-Mode`).+#![cfg(feature = "browser-connection")]++use std::time::{Duration, Instant};++use mdm_engine::{Destination, Download, Options, Request};+use mdm_labserver::{Config, Faults, LabServer, LogEntry, content};+use reqwest::header::{COOKIE, HeaderMap, REFERER, USER_AGENT};++const SETTLE: Duration = Duration::from_secs(20);+const CHROME: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36";++async fn server(faults: &str) -> LabServer {+ LabServer::start(Config {+ faults: Faults::parse(faults).unwrap(),+ ..Config::default()+ })+ .await+ .unwrap()+}++fn opts() -> Options {+ Options {+ retry_delay: Duration::from_millis(50),+ user_agent: CHROME.to_owned(),+ ..Options::default()+ }+}++/// The browser's hand-over: its session cookie and the page as Referer.+fn handed_over() -> HeaderMap {+ let mut h = HeaderMap::new();+ h.insert(COOKIE, "sid=1".parse().unwrap());+ h.insert(REFERER, "http://127.0.0.1/app/".parse().unwrap());+ h+}++fn same_content(path: &std::path::Path, seed: u64, len: usize) {+ let data = std::fs::read(path).unwrap();+ let mut want = vec![0; len];+ content::fill(seed, 0, &mut want);+ assert!(data == want, "content mismatch");+}++async fn settled_log(s: &LabServer) -> Vec<LogEntry> {+ tokio::time::timeout(SETTLE, s.settled())+ .await+ .expect("every request ends");+ s.log()+}++#[tokio::test]+async fn a_bot_check_is_passed_the_way_a_browser_connects() {+ let s = server("browser_only=1&require_cookie=sid=1").await;+ let dir = tempfile::tempdir().unwrap();+ let dl = Download::start(+ Request {+ url: s.url("/gen/3M/app.apk?seed=668").parse().unwrap(),+ headers: handed_over(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ opts(),+ );+ let out = dl+ .wait()+ .await+ .expect("the browser-like connection gets through");+ same_content(&out.path, 668, 3 << 20);+ let log = settled_log(&s).await;+ // MDM's own request first, refused; then the browser-like connection's, one at a time.+ assert_eq!(log[0].outcome, "fault:browser_only", "{log:?}");+ assert!(log[0].sec_fetch_mode.is_none());+ let through: Vec<_> = log[1..].iter().collect();+ assert!(!through.is_empty());+ for e in &through {+ assert!(e.sec_fetch_mode.is_some(), "{e:?}");+ // The download's own User-Agent, the browser's cookie for its site, its Referer.+ assert_eq!(e.user_agent.as_deref(), Some(CHROME), "{e:?}");+ assert_eq!(e.cookie.as_deref(), Some("sid=1"), "{e:?}");+ assert_eq!(e.referer.as_deref(), Some("http://127.0.0.1/app/"), "{e:?}");+ assert!(e.status == 200 || e.status == 206, "{e:?}");+ }+ assert_eq!(+ log.iter()+ .filter(|e| e.outcome == "fault:browser_only")+ .count(),+ 1,+ "asked once more, not again and again: {log:?}"+ );+}++#[tokio::test]+async fn the_user_agent_handed_over_is_the_one_sent() {+ let s = server("browser_only=1").await;+ let dir = tempfile::tempdir().unwrap();+ let firefox = "Mozilla/5.0 (X11; Linux x86_64; rv:145.0) Gecko/20100101 Firefox/145.0";+ let mut headers = HeaderMap::new();+ headers.insert(USER_AGENT, firefox.parse().unwrap());+ let out = Download::start(+ Request {+ url: s.url("/gen/256K/f.bin?seed=2").parse().unwrap(),+ headers,+ dest: Destination::Dir(dir.path().to_owned()),+ },+ opts(),+ )+ .wait()+ .await+ .unwrap();+ same_content(&out.path, 2, 256 << 10);+ let log = settled_log(&s).await;+ assert!(+ log.iter()+ .filter(|e| e.sec_fetch_mode.is_some())+ .all(|e| e.user_agent.as_deref() == Some(firefox)),+ "{log:?}"+ );+}++#[tokio::test]+async fn cookies_stay_with_their_site_through_redirects() {+ let s = server("browser_only=1").await;+ let port = s.addr().port();+ // 127.0.0.1 redirects to localhost: another host, as when a site hands off to a CDN.+ let target = format!("http://localhost:{port}/gen/1M/r.bin?seed=3");+ let enc: String = target+ .chars()+ .map(|c| match c {+ ':' => "%3A".to_owned(),+ '/' => "%2F".to_owned(),+ '?' => "%3F".to_owned(),+ '=' => "%3D".to_owned(),+ c => c.to_string(),+ })+ .collect();+ let dir = tempfile::tempdir().unwrap();+ let out = Download::start(+ Request {+ url: s.url(&format!("/redirect?to={enc}")).parse().unwrap(),+ headers: handed_over(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ opts(),+ )+ .wait()+ .await+ .unwrap();+ same_content(&out.path, 3, 1 << 20);+ let log = settled_log(&s).await;+ assert!(log.iter().any(|e| e.sec_fetch_mode.is_some()), "{log:?}");+ assert!(+ log.iter().all(|e| e.cookie.is_none()),+ "the cookie for 127.0.0.1 reached localhost: {log:?}"+ );+}++#[tokio::test]+async fn a_stopped_download_resumes_through_the_same_connection() {+ let s = server("browser_only=1&rate=1M&stall_at=1M").await;+ let dir = tempfile::tempdir().unwrap();+ let dl = Download::start(+ Request {+ url: s.url("/gen/3M/r.bin?seed=7").parse().unwrap(),+ headers: handed_over(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ Options {+ save_interval: Duration::from_millis(100),+ ..opts()+ },+ );+ let deadline = Instant::now() + Duration::from_secs(20);+ let file = loop {+ tokio::time::sleep(Duration::from_millis(50)).await;+ let snap = dl.snapshot();+ if let Some(f) = snap.file.filter(|_| snap.downloaded >= 256 << 10) {+ break f;+ }+ assert!(Instant::now() < deadline, "the download never started");+ };+ dl.cancel();+ assert!(matches!(dl.wait().await, Err(mdm_engine::Error::Cancelled)));+ s.set_faults(Faults::parse("browser_only=1&rate=4M").unwrap());+ tokio::time::timeout(SETTLE, s.settled()).await.unwrap();+ let state = mdm_engine::state::state_path(&file);+ let saved = mdm_engine::state::ResumeState::load(&state).unwrap();+ assert!(saved.browser_like, "the state says how it got through");+ s.clear_log();+ let out = Download::resume(state.clone(), handed_over(), opts())+ .unwrap()+ .wait()+ .await+ .expect("the resume goes on");+ same_content(&out.path, 7, 3 << 20);+ let log = settled_log(&s).await;+ // Straight through the browser-like connection, from where it stopped, its bytes as they+ // are (no compression asked for a range).+ assert!(!log.is_empty());+ for e in &log {+ assert!(e.sec_fetch_mode.is_some(), "{e:?}");+ assert_eq!(e.status, 206, "{e:?}");+ assert!(+ e.range+ .as_deref()+ .is_some_and(|r| !r.starts_with("bytes=0-")),+ "{e:?}"+ );+ assert_eq!(e.accept_encoding.as_deref(), Some("identity"), "{e:?}");+ }+}++#[tokio::test]+async fn the_speed_limit_holds() {+ let s = server("browser_only=1").await;+ let dir = tempfile::tempdir().unwrap();+ let started = Instant::now();+ let out = Download::start(+ Request {+ url: s.url("/gen/1M/s.bin?seed=9").parse().unwrap(),+ headers: Default::default(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ Options {+ speed_limit: Some(512 << 10),+ ..opts()+ },+ )+ .wait()+ .await+ .unwrap();+ same_content(&out.path, 9, 1 << 20);+ // 1 MiB at 512 KiB/s: two seconds, one at least with the limiter's first second of burst.+ assert!(+ started.elapsed() >= Duration::from_millis(900),+ "{:?}",+ started.elapsed()+ );+}++#[tokio::test]+async fn a_look_gets_past_the_bot_check_too() {+ let s = server("browser_only=1").await;+ let info = mdm_engine::probe(+ s.url("/gen/2M/look.apk?seed=1").parse().unwrap(),+ Default::default(),+ &opts(),+ )+ .await+ .expect("the look gets through");+ assert_eq!(info.size, Some(2 << 20));+ assert_eq!(info.file_name, "look.apk");+}++#[tokio::test]+async fn stop_ends_it() {+ let s = server("browser_only=1&rate=256K").await;+ let dir = tempfile::tempdir().unwrap();+ let dl = Download::start(+ Request {+ url: s.url("/gen/8M/c.bin?seed=4").parse().unwrap(),+ headers: Default::default(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ opts(),+ );+ let deadline = Instant::now() + Duration::from_secs(20);+ while dl.snapshot().downloaded == 0 {+ assert!(Instant::now() < deadline, "never started");+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ dl.cancel();+ let stopped = tokio::time::timeout(Duration::from_secs(5), dl.wait())+ .await+ .expect("stop is prompt");+ assert!(matches!(stopped, Err(mdm_engine::Error::Cancelled)));+}++/// Over HTTPS the lab's bot check looks at the TLS handshake itself, as real ones do: a plain+/// client that sends a browser's headers is still refused; MDM's own request is refused, and the+/// browser-like connection, whose handshake is Chrome's, gets the file.+#[tokio::test]+async fn over_https_the_handshake_itself_is_what_gets_through() {+ let s = LabServer::start(Config {+ faults: Faults::parse("browser_only=1").unwrap(),+ tls: true,+ ..Config::default()+ })+ .await+ .unwrap();+ let ca = s.ca_der().unwrap();+ // A program's TLS with every header a browser sends: refused all the same.+ let plain = reqwest::Client::builder()+ .tls_certs_merge([reqwest::Certificate::from_der(&ca).unwrap()])+ .build()+ .unwrap();+ let refused = plain+ .get(s.url("/gen/64K/x.bin?seed=1"))+ .header(USER_AGENT, CHROME)+ .header("Sec-Fetch-Mode", "navigate")+ .send()+ .await+ .unwrap();+ assert_eq!(refused.status(), 403);+ assert_eq!(refused.headers()["cf-mitigated"], "challenge");+ s.clear_log();++ let dir = tempfile::tempdir().unwrap();+ let out = Download::start(+ Request {+ url: s.url("/gen/2M/app.apk?seed=21").parse().unwrap(),+ headers: handed_over(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ Options {+ extra_roots: vec![ca],+ ..opts()+ },+ )+ .wait()+ .await+ .expect("the browser-like connection gets through");+ same_content(&out.path, 21, 2 << 20);+ let log = settled_log(&s).await;+ assert_eq!(log[0].outcome, "fault:browser_only", "{log:?}");+ assert_eq!(log[0].browser_tls, Some(false), "{log:?}");+ assert!(log.len() >= 2, "{log:?}");+ for e in &log[1..] {+ assert_eq!(e.browser_tls, Some(true), "{e:?}");+ assert!(e.status == 200 || e.status == 206, "{e:?}");+ }+}++/// The file's information window looks first (`probe_kept`): its browser-like answer is kept+/// for the download, so a click costs one refused request and one that gets through, no more.+#[tokio::test]+async fn a_look_and_its_download_ask_once_more_in_all() {+ let s = server("browser_only=1").await;+ let url: url::Url = s.url("/gen/1M/kept.apk?seed=5").parse().unwrap();+ let (info, kept) = mdm_engine::probe_kept(url.clone(), handed_over(), &opts())+ .await+ .expect("the look gets through");+ assert_eq!(info.size, Some(1 << 20));+ assert!(kept.is_some(), "the browser-like answer is kept");+ let dir = tempfile::tempdir().unwrap();+ let out = Download::start_with(+ Request {+ url,+ headers: handed_over(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ opts(),+ kept,+ )+ .wait()+ .await+ .unwrap();+ same_content(&out.path, 5, 1 << 20);+ let log = settled_log(&s).await;+ assert_eq!(log.len(), 2, "{log:?}");+ assert_eq!(log[0].outcome, "fault:browser_only");+ assert!(+ log[1].sec_fetch_mode.is_some() && log[1].status == 200,+ "{log:?}"+ );+}++/// Options → Proxy: the browser-like connection goes through the proxy too. The lab server+/// stands in for the proxy (it answers by path), so a host that can't exist only works there.+#[tokio::test]+async fn it_goes_through_the_proxy() {+ let s = server("browser_only=1").await;+ let dir = tempfile::tempdir().unwrap();+ let out = Download::start(+ Request {+ url: "http://nowhere.invalid/gen/512K/p.bin?seed=8"+ .parse()+ .unwrap(),+ headers: Default::default(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ Options {+ proxy: mdm_engine::Proxy::Manual {+ url: s.url(""),+ login: None,+ http: true,+ https: true,+ },+ ..opts()+ },+ )+ .wait()+ .await+ .expect("downloaded through the proxy");+ same_content(&out.path, 8, 512 << 10);+ let log = settled_log(&s).await;+ assert_eq!(log[0].outcome, "fault:browser_only", "{log:?}");+ assert!(+ log[1..].iter().all(|e| e.sec_fetch_mode.is_some()),+ "{log:?}"+ );+}++/// A site that refuses the browser-like connection too (a challenge to solve, say): the+/// download fails with the bot check's refusal, as before, after one more request only.+#[tokio::test]+async fn a_second_refusal_stays_the_bot_check() {+ let s = server("browser_only=1&refuse_agent=Chrome").await;+ let dir = tempfile::tempdir().unwrap();+ let err = Download::start(+ Request {+ url: s.url("/gen/64K/no.bin?seed=1").parse().unwrap(),+ headers: Default::default(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ opts(),+ )+ .wait()+ .await+ .unwrap_err();+ assert!(matches!(err, mdm_engine::Error::BotCheck), "{err:?}");+ let log = settled_log(&s).await;+ assert_eq!(log.len(), 2, "{log:?}");+}++/// FileHippo's way (#630): 412 Precondition Failed, empty, to whatever isn't a browser. MDM's+/// first request carries no precondition, so that 412 can only refuse the program: it is asked+/// once more the way a browser connects too, and the file comes.+#[tokio::test]+async fn a_412_to_a_request_without_preconditions_is_asked_once_more_too() {+ let s = server("refuse_programs=412").await;+ let dir = tempfile::tempdir().unwrap();+ let out = Download::start(+ Request {+ url: s.url("/gen/1M/winrar-x64.exe?seed=630").parse().unwrap(),+ headers: handed_over(),+ dest: Destination::Dir(dir.path().to_owned()),+ },+ opts(),+ )+ .wait()+ .await+ .expect("the browser-like connection gets through");+ same_content(&out.path, 630, 1 << 20);+ let log = settled_log(&s).await;+ assert_eq!(log[0].status, 412, "{log:?}");+ assert_eq!(log.iter().filter(|e| e.status == 412).count(), 1, "{log:?}");+ assert!(+ log[1..].iter().all(|e| e.sec_fetch_mode.is_some()),+ "{log:?}"+ );+}diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rsindex 319d5947..10981416 100644--- a/crates/engine/tests/e2e.rs+++ b/crates/engine/tests/e2e.rs@@ -1941,11 +1941,24 @@ async fn a_refused_link_goes_on_where_the_browser_download_ended() {.await.expect("every request ends");let log = s.log();+ let refused = |browser_like: bool| {+ log.iter()+ .filter(|e| e.outcome == "fault:refuse" && e.sec_fetch_mode.is_some() == browser_like)+ .count()+ };assert_eq!(- log.iter().filter(|e| e.outcome == "fault:refuse").count(),+ refused(false),2,"the link was asked once per download: {log:?}");+ // Without the browser's address, it was asked once more the way a browser connects (#668),+ // refused too; with it, the browser's address got the file first.+ let once_more = if cfg!(feature = "browser-connection") {+ 1+ } else {+ 0+ };+ assert_eq!(refused(true), once_more, "{log:?}");let served: Vec<_> = log.iter().filter(|e| e.status == 200 || e.status == 206)diff --git a/crates/engine/tests/post.rs b/crates/engine/tests/post.rsindex 2d1d5a7a..2532aedf 100644--- a/crates/engine/tests/post.rs+++ b/crates/engine/tests/post.rs@@ -216,8 +216,9 @@ async fn fetch(s: &Server, path: &str, opts: Options, want: &[u8]) -> String {out.path.file_name().unwrap().to_string_lossy().into_owned()}-/// #376: Cloudflare's challenge, as it marks it, is reported as the site's bot check, with no-/// retries; another 403 stays a 403.+/// #376: Cloudflare's challenge, as it marks it, is reported as the site's bot check; another+/// 403 stays a 403. It is asked once more the way a browser connects (#668), never more: a+/// challenge that one meets too stays the bot check's refusal.#[tokio::test]async fn a_bot_check_is_named() {let s = Server::start(|seen| {@@ -245,7 +246,16 @@ async fn a_bot_check_is_named() {matches!(challenge, mdm_engine::Error::BotCheck),"{challenge:?}");- assert_eq!(s.seen.lock().unwrap().len(), 1, "a bot check isn't retried");+ let asked = if cfg!(feature = "browser-connection") {+ 2+ } else {+ 1+ };+ assert_eq!(+ s.seen.lock().unwrap().len(),+ asked,+ "a bot check is asked once more at most"+ );let plain = attempt("/plain/f.dat").wait().await.unwrap_err();assert!(matches!(plain, mdm_engine::Error::Status(_)), "{plain:?}");}diff --git a/crates/labserver/Cargo.toml b/crates/labserver/Cargo.tomlindex ad45509b..12bdd1ff 100644--- a/crates/labserver/Cargo.toml+++ b/crates/labserver/Cargo.toml@@ -30,6 +30,8 @@ tokio.workspace = truercgen.workspace = truerustls.workspace = truetokio-rustls.workspace = true+# The HTTPS lab (`Config::tls`): its connections served by hand, axum's own features.+hyper-util = { workspace = true, features = ["server", "http1", "tokio", "service"] }url.workspace = true[dev-dependencies]diff --git a/crates/labserver/src/faults.rs b/crates/labserver/src/faults.rsindex 7ae016af..9419ceb7 100644--- a/crates/labserver/src/faults.rs+++ b/crates/labserver/src/faults.rs@@ -60,6 +60,14 @@ pub struct Faults {/// turns away whatever isn't a browser (FileHippo's 412, #630), or a link the browser/// already spent.pub refuse: Option<u16>,+ /// A bot check that lets only browsers through (#668): 403 with Cloudflare's+ /// `cf-mitigated: challenge` and a challenge page to every file request that doesn't carry+ /// the headers every current browser sends with a navigation (`Sec-Fetch-Mode`).+ #[serde(deserialize_with = "flag_opt")]+ pub browser_only: Option<bool>,+ /// The same check answering this status instead, empty, with `Retry-After: 0` (FileHippo's+ /// 412 to whatever isn't a browser, #630, #668).+ pub refuse_programs: Option<u16>,/// A one-time link: the first request for this path and query is served, every later one/// (HEAD and ranges included) gets 410 Gone.#[serde(deserialize_with = "flag_opt")]@@ -98,6 +106,8 @@ impl Faults {require_cookie: over.require_cookie.clone().or(self.require_cookie.clone()),refuse_agent: over.refuse_agent.clone().or(self.refuse_agent.clone()),refuse: over.refuse.or(self.refuse),+ browser_only: over.browser_only.or(self.browser_only),+ refuse_programs: over.refuse_programs.or(self.refuse_programs),require_referer: over.require_referer.clone()@@ -172,8 +182,10 @@ mod tests {#[test]fn flags_and_refusals() {- let f = Faults::parse("once=1&html=0&no_range=true&require_cookie=sid=1").unwrap();+ let f = Faults::parse("once=1&html=0&no_range=true&require_cookie=sid=1&browser_only=1")+ .unwrap();assert_eq!(f.once, Some(true));+ assert_eq!(f.browser_only, Some(true));assert_eq!(f.html, Some(false));assert_eq!(f.no_range, Some(true));assert_eq!(f.require_cookie.as_deref(), Some("sid=1"));diff --git a/crates/labserver/src/ftp.rs b/crates/labserver/src/ftp.rsindex 0af4e734..c5fe92d8 100644--- a/crates/labserver/src/ftp.rs+++ b/crates/labserver/src/ftp.rs@@ -92,7 +92,10 @@ impl FtpServer {let addr = listener.local_addr()?;let tls = match config.tls {FtpTls::None => None,- _ => Some(certificate().map_err(io::Error::other)?),+ _ => {+ let (config, ca) = certificate().map_err(io::Error::other)?;+ Some((TlsAcceptor::from(Arc::new(config)), ca))+ }};let shared = Arc::new(Shared {config,@@ -172,8 +175,9 @@ impl Drop for FtpServer {}}-/// A test CA and a `localhost` certificate it signed: the acceptor, and the CA's DER.-fn certificate() -> Result<(TlsAcceptor, Vec<u8>), String> {+/// A test CA and a `localhost` certificate it signed: the server's configuration, and the CA's+/// DER (FTPS here, HTTPS for `Config::tls`).+pub(crate) fn certificate() -> Result<(rustls::ServerConfig, Vec<u8>), String> {use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, DnType, IsCa, KeyPair,KeyUsagePurpose,@@ -204,7 +208,7 @@ fn certificate() -> Result<(TlsAcceptor, Vec<u8>), String> {rustls::pki_types::PrivateKeyDer::Pkcs8(key.serialize_der().into()),).map_err(|e| e.to_string())?;- Ok((TlsAcceptor::from(Arc::new(config)), ca.der().to_vec()))+ Ok((config, ca.der().to_vec()))}/// `/gen/{size}[/s{seed}][/{name}]` → (seed, size).diff --git a/crates/labserver/src/main.rs b/crates/labserver/src/main.rsindex cefc2b2e..caaf46ad 100644--- a/crates/labserver/src/main.rs+++ b/crates/labserver/src/main.rs@@ -38,6 +38,10 @@ struct Args {/// A folder of .torrent files for /rss/dir.xml (the RSS tests' downloads).#[arg(long)]rss_dir: Option<std::path::PathBuf>,+ /// Serve HTTPS (as localhost, from a test CA made at start, written next to the log or+ /// printed) instead of HTTP: `browser_only` then looks at the TLS handshake too.+ #[arg(long)]+ tls: bool,}#[tokio::main]@@ -66,12 +70,19 @@ async fn main() -> anyhow::Result<()> {on_log: Some(on_log),files: args.files.clone(),rss_dir: args.rss_dir,+ tls: args.tls,}).await?;eprintln!(- "labserver listening on http://{} (GET / for help)",- server.addr()+ "labserver listening on {} (GET / for help)",+ server.url(""));+ if let Some(ca) = server.ca_der() {+ let path =+ std::env::temp_dir().join(format!("mdm-labserver-ca-{}.der", server.addr().port()));+ std::fs::write(&path, ca)?;+ eprintln!("its test CA's certificate (DER): {}", path.display());+ }let _ftp = match args.ftp {Some(bind) => {use mdm_labserver::ftp::{FtpConfig, FtpServer, FtpTls};diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rsindex 921f39fe..e8f64bdc 100644--- a/crates/labserver/src/server.rs+++ b/crates/labserver/src/server.rs@@ -81,6 +81,17 @@ pub struct LogEntry {/// The `Referer` header.#[serde(default)]pub referer: Option<String>,+ /// The `Sec-Fetch-Mode` header, which browsers send and programs don't (`browser_only`).+ #[serde(default)]+ pub sec_fetch_mode: Option<String>,+ /// The `Accept-Encoding` header.+ #[serde(default)]+ pub accept_encoding: Option<String>,+ /// Over HTTPS (`Config::tls`): whether the connection's TLS ClientHello was a browser's as+ /// `browser_only` tells it, with GREASE values among its cipher suites (as Chrome's and+ /// every Chromium browser's are; programs' TLS libraries send none). None over plain HTTP.+ #[serde(default)]+ pub browser_tls: Option<bool>,/// The request's `Content-Type` (a form post's encoding).#[serde(default)]pub req_content_type: Option<String>,@@ -172,6 +183,9 @@ pub struct Config {pub files: Option<std::path::PathBuf>,/// The folder whose .torrent files /rss/dir.xml lists (`feeds`).pub rss_dir: Option<std::path::PathBuf>,+ /// Serve HTTPS instead of HTTP, as `localhost`, with a certificate from a test CA made at+ /// start (`LabServer::ca_der`): `browser_only` then looks at the TLS handshake too (#668).+ pub tls: bool,}impl Default for Config {@@ -182,6 +196,7 @@ impl Default for Config {on_log: None,files: None,rss_dir: None,+ tls: false,}}}@@ -212,6 +227,9 @@ pub(crate) struct Shared {/// The fake Drive's virus-scan pages' `uuid`s handed out (`drive`).pub(crate) drive_uuids: Mutex<HashSet<String>>,files: Option<std::path::PathBuf>,+ /// Over HTTPS: each connection's ClientHello, browser-like or not (`LogEntry::browser_tls`),+ /// by the client's address.+ browser_tls: Mutex<HashMap<SocketAddr, bool>>,}impl Shared {@@ -271,6 +289,9 @@ impl Shared {authorization: header_str(headers, header::AUTHORIZATION).map(|a| a.chars().take(11).collect::<String>() + "…"),referer: header_str(headers, header::REFERER),+ sec_fetch_mode: header_str(headers, header::HeaderName::from_static("sec-fetch-mode")),+ accept_encoding: header_str(headers, header::ACCEPT_ENCODING),+ browser_tls: self.browser_tls.lock().unwrap().get(&peer).copied(),req_content_type: header_str(headers, header::CONTENT_TYPE),req_body_len: has_body.then_some(body.len() as u64),req_body_sha256: has_body.then(|| hex::encode(Sha256::digest(body))),@@ -307,6 +328,8 @@ pub struct LabServer {addr: SocketAddr,shared: Arc<Shared>,task: JoinHandle<()>,+ /// Over HTTPS (`Config::tls`): the test CA's certificate (DER).+ ca: Option<Vec<u8>>,}impl LabServer {@@ -329,7 +352,12 @@ impl LabServer {on_log: cfg.on_log,drive_uuids: Mutex::default(),files: cfg.files,+ browser_tls: Mutex::default(),});+ let tls = match cfg.tls {+ true => Some(crate::ftp::certificate().map_err(io::Error::other)?),+ false => None,+ };// Routes answered from memory, logged by `log_simple`.let simple = Router::new().route("/page", get(pages::page))@@ -478,13 +506,30 @@ impl LabServer {// Every other address: the fake Google Drive's, by the Host header (`drive`)..fallback(drive::handle).with_state(shared.clone());- let task = tokio::spawn(async move {- let svc = app.into_make_service_with_connect_info::<SocketAddr>();- if let Err(e) = axum::serve(listener, svc).await {- eprintln!("labserver: {e}");+ let ca = tls.as_ref().map(|(_, ca)| ca.clone());+ let task = match tls {+ None => tokio::spawn(async move {+ let svc = app.into_make_service_with_connect_info::<SocketAddr>();+ if let Err(e) = axum::serve(listener, svc).await {+ eprintln!("labserver: {e}");+ }+ }),+ Some((config, _)) => {+ tokio::spawn(serve_tls(listener, app, Arc::new(config), shared.clone()))}- });- Ok(LabServer { addr, shared, task })+ };+ Ok(LabServer {+ addr,+ shared,+ task,+ ca,+ })+ }++ /// Over HTTPS (`Config::tls`): the test CA's certificate (DER); a client trusting it trusts+ /// this server as `localhost`.+ pub fn ca_der(&self) -> Option<Vec<u8>> {+ self.ca.clone()}pub fn addr(&self) -> SocketAddr {@@ -492,8 +537,13 @@ impl LabServer {}/// `http://<addr><path>`; `path` starts with `/`.+ /// The address of `path` (starting with `/`): `http://127.0.0.1:port`, or over HTTPS+ /// `https://localhost:port` (the certificate's name).pub fn url(&self, path: &str) -> String {- format!("http://{}{}", self.addr, path)+ match self.ca {+ None => format!("http://{}{}", self.addr, path),+ Some(_) => format!("https://localhost:{}{}", self.addr.port(), path),+ }}pub fn log(&self) -> Vec<LogEntry> {@@ -581,6 +631,10 @@ GET|HEAD /gen/{size}[/{name}]?seed=N&<file params>&<faults> size: 12345, 64K,refuse_agent=TEXT 403 when the User-Agent contains TEXTrefuse=STATUS every request answered with that 4xx or 5xx status, before any byte (a sitethat turns away whatever isn't a browser: FileHippo's 412, #630)+ browser_only=1 a bot check: 403 with cf-mitigated: challenge and a challenge page unless the+ request carries a browser's Sec-Fetch-Mode header and, over HTTPS (--tls),+ came on a TLS handshake with GREASE, as Chrome's has (#668)+ refuse_programs=STATUS the same check answering STATUS, empty (FileHippo's 412, #630)once=1 a one-time link: the first request for this path and query is served, everylater one (HEAD and ranges too) gets 410 Gone; vary seed= for a fresh link"every Nth" counts file requests (/gen and /form) only.@@ -1061,6 +1115,53 @@ struct FileQuery {faults: Faults,}+/// The lab server over HTTPS (`Config::tls`): each connection's ClientHello is read first, and+/// whether it is a browser's noted for `browser_only` (`LogEntry::browser_tls`), then its+/// requests are served as over HTTP (HTTP/1.1).+async fn serve_tls(+ listener: TcpListener,+ app: Router,+ config: Arc<tokio_rustls::rustls::ServerConfig>,+ shared: Arc<Shared>,+) {+ use hyper_util::rt::{TokioExecutor, TokioIo};+ loop {+ let Ok((tcp, peer)) = listener.accept().await else {+ continue;+ };+ let (app, config, shared) = (app.clone(), config.clone(), shared.clone());+ tokio::spawn(async move {+ let accepting = tokio_rustls::LazyConfigAcceptor::new(+ tokio_rustls::rustls::server::Acceptor::default(),+ tcp,+ );+ let Ok(start) = accepting.await else {+ return;+ };+ let grease = start+ .client_hello()+ .cipher_suites()+ .iter()+ .any(|c| is_grease(u16::from(*c)));+ shared.browser_tls.lock().unwrap().insert(peer, grease);+ let Ok(tls) = start.into_stream(config).await else {+ return;+ };+ let svc = app.layer(axum::Extension(ConnectInfo(peer)));+ let svc = hyper_util::service::TowerToHyperService::new(svc);+ let _ = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())+ .serve_connection(TokioIo::new(tls), svc)+ .await;+ });+ }+}++/// A GREASE value (RFC 8701: 0x0A0A, 0x1A1A … 0xFAFA), which Chrome's TLS puts among its+/// cipher suites and extensions so that servers keep tolerating unknown ones.+fn is_grease(v: u16) -> bool {+ v & 0x0f0f == 0x0a0a && v >> 8 == v & 0xff+}+/// Serves the generated file `size`/`name` for a request whose log entry is `entry`.pub(crate) async fn serve(shared: Arc<Shared>,@@ -1099,6 +1200,28 @@ pub(crate) async fn serve(}let f = shared.faults().overridden_by(&q.faults);+ // The bot check stands in front of the site, as Cloudflare's does: before its own checks.+ let a_program = entry.sec_fetch_mode.is_none() || entry.browser_tls == Some(false);+ if let Some(status) = f+ .refuse_programs+ .and_then(|c| StatusCode::from_u16(c).ok())+ .filter(|s| a_program && (s.is_client_error() || s.is_server_error()))+ {+ shared.record(entry, status.as_u16(), "fault:refuse_programs");+ return (status, [(header::RETRY_AFTER, "0")]).into_response();+ }+ if f.browser_only == Some(true) && a_program {+ shared.record(entry, 403, "fault:browser_only");+ return (+ StatusCode::FORBIDDEN,+ [+ ("cf-mitigated", "challenge"),+ ("content-type", "text/html; charset=UTF-8"),+ ],+ "<!DOCTYPE html><title>Just a moment...</title>\n",+ )+ .into_response();+ }if let Some(want) = &f.require_cookie&& !has_cookie(entry.cookie.as_deref(), want){diff --git a/docs/browser-integration.md b/docs/browser-integration.mdindex 8f096380..2a870a80 100644--- a/docs/browser-integration.md+++ b/docs/browser-integration.md@@ -2,7 +2,7 @@[← Back to docs index](README.md)-With the MDM extension, clicking a download link in your browser hands the download to MDM. MDM gets the address together with the page it came from (the referrer), your cookies for the site and the browser's User-Agent, so downloads that need you to be signed in still work. It also gets the address the browser's own download had reached: when a site refuses MDM the link itself (a one-time link the browser has already used, or a site that lets only browsers ask for its links), MDM goes on from there once, without your cookies if it is another site.+With the MDM extension, clicking a download link in your browser hands the download to MDM. MDM gets the address together with the page it came from (the referrer), your cookies for the site and the browser's User-Agent, so downloads that need you to be signed in still work. It also gets the address the browser's own download had reached: when a site refuses MDM the link itself (a one-time link the browser has already used, or a site that lets only browsers ask for its links), MDM goes on from there once, without your cookies if it is another site. When a site's bot check (Cloudflare's, for one) or its refusal of programs (FileHippo's *412 Precondition Failed*) turns MDM's own connection away, MDM asks once more connecting the way your browser does (the same handshake, settings and order of headers), with your browser's User-Agent and its cookies for that site only, and downloads on that one connection; your proxy, network adapter and speed limits apply as usual. It solves no challenge: a site that still wants one answered refuses again, and MDM says *this site lets only browsers through*; Alt+click the link to leave the download to the browser.The extension works in **Google Chrome**, **Microsoft Edge**, **Brave**, **Opera** and **Vivaldi**, in **Firefox** 140 or later, and in **Safari** 17 or later on a Mac (see [Safari](#safari-macos)).diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 0e153f49..0dac5e8d 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -17,6 +17,7 @@ Every download keeps a log of its recent events: retries, redirects, the server'3. If the link has expired (common for links from sites you sign in to, or links with a time limit in them), get a new one: right-click → **Refresh download address**. See [Resume a broken download](guide-resume-broken-download.md).4. If it says **the file changed on the server**, the file isn't the one MDM started with. Right-click → **Redownload** to start again from the beginning.5. If it says **Google Drive won't give this file now**, Drive's download limit for that file was reached. See [Google Drive links](adding-downloads.md#google-drive-links).+6. If it says **this site lets only browsers through**, the site's bot check (Cloudflare's, for one) turned MDM away. MDM has already asked once more connecting the way your browser does, with your browser's cookies for that site, and the site still wants its check answered in a browser. Open the site in your browser (passing its check there can be enough: click the link again), or hold **Alt** as you click the link to leave that download to the browser. See [Browser integration](browser-integration.md).## A download starts over instead of resumingdiff --git a/rust-toolchain.toml b/rust-toolchain.tomlindex adb8d678..dc301fcd 100644--- a/rust-toolchain.toml+++ b/rust-toolchain.toml@@ -1,4 +1,5 @@-# Stable toolchain; craft-ui requires Rust >= 1.95 (D-003).+# Stable toolchain; craft-ui requires Rust >= 1.95 (D-003), wreq (the engine's browser-like+# connection, #668) 1.98.[toolchain]channel = "stable"components = ["rustfmt", "clippy"]diff --git a/tools/dev/check-cross.ps1 b/tools/dev/check-cross.ps1index f1604ee9..2d03e3a0 100644--- a/tools/dev/check-cross.ps1+++ b/tools/dev/check-cross.ps1@@ -37,7 +37,10 @@ foreach ($t in $Targets) {Set-Item "Env:PKG_CONFIG_$var" "$wrap\pkg-config.cmd"& rustup target add $triple | Out-Null"== $t ($triple)"- & cargo clippy --workspace --all-targets --target $triple --target-dir (Join-Path $root "target\cross") -q -- -D warnings+ # Without the engine's browser-like connection (#668): its BoringSSL doesn't cross-compile+ # through Zig here (CMake looks for the target's threads and macOS tools); the runners build it.+ # The other default features are named back.+ & cargo clippy --workspace --all-targets --no-default-features --features mdm-crash/native-symbols --target $triple --target-dir (Join-Path $root "target\cross") -q -- -D warningsif ($LASTEXITCODE) { $failed += $t }}if ($failed) { throw "failed: $($failed -join ', ')" }diff --git a/tools/lab/linux-vm/setup.sh b/tools/lab/linux-vm/setup.shindex 41a4f354..3d19ea55 100644--- a/tools/lab/linux-vm/setup.sh+++ b/tools/lab/linux-vm/setup.sh@@ -75,7 +75,7 @@ sudo_ apt-get update -qsudo_ apt-get install -y -q \build-essential pkg-config git curl ca-certificates python3 python3-pip python3-pil \libgtk-3-dev libxkbcommon-dev libwayland-dev libgl1-mesa-dev \- libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev \+ libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev cmake libclang-dev \rpm zsync libfuse2t64 \ffmpeg p7zip-full gallery-dl \at-spi2-core python3-pyatspi orca xdotool wmctrl x11-utils mesa-utils imagemagick \diff --git a/tools/lab/wsl/setup.sh b/tools/lab/wsl/setup.shindex 798abecc..47b4da65 100644--- a/tools/lab/wsl/setup.sh+++ b/tools/lab/wsl/setup.sh@@ -45,7 +45,7 @@ apt-get update -qapt-get install -y -q --no-install-recommends \build-essential pkg-config git curl ca-certificates python3 python3-pil \libgtk-3-dev libxkbcommon-dev libwayland-dev libgl1-mesa-dev \- libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev \+ libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev cmake libclang-dev \libgl1-mesa-dri libglx-mesa0 mesa-utils mesa-vulkan-drivers vulkan-tools \xvfb xauth x11-utils x11-apps x11-xserver-utils xdotool wmctrl imagemagick metacity dbus-x11 \adwaita-icon-theme gnome-themes-extra yaru-theme-gtk yaru-theme-icon \