GeoIP: Add lookup function for convenience
[ipfire-2.x.git] / html / cgi-bin / logs.cgi / firewalllogcountry.dat
CommitLineData
e4aac473
AH
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
43638be5 11# and Michael Tremer (www.ipfire.org)
e4aac473
AH
12
13use strict;
e4aac473
AH
14use Getopt::Std;
15
16# enable only the following on debugging purpose
17#use warnings;
18#use CGI::Carp 'fatalsToBrowser';
19
20require '/var/ipfire/general-functions.pl';
3ea01fe0 21require "${General::swroot}/geoip-functions.pl";
e4aac473
AH
22require "${General::swroot}/lang.pl";
23require "${General::swroot}/header.pl";
24
25use POSIX();
26
27my %cgiparams=();
28my %settings=();
29my $pienumber;
30my $otherspie;
31my $showpie;
32my $sortcolumn;
33my $errormessage = '';
34
35$cgiparams{'pienumber'} = 10;
36$cgiparams{'otherspie'} = 1;
37$cgiparams{'showpie'} = 1;
38$cgiparams{'sortcolumn'} = 1;
39
40my @shortmonths = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
43638be5 41 'Sep', 'Oct', 'Nov', 'Dec' );
e4aac473 42my @longmonths = ( $Lang::tr{'january'}, $Lang::tr{'february'}, $Lang::tr{'march'},
43638be5
ME
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'} );
e4aac473
AH
46
47my @now = localtime();
48my $dow = $now[6];
49my $doy = $now[7];
50my $tdoy = $now[7];
51my $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);
58if ($settings{'pienumber'} != 0) { $cgiparams{'pienumber'} = $settings{'pienumber'} };
59if ($settings{'otherspie'} != 0) { $cgiparams{'otherspie'} = $settings{'otherspie'} };
60if ($settings{'showpie'} != 0) { $cgiparams{'showpie'} = $settings{'showpie'} };
61if ($settings{'sortcolumn'} != 0) { $cgiparams{'sortcolumn'} = $settings{'sortcolumn'} };
62
63&Header::getcgihash(\%cgiparams);
64if ($cgiparams{'pienumber'} != 0) { $settings{'pienumber'} = $cgiparams{'pienumber'} };
65if ($cgiparams{'otherspie'} != 0) { $settings{'otherspie'} = $cgiparams{'otherspie'} };
66if ($cgiparams{'showpie'} != 0) { $settings{'showpie'} = $cgiparams{'showpie'} };
67if ($cgiparams{'sortcolumn'} != 0) { $settings{'sortcolumn'} = $cgiparams{'sortcolumn'} };
68
69if ($cgiparams{'ACTION'} eq $Lang::tr{'save'})
70{
43638be5 71 &General::writehash("${General::swroot}/fwlogs/ipsettings", \%settings);
e4aac473
AH
72}
73
74my $start = -1;
75if ($ENV{'QUERY_STRING'} && $cgiparams{'ACTION'} ne $Lang::tr{'update'})
76{
43638be5
ME
77 my @temp = split(',',$ENV{'QUERY_STRING'});
78 $start = $temp[0];
79 $cgiparams{'MONTH'} = $temp[1];
80 $cgiparams{'DAY'} = $temp[2];
e4aac473
AH
81}
82
83if (!($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{
43638be5
ME
86 $cgiparams{'DAY'} = $now[3];
87 $cgiparams{'MONTH'} = $now[4];
e4aac473
AH
88}
89elsif($cgiparams{'ACTION'} eq '>>')
90{
43638be5
ME
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];
e4aac473
AH
100}
101elsif($cgiparams{'ACTION'} eq '<<')
102{
43638be5
ME
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];
e4aac473
AH
112}
113
114if (($cgiparams{'DAY'} ne $now[3]) || ($cgiparams{'MONTH'} ne $now[4]))
115{
43638be5
ME
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 }
e4aac473
AH
132}
133
134my $datediff=0;
135my $dowd=0;
136my $multifile=0;
137if ($tdoy ne $doy) {
43638be5
ME
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 }
e4aac473
AH
146}
147
148my $monthstr = $shortmonths[$cgiparams{'MONTH'}];
149my $longmonthstr = $longmonths[$cgiparams{'MONTH'}];
150my $day = $cgiparams{'DAY'};
151my $daystr='';
152if ($day <= 9) {
43638be5
ME
153 $daystr = " $day";
154}
e4aac473 155else {
43638be5 156 $daystr = $day;
e4aac473
AH
157}
158
159my $skip=0;
160my $filestr='';
161if ($datediff==0) {
43638be5 162 $filestr="/var/log/messages";
e4aac473 163} else {
43638be5
ME
164 $filestr="/var/log/messages.$datediff";
165 $filestr = "$filestr.gz" if -f "$filestr.gz";
e4aac473
AH
166}
167
168if (!(open (FILE,($filestr =~ /.gz$/ ? "gzip -dc $filestr |" : $filestr)))) {
43638be5
ME
169 $errormessage = "$Lang::tr{'date not in logs'}: $filestr $Lang::tr{'could not be opened'}";
170 $skip=1;
171 # Note: This is in case the log does not exist for that date
e4aac473
AH
172}
173my $lines = 0;
174my @log=();
175
176if (!$skip)
177{
43638be5
ME
178 while (<FILE>)
179 {
180 if (/(^${monthstr} ${daystr} ..:..:..) [\w\-]+ kernel:.*(IN=.*)$/) {
181 $log[$lines] = $_;
182 $lines++;
183 }
184 }
185 close (FILE);
e4aac473
AH
186}
187
188$skip=0;
189if ($multifile) {
43638be5
ME
190 $datediff=$datediff-1;
191 if ($datediff==0) {
192 $filestr="/var/log/messages";
193 } else {
194 $filestr="/var/log/messages.$datediff";
195 $filestr = "$filestr.gz" if -f "$filestr.gz";
196 }
197 if (!(open (FILE,($filestr =~ /.gz$/ ? "gzip -dc $filestr |" : $filestr)))) {
198 $errormessage="$Lang::tr{'date not in logs'}: $filestr $Lang::tr{'could not be opened'}";
199 $skip=1;
200 }
201 if (!$skip) {
202 while (<FILE>) {
203 if (/(^${monthstr} ${daystr} ..:..:..) [\w\-]+ kernel:.*(IN=.*)$/) {
204 $log[$lines] = $_;
205 $lines++;
206 }
207 }
208 close (FILE);
209 }
e4aac473
AH
210}
211
212my $MODNAME="fwlogs";
213
214&Header::showhttpheaders();
1bea8be2 215&Header::openpage($Lang::tr{'firewall log country'}, 1, '');
e4aac473
AH
216&Header::openbigbox('100%', 'left', '', $errormessage);
217
218
219if ($errormessage) {
43638be5
ME
220 &Header::openbox('100%', 'left', $Lang::tr{'error messages'});
221 print "<font class='base'>$errormessage&nbsp;</font>\n";
222 &Header::closebox();
e4aac473
AH
223}
224
f4248975 225&Header::openbox('100%', 'left', "$Lang::tr{'settings'}");
e4aac473
AH
226
227print <<END
228<form method='post' action='$ENV{'SCRIPT_NAME'}'>
229<table width='100%'>
230<tr>
43638be5
ME
231 <td width='10%' class='base'>$Lang::tr{'month'}:&nbsp;</td>
232 <td width='10%'>
233 <select name='MONTH'>
e4aac473
AH
234END
235;
236my $month;
237for ($month = 0; $month < 12; $month++)
238{
43638be5
ME
239 print "\t<option ";
240 if ($month == $cgiparams{'MONTH'}) {
241 print "selected='selected' "; }
242 print "value='$month'>$longmonths[$month]</option>\n";
e4aac473
AH
243}
244print <<END
43638be5
ME
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'>
e4aac473
AH
250END
251;
252for ($day = 1; $day <= 31; $day++)
253{
43638be5
ME
254 print "\t<option ";
255 if ($day == $cgiparams{'DAY'}) {
256 print "selected='selected' "; }
257 print "value='$day'>$day</option>\n";
e4aac473
AH
258}
259
260if( $cgiparams{'pienumber'} != 0){$pienumber=$cgiparams{'pienumber'};}
261if( $cgiparams{'otherspie'} != 0){$otherspie=$cgiparams{'otherspie'};}
262if( $cgiparams{'showpie'} != 0){$showpie=$cgiparams{'showpie'};}
263if( $cgiparams{'sortcolumn'} != 0){$sortcolumn=$cgiparams{'sortcolumn'};}
e4aac473
AH
264print <<END
265</select>
266</td>
267<td width='5%' align='center'><input type='submit' name='ACTION' title='$Lang::tr{'day before'}' value='&lt;&lt;' /></td>
268<td width='5%' align='center'><input type='submit' name='ACTION' title='$Lang::tr{'day after'}' value='&gt;&gt;' /></td>
f4248975
AH
269<td width='20%' align='right'><input type='submit' name='ACTION' value='$Lang::tr{'update'}' /></td>
270</tr>
271<tr>
272 <td colspan='3' align='left' valign="left">$Lang::tr{'Number of Countries for the pie chart'}:</td>
273 <td colspan='3' align='left' valign="center"><input type='text' name='pienumber' value='$pienumber' size='4'></td>
274 <td align='right'><input type='submit' name='ACTION' value='$Lang::tr{'save'}' /></td>
e4aac473
AH
275</tr>
276</table>
f4248975 277</form>
e4aac473
AH
278END
279;
280
281&Header::closebox();
282
1bea8be2 283&Header::openbox('100%', 'left', $Lang::tr{'firewall graph country'});
e4aac473
AH
284print "<p><b>$Lang::tr{'firewall hits'} $longmonthstr $daystr: $lines</b></p>";
285
4fca9c99 286my $red_interface = &General::get_red_interface();
e4aac473
AH
287my $linesjc = 0;
288my %tabjc;
e4aac473
AH
289
290if ($pienumber == -1 || $pienumber > $lines || $sortcolumn == 2) { $pienumber = $lines; };
291$lines = 0;
4fca9c99 292
e4aac473
AH
293foreach $_ (@log)
294{
43638be5
ME
295 # If ipv6 uses bridge, use PHYSIN for iface, otherwise IN
296 if (/^... (..) (..:..:..) [\w\-]+ kernel:(.*)(PHYSIN=.*)$/) {}
297 elsif (/^... (..) (..:..:..) [\w\-]+ kernel:(.*)(IN=.*)$/) {}
298 my $packet = $4;
299 my $iface = '';
300 if ($packet =~ /PHYSIN=(\w+)/) { $iface = $1; } elsif ($packet =~ /IN=(\w+)/) { $iface = $1; }
301 if ( $1 =~ /2./ ) { $iface=''; }
302 my $srcaddr = '';
303 # Find ipv4 and ipv6 addresses
304 if ($packet =~ /SRC\=(([\d]{1,3})(\.([\d]{1,3})){3})/) { $srcaddr = $1; }
305 elsif ($packet =~ /SRC\=(([0-9a-fA-F]{0,4})(\:([0-9a-fA-F]{0,4})){2,7})/) { $srcaddr = $1; }
306
307 if($iface eq $red_interface) {
308 # Traffic from red
309 if($srcaddr ne '') {
310 # srcaddr is set
00793c27 311 my $ccode = &GeoIP::lookup($srcaddr);
43638be5
ME
312 if ($ccode eq '') {
313 $ccode = 'unknown';
314 }
315 $tabjc{$ccode} = $tabjc{$ccode} + 1;
316 if(($tabjc{$ccode} == 1) && ($lines < $pienumber)) { $lines = $lines + 1; }
317 $linesjc++;
318 }
319 }
320 else {
321 # Traffic not from red
322 if($iface ne '') {
323 $tabjc{$iface} = $tabjc{$iface} + 1 ;
324 if(($tabjc{$iface} == 1) && ($lines < $pienumber)) { $lines = $lines + 1; }
325 $linesjc++;
326 }
327 else {
328 # What to do with empty iface lines?
329 # This probably is traffic from ipfire itself (IN= OUT=XY)?
330 }
331 }
e4aac473
AH
332}
333
334$pienumber = $lines;
335
336my @keytabjc = keys %tabjc;
337
338my @slice;
339my $go;
340my $nblinejc;
341
342if( $cgiparams{'linejc'} eq 'all' ){ $nblinejc = $linesjc; $go=1; }
343if( ($cgiparams{'linejc'} != 0) && ($cgiparams{'linejc'} ne 'all') ){ $nblinejc = $cgiparams{'linejc'}; $go=1;}
344if( $go != 1){ $nblinejc = 1000; }
345
346my @key;
347my @value;
348my $indice=0;
349my @tabjc2;
350
43638be5
ME
351if ($sortcolumn == 1) {
352 @tabjc2 = sort { $b <=> $a } values (%tabjc);
e4aac473 353}
43638be5
ME
354else {
355 @tabjc2 = sort { $a <=> $b } keys (%tabjc);
e4aac473
AH
356}
357
358my $colour=1;
359
360##############################################
361#pie chart generation
362use GD::Graph::pie;
363use GD::Graph::colour;
364#ips sort by hits number
365my $v;
366
43638be5
ME
367if ($sortcolumn == 1) {
368 for ($v=0;$v<$pienumber;$v++){
369 findkey($tabjc2[$v]);
370 }
e4aac473 371}
43638be5
ME
372else {
373 foreach $v (@tabjc2) {
374 $key[$indice] = $v;
375 $value[$indice] = $tabjc{$v};
376 $indice++;
377 }
e4aac473
AH
378}
379
380my @ips;
381my @numb;
382
383@ips = @key;
384@numb = @value;
385
386my $o;
387
388if($cgiparams{'otherspie'} == 2 ){}
389else{
43638be5
ME
390 my $numothers;
391 for($o=0;$o<$pienumber;$o++){
392 $numothers = $numothers + $numb[$o];
393 }
394 $numothers = $linesjc - $numothers;
395 if ($numothers > 0) {
396 $ips[$pienumber]="$Lang::tr{'otherip'}";
397 $numb[$pienumber] = $numothers;
398 }
e4aac473
AH
399}
400
401my @data = (\@ips,\@numb);
402use GD::Graph::colour qw( :files );
403
404my $color=0;
405my %color = ();
406my %mainsettings = ();
407&General::readhash("${General::swroot}/main/settings", \%mainsettings);
408&General::readhash("/srv/web/ipfire/html/themes/".$mainsettings{'THEME'}."/include/colors.txt", \%color);
409
410if ($showpie != 2 && $pienumber <= 50 && $pienumber != 0) {
43638be5
ME
411 my $mygraph = GD::Graph::pie->new(500, 350);
412 $mygraph->set(
413 'title' => '',
414 'pie_height' => 50,
415 'start_angle' => 89
416 ) or warn $mygraph->error;
417
418 $mygraph->set_value_font(GD::gdMediumBoldFont);
419 $mygraph->set( dclrs => [ "$color{'color1'}" , "$color{'color2'}" , "$color{'color3'}" , "$color{'color4'}" , "$color{'color5'}" , "$color{'color6'}" , "$color{'color7'}" , "$color{'color8'}" , "$color{'color9'}" , "$color{'color10'}" ] );
420 my $myimage = $mygraph->plot(\@data) or die $mygraph->error;
421
422 my @filenames = glob("/srv/web/ipfire/html/graphs/fwlog-country*.png");
423 unlink(@filenames);
424 my $imagerandom = rand(1000000);
425 my $imagename = "/srv/web/ipfire/html/graphs/fwlog-country$imagerandom.png";
426 open(FILE,">$imagename");
427 print FILE $myimage->png;
428 close(FILE);
429 #####################################################
430 print "<div style='text-align:center;'>";
431 print "<img src='/graphs/fwlog-country$imagerandom.png'>";
432 print "</div>";
e4aac473 433}
e4aac473 434print <<END
f4248975
AH
435<table width='100%' class='tbl'>
436<tr>
437<th width='10%' align='center' class='boldbase'></th>
438<th width='30%' align='center' class='boldbase'><b>$Lang::tr{'country'}</b></th>
439<th width='30%' align='center' class='boldbase'><b>Count</b></th>
440<th width='30%' align='center' class='boldbase'><b>$Lang::tr{'percentage'}</b></th>
441</tr>
e4aac473
AH
442END
443;
444
445my $total=0;
446my $show=0;
447
448my $s;
449my $percent;
f4248975 450my $col="";
e4aac473
AH
451
452for($s=0;$s<$lines;$s++)
453{
43638be5
ME
454 $show++;
455 $percent = $value[$s] * 100 / $linesjc;
456 $percent = sprintf("%.f", $percent);
457 $total = $total + $value[$s];
458 # colors are numbered 1 to 10
459 my $colorIndex = ($color % 10) + 1;
460 $col="bgcolor='$color{\"color$colorIndex\"}'";
461 $color++;
462 print "<tr>";
463
464 print "<td align='center' $col>";
465
466 # Dont show details button for "unknown" location.
467 if ($key[$s] ne 'unknown') {
468 print"<form method='post' action='showrequestfromcountry.dat'>";
469 print"<input type='hidden' name='MONTH' value='$cgiparams{'MONTH'}'>";
470 print"<input type='hidden' name='DAY' value='$cgiparams{'DAY'}'>";
471 print"<input type='hidden' name='country' value='$key[$s]'>";
1bea8be2 472 print"<input type='submit' value='$Lang::tr{'details'}'></form>";
43638be5
ME
473 }
474 elsif ($key[$s] eq 'unknown') {
475 print "unknown";
476 }
477 # Looks dangerous to use hardcoded interface names here. Probably needs fixing.
478 if ($key[$s] eq 'blue0' || $key[$s] eq 'green0' || $key[$s] eq 'orange0' ) {
3ea01fe0 479 print "<td align='center' $col>$key[$s]</td>";
43638be5
ME
480 }
481 else {
482 my $fcode = lc($key[$s]);
483
484 # Get flag icon for of the country.
485 my $flag_icon = &GeoIP::get_flag_icon($fcode);
486
487 if($flag_icon) {
488 print "<td align='center' $col><a href='/cgi-bin/country.cgi#$fcode'><img src='$flag_icon' border='0' align='absmiddle' alt='$key[$s]' title='$key[$s]'></a></td>";
489 } else {
490 print "<td align='center' $col>$key[$s]</td>";
491 }
492 }
493 print "<td align='center' $col>$value[$s]</td>";
494 print "<td align='center' $col>$percent</td>";
495 print "</tr>";
f4248975 496}
e4aac473
AH
497
498if($cgiparams{'otherspie'} == 2 ){}
499else{
43638be5
ME
500 # colors are numbered 1 to 10
501 my $colorIndex = ($color % 10) + 1;
502 $col="bgcolor='$color{\"color$colorIndex\"}'";
503 print "<tr>";
504
505 if ( $linesjc ne "0")
506 {
507 my $dif;
508 $dif = $linesjc - $total;
509 $percent = $dif * 100 / $linesjc;
510 $percent = sprintf("%.f", $percent);
511 print <<END
512 <td align='center' $col></TD>
513 <td align='center' $col>$Lang::tr{'other countries'}</td>
514 <td align='center' $col>$dif</TD>
515 <td align='center' $col>$percent</TD>
516 </tr>
e4aac473 517END
43638be5
ME
518 ;
519 }
e4aac473
AH
520}
521print <<END
522</TABLE>
523END
524;
525
526&Header::closebox();
527&Header::closebigbox();
528&Header::closepage();
529
530sub findkey {
43638be5
ME
531 my $v;
532 foreach $v (@keytabjc) {
533 if ($tabjc{$v} eq $_[0]) {
534 delete $tabjc{$v};
535 $key[$indice] = "$v";
536 $value[$indice] = $_[0];
537 $indice++;
538 last;
539 }
540 }
e4aac473
AH
541}
542sub checkversion {
43638be5
ME
543 #Automatic Updates is disabled
544 return "0","0";
e4aac473
AH
545}
546