]>
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 $
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)
91 if ( $var eq "__CGI__"){next;}
93 # Darren Critchley Jan 17, 2003 added the following because when submitting with a graphic, the x and y
94 # location of the mouse are submitted as well, this was being written to the settings file causing
95 # some serious grief! This skips the variable.x and variable.y
96 if (!($var =~ /(.x|.y)$/)) {
99 if (!($var =~ /^ACTION/)) {
100 print FILE
"${var}=${val}\n"; }
109 my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
110 $atime, $mtime, $ctime, $blksize, $blocks) = stat $_[0];
113 my $totalsecs = $now - $mtime;
114 my $days = int($totalsecs / 86400);
115 my $totalhours = int($totalsecs / 3600);
116 my $hours = $totalhours % 24;
117 my $totalmins = int($totalsecs / 60);
118 my $mins = $totalmins % 60;
119 my $secs = $totalsecs % 60;
121 return "${days}d ${hours}h ${mins}m ${secs}s";
128 if (!($ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/)) {
132 my @octets = ($1, $2, $3, $4);
137 if ($_ < 0 || $_ > 255) {
149 if (&validip
($mask)) {
151 # second part a number?
154 if (!($mask =~ /^\d+$/)) {
156 if ($mask >= 0 && $mask <= 32) {
163 my $ipormask = $_[0];
165 # see if it is a IP only.
166 if (&validip
($ipormask)) {
168 # split it into number and mask.
169 if (!($ipormask =~ /^(.*?)\/(.*?
)$/)) {
173 # first part not a ip?
174 if (!(&validip
($ip))) {
176 return &validmask
($mask);
181 my $ipandmask = $_[0];
183 # split it into number and mask.
184 if (!($ipandmask =~ /^(.*?)\/(.*?
)$/)) {
188 # first part not a ip?
189 if (!(&validip
($ip))) {
191 return &validmask
($mask);
202 if ($_ >= 1 && $_ <= 65535) {
215 if ($_ == 53 || $_ == 222 || $_ == 444 || $_ == 81 ) {
217 elsif ($_ >= 1 && $_ <= 65535) {
224 my $checkmac = $_[0];
225 my $ot = '[0-9a-f]{2}'; # 2 Hex digits (one octet)
226 if ($checkmac !~ /^$ot:$ot:$ot:$ot:$ot:$ot$/i)
235 # Checks a hostname against RFC1035
236 my $hostname = $_[0];
238 # Each part should be at least two characters in length
239 # but no more than 63 characters
240 if (length ($hostname) < 1 || length ($hostname) > 63) {
242 # Only valid characters are a-z, A-Z, 0-9 and -
243 if ($hostname !~ /^[a-zA-Z0-9-]*$/) {
245 # First character can only be a letter or a digit
246 if (substr ($hostname, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
248 # Last character can only be a letter or a digit
249 if (substr ($hostname, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
258 # Checks a domain name against RFC1035
259 my $domainname = $_[0];
260 my @parts = split (/\./, $domainname); # Split hostname at the '.'
262 foreach $part (@parts) {
263 # Each part should be at least two characters in length
264 # but no more than 63 characters
265 if (length ($part) < 2 || length ($part) > 63) {
267 # Only valid characters are a-z, A-Z, 0-9 and -
268 if ($part !~ /^[a-zA-Z0-9-]*$/) {
270 # First character can only be a letter or a digit
271 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
273 # Last character can only be a letter or a digit
274 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
284 # Checks a fully qualified domain name against RFC1035
286 my @parts = split (/\./, $fqdn); # Split hostname at the '.'
287 if (scalar(@parts) < 2) { # At least two parts should
288 return 0;} # exist in a FQDN
289 # (i.e. hostname.domain)
290 foreach $part (@parts) {
291 # Each part should be at least one character in length
292 # but no more than 63 characters
293 if (length ($part) < 1 || length ($part) > 63) {
295 # Only valid characters are a-z, A-Z, 0-9 and -
296 if ($part !~ /^[a-zA-Z0-9-]*$/) {
298 # First character can only be a letter or a digit
299 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
301 # Last character can only be a letter or a digit
302 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
308 sub validportrange
# used to check a port range
310 my $port = $_[0]; # port values
311 $port =~ tr/-/:/; # replace all - with colons just in case someone used -
312 my $srcdst = $_[1]; # is it a source or destination port
314 if (!($port =~ /^(\d+)\:(\d+)$/)) {
316 if (!(&validport
($port))) {
317 if ($srcdst eq 'src'){
318 return $Lang::tr
{'source port numbers'};
320 return $Lang::tr
{'destination port numbers'};
326 my @ports = ($1, $2);
328 if ($srcdst eq 'src'){
329 return $Lang::tr
{'bad source range'};
331 return $Lang::tr
{'bad destination range'};
336 if (!(&validport
($_))) {
337 if ($srcdst eq 'src'){
338 return $Lang::tr
{'source port numbers'};
340 return $Lang::tr
{'destination port numbers'};
348 # Test if IP is within a subnet
349 # Call: IpInSubnet (Addr, Subnet, Subnet Mask)
350 # Subnet can be an IP of the subnet: 10.0.0.0 or 10.0.0.1
351 # Everything in dottted notation
355 my $ip = unpack('N', &Socket
::inet_aton
(shift));
356 my $start = unpack('N', &Socket
::inet_aton
(shift));
357 my $mask = unpack('N', &Socket
::inet_aton
(shift));
358 $start &= $mask; # base of subnet...
359 my $end = $start + ~$mask;
360 return (($ip >= $start) && ($ip <= $end));
364 # Return the following IP (IP+1) in dotted notation.
365 # Call: NextIP ('1.1.1.1');
370 return &Socket
::inet_ntoa
( pack("N", 1 + unpack('N', &Socket
::inet_aton
(shift))
377 return 0 if ( $mail !~ /^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/ );
378 return 0 if ( $mail =~ /^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/);
379 return 0 if ( $mail !~ /([0-9a-zA-Z]{1})\@./ );
380 return 0 if ( $mail !~ /.\@([0-9a-zA-Z]{1})/ );
381 return 0 if ( $mail =~ /.\.\-.|.\-\..|.\.\..|.\-\-./g );
382 return 0 if ( $mail =~ /.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./g );
383 return 0 if ( $mail !~ /\.([a-zA-Z]{2,4})$/ );
388 # Currently only vpnmain use this three procs (readhasharray, writehasharray, findhasharray)
389 # The 'key' used is numeric but is perfectly unneeded! This will to be removed so don't use
390 # this code. Vpnmain will be splitted in parts: x509/pki, connection ipsec, connection other,... .
393 my ($filename, $hash) = @_;
396 open(FILE
, $filename) or die "Unable to read file $filename";
399 my ($key, $rest, @temp);
401 ($key, $rest) = split (/,/, $_, 2);
402 if ($key =~ /^[0-9]+$/) {
403 @temp = split (/,/, $rest);
404 $hash->{$key} = \
@temp;
412 my ($filename, $hash) = @_;
413 my ($key, @temp, $i);
415 open(FILE
, ">$filename") or die "Unable to write to file $filename";
417 foreach $key (keys %$hash) {
418 if ($key =~ /^[0-9]+$/) {
420 foreach $i (0 .. $#{$hash->{$key}}) {
421 print FILE
",$hash->{$key}[$i]";
430 sub findhasharraykey
{
431 foreach my $i (1 .. 1000000) {
432 if ( ! exists $_[0]{$i}) {
439 # Darren Critchley - darrenc@telus.net - (c) 2003
440 # &srtarray(SortOrder, AlphaNumeric, SortDirection, ArrayToBeSorted)
441 # This subroutine will take the following parameters:
442 # ColumnNumber = the column which you want to sort on, starts at 1
443 # AlphaNumberic = a or n (lowercase) defines whether the sort should be alpha or numberic
444 # SortDirection = asc or dsc (lowercase) Ascending or Descending sort
445 # ArrayToBeSorted = the array that wants sorting
447 # Returns an array that is sorted to your specs
449 # If SortOrder is greater than the elements in array, then it defaults to the first element
452 my ($colno, $alpnum, $srtdir, @tobesorted) = @_;
458 my $ttlitems = scalar @tobesorted; # want to know the number of rows in the passed array
459 if ($ttlitems < 1){ # if no items, don't waste our time lets leave
460 return (@tobesorted);
462 my @tmp = split(/\,/,$tobesorted[0]);
463 $ttlitems = scalar @tmp; # this should be the number of elements in each row of the passed in array
465 # Darren Critchley - validate parameters
466 if ($colno > $ttlitems){$colno = '1';}
467 $colno--; # remove one from colno to deal with arrays starting at 0
468 if($colno < 0){$colno = '0';}
469 if ($alpnum ne '') { $alpnum = lc($alpnum); } else { $alpnum = 'a'; }
470 if ($srtdir ne '') { $srtdir = lc($srtdir); } else { $srtdir = 'src'; }
472 foreach $line (@tobesorted)
476 my @temp = split(/\,/,$line);
477 # Darren Critchley - juggle the fields so that the one we want to sort on is first
478 my $tmpholder = $temp[0];
479 $temp[0] = $temp[$colno];
480 $temp[$colno] = $tmpholder;
482 for ($ctr=0; $ctr < $ttlitems ; $ctr++) {
483 $newline=$newline . $temp[$ctr] . ",";
486 push(@tmparray,$newline);
489 if ($alpnum eq 'n') {
490 @tmparray = sort {$a <=> $b} @tmparray;
492 @tmparray = (sort @tmparray);
494 foreach $line (@tmparray)
498 my @temp = split(/\,/,$line);
499 my $tmpholder = $temp[0];
500 $temp[0] = $temp[$colno];
501 $temp[$colno] = $tmpholder;
503 for ($ctr=0; $ctr < $ttlitems ; $ctr++){
504 $newline=$newline . $temp[$ctr] . ",";
507 push(@srtedarray,$newline);
511 if ($srtdir eq 'dsc') {
512 @tmparray = reverse(@srtedarray);
515 return (@srtedarray);
521 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
522 if ($_=$proxysettings{'UPSTREAM_PROXY'}) {
523 my ($peer, $peerport) = (/^(?:[a-zA-Z ]+\:\/\
/)?(?:[A-Za-z0-9\_\.\-]*?(?:\:[A-Za-z0-9\_\.\-]*?)?\@)?([a-zA-Z0-9\.\_\-]*?)(?:\:([0-9]{1,5}))?(?:\/.*?
)?
$/);
524 Net
::SSLeay
::set_proxy
($peer,$peerport,$proxysettings{'UPSTREAM_USER'},$proxysettings{'UPSTREAM_PASSWORD'} );
526 my ($out, $response) = Net
::SSLeay
::get_http
( 'checkip.dyndns.org',
529 Net
::SSLeay
::make_headers
('User-Agent' => 'IPFire' )
531 if ($response =~ m
%HTTP/1\
.. 200 OK
%) {
532 $out =~ /Current IP Address: (\d+.\d+.\d+.\d+)/;
539 # Check if hostname.domain provided have IP provided
540 # use gethostbyname to verify that
546 # 1 IP matches host.domain
549 sub DyndnsServiceSync
($;$;$) {
551 my ($ip,$hostName,$domain) = @_;
554 #fix me no ip GROUP, what is the name ?
555 $hostName =~ s/$General::noipprefix//;
556 if ($hostName) { #may be empty
557 $hostName = "$hostName.$domain";
558 @addresses = gethostbyname($hostName);
561 if ($addresses[0] eq '') { # nothing returned ?
562 $hostName = $domain; # try resolving with domain only
563 @addresses = gethostbyname($hostName);
566 if ($addresses[0] ne '') { # got something ?
567 #&General::log("name:$addresses[0], alias:$addresses[1]");
568 # Build clear text list of IP
569 @addresses = map ( &Socket
::inet_ntoa
($_), @addresses[4..$#addresses]);
570 if (grep (/$ip/, @addresses)) {
577 # This sub returns the red IP used to compare in DyndnsServiceSync
581 &General
::readhash
("${General::swroot}/ddns/settings", \
%settings);
583 open(IP
, "${General::swroot}/red/local-ipaddress") or return 'unavailable';
588 if (&General
::IpInSubnet
($ip,'10.0.0.0','255.0.0.0') ||
589 &General
::IpInSubnet
($ip,'172.16.0.0.','255.240.0.0') ||
590 &General
::IpInSubnet
($ip,'192.168.0.0','255.255.0.0'))
592 if ($settings{'BEHINDROUTER'} eq 'FETCH_IP') {
593 my $RealIP = &General
::FetchPublicIp
;
594 $ip = (&General
::validip
($RealIP) ?
$RealIP : 'unavailable');
600 # Translate ICMP code to text
601 # ref: http://www.iana.org/assignments/icmp-parameters
602 sub GetIcmpDescription
($) {
604 my @icmp_description = (
608 'Destination Unreachable',
611 'Alternate Host Address',
614 'Router Advertisement',
615 'Router Solicitation', #10
620 'Information Request',
622 'Address Mask Request',
623 'Address Mask Reply',
624 'Reserved (for Security)',
625 'Reserved (for Robustness Experiment)', #20
636 'Datagram Conversion Error',
637 'Mobile Host Redirect',
638 'IPv6 Where-Are-You',
640 'Mobile Registration Request',
641 'Mobile Registration Reply',
642 'Domain Name Request',
647 if ($index>41) {return 'unknown'} else {return @icmp_description[$index]};