Newer
Older
mb-aaaa / mb-aaaa-update
#!/usr/bin/env bash
# mb-aaaa-update — publish this host's IPv6 address to Mythic Beasts,
# but only when it differs from the last address we successfully published.
# Steady state: zero network requests.

set -uo pipefail

API="${MB_API:-https://api.mythic-beasts.com/dns/v2}"
ZONE="${MB_ZONE:?MB_ZONE is not set}"
HOST="${MB_HOST:?MB_HOST is not set}"        # relative name, or @ for apex
TTL="${MB_TTL:-60}"
IFACE="${MB_IFACE:-}"
CREDS="${MB_CREDS:-/etc/mb-aaaa.credentials}"
STATE_DIR="${MB_STATE_DIR:-/var/lib/mb-aaaa}"
DNS_CHECK="${MB_DNS_CHECK:-0}"               # 1 = ask ns1/ns2 before writing
RECHECK_AGE="${MB_RECHECK_AGE:-0}"           # seconds; 0 = never re-check
VERBOSE="${MB_VERBOSE:-0}"                   # 1 = log no-op runs too
DRY_RUN="${MB_DRY_RUN:-0}"

# One state file per zone+host, so several copies can share the directory.
STATE="$STATE_DIR/${ZONE//[^A-Za-z0-9.-]/_}_${HOST//[^A-Za-z0-9.-]/_}.addr"

log()  { printf '%s %s: %s\n' "$(date -Is)" "$HOST" "$*" >&2; }
vlog() { [ "$VERBOSE" = 1 ] && log "$@"; return 0; }
die()  { log "ERROR: $*"; exit 1; }

lower() { printf '%s' "$1" | tr 'A-F' 'a-f'; }

# ------------------------------------------------------------ credentials
[ -r "$CREDS" ] || die "credentials file $CREDS missing or unreadable"
perm=$(stat -c '%a' "$CREDS")
(( 8#$perm & 8#077 )) && log "WARNING: $CREDS is group/world readable (mode $perm)"
# shellcheck disable=SC1090
. "$CREDS"
[ -n "${KEY:-}" ] && [ -n "${SECRET:-}" ] || die "KEY/SECRET not defined in $CREDS"

# ------------------------------------------------------------------- lock
command -v curl >/dev/null || die "curl not found"
command -v ip   >/dev/null || die "ip not found"
mkdir -p "$STATE_DIR" || die "cannot create $STATE_DIR"
exec 9>"$STATE_DIR/.lock" || die "cannot open lock"
flock -n 9 || { vlog "another instance is running"; exit 0; }

# ------------------------------------------------------- local IPv6 address
find_ipv6() {
  local def
  def=$(ip -6 route show default 2>/dev/null |
          awk '{for (i=1;i<=NF;i++) if ($i=="dev") {print $(i+1); exit}}')
  ip -6 addr show scope global 2>/dev/null | awk -v def="$def" -v want="$IFACE" '
    /^[0-9]+:/ { iface=$2; sub(/:$/,"",iface); sub(/@.*/,"",iface); next }
    /inet6 / {
      if ($0 ~ /(temporary|deprecated|tentative|dadfailed|optimistic)/) next
      split($2, p, "/"); addr=p[1]
      if (addr !~ /^(2|3)/) next                  # 2000::/3 only
      if (want != "" && iface != want) next
      print ((iface==def)?0:1), (($0 ~ /mngtmpaddr/)?0:1), addr
    }' | sort -k1,1n -k2,2n -k3,3 | awk 'NR==1 {print $3}'
}

# ------------------------------------------------- optional DNS pre-flight
# 0 = confirmed on every nameserver, 1 = differs, 2 = cannot check
dns_confirms() {
  local want=$1 ns out fqdn seen=0
  [ "$HOST" = "@" ] && fqdn="$ZONE" || fqdn="$HOST.$ZONE"
  command -v dig >/dev/null || return 2
  for ns in ns1.mythic-beasts.com ns2.mythic-beasts.com; do
    out=$(dig +short +time=3 +tries=1 AAAA "$fqdn" "@$ns" 2>/dev/null) || continue
    seen=1
    grep -qixF -- "$want" <<<"$out" || return 1
  done
  [ "$seen" = 1 ] || return 2
  return 0
}

save_state() {
  local tmp="$STATE.tmp.$$"
  printf '%s\n%s\n' "$1" "$(date -Is)" >"$tmp" &&
    chmod 0644 "$tmp" && mv -f "$tmp" "$STATE"
}

# -------------------------------------------------------------------- main
ADDR=$(find_ipv6)
[ -n "$ADDR" ] || { vlog "no usable global IPv6 address yet; nothing to do"; exit 0; }

last=$(head -n 1 "$STATE" 2>/dev/null || true)

if [ -n "$last" ] && [ "$(lower "$last")" = "$(lower "$ADDR")" ]; then
  # Address unchanged. Only reach for the network if a periodic re-check is due.
  if [ "$RECHECK_AGE" -gt 0 ]; then
    now=$(date +%s); mtime=$(stat -c %Y "$STATE" 2>/dev/null || echo 0)
    if [ $(( now - mtime )) -lt "$RECHECK_AGE" ]; then
      vlog "unchanged ($ADDR), state ${last} is current; no request made"
      exit 0
    fi
    vlog "unchanged locally, but state is $(( now - mtime ))s old; re-checking DNS"
  else
    vlog "unchanged ($ADDR); no request made"
    exit 0
  fi
elif [ -n "$last" ]; then
  log "address changed: $last -> $ADDR"
else
  log "no recorded state; publishing $ADDR"
fi

if [ "$DNS_CHECK" = 1 ]; then
  dns_confirms "$ADDR"; rc=$?
  case $rc in
    0) log "authoritative DNS already matches; recording state, no write"
       save_state "$ADDR"; exit 0 ;;
    2) log "dig unavailable/failed; proceeding with write" ;;
    *) log "authoritative DNS differs; proceeding with write" ;;
  esac
fi

if [ "$DRY_RUN" = 1 ]; then
  log "dry-run: would PUT $ADDR (ttl $TTL) to /zones/$ZONE/records/$HOST/AAAA"
  exit 0
fi

body=$(mktemp) || die "mktemp failed"
trap 'rm -f "$body"' EXIT

code=$(curl -sS --max-time 20 --retry 2 --retry-delay 3 \
         -u "$KEY:$SECRET" -X PUT \
         --data-urlencode "data=$ADDR" \
         --data-urlencode "ttl=$TTL" \
         -o "$body" -w '%{http_code}' \
         "$API/zones/$ZONE/records/$HOST/AAAA") || die "curl failed on PUT"

case $code in
  200|201) log "updated to $ADDR (ttl $TTL): $(cat "$body")" ;;
  401|403) die "auth/authorisation failed (HTTP $code): $(cat "$body")" ;;
  404)     die "zone or host not found (HTTP 404): $(cat "$body")" ;;
  *)       die "unexpected HTTP $code: $(cat "$body")" ;;
esac

save_state "$ADDR"
exit 0