#!/usr/bin/perl -w
use Net::DNS::Nameserver;
use strict;

# Licensed under the GPL v3. Copyright Miek Gieben (c) 2007-2008
# we need to different IP addresses to make this work
my $ns1  = "127.0.0.1";
my $ns2  = "127.0.0.2";
my $port = 15353;

sub reply_handler {
	my ($qname, $qclass, $qtype, $peerhost, $hash) = @_;
	my ($rcode, @ans, @auth, @add, $rdata, $serial);
	my $ttl = 3600;

	# only reply to .nl questions
	print $qname . "\n";
	if ($qname !~ /\.nl$/ or $qtype eq "AAAA") {
	    $rcode = "FORMERR";
	    return ($rcode, \@ans, \@auth, \@add, { aa => 1 });
	}
	if ($qtype eq "SOA") {
	    $serial = `date +%Y%m%d00`; chomp $serial;
	    $rdata = "ns1.$qname postmaster.$qname $serial 21600 7200 604800 3600";
	    push @ans, Net::DNS::RR->new("$qname $ttl $qclass SOA $rdata");
	}
	if ($qtype eq "MX") {
	    $rdata ="100 mx1.$qname";
	    push @ans, Net::DNS::RR->new("$qname $ttl $qclass MX $rdata");

	    $rdata ="100 mx2.$qname";
	    push @ans, Net::DNS::RR->new("$qname $ttl $qclass MX $rdata");
	}
	if ($qtype eq "NS") {
	    $rdata = "ns1.$qname";
	    push @ans, Net::DNS::RR->new("$qname $ttl $qclass NS $rdata");

	    $rdata = "ns2.$qname";
	    push @ans, Net::DNS::RR->new("$qname $ttl $qclass NS $rdata");
	}
	if ($qtype eq "A" or $qtype eq "ANY") {
	    if ($qname =~ /^localhost/) {
	        push @ans, Net::DNS::RR->new("$qname $ttl $qclass A 127.0.0.1");
	    } else {
	        push @ans, Net::DNS::RR->new("$qname $ttl $qclass A $ns1");
	        push @ans, Net::DNS::RR->new("$qname $ttl $qclass A $ns2");
	    }
	}
	$rcode = "NOERROR";
	return ($rcode, \@ans, \@auth, \@add, { aa => 1 });
}

my $ns = Net::DNS::Nameserver->new(
    LocalPort    => $port,
    LocalAddr    => $ns1,
    ReplyHandler => \&reply_handler,
    Verbose      => 1,
    ) || die "couldn't create nameserver object\n";

$ns->main_loop;
