GeoIP: Add lookup function for convenience
[ipfire-2.x.git] / html / cgi-bin / logs.cgi / firewalllogip.dat
1 #!/usr/bin/perl
2 #
3 # SmoothWall CGIs
4 #
5 # This code is distributed under the terms of the GPL
6 #
7 # JC HERITIER 
8 # page inspired from the initial firewalllog.dat
9 #
10 # Modified for IPFire by Christian Schmidt
11 #                           and Michael Tremer (www.ipfire.org)
12
13 use strict;
14 use Getopt::Std;
15
16 # enable only the following on debugging purpose
17 #use warnings;
18 #use CGI::Carp 'fatalsToBrowser';
19
20 require '/var/ipfire/general-functions.pl';
21 require "${General::swroot}/geoip-functions.pl";
22 require "${General::swroot}/lang.pl";
23 require "${General::swroot}/header.pl";
24
25 use POSIX();
26
27 my %cgiparams=();
28 my %settings=();
29 my $pienumber;
30 my $otherspie;
31 my $showpie;
32 my $sortcolumn;
33 my $errormessage = '';
34
35 $cgiparams{'pienumber'} = 10;
36 $cgiparams{'otherspie'} = 1;
37 $cgiparams{'showpie'} = 1;
38 $cgiparams{'sortcolumn'} = 1;
39
40 my @shortmonths = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
41         'Sep', 'Oct', 'Nov', 'Dec' );
42 my @longmonths = ( $Lang::tr{'january'}, $Lang::tr{'february'}, $Lang::tr{'march'},
43         $Lang::tr{'april'}, $Lang::tr{'may'}, $Lang::tr{'june'}, $Lang::tr{'july'}, $Lang::tr{'august'},
44         $Lang::tr{'september'}, $Lang::tr{'october'}, $Lang::tr{'november'},
45         $Lang::tr{'december'} );
46
47 my @now = localtime();
48 my $dow = $now[6];
49 my $doy = $now[7];
50 my $tdoy = $now[7];
51 my $year = $now[5]+1900;
52
53 $cgiparams{'DAY'} = $now[3];
54 $cgiparams{'MONTH'} = $now[4];
55 $cgiparams{'ACTION'} = '';
56
57 &General::readhash("${General::swroot}/fwlogs/ipsettings", \%settings);
58 if ($settings{'pienumber'} != 0) { $cgiparams{'pienumber'} = $settings{'pienumber'} };
59 if ($settings{'otherspie'} != 0) { $cgiparams{'otherspie'} = $settings{'otherspie'} };
60 if ($settings{'showpie'} != 0) { $cgiparams{'showpie'} = $settings{'showpie'} };
61 if ($settings{'sortcolumn'} != 0) { $cgiparams{'sortcolumn'} = $settings{'sortcolumn'} };
62
63 &Header::getcgihash(\%cgiparams);
64 if ($cgiparams{'pienumber'} != 0) { $settings{'pienumber'} = $cgiparams{'pienumber'} };
65 if ($cgiparams{'otherspie'} != 0) { $settings{'otherspie'} = $cgiparams{'otherspie'} };
66 if ($cgiparams{'showpie'} != 0) { $settings{'showpie'} = $cgiparams{'showpie'} };
67 if ($cgiparams{'sortcolumn'} != 0) { $settings{'sortcolumn'} = $cgiparams{'sortcolumn'} };
68
69 if ($cgiparams{'ACTION'} eq $Lang::tr{'save'})
70 {
71         &General::writehash("${General::swroot}/fwlogs/ipsettings", \%settings);
72 }
73
74 my $start = -1;
75 if ($ENV{'QUERY_STRING'} && $cgiparams{'ACTION'} ne $Lang::tr{'update'})
76 {
77         my @temp = split(',',$ENV{'QUERY_STRING'});
78         $start = $temp[0];
79         $cgiparams{'MONTH'} = $temp[1];
80         $cgiparams{'DAY'} = $temp[2];
81 }
82
83 if (!($cgiparams{'MONTH'} =~ /^(0|1|2|3|4|5|6|7|8|9|10|11)$/) ||
84     !($cgiparams{'DAY'} =~ /^(1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)$/))
85 {
86         $cgiparams{'DAY'} = $now[3];
87         $cgiparams{'MONTH'} = $now[4];
88 }
89 elsif($cgiparams{'ACTION'} eq '>>')
90 {
91         my @temp_then=();
92         my @temp_now = localtime(time);
93         $temp_now[4] = $cgiparams{'MONTH'};
94         $temp_now[3] = $cgiparams{'DAY'};
95         @temp_then = localtime(POSIX::mktime(@temp_now) + 86400);
96         ## Retrieve the same time on the next day -
97         ## 86400 seconds in a day
98         $cgiparams{'MONTH'} = $temp_then[4];
99         $cgiparams{'DAY'} = $temp_then[3];
100 }
101 elsif($cgiparams{'ACTION'} eq '<<')
102 {
103         my @temp_then=();
104         my @temp_now = localtime(time);
105         $temp_now[4] = $cgiparams{'MONTH'};
106         $temp_now[3] = $cgiparams{'DAY'};
107         @temp_then = localtime(POSIX::mktime(@temp_now) - 86400);
108         ## Retrieve the same time on the previous day -
109         ## 86400 seconds in a day
110         $cgiparams{'MONTH'} = $temp_then[4];
111         $cgiparams{'DAY'} = $temp_then[3];
112 }
113
114 if (($cgiparams{'DAY'} ne $now[3]) || ($cgiparams{'MONTH'} ne $now[4]))
115 {
116         my @then = ();
117         if ( (  $cgiparams{'MONTH'} eq $now[4]) && ($cgiparams{'DAY'} > $now[3]) ||
118              ( $cgiparams{'MONTH'} > $now[4] ) ) {
119                 @then = localtime(POSIX::mktime( 0, 0, 0, $cgiparams{'DAY'}, $cgiparams{'MONTH'}, $year - 1901 ));
120         } else {
121                 @then = localtime(POSIX::mktime( 0, 0, 0, $cgiparams{'DAY'}, $cgiparams{'MONTH'}, $year - 1900 ));
122         }
123         $tdoy = $then[7];
124         my $lastleap=($year-1)%4;
125         if ($tdoy>$doy) {
126                 if ($lastleap == 0 && $tdoy < 60) {
127                         $doy=$tdoy+366;
128                 } else {
129                         $doy=$doy+365;
130                 }
131         }
132 }
133
134 my $datediff=0;
135 my $dowd=0;
136 my $multifile=0;
137 if ($tdoy ne $doy) {
138         $datediff=int(($doy-$tdoy)/7);
139         $dowd=($doy-$tdoy)%7;
140         if (($dow-$dowd)<1) {
141                 $datediff=$datediff+1;
142         }
143         if (($dow-$dowd)==0) {
144                 $multifile=1;
145         }
146 }
147
148 my $monthstr = $shortmonths[$cgiparams{'MONTH'}];
149 my $longmonthstr = $longmonths[$cgiparams{'MONTH'}];
150 my $day = $cgiparams{'DAY'};
151 my $daystr='';
152 if ($day <= 9) {
153         $daystr = " $day"; }
154 else {
155         $daystr = $day;
156 }
157
158 my $skip=0;
159 my $filestr='';
160 if ($datediff==0) {
161         $filestr="/var/log/messages";
162 } else {
163        $filestr="/var/log/messages.$datediff";
164        $filestr = "$filestr.gz" if -f "$filestr.gz";
165 }
166
167 if (!(open (FILE,($filestr =~ /.gz$/ ? "gzip -dc $filestr |" : $filestr)))) {
168         $errormessage = "$Lang::tr{'date not in logs'}: $filestr $Lang::tr{'could not be opened'}";
169         $skip=1;
170         # Note: This is in case the log does not exist for that date
171 }
172 my $lines = 0;
173 my @log=();
174
175 if (!$skip)
176 {
177         while (<FILE>)
178         {
179                 if (/(^${monthstr} ${daystr} ..:..:..) [\w\-]+ kernel:.*(IN=.*)$/) {
180                         $log[$lines] = $_;
181                         $lines++;
182                 }
183         }
184         close (FILE);   
185 }
186
187 $skip=0;
188 if ($multifile) {
189         $datediff=$datediff-1;
190         if ($datediff==0) {
191                 $filestr="/var/log/messages";
192         } else {
193                 $filestr="/var/log/messages.$datediff";
194                 $filestr = "$filestr.gz" if -f "$filestr.gz";
195         }
196         if (!(open (FILE,($filestr =~ /.gz$/ ? "gzip -dc $filestr |" : $filestr)))) {
197                 $errormessage="$Lang::tr{'date not in logs'}: $filestr $Lang::tr{'could not be opened'}";
198                 $skip=1;
199         }
200         if (!$skip) {
201                 while (<FILE>) {
202                         if (/(^${monthstr} ${daystr} ..:..:..) [\w\-]+ kernel:.*(IN=.*)$/) {
203                                 $log[$lines] = $_;
204                                 $lines++;
205                         }
206                 }
207                 close (FILE);
208         }
209 }
210
211 my $MODNAME="fwlogs";
212
213 &Header::showhttpheaders();
214 &Header::openpage($Lang::tr{'firewall log ip'}, 1, '');
215 &Header::openbigbox('100%', 'left', '', $errormessage);
216
217
218 if ($errormessage) {
219         &Header::openbox('100%', 'left', $Lang::tr{'error messages'});
220         print "<font class='base'>$errormessage&nbsp;</font>\n";
221         &Header::closebox();
222 }
223
224 &Header::openbox('100%', 'left', "$Lang::tr{'settings'}");
225
226 print <<END
227 <form method='post' action='$ENV{'SCRIPT_NAME'}'>
228 <table width='100%'>
229 <tr>
230         <td width='10%' class='base'>$Lang::tr{'month'}:&nbsp;</td>
231         <td width='10%'>
232         <select name='MONTH'>
233 END
234 ;
235 my $month;
236 for ($month = 0; $month < 12; $month++)
237 {
238         print "\t<option ";
239         if ($month == $cgiparams{'MONTH'}) {
240                 print "selected='selected' "; 
241         }
242         print "value='$month'>$longmonths[$month]</option>\n";
243 }
244 print <<END
245         </select>
246         </td>
247         <td width='10%' class='base' align='right'>&nbsp;$Lang::tr{'day'}:&nbsp;</td>
248         <td width='40%'>
249         <select name='DAY'>
250 END
251 ;
252 for ($day = 1; $day <= 31; $day++) 
253 {
254         print "\t<option ";
255         if ($day == $cgiparams{'DAY'}) {
256                 print "selected='selected' "; 
257         }
258         print "value='$day'>$day</option>\n";
259 }
260
261 if( $cgiparams{'pienumber'} != 0){$pienumber=$cgiparams{'pienumber'};}
262 if( $cgiparams{'otherspie'} != 0){$otherspie=$cgiparams{'otherspie'};}
263 if( $cgiparams{'showpie'} != 0){$showpie=$cgiparams{'showpie'};}
264 if( $cgiparams{'sortcolumn'} != 0){$sortcolumn=$cgiparams{'sortcolumn'};}
265
266 print <<END
267 </select>
268 </td>
269 <td width='5%'  align='center'><input type='submit' name='ACTION' title='$Lang::tr{'day before'}' value='&lt;&lt;' /></td>
270 <td width='5%'  align='center'><input type='submit' name='ACTION' title='$Lang::tr{'day after'}' value='&gt;&gt;' /></td>
271 <td width='20%' align='right'><input type='submit' name='ACTION' value='$Lang::tr{'update'}' /></td>
272 </tr>
273 <tr>
274         <td colspan='3' align='left' valign="left">$Lang::tr{'Number of IPs for the pie chart'}:</td>
275         <td colspan='3' align='left' valign="center"><input type='text' name='pienumber' value='$pienumber' size='4'></td>
276         <td align='right'><input type='submit' name='ACTION' value='$Lang::tr{'save'}' /></td>
277 </tr>
278 </table>
279 </form>
280 END
281 ;
282
283 &Header::closebox();
284
285 &Header::openbox('100%', 'left', $Lang::tr{'firewall graph ip'});
286 print "<p><b>$Lang::tr{'firewall hits'} $longmonthstr $daystr: $lines</b></p>";
287
288 my $linesjc = 0;
289 my %tabjc;
290
291 if ($pienumber == -1 || $pienumber > $lines || $sortcolumn == 2) { $pienumber = $lines; };
292 $lines = 0;
293 foreach $_ (@log)
294 {
295         # Extract ipv4 or ipv6 address
296         if (($_ =~  /SRC\=(([\d]{1,3})(\.([\d]{1,3})){3})/) or ($_ =~ /SRC\=(([0-9a-fA-F]{0,4})(\:([0-9a-fA-F]{0,4})){2,7})/)) {
297                 $tabjc{$1} = $tabjc{$1} + 1 ;
298                 if(($tabjc{$1} == 1) && ($lines < $pienumber)) { $lines = $lines + 1; }
299                 $linesjc++;
300         }
301 }
302
303 $pienumber = $lines;
304
305 my @keytabjc = keys %tabjc;
306
307 my @slice;
308 my $go;
309 my $nblinejc;
310
311 if( $cgiparams{'linejc'} eq 'all' ){ $nblinejc = $linesjc; $go=1; }
312 if( ($cgiparams{'linejc'} != 0) && ($cgiparams{'linejc'} ne 'all') ){ $nblinejc = $cgiparams{'linejc'}; $go=1;}
313 if( $go != 1){ $nblinejc = 1000; }
314
315 my @key;
316 my @value;
317 my $indice=0;
318 my @tabjc2;
319
320 if ($sortcolumn == 1)
321 {
322         @tabjc2 = sort { $b <=> $a } values (%tabjc);
323 }
324 else
325 {
326         @tabjc2 = sort { $a <=> $b } keys (%tabjc);
327 }
328
329 my $colour=1;
330
331 ##############################################
332 #pie chart generation
333 use GD::Graph::pie;
334 use GD::Graph::colour;
335 #ips sort by hits number
336 my $v;
337
338 if ($sortcolumn == 1)
339 {
340         for ($v=0;$v<$pienumber;$v++){
341                 findkey($tabjc2[$v]);
342         }
343 }
344 else
345 {
346         foreach $v (@tabjc2) {
347                 $key[$indice] = $v;
348                 $value[$indice] = $tabjc{$v};
349                 $indice++;
350         }
351 }
352
353 my @ips;
354 my @numb;
355
356 @ips = @key;
357 @numb = @value;
358
359 my $o;
360
361 if($cgiparams{'otherspie'} == 2 ){}
362 else{ 
363         my $numothers;
364         for($o=0;$o<$pienumber;$o++){
365                 $numothers = $numothers + $numb[$o];
366         }
367         $numothers =  $linesjc - $numothers;
368         if ($numothers > 0) {
369                 $ips[$pienumber]="$Lang::tr{'otherip'}";
370                 $numb[$pienumber] =  $numothers;
371         }
372 }
373
374 my @data = (\@ips,\@numb);
375 use GD::Graph::colour qw( :files );
376
377 my $color=0;
378 my %color = ();
379 my %mainsettings = ();
380 &General::readhash("${General::swroot}/main/settings", \%mainsettings);
381 &General::readhash("/srv/web/ipfire/html/themes/".$mainsettings{'THEME'}."/include/colors.txt", \%color);
382
383 if ($showpie != 2 && $pienumber <= 50 && $pienumber != 0) {
384         my $mygraph = GD::Graph::pie->new(500, 350);
385         $mygraph->set(
386               'title' => '',
387               'pie_height' => 50,
388               'start_angle' => 89
389         ) or warn $mygraph->error;
390
391         $mygraph->set_value_font(GD::gdMediumBoldFont);
392         $mygraph->set( dclrs => [ "$color{'color1'}" , "$color{'color2'}" , "$color{'color3'}" , "$color{'color4'}" , "$color{'color5'}" , "$color{'color6'}" , "$color{'color7'}" , "$color{'color8'}" , "$color{'color9'}" , "$color{'color10'}" ] );
393         my $myimage = $mygraph->plot(\@data) or die $mygraph->error;
394
395         my @filenames = glob("/srv/web/ipfire/html/graphs/fwlog-ip*.png");
396         unlink(@filenames);
397         my $imagerandom = rand(1000000);
398         my $imagename = "/srv/web/ipfire/html/graphs/fwlog-ip$imagerandom.png";
399         open(FILE,">$imagename");
400         print FILE $myimage->png;
401         close(FILE);
402         #####################################################
403         print "<div style='text-align:center'>";
404         print "<img src='/graphs/fwlog-ip$imagerandom.png'>";
405         print "</div>";
406 }
407
408 print <<END
409 <table width='100%' class='tbl'>
410 <tr>
411 <th width='10%' align='center' class='boldbase'></th>
412 <th width='30%' align='center' class='boldbase'><b>$Lang::tr{'ip address'}</b></th>
413 <th width='10%' align='center' class='boldbase'><b>$Lang::tr{'country'}</b></th>
414 <th width='10%' align='center' class='boldbase'><b>$Lang::tr{'count'}</b></th>
415 <th width='30%' align='center' class='boldbase'><b>$Lang::tr{'percentage'}</b></th>
416 </tr>
417 END
418 ;
419
420 my $total=0;
421 my $show=0;
422
423 my $s;
424 my $percent;
425 my $col="";
426
427 for($s=0;$s<$lines;$s++)
428 {
429         $show++;
430         $percent = $value[$s] * 100 / $linesjc;
431         $percent = sprintf("%.f", $percent);
432         $total = $total + $value[$s];
433         # colors are numbered 1 to 10
434         my $colorIndex = ($color % 10) + 1;
435         $col="bgcolor='$color{\"color$colorIndex\"}'";
436         print "<tr>";
437
438         my $ccode = &GeoIP::lookup($key[$s]);
439   
440         $color++;
441         print "<td align='center' $col><form method='post' action='showrequestfromip.dat'><input type='hidden' name='MONTH' value='$cgiparams{'MONTH'}'> <input type='hidden' name='DAY' value='$cgiparams{'DAY'}'> <input type='hidden' name='ip' value='$key[$s]'> <input type='submit' value='$Lang::tr{'details'}'></form></td>";
442         print "<td align='center' $col><a href='/cgi-bin/ipinfo.cgi?ip=$key[$s]'>$key[$s]</a></td>";
443
444         # Get flag icon for of the country.
445         my $flag_icon = &GeoIP::get_flag_icon($ccode);
446
447         if ( $flag_icon ) {
448                 print "<td align='center' $col><a href='/cgi-bin/country.cgi#$ccode'><img src='$flag_icon' border='0' align='absmiddle' alt='$ccode' title='$ccode'></a></td>";
449         } else {
450                 print "<td align='center' $col></td>";
451         }
452
453         print "<td align='center' $col>$value[$s]</td>";
454         print "<td align='center' $col>$percent</td>";
455         print "</tr>";
456 }
457
458 if($cgiparams{'otherspie'} == 2 ){}
459 else{
460         # colors are numbered 1 to 10
461         my $colorIndex = ($color % 10) + 1;
462         $col="bgcolor='$color{\"color$colorIndex\"}'";
463         print "<tr>";
464
465         if ( $linesjc ne "0")
466         {
467                 my $dif;
468                 $dif = $linesjc - $total;
469                 $percent = $dif * 100 / $linesjc;
470                 $percent = sprintf("%.f", $percent);
471                 print <<END
472                 <td align='center' $col></td>
473                 <td align='center' $col>$Lang::tr{'otherip'}</td>
474                 <td align='center' $col></td>
475                 <td align='center' $col>$dif</td>
476                 <td align='center' $col>$percent</td>
477                 </tr>
478 END
479                 ;
480         }
481 }
482 print <<END
483 </table>
484 END
485 ;
486
487 &Header::closebox();
488 &Header::closebigbox();
489 &Header::closepage();
490
491 sub findkey {
492         my $v;
493         foreach $v (@keytabjc) {
494                 if ($tabjc{$v} eq $_[0]) {
495                         delete $tabjc{$v};
496                         $key[$indice] = "$v";
497                         $value[$indice] = $_[0];
498                         $indice++;
499                         last;
500                 }
501         }
502 }
503
504 sub checkversion {
505         #Automatic Updates is disabled
506         return "0","0";
507 }
508