- accounts with name + password (salted sha256), one account on several devices at once, profile menu: change password, profile picture, link another device (QR code + one-time link), logout, delete account - @mentions with picker and highlighting - https by default with the router web admin's certificate; --http, --cert/--key installer options - logo/favicon, app manifest, service worker (installable PWA) - browser notifications via the service worker, no internet needed - devserver: https option, ignore connections reset by the browser Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
182 lines
6.5 KiB
Python
Executable File
182 lines
6.5 KiB
Python
Executable File
#!/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
|
|
python3 devserver.py --cert c.pem --key k.pem # https (to test the app
|
|
# install and notifications from a phone;
|
|
# on localhost they work over http too)
|
|
|
|
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 ssl
|
|
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))
|
|
|
|
try:
|
|
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)
|
|
except (BrokenPipeError, ConnectionResetError):
|
|
# the browser gave up on this request (usually an aborted long poll:
|
|
# tab reopened, phone woke up, page closed) - nothing to do
|
|
self.close_connection = True
|
|
|
|
|
|
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")
|
|
ap.add_argument("--cert", help="TLS certificate (PEM): serve https")
|
|
ap.add_argument("--key", help="TLS private key (PEM), with --cert")
|
|
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))
|
|
scheme = "http"
|
|
if a.cert:
|
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
ctx.load_cert_chain(a.cert, a.key)
|
|
srv.socket = ctx.wrap_socket(srv.socket, server_side=True)
|
|
scheme = "https"
|
|
|
|
print(f"Cabin Chat dev server - serving {root}")
|
|
print(f" {scheme}://localhost:{a.port}/")
|
|
ip = None if a.local else lan_ip()
|
|
if ip:
|
|
print(f" {scheme}://{ip}:{a.port}/ (other devices on your network)")
|
|
print("Ctrl+C to stop")
|
|
try:
|
|
srv.serve_forever()
|
|
except KeyboardInterrupt:
|
|
print()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|