]>
git.ipfire.org Git - 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 $
23 $|=1; # line buffering
25 $General::version
= 'VERSION';
26 $General::swroot
= 'CONFIG_ROOT';
27 $General::noipprefix
= 'noipg-';
28 $General::adminmanualurl
= 'http://wiki.ipfire.org';
31 # log ("message") use default 'ipcop' tag
32 # log ("tag","message") use your tag
37 $tag = shift if (@_>1);
38 my $logmessage = $_[0];
39 $logmessage =~ /([\w\W]*)/;
41 system('logger', '-t', $tag, $logmessage);
51 # Some ipcop code expects that readhash 'complete' the hash if new entries
52 # are presents. Not clear it !!!
55 open(FILE
, $filename) or die "Unable to read file $filename";
60 ($var, $val) = split /=/, $_, 2;
66 # Untaint variables read from hash
67 # trim space from begin and end
70 $var =~ /([A-Za-z0-9_-]*)/;
87 # write cgi vars to the file.
88 open(FILE
, ">${filename}") or die "Unable to write file $filename";
90 foreach $var (keys %$hash)
92 if ( $var eq "__CGI__"){next;}
94 # Darren Critchley Jan 17, 2003 added the following because when submitting with a graphic, the x and y
95 # location of the mouse are submitted as well, this was being written to the settings file causing
96 # some serious grief! This skips the variable.x and variable.y
97 if (!($var =~ /(.x|.y)$/)) {
100 if (!($var =~ /^ACTION/)) {
101 print FILE
"${var}=${val}\n"; }
109 # This function replaces the given hash in the original hash by keeping the old
110 # content and just replacing the new content
112 my $filename = $_[0];
117 readhash
("${filename}", \
%oldhash);
119 foreach $var (keys %$newhash){
120 $oldhash{$var}=$newhash->{$var};
123 # write cgi vars to the file.
124 open(FILE
, ">${filename}") or die "Unable to write file $filename";
126 foreach $var (keys %oldhash)
128 if ( $var eq "__CGI__"){next;}
129 $val = $oldhash{$var};
130 # Darren Critchley Jan 17, 2003 added the following because when submitting with a graphic, the x and y
131 # location of the mouse are submitted as well, this was being written to the settings file causing
132 # some serious grief! This skips the variable.x and variable.y
133 if (!($var =~ /(.x|.y)$/)) {
136 if (!($var =~ /^ACTION/)) {
137 print FILE
"${var}=${val}\n"; }
145 my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
146 $atime, $mtime, $ctime, $blksize, $blocks) = stat $_[0];
149 my $totalsecs = $now - $mtime;
150 my $days = int($totalsecs / 86400);
151 my $totalhours = int($totalsecs / 3600);
152 my $hours = $totalhours % 24;
153 my $totalmins = int($totalsecs / 60);
154 my $mins = $totalmins % 60;
155 my $secs = $totalsecs % 60;
157 return "${days}d ${hours}h ${mins}m ${secs}s";
164 if (!($ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/)) {
168 my @octets = ($1, $2, $3, $4);
173 if ($_ < 0 || $_ > 255) {
185 if (&validip
($mask)) {
187 # second part a number?
190 if (!($mask =~ /^\d+$/)) {
192 if ($mask >= 0 && $mask <= 32) {
199 my $ipormask = $_[0];
201 # see if it is a IP only.
202 if (&validip
($ipormask)) {
204 # split it into number and mask.
205 if (!($ipormask =~ /^(.*?)\/(.*?
)$/)) {
209 # first part not a ip?
210 if (!(&validip
($ip))) {
212 return &validmask
($mask);
217 my $ipandmask = $_[0];
219 # split it into number and mask.
220 if (!($ipandmask =~ /^(.*?)\/(.*?
)$/)) {
224 # first part not a ip?
225 if (!(&validip
($ip))) {
227 return &validmask
($mask);
238 if ($_ >= 1 && $_ <= 65535) {
251 if ($_ == 53 || $_ == 222 || $_ == 444 || $_ == 81 ) {
253 elsif ($_ >= 1 && $_ <= 65535) {
260 my $checkmac = $_[0];
261 my $ot = '[0-9a-f]{2}'; # 2 Hex digits (one octet)
262 if ($checkmac !~ /^$ot:$ot:$ot:$ot:$ot:$ot$/i)
271 # Checks a hostname against RFC1035
272 my $hostname = $_[0];
274 # Each part should be at least two characters in length
275 # but no more than 63 characters
276 if (length ($hostname) < 1 || length ($hostname) > 63) {
278 # Only valid characters are a-z, A-Z, 0-9 and -
279 if ($hostname !~ /^[a-zA-Z0-9-]*$/) {
281 # First character can only be a letter or a digit
282 if (substr ($hostname, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
284 # Last character can only be a letter or a digit
285 if (substr ($hostname, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
294 # Checks a domain name against RFC1035
295 my $domainname = $_[0];
296 my @parts = split (/\./, $domainname); # Split hostname at the '.'
298 foreach $part (@parts) {
299 # Each part should be at least two characters in length
300 # but no more than 63 characters
301 if (length ($part) < 2 || length ($part) > 63) {
303 # Only valid characters are a-z, A-Z, 0-9 and -
304 if ($part !~ /^[a-zA-Z0-9-]*$/) {
306 # First character can only be a letter or a digit
307 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
309 # Last character can only be a letter or a digit
310 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
320 # Checks a fully qualified domain name against RFC1035
322 my @parts = split (/\./, $fqdn); # Split hostname at the '.'
323 if (scalar(@parts) < 2) { # At least two parts should
324 return 0;} # exist in a FQDN
325 # (i.e. hostname.domain)
326 foreach $part (@parts) {
327 # Each part should be at least one character in length
328 # but no more than 63 characters
329 if (length ($part) < 1 || length ($part) > 63) {
331 # Only valid characters are a-z, A-Z, 0-9 and -
332 if ($part !~ /^[a-zA-Z0-9-]*$/) {
334 # First character can only be a letter or a digit
335 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
337 # Last character can only be a letter or a digit
338 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
344 sub validportrange
# used to check a port range
346 my $port = $_[0]; # port values
347 $port =~ tr/-/:/; # replace all - with colons just in case someone used -
348 my $srcdst = $_[1]; # is it a source or destination port
350 if (!($port =~ /^(\d+)\:(\d+)$/)) {
352 if (!(&validport
($port))) {
353 if ($srcdst eq 'src'){
354 return $Lang::tr
{'source port numbers'};
356 return $Lang::tr
{'destination port numbers'};
362 my @ports = ($1, $2);
364 if ($srcdst eq 'src'){
365 return $Lang::tr
{'bad source range'};
367 return $Lang::tr
{'bad destination range'};
372 if (!(&validport
($_))) {
373 if ($srcdst eq 'src'){
374 return $Lang::tr
{'source port numbers'};
376 return $Lang::tr
{'destination port numbers'};
384 # Test if IP is within a subnet
385 # Call: IpInSubnet (Addr, Subnet, Subnet Mask)
386 # Subnet can be an IP of the subnet: 10.0.0.0 or 10.0.0.1
387 # Everything in dottted notation
391 my $ip = unpack('N', &Socket
::inet_aton
(shift));
392 my $start = unpack('N', &Socket
::inet_aton
(shift));
393 my $mask = unpack('N', &Socket
::inet_aton
(shift));
394 $start &= $mask; # base of subnet...
395 my $end = $start + ~$mask;
396 return (($ip >= $start) && ($ip <= $end));
400 # Return the following IP (IP+1) in dotted notation.
401 # Call: NextIP ('1.1.1.1');
406 return &Socket
::inet_ntoa
( pack("N", 1 + unpack('N', &Socket
::inet_aton
(shift))
413 my ($ip,$cidr) = &Net
::IPv4Addr
::ipv4_parse
(shift);
419 my ($ip,$cidr) = &Net
::IPv4Addr
::ipv4_parse
(shift);
420 my $netmask = &Net
::IPv4Addr
::ipv4_cidr2msk
($cidr);
421 return "$ip\/$netmask";
427 return 0 if ( $mail !~ /^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/ );
428 return 0 if ( $mail =~ /^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/);
429 return 0 if ( $mail !~ /([0-9a-zA-Z]{1})\@./ );
430 return 0 if ( $mail !~ /.\@([0-9a-zA-Z]{1})/ );
431 return 0 if ( $mail =~ /.\.\-.|.\-\..|.\.\..|.\-\-./g );
432 return 0 if ( $mail =~ /.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./g );
433 return 0 if ( $mail !~ /\.([a-zA-Z]{2,4})$/ );
438 # Currently only vpnmain use this three procs (readhasharray, writehasharray, findhasharray)
439 # The 'key' used is numeric but is perfectly unneeded! This will to be removed so don't use
440 # this code. Vpnmain will be splitted in parts: x509/pki, connection ipsec, connection other,... .
443 my ($filename, $hash) = @_;
446 open(FILE
, $filename) or die "Unable to read file $filename";
449 my ($key, $rest, @temp);
451 ($key, $rest) = split (/,/, $_, 2);
452 if ($key =~ /^[0-9]+$/) {
453 @temp = split (/,/, $rest);
454 $hash->{$key} = \
@temp;
462 my ($filename, $hash) = @_;
463 my ($key, @temp, $i);
465 open(FILE
, ">$filename") or die "Unable to write to file $filename";
467 foreach $key (keys %$hash) {
468 if ($key =~ /^[0-9]+$/) {
470 foreach $i (0 .. $#{$hash->{$key}}) {
471 print FILE
",$hash->{$key}[$i]";
480 sub findhasharraykey
{
481 foreach my $i (1 .. 1000000) {
482 if ( ! exists $_[0]{$i}) {
489 # Darren Critchley - darrenc@telus.net - (c) 2003
490 # &srtarray(SortOrder, AlphaNumeric, SortDirection, ArrayToBeSorted)
491 # This subroutine will take the following parameters:
492 # ColumnNumber = the column which you want to sort on, starts at 1
493 # AlphaNumberic = a or n (lowercase) defines whether the sort should be alpha or numberic
494 # SortDirection = asc or dsc (lowercase) Ascending or Descending sort
495 # ArrayToBeSorted = the array that wants sorting
497 # Returns an array that is sorted to your specs
499 # If SortOrder is greater than the elements in array, then it defaults to the first element
502 my ($colno, $alpnum, $srtdir, @tobesorted) = @_;
508 my $ttlitems = scalar @tobesorted; # want to know the number of rows in the passed array
509 if ($ttlitems < 1){ # if no items, don't waste our time lets leave
510 return (@tobesorted);
512 my @tmp = split(/\,/,$tobesorted[0]);
513 $ttlitems = scalar @tmp; # this should be the number of elements in each row of the passed in array
515 # Darren Critchley - validate parameters
516 if ($colno > $ttlitems){$colno = '1';}
517 $colno--; # remove one from colno to deal with arrays starting at 0
518 if($colno < 0){$colno = '0';}
519 if ($alpnum ne '') { $alpnum = lc($alpnum); } else { $alpnum = 'a'; }
520 if ($srtdir ne '') { $srtdir = lc($srtdir); } else { $srtdir = 'src'; }
522 foreach $line (@tobesorted)
526 my @temp = split(/\,/,$line);
527 # Darren Critchley - juggle the fields so that the one we want to sort on is first
528 my $tmpholder = $temp[0];
529 $temp[0] = $temp[$colno];
530 $temp[$colno] = $tmpholder;
532 for ($ctr=0; $ctr < $ttlitems ; $ctr++) {
533 $newline=$newline . $temp[$ctr] . ",";
536 push(@tmparray,$newline);
539 if ($alpnum eq 'n') {
540 @tmparray = sort {$a <=> $b} @tmparray;
542 @tmparray = (sort @tmparray);
544 foreach $line (@tmparray)
548 my @temp = split(/\,/,$line);
549 my $tmpholder = $temp[0];
550 $temp[0] = $temp[$colno];
551 $temp[$colno] = $tmpholder;
553 for ($ctr=0; $ctr < $ttlitems ; $ctr++){
554 $newline=$newline . $temp[$ctr] . ",";
557 push(@srtedarray,$newline);
561 if ($srtdir eq 'dsc') {
562 @tmparray = reverse(@srtedarray);
565 return (@srtedarray);
571 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
572 if ($_=$proxysettings{'UPSTREAM_PROXY'}) {
573 my ($peer, $peerport) = (/^(?:[a-zA-Z ]+\:\/\
/)?(?:[A-Za-z0-9\_\.\-]*?(?:\:[A-Za-z0-9\_\.\-]*?)?\@)?([a-zA-Z0-9\.\_\-]*?)(?:\:([0-9]{1,5}))?(?:\/.*?
)?
$/);
574 Net
::SSLeay
::set_proxy
($peer,$peerport,$proxysettings{'UPSTREAM_USER'},$proxysettings{'UPSTREAM_PASSWORD'} );
576 my ($out, $response) = Net
::SSLeay
::get_http
( 'checkip.dyndns.org',
579 Net
::SSLeay
::make_headers
('User-Agent' => 'IPFire' )
581 if ($response =~ m
%HTTP/1\
.. 200 OK
%) {
582 $out =~ /Current IP Address: (\d+.\d+.\d+.\d+)/;
589 # Check if hostname.domain provided have IP provided
590 # use gethostbyname to verify that
596 # 1 IP matches host.domain
599 sub DyndnsServiceSync
($;$;$) {
601 my ($ip,$hostName,$domain) = @_;
604 #fix me no ip GROUP, what is the name ?
605 $hostName =~ s/$General::noipprefix//;
606 if ($hostName) { #may be empty
607 $hostName = "$hostName.$domain";
608 @addresses = gethostbyname($hostName);
611 if ($addresses[0] eq '') { # nothing returned ?
612 $hostName = $domain; # try resolving with domain only
613 @addresses = gethostbyname($hostName);
616 if ($addresses[0] ne '') { # got something ?
617 #&General::log("name:$addresses[0], alias:$addresses[1]");
618 # Build clear text list of IP
619 @addresses = map ( &Socket
::inet_ntoa
($_), @addresses[4..$#addresses]);
620 if (grep (/$ip/, @addresses)) {
627 # This sub returns the red IP used to compare in DyndnsServiceSync
631 &General
::readhash
("${General::swroot}/ddns/settings", \
%settings);
633 open(IP
, "${General::swroot}/red/local-ipaddress") or return 'unavailable';
638 if (&General
::IpInSubnet
($ip,'10.0.0.0','255.0.0.0') ||
639 &General
::IpInSubnet
($ip,'172.16.0.0.','255.240.0.0') ||
640 &General
::IpInSubnet
($ip,'192.168.0.0','255.255.0.0'))
642 if ($settings{'BEHINDROUTER'} eq 'FETCH_IP') {
643 my $RealIP = &General
::FetchPublicIp
;
644 $ip = (&General
::validip
($RealIP) ?
$RealIP : 'unavailable');
650 # Translate ICMP code to text
651 # ref: http://www.iana.org/assignments/icmp-parameters
652 sub GetIcmpDescription
($) {
654 my @icmp_description = (
658 'Destination Unreachable',
661 'Alternate Host Address',
664 'Router Advertisement',
665 'Router Solicitation', #10
670 'Information Request',
672 'Address Mask Request',
673 'Address Mask Reply',
674 'Reserved (for Security)',
675 'Reserved (for Robustness Experiment)', #20
686 'Datagram Conversion Error',
687 'Mobile Host Redirect',
688 'IPv6 Where-Are-You',
690 'Mobile Registration Request',
691 'Mobile Registration Reply',
692 'Domain Name Request',
697 if ($index>41) {return 'unknown'} else {return @icmp_description[$index]};