#!/usr/bin/perl

=head1 NAME

pfmon - ARP listener and maintenance threads

=head1 SYNOPSIS

pfmon [options]

 Options:
   -d      Daemonize
   -h      Help
   -v      Verbose

=cut

use warnings;
use strict;
use Getopt::Std;
use Net::Pcap 0.16;
use File::Basename qw(basename);
use POSIX qw(:signal_h pause);
use Pod::Usage;

#pf::log must always be initilized first
BEGIN {
    # log4perl init
    use constant INSTALL_DIR => '/usr/local/pf';
    use lib INSTALL_DIR . "/lib";
    use pf::log(service => 'pfmon');
}

use pf::accounting qw(acct_maintenance);
use pf::config;
use pf::config::cached;
use pf::inline::accounting;
use pf::iplog;
use pf::locationlog;
use pf::node;
use pf::services;
use pf::traplog;
use pf::util;
use pf::services::util;
use pf::violation qw(violation_maintenance);

# initialization
# --------------
# assign process name (see #1464)
our $PROGRAM_NAME = $0 = basename($0);

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

$SIG{HUP} = \&normal_sighandler;
$SIG{INT} = \&normal_sighandler;
$SIG{TERM} = \&normal_sighandler;
$SIG{ALRM} = sub {};

my %args;
getopts( 'dhvr', \%args );

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

my $daemonize = $args{d};
my $verbose   = $args{v};
my $restart   = $args{r};
our $running = 1;

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

# run the cleanup
cleanup();

END {
    if ( !$args{h} ) {
        deletepid();
        $logger->info("stopping pfmon");
    }
}

exit(0);

=head1 SUBROUTINES

=over

=item arp_detector

Listens to ARP traffic and logs.

In PacketFence 3.0 we dropped support for ARP mode. This method has been
severely crippled as part of that work. However it has been kept around since
we might introduce ARP surveillance in the future.

=cut
sub arp_detector {
    my ($eth) = @_;
    my $logger = Log::Log4perl::get_logger('pfmon::arp_detector');
    Log::Log4perl::MDC->put( 'tid', threads->self->tid() );

    my ( $filter_t, $net, $mask, $opt, $err );
    $opt = 1;

    my $pcap_t = Net::Pcap::pcap_open_live( $eth, 1500, 1, 0, \$err );
    my $filter = arp_filter();
    if ( ( Net::Pcap::lookupnet( $eth, \$net, \$mask, \$err ) ) == -1 ) {
        $logger->logdie("Net::Pcap::lookupnet failed. Error was $err");
    }
    if ( ( Net::Pcap::compile( $pcap_t, \$filter_t, $filter, $opt, $net ) )
        == -1 )
    {
        $logger->logdie("Unable to compile filter string '$filter'");
    }
    Net::Pcap::setfilter( $pcap_t, $filter_t );
    Net::Pcap::loop( $pcap_t, -1, \&process_packet, $eth );
}

sub process_packet {
    my ( $user_data, $header, $packet ) = @_;
    listen_arp($packet) if ($packet);
}

=item listen_arp

Listens to ARP traffic and logs.

In PacketFence 3.0 we dropped support for ARP mode.
This method has been severely crippled as part of that work.
However it has been kept around since we might introduce ARP surveillance in the future.

=cut
sub listen_arp {
    my ( $type, $srcmac, $srcip, $destmac, $destip ) = &decode(@_);
    # below was commented as part of the interface.gateway removal
    # if re-implementation required, go through conf/networks.conf to determine if it's internal or not
    #return if ( !isinternal($srcip) );

    if ( $type == 1 ) {
        $logger->debug(
            "ARP who-has $destip tell $srcip  $srcmac $srcip $destmac $destip"
        );
        # commented as part of the interface.gateway removal
        # if re-implementation required, go through conf/networks.conf to fetch the gateway for a network
        #my $gip = ip2gateway($srcip);
        #if ( valid_ip($srcip) && valid_ip($gip) && ( $srcip eq $gip ) ) {
            if (   $destmac =~ /ff:ff:ff:ff:ff:ff/i
                || $destmac =~ /00:00:00:00:00:00/i )
            {
                $logger->info(
                    "broadcast arp request from router for $destip - re-trapping all nodes"
                );
            } elsif ( !grep( { $_ eq $monitor_int } @listen_ints ) ) {
                $logger->info(
                    "flooded arp request from router for $destmac ($destip) - re-trapping all nodes"
                );
            } else {
                $logger->debug(
                    "arp request from router for $destmac ($destip)");
                return;
            }
        #}

    } elsif ( $type == 2 ) {
        $logger->debug("ARP $srcip is-at $srcmac $srcmac $srcip $destmac $destip");
    }
}

sub cleanup {
    while ($running) {
        # run these functions every $maintenance_interval
        eval {
            $logger->info("running expire check");
            iplog_cleanup( $Config{'expire'}{'iplog'} )
              if ( $Config{'expire'}{'iplog'} );
            locationlog_cleanup( $Config{'expire'}{'locationlog'} )
              if ( $Config{'expire'}{'locationlog'} );
            node_cleanup( $Config{'expire'}{'node'} )
              if ( $Config{'expire'}{'node'} );
            traplog_cleanup( $Config{'expire'}{'traplog'} )
              if ( $Config{'expire'}{'traplog'} );

            purge_cache('httpd.admin')
              if ( isenabled($Config{'expire'}{'httpd_admin'}) );

            purge_cache('httpd.portal')
              if ( isenabled($Config{'expire'}{'httpd_portal'}) );

            $logger->info("checking registered nodes for expiration");
            nodes_maintenance();

            $logger->info("checking violations for expiration");
            violation_maintenance();

            $logger->info("checking accounting data for potential bandwidth abuse");
            if (isenabled($Config{'inline'}{'accounting'})) {
                inline_accounting_maintenance($Config{'inline'}{'level3_accounting_session_timeout'});
            }
            acct_maintenance();

            #reload all cached configs after each iteration
            pf::config::cached::ReloadConfigs();
        };
        if ($@) {
            $logger->error("Error restarting pfmon: $@");
            deletepid();
            exec "${install_dir}/sbin/pfmon", @ARGV;
        }
        alarm $Config{'general'}{'maintenance_interval'};
        pause;
    }
}

sub purge_cache {
    my ($namespace) = @_;
    my $cache = pf::CHI->new( namespace => $namespace );
    for my $key ($cache->get_keys) {
        $cache->remove($key) if $cache->exists_and_is_expired($key);
    }
}

=item decode

Encapsulate the ARP packet decoding.

=cut
sub decode {
    my $pkt = shift;

    my ($m1, $m2, $proto, $hwas, $pas, $hwal, $pal, $opcode, $sha, $spa, $tha, $tpa)
        = unpack( 'H12H12nnnCCnH12NH12N', $pkt );

    return ($opcode, clean_mac($sha), int2ip($spa), clean_mac($tha), int2ip($tpa));
}


sub normal_sighandler {
    $running = 0;
}

=back

=head1 AUTHOR

Inverse inc. <info@inverse.ca>

Minor parts of this file may have been contributed. See CREDITS.

=head1 COPYRIGHT

Copyright (C) 2005-2013 Inverse inc.

Copyright (C) 2005 Kevin Amorin

Copyright (C) 2005 David LaPorte

=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

