S007: network smoke tests, local test server, selftest cancel_download, @HOME@ in smoke scripts

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-12 10:26:07 -06:00
commit 2263336df9
10 changed files with 522 additions and 5 deletions

View file

@ -71,6 +71,7 @@ Never modify: `~/Documents/Apps/Nacre` (the original Python Nacre, reference onl
| `SMOKE_SIZE=1400x900 tools/smoke.sh tests/smoke/backgrounds.txt` | every new tab background with the pointer, Customize panel dark/light, image + blur, GIF frames; `perf-*-a/b.json` `frames` (median/max draw ms, `drawn` count) per background at Lots/Fast, hidden tab, still, Motion off. Selftest `pointer x y`, `customize`; `@PAGESDIR@` = path of tests/smoke/pages | now (S018) |
| `tools/smoke.sh tests/smoke/settings.txt` (+ `SMOKE_SIZE=1280x1100`) | every settings section and sub-page dark and light, search results (`nacre://settings/?search=…`), narrow width; `settings-write.txt` (hidden, `SMOKE_SIZE=1280x1100`, fresh outdir) taps controls with selftest `tap x y`, then check `home/.config/nacre-servo/Default/settings.json` (expected values in its header) | now (S019) |
| `SMOKE_SIZE=1280x1600 tools/smoke.sh tests/smoke/sliders.txt` | controls hold still (R1-21): Interface size drag (value label while held, applied on release), Contrast live, Style chip pick; `SMOKE_VISIBLE=1 tools/smoke.sh tests/smoke/sliders-visible.txt` the same plus scrolling for the user's window (~772 px). Selftest `press`/`drag`/`release`, `scroll x y dy`; read the PNGs | now (R1-21) |
| `python3 tests/smoke/net/server.py &` + `tools/smoke.sh tests/smoke/net-{privacy,adblock,downloads}.txt` | network pass, offline: secure DNS through a local DoH stub (`*.nacre.test` → 127.0.0.1), HTTPS-only + certificate warning, tracking params, ad blocker with a local list, downloads + download manager stubs; the server's `/log` has requests, DNS names, Range headers, manager calls. `cache-restart.txt` with `SMOKE_HOME=<cache.txt outdir>/home`: disk cache. `net-real.txt` needs internet. `@HOME@` in scripts = the throwaway home | now (S007) |
| `python tools/icons.py` | rebuilds the icon font subset and `src/ui/icons.rs` from `tools/icons.txt` (needs fontTools and Arch's ttf-material-symbols-variable) | now (S015) |
| appimagetool, wine + Inno Setup, VM "Windows 10" | packaging and Windows checks | see the user's global CLAUDE.md "Building" |

View file

@ -19,7 +19,8 @@
//! do <action> a shortcut action by its settings key, e.g. `do new_tab`
//! cmd <name> [arg] back, forward, reload, bookmark, install_app, pip, exitpip, free_memory,
//! update_lists, check_updates, close_tab, select <n>, zoom <step>,
//! find <text>, download <url>, navigate <typed text>, mute, pin
//! find <text>, download <url>, pause_download|resume_download|cancel_download [id] (newest),
//! navigate <typed text>, mute, pin
//! js <script> run JavaScript in the current tab; the result goes to the log
//! assert <js expression> the expression must give true, else `ASSERT FAILED` in the log fails the smoke run
//! expect <pointer> <json> a value of the `status` JSON must equal json (e.g. `expect /tabs/1/pinned true`;
@ -305,6 +306,7 @@ impl App {
let (name, arg) = rest.split_once(char::is_whitespace).map(|(n, a)| (n, a.trim())).unwrap_or((rest, ""));
let tab = self.windows.get(&window).and_then(|w| w.tab()).map(|t| t.id).unwrap_or(0);
let page = self.windows.get(&window).and_then(|w| w.tab()).map(|t| t.url.clone()).unwrap_or_default();
let newest = self.shared.downloads.borrow().items.first().map(|d| d.id).unwrap_or(1);
let command = match name {
"back" => Command::Back,
"forward" => Command::Forward,
@ -321,8 +323,9 @@ impl App {
"zoom" => Command::Zoom(arg.parse().unwrap_or(1)),
"find" => Command::Find { text: arg.to_owned(), forward: true, case: false },
"download" => Command::DownloadUrl { url: arg.to_owned(), page, name: String::new() },
"pause_download" => Command::Download(DownloadOp::Pause(arg.parse().unwrap_or(1))),
"resume_download" => Command::Download(DownloadOp::Resume(arg.parse().unwrap_or(1))),
"pause_download" => Command::Download(DownloadOp::Pause(arg.parse().unwrap_or(newest))),
"resume_download" => Command::Download(DownloadOp::Resume(arg.parse().unwrap_or(newest))),
"cancel_download" => Command::Download(DownloadOp::Cancel(arg.parse().unwrap_or(newest))),
"navigate" => Command::Navigate(arg.to_owned()),
"mute" => Command::MuteTab(tab),
"pin" => Command::PinTab(tab),

View file

@ -0,0 +1,15 @@
# HTTP disk cache across a restart (R1-04, S007): after tests/smoke/cache.txt fetched the stylesheet once, a new run
# on the same profile shows the page with it and the server still counts one fetch. Offline. Keep the same server
# running for both runs:
# python3 tests/smoke/cache/server.py &
# tools/smoke.sh tests/smoke/cache.txt target/smoke/cache-a
# SMOKE_HOME=target/smoke/cache-a/home tools/smoke.sh tests/smoke/cache-restart.txt
wait 3
open http://127.0.0.1:8765/
waitfor 20 document.title === "Cache" && getComputedStyle(document.body).backgroundColor === "rgb(34, 170, 119)"
js fetch("/count").then(r => r.text()).then(t => { window.count = t; })
waitfor 5 window.count !== undefined
js window.count
assert window.count === "1"
status done
quit

View file

@ -0,0 +1,56 @@
# Network pass (S007): the ad blocker on a local page. The shipped seed lists build offline; then only a local list
# (tests/smoke/net/server.py /list.txt, a custom list URL) blocks a script and an image, and hides one element by a
# site rule and one by a generic rule; pausing for the site lets everything through; a list that can't be fetched
# is reported and the engine keeps the rules it has. Offline. Never Tor or proxies. Start the server first:
# python3 tests/smoke/net/server.py & then tools/smoke.sh tests/smoke/net-adblock.txt
wait 3
set /adblock/update_days 0
wait 5
status seed
expect /adblock/ready true
expect /adblock/rules > 10000
set /adblock/lists []
set /adblock/custom ["http://127.0.0.1:8766/list.txt"]
wait 5
status local
expect /adblock/rules 4
open http://127.0.0.1:8766/ads.html
waitfor 20 document.title === "Ads" && window.pixelLoaded !== null
wait 2
shot blocked
assert window.adScript === false && window.pixelLoaded === false
assert getComputedStyle(document.querySelector(".nacre-ad")).display === "none"
assert getComputedStyle(document.getElementById("nacre-generic-ad")).display === "none"
assert getComputedStyle(document.getElementById("content")).display !== "none"
status page
expect /active/blocked > 1
expect /active/hidden_elements > 0
# Paused for this site: nothing is blocked or hidden.
set /adblock/allow ["127.0.0.1"]
open http://127.0.0.1:8766/ads.html
waitfor 20 document.title === "Ads" && window.pixelLoaded !== null
wait 2
shot paused
assert window.adScript === true && window.pixelLoaded === true
assert getComputedStyle(document.querySelector(".nacre-ad")).display !== "none"
status paused
expect /active/blocked 0
set /adblock/allow []
# A list that can't be fetched: the failure is reported, the local list's rules stay.
set /adblock/custom ["http://127.0.0.1:8766/list.txt","http://127.0.0.1:8767/missing.txt"]
wait 5
cmd update_lists
wait 5
status failed
expect /adblock/rules 4
open http://127.0.0.1:8766/ads.html
waitfor 20 document.title === "Ads" && window.pixelLoaded !== null
assert window.adScript === false
wait 1
status reloaded
expect /active/blocked > 1
flyout shield
wait 1
shot shield
status done
quit

View file

@ -0,0 +1,112 @@
# Network pass (S007): downloads. A link by its file type and one by its Content-Disposition header land in the
# "Save to" folder; a slow 4 MiB file pauses and resumes with a Range request; another is cancelled; the external
# download managers get the link (aria2, AB Download Manager and JDownloader stubs in tests/smoke/net/server.py, a
# dummy FDM program, tests/smoke/net/fake-fdm.sh) and Nacre downloads it itself when the manager isn't there.
# Offline. Never Tor or proxies. Start the server first:
# python3 tests/smoke/net/server.py & then tools/smoke.sh tests/smoke/net-downloads.txt
# Afterwards: <outdir>/home/saved/ has file.zip, report.txt, their (1) copies, big.bin (4194304 bytes, byte i = i % 251) and no .part;
# <outdir>/home/fdm-args.txt has the FDM link.
wait 3
set /downloads/dir "@HOME@/saved"
set /downloads/ask false
set /downloads/auto_open false
set /downloads/manager "builtin"
open http://127.0.0.1:8766/
waitfor 20 document.title === "Net test http"
# A link whose address says "file": saved, the page stays.
open http://127.0.0.1:8766/file.zip
wait 3
status zip
expect /downloads/0/name "file.zip"
expect /downloads/0/state "Done"
expect /downloads/0/received 22
expect /active/url "http://127.0.0.1:8766/"
# A link whose headers say "attachment": the probe finds it, the name comes from the header.
open http://127.0.0.1:8766/attachment
wait 3
status attachment
expect /downloads/0/name "report.txt"
expect /downloads/0/state "Done"
# The same from links on a page.
open http://127.0.0.1:8766/
waitfor 20 document.title === "Net test http"
locate #zip
wait 0.5
click @
wait 3
expect /downloads/0/name "file (1).zip"
expect /downloads/0/state "Done"
locate #attachment
wait 0.5
click @
wait 3
status links
expect /downloads/0/name "report (1).txt"
expect /downloads/0/state "Done"
expect /active/url "http://127.0.0.1:8766/"
# Pause and resume: the rest comes with a Range request.
cmd download http://127.0.0.1:8766/big.bin
wait 2
cmd pause_download
wait 1
status paused
expect /downloads/0/state "Paused"
expect /downloads/0/received > 0
wait 1
cmd resume_download
wait 9
status resumed
expect /downloads/0/state "Done"
expect /downloads/0/received 4194304
flyout downloads
wait 1
shot downloads
flyout none
# Cancel: the part file goes, the item says cancelled.
cmd download http://127.0.0.1:8766/big.bin
wait 2
cmd cancel_download
wait 1
status cancelled
expect /downloads/0/state "Cancelled"
# External download managers: each gets the link; the list shows it as handed off.
set /downloads/managers ["aria2","abdm","jdownloader","fdm"]
set /downloads/aria2_port 8766
set /downloads/abdm_port 8766
set /downloads/jd_port 8766
set /downloads/fdm_path "@PAGESDIR@/../net/fake-fdm.sh"
set /downloads/manager "aria2"
cmd download http://127.0.0.1:8766/file.zip?to=aria2
wait 2
set /downloads/manager "abdm"
cmd download http://127.0.0.1:8766/file.zip?to=abdm
wait 2
set /downloads/manager "jdownloader"
cmd download http://127.0.0.1:8766/file.zip?to=jdownloader
wait 2
set /downloads/manager "fdm"
cmd download http://127.0.0.1:8766/file.zip?to=fdm
wait 2
status handed
expect /downloads/0/state "HandedOff"
expect /downloads/1/state "HandedOff"
expect /downloads/2/state "HandedOff"
expect /downloads/3/state "HandedOff"
open http://127.0.0.1:8766/
waitfor 20 document.title === "Net test http"
js fetch("http://127.0.0.1:8766/log").then(r => r.json()).then(l => { window.netlog = l; })
waitfor 5 window.netlog !== undefined
js JSON.stringify(window.netlog.dlm) + " ranges " + JSON.stringify(window.netlog.ranges)
assert window.netlog.ranges.length > 0
assert window.netlog.dlm.some(c => c.manager === "aria2" && c.method === "aria2.addUri" && c.params[0][0].endsWith("to=aria2"))
assert window.netlog.dlm.some(c => c.manager === "abdm" && c.body.items[0].link.endsWith("to=abdm"))
assert window.netlog.dlm.some(c => c.manager === "jdownloader" && c.form.urls[0].endsWith("to=jdownloader"))
# The manager isn't running: Nacre downloads it itself.
set /downloads/manager "aria2"
set /downloads/aria2_port 9
cmd download http://127.0.0.1:8766/file.zip?to=fallback
wait 6
status fallback
expect /downloads/0/state "Done"
status done
quit

View file

@ -0,0 +1,61 @@
# Network pass (S007): secure DNS through a local stub, the bridge with the VPN off, HTTPS-only (upgrade, the
# certificate warning's "Open anyway", fallback prompt, local addresses stay http), tracking parameter stripping.
# Offline: every name resolves through tests/smoke/net/server.py (*.nacre.test -> 127.0.0.1, the rest NXDOMAIN).
# Never Tor or proxies. Start the server first:
# python3 tests/smoke/net/server.py & then tools/smoke.sh tests/smoke/net-privacy.txt
wait 3
set /vpn/enabled false
set /privacy/doh_custom "http://127.0.0.1:8766/dns-query"
set /privacy/doh "custom"
set /privacy/strip_params true
set /privacy/https_only false
wait 1
status route
expect /vpn "Off"
expect /route "Route { upstream: Direct, doh: \"http://127.0.0.1:8766/dns-query\" }"
# A name only the stub knows: it loads, so the bridge asked secure DNS.
open http://site.nacre.test:8766/
waitfor 20 document.title === "Net test http"
expect /bridge_bytes > 0
# HTTPS-only: the http address is upgraded; the self-signed certificate shows the warning; "Open anyway" opens it.
set /privacy/https_only true
open http://site.nacre.test:8766/
waitfor 20 document.title === "Connection not secure"
shot badcert
locate #allow
wait 0.5
click @
waitfor 20 document.title === "Net test https"
assert location.href === "https://site.nacre.test:8766/"
shot https
# A site with no secure version: the upgrade fails and the tab asks whether to open it over http.
open http://plain.nacre.test:8767/
wait 8
status fallback
shot fallback
expect /active/prompts 1
# "Open anyway" (the prompt bar's main button) opens it over http, and the site stays http this session.
tap 1156 124
waitfor 20 document.title === "Net test http"
assert location.href === "http://plain.nacre.test:8767/"
open http://plain.nacre.test:8767/echo?again
waitfor 20 document.title === "Echo again"
assert location.protocol === "http:"
# Local addresses are never upgraded.
open http://127.0.0.1:8767/
waitfor 20 document.title === "Net test http"
assert location.protocol === "http:"
# Tracking parameters: removed, the rest kept, and the page is the clean address.
open http://127.0.0.1:8766/echo?utm_source=news&id=3&fbclid=abc&utm_medium=mail
waitfor 20 document.title === "Echo id=3"
assert location.search === "?id=3"
set /privacy/strip_params false
open http://127.0.0.1:8766/echo?id=4&gclid=x
waitfor 20 document.title === "Echo id=4&gclid=x"
# The stub saw the names, so lookups went through secure DNS.
js fetch("http://127.0.0.1:8766/log").then(r => r.json()).then(l => { window.netlog = l; })
waitfor 5 window.netlog !== undefined
js JSON.stringify(window.netlog.dns)
assert window.netlog.dns.includes("site.nacre.test") && window.netlog.dns.includes("plain.nacre.test")
status done
quit

29
tests/smoke/net-real.txt Normal file
View file

@ -0,0 +1,29 @@
# Caching on a real site (R1-04, S007). NEEDS INTERNET. Direct connection only: the VPN stays off, never Tor or a
# proxy. Two Wikipedia articles share their stylesheets, scripts and logo, so the second one and a revisit of the
# first must come mostly from the HTTP cache: compare `bridge_bytes` (bytes through the network bridge) in
# first.json, second.json and revisit.json, and the resource entries the `js` lines log (transferSize 0 = cache).
# Run it twice, the second time with SMOKE_HOME=<first outdir>/home: start.json -> revisit.json is the disk cache.
# tools/smoke.sh tests/smoke/net-real.txt target/smoke/net-real-a
# SMOKE_HOME=target/smoke/net-real-a/home tools/smoke.sh tests/smoke/net-real.txt target/smoke/net-real-b
wait 3
set /vpn/enabled false
expect /vpn "Off"
status start
open https://en.wikipedia.org/wiki/Web_browser
waitload 60
wait 4
status first
js JSON.stringify(performance.getEntriesByType("resource").map(e => [e.name.split("?")[0].slice(-40), e.transferSize, e.decodedBodySize]))
open https://en.wikipedia.org/wiki/Rust_(programming_language)
waitload 60
wait 4
status second
js JSON.stringify(performance.getEntriesByType("resource").map(e => [e.name.split("?")[0].slice(-40), e.transferSize, e.decodedBodySize]))
open https://en.wikipedia.org/wiki/Web_browser
waitload 60
wait 4
status revisit
js JSON.stringify(performance.getEntriesByType("resource").map(e => [e.name.split("?")[0].slice(-40), e.transferSize, e.decodedBodySize]))
shot revisit
status done
quit

3
tests/smoke/net/fake-fdm.sh Executable file
View file

@ -0,0 +1,3 @@
#!/bin/sh
# Stands in for Free Download Manager in tests/smoke/net-downloads.txt: records the link it was handed.
printf '%s\n' "$@" >> "$HOME/fdm-args.txt"

236
tests/smoke/net/server.py Normal file
View file

@ -0,0 +1,236 @@
#!/usr/bin/env python3
"""Local test server for tests/smoke/net-*.txt (S007). Offline: listens on 127.0.0.1 only.
Port 8766 speaks plain HTTP and HTTPS on the same socket (it looks at the first byte), with a throwaway self-signed
certificate for *.nacre.test. Port 8767 speaks plain HTTP only (an HTTPS upgrade to it fails).
/dns-query DNS over HTTPS stub (RFC 8484 GET): *.nacre.test -> 127.0.0.1, every other name NXDOMAIN, so
secure DNS pointed here never reaches a public resolver
/ "Net test" page with links to the downloads below; /echo shows the query string in the title
/ads.html page with a listed script and image and elements the cosmetic rules hide
/ads/* the "ads" (count as hits when they get through)
/list.txt filter list for the ad blocker (a custom list URL)
/big.bin 4 MiB sent slowly (about 7 s), with Range support for pause/resume
/file.zip small file (a download by its URL)
/attachment small file with Content-Disposition: attachment (a download by its headers); /report the same
file at a path that gives no hint
/add, /jsonrpc, /flashgot stubs for AB Download Manager, aria2 and JDownloader 2
/log JSON: every request path, DNS name asked, Range header and download manager call
Runs until killed. Usage: python3 tests/smoke/net/server.py &
"""
import json
import os
import socket
import ssl
import subprocess
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
BIG = 4 * 1024 * 1024
log = {"paths": [], "dns": [], "ranges": [], "dlm": [], "tls": 0}
lock = threading.Lock()
def record(key, value):
with lock:
log[key].append(value)
def make_cert():
folder = tempfile.mkdtemp(prefix="nacre-net-")
cert, key = os.path.join(folder, "cert.pem"), os.path.join(folder, "key.pem")
subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "2", "-subj", "/CN=nacre.test",
"-addext", "subjectAltName=DNS:*.nacre.test,DNS:nacre.test", "-keyout", key, "-out", cert],
check=True, capture_output=True)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert, key)
return context
def dns_answer(query):
"""Answer a wire-format DNS query: A 127.0.0.1 for *.nacre.test, empty for AAAA, NXDOMAIN otherwise."""
pos, labels = 12, []
while query[pos]:
labels.append(query[pos + 1:pos + 1 + query[pos]].decode("ascii", "replace"))
pos += 1 + query[pos]
qtype = int.from_bytes(query[pos + 1:pos + 3], "big")
question = query[12:pos + 5]
name = ".".join(labels).lower()
record("dns", name)
ours = name == "nacre.test" or name.endswith(".nacre.test")
flags = b"\x81\x80" if ours else b"\x81\x83"
answers = b""
if ours and qtype == 1:
answers = b"\xc0\x0c\x00\x01\x00\x01\x00\x00\x01\x2c\x00\x04" + bytes([127, 0, 0, 1])
count = 1 if answers else 0
return query[:2] + flags + b"\x00\x01" + count.to_bytes(2, "big") + b"\x00\x00\x00\x00" + question + answers
ADS_PAGE = b"""<!doctype html><meta charset=utf-8><title>Ads</title>
<style>div { height: 40px; margin: 4px; background: #c33; color: #fff; font: 16px sans-serif; }</style>
<p id=content>Content stays</p>
<div class="nacre-ad">site-specific ad (cosmetic rule for nacre.test)</div>
<div id="nacre-generic-ad">generic ad (generic cosmetic rule)</div>
<img id=pixel src="/ads/pixel.gif" width=10 height=10>
<script>window.adScript = false;</script>
<script src="/ads/banner.js"></script>
<script>
window.pixelLoaded = null;
let img = document.getElementById("pixel");
img.onload = () => { window.pixelLoaded = true; };
img.onerror = () => { window.pixelLoaded = false; };
if (img.complete) { window.pixelLoaded = img.naturalWidth > 0; }
</script>
"""
FILTER_LIST = b"""! Title: Nacre network smoke test list (S007)
! Served by tests/smoke/net/server.py; every rule names something only the test pages use.
/ads/banner.js
/ads/pixel.gif
nacre.test,127.0.0.1##.nacre-ad
###nacre-generic-ad
"""
GIF = bytes.fromhex("47494638396101000100800000ffffff00000021f90401000000002c00000000010001000002024401003b")
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_GET(self):
url = urlsplit(self.path)
path = url.path
record("paths", self.path)
if path == "/dns-query":
import base64
wire = parse_qs(url.query).get("dns", [""])[0]
query = base64.urlsafe_b64decode(wire + "=" * (-len(wire) % 4))
return self.reply(dns_answer(query), "application/dns-message")
if path == "/log":
with lock:
return self.reply(json.dumps(log).encode(), "application/json")
if path == "/":
scheme = "https" if isinstance(self.connection, ssl.SSLSocket) else "http"
links = '<p><a id=zip href="/file.zip?link">zip</a> <a id=attachment href="/attachment?link">attachment</a> <a id=report href="/report">report</a>'
return self.reply(f"<!doctype html><title>Net test {scheme}</title><p>Net test over {scheme}{links}".encode(), "text/html")
if path == "/echo":
return self.reply(f"<!doctype html><title>Echo {url.query}</title><p>{url.query}".encode(), "text/html")
if path == "/ads.html":
return self.reply(ADS_PAGE, "text/html")
if path == "/ads/banner.js":
return self.reply(b"window.adScript = true;", "text/javascript")
if path == "/ads/pixel.gif":
return self.reply(GIF, "image/gif")
if path == "/list.txt":
return self.reply(FILTER_LIST, "text/plain")
if path == "/file.zip":
return self.reply(b"PK\x05\x06" + b"\x00" * 18, "application/zip")
if path in ("/attachment", "/report"):
return self.reply(b"attachment body\n", "application/octet-stream", {"Content-Disposition": 'attachment; filename="report.txt"'})
if path == "/big.bin":
return self.big()
self.reply(b"not found", "text/plain", status=404)
def do_HEAD(self):
url = urlsplit(self.path)
record("paths", "HEAD " + self.path)
if url.path in ("/attachment", "/report"):
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Disposition", 'attachment; filename="report.txt"')
self.send_header("Content-Length", "16")
self.end_headers()
else:
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", "0")
self.end_headers()
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length).decode("utf-8", "replace")
path = urlsplit(self.path).path
record("paths", "POST " + self.path)
if path == "/jsonrpc":
call = json.loads(body)
record("dlm", {"manager": "aria2", "method": call.get("method"), "params": call.get("params")})
result = {"version": "1.37.0"} if call.get("method") == "aria2.getVersion" else "2089b05ecca3d829"
return self.reply(json.dumps({"id": call.get("id"), "jsonrpc": "2.0", "result": result}).encode(), "application/json")
if path == "/add":
record("dlm", {"manager": "abdm", "body": json.loads(body)})
return self.reply(b"OK", "text/plain")
if path in ("/flashgot", "/flash/add"):
record("dlm", {"manager": "jdownloader", "path": path, "form": parse_qs(body)})
return self.reply(b"success\r\n", "text/plain")
self.reply(b"not found", "text/plain", status=404)
def big(self):
start = 0
wanted = self.headers.get("Range")
if wanted:
record("ranges", wanted)
start = int(wanted.split("=")[1].split("-")[0])
self.send_response(206 if start else 200)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Length", str(BIG - start))
if start:
self.send_header("Content-Range", f"bytes {start}-{BIG - 1}/{BIG}")
self.end_headers()
chunk = 64 * 1024
sent = start
try:
while sent < BIG:
# Byte i of the file is i % 251, so a resumed file can be checked end to end.
n = min(chunk, BIG - sent)
self.wfile.write(bytes((sent + i) % 251 for i in range(n)))
sent += n
time.sleep(0.11)
except (BrokenPipeError, ConnectionResetError, ssl.SSLError):
pass
def reply(self, body, kind, headers=None, status=200):
self.send_response(status)
self.send_header("Content-Type", kind)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
for name, value in (headers or {}).items():
self.send_header(name, value)
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
class Sniffing(ThreadingHTTPServer):
"""Plain HTTP and TLS on one port: a TLS connection starts with a handshake record (0x16)."""
daemon_threads = True
tls = None
def finish_request(self, request, client_address):
if self.tls is not None:
request.settimeout(10)
try:
first = request.recv(1, socket.MSG_PEEK)
except OSError:
return
if first == b"\x16":
with lock:
log["tls"] += 1
try:
request = self.tls.wrap_socket(request, server_side=True)
except (ssl.SSLError, OSError):
return # the browser refused the certificate
request.settimeout(None)
super().finish_request(request, client_address)
both = Sniffing(("127.0.0.1", 8766), Handler)
both.tls = make_cert()
plain = Sniffing(("127.0.0.1", 8767), Handler)
threading.Thread(target=plain.serve_forever, daemon=True).start()
both.serve_forever()

View file

@ -23,7 +23,8 @@
# Script commands (src/selftest.rs has the full list): wait <s>, waitload [s], open <url>, newtab <url>,
# page <nacre://...>, shot <name>, status <name>, set <json pointer> <json>, flyout <name>, do <action>,
# cmd <name> [arg], js <script>, assert <js>, click|rclick <x> <y>, pagetype <text>, log <text>, quit. Lines starting with # are notes.
# In the script, @PAGES@ is replaced by the file:// URL of tests/smoke/pages, @PAGESDIR@ by its path.
# In the script, @PAGES@ is replaced by the file:// URL of tests/smoke/pages, @PAGESDIR@ by its path, @HOME@ by the
# throwaway home.
#
# Never uses the user's profile, display, Discord socket or session bus; never sets a proxy.
set -u
@ -48,7 +49,7 @@ home=${SMOKE_HOME:-$out/home}
mkdir -p "$home"
home=$(cd "$home" && pwd)
rm -f "$out"/*.png "$out"/*.json "$out/selftest.log" "$out/nacre.log"
sed -e "s|@PAGES@|file://$root/tests/smoke/pages|g" -e "s|@PAGESDIR@|$root/tests/smoke/pages|g" "$script" >"$out/script.txt"
sed -e "s|@PAGES@|file://$root/tests/smoke/pages|g" -e "s|@PAGESDIR@|$root/tests/smoke/pages|g" -e "s|@HOME@|$home|g" "$script" >"$out/script.txt"
runtime=$(mktemp -d /tmp/nacre-smoke-XXXXXX)
chmod 700 "$runtime"