]>
git.ipfire.org Git - people/teissler/ipfire-2.x.git/blob - config/cfgroot/general-functions.pl
3 # This code is distributed under the terms of the GPL
5 # (c) The SmoothWall Team
6 # Copyright (C) 2002 Alex Hudson - getcgihash() rewrite
7 # Copyright (C) 2002 Bob Grant <bob@cache.ucr.edu> - validmac()
8 # Copyright (c) 2002/04/13 Steve Bootes - add alias section, helper functions
9 # Copyright (c) 2002/08/23 Mark Wormgoor <mark@wormgoor.com> validfqdn()
10 # Copyright (c) 2003/09/11 Darren Critchley <darrenc@telus.net> srtarray()
12 # $Id: general-functions.pl,v 1.1.2.26 2006/01/04 16:33:55 franck78 Exp $
22 $|=1; # line buffering
24 $General::version
= 'VERSION';
25 $General::swroot
= 'CONFIG_ROOT';
26 $General::noipprefix
= 'noipg-';
27 $General::adminmanualurl
= 'http://wiki.ipfire.org';
30 # log ("message") use default 'ipcop' tag
31 # log ("tag","message") use your tag
36 $tag = shift if (@_>1);
37 my $logmessage = $_[0];
38 $logmessage =~ /([\w\W]*)/;
40 system('logger', '-t', $tag, $logmessage);
50 # Some ipcop code expects that readhash 'complete' the hash if new entries
51 # are presents. Not clear it !!!
54 open(FILE
, $filename) or die "Unable to read file $filename";
59 ($var, $val) = split /=/, $_, 2;
65 # Untaint variables read from hash
66 # trim space from begin and end
69 $var =~ /([A-Za-z0-9_-]*)/;
86 # write cgi vars to the file.
87 open(FILE
, ">${filename}") or die "Unable to write file $filename";
89 foreach $var (keys %$hash)
92 # Darren Critchley Jan 17, 2003 added the following because when submitting with a graphic, the x and y
93 # location of the mouse are submitted as well, this was being written to the settings file causing
94 # some serious grief! This skips the variable.x and variable.y
95 if (!($var =~ /(.x|.y)$/)) {
98 if (!($var =~ /^ACTION/)) {
99 print FILE
"${var}=${val}\n"; }
108 my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
109 $atime, $mtime, $ctime, $blksize, $blocks) = stat $_[0];
112 my $totalsecs = $now - $mtime;
113 my $days = int($totalsecs / 86400);
114 my $totalhours = int($totalsecs / 3600);
115 my $hours = $totalhours % 24;
116 my $totalmins = int($totalsecs / 60);
117 my $mins = $totalmins % 60;
118 my $secs = $totalsecs % 60;
120 return "${days}d ${hours}h ${mins}m ${secs}s";
127 if (!($ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/)) {
131 my @octets = ($1, $2, $3, $4);
136 if ($_ < 0 || $_ > 255) {
148 if (&validip
($mask)) {
150 # second part a number?
153 if (!($mask =~ /^\d+$/)) {
155 if ($mask >= 0 && $mask <= 32) {
162 my $ipormask = $_[0];
164 # see if it is a IP only.
165 if (&validip
($ipormask)) {
167 # split it into number and mask.
168 if (!($ipormask =~ /^(.*?)\/(.*?
)$/)) {
172 # first part not a ip?
173 if (!(&validip
($ip))) {
175 return &validmask
($mask);
180 my $ipandmask = $_[0];
182 # split it into number and mask.
183 if (!($ipandmask =~ /^(.*?)\/(.*?
)$/)) {
187 # first part not a ip?
188 if (!(&validip
($ip))) {
190 return &validmask
($mask);
201 if ($_ >= 1 && $_ <= 65535) {
214 if ($_ == 53 || $_ == 222 || $_ == 444 || $_ == 81 ) {
216 elsif ($_ >= 1 && $_ <= 65535) {
223 my $checkmac = $_[0];
224 my $ot = '[0-9a-f]{2}'; # 2 Hex digits (one octet)
225 if ($checkmac !~ /^$ot:$ot:$ot:$ot:$ot:$ot$/i)
234 # Checks a hostname against RFC1035
235 my $hostname = $_[0];
237 # Each part should be at least two characters in length
238 # but no more than 63 characters
239 if (length ($hostname) < 1 || length ($hostname) > 63) {
241 # Only valid characters are a-z, A-Z, 0-9 and -
242 if ($hostname !~ /^[a-zA-Z0-9-]*$/) {
244 # First character can only be a letter or a digit
245 if (substr ($hostname, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
247 # Last character can only be a letter or a digit
248 if (substr ($hostname, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
257 # Checks a domain name against RFC1035
258 my $domainname = $_[0];
259 my @parts = split (/\./, $domainname); # Split hostname at the '.'
261 foreach $part (@parts) {
262 # Each part should be at least two characters in length
263 # but no more than 63 characters
264 if (length ($part) < 2 || length ($part) > 63) {
266 # Only valid characters are a-z, A-Z, 0-9 and -
267 if ($part !~ /^[a-zA-Z0-9-]*$/) {
269 # First character can only be a letter or a digit
270 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
272 # Last character can only be a letter or a digit
273 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
283 # Checks a fully qualified domain name against RFC1035
285 my @parts = split (/\./, $fqdn); # Split hostname at the '.'
286 if (scalar(@parts) < 2) { # At least two parts should
287 return 0;} # exist in a FQDN
288 # (i.e. hostname.domain)
289 foreach $part (@parts) {
290 # Each part should be at least one character in length
291 # but no more than 63 characters
292 if (length ($part) < 1 || length ($part) > 63) {
294 # Only valid characters are a-z, A-Z, 0-9 and -
295 if ($part !~ /^[a-zA-Z0-9-]*$/) {
297 # First character can only be a letter or a digit
298 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
300 # Last character can only be a letter or a digit
301 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
307 sub validportrange
# used to check a port range
309 my $port = $_[0]; # port values
310 $port =~ tr/-/:/; # replace all - with colons just in case someone used -
311 my $srcdst = $_[1]; # is it a source or destination port
313 if (!($port =~ /^(\d+)\:(\d+)$/)) {
315 if (!(&validport
($port))) {
316 if ($srcdst eq 'src'){
317 return $Lang::tr
{'source port numbers'};
319 return $Lang::tr
{'destination port numbers'};
325 my @ports = ($1, $2);
327 if ($srcdst eq 'src'){
328 return $Lang::tr
{'bad source range'};
330 return $Lang::tr
{'bad destination range'};
335 if (!(&validport
($_))) {
336 if ($srcdst eq 'src'){
337 return $Lang::tr
{'source port numbers'};
339 return $Lang::tr
{'destination port numbers'};
347 # Test if IP is within a subnet
348 # Call: IpInSubnet (Addr, Subnet, Subnet Mask)
349 # Subnet can be an IP of the subnet: 10.0.0.0 or 10.0.0.1
350 # Everything in dottted notation
354 my $ip = unpack('N', &Socket
::inet_aton
(shift));
355 my $start = unpack('N', &Socket
::inet_aton
(shift));
356 my $mask = unpack('N', &Socket
::inet_aton
(shift));
357 $start &= $mask; # base of subnet...
358 my $end = $start + ~$mask;
359 return (($ip >= $start) && ($ip <= $end));
363 # Return the following IP (IP+1) in dotted notation.
364 # Call: NextIP ('1.1.1.1');
369 return &Socket
::inet_ntoa
( pack("N", 1 + unpack('N', &Socket
::inet_aton
(shift))
376 return 0 if ( $mail !~ /^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/ );
377 return 0 if ( $mail =~ /^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/);
378 return 0 if ( $mail !~ /([0-9a-zA-Z]{1})\@./ );
379 return 0 if ( $mail !~ /.\@([0-9a-zA-Z]{1})/ );
380 return 0 if ( $mail =~ /.\.\-.|.\-\..|.\.\..|.\-\-./g );
381 return 0 if ( $mail =~ /.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./g );
382 return 0 if ( $mail !~ /\.([a-zA-Z]{2,4})$/ );
387 # Currently only vpnmain use this three procs (readhasharray, writehasharray, findhasharray)
388 # The 'key' used is numeric but is perfectly unneeded! This will to be removed so don't use
389 # this code. Vpnmain will be splitted in parts: x509/pki, connection ipsec, connection other,... .
392 my ($filename, $hash) = @_;
395 open(FILE
, $filename) or die "Unable to read file $filename";
398 my ($key, $rest, @temp);
400 ($key, $rest) = split (/,/, $_, 2);
401 if ($key =~ /^[0-9]+$/) {
402 @temp = split (/,/, $rest);
403 $hash->{$key} = \
@temp;
411 my ($filename, $hash) = @_;
412 my ($key, @temp, $i);
414 open(FILE
, ">$filename") or die "Unable to write to file $filename";
416 foreach $key (keys %$hash) {
417 if ($key =~ /^[0-9]+$/) {
419 foreach $i (0 .. $#{$hash->{$key}}) {
420 print FILE
",$hash->{$key}[$i]";
429 sub findhasharraykey
{
430 foreach my $i (1 .. 1000000) {
431 if ( ! exists $_[0]{$i}) {
438 # Darren Critchley - darrenc@telus.net - (c) 2003
439 # &srtarray(SortOrder, AlphaNumeric, SortDirection, ArrayToBeSorted)
440 # This subroutine will take the following parameters:
441 # ColumnNumber = the column which you want to sort on, starts at 1
442 # AlphaNumberic = a or n (lowercase) defines whether the sort should be alpha or numberic
443 # SortDirection = asc or dsc (lowercase) Ascending or Descending sort
444 # ArrayToBeSorted = the array that wants sorting
446 # Returns an array that is sorted to your specs
448 # If SortOrder is greater than the elements in array, then it defaults to the first element
451 my ($colno, $alpnum, $srtdir, @tobesorted) = @_;
457 my $ttlitems = scalar @tobesorted; # want to know the number of rows in the passed array
458 if ($ttlitems < 1){ # if no items, don't waste our time lets leave
459 return (@tobesorted);
461 my @tmp = split(/\,/,$tobesorted[0]);
462 $ttlitems = scalar @tmp; # this should be the number of elements in each row of the passed in array
464 # Darren Critchley - validate parameters
465 if ($colno > $ttlitems){$colno = '1';}
466 $colno--; # remove one from colno to deal with arrays starting at 0
467 if($colno < 0){$colno = '0';}
468 if ($alpnum ne '') { $alpnum = lc($alpnum); } else { $alpnum = 'a'; }
469 if ($srtdir ne '') { $srtdir = lc($srtdir); } else { $srtdir = 'src'; }
471 foreach $line (@tobesorted)
475 my @temp = split(/\,/,$line);
476 # Darren Critchley - juggle the fields so that the one we want to sort on is first
477 my $tmpholder = $temp[0];
478 $temp[0] = $temp[$colno];
479 $temp[$colno] = $tmpholder;
481 for ($ctr=0; $ctr < $ttlitems ; $ctr++) {
482 $newline=$newline . $temp[$ctr] . ",";
485 push(@tmparray,$newline);
488 if ($alpnum eq 'n') {
489 @tmparray = sort {$a <=> $b} @tmparray;
491 @tmparray = (sort @tmparray);
493 foreach $line (@tmparray)
497 my @temp = split(/\,/,$line);
498 my $tmpholder = $temp[0];
499 $temp[0] = $temp[$colno];
500 $temp[$colno] = $tmpholder;
502 for ($ctr=0; $ctr < $ttlitems ; $ctr++){
503 $newline=$newline . $temp[$ctr] . ",";
506 push(@srtedarray,$newline);
510 if ($srtdir eq 'dsc') {
511 @tmparray = reverse(@srtedarray);
514 return (@srtedarray);
520 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
521 if ($_=$proxysettings{'UPSTREAM_PROXY'}) {
522 my ($peer, $peerport) = (/^(?:[a-zA-Z ]+\:\/\
/)?(?:[A-Za-z0-9\_\.\-]*?(?:\:[A-Za-z0-9\_\.\-]*?)?\@)?([a-zA-Z0-9\.\_\-]*?)(?:\:([0-9]{1,5}))?(?:\/.*?
)?
$/);
523 Net
::SSLeay
::set_proxy
($peer,$peerport,$proxysettings{'UPSTREAM_USER'},$proxysettings{'UPSTREAM_PASSWORD'} );
525 my ($out, $response) = Net
::SSLeay
::get_http
( 'checkip.dyndns.org',
528 Net
::SSLeay
::make_headers
('User-Agent' => 'IPFire' )
530 if ($response =~ m
%HTTP/1\
.. 200 OK
%) {
531 $out =~ /Current IP Address: (\d+.\d+.\d+.\d+)/;
538 # Check if hostname.domain provided have IP provided
539 # use gethostbyname to verify that
545 # 1 IP matches host.domain
548 sub DyndnsServiceSync
($;$;$) {
550 my ($ip,$hostName,$domain) = @_;
553 #fix me no ip GROUP, what is the name ?
554 $hostName =~ s/$General::noipprefix//;
555 if ($hostName) { #may be empty
556 $hostName = "$hostName.$domain";
557 @addresses = gethostbyname($hostName);
560 if ($addresses[0] eq '') { # nothing returned ?
561 $hostName = $domain; # try resolving with domain only
562 @addresses = gethostbyname($hostName);
565 if ($addresses[0] ne '') { # got something ?
566 #&General::log("name:$addresses[0], alias:$addresses[1]");
567 # Build clear text list of IP
568 @addresses = map ( &Socket
::inet_ntoa
($_), @addresses[4..$#addresses]);
569 if (grep (/$ip/, @addresses)) {
576 # This sub returns the red IP used to compare in DyndnsServiceSync
580 &General
::readhash
("${General::swroot}/ddns/settings", \
%settings);
582 open(IP
, "${General::swroot}/red/local-ipaddress") or return 'unavailable';
587 if (&General
::IpInSubnet
($ip,'10.0.0.0','255.0.0.0') ||
588 &General
::IpInSubnet
($ip,'172.16.0.0.','255.240.0.0') ||
589 &General
::IpInSubnet
($ip,'192.168.0.0','255.255.0.0'))
591 if ($settings{'BEHINDROUTER'} eq 'FETCH_IP') {
592 my $RealIP = &General
::FetchPublicIp
;
593 $ip = (&General
::validip
($RealIP) ?
$RealIP : 'unavailable');
599 # Translate ICMP code to text
600 # ref: http://www.iana.org/assignments/icmp-parameters
601 sub GetIcmpDescription
($) {
603 my @icmp_description = (
607 'Destination Unreachable',
610 'Alternate Host Address',
613 'Router Advertisement',
614 'Router Solicitation', #10
619 'Information Request',
621 'Address Mask Request',
622 'Address Mask Reply',
623 'Reserved (for Security)',
624 'Reserved (for Robustness Experiment)', #20
635 'Datagram Conversion Error',
636 'Mobile Host Redirect',
637 'IPv6 Where-Are-You',
639 'Mobile Registration Request',
640 'Mobile Registration Reply',
641 'Domain Name Request',
646 if ($index>41) {return 'unknown'} else {return @icmp_description[$index]};