#!/bin/sh
# Start TorDNSEL without a Tor client and check that it answers authoritative
# DNS queries over UDP and TCP, and HTTP API requests. With no Tor, nothing is
# an exit, so exit queries must be answered negatively.
set -eu
dir=$(mktemp -d)
pid=
cleanup() {
  [ -n "$pid" ] && kill "$pid" 2>/dev/null || true
  rm -rf "$dir"
}
trap cleanup EXIT
mkdir -m 700 "$dir/state" "$dir/run"
cat > "$dir/tordnsel.conf" <<EOT
ZoneOfAuthority exitlist.example.com.
DomainName exitlist-ns.example.com.
SOARName hostmaster.example.com.
StateDirectory $dir/state
RuntimeDirectory $dir/run
RunAsDaemon False
DNSListenAddress 127.0.0.1:15353
HTTPListenAddress 127.0.0.1:18053
# Nothing listens here: run without Tor.
TorControlAddress 127.0.0.1:9
Log notice stderr
EOT
tordnsel -f "$dir/tordnsel.conf" &
pid=$!

dig="dig -p 15353 @127.0.0.1 +time=2 +tries=1"
for i in $(seq 20); do
  $dig +short exitlist.example.com SOA >/dev/null 2>&1 && break
  sleep 0.5
done

echo "SOA over UDP"
$dig +short exitlist.example.com SOA | grep -q '^exitlist-ns\.example\.com\. hostmaster\.example\.com\. '
echo "NS over TCP"
$dig +tcp +short exitlist.example.com NS | grep -qx 'exitlist-ns\.example\.com\.'
echo "exit query: NXDOMAIN"
$dig 4.3.2.1.exitlist.example.com A | grep -q 'status: NXDOMAIN'
echo "outside the zone: REFUSED"
$dig www.example.org A | grep -q 'status: REFUSED'
echo "HTTP /api/v1/exit"
curl -fsS 'http://127.0.0.1:18053/api/v1/exit?ip=1.2.3.4' | grep -q '"listed":false'
echo OK
