Add cabinchat: web chat for OpenWrt travel routers

Web app, uhttpd shell CGI backend, installer, build script and dev
server. README merged with the repository's project description.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal Suter
2026-11-16 11:28:27 +01:00
co-authored by Claude Opus 5.5
parent 65fec81a01
commit 7e8d07e6c1
9 changed files with 3471 additions and 1 deletions
Executable
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""Cabin Chat development server.
Serves www/ like uhttpd does on the router: static files plus CGI scripts
under /cgi-bin/. Python standard library only, so it runs on a notebook
(Linux/macOS) and on Android in Termux (`pkg install python`).
python3 devserver.py # http://localhost:8088, reachable from your LAN
python3 devserver.py -p 9000 # other port
python3 devserver.py --local # only this machine
Chat data is stored in ./data/ and photos in www/img/ (delete both to start
fresh); presence and typing state live in $TMPDIR/cabinchat/. CGI scripts are
run through `sh`, so they work even without the executable bit (e.g. on
Android shared storage).
"""
import argparse
import functools
import os
import shutil
import socket
import subprocess
import sys
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
HERE = os.path.dirname(os.path.abspath(__file__))
SH = shutil.which("sh") or "/bin/sh"
class Handler(SimpleHTTPRequestHandler):
quiet = False
def is_cgi(self):
return self.path.startswith("/cgi-bin/")
def do_GET(self):
if self.is_cgi():
return self.run_cgi()
super().do_GET()
def do_HEAD(self):
if self.is_cgi():
return self.run_cgi()
super().do_HEAD()
def do_POST(self):
if self.is_cgi():
return self.run_cgi()
self.send_error(405, "POST only for /cgi-bin/")
def end_headers(self):
if not self.is_cgi(): # always serve fresh files while developing
self.send_header("Cache-Control", "no-store")
super().end_headers()
def log_message(self, fmt, *args):
if not self.quiet:
super().log_message(fmt, *args)
def run_cgi(self):
path, _, query = self.path.partition("?")
name = path[len("/cgi-bin/"):].split("/")[0]
script = os.path.join(self.directory, "cgi-bin", name)
if not name or name.startswith(".") or not os.path.isfile(script):
return self.send_error(404)
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else b""
env = dict(os.environ)
env.update({
"GATEWAY_INTERFACE": "CGI/1.1",
"SERVER_SOFTWARE": "cabinchat-devserver",
"SERVER_PROTOCOL": self.request_version,
"SERVER_PORT": str(self.server.server_address[1]),
"REQUEST_METHOD": self.command,
"QUERY_STRING": query,
"SCRIPT_NAME": "/cgi-bin/" + name,
"SCRIPT_FILENAME": script,
"REMOTE_ADDR": self.client_address[0],
"CONTENT_LENGTH": str(length) if length else "",
"CONTENT_TYPE": self.headers.get("Content-Type", ""),
"HTTP_HOST": self.headers.get("Host", ""),
"HTTP_USER_AGENT": self.headers.get("User-Agent", ""),
# no /etc clock file while developing
"CABINCHAT_CLOCK": "",
})
try:
p = subprocess.run([SH, script], input=body, capture_output=True,
env=env, cwd=os.path.dirname(script), timeout=60)
except subprocess.TimeoutExpired:
return self.send_error(504, "CGI timeout")
if p.stderr:
sys.stderr.write(p.stderr.decode(errors="replace"))
out = p.stdout
cut = [(out.find(s), len(s)) for s in (b"\r\n\r\n", b"\n\n") if out.find(s) >= 0]
if not cut:
return self.send_error(502, "CGI sent no headers")
pos, seplen = min(cut)
head, payload = out[:pos].decode("latin-1"), out[pos + seplen:]
code, reason, headers = 200, "OK", []
for line in head.splitlines():
if ":" not in line:
continue
k, v = line.split(":", 1)
k, v = k.strip(), v.strip()
if k.lower() == "status":
parts = v.split(" ", 1)
code = int(parts[0])
reason = parts[1] if len(parts) > 1 else ""
else:
headers.append((k, v))
self.send_response(code, reason)
for k, v in headers:
self.send_header(k, v)
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
if self.command != "HEAD":
self.wfile.write(payload)
def lan_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("10.255.255.255", 1))
return s.getsockname()[0]
except OSError:
return None
finally:
s.close()
def main():
ap = argparse.ArgumentParser(description="Cabin Chat development server")
ap.add_argument("-p", "--port", type=int, default=8088)
ap.add_argument("--local", action="store_true", help="listen on 127.0.0.1 only")
ap.add_argument("--root", default=os.path.join(HERE, "www"), help="web root (default: ./www)")
ap.add_argument("-q", "--quiet", action="store_true", help="don't log requests")
a = ap.parse_args()
root = os.path.abspath(a.root)
if not os.path.isfile(os.path.join(root, "cgi-bin", "chat")):
sys.exit(f"no cgi-bin/chat found in {root}")
Handler.quiet = a.quiet
bind = "127.0.0.1" if a.local else "0.0.0.0"
srv = ThreadingHTTPServer((bind, a.port), functools.partial(Handler, directory=root))
print(f"Cabin Chat dev server - serving {root}")
print(f" http://localhost:{a.port}/")
ip = None if a.local else lan_ip()
if ip:
print(f" http://{ip}:{a.port}/ (other devices on your network)")
print("Ctrl+C to stop")
try:
srv.serve_forever()
except KeyboardInterrupt:
print()
if __name__ == "__main__":
main()