cirosantillibinwayback-machine-replay-server
bin/wayback-machine-replay-server
#!/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'''<base\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))''', text, re.I)
if match: self.base = urljoin(base, unescape(next(x for x in match.groups() if x is not None)))
self.output, self.in_style, self.injected = [], False, False
self.feed(text)
self.close()
def inject(self):
if not self.injected:
config = lambda v: json.dumps(v).replace('<', '\\u003c')
self.output.append('<script>' + RUNTIME.replace('__STAMP__', config(self.stamp)).replace('__URL__', config(self.base)) + '</script>')
self.injected = True
def handle_starttag(self, tag, attrs):
lower = dict(attrs)
if tag == 'meta' and lower.get('http-equiv', '').lower() in ('content-security-policy', 'refresh'):
return
if tag == 'head':
self.output.append(self.get_starttag_text()); self.inject(); return
if tag in ('script', 'body', 'frameset') and not self.injected: self.inject()
def attr(match):
name = match[1].lower()
value = unescape(next(x for x in match.groups()[2:] if x is not None))
if name in ('integrity', 'crossorigin', 'nonce'): return ''
if name == 'style': value = rewrite_css(value, self.base, self.stamp)
elif name in ('srcset', 'imagesrcset'): value = rewrite_srcset(value, self.base, self.stamp)
elif name in URL_ATTRS: value = replay_url(value, self.stamp, self.base)
elif name == 'archive': value = ','.join(replay_url(v.strip(), self.stamp, urljoin(self.base, lower.get('codebase', ''))) for v in value.split(','))
elif tag == 'param' and name == 'value' and lower.get('name', '').lower() in ('movie', 'src', 'url'): value = replay_url(value, self.stamp, self.base)
elif tag == 'meta' and name == 'charset': value = 'utf-8'
elif tag == 'meta' and name == 'content' and lower.get('http-equiv', '').lower() == 'content-type': value = 'text/html; charset=utf-8'
return match[1] + '="' + escape(value, quote=True) + '"'
self.output.append(ATTR.sub(attr, self.get_starttag_text()))
if tag == 'style': self.in_style = True
def handle_startendtag(self, tag, attrs): self.handle_starttag(tag, attrs)
def handle_endtag(self, tag):
self.output.append('</' + tag + '>')
if tag == 'style': self.in_style = False
def handle_data(self, data): self.output.append(rewrite_css(data, self.base, self.stamp) if self.in_style else data)
def handle_entityref(self, name): self.output.append('&' + name + ';')
def handle_charref(self, name): self.output.append('&#' + name + ';')
def handle_decl(self, decl): self.output.append('<!' + decl + '>')
def handle_comment(self, data): self.output.append('<!--' + data + '-->')
def handle_pi(self, data): self.output.append('<?' + data + '>')
def unknown_decl(self, data): self.output.append('<![' + data + ']>')
def decode(data, mime):
if data.startswith(b'\xef\xbb\xbf'): return data.decode('utf-8-sig', errors='replace')
match = re.search(r'charset\s*=\s*["\']?([\w-]+)', mime, re.I)
if not match: match = re.search(r'charset\s*=\s*["\']?([\w-]+)', data[:4096].decode('ascii', errors='ignore'), re.I)
if match:
try: return data.decode(match[1], errors='replace')
except LookupError: pass
try: return data.decode('utf-8')
except UnicodeDecodeError: return data.decode('windows-1252', errors='replace')
def page(title, body):
return ('<!doctype html><meta charset="utf-8"><title>' + escape(title) + '</title><style>' + STYLE + '</style><h1>' + escape(title) + '</h1>' + body).encode()
class Handler(BaseHTTPRequestHandler):
def send(self, status, data, mime='text/html; charset=utf-8', extra=None):
self.send_response(status)
self.send_header('Content-Type', mime)
self.send_header('Content-Length', str(len(data)))
self.send_header('Cache-Control', 'no-store')
self.send_header('Content-Security-Policy', "default-src 'self' data: blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src 'self'; object-src 'none'; form-action 'none'; frame-src 'self';")
self.send_header('Referrer-Policy', 'same-origin')
for name, value in (extra or {}).items(): self.send_header(name, value)
self.end_headers()
if self.command != 'HEAD':
try: self.wfile.write(data)
except (BrokenPipeError, ConnectionResetError): pass
def do_HEAD(self): self.do_GET()
def do_GET(self):
try: self.route()
except (ValueError, OSError) as error:
self.send(400, page('Cannot replay this resource', '<p>' + escape(str(error)) + '</p>'))
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 = '<form><input name="q" placeholder="Filter domains" value="' + escape(query, quote=True) + '"><button>Filter</button></form><p><a href="/refresh">Refresh files from disk</a></p><table><tr><th>Domain</th><th>Recursive HTML files</th><th>All files</th><th>Replay</th></tr>'
with archive.lock:
hosts = sorted(archive.by_host.items())
for host, records in hosts:
if query not in host: continue
count = sum(r.is_html for r in records)
href = '/domain/' + quote(host, safe='')
home = archive.lookup('http://' + host + '/', self.server.stamp)
replay = '<a href="' + replay_url(home.url, home.stamp, home.url) + '">Open homepage</a>' if home else ''
body += '<tr><td><a href="' + href + '">' + escape(host) + '/</a></td><td>' + (str(count) + ' HTML' if count else 'no HTML') + '</td><td>' + str(len(records)) + '</td><td>' + replay + '</td></tr>'
body += '</table><p>Counts include all nested directories and capture versions. Source files are read-only.</p>'
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 = '<p><a href="/">All domains</a> | <a href="?all=1">All files</a> | <a href="?">HTML only</a></p><table><tr><th>Original path</th><th>Capture (UTC)</th><th>Type</th></tr>'
for r in sorted(records, key=lambda r: (urlsplit(r.url).path, r.stamp)):
if not show_all and not r.is_html: continue
path = urlsplit(r.url).path + ('?' + urlsplit(r.url).query if urlsplit(r.url).query else '')
body += '<tr><td><a href="' + escape(replay_url(r.url, r.stamp, r.url), quote=True) + '">' + escape(path) + '</a></td><td>' + escape(r.stamp) + '</td><td>' + escape(r.mime) + '</td></tr>'
body += '</table><p>' + str(sum(r.is_html for r in records)) + ' HTML files recursively; ' + str(len(records)) + ' files total.</p>'
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', '<p><a href="/">Browse archives</a></p>'))
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', '<p><code>' + escape(url) + '</code></p><p>No matching local capture. No network request was made.</p><p><a href="/">Browse archives</a></p>'))
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()