#!/usr/bin/perl
print "Content-type: text/html \n\n";

#################################################################
# Yu.Semenov ITEP	October 2009				#
# <access_log> development					#
# 1. Programm looks for reqests with "///" and makes		#
#    a IP-distribution for these events				#
#    (file <atk_ip.txt>).					#
#	 File format: IP-address number				#
# 2. Program builds a time evolution of <access_log>-file	#
#    These data are put into the file <delta.txt>		#
#	 File format: 						#
#    seconds_number_(10_secs_interval) delta_len		#
# 3. Program calculate a record length distributin and put	#
#    it into the file <rec_leng.txt>.				#
#	 File format: rec_length number				#
# 4. Program register events with more than 2 requests in	#
#    a one second and build a distribution of such requests	#
#	 on IP-addresses (file <atk_dens.txt>)			#
#	 Requests for files with extentions .gif are out of	#
#	 consideration.						#
#	 File format: IP-address number				#
# 5  Total length_of_records & number_of_records for the	#
#    last day	(file <rec_num.txt>)				#
# The selected data for attack cases is written into		#
# DataBase <saturn.access_log> format:				#
# <ip> <date_time> <ID> <full_record> 				#
# $att_type=1 for "/////"; $att_type=2 for >3 recs in sec;	#
# $att_type=3 for very long records				#
#################################################################

use IO::File;
use Socket;
use Time::Local;
use DBI;
use GD;
use graf_dec;   # Sher library
#use Chart::Gnuplot;
use strict;

my @mon=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
my @incl=(".gif",".GIF",".jpg",".ico",".css",".png","robots.txt",".crowl.","yandsearch","spider6","robot06.rambler","robot02.rambler","spider18.yandex","spider55.yandex",".googlebot.com","crawl.baidu.com","dotnetdotcom.org","search.msn.com",".cuil.com","crawl.yahoo.net","bredband.telia.com",".us.archive.org",".naver.jp","av16570.comex.ru",".domolink.tula.net",".setooz.com","gigablast.com","78.41.98.38","78.41.98.166","94.103.89.246","robot07.rambler.ru","robot9.rambler.ru","spider27.picsearch","spider30.picsearch","spider23.picsearch","turbospider.yandex","robot7.rambler.ru","spider09.yandex");
my @forbid=("cgiwrap",'"PUT','"TRACE','"DELETE','"OPTIONS','"PROPFIND');
my $l_len=1;			# init line index
my $n_req=0;
my $n_reqt=0;
my $N_rc=0;
my $name="";
my $marker=-1;
my $duration=0;
my $ipa_count=0;		# number of records in file <atk_ip.txt>
my $s_cur=0;
my $browser="";
my $day_night=86400;		# seconds
my $star_TIME=0;
my $count=0;
my %rec=();			# Hash-array of records
my $delt=0;
my $step=50;			# bin width
my $sum_len=0;			# sum length of all records
my @records=("","","","","","","","","","","");	#records array
my $tot_len=0;			# length from the file beginning
my $tot_rec_count=0;		# record counter in a file
my $local_rec_count=0;		# record counter in a second
my %ipa=();			# IP-hash-array
my %ipb=();			# IP-hash array for .cgi
my %ipd=();			# IP-hash for dense records
my %len=();			# hash for record-lengths
my %ips=();			# hash array of ips{name}
#my %d=();			# hash-array of timescale
my $where=-1;
my $where1=-1;
my ($line,$con,$length,$p1,$p2,$year,$month,$day,$Tst,$path1,$path2,$att_type,$t_bin_num);
my ($sigm,$D,$s_length,$len_avr,$tot_num,$pi,$K,$j,$datetime,$res,$DT0,$stop_TIME,$pppp);
my ($p_cgi,$p_ill);
my ($hours,$minutes,$seconds,$TIME,$date,$date_time,$pr,$p_r,$img,$start_TIME,$cur_TIME);
my ($p_dens,$ip_num,$p,$p_del,$T0,$ip,$p_rec,$ip_adr,$p_len,$p_delta,$pin1,$ptd,$pdel,$counts,$p1_del);
my ($i,$nm,$s,$m,$pin,$key,$delta,$k,$ico,$jpg,$p_reqv,$fl,$M,$len,$num,$pp,$end_TIME,$cnt);
my (@ar,@L,@LL,@LLL,@Mi,@Lm,@R,@lengths,@recds,@MM,@MMM,@NNN,@t_bins,@tm,@ill);
@Mi=("","","","");
$R[0]="";
my $il=0;
for($i=0;$i<1441;$i++)	{$t_bins[$i]=0;
			 $tm[$i]=0;}			# day-distribution initiating
