]>
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)
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) {
208 my $checkmac = $_[0];
209 my $ot = '[0-9a-f]{2}'; # 2 Hex digits (one octet)
210 if ($checkmac !~ /^$ot:$ot:$ot:$ot:$ot:$ot$/i)
219 # Checks a hostname against RFC1035
220 my $hostname = $_[0];
222 # Each part should be at least two characters in length
223 # but no more than 63 characters
224 if (length ($hostname) < 1 || length ($hostname) > 63) {
226 # Only valid characters are a-z, A-Z, 0-9 and -
227 if ($hostname !~ /^[a-zA-Z0-9-]*$/) {
229 # First character can only be a letter or a digit
230 if (substr ($hostname, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
232 # Last character can only be a letter or a digit
233 if (substr ($hostname, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
242 # Checks a domain name against RFC1035
243 my $domainname = $_[0];
244 my @parts = split (/\./, $domainname); # Split hostname at the '.'
246 foreach $part (@parts) {
247 # Each part should be at least two characters in length
248 # but no more than 63 characters
249 if (length ($part) < 2 || length ($part) > 63) {
251 # Only valid characters are a-z, A-Z, 0-9 and -
252 if ($part !~ /^[a-zA-Z0-9-]*$/) {
254 # First character can only be a letter or a digit
255 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
257 # Last character can only be a letter or a digit
258 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
268 # Checks a fully qualified domain name against RFC1035
270 my @parts = split (/\./, $fqdn); # Split hostname at the '.'
271 if (scalar(@parts) < 2) { # At least two parts should
272 return 0;} # exist in a FQDN
273 # (i.e. hostname.domain)
274 foreach $part (@parts) {
275 # Each part should be at least one character in length
276 # but no more than 63 characters
277 if (length ($part) < 1 || length ($part) > 63) {
279 # Only valid characters are a-z, A-Z, 0-9 and -
280 if ($part !~ /^[a-zA-Z0-9-]*$/) {
282 # First character can only be a letter or a digit
283 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
285 # Last character can only be a letter or a digit
286 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
292 sub validportrange
# used to check a port range
294 my $port = $_[0]; # port values
295 $port =~ tr/-/:/; # replace all - with colons just in case someone used -
296 my $srcdst = $_[1]; # is it a source or destination port
298 if (!($port =~ /^(\d+)\:(\d+)$/)) {
300 if (!(&validport
($port))) {
301 if ($srcdst eq 'src'){
302 return $Lang::tr
{'source port numbers'};
304 return $Lang::tr
{'destination port numbers'};
310 my @ports = ($1, $2);
312 if ($srcdst eq 'src'){
313 return $Lang::tr
{'bad source range'};
315 return $Lang::tr
{'bad destination range'};
320 if (!(&validport
($_))) {
321 if ($srcdst eq 'src'){
322 return $Lang::tr
{'source port numbers'};
324 return $Lang::tr
{'destination port numbers'};
332 # Test if IP is within a subnet
333 # Call: IpInSubnet (Addr, Subnet, Subnet Mask)
334 # Subnet can be an IP of the subnet: 10.0.0.0 or 10.0.0.1
335 # Everything in dottted notation
339 my $ip = unpack('N', &Socket
::inet_aton
(shift));
340 my $start = unpack('N', &Socket
::inet_aton
(shift));
341 my $mask = unpack('N', &Socket
::inet_aton
(shift));
342 $start &= $mask; # base of subnet...
343 my $end = $start + ~$mask;
344 return (($ip >= $start) && ($ip <= $end));
348 # Return the following IP (IP+1) in dotted notation.
349 # Call: NextIP ('1.1.1.1');
354 return &Socket
::inet_ntoa
( pack("N", 1 + unpack('N', &Socket
::inet_aton
(shift))
361 return 0 if ( $mail !~ /^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/ );
362 return 0 if ( $mail =~ /^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/);
363 return 0 if ( $mail !~ /([0-9a-zA-Z]{1})\@./ );
364 return 0 if ( $mail !~ /.\@([0-9a-zA-Z]{1})/ );
365 return 0 if ( $mail =~ /.\.\-.|.\-\..|.\.\..|.\-\-./g );
366 return 0 if ( $mail =~ /.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./g );
367 return 0 if ( $mail !~ /\.([a-zA-Z]{2,4})$/ );
372 # Currently only vpnmain use this three procs (readhasharray, writehasharray, findhasharray)
373 # The 'key' used is numeric but is perfectly unneeded! This will to be removed so don't use
374 # this code. Vpnmain will be splitted in parts: x509/pki, connection ipsec, connection other,... .
377 my ($filename, $hash) = @_;
380 open(FILE
, $filename) or die "Unable to read file $filename";
383 my ($key, $rest, @temp);
385 ($key, $rest) = split (/,/, $_, 2);
386 if ($key =~ /^[0-9]+$/) {
387 @temp = split (/,/, $rest);
388 $hash->{$key} = \
@temp;
396 my ($filename, $hash) = @_;
397 my ($key, @temp, $i);
399 open(FILE
, ">$filename") or die "Unable to write to file $filename";
401 foreach $key (keys %$hash) {
402 if ($key =~ /^[0-9]+$/) {
404 foreach $i (0 .. $#{$hash->{$key}}) {
405 print FILE
",$hash->{$key}[$i]";
414 sub findhasharraykey
{
415 foreach my $i (1 .. 1000000) {
416 if ( ! exists $_[0]{$i}) {
423 # Darren Critchley - darrenc@telus.net - (c) 2003
424 # &srtarray(SortOrder, AlphaNumeric, SortDirection, ArrayToBeSorted)
425 # This subroutine will take the following parameters:
426 # ColumnNumber = the column which you want to sort on, starts at 1
427 # AlphaNumberic = a or n (lowercase) defines whether the sort should be alpha or numberic
428 # SortDirection = asc or dsc (lowercase) Ascending or Descending sort
429 # ArrayToBeSorted = the array that wants sorting
431 # Returns an array that is sorted to your specs
433 # If SortOrder is greater than the elements in array, then it defaults to the first element
436 my ($colno, $alpnum, $srtdir, @tobesorted) = @_;
442 my $ttlitems = scalar @tobesorted; # want to know the number of rows in the passed array
443 if ($ttlitems < 1){ # if no items, don't waste our time lets leave
444 return (@tobesorted);
446 my @tmp = split(/\,/,$tobesorted[0]);
447 $ttlitems = scalar @tmp; # this should be the number of elements in each row of the passed in array
449 # Darren Critchley - validate parameters
450 if ($colno > $ttlitems){$colno = '1';}
451 $colno--; # remove one from colno to deal with arrays starting at 0
452 if($colno < 0){$colno = '0';}
453 if ($alpnum ne '') { $alpnum = lc($alpnum); } else { $alpnum = 'a'; }
454 if ($srtdir ne '') { $srtdir = lc($srtdir); } else { $srtdir = 'src'; }
456 foreach $line (@tobesorted)
460 my @temp = split(/\,/,$line);
461 # Darren Critchley - juggle the fields so that the one we want to sort on is first
462 my $tmpholder = $temp[0];
463 $temp[0] = $temp[$colno];
464 $temp[$colno] = $tmpholder;
466 for ($ctr=0; $ctr < $ttlitems ; $ctr++) {
467 $newline=$newline . $temp[$ctr] . ",";
470 push(@tmparray,$newline);
473 if ($alpnum eq 'n') {
474 @tmparray = sort {$a <=> $b} @tmparray;
476 @tmparray = (sort @tmparray);
478 foreach $line (@tmparray)
482 my @temp = split(/\,/,$line);
483 my $tmpholder = $temp[0];
484 $temp[0] = $temp[$colno];
485 $temp[$colno] = $tmpholder;
487 for ($ctr=0; $ctr < $ttlitems ; $ctr++){
488 $newline=$newline . $temp[$ctr] . ",";
491 push(@srtedarray,$newline);
495 if ($srtdir eq 'dsc') {
496 @tmparray = reverse(@srtedarray);
499 return (@srtedarray);
505 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
506 if ($_=$proxysettings{'UPSTREAM_PROXY'}) {
507 my ($peer, $peerport) = (/^(?:[a-zA-Z ]+\:\/\
/)?(?:[A-Za-z0-9\_\.\-]*?(?:\:[A-Za-z0-9\_\.\-]*?)?\@)?([a-zA-Z0-9\.\_\-]*?)(?:\:([0-9]{1,5}))?(?:\/.*?
)?
$/);
508 Net
::SSLeay
::set_proxy
($peer,$peerport,$proxysettings{'UPSTREAM_USER'},$proxysettings{'UPSTREAM_PASSWORD'} );
510 my ($out, $response) = Net
::SSLeay
::get_http
( 'checkip.dyndns.org',
513 Net
::SSLeay
::make_headers
('User-Agent' => 'IPFire' )
515 if ($response =~ m
%HTTP/1\
.. 200 OK
%) {
516 $out =~ /Current IP Address: (\d+.\d+.\d+.\d+)/;
523 # Check if hostname.domain provided have IP provided
524 # use gethostbyname to verify that
530 # 1 IP matches host.domain
533 sub DyndnsServiceSync
($;$;$) {
535 my ($ip,$hostName,$domain) = @_;
538 #fix me no ip GROUP, what is the name ?
539 $hostName =~ s/$General::noipprefix//;
540 if ($hostName) { #may be empty
541 $hostName = "$hostName.$domain";
542 @addresses = gethostbyname($hostName);
545 if ($addresses[0] eq '') { # nothing returned ?
546 $hostName = $domain; # try resolving with domain only
547 @addresses = gethostbyname($hostName);
550 if ($addresses[0] ne '') { # got something ?
551 #&General::log("name:$addresses[0], alias:$addresses[1]");
552 # Build clear text list of IP
553 @addresses = map ( &Socket
::inet_ntoa
($_), @addresses[4..$#addresses]);
554 if (grep (/$ip/, @addresses)) {
561 # This sub returns the red IP used to compare in DyndnsServiceSync
565 &General
::readhash
("${General::swroot}/ddns/settings", \
%settings);
567 open(IP
, "${General::swroot}/red/local-ipaddress") or return 'unavailable';
572 if (&General
::IpInSubnet
($ip,'10.0.0.0','255.0.0.0') ||
573 &General
::IpInSubnet
($ip,'172.16.0.0.','255.240.0.0') ||
574 &General
::IpInSubnet
($ip,'192.168.0.0','255.255.0.0'))
576 if ($settings{'BEHINDROUTER'} eq 'FETCH_IP') {
577 my $RealIP = &General
::FetchPublicIp
;
578 $ip = (&General
::validip
($RealIP) ?
$RealIP : 'unavailable');
584 # Translate ICMP code to text
585 # ref: http://www.iana.org/assignments/icmp-parameters
586 sub GetIcmpDescription
($) {
588 my @icmp_description = (
592 'Destination Unreachable',
595 'Alternate Host Address',
598 'Router Advertisement',
599 'Router Solicitation', #10
604 'Information Request',
606 'Address Mask Request',
607 'Address Mask Reply',
608 'Reserved (for Security)',
609 'Reserved (for Robustness Experiment)', #20
620 'Datagram Conversion Error',
621 'Mobile Host Redirect',
622 'IPv6 Where-Are-You',
624 'Mobile Registration Request',
625 'Mobile Registration Reply',
626 'Domain Name Request',
631 if ($index>41) {return 'unknown'} else {return @icmp_description[$index]};