#!/usr/bin/perl

=head1 NAME

pfdns - PacketFence DNS server

=head1 SYNOPSIS

pfdns [options]

 Options:
   -d      Daemonize
   -h      Help
   -v      Verbose

=cut

use warnings;
use strict;
use Readonly;
use File::Basename qw(basename);
use Getopt::Std;
use Pod::Usage;
use POSIX qw(:signal_h);
use Try::Tiny;
use Net::DNS::Nameserver;
use NetAddr::IP;

BEGIN {
    # log4perl init
    use constant INSTALL_DIR => '/usr/local/pf';
    use lib INSTALL_DIR . "/lib";
    use pf::log(service => 'pfdns');
}

use pf::config;
use pf::config::cached;
use pf::util;
use pf::services::util;
use pf::pfdns::constants;
use pf::CHI;

# initialization
# --------------
# assign process name (see #1464)

# init signal handlers
our $PROGRAM_NAME = $0 = basename($0);

my $logger = Log::Log4perl->get_logger( basename($PROGRAM_NAME) );

POSIX::sigaction(
    &POSIX::SIGHUP,
    POSIX::SigAction->new(
        'normal_sighandler', POSIX::SigSet->new(), &POSIX::SA_NODEFER
    )
) or $logger->logdie("pfdns: could not set SIGHUP handler: $!");

POSIX::sigaction(
    &POSIX::SIGTERM,
    POSIX::SigAction->new(
        'normal_sighandler', POSIX::SigSet->new(), &POSIX::SA_NODEFER
    )
) or $logger->logdie("pfdns: could not set SIGTERM handler: $!");

POSIX::sigaction(
    &POSIX::SIGINT,
    POSIX::SigAction->new(
        'normal_sighandler', POSIX::SigSet->new(), &POSIX::SA_NODEFER
    )
) or $logger->logdie("pfdns: could not set SIGINT handler: $!");


my %args;
getopts( 'dhi:', \%args );

my $daemonize = $args{d};

pod2usage( -verbose => 1 ) if ( $args{h} );

our $RUNNING = 1;


# standard signals and daemonize
daemonize($PROGRAM_NAME) if ($daemonize);

my @ip_addr;
my @routed_inline_nets_named;
my @routed_isolation_nets_named;
my @routed_registration_nets_named;

my $CHI_CACHE = pf::CHI->new( namespace => 'pfdns' );

Readonly::Scalar our $TTL                => '15';
Readonly::Scalar our $HTTPS_PORT         => '443';
Readonly::Scalar our $HTTP_PORT         => '80';

foreach my $interface ( $cached_pf_config->GroupMembers("interface") ) {
    my $ip = $Config{$interface}{'vip'} || $Config{$interface}{'ip'};
    if ( defined ($Config{$interface}{'enforcement'}) && ( ($Config{$interface}{'enforcement'} eq $IF_ENFORCEMENT_VLAN) || is_type_inline($Config{$interface}{'enforcement'}) ) ) {
        push @ip_addr, $ip;
    }
}

foreach my $network ( keys %ConfigNetworks ) {
    if ( $ConfigNetworks{$network}{'named'} eq 'enabled' ) {
        if ( pf::config::is_network_type_inline($network) ) {
            my $inline_obj = NetAddr::IP->new( $network, $ConfigNetworks{$network}{'netmask'} );
            push @routed_inline_nets_named, $inline_obj;
        } elsif ( pf::config::is_network_type_vlan_isol($network) ) {
            my $isolation_obj = NetAddr::IP->new( $network, $ConfigNetworks{$network}{'netmask'} );
            push @routed_isolation_nets_named, $isolation_obj;

        } elsif ( pf::config::is_network_type_vlan_reg($network) ) {
            my $registration_obj = NetAddr::IP->new( $network, $ConfigNetworks{$network}{'netmask'} );
            push @routed_registration_nets_named, $registration_obj;
        }
    }
}


my $ns = new Net::DNS::Nameserver(
    LocalAddr       => [@ip_addr],
    LocalPort    => 53,
    ReplyHandler => \&response_handler,
    Verbose      => 0
    ) || die "couldn't create nameserver object\n";


while($RUNNING) {
    $ns->loop_once(10);
}

END {
    deletepid("pfdns") unless $args{h};
}

