]>
git.ipfire.org Git - people/pmueller/ipfire-2.x.git/blob - config/cfgroot/general-functions.pl
96a826a154655a5451710d81f071e4d1290b59fe
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
= 'VERSION';
25 $General::swroot
= 'CONFIG_ROOT';
26 $General::noipprefix
= 'noipg-';
27 $General::adminmanualurl
= 'http://wiki.ipfire.org';
29 require "${General::swroot}/network-functions.pl";
31 # This function executes a shell command without forking a shell or do any other
32 # Perl-voodoo before it. It deprecates the "system" command and is the only way
33 # to call shell commands.
37 system { ${command
[0]} } @command;
43 # Calls a process in the background and returns nothing
44 sub system_background
($) {
55 # Returns the output of a shell command
56 sub system_output
($) {
61 unless ($pid = open(OUTPUT
, "-|")) {
62 open(STDERR
, ">&STDOUT");
63 exec { ${command
[0]} } @command;
64 die "Could not execute @command: $!";
77 # Calls a shell command and throws away the output
81 open(SAVEOUT
, ">&STDOUT");
82 open(SAVEERR
, ">&STDERR");
84 open(STDOUT
, ">/dev/null");
85 open(STDERR
, ">&STDOUT");
90 my $rc = &safe_system
(@command);
96 open(STDOUT
, ">&SAVEOUT");
97 open(STDERR
, ">&SAVEERR");
102 # Function to remove duplicates from an array
103 sub uniq
{ my %seen; grep !$seen{$_}++, @_ }
106 # log ("message") use default 'ipcop' tag
107 # log ("tag","message") use your tag
112 $tag = shift if (@_>1);
113 my $logmessage = $_[0];
114 $logmessage =~ /([\w\W]*)/;
116 system('logger', '-t', $tag, $logmessage);
118 sub setup_default_networks
121 my $defaultNetworks = shift;
123 &readhash
("/var/ipfire/ethernet/settings", \
%netsettings);
125 # Get current defined networks (Red, Green, Blue, Orange)
126 $defaultNetworks->{$Lang::tr{'fwhost any'}}{'IPT'} = "0.0.0.0/0.0.0.0";
127 $defaultNetworks->{$Lang::tr{'fwhost any'}}{'NAME'} = "ALL";
129 $defaultNetworks->{$Lang::tr{'green'}}{'IPT'} = "$netsettings{'GREEN_NETADDRESS'}/$netsettings{'GREEN_NETMASK'}";
130 $defaultNetworks->{$Lang::tr{'green'}}{'NET'} = "$netsettings{'GREEN_ADDRESS'}";
131 $defaultNetworks->{$Lang::tr{'green'}}{'NAME'} = "GREEN";
133 if ($netsettings{'RED_DEV'} ne ''){
134 $defaultNetworks->{$Lang::tr{'fwdfw red'}}{'IPT'} = "$netsettings{'RED_NETADDRESS'}/$netsettings{'RED_NETMASK'}";
135 $defaultNetworks->{$Lang::tr{'fwdfw red'}}{'NET'} = "$netsettings{'RED_ADDRESS'}";
136 $defaultNetworks->{$Lang::tr{'fwdfw red'}}{'NAME'} = "RED";
138 if ($netsettings{'ORANGE_DEV'} ne ''){
139 $defaultNetworks->{$Lang::tr{'orange'}}{'IPT'} = "$netsettings{'ORANGE_NETADDRESS'}/$netsettings{'ORANGE_NETMASK'}";
140 $defaultNetworks->{$Lang::tr{'orange'}}{'NET'} = "$netsettings{'ORANGE_ADDRESS'}";
141 $defaultNetworks->{$Lang::tr{'orange'}}{'NAME'} = "ORANGE";
144 if ($netsettings{'BLUE_DEV'} ne ''){
145 $defaultNetworks->{$Lang::tr{'blue'}}{'IPT'} = "$netsettings{'BLUE_NETADDRESS'}/$netsettings{'BLUE_NETMASK'}";
146 $defaultNetworks->{$Lang::tr{'blue'}}{'NET'} = "$netsettings{'BLUE_ADDRESS'}";
147 $defaultNetworks->{$Lang::tr{'blue'}}{'NAME'} = "BLUE";
151 $defaultNetworks->{'IPFire'}{'NAME'} = "IPFire";
154 if(-e
"${General::swroot}/ovpn/settings")
156 my %ovpnSettings = ();
157 &readhash
("${General::swroot}/ovpn/settings", \
%ovpnSettings);
160 if(defined($ovpnSettings{'DOVPN_SUBNET'}))
162 my ($ip,$sub) = split(/\//,$ovpnSettings{'DOVPN_SUBNET'});
163 $sub=&General
::iporsubtocidr
($sub);
164 my @tempovpnsubnet = split("\/", $ovpnSettings{'DOVPN_SUBNET'});
165 $defaultNetworks->{'OpenVPN ' ."($ip/$sub)"}{'ADR'} = $tempovpnsubnet[0];
166 $defaultNetworks->{'OpenVPN ' ."($ip/$sub)"}{'NAME'} = "OpenVPN-Dyn";
170 if(-e
"${General::swroot}/vpn/settings")
172 my %ipsecsettings = ();
173 &readhash
("${General::swroot}/vpn/settings", \
%ipsecsettings);
174 if($ipsecsettings{'RW_NET'} ne '')
176 my ($ip,$sub) = split(/\//,$ipsecsettings{'RW_NET'});
177 $sub=&General
::iporsubtocidr
($sub);
178 my @tempipsecsubnet = split("\/", $ipsecsettings{'RW_NET'});
179 $defaultNetworks->{'IPsec RW (' .$ip."/".$sub.")"}{'ADR'} = $tempipsecsubnet[0];
180 $defaultNetworks->{'IPsec RW (' .$ip."/".$sub.")"}{'NAME'} = "IPsec RW";
181 $defaultNetworks->{'IPsec RW (' .$ip."/".$sub.")"}{'NET'} = &getnextip
($ip);
188 my $defaultNetworks = shift;
189 open(FILE
, "${General::swroot}/ethernet/aliases") or die 'Unable to open aliases file.';
190 my @current = <FILE
>;
193 foreach my $line (@current)
197 my @temp = split(/\,/,$line);
198 if ($temp[2] eq '') {
199 $temp[2] = "Alias $ctr : $temp[0]";
201 $defaultNetworks->{$temp[2]}{'IPT'} = "$temp[0]";
202 $defaultNetworks->{$temp[2]}{'NET'} = "$temp[0]";
211 my $filename = $_[0];
216 # Some ipcop code expects that readhash 'complete' the hash if new entries
217 # are presents. Not clear it !!!
220 open(FILE
, $filename) or die "Unable to read file $filename";
227 next if ($_ =~ /^#/);
229 ($var, $val) = split /=/, $_, 2;
235 # Untaint variables read from hash
236 # trim space from begin and end
239 $var =~ /([A-Za-z0-9_-]*)/;
243 $hash->{$var} = $val;
252 my $filename = $_[0];
256 # write cgi vars to the file.
257 open(FILE
, ">${filename}") or die "Unable to write file $filename";
259 foreach $var (keys %$hash)
261 if ( $var eq "__CGI__"){next;}
262 $val = $hash->{$var};
263 # Darren Critchley Jan 17, 2003 added the following because when submitting with a graphic, the x and y
264 # location of the mouse are submitted as well, this was being written to the settings file causing
265 # some serious grief! This skips the variable.x and variable.y
266 if (!($var =~ /(.x|.y)$/)) {
269 if (!($var =~ /^ACTION/)) {
270 print FILE
"${var}=${val}\n"; }
278 # This function replaces the given hash in the original hash by keeping the old
279 # content and just replacing the new content
281 my $filename = $_[0];
286 readhash
("${filename}", \
%oldhash);
288 foreach $var (keys %$newhash){
289 $oldhash{$var}=$newhash->{$var};
292 # write cgi vars to the file.
293 open(FILE
, ">${filename}") or die "Unable to write file $filename";
295 foreach $var (keys %oldhash)
297 if ( $var eq "__CGI__"){next;}
298 $val = $oldhash{$var};
299 # Darren Critchley Jan 17, 2003 added the following because when submitting with a graphic, the x and y
300 # location of the mouse are submitted as well, this was being written to the settings file causing
301 # some serious grief! This skips the variable.x and variable.y
302 if (!($var =~ /(.x|.y)$/)) {
305 if (!($var =~ /^ACTION/)) {
306 print FILE
"${var}=${val}\n"; }
313 my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
314 $atime, $mtime, $ctime, $blksize, $blocks) = stat $_[0];
315 my $t = time() - $mtime;
317 return &format_time
($t);
321 my $totalsecs = shift;
324 my $secs = $totalsecs % 60;
327 push(@s, "${secs}s");
330 my $min = $totalsecs % 60;
336 my $hrs = $totalsecs % 24;
342 my $days = int($totalsecs);
344 push(@s, "${days}d");
347 return join(" ", reverse(@s));
354 if (!($ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/)) {
358 my @octets = ($1, $2, $3, $4);
363 if ($_ < 0 || $_ > 255) {
373 return &Network
::check_netmask
($mask) || &Network
::check_prefix
($mask);
378 my $ipormask = $_[0];
380 # see if it is a IP only.
381 if (&validip
($ipormask)) {
383 # split it into number and mask.
384 if (!($ipormask =~ /^(.*?)\/(.*?
)$/)) {
388 # first part not a ip?
389 if (!(&validip
($ip))) {
391 return &validmask
($mask);
395 return &Network
::convert_netmask2prefix
(shift);
399 return &Network
::convert_prefix2netmask
(shift);
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);
417 #Subnet already in decimal and valid?
418 if ($mask=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&(($1<=255 && $2<=$1 && $3<=$2 && $4<=$3 ))) {
419 for (my $i=0;$i<=32;$i++){
420 if (&General
::cidrtosub
($i) eq $mask){
421 if ($full == 0){return $mask;}else{
422 return $net."/".$mask;
427 #Subnet in binary format?
428 if ($mask=~/^(\d{1,2})$/ && (($1<=32 && $1>=0))){
429 if($full == 0){ return &General
::cidrtosub
($mask);}else{
430 return $net."/".&General
::cidrtosub
($mask);
441 #gets: Ip Address or subnetmask in decimal oder CIDR
442 #Gives: What it gets only in CIDR format
447 if ($subnet =~ /^(.*?)\/(.*?
)$/) {
448 ($net,$mask) = split (/\//,$subnet);
453 #Subnet in decimal and valid?
454 if ($mask=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&(($1<=255 && $2<=$1 && $3<=$2 && $4<=$3 ))) {
455 for (my $i=0;$i<=32;$i++){
456 if (&General
::cidrtosub
($i) eq $mask){
457 if ($full == 0){return &General
::subtocidr
($mask);}else{
458 return $net."/".&General
::subtocidr
($mask);
463 #Subnet already in binary format?
464 if ($mask=~/^(\d{1,2})$/ && (($1<=32 && $1>=0))){
465 if($full == 0){ return $mask;}else{
466 return $net."/".$mask;
475 my $arg = join("/", @_);
477 return &Network
::get_netaddress
($arg);
482 #Gets: IP in Form ("192.168.0.0/24")
483 #Gives: Broadcastaddress of network
485 my ($ccdip,$ccdsubnet) = split "/",$ccdnet;
486 my $ip_address_binary = inet_aton
( $ccdip );
487 my $netmask_binary = ~pack("N", (2**(32-$ccdsubnet))-1);
488 my $broadcast_address = inet_ntoa
( $ip_address_binary | ~$netmask_binary );
489 return $broadcast_address;
493 return &Network
::ip2bin
(shift);
497 return &Network
::bin2ip
(shift);
501 return &Network
::find_next_ip_address
(shift, 4);
505 return &Network
::find_next_ip_address
(shift, -1);
510 #Gets: Ip address in 192.168.0.0/24 or 192.168.0.0/255.255.255.0 and checks if subnet valid
511 #Gives: True bzw 0 if success or false
515 if (!($ccdnet =~ /^(.*?)\/(.*?
)$/)) {
518 my ($ccdip,$ccdsubnet)=split (/\//, $ccdnet);
520 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 ))) {
521 #Subnet in decimal and valid?
522 if ($ccdsubnet=~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ &&(($1<=255 && $2<=$1 && $3<=$2 && $4<=$3 ))) {
523 for (my $i=0;$i<=32;$i++){
524 if (&General
::cidrtosub
($i) eq $ccdsubnet){
528 #Subnet already in binary format?
529 }elsif ($ccdsubnet=~/^(\d{1,2})$/ && (($1<=32 && $1>=0))){
553 my ($ip,$cidr)=split(/\//,$ccdnet);
554 $cidr=&iporsubtocidr
($cidr);
556 #get OVPN-Subnet (dynamic range)
557 &readhash
("${General::swroot}/ovpn/settings", \
%ovpnconf);
558 my ($ovpnip,$ovpncidr)= split (/\//,$ovpnconf{'DOVPN_SUBNET'});
559 $ovpncidr=&iporsubtocidr
($ovpncidr);
561 #check if we try to use same network as ovpn server
562 if ("$ip/$cidr" eq "$ovpnip/$ovpncidr") {
563 $errormessage=$errormessage.$Lang::tr
{'ccd err isovpnnet'}."<br>";
564 return $errormessage;
567 #check if we try to use same network as another ovpn N2N
568 if($ownnet ne 'ovpn'){
569 &readhasharray
("${General::swroot}/ovpn/ovpnconfig", \
%ovpnconfhash);
570 foreach my $key (keys %ovpnconfhash) {
571 if ($ovpnconfhash{$key}[3] eq 'net'){
572 my @ovpnnet=split (/\//,$ovpnconfhash{$key}[11]);
573 if (&IpInSubnet
($ip,$ovpnnet[0],&iporsubtodec
($ovpnnet[1]))){
574 $errormessage=$errormessage.$Lang::tr
{'ccd err isovpnn2n'}." $ovpnconfhash{$key}[1] <br>";
575 return $errormessage;
581 #check if we use a network-name/subnet (static-ovpn) that already exists
582 &readhasharray
("${General::swroot}/ovpn/ccd.conf", \
%ccdconfhash);
583 foreach my $key (keys %ccdconfhash) {
584 @ccdconf=split(/\//,$ccdconfhash{$key}[1]);
585 if ($ccdname eq $ccdconfhash{$key}[0])
587 $errormessage=$errormessage.$Lang::tr
{'ccd err nameexist'}."<br>";
588 return $errormessage;
590 my ($newip,$newsub) = split(/\//,$ccdnet);
591 if (&IpInSubnet
($newip,$ccdconf[0],&iporsubtodec
($ccdconf[1])))
593 $errormessage=$errormessage.$Lang::tr
{'ccd err issubnet'}." $ccdconfhash{$key}[0]<br>";
594 return $errormessage;
598 #check if we use a ipsec right network which is already defined
599 if($ownnet ne 'ipsec'){
600 &General
::readhasharray
("${General::swroot}/vpn/config", \
%ipsecconf);
601 foreach my $key (keys %ipsecconf){
602 if ($ipsecconf{$key}[11] ne '' && $ipsecconf{$key}[36] eq ""){
603 foreach my $ipsecsubitem (split(/\|/, $ipsecconf{$key}[11])) {
604 my ($ipsecip,$ipsecsub) = split (/\//, $ipsecconf{$key}[11]);
605 $ipsecsub=&iporsubtodec
($ipsecsub);
606 if($ipsecconf{$key}[1] ne $ccdname){
607 if ( &IpInSubnet
($ip,$ipsecip,$ipsecsub) ){
608 $errormessage=$Lang::tr
{'ccd err isipsecnet'}." Name: $ipsecconf{$key}[1]";
609 return $errormessage;
617 #check if we use the ipsec RW Network (if defined)
618 &readhash
("${General::swroot}/vpn/settings", \
%vpnconf);
619 if ($vpnconf{'RW_NET'} ne ''){
620 my ($ipsecrwnet,$ipsecrwsub)=split (/\//, $vpnconf{'RW_NET'});
621 if (&IpInSubnet
($ip,$ipsecrwnet,&iporsubtodec
($ipsecrwsub)))
623 $errormessage=$errormessage.$Lang::tr
{'ccd err isipsecrw'}."<br>";
624 return $errormessage;
628 #call check_net_internal
629 if ($checktype eq "exact")
631 &General
::check_net_internal_exact
($ccdnet);
633 &General
::check_net_internal_range
($ccdnet);
637 sub check_net_internal_range
{
639 my ($ip,$cidr)=split(/\//,$network);
642 $cidr=&iporsubtocidr
($cidr);
643 #check if we use one of ipfire's networks (green,orange,blue)
644 &readhash
("${General::swroot}/ethernet/settings", \
%ownnet);
645 if (($ownnet{'GREEN_NETADDRESS'} ne '' && $ownnet{'GREEN_NETADDRESS'} ne '0.0.0.0') && &IpInSubnet
($ip,$ownnet{'GREEN_NETADDRESS'},&iporsubtodec
($ownnet{'GREEN_NETMASK'}))){ $errormessage=$Lang::tr
{'ccd err green'};return $errormessage;}
646 if (($ownnet{'ORANGE_NETADDRESS'} ne '' && $ownnet{'ORANGE_NETADDRESS'} ne '0.0.0.0') && &IpInSubnet
($ip,$ownnet{'ORANGE_NETADDRESS'},&iporsubtodec
($ownnet{'ORANGE_NETMASK'}))){ $errormessage=$Lang::tr
{'ccd err orange'};return $errormessage;}
647 if (($ownnet{'BLUE_NETADDRESS'} ne '' && $ownnet{'BLUE_NETADDRESS'} ne '0.0.0.0') && &IpInSubnet
($ip,$ownnet{'BLUE_NETADDRESS'},&iporsubtodec
($ownnet{'BLUE_NETMASK'}))){ $errormessage=$Lang::tr
{'ccd err blue'};return $errormessage;}
648 if (($ownnet{'RED_NETADDRESS'} ne '' && $ownnet{'RED_NETADDRESS'} ne '0.0.0.0') && &IpInSubnet
($ip,$ownnet{'RED_NETADDRESS'},&iporsubtodec
($ownnet{'RED_NETMASK'}))){ $errormessage=$Lang::tr
{'ccd err red'};return $errormessage;}
651 sub check_net_internal_exact
{
653 my ($ip,$cidr)=split(/\//,$network);
656 $cidr=&iporsubtocidr
($cidr);
657 #check if we use one of ipfire's networks (green,orange,blue)
658 &readhash
("${General::swroot}/ethernet/settings", \
%ownnet);
659 if (($ownnet{'GREEN_NETADDRESS'} ne '' && $ownnet{'GREEN_NETADDRESS'} ne '0.0.0.0') && &Network
::network_equal
("$ownnet{'GREEN_NETADDRESS'}/$ownnet{'GREEN_NETMASK'}", $network)){ $errormessage=$Lang::tr
{'ccd err green'};return $errormessage;}
660 if (($ownnet{'ORANGE_NETADDRESS'} ne '' && $ownnet{'ORANGE_NETADDRESS'} ne '0.0.0.0') && &Network
::network_equal
("$ownnet{'ORANGE_NETADDRESS'}/$ownnet{'ORANGE_NETMASK'}", $network)){ $errormessage=$Lang::tr
{'ccd err orange'};return $errormessage;}
661 if (($ownnet{'BLUE_NETADDRESS'} ne '' && $ownnet{'BLUE_NETADDRESS'} ne '0.0.0.0') && &Network
::network_equal
("$ownnet{'BLUE_NETADDRESS'}/$ownnet{'BLUE_NETMASK'}", $network)){ $errormessage=$Lang::tr
{'ccd err blue'};return $errormessage;}
662 if (($ownnet{'RED_NETADDRESS'} ne '' && $ownnet{'RED_NETADDRESS'} ne '0.0.0.0') && &Network
::network_equal
("$ownnet{'RED_NETADDRESS'}/$ownnet{'RED_NETMASK'}", $network)){ $errormessage=$Lang::tr
{'ccd err red'};return $errormessage;}
673 if ($_ >= 1 && $_ <= 65535) {
686 if ($_ == 53 || $_ == 222 || $_ == 444 || $_ == 81 ) {
688 elsif ($_ >= 1 && $_ <= 65535) {
695 my $checkmac = $_[0];
696 my $ot = '[0-9a-f]{2}'; # 2 Hex digits (one octet)
697 if ($checkmac !~ /^$ot:$ot:$ot:$ot:$ot:$ot$/i)
706 # Checks a hostname against RFC1035
707 my $hostname = $_[0];
709 # Hostname should be at least one character in length
710 # but no more than 63 characters
711 if (length ($hostname) < 1 || length ($hostname) > 63) {
713 # Only valid characters are a-z, A-Z, 0-9 and -
714 if ($hostname !~ /^[a-zA-Z0-9-]*$/) {
716 # First character can only be a letter or a digit
717 if (substr ($hostname, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
719 # Last character can only be a letter or a digit
720 if (substr ($hostname, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
729 # Checks a domain name against RFC1035 and RFC2181
730 my $domainname = $_[0];
731 my @parts = split (/\./, $domainname); # Split domain name at the '.'
733 foreach $part (@parts) {
734 # Each part should be at least one character in length
735 # but no more than 63 characters
736 if (length ($part) < 1 || length ($part) > 63) {
738 # Only valid characters are a-z, A-Z, 0-9, _ and -
739 if ($part !~ /^[a-zA-Z0-9_-]*$/) {
747 # Checks a fully qualified domain name against RFC1035 and RFC2181
749 my @parts = split (/\./, $fqdn); # Split FQDN at the '.'
750 if (scalar(@parts) < 2) { # At least two parts should
751 return 0;} # exist in a FQDN
752 # (i.e.hostname.domain)
754 for (my $index=0; $index < scalar(@parts); $index++) {
755 # Each part should be at least one character in length
756 # but no more than 63 characters
757 if (length ($parts[$index]) < 1 || length ($parts[$index]) > 63) {
760 # This is the hostname part
761 # Only valid characters are a-z, A-Z, 0-9 and -
762 if ($parts[$index] !~ /^[a-zA-Z0-9-]*$/) {
764 # First character can only be a letter or a digit
765 if (substr ($parts[$index], 0, 1) !~ /^[a-zA-Z0-9]*$/) {
767 # Last character can only be a letter or a digit
768 if (substr ($parts[$index], -1, 1) !~ /^[a-zA-Z0-9]*$/) {
771 # This is the domain part
772 # Only valid characters are a-z, A-Z, 0-9, _ and -
773 if ($parts[$index] !~ /^[a-zA-Z0-9_-]*$/) {
780 sub validportrange
# used to check a port range
782 my $port = $_[0]; # port values
783 $port =~ tr/-/:/; # replace all - with colons just in case someone used -
784 my $srcdst = $_[1]; # is it a source or destination port
786 if (!($port =~ /^(\d+)\:(\d+)$/)) {
788 if (!(&validport
($port))) {
789 if ($srcdst eq 'src'){
790 return $Lang::tr
{'source port numbers'};
792 return $Lang::tr
{'destination port numbers'};
798 my @ports = ($1, $2);
800 if ($srcdst eq 'src'){
801 return $Lang::tr
{'bad source range'};
803 return $Lang::tr
{'bad destination range'};
808 if (!(&validport
($_))) {
809 if ($srcdst eq 'src'){
810 return $Lang::tr
{'source port numbers'};
812 return $Lang::tr
{'destination port numbers'};
825 return &Network
::ip_address_in_network
($addr, "$network/$netmask");
829 # Return the following IP (IP+1) in dotted notation.
830 # Call: NextIP ('1.1.1.1');
834 return &Network
::find_next_ip_address
(shift, 1);
838 return &Network
::find_next_ip_address
(shift, 4);
842 my ($ip,$cidr) = &Net
::IPv4Addr
::ipv4_parse
(shift);
847 my ($ip,$cidr) = &Net
::IPv4Addr
::ipv4_parse
(shift);
848 my $netmask = &Net
::IPv4Addr
::ipv4_cidr2msk
($cidr);
849 return "$ip\/$netmask";
854 my @parts = split( /\@/, $address );
857 #check if we have one part before and after '@'
858 return 0 if ( $count != 2 );
860 #check if one of the parts starts or ends with a dot
861 return 0 if ( substr($parts[0],0,1) eq '.' );
862 return 0 if ( substr($parts[0],-1,1) eq '.' );
863 return 0 if ( substr($parts[1],0,1) eq '.' );
864 return 0 if ( substr($parts[1],-1,1) eq '.' );
866 #check first addresspart (before '@' sign)
867 return 0 if ( $parts[0] !~ m/^[a-zA-Z0-9\.!\-\_\+#]+$/ );
869 #check second addresspart (after '@' sign)
870 return 0 if ( $parts[1] !~ m/^[a-zA-Z0-9\.\-]+$/ );
876 # Currently only vpnmain use this three procs (readhasharray, writehasharray, findhasharray)
877 # The 'key' used is numeric but is perfectly unneeded! This will to be removed so don't use
878 # this code. Vpnmain will be splitted in parts: x509/pki, connection ipsec, connection other,... .
881 my ($filename, $hash) = @_;
884 open(FILE
, $filename) or die "Unable to read file $filename";
887 my ($key, $rest, @temp);
889 ($key, $rest) = split (/,/, $_, 2);
890 if ($key =~ /^[0-9]+$/) {
891 @temp = split (/,/, $rest);
892 $hash->{$key} = \
@temp;
900 my ($filename, $hash) = @_;
901 my ($key, @temp, $i);
903 open(FILE
, ">$filename") or die "Unable to write to file $filename";
905 foreach $key (keys %$hash) {
906 if ($key =~ /^[0-9]+$/) {
908 foreach $i (0 .. $#{$hash->{$key}}) {
909 print FILE
",$hash->{$key}[$i]";
918 sub findhasharraykey
{
919 foreach my $i (1 .. 1000000) {
920 if ( ! exists $_[0]{$i}) {
927 # Darren Critchley - darrenc@telus.net - (c) 2003
928 # &srtarray(SortOrder, AlphaNumeric, SortDirection, ArrayToBeSorted)
929 # This subroutine will take the following parameters:
930 # ColumnNumber = the column which you want to sort on, starts at 1
931 # AlphaNumberic = a or n (lowercase) defines whether the sort should be alpha or numberic
932 # SortDirection = asc or dsc (lowercase) Ascending or Descending sort
933 # ArrayToBeSorted = the array that wants sorting
935 # Returns an array that is sorted to your specs
937 # If SortOrder is greater than the elements in array, then it defaults to the first element
940 my ($colno, $alpnum, $srtdir, @tobesorted) = @_;
946 my $ttlitems = scalar @tobesorted; # want to know the number of rows in the passed array
947 if ($ttlitems < 1){ # if no items, don't waste our time lets leave
948 return (@tobesorted);
950 my @tmp = split(/\,/,$tobesorted[0]);
951 $ttlitems = scalar @tmp; # this should be the number of elements in each row of the passed in array
953 # Darren Critchley - validate parameters
954 if ($colno > $ttlitems){$colno = '1';}
955 $colno--; # remove one from colno to deal with arrays starting at 0
956 if($colno < 0){$colno = '0';}
957 if ($alpnum ne '') { $alpnum = lc($alpnum); } else { $alpnum = 'a'; }
958 if ($srtdir ne '') { $srtdir = lc($srtdir); } else { $srtdir = 'src'; }
960 foreach $line (@tobesorted)
964 my @temp = split(/\,/,$line);
965 # Darren Critchley - juggle the fields so that the one we want to sort on is first
966 my $tmpholder = $temp[0];
967 $temp[0] = $temp[$colno];
968 $temp[$colno] = $tmpholder;
970 for ($ctr=0; $ctr < $ttlitems ; $ctr++) {
971 $newline=$newline . $temp[$ctr] . ",";
974 push(@tmparray,$newline);
977 if ($alpnum eq 'n') {
978 @tmparray = sort {$a <=> $b} @tmparray;
980 @tmparray = (sort @tmparray);
982 foreach $line (@tmparray)
986 my @temp = split(/\,/,$line);
987 my $tmpholder = $temp[0];
988 $temp[0] = $temp[$colno];
989 $temp[$colno] = $tmpholder;
991 for ($ctr=0; $ctr < $ttlitems ; $ctr++){
992 $newline=$newline . $temp[$ctr] . ",";
995 push(@srtedarray,$newline);
999 if ($srtdir eq 'dsc') {
1000 @tmparray = reverse(@srtedarray);
1003 return (@srtedarray);
1009 &General
::readhash
("${General::swroot}/proxy/settings", \
%proxysettings);
1010 if ($_=$proxysettings{'UPSTREAM_PROXY'}) {
1011 my ($peer, $peerport) = (/^(?:[a-zA-Z ]+\:\/\
/)?(?:[A-Za-z0-9\_\.\-]*?(?:\:[A-Za-z0-9\_\.\-]*?)?\@)?([a-zA-Z0-9\.\_\-]*?)(?:\:([0-9]{1,5}))?(?:\/.*?
)?
$/);
1012 Net
::SSLeay
::set_proxy
($peer,$peerport,$proxysettings{'UPSTREAM_USER'},$proxysettings{'UPSTREAM_PASSWORD'} );
1014 my $user_agent = &MakeUserAgent
();
1015 my ($out, $response) = Net
::SSLeay
::get_http
( 'checkip4.dns.lightningwirelabs.com',
1018 Net
::SSLeay
::make_headers
('User-Agent' => $user_agent )
1020 if ($response =~ m
%HTTP/1\
.. 200 OK
%) {
1021 $out =~ /Your IP address is: (\d+.\d+.\d+.\d+)/;
1028 # Check if hostname.domain provided have IP provided
1029 # use gethostbyname to verify that
1035 # 1 IP matches host.domain
1038 sub DyndnsServiceSync
($;$;$) {
1040 my ($ip,$hostName,$domain) = @_;
1043 #fix me no ip GROUP, what is the name ?
1044 $hostName =~ s/$General::noipprefix//;
1045 if ($hostName) { #may be empty
1046 $hostName = "$hostName.$domain";
1047 @addresses = gethostbyname($hostName);
1050 if ($addresses[0] eq '') { # nothing returned ?
1051 $hostName = $domain; # try resolving with domain only
1052 @addresses = gethostbyname($hostName);
1055 if ($addresses[0] ne '') { # got something ?
1056 #&General::log("name:$addresses[0], alias:$addresses[1]");
1057 # Build clear text list of IP
1058 @addresses = map ( &Socket
::inet_ntoa
($_), @addresses[4..$#addresses]);
1059 if (grep (/$ip/, @addresses)) {
1066 # This sub returns the red IP used to compare in DyndnsServiceSync
1068 sub GetDyndnsRedIP
{
1070 &General
::readhash
("${General::swroot}/ddns/settings", \
%settings);
1072 open(IP
, "${General::swroot}/red/local-ipaddress") or return 'unavailable';
1077 # 100.64.0.0/10 is reserved for dual-stack lite (http://tools.ietf.org/html/rfc6598).
1078 if (&General
::IpInSubnet
($ip,'10.0.0.0','255.0.0.0') ||
1079 &General
::IpInSubnet
($ip,'172.16.0.0.','255.240.0.0') ||
1080 &General
::IpInSubnet
($ip,'192.168.0.0','255.255.0.0') ||
1081 &General
::IpInSubnet
($ip,'100.64.0.0', '255.192.0.0'))
1083 if ($settings{'BEHINDROUTER'} eq 'FETCH_IP') {
1084 my $RealIP = &General
::FetchPublicIp
;
1085 $ip = (&General
::validip
($RealIP) ?
$RealIP : 'unavailable');
1091 # Translate ICMP code to text
1092 # ref: http://www.iana.org/assignments/icmp-parameters
1093 sub GetIcmpDescription
($) {
1095 my @icmp_description = (
1099 'Destination Unreachable',
1102 'Alternate Host Address',
1105 'Router Advertisement',
1106 'Router Solicitation', #10
1108 'Parameter Problem',
1111 'Information Request',
1112 'Information Reply',
1113 'Address Mask Request',
1114 'Address Mask Reply',
1115 'Reserved (for Security)',
1116 'Reserved (for Robustness Experiment)', #20
1127 'Datagram Conversion Error',
1128 'Mobile Host Redirect',
1129 'IPv6 Where-Are-You',
1131 'Mobile Registration Request',
1132 'Mobile Registration Reply',
1133 'Domain Name Request',
1134 'Domain Name Reply',
1138 if ($index>41) {return 'unknown'} else {return $icmp_description[$index]};
1141 sub GetCoreUpdateVersion
() {
1144 open(FILE
, "/opt/pakfire/db/core/mine");
1151 return $core_update;
1154 sub MakeUserAgent
() {
1155 my $user_agent = "IPFire/$General::version";
1157 my $core_update = &GetCoreUpdateVersion
();
1158 if ($core_update ne "") {
1159 $user_agent .= "/$core_update";
1165 sub RedIsWireless
() {
1166 # This function checks if a network device is a wireless device.
1169 &readhash
("${General::swroot}/ethernet/settings", \
%settings);
1171 # Find the name of the network device.
1172 my $device = $settings{'RED_DEV'};
1174 # Exit, if no device is configured.
1175 return 0 if ($device eq "");
1177 # Return 1 if the device is a wireless one.
1178 my $path = "/sys/class/net/$device/wireless";
1183 # Otherwise return zero.
1187 # Function to read a file with UTF-8 charset.
1188 sub read_file_utf8
($) {
1191 open my $in, '<:encoding(UTF-8)', $file or die "Could not open '$file' for reading $!";
1199 # Function to write a file with UTF-8 charset.
1200 sub write_file_utf8
($) {
1201 my ($file, $content) = @_;
1203 open my $out, '>:encoding(UTF-8)', $file or die "Could not open '$file' for writing $!";;
1204 print $out $content;
1210 my $FIREWALL_RELOAD_INDICATOR = "${General::swroot}/firewall/reread";
1212 sub firewall_config_changed
() {
1213 open FILE
, ">$FIREWALL_RELOAD_INDICATOR" or die "Could not open $FIREWALL_RELOAD_INDICATOR";
1217 sub firewall_needs_reload
() {
1218 if (-e
"$FIREWALL_RELOAD_INDICATOR") {
1225 sub firewall_reload
() {
1226 system("/usr/local/bin/firewallctrl");
1229 # Function which will return the used interface for the red network zone (red0, ppp0, etc).
1230 sub get_red_interface
() {
1232 open(IFACE
, "${General::swroot}/red/iface") or die "Could not open /var/ipfire/red/iface";
1234 my $interface = <IFACE
>;
1241 sub dnssec_status
() {
1242 my $path = "${General::swroot}/red/dnssec-status";
1244 open(STATUS
, $path) or return 0;
1245 my $status = <STATUS
>;
1252 sub number_cpu_cores
() {
1253 open my $cpuinfo, "/proc/cpuinfo" or die "Can't open cpuinfo: $!\n";
1254 my $cores = scalar (map /^processor/, <$cpuinfo>);
1260 # Tiny function to grab a single IP-address from a given file.
1261 sub grab_address_from_file
($) {
1266 # Check if the given file exists.
1268 # Open the file for reading.
1269 open(FILE
, $file) or die "Could not read from $file. $!\n";
1271 # Read the address from the file.
1280 # Check if the obtained address is valid.
1281 if (&validip
($address)) {
1282 # Return the address.
1291 # Function to get all configured and enabled nameservers.
1292 sub get_nameservers
() {
1298 # Read DNS configuration.
1299 &readhash
("$General::swroot/dns/settings", \
%settings);
1301 # Read configured DNS servers.
1302 &readhasharray
("$General::swroot/dns/servers", \
%servers);
1304 # Check if the ISP assigned server should be used.
1305 if ($settings{'USE_ISP_NAMESERVERS'} eq "on") {
1306 # Assign ISP nameserver files.
1307 my @ISP_nameserver_files = ( "/var/run/dns1", "/var/run/dns2" );
1309 # Loop through the array of ISP assigned DNS servers.
1310 foreach my $file (@ISP_nameserver_files) {
1311 # Grab the IP address.
1312 my $address = &grab_address_from_file
($file);
1314 # Check if an address has been grabbed.
1316 # Add the address to the array of nameservers.
1317 push(@nameservers, $address);
1322 # Check if DNS servers are configured.
1324 # Loop through the hash of configured DNS servers.
1325 foreach my $id (keys %servers) {
1326 my $address = $servers{$id}[0];
1327 my $status = $servers{$id}[2];
1329 # Check if the current processed server is enabled.
1330 if ($status eq "enabled") {
1331 # Add the address to the array of nameservers.
1332 push(@nameservers, $address);
1338 return &uniq
(@nameservers);
1341 # Function to format a string containing the amount of bytes to
1342 # something human-readable.
1344 # Private array which contains the units.
1345 my @units = qw(B KB MB GB TB PB);
1350 # Loop through the array of units.
1351 foreach my $element (@units) {
1352 # Assign current processed element to unit.
1355 # Break loop if the bytes are less than the next unit.
1356 last if $bytes < 1024;
1358 # Divide bytes amount with 1024.
1362 # Return the divided and rounded bytes count and the unit.
1363 return sprintf("%.2f %s", $bytes, $unit);
1368 sub running_in_cloud
() {
1369 return &running_on_ec2
() || &running_on_gcp
();
1372 sub running_on_ec2
() {
1373 if (-e
"/var/run/aws-instance-id") {
1380 sub running_on_gcp
() {
1381 if (-e
"/var/run/gcp-instance-id") {