#!/bin/sh /etc/rc.common
#
# procd service for meduzavpnd.
#
# The daemon reads a JSON settings file; OpenWrt configures things in UCI. This
# script is the translation, and it runs on every start, so /etc/config/meduzavpn
# is the only place a setting has to be written -- which is what section 6b of
# docs/router-and-tv-clients-design.md means by "UCI is the source of truth".
#
# The generated file lives in /var, which on OpenWrt is tmpfs: it is derived
# data, it must never be edited, and regenerating it costs the flash nothing.
# The daemon's *state* -- the session it signed in with, and which protocol was
# proved to work on this uplink -- goes to /etc/meduzavpn instead, because /var
# is gone after a reboot and a memory that does not survive a power cut is the
# one case it exists for.

USE_PROCD=1

# After the network (20) and the firewall (19), because there is no point
# testing candidate protocols before there is a WAN to test them over. The
# daemon retries on its own anyway, so being early would only waste attempts.
START=95
# Early in the shutdown, while the network is still up: the daemon has to talk
# to `ip` to put the routing back, and a router whose tunnel rules outlive its
# daemon has no route to the internet and no software left to fix it.
STOP=10

PROG=/usr/sbin/meduzavpnd
CLI=/usr/bin/meduzavpn
RUNDIR=/var/run/meduzavpn
CONFFILE=$RUNDIR/config.json
STATEDIR=/etc/meduzavpn

# write_settings turns the UCI section into the daemon's settings file.
#
# It uses jshn rather than printf so that a location with a quote in it, or an
# empty list, produces valid JSON instead of a file the daemon refuses to parse
# with an error nobody can connect the two halves of.
write_settings() {
	. /usr/share/libubox/jshn.sh

	local service location protocol log_level api_base mtu
	local killswitch ipv6 auto_connect dns
	local policy_mode proxy_only proxy_lan_allow proxy_listen_http proxy_listen_socks

	config_load meduzavpn
	config_get service            general service_id
	config_get location           general location
	config_get protocol           general protocol 'auto'
	config_get log_level          general log_level 'info'
	config_get api_base           general api_base
	config_get mtu                general mtu 0
	config_get dns                general dns
	config_get policy_mode        general policy_mode 'all_vpn'
	config_get proxy_listen_http  general proxy_listen_http
	config_get proxy_listen_socks general proxy_listen_socks
	config_get_bool killswitch      general killswitch 0
	config_get_bool ipv6            general ipv6 0
	config_get_bool auto_connect    general auto_connect 1
	config_get_bool proxy_only      general proxy_only 0
	config_get_bool proxy_lan_allow general proxy_lan_allow 0

	# 'location' is a second spelling of 'service_id': the daemon resolves a
	# service by id, by name or by location, so one field serves both and there
	# is no second lookup to write.
	[ -n "$service" ] || service=$location

	json_init
	[ -n "$api_base" ] && json_add_string api_base "$api_base"
	[ -n "$service" ] && json_add_string service "$service"
	[ -n "$protocol" ] && json_add_string protocol "$protocol"
	[ -n "$log_level" ] && json_add_string log_level "$log_level"
	[ -n "$policy_mode" ] && json_add_string policy_mode "$policy_mode"
	[ -n "$proxy_listen_http" ] && json_add_string proxy_listen_http "$proxy_listen_http"
	[ -n "$proxy_listen_socks" ] && json_add_string proxy_listen_socks "$proxy_listen_socks"
	[ "${mtu:-0}" -gt 0 ] 2>/dev/null && json_add_int mtu "$mtu"
	json_add_boolean kill_switch "$killswitch"
	json_add_boolean ipv6 "$ipv6"
	json_add_boolean auto_connect "$auto_connect"
	json_add_boolean proxy_only "$proxy_only"
	json_add_boolean proxy_lan_allow "$proxy_lan_allow"
	if [ -n "$dns" ]; then
		json_add_array dns
		local one
		for one in $dns; do json_add_string "" "$one"; done
		json_close_array
	fi

	add_policy_json() {
		local sec="$1"
		local p_name p_match p_route
		config_get p_name  "$sec" name
		config_get p_match "$sec" match
		config_get p_route "$sec" route
		[ -n "$p_match" ] && [ -n "$p_route" ] || return 0
		json_add_object ""
		[ -n "$p_name" ] && json_add_string name "$p_name"
		json_add_string match "$p_match"
		json_add_string route "$p_route"
		json_close_object
	}
	json_add_array device_policies
	config_foreach add_policy_json policy
	json_close_array

	mkdir -p "$RUNDIR"
	chmod 0700 "$RUNDIR"
	# Written through a temporary file: procd may be starting the daemon while
	# this runs on a reload, and a half-written settings file is a daemon that
	# will not start for a reason that has nothing to do with the settings.
	json_dump > "$CONFFILE.new" || return 1
	chmod 0600 "$CONFFILE.new"
	mv "$CONFFILE.new" "$CONFFILE"
}