sub response_handler {
    my ($qname, $qclass, $qtype, $peerhost,$query,$conn) = @_;
    pf::config::cached::ReloadConfigs();
    my $ip = new NetAddr::IP::Lite clean_ip($peerhost);
    foreach my $network (@routed_registration_nets_named) {
        if ($network->contains($ip)) {
           return  regzone($qname, $qclass, $qtype, $peerhost,$query,$conn);
        }
    }
    foreach my $network (@routed_isolation_nets_named) {
        if ($network->contains($ip)) {
           # Should be different for isolation network.
           return  isolzone($qname, $qclass, $qtype, $peerhost,$query,$conn);
        }
    }

    foreach my $network (@routed_inline_nets_named) {
        if ($network->contains($ip)) {
           # Should be different for inline
           return  regzone($qname, $qclass, $qtype, $peerhost,$query,$conn);
        }
    }
}

sub regzone {
    my ($qname, $qclass, $qtype, $peerhost,$query,$conn) = @_;
    my ($rcode, @ans, @auth, @add);
    my $_EXIT_CODE_EXISTS = "1";

    $logger->trace("Requested Domain: ".$qname);
    if ($qtype eq "A") {
        if ( ($qname =~ /$OAUTH::ALLOWED_OAUTH_DOMAINS/o && $OAUTH::ALLOWED_OAUTH_DOMAINS ne '') || ($qname =~ /$PASSTHROUGH::ALLOWED_PASSTHROUGH_DOMAINS/o && $PASSTHROUGH::ALLOWED_PASSTHROUGH_DOMAINS ne '') ) {
            my ($ttl, $rdata);
            my $res   = Net::DNS::Resolver->new;
            my $query = $CHI_CACHE->compute($qname, sub { $res->search($qname) });
            if ($query) {
                foreach my $rr ($query->answer) {
                    next unless $rr->type eq "A";
                    my $ip = $rr->address;
                    my $cmd = "LANG=C sudo ipset --add pfsession_passthrough $ip,$HTTP_PORT 2>&1";
                    my @lines  = pf_run($cmd, , accepted_exit_status => [ $_EXIT_CODE_EXISTS ]);
                    $cmd = "LANG=C sudo ipset --add pfsession_passthrough $ip,$HTTPS_PORT 2>&1";
                    @lines  = pf_run($cmd, , accepted_exit_status => [ $_EXIT_CODE_EXISTS ]);
                    ($ttl, $rdata) = ($TTL, $rr->address);
                }
            }

            my $rr = new Net::DNS::RR("$qname $ttl $qclass $qtype $rdata");
            push @ans, $rr;
            $rcode = "NOERROR";
        }
        elsif ($query =~ /$Config{'general'}{'hostname'}.".".$Config{'general'}{'domain'}/) {
            my ($ttl, $rdata) = ($TTL, $conn->{sockhost});
            my $rr = new Net::DNS::RR("$qname $ttl $qclass $qtype $rdata");
            push @ans, $rr;
            $rcode = "NOERROR";
        } else {
            my ($ttl, $rdata) = ($TTL, $Config{'general'}{'hostname'}.".".$Config{'general'}{'domain'}.".");
            my $rr = new Net::DNS::RR("$qname $ttl IN CNAME $rdata");
            my $rr2 = new Net::DNS::RR("$rdata $ttl $qclass $qtype $conn->{sockhost}");
            push @ans, $rr;
            push @ans, $rr2;
            $rcode = "NOERROR";
        }
    }else{
        $rcode = "NXDOMAIN";
    }

    # mark the answer as authoritive (by setting the 'aa' flag
    return ($rcode, \@ans, \@auth, \@add, { aa => 1 });
}

sub isolzone {
    my ($qname, $qclass, $qtype, $peerhost,$query,$conn) = @_;
    my ($rcode, @ans, @auth, @add);
    my $_EXIT_CODE_EXISTS = "1";

    $logger->trace("Requested Domain: ".$qname);
    if ($qtype eq "A") {
        my ($ttl, $rdata) = ($TTL, $conn->{sockhost});
        my $rr = new Net::DNS::RR("$qname $ttl $qclass $qtype $rdata");
        push @ans, $rr;
        $rcode = "NOERROR";
    }else{
        $rcode = "NXDOMAIN";
    }

    # mark the answer as authoritive (by setting the 'aa' flag
    return ($rcode, \@ans, \@auth, \@add, { aa => 1 });
}

sub normal_sighandler {
    $RUNNING = 0;
    $logger->debug( "pfdns: caught SIG" . $_[0] . " - terminating" );
}


=back

=head1 COPYRIGHT

Copyright (C) 2007-2013 Inverse inc.

=head1 LICENSE

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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
USA.

=cut

