]>
git.ipfire.org Git - people/pmueller/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 return 0 if ( $mail !~ /^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/ );
420 return 0 if ( $mail =~ /^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/);
421 return 0 if ( $mail !~ /([0-9a-zA-Z]{1})\@./ );
422 return 0 if ( $mail !~ /.\@([0-9a-zA-Z]{1})/ );
423 return 0 if ( $mail =~ /.\.\-.|.\-\..|.\.\..|.\-\-./g );
424 return 0 if ( $mail =~ /.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./g );
425 return 0 if ( $mail !~ /\.([a-zA-Z]{2,4})$/ );
430 # Currently only vpnmain use this three procs (readhasharray, writehasharray, findhasharray)
431 # The 'key' used is numeric but is perfectly unneeded! This will to be removed so don't use
432 # this code. Vpnmain will be splitted in parts: x509/pki, connection ipsec, connection other,... .
435 my ($filename, $hash) = @_;
438 open(FILE
, $filename) or die "Unable to read file $filename";
441 my ($key, $rest, @temp);
443 ($key, $rest) = split (/,/, $_, 2);
444 if ($key =~ /^[0-9]+$/) {
445 @temp = split (/,/, $rest);
446 $hash->{$key} = \
@temp;
454 my ($filename, $hash) = @_;
455 my ($key, @temp, $i);
457 open(FILE
, ">$filename") or die "Unable to write to file $filename";
459 foreach $key (keys %$hash) {
460 if ($key =~ /^[0-9]+$/) {
462 foreach $i (0 .. $#{$hash->{$key}}) {
463 print FILE
",$hash->{$key}[$i]";
472 sub findhasharraykey
{
473 foreach my $i (1 .. 1000000) {
474 if ( ! exists $_[0]{$i}) {
481 # Darren Critchley - darrenc@telus.net - (c) 2003
482 # &srtarray(SortOrder, AlphaNumeric, SortDirection, ArrayToBeSorted)
483 # This subroutine will take the following parameters:
484 # ColumnNumber = the column which you want to sort on, starts at 1
485 # AlphaNumberic = a or n (lowercase) defines whether the sort should be alpha or numberic
486 # SortDirection = asc or dsc (lowercase) Ascending or Descending sort
487 # ArrayToBeSorted = the array that wants sorting
489 # Returns an array that is sorted to your specs
491 # If SortOrder is greater than the elements in array, then it defaults to the first element
494 my ($colno, $alpnum, $srtdir, @tobesorted) = @_;
500 my $ttlitems = scalar @tobesorted; # want to know the number of rows in the passed array
501 if ($ttlitems < 1){ # if no items, don't waste our time lets leave
502 return (@tobesorted);
504 my @tmp = split(/\,/,$tobesorted[0]);
505 $ttlitems = scalar @tmp; # this should be the number of elements in each row of the passed in array
507 # Darren Critchley - validate parameters
508 if ($colno > $ttlitems){$colno = '1';}
509 $colno--; # remove one from colno to deal with arrays starting at 0
510 if($colno < 0){$colno = '0';}
511 if ($alpnum ne '') { $alpnum = lc($alpnum); } else { $alpnum = 'a'; }
512 if ($srtdir ne '') { $srtdir = lc($srtdir); } else { $srtdir = 'src'; }
514 foreach $line (@tobesorted)
518 my @temp = split(/\,/,$line);
519 # Darren Critchley - juggle the fields so that the one we want to sort on is first
520 my $tmpholder = $temp[0];
521 $temp[0] = $temp[$colno];
522 $temp[$colno] = $tmpholder;
524 for ($ctr=0; $ctr < $ttlitems ; $ctr++) {
525 $newline=$newline . $temp[$ctr] . ",";
528 push(@tmparray,$newline);
531 if ($alpnum eq 'n') {
532 @tmparray = sort {$a <=> $b} @tmparray;
534 @tmparray = (sort @tmparray);
536 foreach $line (@tmparray)
540 my @temp = split(/\,/,$line);
541 my $tmpholder = $temp[0];
542 $temp[0] = $temp[$colno];
543 $temp[$colno] = $tmpholder;
545 for ($ctr=0; $ctr < $ttlitems ; $ctr++){
546 $newline=$newline . $temp[$ctr] . ",";
549 push(@srtedarray,$newline);
553 if ($srtdir eq 'dsc') {
554 @tmparray = reverse(@srtedarray);
557 return (@srtedarray);
563 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
564 if ($_=$proxysettings{'UPSTREAM_PROXY'}) {
565 my ($peer, $peerport) = (/^(?:[a-zA-Z ]+\:\/\
/)?(?:[A-Za-z0-9\_\.\-]*?(?:\:[A-Za-z0-9\_\.\-]*?)?\@)?([a-zA-Z0-9\.\_\-]*?)(?:\:([0-9]{1,5}))?(?:\/.*?
)?
$/);
566 Net
::SSLeay
::set_proxy
($peer,$peerport,$proxysettings{'UPSTREAM_USER'},$proxysettings{'UPSTREAM_PASSWORD'} );
568 my ($out, $response) = Net
::SSLeay
::get_http
( 'checkip.dyndns.org',
571 Net
::SSLeay
::make_headers
('User-Agent' => 'IPFire' )
573 if ($response =~ m
%HTTP/1\
.. 200 OK
%) {
574 $out =~ /Current IP Address: (\d+.\d+.\d+.\d+)/;
581 # Check if hostname.domain provided have IP provided
582 # use gethostbyname to verify that
588 # 1 IP matches host.domain
591 sub DyndnsServiceSync
($;$;$) {
593 my ($ip,$hostName,$domain) = @_;
596 #fix me no ip GROUP, what is the name ?
597 $hostName =~ s/$General::noipprefix//;
598 if ($hostName) { #may be empty
599 $hostName = "$hostName.$domain";
600 @addresses = gethostbyname($hostName);
603 if ($addresses[0] eq '') { # nothing returned ?
604 $hostName = $domain; # try resolving with domain only
605 @addresses = gethostbyname($hostName);
608 if ($addresses[0] ne '') { # got something ?
609 #&General::log("name:$addresses[0], alias:$addresses[1]");
610 # Build clear text list of IP
611 @addresses = map ( &Socket
::inet_ntoa
($_), @addresses[4..$#addresses]);
612 if (grep (/$ip/, @addresses)) {
619 # This sub returns the red IP used to compare in DyndnsServiceSync
623 &General
::readhash
("${General::swroot}/ddns/settings", \
%settings);
625 open(IP
, "${General::swroot}/red/local-ipaddress") or return 'unavailable';
630 if (&General
::IpInSubnet
($ip,'10.0.0.0','255.0.0.0') ||
631 &General
::IpInSubnet
($ip,'172.16.0.0.','255.240.0.0') ||
632 &General
::IpInSubnet
($ip,'192.168.0.0','255.255.0.0'))
634 if ($settings{'BEHINDROUTER'} eq 'FETCH_IP') {
635 my $RealIP = &General
::FetchPublicIp
;
636 $ip = (&General
::validip
($RealIP) ?
$RealIP : 'unavailable');
642 # Translate ICMP code to text
643 # ref: http://www.iana.org/assignments/icmp-parameters
644 sub GetIcmpDescription
($) {
646 my @icmp_description = (
650 'Destination Unreachable',
653 'Alternate Host Address',
656 'Router Advertisement',
657 'Router Solicitation', #10
662 'Information Request',
664 'Address Mask Request',
665 'Address Mask Reply',
666 'Reserved (for Security)',
667 'Reserved (for Robustness Experiment)', #20
678 'Datagram Conversion Error',
679 'Mobile Host Redirect',
680 'IPv6 Where-Are-You',
682 'Mobile Registration Request',
683 'Mobile Registration Reply',
684 'Domain Name Request',
689 if ($index>41) {return 'unknown'} else {return @icmp_description[$index]};