wagon/back/lib/ips_to_peers_rdns

50 lines
1.6 KiB
Bash
Executable File

#!/bin/bash
# FILE: ips_to_peers_rdns
# DESCRIPTION: Takes a list of IPs from wg show allowed-ips
# and adds domains using rdns lookups
# USAGE: ips_to_peers_rdns json <<<"${user_peers}"
# ERRORS:
# 3: bad usage
# 4: nslookup failed
# 5: Invalid format
# 6: Config file not found
CONFIG_FILE='/etc/wgapi/config'
if ! [ -f "${CONFIG_FILE}" ]; then
printf 'ERROR! %s Config file not found\n' "${0}" >>"${LOGFILE}"
exit 6
fi & if ! [ ${#} -eq 1 ] || [ ${#} -eq 3 ]; then
printf 'ERROR! Bad usage: %s %s\n' "$0" "$*" >>"${LOGFILE}"
exit 3
fi & if ! [ -x /usr/bin/wg ]; then
printf 'ERROR! %s /usr/bin/wg not found\n' "${0}" >>"${LOGFILE}"
exit 5
fi
source "${CONFIG_FILE}"
format="${1}"
# Loop through each peer in parallel and do an rDNS lookup for the hostnames
do_lookup(){
pubkey="$(<<<"${1}" cut -d ' ' -f1)"
ips="$(<<<"${1}" cut -d ' ' -f2 | tr ' ' '\n')"
ipv4="$(<<<"${ips}" grep '\.')"
ipv6="$(<<<"${ips}" grep ':')"
ipv4="${ipv4%%/*}"
ipv6="${ipv6%%/*}"
if ! domain="$("${LIB_DIR:?}/ns_lookup_rdns" "${ipv4:?}" | xargs)"
then exit 4
fi
case "${format}" in
'json') printf '{"domain":"%s","ipv4":"%s","ipv6":"%s","pubkey":"%s"},' \
"${domain}" "${ipv4}" "${ipv6}" "${pubkey}";;
'tsv') printf '%s\t%s\t%s\t%s\n' "${domain}" "${ipv4}" "${ipv6}" "${pubkey}";;
*) printf 'ERROR! Invalid format for %s: %s\n' "${0}" "${format}" >>"${LOGFILE}"
exit 5;
esac
}
# This should read from stdin
while IFS= read -r line
do do_lookup "${line}" "${1}" &
[ $( jobs | wc -l ) -ge $( nproc ) ] && wait
done | sed 's/\n//g' | sed 's/,$//' # Remove trailing comma and newline