# clear_device_policies removes any per-device LAN routing mark rules installed
# by apply_device_policies.
clear_device_policies() {
	if command -v nft >/dev/null 2>&1; then
		nft delete table inet meduzavpn_policy 2>/dev/null || true
	fi
	if command -v iptables >/dev/null 2>&1; then
		iptables -t mangle -D PREROUTING -j MEDUZAVPN_POLICY 2>/dev/null || true
		iptables -t mangle -F MEDUZAVPN_POLICY 2>/dev/null || true
		iptables -t mangle -X MEDUZAVPN_POLICY 2>/dev/null || true
	fi
}

# apply_device_policies enforces `config policy` sections (`match` by mac: or
# ip:, `route` vpn | direct) and `option policy_mode` (`all_vpn` | `selected_vpn`).
#
# Marks match netcfg's table 51820 conventions:
#   - 0x4d555052 (ProbeMark) enters the tunnel table at probePref priority.
#   - 0xca6c (MarkForTable(51820)) bypasses the tunnel rule (`not fwmark 0xca6c`)
#     and stays on the physical WAN in table main.
apply_device_policies() {
	clear_device_policies

	local policy_mode count=0
	config_load meduzavpn
	config_get policy_mode general policy_mode 'all_vpn'

	count_rule() {
		local m r
		config_get m "$1" match
		config_get r "$1" route
		[ -n "$m" ] && [ -n "$r" ] && count=$((count + 1))
	}
	config_foreach count_rule policy

	if [ "$policy_mode" != "selected_vpn" ] && [ "$count" -eq 0 ]; then
		return 0
	fi

	if command -v nft >/dev/null 2>&1; then
		local nft_file="$RUNDIR/policy.nft"
		mkdir -p "$RUNDIR"
		{
			echo "table inet meduzavpn_policy {"
			echo "	chain prerouting {"
			echo "		type filter hook prerouting priority mangle; policy accept;"
			echo "		iifname \"lo\" accept"
			echo "		ip daddr { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, 127.0.0.0/8, 169.254.0.0/16, 224.0.0.0/4, 255.255.255.255/32 } accept"
			echo "		ip6 daddr { ::1/128, fc00::/7, fe80::/10, ff00::/8 } accept"
			emit_nft_rule() {
				local sec="$1" match route mark val
				config_get match "$sec" match
				config_get route "$sec" route
				[ -n "$match" ] && [ -n "$route" ] || return 0
				case "$route" in
					vpn)    mark="0x4d555052" ;;
					direct) mark="0xca6c" ;;
					*)      return 0 ;;
				esac
				case "$match" in
					mac:*|MAC:*)
						val=$(printf '%s' "${match#*:}" | tr 'A-F' 'a-f')
						echo "		ether saddr $val meta mark set $mark accept"
						;;
					ip:*|IP:*)
						val="${match#*:}"
						echo "		ip saddr $val meta mark set $mark accept"
						;;
				esac
			}
			config_foreach emit_nft_rule policy
			if [ "$policy_mode" = "selected_vpn" ]; then
				echo "		ip saddr { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10 } meta mark set 0xca6c accept"
			fi
			echo "	}"
			echo "}"
		} > "$nft_file"
		if nft -f "$nft_file" 2>/dev/null; then
			logger -t meduzavpn -p daemon.info \
				"enforced $count per-device policy rule(s) via nftables (mode=$policy_mode)"
			return 0
		fi
	fi

	if command -v iptables >/dev/null 2>&1; then
		iptables -t mangle -N MEDUZAVPN_POLICY 2>/dev/null || true
		for cidr in 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 100.64.0.0/10 127.0.0.0/8 169.254.0.0/16 224.0.0.0/4 255.255.255.255/32; do
			iptables -t mangle -A MEDUZAVPN_POLICY -d "$cidr" -j RETURN 2>/dev/null || true
		done
		emit_ipt_rule() {
			local sec="$1" match route mark val
			config_get match "$sec" match
			config_get route "$sec" route
			[ -n "$match" ] && [ -n "$route" ] || return 0
			case "$route" in
				vpn)    mark="0x4d555052" ;;
				direct) mark="0xca6c" ;;
				*)      return 0 ;;
			esac
			case "$match" in
				mac:*|MAC:*)
					val=$(printf '%s' "${match#*:}" | tr 'a-f' 'A-F')
					iptables -t mangle -A MEDUZAVPN_POLICY -m mac --mac-source "$val" -j MARK --set-mark "$mark" 2>/dev/null || true
					iptables -t mangle -A MEDUZAVPN_POLICY -m mac --mac-source "$val" -j RETURN 2>/dev/null || true
					;;
				ip:*|IP:*)
					val="${match#*:}"
					iptables -t mangle -A MEDUZAVPN_POLICY -s "$val" -j MARK --set-mark "$mark" 2>/dev/null || true
					iptables -t mangle -A MEDUZAVPN_POLICY -s "$val" -j RETURN 2>/dev/null || true
					;;
			esac
		}
		config_foreach emit_ipt_rule policy
		if [ "$policy_mode" = "selected_vpn" ]; then
			for lan in 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 100.64.0.0/10; do
				iptables -t mangle -A MEDUZAVPN_POLICY -s "$lan" -j MARK --set-mark 0xca6c 2>/dev/null || true
			done
		fi
		iptables -t mangle -I PREROUTING 1 -j MEDUZAVPN_POLICY 2>/dev/null || true
		logger -t meduzavpn -p daemon.info \
			"enforced $count per-device policy rule(s) via iptables mangle (mode=$policy_mode)"
	fi
	return 0
}

