#!/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
