Phase 1: scaffold lab.sh, config and preflight checks

Move the archived 2002 site into site-src/ so the lab README can take the
repo root. Add lab.conf, the lab.sh dispatcher, a qemu backend and the
check/init verbs. No VM is created yet.
This commit is contained in:
2026-10-21 18:34:22 -04:00
commit fb06ee5a52
315 changed files with 16171 additions and 0 deletions
+351
View File
@@ -0,0 +1,351 @@
#!/usr/bin/env python3
"""
Mirror the archived Norbourg site from the Wayback Machine.
Downloads HTML pages + every linked asset (images, css, js, ...) through
`web/<ts>id_/` (raw, unmodified capture) and rewrites internal links so the
result is browsable offline.
Usage:
python3 mirror_norbourg.py [--ts TIMESTAMP] [--out DIR] [--delay 0.5]
"""
import argparse
import os
import re
import sys
import time
import urllib.error
import posixpath
import urllib.parse
import urllib.request
from pathlib import Path
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) norbourg-mirror/1.0"
HTML_EXT = {".html", ".htm", ".asp", ".aspx", ".shtml"}
ASSET_HINT = re.compile(
r"\.(gif|jpe?g|png|bmp|ico|css|js|swf|pdf|zip|doc|docx|xls|txt|xml|mp3|wav|avi|mov)$",
re.I,
)
# attributes that may contain a URL, plus CSS url()
ATTR_RE = re.compile(
rb"""(?is)\b(href|src|background|action|data|lowsrc|dynsrc)\s*=\s*
(?: "([^"]*)" | '([^']*)' | ([^\s>"']+) )""",
re.X,
)
CSS_URL_RE = re.compile(rb"""(?is)url\(\s*(['"]?)([^)'"]+)\1\s*\)""")
def log(msg):
print(msg, flush=True)
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""Turn https locations into http ones (the HTTPS edge is flaky) and let
urllib follow everything else."""
def redirect_request(self, req, fp, code, msg, headers, newurl):
if newurl.startswith("https://web.archive.org/"):
newurl = "http://" + newurl[len("https://"):]
return super().redirect_request(req, fp, code, msg, headers, newurl)
OPENER = urllib.request.build_opener(NoRedirect)
def fetch(url, timeout=60, tries=5):
"""Fetch a wayback raw URL. Returns (content_type, body) or None."""
last = None
for attempt in range(tries):
try:
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
with OPENER.open(req, timeout=timeout) as r:
return r.headers.get("Content-Type", ""), r.read()
except urllib.error.HTTPError as e:
last = e
if e.code in (429, 503, 502, 504):
wait = 5 * (attempt + 1)
log(f" HTTP {e.code}: backing off {wait}s")
time.sleep(wait)
continue
if e.code in (404, 403):
return None
time.sleep(2)
except Exception as e: # noqa: BLE001 - network flakiness
last = e
time.sleep(3 * (attempt + 1))
log(f" giving up on {url}: {last}")
return None
def local_for(url, root):
"""Map a site URL to a mirror-relative path (POSIX)."""
p = urllib.parse.urlsplit(url)
path = urllib.parse.unquote(p.path or "/")
if path.endswith("/"):
path += "index.html"
base, ext = os.path.splitext(path)
if ext.lower() in (".asp", ".aspx", ".shtml"):
path = base + ".html"
elif ext.lower() in (".html", ".htm"):
path = base + ".html"
if p.query:
path = path + "__" + re.sub(r"[^A-Za-z0-9._-]+", "_", p.query)
path = path.lstrip("/")
return path or "index.html"
def canon_host(host):
host = host.lower()
return host[4:] if host.startswith("www.") else host
def norm(url):
"""Normalise a site URL: canonical host, drop fragment, default path."""
s = urllib.parse.urlsplit(url)
path = s.path or "/"
q = s.query
return urllib.parse.urlunsplit(("http", canon_host(s.netloc), path, q, ""))
def aliases(key):
"""Equivalent URL spellings of a mirrored page (extension / index forms)."""
s = urllib.parse.urlsplit(key)
path, q = s.path, s.query
out = [key]
def add(p):
u = urllib.parse.urlunsplit((s.scheme, s.netloc, p, q, ""))
if u not in out:
out.append(u)
for ext in (".asp", ".aspx", ".shtml", ".htm"):
if path.endswith(ext):
add(path[: -len(ext)] + ".html")
if path.endswith(".html"):
add(path[: -5] + ".asp")
add(path[: -5] + ".htm")
if path in ("/", "/index.html", "/index.asp", "/default.asp", "/default.html"):
for p in ("/", "/index.html", "/index.asp", "/default.asp"):
add(p)
return out
ABS_LINK_RE = re.compile(
rb"""https?://web\.archive\.org/web/\d+(?:id_)?/((?:https?://|/)[^"'\s>)]+)"""
)
SCRIPT_RE = re.compile(rb"(?is)<script\b.*?</script\s*>|<!--.*?-->|<style\b.*?</style\s*>")
SCRIPT_SPLIT = re.compile(rb"(?is)(<script\b.*?</script\s*>|<!--.*?-->|<style\b.*?</style\s*>)")
def extract_links(body, page_url, base_hosts):
"""Yield absolute URLs referenced by an HTML or CSS document."""
found = []
text = SCRIPT_RE.sub(b" ", body)
for m in ATTR_RE.finditer(text):
raw = m.group(2) or m.group(3) or m.group(4) or b""
found.append(raw.decode("latin-1"))
# meta refresh / inline css url()
for m in CSS_URL_RE.finditer(text):
found.append(m.group(2).decode("latin-1"))
out = []
for raw in found:
raw = raw.strip()
if not raw or raw.startswith(("#", "mailto:", "javascript:", "data:", "tel:")):
continue
if "web.archive.org/web/" in raw: # already-rewritten internal link
continue
absu = urllib.parse.urljoin(page_url, raw)
s = urllib.parse.urlsplit(absu)
if s.scheme not in ("http", "https"):
continue
if canon_host(s.netloc) not in base_hosts:
continue
if "/webstat/" in s.path:
continue
out.append(norm(absu))
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ts", default="20020929201450", help="Wayback timestamp to pin")
ap.add_argument("--out", default="norbourg-2002", help="output directory")
ap.add_argument("--delay", type=float, default=0.4, help="delay between requests")
ap.add_argument("--max-pages", type=int, default=1000)
args = ap.parse_args()
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
shard = f"http://web.archive.org/web/{args.ts}id_/"
hosts = {"norbourg.com"}
queue = ["http://www.norbourg.com/", "http://www.norbourg.com/index.asp"]
seen = set()
saved = {} # normalised site url -> local relative path
pages = 0
# resume support: reuse the URL -> file map from a previous run
mapfile = out / "_index.json"
if mapfile.exists():
try:
import json
saved = json.loads(mapfile.read_text())
log(f"Resuming with {len(saved)} already-mirrored files")
queue.extend(saved.keys())
except Exception: # noqa: BLE001
saved = {}
while queue and pages < args.max_pages:
url = queue.pop(0)
key = norm(url)
if key in seen:
continue
seen.add(key)
log(f"[{pages+1}] {url}")
local = out / saved.get(key, "")
if key in saved and local.is_file() and local.stat().st_size > 0:
ctype, body = "", local.read_bytes()
rel = saved[key]
else:
got = fetch(shard + key)
if not got:
continue
ctype, body = got
if len(body) < 100:
continue
rel = local_for(key, out)
dest = out / rel
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(body)
saved[key] = rel
pages += 1
is_html = ("html" in ctype) or rel.endswith(".html") or key.endswith("/")
is_css = "css" in ctype or rel.endswith(".css")
if is_html or is_css:
for link in extract_links(body, key, hosts):
if link not in seen:
queue.append(link)
time.sleep(args.delay)
log(f"\nDownloaded {len(saved)} files. Rewriting links...")
# ---- fill pass: grab assets that earlier passes left as online links ---
filled = 0
for p in sorted(out.rglob("*")):
if not p.is_file() or p.suffix.lower() not in (".html", ".css"):
continue
for raw in ABS_LINK_RE.findall(p.read_bytes()):
url = raw.decode("latin-1")
if canon_host(urllib.parse.urlsplit(url).netloc) not in hosts:
continue
key = norm(url)
rel = local_for(key, out)
if (out / rel).is_file():
continue
got = fetch(shard + key)
if got and len(got[1]) > 50:
(out / rel).parent.mkdir(parents=True, exist_ok=True)
(out / rel).write_bytes(got[1])
filled += 1
time.sleep(args.delay)
if filled:
log(f"filled {filled} missing asset(s)")
# Lookup table with aliases so /x.asp, /x.html and /x/ all resolve to the
# same mirrored file.
lookup = {}
for k, rel in saved.items():
for alias in aliases(k):
lookup.setdefault(alias, rel)
# also index whatever is already on disk, so a re-run (or an interrupted
# crawl) can still rewrite every page
for p in out.rglob("*"):
if not p.is_file() or p.name in ("_index.json", "MIRROR.txt"):
continue
rel = p.relative_to(out).as_posix()
for alias in aliases("http://norbourg.com/" + rel):
lookup.setdefault(alias, rel)
# ---- rewrite pass -----------------------------------------------------
def rewrite_bytes(body, page_url, page_rel, is_css=False):
def sub(m):
if is_css:
quote, raw = m.group(1), m.group(2)
new = rewrite_url(raw.decode("latin-1"))
return b"url(" + quote + new.encode("latin-1") + quote + b")"
attr = m.group(1)
raw = (m.group(2) or m.group(3) or m.group(4) or b"").decode("latin-1")
quote = b'"' if m.group(2) is not None else b"'" if m.group(3) is not None else b""
new = rewrite_url(raw)
return attr + b"=" + quote + new.encode("latin-1") + quote
def rewrite_url(raw):
raw = raw.strip()
if not raw or raw.startswith(("#", "mailto:", "javascript:", "data:", "tel:")):
return raw
absu = urllib.parse.urljoin(page_url, raw)
# unwrap any earlier Wayback fallback link
if "web.archive.org/web/" in absu:
absu = re.sub(r"^https?://web\.archive\.org/web/\d+(?:id_)?/", "", absu)
s = urllib.parse.urlsplit(absu)
if canon_host(s.netloc) not in hosts:
return raw
key = norm(absu)
for candidate in aliases(key):
if candidate in lookup:
target = "/" + lookup[candidate]
base = "/" + posixpath.dirname(page_rel)
return posixpath.relpath(target, base)
# not archived: send readers to the live Wayback copy
return "https://web.archive.org/web/" + args.ts + "/" + key
if is_css:
return CSS_URL_RE.sub(sub, body)
# leave <script>/<style>/comments untouched (they contain JS expressions,
# not real URLs)
chunks = SCRIPT_SPLIT.split(body)
for i in range(0, len(chunks), 2):
chunks[i] = ATTR_RE.sub(sub, chunks[i])
return b"".join(chunks)
for p in sorted(out.rglob("*")):
if not p.is_file() or p.suffix.lower() not in (".html", ".css"):
continue
rel = p.relative_to(out).as_posix()
body = p.read_bytes()
body = rewrite_bytes(body, "http://norbourg.com/" + rel, rel, is_css=rel.endswith(".css"))
p.write_bytes(body)
# root index for directory listings / convenience
idx = saved.get(norm("http://www.norbourg.com/")) or saved.get(
norm("http://www.norbourg.com/index.asp")
)
if not idx and (out / "index.html").is_file():
idx = "index.html"
log(f"Index page: /{idx}")
import json
(out / "_index.json").write_text(json.dumps(saved, indent=1, sort_keys=True), encoding="utf-8")
(out / "MIRROR.txt").write_text(
"Norbourg.com mirror\n"
f"Wayback timestamp: {args.ts}\n"
f"Files: {len(saved)}\n\n"
"Open index.html directly, or serve the folder:\n"
"python3 -m http.server 8080 -> http://localhost:8080/\n",
encoding="utf-8",
)
log(f"Done -> {out.resolve()}")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(130)