warn_about_killswitch() {
	local killswitch
	config_load meduzavpn
	config_get_bool killswitch general killswitch 0
	[ "$killswitch" = 1 ] && \
		logger -t meduzavpn -p daemon.warn \
			"kill switch is on: while the tunnel is down, every device in this house loses the internet -- the LAN and the router itself stay reachable, nothing else does"
	return 0
}

start_service() {
	local enabled
	config_load meduzavpn
	config_get_bool enabled general enabled 0
	if [ "$enabled" != 1 ]; then
		logger -t meduzavpn -p daemon.notice \
			"not starting: disabled in /etc/config/meduzavpn (uci set meduzavpn.general.enabled=1)"
		return 0
	fi

	if ! write_settings; then
		logger -t meduzavpn -p daemon.err "could not write $CONFFILE; not starting"
		return 1
	fi
	warn_about_killswitch
	apply_device_policies

	mkdir -p "$STATEDIR"
	chmod 0700 "$STATEDIR"

	procd_open_instance meduzavpnd
	procd_set_param command "$PROG" --config "$CONFFILE" --state-dir "$STATEDIR"
	# Stamped so the account's device list says how this copy arrived, the same
	# way the .deb and .rpm do it.
	procd_set_param env MEDUZAVPN_INSTALL=openwrt
	# respawn threshold=300 timeout=5 retry=0: give up never. A router that
	# stopped retrying is a router somebody has to drive to.
	procd_set_param respawn 300 5 0
	# Long enough for the daemon to take the tunnel down and put the routing,
	# the DNS and the firewall back before procd reaches for SIGKILL. Cut short,
	# the rules stay and the house has no internet.
	procd_set_param term_timeout 30
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}

# A settings change cannot be applied to a running daemon -- it reads its file
# once at start -- so a reload is a restart, and a restart drops the tunnel.
# procd is told to do it that way rather than pretending otherwise.
service_triggers() {
	procd_add_reload_trigger meduzavpn
}

reload_service() {
	stop
	start
}

stop_service() {
	clear_device_policies
}
