]>
git.ipfire.org Git - people/jschlag/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 $
21 use Net
::IPv4Addr
qw(:all);
22 $|=1; # line buffering
24 $General::version
= '2.11';
25 $General::swroot
= '/var/ipfire';
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);
42 sub setup_default_networks
45 my $defaultNetworks = shift;
47 &readhash
("/var/ipfire/ethernet/settings", \
%netsettings);
49 # Get current defined networks (Red, Green, Blue, Orange)
50 $defaultNetworks->{$Lang::tr{'fwhost any'}}{'IPT'} = "0.0.0.0/0.0.0.0";
51 $defaultNetworks->{$Lang::tr{'fwhost any'}}{'NAME'} = "ALL";
53 $defaultNetworks->{$Lang::tr{'green'}}{'IPT'} = "$netsettings{'GREEN_NETADDRESS'}/$netsettings{'GREEN_NETMASK'}";
54 $defaultNetworks->{$Lang::tr{'green'}}{'NAME'} = "GREEN";
56 if ($netsettings{'RED_DEV'} ne ''){
57 $defaultNetworks->{$Lang::tr{'fwdfw red'}}{'IPT'} = "$netsettings{'RED_NETADDRESS'}/$netsettings{'RED_NETMASK'}";
58 $defaultNetworks->{$Lang::tr{'fwdfw red'}}{'NAME'} = "RED";
60 if ($netsettings{'ORANGE_DEV'} ne ''){
61 $defaultNetworks->{$Lang::tr{'orange'}}{'IPT'} = "$netsettings{'ORANGE_NETADDRESS'}/$netsettings{'ORANGE_NETMASK'}";
62 $defaultNetworks->{$Lang::tr{'orange'}}{'NAME'} = "ORANGE";
65 if ($netsettings{'BLUE_DEV'} ne ''){
66 $defaultNetworks->{$Lang::tr{'blue'}}{'IPT'} = "$netsettings{'BLUE_NETADDRESS'}/$netsettings{'BLUE_NETMASK'}";
67 $defaultNetworks->{$Lang::tr{'blue'}}{'NAME'} = "BLUE";
71 $defaultNetworks->{'IPFire'}{'NAME'} = "IPFire";
74 if(-e
"${General::swroot}/ovpn/settings")
76 my %ovpnSettings = ();
77 &readhash
("${General::swroot}/ovpn/settings", \
%ovpnSettings);
80 if(defined($ovpnSettings{'DOVPN_SUBNET'}))
82 my ($ip,$sub) = split(/\//,$ovpnSettings{'DOVPN_SUBNET'});
83 $sub=&General
::iporsubtocidr
($sub);
84 my @tempovpnsubnet = split("\/", $ovpnSettings{'DOVPN_SUBNET'});
85 $defaultNetworks->{'OpenVPN ' ."($ip/$sub)"}{'ADR'} = $tempovpnsubnet[0];
86 $defaultNetworks->{'OpenVPN ' ."($ip/$sub)"}{'NAME'} = "OpenVPN-Dyn";
90 if(-e
"${General::swroot}/vpn/settings")
92 my %ipsecsettings = ();
93 &readhash
("${General::swroot}/vpn/settings", \
%ipsecsettings);
94 if($ipsecsettings{'RW_NET'} ne '')
96 my ($ip,$sub) = split(/\//,$ipsecsettings{'RW_NET'});
97 $sub=&General
::iporsubtocidr
($sub);
98 my @tempipsecsubnet = split("\/", $ipsecsettings{'RW_NET'});
99 $defaultNetworks->{'IPsec RW ' .$ip."/".$sub}{'ADR'} = $tempipsecsubnet[0];
100 $defaultNetworks->{'IPsec RW ' .$ip."/".$sub}{'NAME'} = "IPsec RW";
107 my $defaultNetworks = shift;
108 open(FILE
, "${General::swroot}/ethernet/aliases") or die 'Unable to open aliases file.';
109 my @current = <FILE
>;
112 foreach my $line (@current)
116 my @temp = split(/\,/,$line);
117 if ($temp[2] eq '') {
118 $temp[2] = "Alias $ctr : $temp[0]";
120 $defaultNetworks->{$temp[2]}{'IPT'} = "$temp[0]";
129 my $filename = $_[0];
134 # Some ipcop code expects that readhash 'complete' the hash if new entries
135 # are presents. Not clear it !!!
138 open(FILE
, $filename) or die "Unable to read file $filename";
143 ($var, $val) = split /=/, $_, 2;
149 # Untaint variables read from hash
150 # trim space from begin and end
153 $var =~ /([A-Za-z0-9_-]*)/;
157 $hash->{$var} = $val;
166 my $filename = $_[0];
170 # write cgi vars to the file.
171 open(FILE
, ">${filename}") or die "Unable to write file $filename";
173 foreach $var (keys %$hash)
175 if ( $var eq "__CGI__"){next;}
176 $val = $hash->{$var};
177 # Darren Critchley Jan 17, 2003 added the following because when submitting with a graphic, the x and y
178 # location of the mouse are submitted as well, this was being written to the settings file causing
179 # some serious grief! This skips the variable.x and variable.y
180 if (!($var =~ /(.x|.y)$/)) {
183 if (!($var =~ /^ACTION/)) {
184 print FILE
"${var}=${val}\n"; }
192 # This function replaces the given hash in the original hash by keeping the old
193 # content and just replacing the new content
195 my $filename = $_[0];
200 readhash
("${filename}", \
%oldhash);
202 foreach $var (keys %$newhash){
203 $oldhash{$var}=$newhash->{$var};
206 # write cgi vars to the file.
207 open(FILE
, ">${filename}") or die "Unable to write file $filename";
209 foreach $var (keys %oldhash)
211 if ( $var eq "__CGI__"){next;}
212 $val = $oldhash{$var};
213 # Darren Critchley Jan 17, 2003 added the following because when submitting with a graphic, the x and y
214 # location of the mouse are submitted as well, this was being written to the settings file causing
215 # some serious grief! This skips the variable.x and variable.y
216 if (!($var =~ /(.x|.y)$/)) {
219 if (!($var =~ /^ACTION/)) {
220 print FILE
"${var}=${val}\n"; }
228 my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
229 $atime, $mtime, $ctime, $blksize, $blocks) = stat $_[0];
232 my $dset = 0; # Day is set, when > 0
233 my $hset = 0; # Hour is set, when > 0
234 my $mset = 0; # Minute is set, when > 0
236 my $totalsecs = $now - $mtime;
237 my $days = int($totalsecs / 86400);
238 my $totalhours = int($totalsecs / 3600);
239 my $hours = $totalhours % 24;
240 my $totalmins = int($totalsecs / 60);
241 my $mins = $totalmins % 60;
242 my $secs = $totalsecs % 60;
245 ${timestring
} .= ${days
}.' '.$Lang::tr
{'days'}.', ';
249 ${timestring
} .= ${days
}.' '.$Lang::tr
{'day'}.', ';
253 if (($hours > 1) && !($dset)) {
254 ${timestring
} .= ${hours
}.' '.$Lang::tr
{'hours'}.', ';
257 elsif (($hours == 1) && !($dset)) {
258 ${timestring
} .= ${hours
}.' '.$Lang::tr
{'hour'}.', ';
262 ${timestring
} .= ${hours
}.' '.$Lang::tr
{'age shour'}.', ';
266 if ((($mins > 1) || ($mins == 0)) && !($dset || $hset)) {
267 ${timestring
} .= ${mins
}.' '.$Lang::tr
{'minutes'}.', ';
270 elsif (($mins == 1) && !($dset || $hset)) {
271 ${timestring
} .= ${mins
}.' '.$Lang::tr
{'minute'}.', ';
275 ${timestring
} .= ${mins
}.' '.$Lang::tr
{'age sminute'}.', ';
279 if ((($secs > 1) || ($secs == 0)) && !($dset || $hset || $mset)) {
280 ${timestring
} .= ${secs
}.' '.$Lang::tr
{'age seconds'};
282 elsif (($secs == 1) && !($dset || $hset || $mset)) {
283 ${timestring
} .= $secs.' '.$Lang::tr
{'age second'};
285 else { ${timestring
} .= $secs.' '.$Lang::tr
{'age ssecond'}; }
287 return ${timestring
};
294 if (!($ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/)) {
298 my @octets = ($1, $2, $3, $4);
303 if ($_ < 0 || $_ > 255) {
315 if (&validip
($mask)) {
317 # second part a number?
320 if (!($mask =~ /^\d+$/)) {
322 if ($mask >= 0 && $mask <= 32) {
329 my $ipormask = $_[0];
331 # see if it is a IP only.
332 if (&validip
($ipormask)) {
334 # split it into number and mask.
335 if (!($ipormask =~ /^(.*?)\/(.*?
)$/)) {
339 # first part not a ip?
340 if (!(&validip
($ip))) {
342 return &validmask
($mask);
347 #gets: Subnet in decimal (255.255.255.0)
348 #Gives: 24 (The cidr of network)
349 my ($byte1, $byte2, $byte3, $byte4) = split(/\./, $_[0].".0.0.0.0");
350 my $num = ($byte1 * 16777216) + ($byte2 * 65536) + ($byte3 * 256) + $byte4;
351 my $bin = unpack("B*", pack("N", $num));
352 my $count = ($bin =~ tr/1/1/);
358 #gets: Cidr of network (20-30 for ccd)
359 #Konverts 30 to 255.255.255.252 e.g
361 my $netmask = &Net
::IPv4Addr
::ipv4_cidr2msk
($cidr);
367 #Gets: Ip address or subnetmask in decimal oder CIDR
368 #Gives: What it gets only in CIDR format
373 if ($subnet =~ /^(.*?)\/(.*?
)$/) {
374 ($net,$mask) = split (/\//,$subnet);
380 #Subnet already in decimal and valid?
381 if ($mask=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&(($1<=255 && $2<=$1 && $3<=$2 && $4<=$3 ))) {
382 for (my $i=8;$i<=32;$i++){
383 if (&General
::cidrtosub
($i) eq $mask){
384 if ($full == 0){return $mask;}else{
385 return $net."/".$mask;
390 #Subnet in binary format?
391 if ($mask=~/^(\d{1,2})$/ && (($1<=32 && $1>=8))){
392 if($full == 0){ return &General
::cidrtosub
($mask);}else{
393 return $net."/".&General
::cidrtosub
($mask);
404 #gets: Ip Address or subnetmask in decimal oder CIDR
405 #Gives: What it gets only in CIDR format
410 if ($subnet =~ /^(.*?)\/(.*?
)$/) {
411 ($net,$mask) = split (/\//,$subnet);
416 #Subnet in decimal and valid?
417 if ($mask=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&(($1<=255 && $2<=$1 && $3<=$2 && $4<=$3 ))) {
418 for (my $i=8;$i<=32;$i++){
419 if (&General
::cidrtosub
($i) eq $mask){
420 if ($full == 0){return &General
::subtocidr
($mask);}else{
421 return $net."/".&General
::subtocidr
($mask);
426 #Subnet already in binary format?
427 if ($mask=~/^(\d{1,2})$/ && (($1<=32 && $1>=8))){
428 if($full == 0){ return $mask;}else{
429 return $net."/".$mask;
439 #Gets: IP, CIDR (10.10.10.0-255, 24)
441 my ($ccdip,$ccdsubnet) = @_;
442 my $ip_address_binary = inet_aton
( $ccdip );
443 my $netmask_binary = ~pack("N", (2**(32-$ccdsubnet))-1);
444 my $network_address = inet_ntoa
( $ip_address_binary & $netmask_binary );
445 return $network_address;
450 #Gets: IP in Form ("192.168.0.0/24")
451 #Gives: Broadcastaddress of network
453 my ($ccdip,$ccdsubnet) = split "/",$ccdnet;
454 my $ip_address_binary = inet_aton
( $ccdip );
455 my $netmask_binary = ~pack("N", (2**(32-$ccdsubnet))-1);
456 my $broadcast_address = inet_ntoa
( $ip_address_binary | ~$netmask_binary );
457 return $broadcast_address;
464 if ( $ip =~ /(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/ ) {
465 $ip_num = (($1*256**3) + ($2*256**2) + ($3*256) + $4);
469 $ip_num = (($1*256**3) + ($2*256**2) + ($3*256) + $4);
478 $ip_num=int($ip_num/256);
480 $ip_num=int($ip_num/256);
482 $ip_num=int($ip_num/256);
484 $ip="$o4.$o3.$o2.$o1";
490 my $decip=&ip2dec
($_[0]);
492 return &dec2ip
($decip);
497 my $decip=&ip2dec
($_[0]);
499 return &dec2ip
($decip);
504 #Gets: Ip address in 192.168.0.0/24 or 192.168.0.0/255.255.255.0 and checks if subnet valid
505 #Gives: True bzw 0 if success or false
509 if (!($ccdnet =~ /^(.*?)\/(.*?
)$/)) {
512 my ($ccdip,$ccdsubnet)=split (/\//, $ccdnet);
514 if ($ccdip=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&(($1>0 && $1<=255 && $2>=0 && $2<=255 && $3>=0 && $3<=255 && $4<=255 ))) {
515 #Subnet in decimal and valid?
516 if ($ccdsubnet=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&(($1<=255 && $2<=$1 && $3<=$2 && $4<=$3 ))) {
517 for (my $i=8;$i<=32;$i++){
518 if (&General
::cidrtosub
($i) eq $ccdsubnet){
522 #Subnet already in binary format?
523 }elsif ($ccdsubnet=~/^(\d{1,2})$/ && (($1<=32 && $1>=8))){
540 my ($ip,$cidr)=split(/\//,$ccdnet);
541 $cidr=&iporsubtocidr
($cidr);
542 #get OVPN-Subnet (dynamic range)
544 &readhash
("${General::swroot}/ovpn/settings", \
%ovpnconf);
545 my ($ovpnip,$ovpncidr)= split (/\//,$ovpnconf{'DOVPN_SUBNET'});
546 $ovpncidr=&iporsubtocidr
($ovpncidr);
547 #check if we try to use same network as ovpn server
548 if ("$ip/$cidr" eq "$ovpnip/$ovpncidr") {
549 $errormessage=$errormessage.$Lang::tr
{'ccd err isovpnnet'}."<br>";
550 return $errormessage;
552 #check if we use a network-name/subnet that already exists
553 &readhasharray
("${General::swroot}/ovpn/ccd.conf", \
%ccdconfhash);
554 foreach my $key (keys %ccdconfhash) {
555 @ccdconf=split(/\//,$ccdconfhash{$key}[1]);
556 if ($ccdname eq $ccdconfhash{$key}[0])
558 $errormessage=$errormessage.$Lang::tr
{'ccd err nameexist'}."<br>";
559 return $errormessage;
561 my ($newip,$newsub) = split(/\//,$ccdnet);
562 if (&IpInSubnet
($newip,$ccdconf[0],&iporsubtodec
($ccdconf[1])))
564 $errormessage=$errormessage.$Lang::tr
{'ccd err issubnet'}."<br>";
565 return $errormessage;
568 #check if we use a ipsec right network which is already defined
570 &General
::readhasharray
("${General::swroot}/vpn/config", \
%ipsecconf);
571 foreach my $key (keys %ipsecconf){
572 if ($ipsecconf{$key}[11] ne ''){
573 my ($ipsecip,$ipsecsub) = split (/\//, $ipsecconf{$key}[11]);
574 $ipsecsub=&iporsubtodec
($ipsecsub);
575 if($ipsecconf{$key}[1] ne $ccdname){
576 if ( &IpInSubnet
($ip,$ipsecip,$ipsecsub) ){
577 $errormessage=$Lang::tr
{'ccd err isipsecnet'}." Name: $ipsecconf{$key}[1]";
578 return $errormessage;
583 #check if we use one of ipfire's networks (green,orange,blue)
585 &readhash
("${General::swroot}/ethernet/settings", \
%ownnet);
586 if (($ownnet{'GREEN_NETADDRESS'} ne '' && $ownnet{'GREEN_NETADDRESS'} ne '0.0.0.0') && &IpInSubnet
($ownnet{'GREEN_NETADDRESS'},$ip,&iporsubtodec
($cidr))){ $errormessage=$Lang::tr
{'ccd err green'};return $errormessage;}
587 if (($ownnet{'ORANGE_NETADDRESS'} ne '' && $ownnet{'ORANGE_NETADDRESS'} ne '0.0.0.0') && &IpInSubnet
($ownnet{'ORANGE_NETADDRESS'},$ip,&iporsubtodec
($cidr))){ $errormessage=$Lang::tr
{'ccd err orange'};return $errormessage;}
588 if (($ownnet{'BLUE_NETADDRESS'} ne '' && $ownnet{'BLUE_NETADDRESS'} ne '0.0.0.0') && &IpInSubnet
($ownnet{'BLUE_NETADDRESS'},$ip,&iporsubtodec
($cidr))){ $errormessage=$Lang::tr
{'ccd err blue'};return $errormessage;}
589 if (($ownnet{'RED_NETADDRESS'} ne '' && $ownnet{'RED_NETADDRESS'} ne '0.0.0.0') && &IpInSubnet
($ownnet{'RED_NETADDRESS'},$ip,&iporsubtodec
($cidr))){ $errormessage=$Lang::tr
{'ccd err red'};return $errormessage;}
601 if ($_ >= 1 && $_ <= 65535) {
614 if ($_ == 53 || $_ == 222 || $_ == 444 || $_ == 81 ) {
616 elsif ($_ >= 1 && $_ <= 65535) {
623 my $checkmac = $_[0];
624 my $ot = '[0-9a-f]{2}'; # 2 Hex digits (one octet)
625 if ($checkmac !~ /^$ot:$ot:$ot:$ot:$ot:$ot$/i)
634 # Checks a hostname against RFC1035
635 my $hostname = $_[0];
637 # Each part should be at least two characters in length
638 # but no more than 63 characters
639 if (length ($hostname) < 1 || length ($hostname) > 63) {
641 # Only valid characters are a-z, A-Z, 0-9 and -
642 if ($hostname !~ /^[a-zA-Z0-9-\s]*$/) {
644 # First character can only be a letter or a digit
645 if (substr ($hostname, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
647 # Last character can only be a letter or a digit
648 if (substr ($hostname, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
657 # Checks a domain name against RFC1035
658 my $domainname = $_[0];
659 my @parts = split (/\./, $domainname); # Split hostname at the '.'
661 foreach $part (@parts) {
662 # Each part should be at least two characters in length
663 # but no more than 63 characters
664 if (length ($part) < 2 || length ($part) > 63) {
666 # Only valid characters are a-z, A-Z, 0-9 and -
667 if ($part !~ /^[a-zA-Z0-9-]*$/) {
669 # First character can only be a letter or a digit
670 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
672 # Last character can only be a letter or a digit
673 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
683 # Checks a fully qualified domain name against RFC1035
685 my @parts = split (/\./, $fqdn); # Split hostname at the '.'
686 if (scalar(@parts) < 2) { # At least two parts should
687 return 0;} # exist in a FQDN
688 # (i.e. hostname.domain)
689 foreach $part (@parts) {
690 # Each part should be at least one character in length
691 # but no more than 63 characters
692 if (length ($part) < 1 || length ($part) > 63) {
694 # Only valid characters are a-z, A-Z, 0-9 and -
695 if ($part !~ /^[a-zA-Z0-9-]*$/) {
697 # First character can only be a letter or a digit
698 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
700 # Last character can only be a letter or a digit
701 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
707 sub validportrange
# used to check a port range
709 my $port = $_[0]; # port values
710 $port =~ tr/-/:/; # replace all - with colons just in case someone used -
711 my $srcdst = $_[1]; # is it a source or destination port
713 if (!($port =~ /^(\d+)\:(\d+)$/)) {
715 if (!(&validport
($port))) {
716 if ($srcdst eq 'src'){
717 return $Lang::tr
{'source port numbers'};
719 return $Lang::tr
{'destination port numbers'};
725 my @ports = ($1, $2);
727 if ($srcdst eq 'src'){
728 return $Lang::tr
{'bad source range'};
730 return $Lang::tr
{'bad destination range'};
735 if (!(&validport
($_))) {
736 if ($srcdst eq 'src'){
737 return $Lang::tr
{'source port numbers'};
739 return $Lang::tr
{'destination port numbers'};
747 # Test if IP is within a subnet
748 # Call: IpInSubnet (Addr, Subnet, Subnet Mask)
749 # Subnet can be an IP of the subnet: 10.0.0.0 or 10.0.0.1
750 # Everything in dottted notation
754 my $ip = unpack('N', &Socket
::inet_aton
(shift));
755 my $start = unpack('N', &Socket
::inet_aton
(shift));
756 my $mask = unpack('N', &Socket
::inet_aton
(shift));
757 $start &= $mask; # base of subnet...
758 my $end = $start + ~$mask;
759 return (($ip >= $start) && ($ip <= $end));
763 # Return the following IP (IP+1) in dotted notation.
764 # Call: NextIP ('1.1.1.1');
769 return &Socket
::inet_ntoa
( pack("N", 1 + unpack('N', &Socket
::inet_aton
(shift))
775 return &Socket
::inet_ntoa
( pack("N", 4 + unpack('N', &Socket
::inet_aton
(shift))
781 my ($ip,$cidr) = &Net
::IPv4Addr
::ipv4_parse
(shift);
787 my ($ip,$cidr) = &Net
::IPv4Addr
::ipv4_parse
(shift);
788 my $netmask = &Net
::IPv4Addr
::ipv4_cidr2msk
($cidr);
789 return "$ip\/$netmask";
795 return 0 if ( $mail !~ /^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/ );
796 return 0 if ( $mail =~ /^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/);
797 return 0 if ( $mail !~ /([0-9a-zA-Z]{1})\@./ );
798 return 0 if ( $mail !~ /.\@([0-9a-zA-Z]{1})/ );
799 return 0 if ( $mail =~ /.\.\-.|.\-\..|.\.\..|.\-\-./g );
800 return 0 if ( $mail =~ /.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./g );
801 return 0 if ( $mail !~ /\.([a-zA-Z]{2,4})$/ );
806 # Currently only vpnmain use this three procs (readhasharray, writehasharray, findhasharray)
807 # The 'key' used is numeric but is perfectly unneeded! This will to be removed so don't use
808 # this code. Vpnmain will be splitted in parts: x509/pki, connection ipsec, connection other,... .
811 my ($filename, $hash) = @_;
814 open(FILE
, $filename) or die "Unable to read file $filename";
817 my ($key, $rest, @temp);
819 ($key, $rest) = split (/,/, $_, 2);
820 if ($key =~ /^[0-9]+$/) {
821 @temp = split (/,/, $rest);
822 $hash->{$key} = \
@temp;
830 my ($filename, $hash) = @_;
831 my ($key, @temp, $i);
833 open(FILE
, ">$filename") or die "Unable to write to file $filename";
835 foreach $key (keys %$hash) {
836 if ($key =~ /^[0-9]+$/) {
838 foreach $i (0 .. $#{$hash->{$key}}) {
839 print FILE
",$hash->{$key}[$i]";
848 sub findhasharraykey
{
849 foreach my $i (1 .. 1000000) {
850 if ( ! exists $_[0]{$i}) {
857 # Darren Critchley - darrenc@telus.net - (c) 2003
858 # &srtarray(SortOrder, AlphaNumeric, SortDirection, ArrayToBeSorted)
859 # This subroutine will take the following parameters:
860 # ColumnNumber = the column which you want to sort on, starts at 1
861 # AlphaNumberic = a or n (lowercase) defines whether the sort should be alpha or numberic
862 # SortDirection = asc or dsc (lowercase) Ascending or Descending sort
863 # ArrayToBeSorted = the array that wants sorting
865 # Returns an array that is sorted to your specs
867 # If SortOrder is greater than the elements in array, then it defaults to the first element
870 my ($colno, $alpnum, $srtdir, @tobesorted) = @_;
876 my $ttlitems = scalar @tobesorted; # want to know the number of rows in the passed array
877 if ($ttlitems < 1){ # if no items, don't waste our time lets leave
878 return (@tobesorted);
880 my @tmp = split(/\,/,$tobesorted[0]);
881 $ttlitems = scalar @tmp; # this should be the number of elements in each row of the passed in array
883 # Darren Critchley - validate parameters
884 if ($colno > $ttlitems){$colno = '1';}
885 $colno--; # remove one from colno to deal with arrays starting at 0
886 if($colno < 0){$colno = '0';}
887 if ($alpnum ne '') { $alpnum = lc($alpnum); } else { $alpnum = 'a'; }
888 if ($srtdir ne '') { $srtdir = lc($srtdir); } else { $srtdir = 'src'; }
890 foreach $line (@tobesorted)
894 my @temp = split(/\,/,$line);
895 # Darren Critchley - juggle the fields so that the one we want to sort on is first
896 my $tmpholder = $temp[0];
897 $temp[0] = $temp[$colno];
898 $temp[$colno] = $tmpholder;
900 for ($ctr=0; $ctr < $ttlitems ; $ctr++) {
901 $newline=$newline . $temp[$ctr] . ",";
904 push(@tmparray,$newline);
907 if ($alpnum eq 'n') {
908 @tmparray = sort {$a <=> $b} @tmparray;
910 @tmparray = (sort @tmparray);
912 foreach $line (@tmparray)
916 my @temp = split(/\,/,$line);
917 my $tmpholder = $temp[0];
918 $temp[0] = $temp[$colno];
919 $temp[$colno] = $tmpholder;
921 for ($ctr=0; $ctr < $ttlitems ; $ctr++){
922 $newline=$newline . $temp[$ctr] . ",";
925 push(@srtedarray,$newline);
929 if ($srtdir eq 'dsc') {
930 @tmparray = reverse(@srtedarray);
933 return (@srtedarray);
939 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
940 if ($_=$proxysettings{'UPSTREAM_PROXY'}) {
941 my ($peer, $peerport) = (/^(?:[a-zA-Z ]+\:\/\
/)?(?:[A-Za-z0-9\_\.\-]*?(?:\:[A-Za-z0-9\_\.\-]*?)?\@)?([a-zA-Z0-9\.\_\-]*?)(?:\:([0-9]{1,5}))?(?:\/.*?
)?
$/);
942 Net
::SSLeay
::set_proxy
($peer,$peerport,$proxysettings{'UPSTREAM_USER'},$proxysettings{'UPSTREAM_PASSWORD'} );
944 my $user_agent = &MakeUserAgent
();
945 my ($out, $response) = Net
::SSLeay
::get_http
( 'checkip4.dns.lightningwirelabs.com',
948 Net
::SSLeay
::make_headers
('User-Agent' => $user_agent )
950 if ($response =~ m
%HTTP/1\
.. 200 OK
%) {
951 $out =~ /Your IP address is: (\d+.\d+.\d+.\d+)/;
958 # Check if hostname.domain provided have IP provided
959 # use gethostbyname to verify that
965 # 1 IP matches host.domain
968 sub DyndnsServiceSync
($;$;$) {
970 my ($ip,$hostName,$domain) = @_;
973 #fix me no ip GROUP, what is the name ?
974 $hostName =~ s/$General::noipprefix//;
975 if ($hostName) { #may be empty
976 $hostName = "$hostName.$domain";
977 @addresses = gethostbyname($hostName);
980 if ($addresses[0] eq '') { # nothing returned ?
981 $hostName = $domain; # try resolving with domain only
982 @addresses = gethostbyname($hostName);
985 if ($addresses[0] ne '') { # got something ?
986 #&General::log("name:$addresses[0], alias:$addresses[1]");
987 # Build clear text list of IP
988 @addresses = map ( &Socket
::inet_ntoa
($_), @addresses[4..$#addresses]);
989 if (grep (/$ip/, @addresses)) {
996 # This sub returns the red IP used to compare in DyndnsServiceSync
1000 &General
::readhash
("${General::swroot}/ddns/settings", \
%settings);
1002 open(IP
, "${General::swroot}/red/local-ipaddress") or return 'unavailable';
1007 # 100.64.0.0/10 is reserved for dual-stack lite (http://tools.ietf.org/html/rfc6598).
1008 if (&General
::IpInSubnet
($ip,'10.0.0.0','255.0.0.0') ||
1009 &General
::IpInSubnet
($ip,'172.16.0.0.','255.240.0.0') ||
1010 &General
::IpInSubnet
($ip,'192.168.0.0','255.255.0.0') ||
1011 &General
::IpInSubnet
($ip,'100.64.0.0', '255.192.0.0'))
1013 if ($settings{'BEHINDROUTER'} eq 'FETCH_IP') {
1014 my $RealIP = &General
::FetchPublicIp
;
1015 $ip = (&General
::validip
($RealIP) ?
$RealIP : 'unavailable');
1021 # Translate ICMP code to text
1022 # ref: http://www.iana.org/assignments/icmp-parameters
1023 sub GetIcmpDescription
($) {
1025 my @icmp_description = (
1029 'Destination Unreachable',
1032 'Alternate Host Address',
1035 'Router Advertisement',
1036 'Router Solicitation', #10
1038 'Parameter Problem',
1041 'Information Request',
1042 'Information Reply',
1043 'Address Mask Request',
1044 'Address Mask Reply',
1045 'Reserved (for Security)',
1046 'Reserved (for Robustness Experiment)', #20
1057 'Datagram Conversion Error',
1058 'Mobile Host Redirect',
1059 'IPv6 Where-Are-You',
1061 'Mobile Registration Request',
1062 'Mobile Registration Reply',
1063 'Domain Name Request',
1064 'Domain Name Reply',
1068 if ($index>41) {return 'unknown'} else {return @icmp_description[$index]};
1071 sub GetCoreUpdateVersion
() {
1074 open(FILE
, "/opt/pakfire/db/core/mine");
1081 return $core_update;
1084 sub MakeUserAgent
() {
1085 my $user_agent = "IPFire/$General::version";
1087 my $core_update = &GetCoreUpdateVersion
();
1088 if ($core_update ne "") {
1089 $user_agent .= "/$core_update";
1095 sub RedIsWireless
() {
1096 # This function checks if a network device is a wireless device.
1099 &readhash
("${General::swroot}/ethernet/settings", \
%settings);
1101 # Find the name of the network device.
1102 my $device = $settings{'RED_DEV'};
1104 # Exit, if no device is configured.
1105 return 0 if ($device eq "");
1107 # Return 1 if the device is a wireless one.
1108 my $path = "/sys/class/net/$device/wireless";
1113 # Otherwise return zero.
1117 # Function to read a file with UTF-8 charset.
1118 sub read_file_utf8
($) {
1121 open my $in, '<:encoding(UTF-8)', $file or die "Could not open '$file' for reading $!";
1129 # Function to write a file with UTF-8 charset.
1130 sub write_file_utf8
($) {
1131 my ($file, $content) = @_;
1133 open my $out, '>:encoding(UTF-8)', $file or die "Could not open '$file' for writing $!";;
1134 print $out $content;