#!/usr/bin/perl -w
# $Id: portsentry-build-ignore-file,v 1.9 2004/09/30 18:38:13 agx Exp $
#
# build portsentry.ignore from portsentry.ignore.static and
# all other IPs found on this host
#
# by Guido Guenther <agx@debian.org>
#
# it was inspired by ignore.csh provided with the original
# portsentry package (see /usr/share/doc/portsentry/examples/ignore.csh)

use strict;
use File::Temp qw( tempfile );

my $etcdir="/etc/portsentry";
my $static_file="$etcdir/portsentry.ignore.static";# static IPs
my $ignore_file="$etcdir/portsentry.ignore";       # build this one
my $tmpdir="/var/lib/portsentry";
my $ip_re='[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}';
my $ipnm_re='[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(/[0-9]{1,2})?';

(my $th, my $tfname) = tempfile("portsentry.ignore.static.XXXXXX", DIR => $tmpdir);
# build file header
print $th "# $ignore_file: Contains all IPs portsentry(8)
\#                                    will never block.
\#
\# This file was generated by $0.
\# DO NOT EDIT - edit $static_file instead and use
\# \"/etc/init.d/portsentry restart\" to reload the configuration.\n\n";

# insert $static_file:
open( Q, "$static_file") || die "Cannot open $static_file: $!\n";
my @static_ips = grep( /^\s*$ipnm_re\s*(#|$)/, <Q>);
close(Q);
print $th "\# IPs from $static_file:\n";
print $th @static_ips;

# insert dynamic IPs
print $th "\n\# dynamically fetched IPs(via ifconfig -a):\n";
my @dyn_ips = grep( /inet/, `LC_ALL=C /sbin/ifconfig -a`);
foreach my $i (@dyn_ips) {
	if ($i =~ /addr:($ip_re)/) {
# XXX: this is too lax, need to check subnet matches here too
	    print $th "$1\n" if !grep( /^\s*$1[\s#]/, @static_ips);
	}
}

close( $th ) || die "Cannot close $tfname: $!\n";
chmod( 0644, $tfname );
exec( "/bin/mv","-f", $tfname, $ignore_file) || die "moving $ignore_file into place failed: $?\n";
