#!/usr/bin/env python3 """serve.py — directory-root HTTP server, multi-interface aware. Serves the directory this script lives in by default. Binds one named address or all of them, and refuses to start on an address the machine does not own, which is the failure that produces a silent 502 behind a reverse proxy. ./serve.py --list-ips # what this box actually has ./serve.py --bind 192.168.1.146 --port 8000 sudo ./serve.py --port 80 ./serve.py --bind :: --port 8000 # dual stack ./serve.py --dir ~/ios27 --port 8000 --auth analyst:hunter2 ./serve.py --port 443 --tls --cert /etc/ssl/txtreader.pem Directory listing, byte ranges, optional basic auth, optional TLS, no caching. Ports under 1024 need root. Remote fetchers only reach 80/443; anything else needs a proxy in front, and the proxy target must match --bind exactly. """ import argparse import base64 import functools import http.server import os import socket import ssl import subprocess import sys import threading import urllib.request TEXT = { ".txt": "text/plain; charset=utf-8", ".tsv": "text/plain; charset=utf-8", ".csv": "text/plain; charset=utf-8", ".md": "text/plain; charset=utf-8", ".log": "text/plain; charset=utf-8", ".json": "text/plain; charset=utf-8", ".asm": "text/plain; charset=utf-8", ".dis": "text/plain; charset=utf-8", ".s": "text/plain; charset=utf-8", ".hex": "text/plain; charset=utf-8", ".h": "text/plain; charset=utf-8", ".c": "text/plain; charset=utf-8", ".swift": "text/plain; charset=utf-8", ".py": "text/plain; charset=utf-8", ".plist": "text/plain; charset=utf-8", ".sh": "text/plain; charset=utf-8", ".pdf": "application/pdf", } def local_addrs(): """Every address this host owns, v4 then v6, interface-qualified.""" out = [] for fam, flag in ((socket.AF_INET, "-4"), (socket.AF_INET6, "-6")): try: res = subprocess.run(["ip", "-o", flag, "addr"], capture_output=True, text=True) except FileNotFoundError: break for line in res.stdout.splitlines(): f = line.split() if len(f) > 3 and f[2] == "inet" or (len(f) > 3 and f[2] == "inet6"): addr = f[3].split("/")[0] if fam == socket.AF_INET6 and "%" in addr: addr = addr.split("%")[0] out.append((f[1], addr)) return out def is_local(addr): if addr in ("0.0.0.0", "::"): return True return any(a == addr for _, a in local_addrs()) def proxy_targets(): """Best-effort: what the local Apache configs point at, if readable.""" hits = [] for d in ("/etc/apache2/sites-enabled", "/etc/apache2/conf-enabled"): try: names = os.listdir(d) except OSError: continue for n in names: try: with open(os.path.join(d, n), errors="replace") as fh: for i, line in enumerate(fh, 1): if "ProxyPass" in line and "://" in line: hits.append((os.path.join(d, n), i, line.strip())) except OSError: pass return hits class Limited: """Reader that stops after n bytes so a Range response cannot overrun.""" def __init__(self, fh, n): self.fh, self.left = fh, n def read(self, amt=-1): if self.left <= 0: return b"" if amt < 0 or amt > self.left: amt = self.left data = self.fh.read(amt) self.left -= len(data) return data def close(self): self.fh.close() class Handler(http.server.SimpleHTTPRequestHandler): server_version = "chollima-serve/1.1" extensions_map = {**http.server.SimpleHTTPRequestHandler.extensions_map, **TEXT} def log_message(self, fmt, *args): line = "%s %s\n" % (self.address_string(), fmt % args) sys.stderr.write(line) try: with self.server.loglock: with open(self.server.logfile, "a") as fh: fh.write(line) except OSError: pass def _authed(self): want = self.server.auth if not want: return True got = self.headers.get("Authorization", "") if not got.startswith("Basic "): return False try: user, _, pw = base64.b64decode(got[6:]).decode().partition(":") except Exception: return False return "%s:%s" % (user, pw) == want def _gate(self): if self._authed(): return True self.send_response(401) self.send_header("WWW-Authenticate", 'Basic realm="dumps"') self.send_header("Content-Length", "0") self.end_headers() return False def end_headers(self): self.send_header("Cache-Control", "no-store") super().end_headers() def do_GET(self): if self._gate(): super().do_GET() def do_HEAD(self): if self._gate(): super().do_HEAD() def send_head(self): path = self.translate_path(self.path) if os.path.isdir(path): return super().send_head() rng = self.headers.get("Range", "") try: fh = open(path, "rb") except OSError: self.send_error(404, "not found") return None size = os.fstat(fh.fileno()).st_size start, end, partial = 0, max(size - 1, 0), False if rng.startswith("bytes=") and "," not in rng: lo, _, hi = rng[6:].partition("-") try: if lo: start = int(lo) if hi: end = int(hi) elif hi: start = max(0, size - int(hi)) partial = True except ValueError: start, end, partial = 0, max(size - 1, 0), False end = min(end, size - 1) if start > end or start >= size: self.send_error(416, "range not satisfiable") fh.close() return None length = end - start + 1 self.send_response(206 if partial else 200) self.send_header("Content-Type", self.guess_type(path)) self.send_header("Content-Length", str(length)) self.send_header("Accept-Ranges", "bytes") if partial: self.send_header("Content-Range", "bytes %d-%d/%d" % (start, end, size)) self.end_headers() if self.command == "HEAD": fh.close() return None fh.seek(start) return Limited(fh, length) class Server(http.server.ThreadingHTTPServer): daemon_threads = True allow_reuse_address = True def self_test(scheme, addr, port, auth): probe = "127.0.0.1" if addr in ("0.0.0.0", "::") else addr if ":" in probe: probe = "[%s]" % probe url = "%s://%s:%d/" % (scheme, probe, port) req = urllib.request.Request(url, method="HEAD") if auth: req.add_header("Authorization", "Basic " + base64.b64encode(auth.encode()).decode()) try: with urllib.request.urlopen(req, timeout=3) as r: return url, r.status except urllib.error.HTTPError as e: return url, e.code except Exception as e: return url, repr(e) def main(): here = os.path.dirname(os.path.abspath(__file__)) p = argparse.ArgumentParser(description="serve a directory over HTTP") p.add_argument("--bind", default="0.0.0.0", help="address to bind") p.add_argument("--port", type=int, default=8000) p.add_argument("--dir", default=here) p.add_argument("--auth", default="", help="user:pass") p.add_argument("--tls", action="store_true") p.add_argument("--cert", default="") p.add_argument("--key", default="") p.add_argument("--list-ips", action="store_true", help="print local addresses and exit") p.add_argument("--no-self-test", action="store_true") a = p.parse_args() if a.list_ips: for iface, addr in local_addrs(): print("%-16s %s" % (iface, addr)) return root = os.path.abspath(os.path.expanduser(a.dir)) if not os.path.isdir(root): sys.exit("not a directory: %s" % root) if not is_local(a.bind): print("bind %s is not on this host. Local addresses:" % a.bind) for iface, addr in local_addrs(): print(" %-16s %s" % (iface, addr)) sys.exit(2) srv = Server((a.bind, a.port), functools.partial(Handler, directory=root)) srv.auth = a.auth srv.logfile = os.path.join(root, "server.log") srv.loglock = threading.Lock() if a.tls: cert = a.cert or os.path.join(root, ".selfsigned.pem") if not os.path.exists(cert): subprocess.run([ "openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", cert, "-out", cert, "-days", "30", "-subj", "/CN=%s" % socket.gethostname(), ], check=True, capture_output=True) ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_cert_chain(cert, a.key or cert) srv.socket = ctx.wrap_socket(srv.socket, server_side=True) scheme = "https" else: scheme = "http" print("root : %s" % root) print("log : %s" % srv.logfile) print("bind : %s:%d (%s)" % (a.bind, a.port, scheme)) if a.port < 1024 and os.geteuid() != 0: print("warn : port %d needs root" % a.port) if a.port not in (80, 443): print("warn : remote fetchers only reach 80/443; proxy this port") for path, line_no, line in proxy_targets(): if str(a.port) in line: tgt = line.split()[1] if len(line.split()) > 1 else "" ok = a.bind in tgt or (a.bind in ("0.0.0.0", "::")) print("%s proxy %s:%d -> %s" % ("ok " if ok else "MISMATCH", path, line_no, tgt)) if not ok: print(" proxy target does not match --bind %s" % a.bind) if not a.no_self_test: url, status = self_test(scheme, a.bind, a.port, a.auth) print("self : %s -> %s" % (url, status)) print("ctrl-c to stop") try: srv.serve_forever() except KeyboardInterrupt: print("\nstopped") if __name__ == "__main__": main()