#$pin="/var/log/httpd/access_log";			# Basic log-file
$pin="/home/httpd/htdocs/saturn/attacks/ids/access_log.filt";

# Opening the access_log-file
sysopen(AFIL, $pin, O_RDWR) or die$!;

#################################################################
# Reading of file <access_log>, if there are records for	#
# less than 24 hours, then open a file <access_log.1> and	#
# read necessary additional records				#
#################################################################
print " NN=",$#incl,"\n";					#

while (!eof(AFIL)) {	# Cycle for <access_log>-file ## Development START ###
$line="";								#
$line=readline(AFIL);							#
@ar=split(//,$line);                                            	#
if($#ar>52)	{				# line length control	#
#print "Line=",$line,"\n";						#
$N_rc++;					# Next record		#
@MM=split/\s+/,$line;							#
#########################################################################
# First record in the file <access_log> is a last in time		#
# pool-93-186-96-64.lanta-net.ru - - [22/Nov/2009:04:09:51 +0300]	#
# Date-Time format: [22/Nov/2009:04:09:51 +0300]			#
#########################################################################
$date_time=substr($MM[3],1,20);	# leading [-symbol removing	#
@MMM=split(/\:/,$date_time);					#
if($#MMM==3){			# date terms number control	#
$date=$MMM[0];							#
#if($N_rc==1)	{print " DA=",$date,"\n";}			#
@NNN=split(/\//,$date);						#
if(!(defined$NNN[0]))	{$NNN[0]=1;}				#
$day=$NNN[0];							#
if(!(defined$NNN[1]))	{$NNN[1]=1;}				#
$month=$NNN[1];							#
for($i=0;$i<12;$i++){if($month eq $mon[$i]){$month=$i;}}	#
if(!(defined$NNN[2]))	{$NNN[2]=2;}				#
$year=$NNN[2];							#
#if($N_rc==1)	{print " Y=",$year,"\n";}			#
$year=$year-1900;						#
if(!(defined$MMM[1]))	{$MMM[1]=1;}				#
$hours=$MMM[1];							#
if(!(defined$MMM[2]))	{$MMM[2]=1;}				#
$minutes=$MMM[2];						#
if(!(defined$MMM[3]))	{$MMM[3]=1;}				#
$seconds=$MMM[3];
$cur_TIME=timelocal($seconds,$minutes,$hours,$day,$month,$year);
#print " year=",$year," mon=",$month," day=",$day," hour=",$hours," min=",$minutes," sec=",$seconds,"\n";	#
if($N_rc==1)	{print "S=",$seconds,"\n";}
if($N_rc==1)	{						#####
print "start-time=",$cur_TIME,"\n";				    #
#$end_TIME=$cur_TIME+$day_night;				    #
				}				#####
$fl=0;					# init includings flag	#
for($i=0;$i<$#incl+1;$i++)	{	#####################
if($fl==0)	{			#####################
if(index($line,$incl[$i])>=0){$fl=1;}	#
#print "Flag=",$fl," idx=",index($line,"spider18.yandex")," incl=",$incl[$i],"\n";
		}			#####################
#print "fl=",$fl," I=",$i," LL=",$line,"\n";
				}	#####################
if($fl==0)	{		# There is no useless includings#
#print "indx=",index($line,$incl[$i]),"\nline=",$line,"\n";
#print "F=",$fl," LLL=",$line,"\n";
$records[$n_req]=$line;		# put down the record		#
$rec{$records[$n_req]}=$cur_TIME;	# hash rec		#
#print Fpi $line;						#
$n_req++;							#
		}		# end of IF			#
@ar=split(//,$line);						#
$length=$#ar;			# symbols in current line	#
$sum_len=$sum_len+$length;	# Total record length		#
$n_reqt++;							#
    }				# control number of terms in date
	}			# if for line length control	#
			}	# end of basic WHILE	#############
$stop_TIME=timelocal($seconds,$minutes,$hours,$day,$month,$year);
$start_TIME=$stop_TIME-$day_night;

#print "stop-time=",$stop_TIME," hrs=",$hours," day=",$day," mon=",$month,"\n";
close(AFIL);			# Close file <access_log>	#
#print "useful records=",$n_req," Total length=",$sum_len," Total_recs=",$n_reqt,"\n";

#################################################
# The record array reodering according TIME	#
#################################################

$counts=0;
foreach $key (sort {$rec{$a}<=>$rec{$b}} keys %rec)
{
if($rec{$key}>$start_TIME)	{
$records[$counts]="$key";					# Writing into file <record-array>
# print "rec=",$records[$counts],"\n";
    $counts++;
				}
}
#print "counts=",$counts," rec0=",$records[0],"\n","rec_last=",$records[$counts-1],"\n";

# template for the file <date_time.txt>
$p_rec="/home/httpd/htdocs/saturn/attacks/ids/";

# Opening the array_log-file
#sysopen(AFIL, $pi, O_RDWR) or die$!;

# form the pass for the file <delta.txt>			#
$p_del=$p_rec."delta.txt";	# /home/httpd/htdocs/saturn/attacks/ids/delta.txt
$p1_del="/home/httpd/htdocs/saturn/attacks/ids/delta1.txt";
# Opening the time_log-file	<delta1.txt>			#
sysopen(AFT, $p_del, O_RDWR|O_TRUNC|O_CREAT) or die$!;		#

# form the pass for the file <rec_leng.txt>
$p_len=$p_rec."rec_leng.txt";
# Opening file <rec_leng.txt>: length-number			#
sysopen(Flen, $p_len, O_RDWR|O_TRUNC|O_CREAT) or die$!;		#

# form the pass for the file <atk_ip.txt>
$p_r=$p_rec."atk_ip.txt";		# e:/www/attacks/ids/atk_ip.txt
# Opening file <atk_ip.txt>					#
sysopen(Fipa, $p_r, O_RDWR|O_TRUNC|O_CREAT) or die$!;		#

# the pass for the file <atk_dens.txt>
$p_dens=$p_rec."atk_dens.txt";	# /home/httpd/htdocs/saturn/attacks/ids/atk_dens.txt
# Opening the <atk_dens.txt>					#
sysopen(Fipd, $p_dens, O_RDWR|O_TRUNC|O_CREAT) or die$!;	#
# the pass for the file <cgi.txt>				#
$p_cgi=$p_rec."cgi.txt";	
# Opening the <cgi.txt>						#
sysopen(Fcgi, $p_cgi, O_RDWR|O_TRUNC|O_CREAT) or die$!;		#

# open file <time_length.txt>                                   #
$pppp="/home/httpd/htdocs/saturn/attacks/ids/time_length.txt";
sysopen(Ftml, $pppp, O_RDWR|O_TRUNC|O_CREAT) or die$!;          #

# the pass for the file <illegal.txt>				#
$p_ill=$p_rec."illegal.txt";	# /home/httpd/htdocs/saturn/attacks/ids/illegal.txt
# Opening the <illegal.txt>									#
sysopen(Fil, $p_ill, O_RDWR|O_TRUNC|O_CREAT) or die$!;		#

#########################################
# connect to the DB <saturn.access_log>	#
# Table format:				#
# date_time, ip, brouser, type, attack#	#
#########################################

#$con = DBI->connect("DBI:mysql:host=localhost;database=saturn",
#                    "root",
#                    "yurgur241",
#{PrintError => 0, RaiseError => 1})or die "no connect to DB: $DBI::errstr\n";

#print "useful records=",$n_req," Total length=",$sum_len," Total_recs=","\n";

###########################################################################
# Start of record array development
###########################################################################
#print "Rec_0=",$records[0],"N_rec=",$n_req,"\n";
#print "Rec_fin=",$records[$counts-1],"\n";
###########################################################################
###########################################################################

for($K=0;$K<$counts;$K++)	{			# ARRAY CYCLE #####
$line=$records[$K];					#
#print "K=",$K," line=",$line," R=",$records[$K],"\n";
if($K==0)	{print "R_0=",$line,"\n";}
if($K==$n_req-1){print "R_fin=",$line,"\n";}
@L=split/\s+/,$line;		# Split request line		#
$l_len=$#L;			# number of words in request line#
$p1=$L[8];							#
$p2=$L[9];
$browser=$L[11];		# Fix browser type		#
if(!(defined$browser))	{$browser="-";}				#!!!
#print "browser=",$browser,"\n";
$date_time=substr($L[3],1,20);	# leading [-symbol removing	#
@LL=split(/\:/,$date_time);					#
if($#LL==3){			# date terms number control	#
$date=$LL[0];							#
@LLL=split(/\//,$date);						#
if(!(defined$LLL[0]))	{$LLL[0]=1;}				#
$day=$LLL[0];							#
if(!(defined$LLL[1]))	{$LLL[1]=1;}				#
$month=$LLL[1];							#
for($i=0;$i<12;$i++){if($month eq $mon[$i]){$month=$i;}}	#
if(!(defined$LLL[2]))	{$LLL[2]=2000;}				#
$year=$LLL[2];							#
$year=$year-1900;						#
if(!(defined$LL[1]))	{$LL[1]=1;}				#
$hours=$LL[1];							#
if(!(defined$LL[2]))	{$LL[2]=1;}				#
$minutes=$LL[2];						#
if(!(defined$LL[3]))	{$LL[3]=1;}				#
$seconds=$LL[3];						#
# date-time for MYSQL
$datetime=($year+1900)."-".($month+1)."-".$day." ".$hours.":".$minutes.":".$seconds;
#print "msql_date=",$datetime,"\n";
#if($day eq ""){print "Day=",$day," L=",$line,"\n",$records[$K-1],"\n";}
#############################################################
# Absolute time calculation				    #
#############################################################
# $Tst = date & time of the first record in seconds	    #
$TIME=timelocal($seconds,$minutes,$hours,$day,$month,$year);#############
# The start record development						#
#########################################################################
if($K==0)	{		# The last record analysis first	#
$T0=$TIME;			# The last record time			#
$s_cur=$T0;			# start time seconds			#
$Tst=$T0;			# Start time constant			#
$star_TIME=$TIME;		# start time for array			#
#print "star_Time=",$star_TIME,"\n";
$DT0=$datetime;								#
			}	# end of start time development		#
#########################################################################

@ar=split(//,$line);							#
$length=$#ar;
print Ftml $TIME," ",$length,"\n";		# file time_length.txt



#################################
# %len-hash creating & updating	#
#################################################################
								#
if(exists($len{$length}))	{	# length-hash updating	#
	$len{$length}=$len{$length}+1;				#
#print "len=",$length," n=",$len{$length},"\n";			#
							}	#
else{$len{$length}=1;}			# hash init		#
								#
#################################################################
# Record analysis						#
#################################################################
#print "R0=",$records[0],"\n";					#
#print "K=",$K," r0=",$records[0],"\n";				#
$where=index($line,"////");					#
$where1=-1;
$fl=0;
for($nm=0;$nm<$#forbid+1;$nm++)	{	#####################
if($fl==0)	{			######################	#
$marker=index($line,$forbid[$nm]);	#		#
if(($marker>=0)&&($marker<87))	{$fl=1;
if($L[0] ne "semenov.itep.ru")	{
$ill[$il]=$line;
$il++;
				}
				}	#		#	#
#print "Flag=",$fl," idx="," incl=",$forbid[$i],"\n";		#
		}		######################	#
#print "fl=",$fl," I=",$i," LL=",$line,"\n";			#	#
				}	#####################
if($fl==1)	{$where1=1};		# if GET ...cgi	

if(($where!=-1)||($where1>0))	{	# if there is "////"	#################
@Mi=split/\./,$L[0];		# Name analysis	(is it IP?)			#
@ar=split(//,$L[0]);								#
#print "Where=",$where," leng=",$#ar,"\n";					#

if($#ar<16)	{					############
if($#Mi==3)		{		# Is it IP-address	#########	#
if($Mi[0]!~/\D/)		{	# if number	#################	#	#
	if($Mi[0]>0 && $Mi[0]<255)	{	#####	#	#	#
if($Mi[1]!~/\D/)	{		# if number #####	#	#	#	#
	if($Mi[1]>0 && $Mi[1]<255)	{	#####	#	#	#	#	#
if($Mi[2]!~/\D/)		{	# if number #####	#	#	#	#	#	#
	if($Mi[2]>0 && $Mi[2]<255)	{		#	#	#	#	#	#	#
		if($Mi[3]>0 && $Mi[3]<255)	{	#	#	#	#	#	#	#
		$ips{$L[0]}=$L[0];			#	#	#	#	#	#	#
#print "ips=",$ips{$L[0]},"\n";				#	#	#	#	#	#
						}	#	#	#	#	#	#	#
					}		#	#	#	#	#	#	#
					}	#	#####	#	#	#	#	#	#
					}			#####	#	#	#	#	#
					}			#####	#	#	#	#
					}		#####	#	#	#
					}		#################	#	#
				}			#####	#
			}			#####

if(exists($ips{$L[0]}))	{	#########
	$ip=$ips{$L[0]};		#
#print "IP=",$ip,"\n";			#
			}	#########
else{				# find out if nothing in hash	    #####
#print "Name///=",$L[0],"\n";						#
$ip_adr= gethostbyname($L[0]);						#
if (defined $ip_adr) 	{					####	#
$ip = inet_ntoa($ip_adr);		# IP-adr with "///"	   #	#
			}					####	#
else{$ip="1.1.1.1";}
    }								    #####
#print "ip=",$ip," name=",$L[0],"\n";	# fix IP
$ip_num=ip_to_num($ip);			# IP-number for DB
#########################################################
# %ipa-hash creating for ////-events	& updating	#
#################################################################	
if($where!=-1)	{
$att_type=1;
		}			# Fix attack type			#
if($where1!=-1)	{
$att_type=4;
		}
if($ip eq "194.85.70.31"){$ip="1.1.1.1";}
if($where!=-1)	{
if(exists($ipa{$ip}))	{		# IP-hash updating	########	#
$ipa{$ip}=$ipa{$ip}+1;						       #	#
#print "ipa=",$ip," n=",$ipa{$ip}," type=",$att_type," brwsr=",$browser,"\n";
#$res = $con->prepare("INSERT INTO access_log VALUES('$datetime','$ip_num','$att_type',1,'$browser')") or die "no prepare sql-command: $DBI::errstr\n";
#$res->execute();						       #
			}					  ######	#
else{$ipa{$ip}=1;								#
#$res = $con->prepare("INSERT INTO access_log VALUES('$datetime','$ip_num','$att_type',1,'$browser')") or die "no prepare sql-command: $DBI::errstr\n";
#$res->execute();
	}			# hash init	#	#
		}		# end for WHERE!=-1
if($where1!=-1)	{
if(exists($ipb{$ip}))	{	# IP-hash updating		#####
    $ipb{$ip}=$ipb{$ip}+1;					#
#print "ipb=",$ip," n=",$ipb{$ip}," type=",$att_type," brwsr=",$browser,"\n";
#$res = $con->prepare("INSERT INTO access_log VALUES('$datetime','$ip_num','$att_type',1,'$browser')") or die "no prepare sql-command: $DBI::errstr\n";
#$res->execute();						#
			}					#####

else{$ipb{$ip}=1;		#####
#$res = $con->prepare("INSERT INTO access_log VALUES('$datetime','$ip_num','$att_type',1,'$browser')") or die "no prepare sql-command: $DBI::errstr\n";
#$res->execute();						#
    }		# hash init		#####			#
		}			# end for WHERE1!=-1	#	#
				}	# end of if	for ///	#####
#############################################################

#print	"day=",$day," mon=",$month," Year=",$year," hours=",$hours," min=",$minutes," sec=",$seconds,"\n";

#############################################################

if($TIME>($Tst+$day_night))	{$K=$n_req;
#print "FINISH\n";
				}	# set end of cycle
#print "Tst=",$Tst," TIME=",$TIME,"\n";
#########################################################
# Building the file increments distribution 		#
#########################################################
							#
$t_bin_num=int(($TIME-$star_TIME)/60);			#
# number of 60-second interval				#						
#print " del_T=",($TIME-$star_TIME)," idx=",$t_bin_num," leng=",$length," time=",$TIME,"\n";
if(($t_bin_num<1440) && ($t_bin_num>=0))		#
{$t_bins[$t_bin_num]=$t_bins[$t_bin_num]+ $length;}	#
#########################################################

$delta=$TIME-$s_cur;			# Is this record in the same second?
#print "delta=",$delta," count=",$count," Sec=",$seconds,"\n";
#if($delta<0){print "r=",$line,"\n";}	# if time jump

if($delta==0)	{			# if inside a second	#####
	$recds[$count]=$line;					    #
#print "count=",$count,"\n";					    #
#print "RR=",$recds[$count],"\n";				    #
	$count++;			# records in sec	    #
		}						#####
else	{				# it is not in the same second	#############
	$m=$count-1;			# record counter			    #
	$count=0;								    #
	$s_cur=$TIME;			# renew current second			    #
#print "m=",$m," REC=",$recds[0],"\n";						    #
#############################################################
if($m>3)	{			# if > 3 records in sec		#########	#
for($j=0;$j<$m;$j++)	{							#####	#	#
#print "j=",$j," rec=",$recds[$j],"\n";						#	#	#
@R=split/\s+/,$recds[$j];							#	#	#
@Mi=split/\./,$R[0];			# Is name of IP-form?		#	#	#

if($#Mi==3)	{		#########################################	#	#	#
if($Mi[0]!~/\D/)	{			# if number	#####	#	#	#	#
	if($Mi[0]>0 && $Mi[0]<255)	{	#################	#	#	#	#	#
if($Mi[1]!~/\D/)			{	# if number		#	#	#	#	#	#
	if($Mi[1]>0 && $Mi[1]<255)	{				#	#	#	#	#	#
		if($Mi[2]>0 && $Mi[2]<255)	{	###########	#	#	#	#	#
			if($Mi[3]>0 && $Mi[3]<255)	{    #### #	#	#	#	#	#	#
				$ips{$R[0]}=$R[0];		# #	#	#	#	#	#	#
							}    #### #	#	#	#	#	#	#
						}	###########	#	#	#	#	#	#
					}		#	#	#	#	#	#
							}		#	#	#	#	#	#
					}	#################	#	#	#	#	#
					}	#################################	#	#	#	#
			}				#########	#	#	#
if(exists($ips{$R[0]}))	{$ip=$ips{$R[0]};}	# fix IP			#	#	#
else{								#########	#	#	#
$ip_adr= gethostbyname($R[0]);					#	#	#	#
if (defined $ip_adr) 	{		# If there is IP	#####	#	#	#	#
	$ip = inet_ntoa($ip_adr);	# IP-adr within cluster	#	#	#	#	#
#print "IP=",$ip," name=",$R[0],"\n";					#	#	#	#	#
	$ips{$R[0]}=$ip;			# if it is not in hash	#	#	#	#	#
	$ip_num=ip_to_num($ip);		# IP-number for DB		#	#	#	#	#
if(exists($ipd{$ip}))	{		##### IP-hash updating	#	#	#	#	# !!!
	$ipd{$ip}=$ipd{$ip}+1;		# for $ipd			#	#	#	#	#
#print "ipd=",$ip," n=",$ipd{$ip},"\n";	#	#	#	#	#
			}		##### 		#	#	#	#	#
else{$ipd{$ip}=1;}			# hash init	#	#	#	#	#
			}		#####	#	#	#	#
	}				# end of ELSE $m	#####	#	#	#
			}	########## end of FOR $m ############	#	#
for($i=0; $i<$m; $i++)	{	#####			#	#
	$recds[$i]="";		# clear record array	#	#
	$count=1;	}	#####			#	#
	$recds[0]=$line;					#	#
$att_type=2;			# too many requests in a second	#	#
if(!defined $ip_num) {$ip_num=0;}				#	#
#print "DT=",$datetime," IP=",$ip_num," BRWS=",$browser," m=",$m,"\n";	#
#$res = $con->prepare("INSERT INTO access_log VALUES('$datetime','$ip_num','$att_type','1','$browser')") or die "no prepare sql-command: $DBI::errstr\n";
#$res->execute();													#	#
			}	# end of IF $m>2		#########	#
			}	# end of ELSE not in a second	#############
#############################################################
	    }						# date terms number control
$tm[$t_bin_num]=$star_TIME+$t_bin_num*60+30;
}							# end of basic FOR cycle
print "star_time=",$star_TIME,"\n";
print "st0=",$tm[1]," - ",$t_bins[1]," lst=",$tm[1439]," - ",$t_bins[1439],"\n";

sysopen(AFT1, $p1_del, O_RDWR|O_TRUNC|O_CREAT) or die$!;         #
for($i=0;$i<1440;$i++)	{				# minute intervals
if($tm[$i]==0) {$tm[$i]=$star_TIME+($i)*60+30;}
if($t_bins[$i] eq "")	{$t_bins[$i]=0;}
print AFT1 $tm[$i]," ",$t_bins[$i],"\n";
print AFT $i," ",$t_bins[$i],"\n";			# growth rate evolution <delta.txt>
			}
close(AFT);						# close file <delta.txt>

$ipa_count=0;
foreach $key (reverse sort {$ipa{$a}<=>$ipa{$b}} keys %ipa)
{print Fipa "$key $ipa{$key}\n";			# Writing into file <atk_ip.txt>
	$ipa_count++;
#	print " ipa= $key $ipa{$key}\n";
}
if($ipa_count==0)	{print Fipa "- 0\n";}
#print "IPA-count=",$ipa_count,"\n";
foreach $key (reverse sort {$ipb{$a} <=> $ipb{$b}} keys %ipb)
{print Fcgi "$key $ipb{$key}\n";			# Writing into file <cgi.txt>
#print " ipb= $key $ipb{$key}\n";
}
foreach $key (reverse sort {$ipd{$a} <=> $ipd{$b}} keys %ipd)
{print Fipd "$key $ipd{$key}\n";			# Writing into file <atk_dens.txt>
#print " ipd= $key $ipd{$key}\n";
}
foreach $key (reverse sort {$len{$a} <=> $len{$b}} keys %len)
{print Flen "$key $len{$key}\n";			# Writing to file <rec_leng.txt>
$sum_len=$sum_len+($key*$len{$key});
#print " len= $key $len{$key}\n";
}
close(Flen);
close(Fipa);
close(Fipd);

for($i=0;$i<2000;$i++)	{$lengths[$i]=0;}

# The output file <lengths.txt>
$pp="/home/httpd/htdocs/saturn/attacks/ids/lengths.txt";

# Opening the output file <lengths.txt>
sysopen(FH, $pp, O_RDWR|O_TRUNC|O_CREAT) or die$!;

$p="/home/httpd/htdocs/saturn/attacks/ids/rec_leng.txt";

#################################################
# Average record length and root mean square 	#
# diviation calculation				#
# Opening the input file <rec_leng.txt>		#
#################################################

sysopen(FHH, $p, O_RDWR|O_CREAT) or die$!;
$s_length=0;
$tot_num=0;
while (!eof(FHH)) {		# Cycle for <rec_leng.txt>-file
	$line=readline(FHH);
	@L=split/\s+/,$line;
	$len=$L[0];			# record length
	$num=$L[1];			# number of such records
	$s_length=$s_length+$len*$num;
	$tot_num=$tot_num+$num;
	$k=int($len/$step);
#print "indx=",$k,"\n";
	$lengths[$k]=$lengths[$k]+$num;
}	# end of WHILE
$len_avr=$s_length/$tot_num;
#print "S_len=",$s_length," N_num=",$tot_num," avr=",$len_avr,"\n";
close(FHH);

$s_length=0;
sysopen(FHH, $p, O_RDWR|O_CREAT) or die$!;
while (!eof(FHH)) {		# Cycle for <rec_leng.txt>-file
$line=readline(FHH);
@L=split/\s+/,$line;
$len=$L[0];			# record length
$num=$L[1];			# number of such records
$s_length=$s_length+($len-$len_avr)*($len-$len_avr)*$num;
}	# end of WHILE

$D=$s_length/$tot_num;		# length dispersion
$sigm=sqrt($D);

for($k=0;$k<40;$k++)	{
print FH $k*50," ",$lengths[$k],"\n";
			}
$p_reqv="/home/httpd/htdocs/saturn/attacks/ids/req_num.txt";    # total rec_num & total length
sysopen(Freq, $p_reqv, O_RDWR|O_TRUNC|O_CREAT) or die$!;        #
print Freq "$sum_len $n_req $sigm $len_avr $n_reqt\n";		# writing into the file <req_num.txt>
#print "Records=",$n_req," Sum_len=",$sum_len," D=",$sigm," AVR=",$len_avr,"\n";
close(Freq);
close(FH);
close(FHH);

for($i=0;$i<30;$i++)	{ 					# filling in file <illegal.txt>
if((defined $ill[$i])&& ($ill[$i] ne "")){print	Fil $ill[$i];
    print $ill[$i],"\n";
					}
			}
#print "useful records=",$n_req," Total length=",$sum_len," Total_recs=",$n_reqt,"\n";
print "START=",$DT0," FINISH=",$datetime,"\n";

###################################################
# making up a picture from the file <lengths.txt> #
###################################################

$path1='/home/httpd/htdocs/saturn/attacks/ids/rec_len.png';
# my ($dY,$maxX,$maxY,$Left,$Right,$w,$box,$path,$path_img,$stringX,$stringY,$col_osi,$col_graf,$nonlin,$polygon,$img)=@_;
$img = &vert_diagr(15,600,400,15,'/home/httpd/htdocs/saturn/attacks/ids/lengths.txt',$path1,1,7,3,$img,25);
#print "len_distrib\n";
sysopen(PICTURE, $path1, O_RDWR|O_CREAT) or die("Cannot open file for writing");
binmode PICTURE;
print PICTURE $img->png;
close PICTURE;
#print "useful records=",$n_req," Total length=",$sum_len," Total_recs=",$n_reqt,"\n";
#print "START=",$DT0," FINISH=",$datetime,"\n";

$path2='/home/httpd/htdocs/saturn/attacks/ids/long_req.png';
# my ($dY,$maxX,$maxY,$Left,$Right,$w,$box,$path,$path_img,$stringX,$stringY,$col_osi,$col_graf,$nonlin,$polygon,$img
$img = &vert_diagr(15,600,400,15,'/home/httpd/htdocs/saturn/attacks/ids/long_req.txt',$path2,1,7,3,$img,25);
#print "long_req_distrib\n";
sysopen(PICTURE,$path2, O_RDWR|O_CREAT) or die("Cannot open file for writing");
binmode PICTURE;
print PICTURE $img->png;
close PICTURE;

use Chart::Gnuplot;

# Plot the data set on the chart
print "GNUPLOT\n";
my $chart = Chart::Gnuplot->new(
output => "/home/semenov/delta1.ps"
);

my $dataSet=Chart::Gnuplot::DataSet->new(
datafile => "/home/httpd/htdocs/saturn/attacks/ids/delta.txt",
style => "boxes"
);

$chart->plot2d($dataSet);
#print "FINISH\n";
do "/home/crontab_files/error.pl";		# start of error.pl (restored at 26-12-2019)
exit;

#########################################
sub ip_to_num
{
#########################################
# IP-address to a number conversion	#
#########################################
my @Lm;
my ($s)=@_;
@Lm=split/\./,$s;
if($#Lm < 3) {return -1;}
else    { return ((((($Lm[0]<<8)+$Lm[1])<<8)+$Lm[2])<<8)+$Lm[3];
		}
}
exit;
#END { }
