#!/bin/sh
#	list-dns-ip 0.02
#
#	Copyright (C) 2000:	Manel Marin <manel3@wanadoo.es>
#	Licence:		GNU GPL version >= 2
#
#
#	Devuelve las IP de los servidores DNS
#	examina resolv.conf y la config de bind named.conf (cache-dns)
#
# ***POR HACER *** Uso de bind accediendo a los DNS root de internet
#
#
#	Uso:	list-dns-ip
#
#
#	------
#	Returns IP of DNS servers
#	reads resolv.conf and bind config (cache-dns)
#
#	Use:	list-dns-ip
#


# BUSCAR TODOS LOS INTERFACES LOCALES

IPIFACES="`list-iface-ip all`"

awk -v IPIFACES="$IPIFACES" '

    BEGIN {


# ARCHIVOS
	RESOLV = "/etc/resolv.conf"
	NAMED = "/etc/bind/named.conf"


# INICIALIZO VARS
	DNS = ""
	cachedns = ""
	forwarders = ""
	ORS = " "	# Separar valores de salida por espacios y no por \n


# LEER RESOLV.CONF
# las lineas que contienen "nameserver" como primera palabra son servidores DNS
	while( 1 == getline < RESOLV )
	    {
    		if( $1 == "nameserver" ) {
		    if( DNS == "" ) DNS = $2
		    else DNS = DNS " " $2
		}
	    }
	close( RESOLV )			# reset de getline

    ##	print "DNS in resolv.conf: " DNS		# debug

# resolv.conf: SI LAS IP SON LOCALES BUSCAR EN CONFIG DE BIND
# si solo hay un DNS y es una IP local buscar servidores DNS en bind
	found = "no"
	split( IPIFACES, parts, "[ \t]+" )	# Crear tabla con IP locales
	for ( n in parts ) {
    ##	    print "n=" parts[n] " "			# debug
	    if ( DNS == parts[n] ) found = "yes"
	}
	if ( found == "no" ) {	# IP NO LOCALES -> Son los DNS
	    print DNS
	}
	else {				# IP LOCALES -> Mirar config de bind
	    DNS = ""		# Inicializo variable...


# LEER NAMED.CONF
# named.conf: SI ES CACHE DNS (forward only;) USAR LAS IP DE LOS forwarders
	    while( 1 == getline < NAMED )
	    {

# CONFIGURADO COMO CACHE DNS?
    		if( $0 ~ "^[ \t]*forward only;" ) cachedns = "yes"

# DELIMITAR AREA DE LAS IP DE LOS DNS EN CACHE DNS
		if( $0 ~ "^[ \t]*forwarders[ \t]*{" ) forwarders = "yes"
		if( $0 ~ "^[ \t]*}[ \t]*;" ) forwarders = ""

# AADIR TODAS LAS IP DE FORWARDERS
		if( forwarders ){
		    if( $0 ~ "^[ \t]*[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" ){
			ip = $0
			gsub( "[^0-9\.]", "", ip )	# Solo dejo IP
			if( DNS == "" ) DNS = ip
			else DNS = DNS " " ip
		    }
		}
	    }
	    close( NAMED )			# reset de getline

    ##	    print "Forwarders in named.conf: " DNS	# debug

# SI ES CACHE DNS Y HAY FORWARDERS -> FIN
	    if( cachedns && DNS ) print DNS
	    else{


# SINO BIND SE USA ACCEDIENTO A TODOS LOS DNS DE INTERNET
#*** POR HACER *** Basta con permitir todas las IP de /etc/bind/db.root?
		print "0/0"

	    }
	}
    }
'
