#!/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 user id
#                          re: id of the quoted message, 0 = none
#   APP/data/seq           last message id (never decreases)
#   APP/data/gen           bumped when messages are deleted (clients reload)
#   APP/data/accounts/UID  "namehex salt sha256(salt+password) avatar-version|-"
#   APP/data/names/LNAME   UID (LNAME = hex of the ASCII-lowercased name)
#   APP/data/sessions/TOK  "UID created" - one per logged-in device
#   APP/data/avatars/UID.jpg
#   /tmp/cabinchat/        volatile state: presence, typing, link codes, event token
# 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: an account is a name + password. Logging in (or redeeming a link code
# from another device) gives the browser a random session token (k, 32 hex).
# A user id (UID, 16 hex) is public; tokens are never sent to other users.
#
# API (k = session token)
#   GET  chat?k=K&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-uid <TAB> gen
#                U <TAB> uid <TAB> namehex <TAB> last-seen <TAB> avatar-version|-
#                W <TAB> uid <TAB> to <TAB> ts                 (who is typing)
#                messages with since < id <= lastid that this user may see
#   GET  chat?a=avatar&u=UID                     profile picture (JPEG)
#   GET  chat?a=check&n=NAMEHEX                  "1" if the name is taken, else "0"
#   GET  chat?a=ping                             "@cabinchat VERSION" (installer self-test)
#   POST chat?a=login&n=NAMEHEX[&ok=OLDKEY]      body: password -> "token <TAB> uid <TAB> new"
#        unknown name: creates the account; OLDKEY (a 3.x browser key) keeps its old id
#   POST chat?a=redeem&c=CODE                    -> "token <TAB> uid"   (link a device)
#   POST chat?a=link&k=K                         -> "code <TAB> seconds-valid"
#   POST chat?a=logout&k=K
#   POST chat?a=passwd&k=K                       body: old-password LF new-password
#   POST chat?a=delete&k=K                       body: password (removes account + posts)
#   POST chat?a=avatar&k=K                       body: JPEG
#   POST chat?a=noavatar&k=K
#   POST chat?a=text&k=K&to=*|UID&re=ID          body: UTF-8 text
#   POST chat?a=img&k=K&to=*|UID&re=ID&w=W&h=H&r=RND  body: JPEG
#   POST chat?a=typing&k=K&to=*|UID|-            (- = 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
LINK_TTL=600        # a "link a device" code is valid this long
MAX_TEXT=4000       # bytes per text message
MAX_IMG=400000      # bytes per photo (the client aims for ~100 kB)
MAX_AVATAR=100000   # bytes per profile picture (the client sends ~20 kB)
MAX_NAME=192        # hex digits per name (the client allows 24 characters)
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
GEN=$DATA/gen
ACC=$DATA/accounts
NAMES=$DATA/names
SESS=$DATA/sessions
AVA=$DATA/avatars
RUN=${TMPDIR:-/tmp}/cabinchat
EV=$RUN/ev
LOCKDIR=$RUN/lock
CLOCK=${CABINCHAT_CLOCK-/etc/cabinchat.clock}
NOW=$(date +%s)
NL='
'
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; }
ok()   { hdr "200 OK"; printf '%s\n' "${1:-ok}"; 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 ]; }
tok32() { hex "$1" && [ ${#1} -eq 32 ]; }

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
}
body_len() { # max-bytes -> $cl, fails if missing or too long
	cl=${CONTENT_LENGTH:-0}; num "$cl" || cl=0
	[ "$cl" -gt 0 ] || fail "400 Bad Request" "empty"
	[ "$cl" -le "$1" ] || fail "413 Payload Too Large" "too large"
}

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
}
sha() {
	if command -v sha256sum >/dev/null 2>&1; then sha256sum | cut -c 1-64
	elif command -v shasum >/dev/null 2>&1; then shasum -a 256 | cut -c 1-64
	else openssl dgst -sha256 -r | cut -c 1-64
	fi
}
rnd() { # N -> N random hex digits (N <= 64)
	{ dd if=/dev/urandom bs=32 count=1 2>/dev/null; date; echo "$$"; } | sha | cut -c "1-$1"
}
pwhash() { printf '%s%s' "$1" "$2" | sha; }   # salt password

# hex of a UTF-8 name -> same with ASCII A-Z lowercased (hex 41-5a -> 61-7a)
lower() {
	printf '%s\n' "$1" | awk '{
		s = ""
		for (i = 1; i <= length($0); i += 2) {
			p = substr($0, i, 2)
			if (p >= "41" && p <= "5a") p = (substr(p, 1, 1) == "4" ? "6" : "7") substr(p, 2, 1)
			s = s p
		}
		print s
	}'
}
valid_name() { hex "$1" && [ $((${#1} % 2)) -eq 0 ] && [ ${#1} -le $MAX_NAME ]; }

# UID -> a_name a_salt a_hash a_ava
read_account() {
	a_name=; a_salt=; a_hash=; a_ava=
	[ -f "$ACC/$1" ] && read -r a_name a_salt a_hash a_ava < "$ACC/$1"
	[ -n "$a_hash" ]
}
write_account() { # UID name salt hash avatar
	printf '%s %s %s %s\n' "$2" "$3" "$4" "${5:--}" > "$ACC/$1.tmp" && mv "$ACC/$1.tmp" "$ACC/$1"
}

new_session() { # UID -> $tok
	tok=$(rnd 32)
	printf '%s %s\n' "$1" "$NOW" > "$SESS/$tok"
}

# k -> $me (user id), $nick (name hex); 401 makes the client show the login
identify() {
	get k; tok=$v
	tok32 "$tok" && [ -f "$SESS/$tok" ] || fail "401 Unauthorized" "login"
	read -r me _ < "$SESS/$tok"
	if ! pubid "$me" || ! read_account "$me"; then
		rm -f "$SESS/$tok"
		fail "401 Unauthorized" "login"
	fi
	nick=$a_name
}

# record that $me is here; wake everybody if that is news
seen_me() {
	f=$RUN/seen/$me; ps=0
	[ -f "$f" ] && read -r ps < "$f"
	num "$ps" || ps=0
	printf '%s\n' "$NOW" > "$f"
	[ "$ps" -ge $((NOW - ONLINE + 20)) ] || bump
}

# 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; }
read_gen() { gen=0; [ -f "$GEN" ] && read -r gen < "$GEN"; num "$gen" || gen=0; }
next_gen() { read_gen; printf '%s\n' $((gen + 1)) > "$GEN.tmp" && mv "$GEN.tmp" "$GEN"; }

needs_prune() {
	[ -s "$LOG" ] || return 1
	first=$(head -n 1 "$LOG" | cut -f 2)
	num "$first" || return 0
	[ "$first" -lt $((NOW - KEEP)) ]
}

# delete the photos listed in DATA/.del (written by the awk filters below)
del_photos() {
	[ -f "$DATA/.del" ] || return 0
	while IFS= read -r f; do
		case $f in .*|*[!0-9a-z.-]*) ;; *.jpg) rm -f "$IMG/$f" ;; esac
	done < "$DATA/.del"
	rm -f "$DATA/.del"
}

# 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"
	del_photos
	# 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"
}

# body = JPEG of at most $1 bytes -> file $2 (or fail)
save_jpeg() {
	body_len "$1"
	read_body > "$2.$$"
	size=$(wc -c < "$2.$$"); size=$((size))
	if [ "$size" -ne "$cl" ]; then rm -f "$2.$$"; fail "400 Bad Request" "incomplete upload"; fi
	if [ "$(head -c 3 "$2.$$")" != "$(printf '\377\330\377')" ]; then
		rm -f "$2.$$"; fail "415 Unsupported Media Type" "JPEG expected"
	fi
	mv "$2.$$" "$2"
}

for d in "$DATA" "$IMG" "$ACC" "$NAMES" "$SESS" "$AVA" "$RUN/seen" "$RUN/typing" "$RUN/links"; do
	[ -d "$d" ] || mkdir -p "$d" || fail "500 Internal Server Error" "cannot create $d"
done
[ -f "$EV" ] || bump
get a; act=$v

# ---------------------------------------------------------------- public GETs
if [ "$REQUEST_METHOD" != POST ]; then
	case $act in
	avatar)
		get u; u=$v
		pubid "$u" && [ -f "$AVA/$u.jpg" ] || fail "404 Not Found" "no picture"
		printf 'Status: 200 OK\r\nContent-Type: image/jpeg\r\nCache-Control: max-age=31536000, immutable\r\n\r\n'
		cat "$AVA/$u.jpg"
		exit 0 ;;
	check)
		get n; valid_name "$v" || fail "400 Bad Request" "bad name"
		[ -f "$NAMES/$(lower "$v")" ] && ok 1 || ok 0 ;;
	ping)
		ok "@cabinchat $(cat "$WEB/VERSION" 2>/dev/null)" ;;
	esac
