#!/bin/sh
# Am I behind CGNAT?  curl -fsSL https://fieldhand.dev/cgnat.sh | sh
# Read-only: looks at this machine's addresses, asks api.fieldhand.dev which
# address it sees, and traces the first few hops. Changes nothing.
# Works with BusyBox. Needs curl or wget; tracepath or traceroute helps.

octets() { echo "$1" | awk -F. '{print $1, $2}'; }
is_cgnat() { set -- $(octets "$1"); [ "$1" = 100 ] && [ "$2" -ge 64 ] && [ "$2" -le 127 ]; } # 100.64.0.0/10
is_private() {
	set -- $(octets "$1")
	[ "$1" = 10 ] || { [ "$1" = 172 ] && [ "$2" -ge 16 ] && [ "$2" -le 31 ]; } || { [ "$1" = 192 ] && [ "$2" = 168 ]; }
}

if [ "${1:-}" = --selftest ]; then
	for a in 100.64.0.1 100.127.255.254; do is_cgnat $a || { echo "FAIL cgnat $a"; exit 1; }; done
	for a in 100.63.0.1 100.128.0.1 10.0.0.1; do is_cgnat $a && { echo "FAIL not cgnat $a"; exit 1; }; done
	for a in 10.1.2.3 172.16.0.1 172.31.9.9 192.168.1.1; do is_private $a || { echo "FAIL private $a"; exit 1; }; done
	for a in 172.15.0.1 172.32.0.1 192.169.0.1 8.8.8.8; do is_private $a && { echo "FAIL not private $a"; exit 1; }; done
	echo ok; exit 0
fi

fetch() { curl -4 -fsS --max-time 10 "$1" 2>/dev/null || wget -4 -qO- -T 10 "$1" 2>/dev/null || wget -qO- "$1" 2>/dev/null; }
public=$(fetch https://api.fieldhand.dev/ip | tr -d '[:space:]')
case "$public" in *.*.*.*) ;; *) echo "Couldn't reach api.fieldhand.dev over IPv4; is this machine online?"; exit 1 ;; esac

if command -v ip >/dev/null 2>&1; then
	# The address traffic leaves from; Tailscale and other VPNs also use 100.64.0.0/10.
	local4=$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "src") print $(i + 1)}')
	local6=$(ip -6 route get 2606:4700:4700::1111 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "src") print $(i + 1)}')
else
	local4=$(ifconfig 2>/dev/null | awk '/^[a-z]/ {vpn = ($1 ~ /^(tailscale|zt|wg|tun)/)} /inet / && !vpn {sub("addr:", "", $2); if ($2 != "127.0.0.1") print $2}')
fi

# Hops 2-6: whatever sits between your router and the internet.
hops=""
if command -v tracepath >/dev/null 2>&1; then
	hops=$(tracepath -n -m 6 1.1.1.1 2>/dev/null | awk '$1 ~ /^[0-9]+:$/ && $2 ~ /^[0-9.]+$/ {sub(":", "", $1); if ($1 > 1) print $2}' | uniq)
elif command -v traceroute >/dev/null 2>&1; then
	hops=$(traceroute -n -m 6 -q 1 -w 2 1.1.1.1 2>/dev/null | awk '$1 ~ /^[0-9]+$/ && $2 ~ /^[0-9.]+$/ && $1 > 1 {print $2}')
fi

echo "Public IPv4 seen by the internet: $public"
echo "This machine's IPv4: $(echo $local4)"
[ -n "$hops" ] && echo "Hops after your router: $(echo $hops)"
echo

verdict() { echo "$1"; shift; for l in "$@"; do echo "  $l"; done; }
cgnat_hop=""; private_hop=""
for h in $hops; do
	is_cgnat "$h" && cgnat_hop=$h && break
	is_private "$h" && [ -z "$private_hop" ] && private_hop=$h
done
on_device=""
for a in $local4; do [ "$a" = "$public" ] && on_device=public; is_cgnat "$a" && on_device=cgnat; done

if [ "$on_device" = public ]; then
	verdict "NOT behind NAT: this machine has the public address itself." \
		"Connections from the internet reach it unless a firewall blocks them."
elif [ "$on_device" = cgnat ]; then
	verdict "BEHIND CGNAT: this machine has a carrier-grade NAT address (100.64.0.0/10)." \
		"Port forwarding can't work; nothing from the internet can connect in over IPv4."
elif [ -n "$cgnat_hop" ]; then
	verdict "BEHIND CGNAT: a hop after your router uses the carrier NAT range ($cgnat_hop)." \
		"Port forwarding on your router won't help; the carrier's NAT is upstream of it."
elif [ -n "$private_hop" ]; then
	verdict "PROBABLY BEHIND CGNAT or a second NAT: the next network after your router is private ($private_hop)." \
		"Check your router's WAN address. If it isn't $public, port forwarding can't work."
elif [ -z "$hops" ]; then
	verdict "UNSURE: couldn't trace the route (no tracepath/traceroute, or ICMP is blocked)." \
		"Open your router's status page: if its WAN address isn't $public, you're behind CGNAT." \
		"On a phone hotspot or a 4G modem, assume CGNAT: almost every mobile carrier uses it."
else
	verdict "PROBABLY NOT behind CGNAT: only your own router's NAT is in the way." \
		"Port forwarding on the router should work if its WAN address is $public."
fi
[ -n "${local6:-}" ] && echo "
You also have IPv6 ($local6). IPv6 has no NAT, but carriers and routers often block inbound connections."
echo "
Can't open a port? A device that connects out can still be reached:
  https://support.fieldhand.dev/answers/reach-raspberry-pi-behind-cgnat"
