#!/bin/bash
# EmmaVPN DNS hook — installed as /usr/lib/emmavpn/emmavpn-dns.
#
# OpenVPN runs it as the --up / --down script (as root) so that, while the
# VPN is connected, ALL DNS lookups go to the VPN's DNS servers through the
# tunnel (no DNS leaks), on every distribution:
#   • systemd-resolved (Ubuntu, Fedora, openSUSE, Arch with resolved, ...):
#     per-link DNS on the tunnel + "~." routing domain = default for all names
#   • otherwise: /etc/resolv.conf is replaced while connected and restored
#     on disconnect.
# "emmavpn-dns cleanup" undoes everything (used after a crash / force stop).
#
# WireGuard and IKEv2 have no OpenVPN environment, so the helper calls it
# directly instead (same behaviour, same restore logic):
#   emmavpn-dns set <link> [dns-ip ...]    (default 1.1.1.1 1.0.0.1)
#   emmavpn-dns unset <link>
# wg-quick's own "DNS =" handling needs resolvconf, which many systems lack;
# the helper strips DNS from the WireGuard config and uses this instead.

set -u
PATH=/usr/sbin:/usr/bin:/sbin:/bin
BACKUP=/run/emmavpn/resolv.conf.emmavpn-backup
MARK="# Set by EmmaVPN while connected"

use_resolved() {
    command -v resolvectl >/dev/null 2>&1 && \
        systemctl is-active --quiet systemd-resolved 2>/dev/null
}

# True when programs actually ask systemd-resolved: /etc/resolv.conf points
# at its local stub. When resolved runs but resolv.conf lists other servers
# (WSL, NetworkManager "default" mode, static files, resolved's "uplink"
# file), the per-link settings alone are ignored by programs and DNS leaks,
# so /etc/resolv.conf has to be replaced as well.
resolv_is_stub() {
    grep -qE '^[[:space:]]*nameserver[[:space:]]+127\.0\.0\.5[34]([[:space:]]|$)' \
        /etc/resolv.conf 2>/dev/null
}

# DNS lock: while connected, every DNS query (port 53) that is not already
# going to the VPN's DNS servers is redirected to them (through the tunnel).
# This holds even when something rewrites /etc/resolv.conf behind our back
# (WSL restores its own file within a minute; NetworkManager can on network
# changes) and for programs that pick their own DNS server. IPv6 DNS needs
# nothing here: the helper's IPv6 block already stops it.
DNS_TABLE=emmavpn_dns
dns_lock_on() {
    command -v nft >/dev/null 2>&1 || return 0
    local v4=() d
    for d in "${dns[@]}"; do [[ "$d" =~ ^[0-9.]+$ ]] && v4+=("$d"); done
    [ "${#v4[@]}" -gt 0 ] || return 0
    local set; set="$(IFS=,; echo "${v4[*]}")"
    # Source for redirected queries: the tunnel's own address (WireGuard /
    # OpenVPN tunnel IP, IKEv2 virtual IP on its DNS link). For IKEv2 the
    # route goes out the physical interface, so "masquerade" would pick the
    # physical address and the query would skip encryption; with the virtual
    # IP the kernel re-checks IPsec after NAT and encrypts it.
    local src; src="$(ip -4 -o addr show dev "$link" 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -1)"
    local nat="masquerade"
    [[ "$src" =~ ^[0-9.]+$ ]] && nat="snat to $src"
    nft delete table ip "$DNS_TABLE" 2>/dev/null || true
    nft -f - <<EOF || echo "emmavpn-dns: warning: could not apply DNS lock" >&2
table ip $DNS_TABLE {
    chain out {
        type nat hook output priority -100; policy accept;
        ip daddr { $set } return
        meta l4proto { udp, tcp } th dport 53 dnat to ${v4[0]}
    }
    chain post {
        type nat hook postrouting priority 100; policy accept;
        # A redirected query still carries the source address chosen for its
        # original destination (LAN address, or a local one like WSL's
        # 10.255.255.254); the tunnel only accepts its own address, so use
        # the outgoing (tunnel) interface's address instead.
        ct status dnat ip daddr { $set } meta l4proto { udp, tcp } th dport 53 $nat
    }
}
EOF
}
dns_lock_off() {
    command -v nft >/dev/null 2>&1 || return 0
    nft delete table ip "$DNS_TABLE" 2>/dev/null || true
}

replace_resolv_conf() {
    mkdir -p "$(dirname "$BACKUP")"
    [ -e "$BACKUP" ] || [ -L "$BACKUP" ] || cp -P /etc/resolv.conf "$BACKUP" 2>/dev/null || true
    tmp="$(mktemp /etc/.resolv.conf.emmavpn.XXXXXX)"
    { echo "$MARK"; for d in "${dns[@]}"; do echo "nameserver $d"; done; } > "$tmp"
    chmod 0644 "$tmp"
    rm -f /etc/resolv.conf
    mv -f "$tmp" /etc/resolv.conf
}

restore_resolv_conf() {
    if [ -e "$BACKUP" ] || [ -L "$BACKUP" ]; then
        rm -f /etc/resolv.conf
        mv -f "$BACKUP" /etc/resolv.conf
    fi
}

valid_link() { [[ "$1" =~ ^[A-Za-z0-9_.-]{1,15}$ ]]; }
valid_ip() { [[ "$1" =~ ^[0-9A-Fa-f.:]+$ ]]; }

dns=()
if [ -z "${script_type:-}" ] && { [ "${1:-}" = "set" ] || [ "${1:-}" = "unset" ]; }; then
    # Direct call from emmavpn-helper (WireGuard / IKEv2).
    [ "${1}" = "set" ] && mode=up || mode=down
    link="${2:-}"
    valid_link "$link" || { echo "emmavpn-dns: bad link name" >&2; exit 1; }
    shift 2
    for d in "$@"; do valid_ip "$d" && dns+=("$d"); done
else
    mode="${script_type:-${1:-}}"
    link="${dev:-tun0}"
    if [ "$mode" = "up" ]; then
        for i in $(seq 1 99); do
            var="foreign_option_$i"
            opt="${!var:-}"
            [ -n "$opt" ] || break
            case "$opt" in
                "dhcp-option DNS "*) dns+=("${opt#dhcp-option DNS }") ;;
            esac
        done
    fi
fi

case "$mode" in
    up)
        [ "${#dns[@]}" -gt 0 ] || dns=(1.1.1.1 1.0.0.1)

        if use_resolved; then
            resolvectl dns "$link" "${dns[@]}"
            resolvectl domain "$link" '~.'
            resolvectl default-route "$link" yes 2>/dev/null || true
            resolvectl flush-caches 2>/dev/null || true
            # resolved runs, but programs don't ask it: replace the file too.
            resolv_is_stub || replace_resolv_conf
        else
            replace_resolv_conf
        fi
        dns_lock_on
        ;;
    down|cleanup)
        dns_lock_off
        if use_resolved; then
            resolvectl revert "$link" 2>/dev/null || true
            # cleanup: also the WireGuard / IKEv2 link (fails quietly if absent).
            [ "$mode" = "cleanup" ] && resolvectl revert emmavpn 2>/dev/null || true
            resolvectl flush-caches 2>/dev/null || true
        fi
        restore_resolv_conf
        ;;
esac
exit 0
