bgpblist/sbin/bgpblacklistd

93 lines
2.4 KiB
Plaintext
Raw Normal View History

2024-07-17 17:04:23 +00:00
#!/usr/bin/php
<?php
if ( !file_exists("/opt/bgpblist/etc/config.ini") ) {
echo "ERROR: no config file\n";
2024-07-17 17:40:56 +00:00
copy("/opt/bgpblist/etc/default/config.ini","/opt/bgpblist/etc/config.ini");
2024-07-17 17:04:23 +00:00
echo "INFO: file created, edit it before next start\n";
die();
}
logtofile("PROCESS_START");
$conf=parse_ini_file("/opt/bgpblist/etc/config.ini",TRUE);
$customer=$conf["customer"]["cust_uuid"];
$logfile=$conf["syslog"]["logfile"];
declare(ticks = 1);
pcntl_signal(SIGINT,"sig_handler");
pcntl_signal(SIGTERM,"sig_handler");
pcntl_signal(SIGHUP,"sig_handler");
$prev_bad=array();
clean_routes();
while(TRUE) {
$cycle_beg=microtime(TRUE);
logtofile("CYCLE_BEG");
$raw=@file_get_contents('https://hosts.funil.de/custom/'.$customer.'/csubscr_aggr.txt');
if ( strlen($raw) == 0 ) {
logtofile("EMPTY_REM");
$sleeptime=10;
logtofile("SLEEP: ".$sleeptime."s");
sleep($sleeptime);
continue;
}
$tmp=explode("\n",$raw);
$bad_nets=array();
foreach($tmp as $k => $v) {
if ( strlen(trim($v)) == 0 ) {
continue;
}
if ( ip2long(preg_replace("/\/.*/","",$v)) == 0 || preg_match("/:/",$v) ) {
unset($tmp[$k]);
}
list($net,$mask)=explode("/",$v);
if ( $mask <= 19 ) {
unset($tmp[$k]);
}
$bad_nets[$v]=TRUE;
}
if ( count($bad_nets) == 0 ) {
logtofile("EMPTY_LST");
$sleeptime=10;
logtofile("SLEEP: ".$sleeptime."s");
sleep($sleeptime);
continue;
}
foreach(array_keys($bad_nets) as $k) {
if ( !array_key_exists($k,$prev_bad) ) {
passthru("ip route add prohibit ".$k);
logtofile("ROUTE + ".$k);
}
}
foreach(array_keys($prev_bad) as $k) {
if ( !array_key_exists($k,$bad_nets) ) {
passthru("ip route del prohibit ".$k);
logtofile("ROUTE - ".$k);
}
}
$prev_bad=$bad_nets;
gc_collect_cycles();
$cycle_end=microtime(TRUE);
logtofile("CYCLE_END");
$cycle_len=number_format($cycle_end-$cycle_beg,3,".","");
logtofile("CYCLE_LEN: ".$cycle_len."s");
$sleeptime=30*ceil($cycle_len);
if ( $sleeptime < 10 ) { $sleeptime=10; }
if ( $sleeptime > 300 ) { $sleeptime=300; }
logtofile("SLEEP: ".$sleeptime."s");
sleep($sleeptime);
}
function logtofile($text) {
global $logfile;
$data=gmdate("Y-m-d H:i:s")." | ".$text."\n";
file_put_contents($logfile,$data,FILE_APPEND);
}
function sig_handler($sig) {
clean_routes();
exit_die();
}
function clean_routes() {
logtofile("CLEANING_RT");
passthru("ip route show | grep '^prohibit ' | awk '{print $2}' | xargs -I '{}' ip route del prohibit '{}'");
}
function exit_die() {
logtofile("EXITING...");
die();
}