open-humanity
Privacy-first peer assistance network for sovereign autonomous agents
Brought by drakestapleton
open-humanity / deploy / portmap.sh
| 1 | #!/bin/bash |
| 2 | # Ask the gateway in NAT_PMP_GATEWAY (NAT-PMP, UDP 5351) to keep public UDP 18098 |
| 3 | # mapped to this host for one hour. Run every 20 minutes by |
| 4 | # open-humanity-relay-portmap.timer. The router's answer is checked: a rejected |
| 5 | # or missing mapping is a failure, not a success. |
| 6 | # Request bytes: version 0, opcode 1 (map UDP), reserved, internal port 18098 |
| 7 | # (0x46b2), external port 18098, lifetime 3600 s (0x0e10). RFC 6886 section 3.3. |
| 8 | # Offline check: portmap.sh --check-response FILE (16-byte NAT-PMP response). |
| 9 | set -u |
| 10 | |
| 11 | check_response() { |
| 12 | f=$1 |
| 13 | n=$(wc -c < "$f" | tr -d ' ') |
| 14 | if [ "$n" -ne 16 ]; then |
| 15 | echo "NAT-PMP: response is $n bytes, want 16" >&2 |
| 16 | return 1 |
| 17 | fi |
| 18 | hex=$(od -An -tx1 -v -N16 "$f" | tr -d ' \n') |
| 19 | ver=${hex:0:2} |
| 20 | op=${hex:2:2} |
| 21 | result=${hex:4:4} |
| 22 | internal=${hex:16:4} |
| 23 | external=${hex:20:4} |
| 24 | life=${hex:24:8} |
| 25 | if [ "$ver" != 00 ] || [ "$op" != 81 ] || [ "$result" != 0000 ] \ |
| 26 | || [ "$internal" != 46b2 ] || [ "$external" != 46b2 ] || [ "$life" = 00000000 ]; then |
| 27 | echo "NAT-PMP: rejected mapping ver=$ver op=$op result=$result internal=$internal external=$external life=$life" >&2 |
| 28 | return 1 |
| 29 | fi |
| 30 | return 0 |
| 31 | } |
| 32 | |
| 33 | if [ "${1:-}" = "--check-response" ]; then |
| 34 | check_response "$2" |
| 35 | exit $? |
| 36 | fi |
| 37 | |
| 38 | gw=${NAT_PMP_GATEWAY:-} |
| 39 | if [ -z "$gw" ]; then |
| 40 | echo "NAT_PMP_GATEWAY is empty; not opening a mapping" >&2 |
| 41 | exit 1 |
| 42 | fi |
| 43 | if ! printf '%s\n' "$gw" | grep -Eq '^[0-9]{1,3}(\.[0-9]{1,3}){3}$'; then |
| 44 | echo "NAT_PMP_GATEWAY is not an IPv4 address" >&2 |
| 45 | exit 1 |
| 46 | fi |
| 47 | IFS=. read -r o1 o2 o3 o4 <<EOF |
| 48 | $gw |
| 49 | EOF |
| 50 | for o in "$o1" "$o2" "$o3" "$o4"; do |
| 51 | if [ "$o" -gt 255 ]; then |
| 52 | echo "NAT_PMP_GATEWAY octet out of range" >&2 |
| 53 | exit 1 |
| 54 | fi |
| 55 | done |
| 56 | |
| 57 | exec 3<>"/dev/udp/${gw}/5351" || exit 1 |
| 58 | printf '\x00\x01\x00\x00\x46\xb2\x46\xb2\x00\x00\x0e\x10' >&3 || exit 1 |
| 59 | tmp=$(mktemp) |
| 60 | trap 'rm -f "$tmp"' EXIT |
| 61 | if ! timeout 2 dd bs=16 count=1 status=none <&3 >"$tmp"; then |
| 62 | echo "NAT-PMP: no answer from ${gw}:5351" >&2 |
| 63 | exit 1 |
| 64 | fi |
| 65 | check_response "$tmp" |