#!/usr/bin/env python3
"""Replay loose Wayback downloads without altering them or fetching the network.
Usage: wayback-machine-replay-server path/to/cia-2010-websites-dump \
path/to/cia-2010-websites-dump-external
where the the reference data can be found at:
https://github.com/cirosantilli/cia-2010-websites-dump
Supports HOST/14-digit-capture/PATH, external capture indexes and adjacent site-review manifests.
Open the printed URL for clickable domains and recursive HTML counts.
Assets resolve nearest to the selected page date (past wins ties).
The first root wins when multiple roots have the same URL and capture time.
This is static archive replay, not a Java/Flash or backend emulator.
"""
import argparse
from bisect import bisect_left
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from html import escape, unescape
from html.parser import HTMLParser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import mimetypes
from pathlib import Path
import re
import threading
from urllib.parse import parse_qs, quote, unquote, urljoin, urlsplit, urlunsplit
STAMP = re.compile(r'^\d{14}$')
REPLAY = re.compile(r'^/web/(\d{14})/(https?://.*)$')
ATTR = re.compile(r'''([^\s=<>/]+)(\s*=\s*)(?:"([^"]*)"|'([^']*)'|([^\s>]+))''')
URL_ATTRS = {'href', 'src', 'background', 'poster', 'data', 'action', 'formaction', 'codebase', 'longdesc', 'xlink:href'}
HTML_SUFFIXES = {'.html', '.htm', '.shtml', '.xhtml'}
CAPTURE_TYPES = {
'.css': 'text/css', '.gif': 'image/gif', '.htm': 'text/html', '.html': 'text/html',
'.jpeg': 'image/jpeg', '.jpg': 'image/jpeg', '.js': 'application/javascript',
'.mjs': 'application/javascript', '.png': 'image/png', '.svg': 'image/svg+xml',
'.webp': 'image/webp',
}
STYLE = 'body{font:16px system-ui;margin:2em;line-height:1.5}a{color:#145ba8}td,th{text-align:left;padding:.3em 1em .3em 0}small{color:#555}input{padding:.4em;width:24em}code{overflow-wrap:anywhere}'
def seconds(stamp):
return datetime.strptime(stamp, '%Y%m%d%H%M%S').replace(tzinfo=timezone.utc).timestamp()
def original_url(url):
p = urlsplit(url if not url.startswith('//') else 'https:' + url)
if p.hostname == 'web.archive.org':
match = re.match(r'/web/\d{1,14}[a-z_]*/(https?://.*)', p.path + ('?' + p.query if p.query else ''))
if match:
return match[1]
return url
def canonical(url):
p = urlsplit(original_url(url))
if p.scheme not in ('http', 'https') or not p.hostname or p.username or p.password:
return None
try:
host = p.hostname.lower().encode('idna').decode()
if p.port and p.port not in (80, 443): host += ':' + str(p.port)
except (ValueError, UnicodeError):
return None
# Match escaped and unescaped filesystem paths, preserving escaped slashes.
path = '/'.join(quote(unquote(part, errors='replace'), safe="!$&'()*+,;=:@-._~")
for part in (p.path or '/').split('/'))
return host, path, p.query
def replay_url(url, stamp, base):
if not url or url.startswith(('#', 'data:', 'blob:')): return url
url = original_url(unescape(url.strip()))
full = urljoin(base, url)
p = urlsplit(full)
if p.scheme not in ('http', 'https'): return url
if not canonical(full): return '#'
# Quote the embedded URL once so its query stays part of the replay path.
return '/web/' + stamp + '/' + quote(urlunsplit(p._replace(fragment='')), safe=':/') + ('#' + quote(p.fragment) if p.fragment else '')
@dataclass(frozen=True)
class Capture:
url: str
stamp: str
path: Path
mime: str
is_html: bool
def content_type(path, original, metadata=None):
suffix = Path(urlsplit(original).path).suffix.lower()
mime = ''
if metadata:
try:
record = metadata if isinstance(metadata, dict) else json.loads(Path(metadata).read_text())
headers = record.get('headers', {})
mime = record.get('content_type') or next((v for k, v in headers.items() if k.lower() == 'content-type'), '')
except (OSError, ValueError): pass
if suffix in ('.js', '.mjs'): return 'application/javascript'
if suffix == '.css': return 'text/css'
if suffix in HTML_SUFFIXES: return mime if 'html' in mime else 'text/html'
if not mime: mime = mimetypes.guess_type(urlsplit(original).path)[0] or 'application/octet-stream'
if mime == 'application/octet-stream' or suffix in ('', '.php', '.asp', '.aspx', '.jsp'):
try:
with path.open('rb') as f: head = f.read(4096)
if re.search(rb'<(?:!doctype\s+html|html|head|body|frameset)\b', head, re.I): return 'text/html'
except OSError: pass
return mime
def infer_capture(parts):
host, _, *components = parts
name, separator, query = components[-1].partition('%3F')
components[-1] = name
path = '/'.join('' if part == '%00' else part for part in components)
url = f'http://{host}/{path}' + ('?' + query if separator else '')
return url, CAPTURE_TYPES.get(Path(name).suffix.lower())
def manifest_paths(entries):
"""Yield local capture paths for URL-keyed and older path-keyed manifests."""
for key, entry in entries.items():
if not key.startswith(('http://', 'https://')):
yield key, entry
continue
match = re.fullmatch(r'https?://web\.archive\.org/web/(\d{14})id_/(https?://.+)', key)
if not match or not isinstance(entry, dict):
continue
stamp, requested = match.groups()
for row in entry.get('captures', [entry]):
relative = row.get('path')
if not isinstance(relative, str) or Path(relative).parts[1:2] != (stamp,):
continue
yield relative, {**row, 'original_url': row.get('original_url', requested), 'request_url': requested}
class Archive:
def __init__(self, roots):
self.roots = list(dict.fromkeys(p.resolve() for p in roots))
self.lock = threading.RLock()
self.refresh()
def refresh(self):
records = defaultdict(dict)
files = {}
declared_hosts = set()
def add(root, url, stamp, path, metadata=None, alias=None, declared_mime=None):
key = canonical(url)
if not key or not STAMP.fullmatch(stamp): return
try:
seconds(stamp)
path = path.resolve()
if not path.is_file() or not path.is_relative_to(root): return
except (OSError, ValueError): return
if path not in files:
mime = (declared_mime if declared_mime and re.fullmatch(r'[\x20-\x7e]+', declared_mime)
else content_type(path, url, metadata))
files[path] = Capture(url, stamp, path, mime, 'html' in mime)
record = files[path]
records[key].setdefault(stamp, record)
if alias and canonical(alias): records[canonical(alias)].setdefault(stamp, record)
if key[1].endswith('/index.html') and not key[2]:
records[(key[0], key[1][:-10], '')].setdefault(stamp, record)
# Manifests preserve query strings, redirect aliases and response MIME types.
for root in self.roots:
if root.name == 'site-mirrors':
state = root.parent / 'site-review' / 'domains'
for manifest in sorted(state.glob('*.json')):
try: data = json.loads(manifest.read_text())
except (OSError, ValueError): continue
for item in data.get('items', {}).values():
record = item.get('record', {})
if item.get('status') == 'saved' and all(k in record for k in ('url', 'capture', 'path')):
add(root, record['url'], record['capture'], Path(record['path']), record.get('metadata'), item.get('url'))
external = set()
index = next((root / name for name in ('meta.json', 'external-captures.json', 'map.json')
if (root / name).is_file()), root / 'meta.json')
try:
entries = json.loads(index.read_text())
except (OSError, ValueError):
entries = {}
if not isinstance(entries, dict):
entries = {}
for relative, row in sorted(manifest_paths(entries), key=lambda pair: pair[0]):
parts = Path(relative).parts
if len(parts) < 3 or not STAMP.fullmatch(parts[1]):
continue
path = root / relative
if path.resolve() != path or not path.is_relative_to(root):
continue
if index.name == 'meta.json' and isinstance(row, dict):
url, mime = infer_capture(parts)
add(root, row.get('original_url', url), parts[1], path, alias=row.get('request_url'),
declared_mime=row.get('content_type', mime))
elif isinstance(row, str):
add(root, row, parts[1], path)
elif isinstance(row, dict) and row.get('capture') == parts[1] and 'original_url' in row:
add(root, row['original_url'], parts[1], path, alias=row.get('request_url'),
declared_mime=row.get('content_type'))
else:
continue
external.add(path)
for sidecar in sorted(root.glob('*/*/*.external.json')):
if sidecar in external:
continue
try:
row = json.loads(sidecar.read_text())
path = (sidecar.parent / row['file']).resolve()
if path.parent != sidecar.parent.resolve() or row['capture'] != sidecar.parent.name:
continue
add(root, row['original_url'], row['capture'], path, sidecar, row.get('request_url'))
external.add(path)
except (OSError, ValueError, TypeError, KeyError):
continue
for host in sorted(root.iterdir()):
if not host.is_dir() or host.name.startswith('.') or '.' not in host.name: continue
for capture in sorted(host.iterdir()):
if not capture.is_dir() or not STAMP.fullmatch(capture.name): continue
declared_hosts.add(host.name)
for path in capture.rglob('*'):
if not path.is_file() or path.name.endswith(('.new', '.external.json')) or path.name.startswith('.external-'): continue
if path.resolve() in external: continue
rel = path.relative_to(capture).as_posix()
add(root, 'http://' + host.name + '/' + rel, capture.name, path)
by_host = defaultdict(list)
for record in files.values():
host = canonical(record.url)[0]
by_host[host].append(record)
for host in declared_hosts: by_host.setdefault(host, [])
with self.lock:
self.records = {k: sorted(v.values(), key=lambda r: r.stamp) for k, v in records.items()}
self.by_host = dict(by_host)
self.file_count = len(files)
def lookup(self, url, stamp):
key = canonical(url)
if not key: return None
with self.lock:
choices = self.records.get(key)
if not choices:
host = key[0][4:] if key[0].startswith('www.') else 'www.' + key[0]
choices = self.records.get((host, key[1], key[2]))
if not choices: return None
i = bisect_left([r.stamp for r in choices], stamp)
return min(choices[max(0, i-1):i+1], key=lambda r: (abs(seconds(r.stamp)-seconds(stamp)), r.stamp))
def rewrite_css(text, base, stamp):
def replace(match):
value = match[2] if match[1] else match[3]
return 'url("' + replay_url(value.strip(), stamp, base).replace('"', '%22') + '")'
text = re.sub(r'''url\(\s*(?:(["'])(.*?)\1|([^)]*?))\s*\)''', replace, text, flags=re.I|re.S)
return re.sub(r'''(@import\s+)(["'])(.*?)\2''', lambda m: m[1] + m[2] + replay_url(m[3], stamp, base) + m[2], text, flags=re.I)
def rewrite_srcset(value, base, stamp):
# URLs consume non-whitespace characters; trailing commas terminate a
# candidate. Internal commas (notably data URLs) belong to the URL.
candidates = []
pos = 0
while pos < len(value):
while pos < len(value) and (value[pos].isspace() or value[pos] == ','): pos += 1
start = pos
while pos < len(value) and not value[pos].isspace(): pos += 1
token = value[start:pos]
if not token: break
descriptor = ''
if not token.endswith(','):
start = pos
while pos < len(value) and value[pos] != ',': pos += 1
descriptor = value[start:pos].strip()
candidates.append(replay_url(token.rstrip(','), stamp, base) + (' ' + descriptor if descriptor else ''))
return ', '.join(candidates)
# Runtime rewriting covers feed2js document.write and common dynamic image/XHR
# loads. Full JavaScript emulation (location, workers, old plugins) is out of scope.
RUNTIME = r'''
(function(){
const stamp=__STAMP__, original=__URL__, prefix='/web/'+stamp+'/';
function rw(v){
if(typeof v!=='string'||!v||/^(#|data:|blob:|javascript:|mailto:)/i.test(v))return v;
if(v.startsWith('/web/')||v.startsWith(location.origin+'/web/'))return v;
try{v=v.replace(/^(?:https?:)?\/\/web\.archive\.org\/web\/\d+[a-z_]*\//,'');
const u=new URL(v,original);if(!/^https?:$/.test(u.protocol))return v;
const hash=u.hash;u.hash='';return prefix+encodeURIComponent(u.href).replace(/%3A/gi,':').replace(/%2F/gi,'/')+hash;
}catch(e){return v;}
}
function html(s){return String(s).replace(/\b(src|href|background|poster|action)\s*=\s*(["'])(.*?)\2/gi,(m,n,q,v)=>n+'='+q+rw(v)+q);}
for(const n of ['write','writeln']){const f=document[n].bind(document);document[n]=(...a)=>f(...a.map(html));}
const set=Element.prototype.setAttribute;
Element.prototype.setAttribute=function(n,v){if(/^(src|href|background|poster|action)$/i.test(n))v=rw(v);return set.call(this,n,v);};
for(const [cls,key] of [[HTMLImageElement,'src'],[HTMLScriptElement,'src'],[HTMLIFrameElement,'src'],[HTMLLinkElement,'href'],[HTMLAnchorElement,'href']]){
const d=Object.getOwnPropertyDescriptor(cls.prototype,key);if(d&&d.set)Object.defineProperty(cls.prototype,key,{...d,set(v){d.set.call(this,rw(v));}});
}
const open=XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open=function(method,url,...rest){return open.call(this,method,rw(url),...rest);};
if(window.fetch){const f=window.fetch.bind(window);window.fetch=(url,opts)=>f(typeof url==='string'?rw(url):url,opts);}
})();
'''
class Rewriter(HTMLParser):
def __init__(self, text, base, stamp):
super().__init__(convert_charrefs=False)
self.base, self.stamp = base, stamp
# The first base href governs the whole document, including earlier tags.
match = re.search(r'''
' + escape(str(error)) + '
')) def route(self): archive = self.server.archive parsed = urlsplit(self.path) params = parse_qs(parsed.query) if parsed.path == '/': query = params.get('q', [''])[0].lower() body = '| Domain | Recursive HTML files | All files | Replay |
|---|---|---|---|
| ' + escape(host) + '/ | ' + (str(count) + ' HTML' if count else 'no HTML') + ' | ' + str(len(records)) + ' | ' + replay + ' |
Counts include all nested directories and capture versions. Source files are read-only.
' return self.send(200, page('Local Wayback archives', body)) if parsed.path == '/refresh': archive.refresh() return self.send(303, b'', extra={'Location': '/'}) if parsed.path.startswith('/domain/'): host = unquote(parsed.path[len('/domain/'):]) with archive.lock: records = list(archive.by_host.get(host, [])) if not records: return self.send(404, page('No saved files', escape(host))) show_all = params.get('all') == ['1'] body = 'All domains | All files | HTML only
| Original path | Capture (UTC) | Type |
|---|---|---|
| ' + escape(path) + ' | ' + escape(r.stamp) + ' | ' + escape(r.mime) + ' |
' + str(sum(r.is_html for r in records)) + ' HTML files recursively; ' + str(len(records)) + ' files total.
' return self.send(200, page(host, body)) match = REPLAY.match(unquote(parsed.path)) if not match: return self.send(404, page('Not a replay URL', '')) stamp, url = match.groups() if parsed.query: url += '?' + parsed.query seconds(stamp) record = archive.lookup(url, stamp) if not record: self.log_message('MISSING %s at %s', url, stamp) return self.send(404, page('Resource not downloaded', '' + escape(url) + '
No matching local capture. No network request was made.
')) data = record.path.read_bytes() mime = record.mime if record.is_html: data = ''.join(Rewriter(decode(data, mime), record.url, stamp).output).encode() mime = 'text/html; charset=utf-8' elif mime.split(';')[0] == 'text/css': data = rewrite_css(decode(data, mime), record.url, stamp).encode() mime = 'text/css; charset=utf-8' self.send(200, data, mime, {'X-Archive-Capture': record.stamp}) def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('roots', type=Path, nargs='*', metavar='PATH', help='One or more archive roots in precedence order. Defaults to the current directory.') parser.add_argument('--port', type=int, default=8001) parser.add_argument('--timestamp', default='20110203000000', help='Preferred homepage date, YYYYMMDDhhmmss') args = parser.parse_args() try: seconds(args.timestamp) if not STAMP.fullmatch(args.timestamp): raise ValueError('Timestamp must have 14 digits') roots = args.roots or [Path.cwd()] for root in roots: if not root.is_dir(): raise ValueError('Not a directory: ' + str(root)) archive = Archive(roots) except (ValueError, OSError) as error: parser.error(str(error)) server = ThreadingHTTPServer(('127.0.0.1', args.port), Handler) server.archive, server.stamp = archive, args.timestamp print(f'Site: http://127.0.0.1:{server.server_port}/', flush=True) print(f'Indexed {archive.file_count:,} files across {len(archive.by_host):,} domains. Sources stay unchanged.', flush=True) print('Use Refresh files from disk to include ongoing downloads. Ctrl-C stops the server.', flush=True) try: server.serve_forever() except KeyboardInterrupt: pass finally: server.server_close() if __name__ == '__main__': main()