# IP address, hostname, and related input validation helpers.

is_valid_ipv4_addr() {
    local ip="$1"

    # RFC 3986 section 3.2.2 dec-octet grammar: dotted decimal, 0-255,
    # and no leading zeros.
    echo "$ip" | grep -Eq '^(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}$'
}

is_valid_ipv4() {
    is_valid_ipv4_addr "$1"
}

trim_ws() {
    echo "$1" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//'
}

canonical_proxy_url() {
    local proxy="$1"
    local scheme rest authority host port

    proxy="$(trim_ws "$proxy")"
    [[ "$proxy" =~ ^([Hh][Tt][Tt][Pp][Ss]?)://([^/\?\#[:space:]]+)$ ]] || return 1
    [[ "$proxy" != *"'"* ]] || return 1
    scheme="${BASH_REMATCH[1]}"
    rest="${BASH_REMATCH[2]}"

    authority="$rest"
    if [[ "$authority" == *"@"* ]] ; then
        authority="${authority##*@}"
    fi
    [ -n "$authority" ] || return 1

    if [[ "$authority" =~ ^\[([^][]+)\](:([0-9]+))?$ ]] ; then
        host="${BASH_REMATCH[1]}"
        port="${BASH_REMATCH[3]}"
        is_valid_ipv6_addr "$host" || return 1
    else
        if [[ "$authority" == *":"* ]] ; then
            host="${authority%%:*}"
            port="${authority##*:}"
            [[ "$port" =~ ^[0-9]+$ ]] || return 1
        else
            host="$authority"
            port=""
        fi
        is_valid_ipv4_addr "$host" || is_valid_hostname "$host" || return 1
    fi

    if [ -n "$port" ] && { [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; } ; then
        return 1
    fi

    case "${scheme,,}" in
        http) printf 'http://%s\n' "$rest" ;;
        https) printf 'https://%s\n' "$rest" ;;
        *) return 1 ;;
    esac
}

is_valid_proxy_url() {
    canonical_proxy_url "$1" >/dev/null
}

is_valid_ipv6_addr() {
    local ip="$1"

    # RFC 5952 canonical IPv6 text: lowercase hexadecimal, no leading zeros,
    # one :: compression at most, and compression only for two or more zero
    # fields using the leftmost longest zero run.
    echo "$ip" | awk '
        function parse_side(side, out,   n, i) {
            if (side == "") return 0
            n = split(side, t, ":")
            for (i = 1; i <= n; i++) {
                if (t[i] == "" || t[i] !~ /^[0-9a-f]{1,4}$/) return -1
                if (length(t[i]) > 1 && substr(t[i], 1, 1) == "0") return -1
                out[i] = t[i]
            }
            return n
        }
        function endswith_colon(x) { return substr(x, length(x), 1) == ":" }
        {
            s=$0
            if (s == "" || s !~ /^[0-9a-f:]+$/) exit 1
            if (s ~ /^:[^:]/ || s ~ /[^:]:$/) exit 1
            dc=0
            for (i=1; i<length(s); i++) if (substr(s,i,2) == "::") dc++
            if (dc > 1) exit 1
            dpos = index(s, "::")
            if (dpos > 0) {
                lcount = parse_side(substr(s, 1, dpos-1), la)
                rcount = parse_side(substr(s, dpos+2), ra)
                if (lcount < 0 || rcount < 0 || 8-lcount-rcount < 2) exit 1
                idx=1
                for (i=1; i<=lcount; i++) full[idx++]=la[i]
                for (i=1; i<=8-lcount-rcount; i++) full[idx++]="0"
                for (i=1; i<=rcount; i++) full[idx++]=ra[i]
                if (idx != 9) exit 1
            } else {
                n=parse_side(s, full)
                if (n != 8) exit 1
            }
            best_start=0; best_len=0; run_start=0; run_len=0
            for (i=1; i<=8; i++) {
                if (full[i] == "0") {
                    if (run_len == 0) run_start=i
                    run_len++
                } else {
                    if (run_len >= 2 && run_len > best_len) { best_len=run_len; best_start=run_start }
                    run_len=0
                }
            }
            if (run_len >= 2 && run_len > best_len) { best_len=run_len; best_start=run_start }
            out=""; i=1
            while (i <= 8) {
                if (best_len >= 2 && i == best_start) {
                    if (out == "") out="::"; else out=out "::"
                    i += best_len
                    if (i > 8) break
                    continue
                }
                if (out != "" && !endswith_colon(out)) out=out ":"
                out=out full[i]; i++
            }
            if (out != s) exit 1
            exit 0
        }'
}

is_valid_ipv6() { is_valid_ipv6_addr "$1"; }

is_valid_ipv6_cidr() {
    local cidr="$1" ip="${cidr%%/*}" prefix="${cidr##*/}"
    [ -n "$ip" ] && [ -n "$prefix" ] || return 1
    echo "$prefix" | grep -Eq '^[0-9]+$' || return 1
    [ "$prefix" -ge 0 ] && [ "$prefix" -le 128 ] || return 1
    is_valid_ipv6_addr "$ip"
}

is_valid_ipv6_dns_list() {
    local dns_list="$1" dns
    [ -z "$dns_list" ] && return 0
    for dns in $dns_list ; do is_valid_ipv6_addr "$dns" || return 1; done
}

is_valid_ipv6_host() {
    is_valid_ipv6_addr "$1"
}

is_valid_hostname() {
    local hostname=$1 label
    local -a labels

    # RFC 1034/1035 hostname syntax: ASCII labels, 1-63 characters each,
    # separated by dots, with letters, digits, and hyphens only. RFC 1123
    # permits a hostname label to begin with a digit.
    [ -n "$hostname" ] && [ "${#hostname}" -le 253 ] || return 1
    [[ "$hostname" != *[^A-Za-z0-9.-]* ]] || return 1
    IFS=. read -r -a labels <<< "$hostname"
    for label in "${labels[@]}" ; do
        [ -n "$label" ] && [ "${#label}" -le 63 ] || return 1
        # RFC 1123 hostname labels may start with a digit, but not a hyphen.
        [[ "$label" =~ ^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?$ ]] || return 1
    done
}

is_valid_ntp_server() {
    local server=$1

    if [[ "$server" == *:* ]]; then is_valid_ipv6_host "$server"; return $?; fi
    if [[ "$server" == *.* && "$server" =~ ^[0-9.]+$ ]]; then is_valid_ipv4 "$server"; return $?; fi
    is_valid_hostname "$server"
}