#!/bin/sh # Cabin Chat 3.0.0 - 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="3.0.0" 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" cat > "$STAGE/VERSION" <<'__CABINCHAT_EOF__' 3.0.0 __CABINCHAT_EOF__ mkdir -p "$STAGE/cgi-bin" cat > "$STAGE/cgi-bin/chat" <<'__CABINCHAT_EOF__' #!/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 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 lastid token my-public-id # U id nickhex last-seen (users seen in 24 h) # W id to 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 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 __CABINCHAT_EOF__ cat > "$STAGE/index.html" <<'__CABINCHAT_EOF__' Cabin Chat
Everyone Connectingโ€ฆ
__CABINCHAT_EOF__ [ -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 " 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