fi

# ---------------------------------------------------------------- POST
if [ "$REQUEST_METHOD" = POST ]; then
	case $act in
	login)
		get n; name=$v
		valid_name "$name" || fail "400 Bad Request" "bad name"
		body_len 1024
		pw=$(read_body)
		[ -n "$pw" ] || fail "400 Bad Request" "empty password"
		lk=$(lower "$name")
		take_lock
		uid=; [ -f "$NAMES/$lk" ] && read -r uid < "$NAMES/$lk"
		if pubid "$uid" && read_account "$uid"; then
			drop_lock
			if [ "$(pwhash "$a_salt" "$pw")" != "$a_hash" ]; then
				sleep 1      # slows down guessing
				fail "403 Forbidden" "wrong password"
			fi
			new=0
		else
			# new account; a 3.x browser hands in its old key to keep its id (and messages)
			get ok; uid=
			tok32 "$v" && uid=$(hash16 "$v")
			while ! pubid "$uid" || [ -f "$ACC/$uid" ]; do uid=$(rnd 16); done
			salt=$(rnd 16)
			write_account "$uid" "$name" "$salt" "$(pwhash "$salt" "$pw")" -
			printf '%s\n' "$uid" > "$NAMES/$lk"
			drop_lock
			bump
			new=1
		fi
		new_session "$uid"
		ok "$tok	$uid	$new" ;;

	redeem)
		get c; code=$v
		tok32 "$code" && [ -f "$RUN/links/$code" ] || fail "403 Forbidden" "invalid link"
		read -r uid ts < "$RUN/links/$code"
		rm -f "$RUN/links/$code"           # one device per code
		num "$ts" && [ "$ts" -ge $((NOW - LINK_TTL)) ] || fail "403 Forbidden" "link expired"
		pubid "$uid" && read_account "$uid" || fail "403 Forbidden" "account deleted"
		new_session "$uid"
		ok "$tok	$uid" ;;
	esac

	identify
	seen_me
	get to; to=$v

	case $act in
	typing)
		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
		ok ;;

	logout)
		rm -f "$SESS/$tok"
		ok ;;

	link)
		for f in "$RUN"/links/*; do     # forget expired codes
			[ -f "$f" ] || continue
			read -r u ts < "$f"
			num "$ts" && [ "$ts" -ge $((NOW - LINK_TTL)) ] || rm -f "$f"
		done
		code=$(rnd 32)
		printf '%s %s\n' "$me" "$NOW" > "$RUN/links/$code"
		ok "$code	$LINK_TTL" ;;

	passwd)
		body_len 2048
		body=$(read_body)
		old=${body%%"$NL"*}; pw=${body#*"$NL"}
		[ "$old" != "$body" ] && [ -n "$pw" ] || fail "400 Bad Request" "bad request"
		take_lock
		read_account "$me"
		if [ "$(pwhash "$a_salt" "$old")" != "$a_hash" ]; then
			drop_lock; sleep 1; fail "403 Forbidden" "wrong password"
		fi
		salt=$(rnd 16)
		write_account "$me" "$a_name" "$salt" "$(pwhash "$salt" "$pw")" "$a_ava"
		drop_lock
		ok ;;

	delete)
		body_len 1024
		pw=$(read_body)
		[ "$(pwhash "$a_salt" "$pw")" = "$a_hash" ] || { sleep 1; fail "403 Forbidden" "wrong password"; }
		take_lock
		rm -f "$ACC/$me" "$NAMES/$(lower "$nick")" "$AVA/$me.jpg" "$RUN/seen/$me" "$RUN/typing/$me"
		for f in "$SESS"/*; do
			[ -f "$f" ] || continue
			read -r u _ < "$f"
			[ "$u" = "$me" ] && rm -f "$f"
		done
		# everything this user posted goes too
		if [ -s "$LOG" ]; then
			awk -F '\t' -v me="$me" -v del="$DATA/.del" '
				$4 == me { if ($3 == "i") { split($8, a, " "); print a[1] > del }; next }
				{ print }
			' "$LOG" > "$LOG.tmp" && mv "$LOG.tmp" "$LOG"
			del_photos
		fi
		next_gen
		drop_lock
		bump
		ok ;;

	avatar|noavatar)
		ver=-
		if [ "$act" = avatar ]; then
			save_jpeg $MAX_AVATAR "$AVA/$me.jpg"
			ver=$(rnd 8)
		else
			rm -f "$AVA/$me.jpg"
		fi
		take_lock
		read_account "$me" && write_account "$me" "$a_name" "$a_salt" "$a_hash" "$ver"
		drop_lock
		bump
		ok "$ver" ;;

	text|img)
		[ "$to" = '*' ] || pubid "$to" || fail "400 Bad Request" "bad recipient"
		get re; re=$v; num "$re" || re=0
		if [ "$act" = text ]; then
			body_len $MAX_TEXT
			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
		else
			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"
			save_jpeg $MAX_IMG "$IMG/.upload-$$"
			take_lock; prune; next_id
			mv "$IMG/.upload-$$" "$IMG/$id-$rnd.jpg"
			append i "$id-$rnd.jpg $w $h"
			drop_lock
		fi
		rm -f "$RUN/typing/$me"
		bump
		touch_clock
		ok "$id" ;;

	*) fail "400 Bad Request" "unknown action" ;;
	esac
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
	[ -f "$ACC/$me" ] && printf '%s\n' "$NOW" > "$RUN/seen/$me"
fi

read_gen
touch_clock
hdr "200 OK"
printf '@%s\t%s\t%s\t%s\t%s\n' "$NOW" "$lastid" "$ev" "$me" "$gen"

for f in "$ACC"/*; do
	[ -f "$f" ] || continue
	u=${f##*/}
	pubid "$u" || continue
	read -r n _ _ av < "$f"
	s=0; [ -f "$RUN/seen/$u" ] && read -r s < "$RUN/seen/$u"
	num "$s" || s=0
	printf 'U\t%s\t%s\t%s\t%s\n' "$u" "$n" "$s" "${av:--}"
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
