#!/usr/bin/perl -w

# Copyright (C) 2004 Hagen Paul Pfeifer <hagen@jauu.net>
#   
# $Id: axfrtrans.pl 13 2004-05-21 17:07:16Z pfeifer $
#   
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software 
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.


use strict;
use Getopt::Std;
use Net::DNS;

# global players
use vars qw($pname %options);


($pname = $0) =~ s#.*/##;


getopts("hxz:n:", \%options) or usage();
usage() if defined $options{h};

axfr_trans($options{z}) if defined $options{z};
find_ns($options{n}) if defined $options{n};

usage();

sub find_ns
{
   my $zone = shift;
   my $res   = Net::DNS::Resolver->new;
   
   my $query = $res->query($zone, "NS");
   if ($query) {
      print "Nameserver for $zone:\n";
      foreach my $rr (grep { $_->type eq 'NS' } $query->answer) {
         print $rr->nsdname . "\n";
      }
   }
   else {
      warn "query failed: ", $res->errorstring, "\n";
   }

   exit 0;
   
}

sub axfr_trans
{
   my $zone  = shift;
   my @res_zone;
   my $res   = Net::DNS::Resolver->new;
   
   my $query = $res->query($zone, "NS");

   if ($query) {
      foreach my $rr (grep { $_->type eq 'NS' } $query->answer) {
         warn "NS => " . $rr->nsdname . "\n";
         $res->nameservers($rr->nsdname);
         if ($options{x}) {
            (my $subzone = $rr->nsdname) =~ s/.*?\.//;
            @res_zone = $res->axfr($subzone);
         } else {
            @res_zone = $res->axfr($zone);
         }
         foreach $rr (@res_zone) {
            $rr->print;
         }
         last if length(@res_zone) >= 1;
      }
   }
   else {
      warn "query failed: ", $res->errorstring, "\n";
   }

   exit 0;
}


sub usage
{
   die << "USAGE"
   $pname [options] [scan type] <zone>
   scan types:
      -z        do a zonetrasnfer for particulare zone
      -n        list all nameserver for zone
   options:
      -x        do a axfr transfer for ns zone (only valid with scantyp "-z")
      -h        display this helpscreen
USAGE
}

