GeoIP: Add lookup function for convenience
[ipfire-2.x.git] / html / cgi-bin / logs.cgi / firewalllogcountry.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 }
155 else {
156         $daystr = $day;
157 }
158
159 my $skip=0;
160 my $filestr='';
161 if ($datediff==0) {
162         $filestr="/var/log/messages";
163 } else {
164                          $filestr="/var/log/messages.$datediff";
165                          $filestr = "$filestr.gz" if -f "$filestr.gz";
166 }
167
168 if (!(open (FILE,($filestr =~ /.gz$/ ? "gzip -dc $filestr |" : $filestr)))) {
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
172 }
173 my $lines = 0;
174 my @log=();
175
176 if (!$skip)
177 {
178         while (<FILE>)
179         {
180                 if (/(^${monthstr} ${daystr} ..:..:..) [\w\-]+ kernel:.*(IN=.*)$/) {
181                         $log[$lines] = $_;
182                         $lines++;
183                 }
184         }
185         close (FILE);   
186 }
187
188 $skip=0;
189 if ($multifile) {
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         }
210 }
211
212 my $MODNAME="fwlogs";
213
214 &Header::showhttpheaders();
215 &Header::openpage($Lang::tr{'firewall log country'}, 1, '');
216 &Header::openbigbox('100%', 'left', '', $errormessage);
217
218
219 if ($errormessage) {
220         &Header::openbox('100%', 'left', $Lang::tr{'error messages'});
221         print "<font class='base'>$errormessage&nbsp;</font>\n";
222         &Header::closebox();
223 }
224
225 &Header::openbox('100%', 'left', "$Lang::tr{'settings'}");
226
227 print <<END
228 <form method='post' action='$ENV{'SCRIPT_NAME'}'>
229 <table width='100%'>
230 <tr>
231         <td width='10%' class='base'>$Lang::tr{'month'}:&nbsp;</td>
232         <td width='10%'>
233         <select name='MONTH'>
234 END
235 ;
236 my $month;
237 for ($month = 0; $month < 12; $month++)
238 {
239         print "\t<option ";
240         if ($month == $cgiparams{'MONTH'}) {
241                 print "selected='selected' "; }
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         print "value='$day'>$day</option>\n";
258 }
259
260 if( $cgiparams{'pienumber'} != 0){$pienumber=$cgiparams{'pienumber'};}
261 if( $cgiparams{'otherspie'} != 0){$otherspie=$cgiparams{'otherspie'};}
262 if( $cgiparams{'showpie'} != 0){$showpie=$cgiparams{'showpie'};}
263 if( $cgiparams{'sortcolumn'} != 0){$sortcolumn=$cgiparams{'sortcolumn'};}
264 print <<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>
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>
275 </tr>
276 </table>
277 </form>
278 END
279 ;
280
281 &Header::closebox();
282
283 &Header::openbox('100%', 'left', $Lang::tr{'firewall graph country'});
284 print "<p><b>$Lang::tr{'firewall hits'} $longmonthstr $daystr: $lines</b></p>";
285
286 my $red_interface = &General::get_red_interface();
287 my $linesjc = 0;
288 my %tabjc;
289
290 if ($pienumber == -1 || $pienumber > $lines || $sortcolumn == 2) { $pienumber = $lines; };
291 $lines = 0;
292
293 foreach $_ (@log)
294 {
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
311                         my $ccode = &GeoIP::lookup($srcaddr);
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         }
332 }
333
334 $pienumber = $lines;
335
336 my @keytabjc = keys %tabjc;
337
338 my @slice;
339 my $go;
340 my $nblinejc;
341
342 if( $cgiparams{'linejc'} eq 'all' ){ $nblinejc = $linesjc; $go=1; }
343 if( ($cgiparams{'linejc'} != 0) && ($cgiparams{'linejc'} ne 'all') ){ $nblinejc = $cgiparams{'linejc'}; $go=1;}
344 if( $go != 1){ $nblinejc = 1000; }
345
346 my @key;
347 my @value;
348 my $indice=0;
349 my @tabjc2;
350
351 if ($sortcolumn == 1) {
352         @tabjc2 = sort { $b <=> $a } values (%tabjc);
353 }
354 else {
355         @tabjc2 = sort { $a <=> $b } keys (%tabjc);
356 }
357
358 my $colour=1;
359
360 ##############################################
361 #pie chart generation
362 use GD::Graph::pie;
363 use GD::Graph::colour;
364 #ips sort by hits number
365 my $v;
366
367 if ($sortcolumn == 1) {
368         for ($v=0;$v<$pienumber;$v++){
369                 findkey($tabjc2[$v]);
370         }
371 }
372 else {
373         foreach $v (@tabjc2) {
374                 $key[$indice] = $v;
375                 $value[$indice] = $tabjc{$v};
376                 $indice++;
377         }
378 }
379
380 my @ips;
381 my @numb;
382
383 @ips = @key;
384 @numb = @value;
385
386 my $o;
387
388 if($cgiparams{'otherspie'} == 2 ){}
389 else{ 
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         }
399 }
400
401 my @data = (\@ips,\@numb);
402 use GD::Graph::colour qw( :files );
403
404 my $color=0;
405 my %color = ();
406 my %mainsettings = ();
407 &General::readhash("${General::swroot}/main/settings", \%mainsettings);
408 &General::readhash("/srv/web/ipfire/html/themes/".$mainsettings{'THEME'}."/include/colors.txt", \%color);
409
410 if ($showpie != 2 && $pienumber <= 50 && $pienumber != 0) {
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>";
433 }
434 print <<END
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>
442 END
443 ;
444
445 my $total=0;
446 my $show=0;
447
448 my $s;
449 my $percent;
450 my $col="";
451
452 for($s=0;$s<$lines;$s++)
453 {
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]'>";
472                 print"<input type='submit' value='$Lang::tr{'details'}'></form>";
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' ) {
479                 print "<td align='center' $col>$key[$s]</td>";
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>";
496 }
497
498 if($cgiparams{'otherspie'} == 2 ){}
499 else{
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>
517 END
518                 ;
519         }
520 }
521 print <<END
522 </TABLE>
523 END
524 ;
525
526 &Header::closebox();
527 &Header::closebigbox();
528 &Header::closepage();
529
530 sub findkey {
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         }
541 }
542 sub checkversion {
543         #Automatic Updates is disabled
544         return "0","0";
545 }
546