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:
co-authored by
Claude Opus 5.5
parent
65fec81a01
commit
7e8d07e6c1
@@ -0,0 +1,3 @@
|
||||
data/
|
||||
www/img/
|
||||
dist/.payload
|
||||
@@ -1,3 +1,47 @@
|
||||
# cabinchat
|
||||
|
||||
a light weight, web based chat application for a small group of people to communicate with each other (i.e. aboard a commercial flight) to be hosted on OpenWrt devices such as the Gl.iNet Beryl 7.
|
||||
A lightweight, web-based chat application for a small group of people to
|
||||
communicate with each other (e.g. aboard a commercial flight), hosted on
|
||||
OpenWrt devices such as the GL.iNet Beryl 7.
|
||||
|
||||
Browser-based group chat for a GL.iNet travel router (or any OpenWrt box).
|
||||
Nothing to install on the phones, no extra packages on the router: it runs on
|
||||
the built-in `uhttpd` web server with one small shell CGI script.
|
||||
|
||||
## Install on the router
|
||||
|
||||
scp -O dist/install-cabinchat.sh root@192.168.8.1:/tmp/
|
||||
ssh root@192.168.8.1 sh /tmp/install-cabinchat.sh
|
||||
|
||||
Running a newer installer over an existing install upgrades it and keeps
|
||||
messages, photos and the port. Other commands: `-p <port>`, `wipe`, `uninstall`.
|
||||
|
||||
Open `http://192.168.8.1:8088` (or `http://chat.lan:8088`) on the router's WiFi.
|
||||
|
||||
## Project layout
|
||||
|
||||
www/index.html the whole web app (HTML/CSS/JS, no external files)
|
||||
www/cgi-bin/chat backend (POSIX sh + busybox); the API is described at its top
|
||||
www/VERSION version string, bump it for a new release
|
||||
data/, www/img/ chat data while developing (created on first use)
|
||||
installer.sh.in installer template
|
||||
build.sh bundles www/ into dist/install-cabinchat.sh
|
||||
devserver.py dev server that behaves like uhttpd (stdlib Python)
|
||||
|
||||
## Develop on a notebook or in Termux
|
||||
|
||||
python3 devserver.py # Termux: pkg install python
|
||||
# open http://localhost:8088, or the LAN URL it prints from a phone
|
||||
|
||||
Edit `www/`, reload the browser. Chat data lives in `data/` and photos in
|
||||
`www/img/` (delete both to start over). Open the page in two browsers (or a
|
||||
normal and a private window) to test private chats and typing notices. When you're happy: bump `www/VERSION`, run `sh build.sh`, copy
|
||||
`dist/install-cabinchat.sh` to the router.
|
||||
|
||||
## Storage
|
||||
|
||||
On the router's flash: `/www-chat/data/messages` (one line per message) and
|
||||
`seq`, outside the web root; photos in `/www-chat/htdocs/img/` with random file
|
||||
names. Messages older than 24 h are dropped on the fly. Photos are refused once
|
||||
they pass 50 MB. Presence, typing notices and the long-poll event token live in
|
||||
RAM under `/tmp/cabinchat/`. Limits are at the top of `www/cgi-bin/chat`.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/bin/sh
|
||||
# Bundle www/ into one self-contained installer: dist/install-cabinchat.sh
|
||||
# Works on Linux, macOS and Termux. Usage: sh build.sh
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
VERSION=$(tr -d ' \r\n' < www/VERSION)
|
||||
OUT=dist/install-cabinchat.sh
|
||||
DELIM=__CABINCHAT_EOF__
|
||||
PAYLOAD=dist/.payload
|
||||
|
||||
mkdir -p dist
|
||||
(cd www && find . -type f ! -path './img/*' ! -name '.*' | sort) | while IFS= read -r f; do
|
||||
f=${f#./}
|
||||
if grep -q "^$DELIM\$" "www/$f"; then
|
||||
echo "build: $f contains the line $DELIM - cannot embed it" >&2
|
||||
exit 1
|
||||
fi
|
||||
dir=$(dirname "$f")
|
||||
[ "$dir" = . ] || echo " mkdir -p \"\$STAGE/$dir\""
|
||||
echo " cat > \"\$STAGE/$f\" <<'$DELIM'"
|
||||
cat "www/$f"
|
||||
[ -z "$(tail -c 1 "www/$f")" ] || echo
|
||||
echo "$DELIM"
|
||||
done > "$PAYLOAD"
|
||||
|
||||
awk -v v="$VERSION" -v p="$PAYLOAD" '
|
||||
$0 == "@@PAYLOAD@@" { while ((getline l < p) > 0) print l; next }
|
||||
{ gsub(/@@VERSION@@/, v); print }
|
||||
' installer.sh.in > "$OUT"
|
||||
rm -f "$PAYLOAD"
|
||||
chmod 755 "$OUT"
|
||||
sh -n "$OUT"
|
||||
|
||||
echo "built $OUT (Cabin Chat $VERSION, $(wc -c < "$OUT" | tr -d ' ') bytes)"
|
||||
Executable
+164
@@ -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()
|
||||
+1615
File diff suppressed because it is too large
Load Diff
+206
@@ -0,0 +1,206 @@
|
||||
#!/bin/sh
|
||||
# Cabin Chat @@VERSION@@ - self-contained installer for OpenWrt / GL.iNet routers.
|
||||
# Uses only what the firmware already ships (uhttpd, busybox, uci).
|
||||
#
|
||||
# sh install-cabinchat.sh install, or upgrade an existing install
|
||||
# (keeps messages, photos and the port)
|
||||
# sh install-cabinchat.sh -p 8090 install/upgrade on a specific port
|
||||
# sh install-cabinchat.sh wipe delete all messages and photos
|
||||
# sh install-cabinchat.sh uninstall remove Cabin Chat completely
|
||||
#
|
||||
# Generated by build.sh - edit www/ and installer.sh.in instead of this file.
|
||||
|
||||
VERSION="@@VERSION@@"
|
||||
APP=/www-chat
|
||||
WEB=$APP/htdocs
|
||||
DATA=$APP/data
|
||||
RUN=/tmp/cabinchat
|
||||
CLOCK=/etc/cabinchat.clock
|
||||
DNSNAME=chat.lan
|
||||
DEFAULT_PORT=8088
|
||||
STAGE=/tmp/cabinchat-stage.$$
|
||||
|
||||
info() { echo ">> $*"; }
|
||||
warn() { echo "WARNING: $*" >&2; }
|
||||
die() { echo "ERROR: $*" >&2; rm -rf "$STAGE"; exit 1; }
|
||||
usage() { sed -n '4,9p' "$0" | sed 's/^# \{0,1\}//'; }
|
||||
|
||||
listening() { netstat -tln 2>/dev/null | grep -qE "[:.]$1[[:space:]]"; }
|
||||
|
||||
configured_port() {
|
||||
uci -q get uhttpd.chat.listen_http | tr ' ' '\n' | sed -n 's/.*:\([0-9][0-9]*\)$/\1/p' | head -n 1
|
||||
}
|
||||
|
||||
remove_config() {
|
||||
if uci -q get uhttpd.chat >/dev/null; then
|
||||
uci delete uhttpd.chat
|
||||
uci commit uhttpd
|
||||
fi
|
||||
for a in $(uci -q get dhcp.@dnsmasq[0].address); do
|
||||
case $a in "/$DNSNAME/"*) uci del_list dhcp.@dnsmasq[0].address="$a" ;; esac
|
||||
done
|
||||
uci commit dhcp
|
||||
[ -f /etc/sysupgrade.conf ] && sed -i "\#^$APP/\$#d" /etc/sysupgrade.conf
|
||||
}
|
||||
|
||||
extract_payload() {
|
||||
rm -rf "$STAGE"
|
||||
mkdir -p "$STAGE" || die "cannot create $STAGE"
|
||||
@@PAYLOAD@@
|
||||
[ -f "$STAGE/index.html" ] && [ -f "$STAGE/cgi-bin/chat" ] && [ -f "$STAGE/VERSION" ] \
|
||||
|| die "installer payload is incomplete"
|
||||
}
|
||||
|
||||
# version 2 lines (6 fields) -> version 3 (8 fields: + recipient "*" and no quote)
|
||||
migrate_messages() {
|
||||
[ -s "$DATA/messages" ] || return 0
|
||||
awk -F '\t' 'BEGIN { OFS = "\t" }
|
||||
NF == 6 { print $1, $2, $3, $4, "*", 0, $5, $6; next }
|
||||
NF == 8 { print }' "$DATA/messages" > "$DATA/messages.new" &&
|
||||
mv "$DATA/messages.new" "$DATA/messages"
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ install
|
||||
do_install() {
|
||||
[ -x /usr/sbin/uhttpd ] || die "uhttpd is not installed.
|
||||
With internet access run: opkg update && opkg install uhttpd
|
||||
then run this installer again."
|
||||
|
||||
LANIP=$(uci -q get network.lan.ipaddr | cut -d/ -f1)
|
||||
[ -n "$LANIP" ] || die "could not read the LAN IP (network.lan.ipaddr)"
|
||||
|
||||
OLDVER=
|
||||
if [ -f "$APP/VERSION" ]; then
|
||||
OLDVER=$(cat "$APP/VERSION")
|
||||
elif [ -e "$APP/index.html" ] || uci -q get uhttpd.chat >/dev/null; then
|
||||
OLDVER="1.x"
|
||||
fi
|
||||
OLDPORT=$(configured_port)
|
||||
[ -n "$PORT" ] || PORT=${OLDPORT:-$DEFAULT_PORT}
|
||||
case $PORT in ''|*[!0-9]*) die "invalid port: $PORT" ;; esac
|
||||
if [ "$PORT" != "$OLDPORT" ] && listening "$PORT"; then
|
||||
die "port $PORT is already in use - choose another one with -p <port>"
|
||||
fi
|
||||
|
||||
if [ -n "$OLDVER" ]; then
|
||||
info "upgrading Cabin Chat $OLDVER -> $VERSION"
|
||||
else
|
||||
info "installing Cabin Chat $VERSION"
|
||||
fi
|
||||
|
||||
# unpack first: if anything is wrong with this file, nothing has been touched yet
|
||||
extract_payload
|
||||
|
||||
if [ -n "$OLDVER" ]; then
|
||||
info "removing the previous version (messages and photos are kept)"
|
||||
fi
|
||||
remove_config
|
||||
mkdir -p "$APP" || die "cannot create $APP"
|
||||
mkdir -p "$DATA"
|
||||
# keep the photos aside (version 2 kept them in data/img, version 3 in htdocs/img)
|
||||
KEEPIMG=$APP/.img-keep
|
||||
mkdir -p "$KEEPIMG"
|
||||
for d in "$WEB/img" "$DATA/img"; do
|
||||
[ -d "$d" ] && mv "$d"/* "$KEEPIMG"/ 2>/dev/null
|
||||
rm -rf "$d"
|
||||
done
|
||||
for f in "$APP"/* "$APP"/.[!.]*; do
|
||||
[ -e "$f" ] || continue
|
||||
case $f in "$DATA"|"$KEEPIMG") continue ;; esac
|
||||
rm -rf "$f"
|
||||
done
|
||||
rm -rf /tmp/chat.log /tmp/chat.lock /tmp/cabinchat.lock # leftovers from versions 1 and 2
|
||||
migrate_messages
|
||||
|
||||
info "installing files to $WEB"
|
||||
mkdir -p "$WEB"
|
||||
cp -R "$STAGE"/* "$WEB"/ || die "copying files failed"
|
||||
rm -rf "$STAGE"
|
||||
chmod 755 "$WEB"/cgi-bin/*
|
||||
mkdir -p "$WEB/img"
|
||||
mv "$KEEPIMG"/* "$WEB/img"/ 2>/dev/null
|
||||
rm -rf "$KEEPIMG"
|
||||
[ -f "$CLOCK" ] || date +%s > "$CLOCK"
|
||||
|
||||
info "configuring web server on $LANIP:$PORT"
|
||||
uci set uhttpd.chat=uhttpd
|
||||
uci add_list uhttpd.chat.listen_http="$LANIP:$PORT"
|
||||
uci set uhttpd.chat.home="$WEB"
|
||||
uci set uhttpd.chat.cgi_prefix='/cgi-bin'
|
||||
uci set uhttpd.chat.index_page='index.html'
|
||||
uci set uhttpd.chat.no_dirlists='1'
|
||||
# long polling keeps one request per open chat waiting for up to 25 s
|
||||
uci set uhttpd.chat.script_timeout='60'
|
||||
uci set uhttpd.chat.network_timeout='60'
|
||||
uci set uhttpd.chat.max_requests='100'
|
||||
uci set uhttpd.chat.max_connections='100'
|
||||
uci commit uhttpd
|
||||
/etc/init.d/uhttpd enable
|
||||
/etc/init.d/uhttpd restart
|
||||
|
||||
info "adding DNS name $DNSNAME"
|
||||
uci add_list dhcp.@dnsmasq[0].address="/$DNSNAME/$LANIP"
|
||||
uci commit dhcp
|
||||
/etc/init.d/dnsmasq restart >/dev/null 2>&1
|
||||
|
||||
touch /etc/sysupgrade.conf
|
||||
grep -qx "$APP/" /etc/sysupgrade.conf || echo "$APP/" >> /etc/sysupgrade.conf
|
||||
|
||||
sleep 1
|
||||
listening "$PORT" || die "uhttpd is not listening on port $PORT - check: logread | grep uhttpd"
|
||||
if command -v wget >/dev/null; then
|
||||
case $(wget -q -O - "http://$LANIP:$PORT/cgi-bin/chat?k=00000000000000000000000000000000&since=0" 2>/dev/null | head -n 1) in
|
||||
@*) info "self-test passed" ;;
|
||||
*) warn "the chat backend did not answer as expected - check: logread | grep uhttpd" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
n=$(grep -c . "$DATA/messages" 2>/dev/null); n=${n:-0}
|
||||
echo
|
||||
info "Cabin Chat $VERSION is running ($n messages from the last 24 h kept)"
|
||||
echo " http://$LANIP:$PORT"
|
||||
echo " http://$DNSNAME:$PORT"
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ uninstall
|
||||
do_uninstall() {
|
||||
info "removing Cabin Chat"
|
||||
remove_config
|
||||
rm -rf "$APP" "$CLOCK" "$RUN" /tmp/chat.log /tmp/chat.lock /tmp/cabinchat.lock
|
||||
/etc/init.d/uhttpd restart >/dev/null 2>&1
|
||||
/etc/init.d/dnsmasq restart >/dev/null 2>&1
|
||||
info "done"
|
||||
}
|
||||
|
||||
do_wipe() {
|
||||
[ -d "$APP" ] || die "Cabin Chat is not installed"
|
||||
rm -rf "$DATA" "$WEB/img"
|
||||
mkdir -p "$DATA" "$WEB/img"
|
||||
# wake up waiting browsers so they notice the empty chat
|
||||
[ -d "$RUN" ] && echo "wipe.$$" > "$RUN/ev"
|
||||
info "all messages and photos deleted"
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ main
|
||||
CMD=install
|
||||
PORT=
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
-p|--port) [ -n "$2" ] || die "-p needs a port number"; PORT=$2; shift 2 ;;
|
||||
[0-9]*) PORT=$1; shift ;;
|
||||
install|upgrade) CMD=install; shift ;;
|
||||
uninstall|remove) CMD=uninstall; shift ;;
|
||||
wipe) CMD=wipe; shift ;;
|
||||
-h|--help|help) usage; exit 0 ;;
|
||||
*) usage; die "unknown argument: $1" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[ "$(id -u)" = "0" ] || die "please run as root"
|
||||
command -v uci >/dev/null || die "uci not found - is this OpenWrt?"
|
||||
|
||||
case $CMD in
|
||||
install) do_install ;;
|
||||
uninstall) do_uninstall ;;
|
||||
wipe) do_wipe ;;
|
||||
esac
|
||||
@@ -0,0 +1 @@
|
||||
3.0.0
|
||||
Executable
+288
@@ -0,0 +1,288 @@
|
||||
#!/bin/sh
|
||||
# Cabin Chat backend - CGI script for uhttpd (OpenWrt) or devserver.py.
|
||||
# Needs only POSIX sh + busybox tools.
|
||||
#
|
||||
# Layout (APP = /www-chat on the router, the project folder when developing):
|
||||
# APP/htdocs/ web root: index.html, cgi-bin/chat, img/ (photos)
|
||||
# APP/data/messages one message per line, 8 TAB-separated fields:
|
||||
# id ts type from to re nick payload
|
||||
# type t: payload = text
|
||||
# type i: payload = "<file> <width> <height>" (file in img/)
|
||||
# to: "*" = everyone, otherwise the recipient's public id
|
||||
# re: id of the quoted message, 0 = none
|
||||
# APP/data/seq last message id (never decreases)
|
||||
# /tmp/cabinchat/ volatile state: presence, typing, event token, key cache
|
||||
# data/ is outside the web root, so private messages can't be downloaded directly;
|
||||
# photo file names contain a random part, so they can't be guessed.
|
||||
#
|
||||
# Identity: each browser keeps a random secret key (k, 32 hex). The server derives a
|
||||
# public id from it (first 16 hex of its MD5). Only public ids are ever sent out.
|
||||
#
|
||||
# API
|
||||
# GET chat?k=KEY&n=NICKHEX&since=ID&ev=TOKEN&w=1
|
||||
# Long poll: if nothing changed since TOKEN, waits up to HOLD seconds.
|
||||
# Reply: @now <TAB> lastid <TAB> token <TAB> my-public-id
|
||||
# U <TAB> id <TAB> nickhex <TAB> last-seen (users seen in 24 h)
|
||||
# W <TAB> id <TAB> to <TAB> ts (who is typing)
|
||||
# messages with since < id <= lastid that this user may see
|
||||
# POST chat?a=text&k=KEY&n=NICKHEX&to=*|ID&re=ID body: UTF-8 text
|
||||
# POST chat?a=img&k=KEY&n=NICKHEX&to=*|ID&re=ID&w=W&h=H&r=RND body: JPEG
|
||||
# POST chat?a=typing&k=KEY&n=NICKHEX&to=*|ID|- (- = stopped)
|
||||
#
|
||||
# Timestamps come from the router's clock; clients only show relative ages.
|
||||
# To keep that clock sane after a power cut (no RTC, no NTP in the air), the
|
||||
# script touches CLOCK in /etc every few minutes: OpenWrt's sysfixtime sets the
|
||||
# clock at boot to the newest file time found in /etc.
|
||||
|
||||
KEEP=86400 # rolling window: 24 h
|
||||
HOLD=25 # long-poll hold time, seconds
|
||||
ONLINE=70 # seen within this many seconds = online (clients do the math)
|
||||
TYPING=8 # a typing notice lives this long
|
||||
MAX_TEXT=4000 # bytes per text message
|
||||
MAX_IMG=400000 # bytes per photo (the client aims for ~100 kB)
|
||||
MAX_DATA_KB=51200 # refuse new photos once img/ exceeds 50 MB
|
||||
|
||||
case $0 in */*) WEB=${0%/*}; WEB=${WEB%/*} ;; *) WEB=.. ;; esac
|
||||
DATA=${CABINCHAT_DATA:-$WEB/../data}
|
||||
IMG=$WEB/img
|
||||
LOG=$DATA/messages
|
||||
SEQ=$DATA/seq
|
||||
RUN=${TMPDIR:-/tmp}/cabinchat
|
||||
EV=$RUN/ev
|
||||
LOCKDIR=$RUN/lock
|
||||
CLOCK=${CABINCHAT_CLOCK-/etc/cabinchat.clock}
|
||||
NOW=$(date +%s)
|
||||
qs="&$QUERY_STRING&"
|
||||
me=
|
||||
|
||||
# ---------------------------------------------------------------- helpers
|
||||
hdr() { printf 'Status: %s\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\n\r\n' "$1"; }
|
||||
fail() { hdr "$1"; echo "$2"; exit 0; }
|
||||
|
||||
# get NAME -> $v (raw value from the query string, empty if missing)
|
||||
get() { v=${qs#*"&$1="}; if [ "$v" = "$qs" ]; then v=; else v=${v%%&*}; fi; }
|
||||
|
||||
num() { case $1 in ''|*[!0-9]*) return 1 ;; esac; }
|
||||
hex() { case $1 in ''|*[!0-9a-f]*) return 1 ;; esac; }
|
||||
pubid() { hex "$1" && [ ${#1} -eq 16 ]; }
|
||||
|
||||
take_lock() {
|
||||
i=0
|
||||
while ! mkdir "$LOCKDIR" 2>/dev/null; do
|
||||
i=$((i + 1))
|
||||
[ $i -gt 50 ] && { rm -rf "$LOCKDIR"; i=0; } # stale lock
|
||||
sleep 0.1 2>/dev/null || sleep 1
|
||||
done
|
||||
}
|
||||
drop_lock() { rmdir "$LOCKDIR" 2>/dev/null; }
|
||||
|
||||
# something changed: wakes up every waiting long poll
|
||||
bump() { echo "$NOW.$$" > "$EV"; }
|
||||
|
||||
read_body() {
|
||||
if head -c 1 </dev/null >/dev/null 2>&1; then head -c "$cl"; else cat; fi
|
||||
}
|
||||
|
||||
hash16() {
|
||||
if command -v md5sum >/dev/null 2>&1; then printf '%s' "$1" | md5sum | cut -c 1-16
|
||||
elif command -v md5 >/dev/null 2>&1; then printf '%s' "$1" | md5 -q | cut -c 1-16
|
||||
else printf '%016x\n' "$(printf '%s' "$1" | cksum | cut -d ' ' -f 1)"
|
||||
fi
|
||||
}
|
||||
|
||||
# k -> $me (public id); cached in RAM so the hash runs once per browser
|
||||
identify() {
|
||||
get k; key=$v
|
||||
hex "$key" && [ ${#key} -eq 32 ] || fail "400 Bad Request" "bad key"
|
||||
[ -f "$RUN/keys/$key" ] && read -r me < "$RUN/keys/$key"
|
||||
if ! pubid "$me"; then
|
||||
me=$(hash16 "$key")
|
||||
printf '%s\n' "$me" > "$RUN/keys/$key"
|
||||
fi
|
||||
}
|
||||
|
||||
# record that $me is here; wake everybody if that is news
|
||||
seen_me() {
|
||||
get n; nick=$v
|
||||
hex "$nick" && [ ${#nick} -le 200 ] || nick=
|
||||
[ -n "$nick" ] || return 0
|
||||
f=$RUN/users/$me; ps=0; pn=
|
||||
[ -f "$f" ] && read -r ps pn < "$f"
|
||||
num "$ps" || ps=0
|
||||
printf '%s %s\n' "$NOW" "$nick" > "$f"
|
||||
if [ "$ps" -lt $((NOW - ONLINE + 20)) ] || [ "$pn" != "$nick" ]; then bump; fi
|
||||
}
|
||||
|
||||
# a power cut can leave a half-written last line: make sure we start on a new one
|
||||
ensure_nl() { [ -s "$LOG" ] && [ -n "$(tail -c 1 "$LOG")" ] && echo >> "$LOG"; }
|
||||
|
||||
next_id() {
|
||||
id=$(cat "$SEQ" 2>/dev/null)
|
||||
if ! num "$id"; then
|
||||
id=$(tail -n 1 "$LOG" 2>/dev/null | cut -f 1)
|
||||
num "$id" || id=0
|
||||
fi
|
||||
id=$((id + 1))
|
||||
printf '%s\n' "$id" > "$SEQ.tmp" && mv "$SEQ.tmp" "$SEQ"
|
||||
}
|
||||
|
||||
read_seq() { lastid=0; [ -f "$SEQ" ] && read -r lastid < "$SEQ"; num "$lastid" || lastid=0; }
|
||||
|
||||
needs_prune() {
|
||||
[ -s "$LOG" ] || return 1
|
||||
first=$(head -n 1 "$LOG" | cut -f 2)
|
||||
num "$first" || return 0
|
||||
[ "$first" -lt $((NOW - KEEP)) ]
|
||||
}
|
||||
|
||||
# drop expired (and malformed) lines, delete their photos; call with lock held
|
||||
prune() {
|
||||
needs_prune || return 0
|
||||
awk -F '\t' -v c=$((NOW - KEEP)) -v del="$DATA/.del" '
|
||||
NF == 8 && $1 ~ /^[0-9]+$/ && $2 >= c { print; next }
|
||||
$3 == "i" { split($8, a, " "); print a[1] > del }
|
||||
' "$LOG" > "$LOG.tmp" && mv "$LOG.tmp" "$LOG"
|
||||
if [ -f "$DATA/.del" ]; then
|
||||
while IFS= read -r f; do
|
||||
case $f in .*|*[!0-9a-f.-]*) ;; *.jpg) rm -f "$IMG/$f" ;; esac
|
||||
done < "$DATA/.del"
|
||||
rm -f "$DATA/.del"
|
||||
fi
|
||||
# photos whose message line never got written (power cut during upload)
|
||||
find "$IMG" -type f -mtime +2 -exec rm -f {} \; 2>/dev/null
|
||||
}
|
||||
|
||||
touch_clock() {
|
||||
[ -n "$CLOCK" ] || return 0
|
||||
last=$(cat "$CLOCK" 2>/dev/null); num "$last" || last=0
|
||||
[ $((NOW - last)) -ge 300 ] || return 0
|
||||
printf '%s\n' "$NOW" > "$CLOCK.tmp" && mv "$CLOCK.tmp" "$CLOCK"
|
||||
}
|
||||
|
||||
append() { # type payload
|
||||
ensure_nl
|
||||
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$NOW" "$1" "$me" "$to" "$re" "$nick" "$2" >> "$LOG"
|
||||
}
|
||||
|
||||
for d in "$DATA" "$IMG" "$RUN/keys" "$RUN/users" "$RUN/typing"; do
|
||||
[ -d "$d" ] || mkdir -p "$d" || fail "500 Internal Server Error" "cannot create $d"
|
||||
done
|
||||
[ -f "$EV" ] || bump
|
||||
|
||||
# ---------------------------------------------------------------- POST
|
||||
if [ "$REQUEST_METHOD" = POST ]; then
|
||||
identify
|
||||
seen_me
|
||||
[ -n "$nick" ] || fail "400 Bad Request" "bad nick"
|
||||
get a; act=$v
|
||||
get to; to=$v
|
||||
|
||||
if [ "$act" = typing ]; then
|
||||
case $to in
|
||||
-) rm -f "$RUN/typing/$me" ;;
|
||||
'*') printf '* %s\n' "$NOW" > "$RUN/typing/$me" ;;
|
||||
*) pubid "$to" || fail "400 Bad Request" "bad recipient"
|
||||
printf '%s %s\n' "$to" "$NOW" > "$RUN/typing/$me" ;;
|
||||
esac
|
||||
bump
|
||||
hdr "200 OK"; echo ok
|
||||
exit 0
|
||||
fi
|
||||
|
||||
[ "$to" = '*' ] || pubid "$to" || fail "400 Bad Request" "bad recipient"
|
||||
get re; re=$v; num "$re" || re=0
|
||||
cl=${CONTENT_LENGTH:-0}; num "$cl" || cl=0
|
||||
[ "$cl" -gt 0 ] || fail "400 Bad Request" "empty"
|
||||
|
||||
case $act in
|
||||
text)
|
||||
[ "$cl" -le $MAX_TEXT ] || fail "413 Payload Too Large" "message too long"
|
||||
msg=$(read_body | tr '\t\r\n' ' ')
|
||||
case $msg in *[![:space:]]*) ;; *) fail "400 Bad Request" "empty" ;; esac
|
||||
take_lock; prune; next_id; append t "$msg"; drop_lock
|
||||
;;
|
||||
img)
|
||||
[ "$cl" -le $MAX_IMG ] || fail "413 Payload Too Large" "photo too large"
|
||||
used=$(du -sk "$IMG" 2>/dev/null | cut -f 1); num "$used" || used=0
|
||||
[ "$used" -lt $MAX_DATA_KB ] || fail "507 Insufficient Storage" "storage full"
|
||||
get w; w=$v; num "$w" || w=0
|
||||
get h; h=$v; num "$h" || h=0
|
||||
get r; rnd=$v
|
||||
hex "$rnd" && [ ${#rnd} -eq 16 ] || fail "400 Bad Request" "bad r"
|
||||
tmp=$IMG/.upload.$$
|
||||
read_body > "$tmp"
|
||||
size=$(wc -c < "$tmp"); size=$((size))
|
||||
if [ "$size" -ne "$cl" ]; then rm -f "$tmp"; fail "400 Bad Request" "incomplete upload"; fi
|
||||
if [ "$(head -c 3 "$tmp")" != "$(printf '\377\330\377')" ]; then
|
||||
rm -f "$tmp"; fail "415 Unsupported Media Type" "JPEG expected"
|
||||
fi
|
||||
take_lock; prune; next_id
|
||||
mv "$tmp" "$IMG/$id-$rnd.jpg"
|
||||
append i "$id-$rnd.jpg $w $h"
|
||||
drop_lock
|
||||
;;
|
||||
*) fail "400 Bad Request" "unknown action" ;;
|
||||
esac
|
||||
rm -f "$RUN/typing/$me"
|
||||
bump
|
||||
touch_clock
|
||||
hdr "200 OK"; echo "$id"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------- GET (long poll)
|
||||
identify
|
||||
seen_me
|
||||
get since; since=$v; num "$since" || since=0
|
||||
get ev; cev=$v
|
||||
get w; wait=$v
|
||||
if needs_prune; then take_lock; prune; drop_lock; fi
|
||||
read_seq
|
||||
read -r ev < "$EV"
|
||||
|
||||
if [ "$wait" = 1 ] && [ "$cev" = "$ev" ] && [ "$since" -ge "$lastid" ]; then
|
||||
# nothing new: hold the request until something changes or HOLD runs out.
|
||||
# Only builtins (read) and sleep run in this loop.
|
||||
if sleep 0.01 2>/dev/null; then step=0.5; loops=$((HOLD * 2)); else step=1; loops=$HOLD; fi
|
||||
while [ $loops -gt 0 ]; do
|
||||
sleep $step
|
||||
read -r ev < "$EV"
|
||||
[ "$ev" != "$cev" ] && break
|
||||
loops=$((loops - 1))
|
||||
done
|
||||
NOW=$(date +%s)
|
||||
read_seq
|
||||
[ -n "$nick" ] && printf '%s %s\n' "$NOW" "$nick" > "$RUN/users/$me"
|
||||
fi
|
||||
|
||||
touch_clock
|
||||
hdr "200 OK"
|
||||
printf '@%s\t%s\t%s\t%s\n' "$NOW" "$lastid" "$ev" "$me"
|
||||
|
||||
for f in "$RUN"/users/*; do
|
||||
[ -f "$f" ] || continue
|
||||
read -r s n < "$f"
|
||||
num "$s" || continue
|
||||
if [ "$s" -ge $((NOW - KEEP)) ]; then
|
||||
printf 'U\t%s\t%s\t%s\n' "${f##*/}" "$n" "$s"
|
||||
else
|
||||
rm -f "$f"
|
||||
fi
|
||||
done
|
||||
|
||||
for f in "$RUN"/typing/*; do
|
||||
[ -f "$f" ] || continue
|
||||
p=${f##*/}
|
||||
[ "$p" = "$me" ] && continue
|
||||
read -r t ts < "$f"
|
||||
num "$ts" || continue
|
||||
[ "$ts" -ge $((NOW - TYPING)) ] || continue
|
||||
case $t in '*'|"$me") printf 'W\t%s\t%s\t%s\n' "$p" "$t" "$ts" ;; esac
|
||||
done
|
||||
|
||||
if [ "$since" -lt "$lastid" ] && [ -s "$LOG" ]; then
|
||||
awk -F '\t' -v s="$since" -v l="$lastid" -v me="$me" '
|
||||
NF == 8 && $1 ~ /^[0-9]+$/ && $1 + 0 > s + 0 && $1 + 0 <= l + 0 &&
|
||||
($5 == "*" || $5 == me || $4 == me)
|
||||
' "$LOG"
|
||||
fi
|
||||
+1114
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user