From 874599b9cd73126bbeee39d0cfee8d17e961a1d0 Mon Sep 17 00:00:00 2001 From: johnbyronent Date: Thu, 20 Nov 2014 20:19:30 +0100 Subject: [PATCH 001/257] Modified DynDns -> Eurodns url --- etc/inc/dyndns.class | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/dyndns.class b/etc/inc/dyndns.class index bb1bbc5937..a6a0f00436 100644 --- a/etc/inc/dyndns.class +++ b/etc/inc/dyndns.class @@ -604,7 +604,7 @@ log_error("EuroDynDns ({$this->_dnsHost}) DNS update() starting."); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); - $server = "https://eurodyndns.org/update/"; + $server = "https://update.eurodyndns.org/update/"; $port = ""; if($this->_dnsPort) $port = ":" . $this->_dnsPort; From c4249322d922901862719cc2e4c269351ed2c82c Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sun, 4 Jan 2015 22:18:08 +0545 Subject: [PATCH 002/257] Support choice of SMTP Authentication Mechanisms https://redmine.pfsense.org/issues/4176 I have left some documentation here of other mechanisms that someone might care about in future (or not). I left the array with name=>desc so it will be easy if new mechanisms come along that need a description different to the name. --- etc/inc/notices.inc | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/etc/inc/notices.inc b/etc/inc/notices.inc index 5bffce29de..044453533d 100644 --- a/etc/inc/notices.inc +++ b/etc/inc/notices.inc @@ -43,6 +43,16 @@ require_once("globals.inc"); require_once("led.inc"); $notice_path = $g['tmp_path'] . '/notices'; +$smtp_authentication_mechanisms = array( + 'PLAIN' => 'PLAIN', + 'LOGIN' => 'LOGIN'); +/* Other SMTP Authentication Mechanisms that could be supported. + * Note that MD5 is no longer considered secure. + * 'GSSAPI' => 'GSSAPI ' . gettext("Generic Security Services Application Program Interface") + * 'DIGEST-MD5' => 'DIGEST-MD5 ' . gettext("Digest access authentication") + * 'MD5' => 'MD5' + * 'CRAM-MD5' => 'CRAM-MD5' +*/ /****f* notices/file_notice * NAME @@ -321,7 +331,11 @@ function send_smtp_message($message, $subject = "(no subject)") { // Use SMTP Auth if fields are filled out if($config['notifications']['smtp']['username'] && $config['notifications']['smtp']['password']) { - $smtp->authentication_mechanism = "PLAIN"; + if (isset($config['notifications']['smtp']['authentication_mechanism'])) { + $smtp->authentication_mechanism = $config['notifications']['smtp']['authentication_mechanism']; + } else { + $smtp->authentication_mechanism = "PLAIN"; + } $smtp->user = $config['notifications']['smtp']['username']; $smtp->password = $config['notifications']['smtp']['password']; } From 305856e8fb19495e0543e0d74216117aac1d4bd8 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sun, 4 Jan 2015 22:22:23 +0545 Subject: [PATCH 003/257] Support for Office365 Mail https://redmine.pfsense.org/issues/4176 Allow the user to choose SMTP authentication mechanism PLAIN or LOGIN. For existing configs with this option not set, PLAIN is the default, and will appear first in the dropdown box, so next time the user saves the SMTP Notification settings, PLAIN will be the value selected and saved. --- .../www/system_advanced_notifications.php | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/usr/local/www/system_advanced_notifications.php b/usr/local/www/system_advanced_notifications.php index df4d52af01..da0c418568 100644 --- a/usr/local/www/system_advanced_notifications.php +++ b/usr/local/www/system_advanced_notifications.php @@ -75,6 +75,8 @@ if ($config['notifications']['smtp']['username']) $pconfig['smtpusername'] = $config['notifications']['smtp']['username']; if ($config['notifications']['smtp']['password']) $pconfig['smtppassword'] = $config['notifications']['smtp']['password']; +if ($config['notifications']['smtp']['authentication_mechanism']) + $pconfig['smtpauthmech'] = $config['notifications']['smtp']['authentication_mechanism']; if ($config['notifications']['smtp']['fromaddress']) $pconfig['smtpfromaddress'] = $config['notifications']['smtp']['fromaddress']; @@ -126,6 +128,7 @@ if ($_POST) { $config['notifications']['smtp']['notifyemailaddress'] = $_POST['smtpnotifyemailaddress']; $config['notifications']['smtp']['username'] = $_POST['smtpusername']; $config['notifications']['smtp']['password'] = $_POST['smtppassword']; + $config['notifications']['smtp']['authentication_mechanism'] = $_POST['smtpauthmech']; $config['notifications']['smtp']['fromaddress'] = $_POST['smtpfromaddress']; if($_POST['disable_smtp'] == "yes") @@ -307,6 +310,23 @@ include("head.inc"); + + + + +
+ + +   From a771a6aee364f60ab436f26d061b373118462c43 Mon Sep 17 00:00:00 2001 From: Warren Baker Date: Wed, 14 Jan 2015 13:34:58 +0200 Subject: [PATCH 004/257] Add support for 0x20 DNS random bit support. Fixes #4205 --- etc/inc/unbound.inc | 4 +++- usr/local/www/services_unbound_advanced.php | 18 +++++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/etc/inc/unbound.inc b/etc/inc/unbound.inc index 20ed19b805..cd02c94da1 100644 --- a/etc/inc/unbound.inc +++ b/etc/inc/unbound.inc @@ -2,7 +2,7 @@ /* unbound.inc part of the pfSense project (https://www.pfsense.org) - Copyright (C) 2014 Warren Baker + Copyright (C) 2015 Warren Baker All rights reserved. Redistribution and use in source and binary forms, with or without @@ -230,6 +230,7 @@ EOF; $unwanted_reply_threshold = "0"; $msg_cache_size = (!empty($config['unbound']['msgcachesize'])) ? $config['unbound']['msgcachesize'] : "4"; $verbosity = isset($config['unbound']['log_verbosity']) ? $config['unbound']['log_verbosity'] : 1; + $use_caps = isset($config['unbound']['use_caps']) ? "yes" : "no"; // Set up forwarding if it configured if (isset($config['unbound']['forwarding'])) { @@ -311,6 +312,7 @@ outgoing-range: 4096 {$anchor_file} prefetch: {$prefetch} prefetch-key: {$prefetch_key} +use-caps-for-id: {$use_caps} # Statistics {$statistics} # Interface IP(s) to bind to diff --git a/usr/local/www/services_unbound_advanced.php b/usr/local/www/services_unbound_advanced.php index 0efba70295..e560d1e5d9 100644 --- a/usr/local/www/services_unbound_advanced.php +++ b/usr/local/www/services_unbound_advanced.php @@ -3,7 +3,7 @@ /* services_unbound_advanced.php part of the pfSense project (https://www.pfsense.org) - Copyright (C) 2011 Warren Baker (warren@pfsense.org) + Copyright (C) 2015 Warren Baker (warren@percol8.co.za) Copyright (C) 2013-2015 Electric Sheep Fencing, LP All rights reserved. @@ -82,6 +82,10 @@ if (isset($config['unbound']['disable_auto_added_access_control'])) { $pconfig['disable_auto_added_access_control'] = true; } +if (isset($config['unbound']['use_caps'])) { + $pconfig['use_caps'] = true; +} + if ($_POST) { unset($input_errors); $pconfig = $_POST; @@ -176,6 +180,11 @@ if ($_POST) { } else { unset($config['unbound']['disable_auto_added_access_control']); } + if (isset($_POST['use_caps'])) { + $config['unbound']['use_caps'] = true; + } else { + unset($config['unbound']['use_caps']); + } write_config("DNS Resolver configured."); mark_subsystem_dirty('unbound'); @@ -442,6 +451,13 @@ include_once("head.inc"); + + + + />
+ ", "");?> + + From e30050b66515aa4f3ef164368b552fb5ad913386 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sun, 18 Jan 2015 23:50:00 +0545 Subject: [PATCH 005/257] Unimportant typos in user and group manager that do not effect anything. --- etc/inc/priv.inc | 4 ++-- usr/local/www/system_groupmanager_addprivs.php | 4 ++-- usr/local/www/system_usermanager.php | 6 +++--- usr/local/www/system_usermanager_addprivs.php | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/etc/inc/priv.inc b/etc/inc/priv.inc index c64fa8627e..8d1a736223 100644 --- a/etc/inc/priv.inc +++ b/etc/inc/priv.inc @@ -192,7 +192,7 @@ function isAllowed($username, $page) { if ($user['uid']==0) return true; - /* user privelege access check */ + /* user privilege access check */ if (cmp_page_matches($page, $_SESSION['page-match'])) return true; @@ -216,7 +216,7 @@ function isAllowedPage($page) { if ($user['uid']==0) return true; - /* user privelege access check */ + /* user privilege access check */ return cmp_page_matches($page, $_SESSION['page-match']); } diff --git a/usr/local/www/system_groupmanager_addprivs.php b/usr/local/www/system_groupmanager_addprivs.php index 8f7afeca59..ae7e884409 100644 --- a/usr/local/www/system_groupmanager_addprivs.php +++ b/usr/local/www/system_groupmanager_addprivs.php @@ -78,7 +78,7 @@ if ($_POST) { /* input validation */ $reqdfields = explode(" ", "sysprivs"); - $reqdfieldsn = array(gettext("Selected priveleges")); + $reqdfieldsn = array(gettext("Selected privileges")); do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); @@ -160,7 +160,7 @@ function update_description() { if ($savemsg) print_info_box($savemsg); ?> - +
+ + + + + + + + - + From d7f4c1a42def0b2db12db56c11a6d1949129122d Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Tue, 3 Feb 2015 12:54:26 -0600 Subject: [PATCH 047/257] fix responder-only IPsec text --- usr/local/www/vpn_ipsec_phase1.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/vpn_ipsec_phase1.php b/usr/local/www/vpn_ipsec_phase1.php index 87380381a6..e7c5cdb8b0 100644 --- a/usr/local/www/vpn_ipsec_phase1.php +++ b/usr/local/www/vpn_ipsec_phase1.php @@ -902,10 +902,10 @@ function dpdchkbox_change() { - + From 197cf4331e351d2bd20b5e67937297bfa693a344 Mon Sep 17 00:00:00 2001 From: McB Date: Tue, 3 Feb 2015 20:17:24 +0100 Subject: [PATCH 048/257] Added DynDNS support for GleSYS API (www.glesys.com). --- etc/inc/dyndns.class | 24 ++++++++++++++++++++++++ etc/inc/services.inc | 4 ++-- usr/local/www/services_dyndns_edit.php | 11 +++++++---- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/etc/inc/dyndns.class b/etc/inc/dyndns.class index b2faa4ac24..aaaa2cc4f1 100644 --- a/etc/inc/dyndns.class +++ b/etc/inc/dyndns.class @@ -30,6 +30,7 @@ * - Eurodns (eurodns.com) * - GratisDNS (gratisdns.dk) * - City Network (citynetwork.se) + * - GleSYS (glesys.com) * +----------------------------------------------------+ * Requirements: * - PHP version 4.0.2 or higher with the CURL Library and the PCRE Library @@ -72,6 +73,7 @@ * GratisDNS - Last Tested: 15 August 2012 * OVH DynHOST - Last Tested: NEVER * City Network - Last Tested: 13 November 2013 + * GleSYS - Last Tested: 3 February 2015 * +====================================================+ * * @author E.Kristensen @@ -211,6 +213,7 @@ $this->_error(10); } else { switch ($this->_dnsService) { + case 'glesys': case 'dnsomatic': case 'dyndns': case 'dyndns-static': @@ -279,6 +282,17 @@ } switch ($this->_dnsService) { + case 'glesys': + $needsIP = TRUE; + if ($this->_dnsVerboseLog) + log_error("DynDNS: ({$this->_dnsHost}) DNS update() starting."); + $server = 'https://api.glesys.com/domain/updaterecord/format/json'; + curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); + $post_data['recordid'] = $this->_dnsHost; + $post_data['data'] = $this->_dnsIP; + curl_setopt($ch, CURLOPT_URL, $server); + curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); + break; case 'dyndns': case 'dyndns-static': case 'dyndns-custom': @@ -683,6 +697,16 @@ return; } switch ($this->_dnsService) { + case 'glesys': + if (preg_match('/Record updated/i', $data)) { + $status = "GleSYS ({$this->_dnsHost}): (Success) IP Address Changed Successfully! (".$this->_dnsIP.")"; + $successful_update = true; + } else { + $status = "GleSYS ({$this->_dnsHost}): (Unknown Response)"; + log_error("GleSYS ({$this->_dnsHost}): PAYLOAD: {$data}"); + $this->_debug($data); + } + break; case 'dnsomatic': if (preg_match('/badauth/i', $data)) { $status = "DNS-O-Matic ({$this->_dnsHost}): The DNS-O-Matic username or password specified are incorrect. No updates will be distributed to services until this is resolved."; diff --git a/etc/inc/services.inc b/etc/inc/services.inc index 6b90753db1..5ef7c6613b 100644 --- a/etc/inc/services.inc +++ b/etc/inc/services.inc @@ -38,8 +38,8 @@ pfSense_MODULE: utils */ -define('DYNDNS_PROVIDER_VALUES', 'citynetwork cloudflare custom custom-v6 dhs dnsexit dnsomatic dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns gratisdns he-net he-net-v6 he-net-tunnelbroker loopia namecheap noip noip-free ods opendns ovh-dynhost route53 selfhost zoneedit'); -define('DYNDNS_PROVIDER_DESCRIPTIONS', 'City Network,CloudFlare,Custom,Custom (v6),DHS,DNSexit,DNS-O-Matic,DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,easyDNS,Euro Dns,freeDNS,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,SelfHost,ZoneEdit'); +define('DYNDNS_PROVIDER_VALUES', 'citynetwork cloudflare custom custom-v6 dhs dnsexit dnsomatic dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns glesys gratisdns he-net he-net-v6 he-net-tunnelbroker loopia namecheap noip noip-free ods opendns ovh-dynhost route53 selfhost zoneedit'); +define('DYNDNS_PROVIDER_DESCRIPTIONS', 'City Network,CloudFlare,Custom,Custom (v6),DHS,DNSexit,DNS-O-Matic,DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,easyDNS,Euro Dns,freeDNS,GleSYS,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,SelfHost,ZoneEdit'); /* implement ipv6 route advertising daemon */ function services_radvd_configure($blacklist = array()) { diff --git a/usr/local/www/services_dyndns_edit.php b/usr/local/www/services_dyndns_edit.php index c88e22df62..2545b4e775 100644 --- a/usr/local/www/services_dyndns_edit.php +++ b/usr/local/www/services_dyndns_edit.php @@ -319,7 +319,8 @@ function _onTypeChange(type){

- +
+
@@ -359,8 +360,9 @@ function _onTypeChange(type){ @@ -369,7 +371,8 @@ function _onTypeChange(type){
-
+
+
From 68fde79cb5cc397315a45ddee41f88b12a04b28f Mon Sep 17 00:00:00 2001 From: McB Date: Tue, 3 Feb 2015 20:21:35 +0100 Subject: [PATCH 049/257] Fixed alignment issue. --- usr/local/www/services_dyndns_edit.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/usr/local/www/services_dyndns_edit.php b/usr/local/www/services_dyndns_edit.php index 2545b4e775..106064aaf0 100644 --- a/usr/local/www/services_dyndns_edit.php +++ b/usr/local/www/services_dyndns_edit.php @@ -360,9 +360,9 @@ function _onTypeChange(type){ @@ -371,8 +371,8 @@ function _onTypeChange(type){
-
-
+
+
From 695b6d08bc6bb01e5460b5592e208c5cca9e0e0f Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Wed, 4 Feb 2015 08:03:00 +0545 Subject: [PATCH 050/257] Firmware upgrade script text changes while I am looking at this, might as well correct these. No function problems or impact. --- etc/rc.firmware | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/etc/rc.firmware b/etc/rc.firmware index db886b2b9f..3912291c0c 100755 --- a/etc/rc.firmware +++ b/etc/rc.firmware @@ -145,8 +145,8 @@ pfSenseNanoBSDupgrade) # Prevent full upgrade file from being used to upgrade if [ `echo $IMG | grep "full"` ]; then - echo "You cannot use a full file for upgrade. Please use a file labeled nanobsd upgrade." - file_notice "NanoBSDUpgradeFailure" "You have attemped to use a full NanoBSD installation file as an upgrade. Please use a NanoBSD file labeled 'upgrade' instead." + echo "You cannot use a full file for upgrade. Please use a file labelled nanobsd upgrade." + file_notice "NanoBSDUpgradeFailure" "You have attempted to use a full NanoBSD installation file as an upgrade. Please use a NanoBSD file labelled 'upgrade' instead." rm -f $IMG /etc/rc.conf_mount_ro exit 1 @@ -176,7 +176,7 @@ pfSenseNanoBSDupgrade) REAL_BOOT_DEVICE=`/sbin/glabel list | /usr/bin/grep -B2 ufs/${BOOT_DEVICE} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '` # grab the boot device, example ad1, ad0 BOOT_DRIVE=`/sbin/glabel list | /usr/bin/grep -B2 ufs/pfsense | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' ' | /usr/bin/cut -d's' -f1` - # test the slice. if we are on slice 1 we need to flash 2 and vica versa + # test the slice. if we are on slice 1 we need to flash 2 and vice versa if [ `echo $REAL_BOOT_DEVICE | /usr/bin/grep "s1"` ]; then SLICE="2" OLDSLICE="1" @@ -195,7 +195,7 @@ pfSenseNanoBSDupgrade) OLD_UFS_ID="1" fi - # Output specifc information that this script is using + # Output specific information that this script is using echo "SLICE ${SLICE}" >> /conf/upgrade_log.txt echo "OLDSLICE ${OLDSLICE}" >> /conf/upgrade_log.txt echo "TOFLASH ${TOFLASH}" >> /conf/upgrade_log.txt @@ -207,9 +207,9 @@ pfSenseNanoBSDupgrade) NEW_IMG_SIZE=`echo $((\`gzip -l ${IMG} | grep -v compressed | awk '{ print $2}'\` / 1024 / 1024))` SIZE=`/sbin/fdisk ${COMPLETE_PATH} | /usr/bin/grep Meg | /usr/bin/awk '{ print $5 }' | /usr/bin/cut -d"(" -f2` # USB slices are under-reported even more than CF slices when viewed - # directly, instead of when looking at the entire disk. Compensate - # by adding exactly 6MB. 4MB was consistently 2MB too few, and - # was resulting in failing upgrades on USB Flash based installs. + # directly, instead of when looking at the entire disk. Compensate + # by adding exactly 6MB. 4MB was consistently 2MB too few, and + # was resulting in failing upgrades on USB Flash based installs. SIZE=`expr $SIZE + 6` if [ "$SIZE" -lt "$NEW_IMG_SIZE" ]; then file_notice "UpgradeFailure" "Upgrade failed due to the upgrade image being larger than the partition that is configured on disk. Halting. Size on disk: $SIZE < Size of new image: $NEW_IMG_SIZE" @@ -250,7 +250,7 @@ pfSenseNanoBSDupgrade) echo "/usr/bin/gzip -dc $IMG | /bin/dd of=/dev/${TOFLASH} obs=64k" >> /conf/upgrade_log.txt /usr/bin/gzip -dc $IMG | /bin/dd of=/dev/${TOFLASH} obs=64k >> /conf/upgrade_log.txt 2>&1 - # Grab a after upgrade look at fdisk + # Grab an after upgrade look at fdisk echo "" >> /conf/fdisk_upgrade_log.txt echo "After upgrade fdisk/bsdlabel" >> /conf/upgrade_log.txt fdisk $BOOT_DRIVE >> /conf/fdisk_upgrade_log.txt @@ -364,7 +364,7 @@ pfSenseNanoBSDupgrade) date >> /conf/upgrade_log.txt echo "" >> /conf/upgrade_log.txt - # Trigger a package reinstallation on reobot + # Trigger a package reinstallation on reboot touch /conf/needs_package_sync # remount /cf ro @@ -391,7 +391,7 @@ pfSenseupgrade) exit fi - # wait 1 seconds before beginning + # wait 1 second before beginning sleep 1 # Log that we are really doing a pfSense upgrade From 7e36f71c32f11ec322abd42d12b6b3160c09a721 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 4 Feb 2015 07:42:51 -0200 Subject: [PATCH 051/257] Silent kenv when smbios.system.product is not present. While here, add VirtualBox to the list of virtualenvs --- etc/inc/pfsense-utils.inc | 10 +++++++--- etc/inc/system.inc | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/etc/inc/pfsense-utils.inc b/etc/inc/pfsense-utils.inc index 36640aaa73..7fcb000ea8 100644 --- a/etc/inc/pfsense-utils.inc +++ b/etc/inc/pfsense-utils.inc @@ -1630,10 +1630,14 @@ function load_thermal_hardware() { * returns true if machine is running under a virtual environment ******/ function isvm() { - $virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86"); - $bios_product = trim(`/bin/kenv smbios.system.product`); + $virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86", "VirtualBox"); + $_gb = exec('/bin/kenv smbios.system.product 2>/dev/null', $output, $rc); + + if ($rc != 0 || !isset($output[0])) + return false; + foreach ($virtualenvs as $virtualenv) - if (stripos($bios_product, $virtualenv) !== false) + if (stripos($output[0], $virtualenv) !== false) return true; return false; diff --git a/etc/inc/system.inc b/etc/inc/system.inc index 5de9ec4c4e..4f2fdad77f 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -2036,7 +2036,7 @@ function system_identify_specific_platform() { /* Try to guess from smbios strings */ unset($output); - $_gb = exec('/bin/kenv smbios.system.product', $output); + $_gb = exec('/bin/kenv smbios.system.product 2>/dev/null', $output); switch ($output[0]) { case 'FW7541': return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541')); From 1f97f37920d2f82cb4bbfa420db20609c25ef132 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 4 Feb 2015 08:14:30 -0200 Subject: [PATCH 052/257] In last case, use dmesg.boot do detect ALIX boards when hw.model is not enough --- etc/inc/system.inc | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/etc/inc/system.inc b/etc/inc/system.inc index 4f2fdad77f..7b58cfc788 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -2066,7 +2066,14 @@ function system_identify_specific_platform() { if (preg_match("/Soekris net55../", $dmesg, $matches)) return array('name' => 'net55xx', 'descr' => $matches[0]); - + + unset($dmesg); + + $dmesg_boot = system_get_dmesg_boot(); + if (strpos($dmesg_boot, "PC Engines ALIX") !== false) + return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX')); + unset($dmesg_boot); + /* unknown embedded platform */ return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)')); } From 68716545c5fde880d7a22cd9b13b901d01ccb561 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Wed, 4 Feb 2015 15:45:55 +0100 Subject: [PATCH 053/257] Fixes #3669 Handle properly recording of the ipv6 interface new ip and do not issues commands that cannot succeed. --- etc/rc.newwanipv6 | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/etc/rc.newwanipv6 b/etc/rc.newwanipv6 index 867013c3c0..72aabf7133 100755 --- a/etc/rc.newwanipv6 +++ b/etc/rc.newwanipv6 @@ -122,7 +122,7 @@ if (is_ipaddrv6($curwanipv6)) log_error("rc.newwanipv6: on (IP address: {$curwanipv6}) (interface: {$interface}) (real interface: {$interface_real})."); -$oldipv6 = ""; +$oldipv6 = ''; if (file_exists("{$g['vardb_path']}/{$interface}_cacheipv6")) $oldipv6 = file_get_contents("{$g['vardb_path']}/{$interface}_cacheipv6"); @@ -144,7 +144,7 @@ setup_gateways_monitor(); /* signal filter reload */ filter_configure(); -if (is_ipaddrv6($oldipv6)) { +if (empty($oldipv6) || is_ipaddrv6($oldipv6)) { if ($curwanipv6 == $oldipv6) { // Still need to sync VPNs on PPPoE and such, as even with the same IP the VPN software is unhappy with the IP disappearing. if (in_array($config['interfaces'][$interface]['ipaddrv6'], array('pppoe', 'pptp', 'ppp'))) { @@ -156,13 +156,12 @@ if (is_ipaddrv6($oldipv6)) { openvpn_resync_all($interface); } return; - } else if (does_interface_exist($interface_real)) + } else if (does_interface_exist($interface_real) && !empty($oldipv6)) mwexec("/sbin/ifconfig {$interface_real} inet6 {$oldipv6} delete"); file_put_contents("{$g['vardb_path']}/{$interface}_cacheipv6", $curwanipv6); } - /* reload unbound */ services_unbound_configure(); From 62657a7f8a5cc6c5c932157eaac373c8d9227bc8 Mon Sep 17 00:00:00 2001 From: jim-p Date: Wed, 4 Feb 2015 12:36:07 -0500 Subject: [PATCH 054/257] Fix restartipsec command line script. --- etc/inc/ipsec.inc | 14 ++++++++++++++ etc/phpshellsessions/restartipsec | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/etc/inc/ipsec.inc b/etc/inc/ipsec.inc index 04a4aae3e6..53c60264c3 100644 --- a/etc/inc/ipsec.inc +++ b/etc/inc/ipsec.inc @@ -35,12 +35,14 @@ */ /* IPsec defines */ +global $ipsec_loglevels; $ipsec_loglevels = array("dmn" => "Daemon", "mgr" => "SA Manager", "ike" => "IKE SA", "chd" => "IKE Child SA", "job" => "Job Processing", "cfg" => "Configuration backend", "knl" => "Kernel Interface", "net" => "Networking", "asn" => "ASN encoding", "enc" => "Message encoding", "imc" => "Integrity checker", "imv" => "Integrity Verifier", "pts" => "Platform Trust Service", "tls" => "TLS handler", "esp" => "IPsec traffic", "lib" => "StrongSwan Lib"); +global $my_identifier_list; $my_identifier_list = array( 'myaddress' => array( 'desc' => gettext('My IP address'), 'mobile' => true ), 'address' => array( 'desc' => gettext('IP address'), 'mobile' => true ), @@ -50,6 +52,7 @@ $my_identifier_list = array( 'keyid tag' => array( 'desc' => gettext('KeyID tag'), 'mobile' => true ), 'dyn_dns' => array( 'desc' => gettext('Dynamic DNS'), 'mobile' => true )); +global $peer_identifier_list; $peer_identifier_list = array( 'peeraddress' => array( 'desc' => gettext('Peer IP address'), 'mobile' => false ), 'address' => array( 'desc' => gettext('IP address'), 'mobile' => false ), @@ -58,10 +61,12 @@ $peer_identifier_list = array( 'asn1dn' => array( 'desc' => gettext('ASN.1 distinguished Name'), 'mobile' => true ), 'keyid tag' => array( 'desc' =>gettext('KeyID tag'), 'mobile' => true )); +global $ipsec_idhandling; $ipsec_idhandling = array( 'yes' => 'YES', 'no' => 'NO', 'never' => 'NEVER', 'keep' => 'KEEP' ); +global $p1_ealgos; $p1_ealgos = array( 'aes' => array( 'name' => 'AES', 'keysel' => array( 'lo' => 128, 'hi' => 256, 'step' => 64 ) ), 'blowfish' => array( 'name' => 'Blowfish', 'keysel' => array( 'lo' => 128, 'hi' => 256, 'step' => 64 ) ), @@ -69,6 +74,7 @@ $p1_ealgos = array( 'cast128' => array( 'name' => 'CAST128' ), 'des' => array( 'name' => 'DES' )); +global $p2_ealgos; $p2_ealgos = array( 'aes' => array( 'name' => 'AES', 'keysel' => array( 'lo' => 128, 'hi' => 256, 'step' => 64 ) ), 'aes128gcm' => array( 'name' => 'AES128-GCM', 'keysel' => array( 'lo' => 64, 'hi' => 128, 'step' => 32 ) ), @@ -79,6 +85,7 @@ $p2_ealgos = array( 'cast128' => array( 'name' => 'CAST128' ), 'des' => array( 'name' => 'DES' )); +global $p1_halgos; $p1_halgos = array( 'md5' => 'MD5', 'sha1' => 'SHA1', @@ -88,6 +95,7 @@ $p1_halgos = array( 'aesxcbc' => 'AES-XCBC' ); +global $p1_dhgroups; $p1_dhgroups = array( 1 => '1 (768 bit)', 2 => '2 (1024 bit)', @@ -102,6 +110,7 @@ $p1_dhgroups = array( 24 => '24 (2048(sub 256) bit)' ); +global $p2_halgos; $p2_halgos = array( 'hmac_md5' => 'MD5', 'hmac_sha1' => 'SHA1', @@ -111,6 +120,7 @@ $p2_halgos = array( 'aesxcbc' => 'AES-XCBC' ); +global $p1_authentication_methods; $p1_authentication_methods = array( 'hybrid_rsa_server' => array( 'name' => 'Hybrid RSA + Xauth', 'mobile' => true ), 'xauth_rsa_server' => array( 'name' => 'Mutual RSA + Xauth', 'mobile' => true ), @@ -120,20 +130,24 @@ $p1_authentication_methods = array( 'rsasig' => array( 'name' => 'Mutual RSA', 'mobile' => false ), 'pre_shared_key' => array( 'name' => 'Mutual PSK', 'mobile' => false ) ); +global $ipsec_preshared_key_type; $ipsec_preshared_key_type = array( 'PSK' => 'PSK', 'EAP' => 'EAP' ); +global $p2_modes; $p2_modes = array( 'tunnel' => 'Tunnel IPv4', 'tunnel6' => 'Tunnel IPv6', 'transport' => 'Transport'); +global $p2_protos; $p2_protos = array( 'esp' => 'ESP', 'ah' => 'AH'); +global $p2_pfskeygroups; $p2_pfskeygroups = array( 0 => 'off', 1 => '1 (768 bit)', diff --git a/etc/phpshellsessions/restartipsec b/etc/phpshellsessions/restartipsec index 66f9eb351a..cadff257ca 100644 --- a/etc/phpshellsessions/restartipsec +++ b/etc/phpshellsessions/restartipsec @@ -2,4 +2,4 @@ require_once("config.inc"); require_once("ipsec.inc"); require_once("vpn.inc"); -vpn_ipsec_configure(); +vpn_ipsec_configure(true); From b997da8b61ef9b519dcaaa68e55beb4bccf4dccd Mon Sep 17 00:00:00 2001 From: xbipin Date: Thu, 5 Feb 2015 09:41:17 +0400 Subject: [PATCH 055/257] upgrade config upgrade config code so old entries not lost during upgrade --- conf.default/config.xml | 2 +- etc/inc/globals.inc | 2 +- etc/inc/upgrade_config.inc | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/conf.default/config.xml b/conf.default/config.xml index bbb5acb666..bb94cd8713 100644 --- a/conf.default/config.xml +++ b/conf.default/config.xml @@ -1,6 +1,6 @@ - 11.6 + 11.7 pfsense_ng diff --git a/etc/inc/globals.inc b/etc/inc/globals.inc index f3233f97e7..6a16bc23f9 100644 --- a/etc/inc/globals.inc +++ b/etc/inc/globals.inc @@ -73,7 +73,7 @@ $g = array( "disablecrashreporter" => false, "crashreporterurl" => "https://crashreporter.pfsense.org/crash_reporter.php", "debug" => false, - "latest_config" => "11.6", + "latest_config" => "11.7", "nopkg_platforms" => array("cdrom"), "minimum_ram_warning" => "101", "minimum_ram_warning_text" => "128 MB", diff --git a/etc/inc/upgrade_config.inc b/etc/inc/upgrade_config.inc index 690db4596f..572c06b15e 100644 --- a/etc/inc/upgrade_config.inc +++ b/etc/inc/upgrade_config.inc @@ -3552,4 +3552,21 @@ function upgrade_115_to_116() { } } +function upgrade_116_to_117() { + global $config; + + if (!isset($config['installedpackages']['miniupnpd']['config'][0])) + return; + + $miniupnpd =& $config['installedpackages']['miniupnpd']['config'][0]; + + $miniupnpd['row'] = array(); + + for ($i = 1; $i <= 4; $i++) { + if (isset($miniupnpd["permuser{$i}"]) && !empty($miniupnpd["permuser{$i}"])) { + $miniupnpd['row'][] = array('permuser' => $miniupnpd["permuser{$i}"]); + unset($miniupnpd["permuser{$i}"]); + } + } +} ?> From ee874f47823b0677ae129ca7c206e59433f8d536 Mon Sep 17 00:00:00 2001 From: xbipin Date: Thu, 5 Feb 2015 13:11:25 +0400 Subject: [PATCH 056/257] remove empty values remove empty values --- etc/inc/upgrade_config.inc | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/etc/inc/upgrade_config.inc b/etc/inc/upgrade_config.inc index 572c06b15e..e06c2590bd 100644 --- a/etc/inc/upgrade_config.inc +++ b/etc/inc/upgrade_config.inc @@ -3555,18 +3555,17 @@ function upgrade_115_to_116() { function upgrade_116_to_117() { global $config; - if (!isset($config['installedpackages']['miniupnpd']['config'][0])) - return; + if (!isset($config['installedpackages']['miniupnpd']['config'][0])) + return; - $miniupnpd =& $config['installedpackages']['miniupnpd']['config'][0]; + $miniupnpd =& $config['installedpackages']['miniupnpd']['config'][0]; - $miniupnpd['row'] = array(); + $miniupnpd['row'] = array(); - for ($i = 1; $i <= 4; $i++) { - if (isset($miniupnpd["permuser{$i}"]) && !empty($miniupnpd["permuser{$i}"])) { - $miniupnpd['row'][] = array('permuser' => $miniupnpd["permuser{$i}"]); - unset($miniupnpd["permuser{$i}"]); - } - } + for ($i = 1; $i <= 4; $i++) { + if (isset($miniupnpd["permuser{$i}"]) && !empty($miniupnpd["permuser{$i}"])) + $miniupnpd['row'][] = array('permuser' => $miniupnpd["permuser{$i}"]); + unset($miniupnpd["permuser{$i}"]); + } } ?> From d06f9ebea38c14c532085714456fa5e846283ba2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20=C3=96hman?= Date: Thu, 5 Feb 2015 10:41:20 +0100 Subject: [PATCH 057/257] Use web-gui setting for pap or chap instead of having it hard-coded to chap. --- etc/inc/vpn.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 632ea9b462..860d5b68a7 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -1646,7 +1646,7 @@ l2tp_standard: set iface down-script /usr/local/sbin/vpn-linkdown set link yes acfcomp protocomp set link no pap chap - set link enable chap + {$paporchap} set link keep-alive 10 180 EOD; From bb8a30c23b04d8332e8d4fccf15ed91d950cda2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Thu, 5 Feb 2015 20:40:39 +0100 Subject: [PATCH 058/257] Fixes #4381 this was a leftover of the change of zoneids to start from 2. --- etc/inc/filter.inc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index 53c4984637..602878dc81 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -2891,8 +2891,8 @@ EOD; if (count($cpiplist) > 0 && count($cpiflist) > 0) { $cpinterface = implode(" ", $cpiflist); $cpaddresses = implode(" ", $cpiplist); - $listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 1); - $listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : $cpcfg['zoneid']; + $listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : 8000 + ($cpcfg['zoneid'] + 1); + $listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : 8000 + $cpcfg['zoneid']; $portalias = $listenporthttps; $portalias .= " {$listenporthttp}"; $ipfrules .= "pass in {$log['pass']} quick on { {$cpinterface} } proto tcp from any to { {$cpaddresses} } port { {$portalias} } tracker {$increment_tracker($tracker)} keep state(sloppy)\n"; From 2dfe784626d79ebb79e0952a413f7abe4e7c5ddf Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 5 Feb 2015 13:47:25 -0600 Subject: [PATCH 059/257] remove CGN from "Block private networks" as it was in 2.0x and earlier releases since it specifically notes RFC 1918 and CGN is more bogon. Ticket #4379 --- etc/inc/filter.inc | 1 - 1 file changed, 1 deletion(-) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index 602878dc81..21dd2ee348 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -2978,7 +2978,6 @@ EOD; # block anything from private networks on interfaces with the option set block in $privnetlog quick on \${$oc['descr']} from 10.0.0.0/8 to any tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Block private networks from {$oc['descr']} block 10/8")}" block in $privnetlog quick on \${$oc['descr']} from 127.0.0.0/8 to any tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Block private networks from {$oc['descr']} block 127/8")}" -block in $privnetlog quick on \${$oc['descr']} from 100.64.0.0/10 to any tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Block private networks from {$oc['descr']} block 100.64/10")}" block in $privnetlog quick on \${$oc['descr']} from 172.16.0.0/12 to any tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Block private networks from {$oc['descr']} block 172.16/12")}" block in $privnetlog quick on \${$oc['descr']} from 192.168.0.0/16 to any tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Block private networks from {$oc['descr']} block 192.168/16")}" block in $privnetlog quick on \${$oc['descr']} from fc00::/7 to any tracker {$increment_tracker($tracker)} label "{$fix_rule_label("Block ULA networks from {$oc['descr']} block fc00::/7")}" From 6d5d965875ea7e26b8e9113ce8281ccbb3da7a74 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Fri, 6 Feb 2015 22:28:07 -0600 Subject: [PATCH 060/257] fix up text --- .../share/locale/en/LC_MESSAGES/pfSense.pot | 2 +- .../share/locale/ja/LC_MESSAGES/pfSense.po | 2 +- .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo | Bin 643027 -> 643027 bytes .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po | 2 +- .../share/locale/tr/LC_MESSAGES/pfSense.mo | Bin 578284 -> 578284 bytes .../share/locale/tr/LC_MESSAGES/pfSense.po | 2 +- usr/local/www/services_captiveportal.php | 2 +- 7 files changed, 5 insertions(+), 5 deletions(-) diff --git a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot index 721d0bbce1..7419f47d6b 100644 --- a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot +++ b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot @@ -18023,7 +18023,7 @@ msgid "RADIUS Authentication" msgstr "" #: usr/local/www/services_captiveportal.php:689 -msgid "Radius Protocol" +msgid "RADIUS Protocol" msgstr "" #: usr/local/www/services_captiveportal.php:694 usr/local/www/vpn_l2tp.php:392 diff --git a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po index cbcc770565..afac78fa55 100644 --- a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po @@ -44831,7 +44831,7 @@ msgstr "ãƒãƒ¼ã‚¿ãƒ«HTTP(S )サーãƒã€Œã“ã®è¨­å®šã§ã¯ã€ã‚­ãƒ£ãƒ—ティ #: usr/local/www/services_captiveportal.php:601 #: usr/local/www/services_captiveportal.php:617 #: usr/local/www/services_captiveportal.php:617 -msgid "Radius Protocol" +msgid "RADIUS Protocol" msgstr "åŠå¾„プロトコル" #: usr/local/www/services_captiveportal.php:611 diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo index 5c213a6ba98f7e128124f12a749409d70722b99b..e0a0fb23ec05d39e882c8e06590341aed60abd97 100644 GIT binary patch delta 47 xcmcaSU;XlY^@bM47N#xCbx&9wT|7gB+nb*-12GE_vjQ<25VLP@e!>y(8UXJi6>y(8UO)N77_pe diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po index ef7596bb9e..81c5b3da09 100644 --- a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po @@ -37850,7 +37850,7 @@ msgstr "Esta configura #: usr/local/www/services_captiveportal.php:600 #: usr/local/www/services_captiveportal.php:601 #: usr/local/www/services_captiveportal.php:617 -msgid "Radius Protocol" +msgid "RADIUS Protocol" msgstr "Protocolo Radius" #: usr/local/www/services_captiveportal.php:611 diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.mo index 544d667a85611c2c1bbef29f7b11c22bb30a0506..37a2f27435d06f43bc01afcaecd9e7818f59647c 100644 GIT binary patch delta 47 xcmaE}RQb(P<%Sl<7N#xCt9n@-T|7gB+t>Fp12GE_vjQ<25VLPz-^*d^3IOGR6T$!h delta 47 xcmaE}RQb(P<%Sl<7N#xCt9n@zQ!-17+t>Fp12GE_vjQ<25VLPz-^*d^3IO+@6k-4X diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po index 1da024e6e5..c384e17a00 100644 --- a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po @@ -18985,7 +18985,7 @@ msgid "RADIUS Authentication" msgstr "RADIUS Kimlik DoÄŸrulama" #: usr/local/www/services_captiveportal.php:689 -msgid "Radius Protocol" +msgid "RADIUS Protocol" msgstr "Radius Protokol" #: usr/local/www/services_captiveportal.php:694 usr/local/www/vpn_l2tp.php:392 diff --git a/usr/local/www/services_captiveportal.php b/usr/local/www/services_captiveportal.php index 8c1487b4e1..41a904274e 100644 --- a/usr/local/www/services_captiveportal.php +++ b/usr/local/www/services_captiveportal.php @@ -692,7 +692,7 @@ function enable_change(enable_change) { - + +
- +
@@ -1037,7 +1037,7 @@ if ($savemsg) From 6a32a3e4bd5d63bfe3add80ab5af7f582ba400f7 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Tue, 27 Jan 2015 00:26:06 -0600 Subject: [PATCH 008/257] use example.com for examples --- usr/local/www/vpn_openvpn_client.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/vpn_openvpn_client.php b/usr/local/www/vpn_openvpn_client.php index f8ff368ead..2f46ca62bd 100644 --- a/usr/local/www/vpn_openvpn_client.php +++ b/usr/local/www/vpn_openvpn_client.php @@ -1061,7 +1061,7 @@ if ($savemsg)
Date: Sun, 25 Jan 2015 21:32:23 +0545 Subject: [PATCH 006/257] Dynamic DNS wildcard typo Self-explanatory, just a dumb typo bug --- etc/inc/services.inc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/etc/inc/services.inc b/etc/inc/services.inc index 5bcf5de6ef..6b90753db1 100644 --- a/etc/inc/services.inc +++ b/etc/inc/services.inc @@ -41,7 +41,7 @@ define('DYNDNS_PROVIDER_VALUES', 'citynetwork cloudflare custom custom-v6 dhs dnsexit dnsomatic dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns gratisdns he-net he-net-v6 he-net-tunnelbroker loopia namecheap noip noip-free ods opendns ovh-dynhost route53 selfhost zoneedit'); define('DYNDNS_PROVIDER_DESCRIPTIONS', 'City Network,CloudFlare,Custom,Custom (v6),DHS,DNSexit,DNS-O-Matic,DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,easyDNS,Euro Dns,freeDNS,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,SelfHost,ZoneEdit'); -/* implement ipv6 route advertising deamon */ +/* implement ipv6 route advertising daemon */ function services_radvd_configure($blacklist = array()) { global $config, $g; @@ -1660,7 +1660,7 @@ function services_dyndns_configure_client($conf) { $dnsHost = $conf['host'], $dnsUser = $conf['username'], $dnsPass = $conf['password'], - $dnsWilcard = $conf['wildcard'], + $dnsWildcard = $conf['wildcard'], $dnsMX = $conf['mx'], $dnsIf = "{$conf['interface']}", $dnsBackMX = NULL, From 580f5eee603406e748023741319f54e353cfa1c0 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Tue, 27 Jan 2015 00:21:05 -0600 Subject: [PATCH 007/257] these descriptions were flipped. Ticket #4273 --- usr/local/www/vpn_openvpn_client.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/vpn_openvpn_client.php b/usr/local/www/vpn_openvpn_client.php index 06cd666190..f8ff368ead 100644 --- a/usr/local/www/vpn_openvpn_client.php +++ b/usr/local/www/vpn_openvpn_client.php @@ -1018,7 +1018,7 @@ if ($savemsg) - --route-up . + .
- . + --route-up .


- remote server.mysite.com 1194; or remote 1.2.3.4 1194; + remote server.example.com 1194; or remote 1.2.3.4 1194;
From f76cbd6ffea4753abae87efae1d7a73bde67f3cd Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Tue, 27 Jan 2015 10:38:45 -0200 Subject: [PATCH 009/257] Fix sed syntax, -i requires a space before the parameter. Also fix regex to find swap device --- usr/local/sbin/ufslabels.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/usr/local/sbin/ufslabels.sh b/usr/local/sbin/ufslabels.sh index 8a6c21149f..0304a06936 100755 --- a/usr/local/sbin/ufslabels.sh +++ b/usr/local/sbin/ufslabels.sh @@ -48,7 +48,7 @@ get_ufsid() { find_fs_device(){ unset DEV - DEV=`/usr/bin/grep -e "[[:blank:]]${1}[[:blank:]]" ${FSTAB} | awk '{print $1;}'` + DEV=`/usr/bin/grep -e "[[:blank:]]*${1}[[:blank:]]" ${FSTAB} | awk '{print $1;}'` DEV=${DEV##/dev/} } @@ -67,7 +67,7 @@ do if [ ${LEN} -ne 16 ]; then echo "Invalid UFS ID for FS ${FS} ($UFSID), skipping" else - /usr/bin/sed -i'' -e "s/${DEV}/ufsid\/${UFSID}/g" ${FSTAB}.tmp + /usr/bin/sed -i '' -e "s/${DEV}/ufsid\/${UFSID}/g" ${FSTAB}.tmp NEED_CHANGES=true fi else @@ -86,7 +86,7 @@ do SWAPDEV=${DEV} echo "FS: Swap slice ${SWAPNUM} on device ${SWAPDEV}" if [ "${SWAPDEV}" != "" ]; then - /usr/bin/sed -i'' -e "s/${SWAPDEV}/label\/swap${SWAPNUM}/g" ${FSTAB}.tmp + /usr/bin/sed -i '' -e "s/${SWAPDEV}/label\/swap${SWAPNUM}/g" ${FSTAB}.tmp NEED_CHANGES=true fi SWAPNUM=`expr ${SWAPNUM} + 1` From db4b45768da09a8a4a08d38c1bc49b9414d876ca Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Tue, 27 Jan 2015 10:59:46 -0200 Subject: [PATCH 010/257] Improve a bit sh syntax and fix it for multiple swap devices --- usr/local/sbin/ufslabels.sh | 71 +++++++++++++++++++++---------------- 1 file changed, 40 insertions(+), 31 deletions(-) diff --git a/usr/local/sbin/ufslabels.sh b/usr/local/sbin/ufslabels.sh index 0304a06936..3c0c68800f 100755 --- a/usr/local/sbin/ufslabels.sh +++ b/usr/local/sbin/ufslabels.sh @@ -12,7 +12,7 @@ string_length() { unset LEN - LEN=`echo -n ${1} | /usr/bin/wc -m | awk '{print $1}'` + LEN=$(echo -n "${1}" | /usr/bin/wc -m) } get_ufsid() { @@ -21,63 +21,72 @@ get_ufsid() { # 51928c99a471c440 unset UFSID + local _dev="${1}" - ID_PARTS=`/sbin/dumpfs /dev/${1} | /usr/bin/head -n 2 | /usr/bin/tail -n 1 | /usr/bin/cut -f2 -d'[' | /usr/bin/cut -f1 -d ']'` + if [ -z "${_dev}" ]; then + return + fi + + ID_PARTS=$(/sbin/dumpfs /dev/${_dev} | \ + /usr/bin/head -n 2 | \ + /usr/bin/tail -n 1 | \ + /usr/bin/cut -f2 -d'[' | \ + /usr/bin/cut -f1 -d ']') # " 51110eb0 f288b35d " (note it has more spaces than we need/want) - ID_PART1=`echo ${ID_PARTS} | awk '{print $1;}'` + ID_PART1=$(echo ${ID_PARTS} | awk '{print $1}') # "51110eb0" - ID_PART2=`echo ${ID_PARTS} | awk '{print $2;}'` + ID_PART2=$(echo ${ID_PARTS} | awk '{print $2}') # "f288b35d" - if [ "${ID_PART1}" = "" ] || [ "${ID_PART2}" = "" ]; then + if [ -z "${ID_PART1}" -o -z "${ID_PART2}" ]; then echo "Invalid ufsid on ${1} (${ID_PARTS}), cannot continue" - exit. + exit -1 fi # Safety check to avoid http://www.freebsd.org/cgi/query-pr.cgi?pr=156908 - string_length ${ID_PART1} + string_length "${ID_PART1}" if [ ${LEN} -ne 8 ]; then - ID_PART1=`printf "%08s" "${ID_PART1}"` + ID_PART1=$(printf "%08s" "${ID_PART1}") fi - string_length ${ID_PART2} + string_length "${ID_PART2}" if [ ${LEN} -ne 8 ]; then - ID_PART2=`printf "%08s" "${ID_PART2}"` + ID_PART2=$(printf "%08s" "${ID_PART2}") fi - UFSID=${ID_PART1}${ID_PART2} + UFSID="${ID_PART1}${ID_PART2}" } -find_fs_device(){ +find_fs_device() { unset DEV - DEV=`/usr/bin/grep -e "[[:blank:]]*${1}[[:blank:]]" ${FSTAB} | awk '{print $1;}'` + DEV=$(/usr/bin/grep -e "[[:blank:]]*${1}[[:blank:]]" ${FSTAB} | awk '{print $1}') DEV=${DEV##/dev/} } FSTAB=/etc/fstab -NEED_CHANGES=false +unset NEED_CHANGES cp ${FSTAB} ${FSTAB}.tmp -ALL_FILESYSTEMS=`/bin/cat /etc/fstab | /usr/bin/awk '/ufs/ && !(/dev\/mirror\// || /dev\/ufsid\// || /dev\/label\// || /dev\/geom\//) {print $2;}'` +ALL_FILESYSTEMS=$(/usr/bin/awk '/ufs/ && !(/dev\/mirror\// || /dev\/ufsid\// || /dev\/label\// || /dev\/geom\//) {print $2}' /etc/fstab) for FS in ${ALL_FILESYSTEMS} do - find_fs_device ${FS} + find_fs_device "${FS}" if [ "${DEV}" != "" ]; then get_ufsid ${DEV} - string_length ${UFSID} + string_length "${UFSID}" if [ ${LEN} -ne 16 ]; then echo "Invalid UFS ID for FS ${FS} ($UFSID), skipping" else /usr/bin/sed -i '' -e "s/${DEV}/ufsid\/${UFSID}/g" ${FSTAB}.tmp - NEED_CHANGES=true + NEED_CHANGES=1 fi else echo "Unable to find device for ${FS}" - return -1 + exit -1 fi echo "FS: ${FS} on device ${DEV} with ufsid ${UFSID}" done -ALL_SWAPFS=`/bin/cat /etc/fstab | /usr/bin/awk '/swap/ && !(/dev\/mirror\// || /dev\/ufsid\// || /dev\/label\// || /dev\/geom\//) {print $1;}'` +ALL_SWAPFS=$(/usr/bin/awk '/swap/ && !(/dev\/mirror\// || /dev\/ufsid\// || /dev\/label\// || /dev\/geom\//) {print $1}' /etc/fstab) SWAPNUM=0 for SFS in ${ALL_SWAPFS} do @@ -87,15 +96,15 @@ do echo "FS: Swap slice ${SWAPNUM} on device ${SWAPDEV}" if [ "${SWAPDEV}" != "" ]; then /usr/bin/sed -i '' -e "s/${SWAPDEV}/label\/swap${SWAPNUM}/g" ${FSTAB}.tmp - NEED_CHANGES=true + NEED_CHANGES=1 fi - SWAPNUM=`expr ${SWAPNUM} + 1` + SWAPNUM=$((SWAPNUM+1)) fi done -if [ "${NEED_CHANGES}" = "false" ]; then +if [ -z "${NEED_CHANGES}" ]; then echo Nothing to do, all filesystems and swap already use some form of device-independent labels - exit + exit 0 fi echo "====================" @@ -113,21 +122,21 @@ else fi # Commit changes -if [ "${COMMIT}" = "y" ] || [ "${COMMIT}" = "Y" ]; then - echo "Disabling swap to apply label" - /sbin/swapoff /dev/${SWAPDEV} +if [ "${COMMIT}" = "y" -o "${COMMIT}" = "Y" ]; then - echo "Applying label to swap parition" + echo "Applying label to swap partition" SWAPNUM=0 for SFS in ${ALL_SWAPFS} do - find_fs_device ${SFS} + find_fs_device "${SFS}" if [ "${DEV}" != "" ]; then SWAPDEV=${DEV} - if [ "${SWAPDEV}" != "" ]; then + if [ -n "${SWAPDEV}" ]; then + echo "Disabling swap ${SWAPDEV} to apply label" + /sbin/swapoff /dev/${SWAPDEV} /sbin/glabel label swap${SWAPNUM} /dev/${SWAPDEV} fi - SWAPNUM=`expr ${SWAPNUM} + 1` + SWAPNUM=$((SWAPNUM+1)) fi done From 873cab1610c1fa8ef426476b03a22ec1ed806373 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Tue, 27 Jan 2015 11:50:21 -0200 Subject: [PATCH 011/257] Teach ufslabels.sh to deal with DESTDIR, useful on installation --- usr/local/sbin/ufslabels.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/usr/local/sbin/ufslabels.sh b/usr/local/sbin/ufslabels.sh index 3c0c68800f..bded665153 100755 --- a/usr/local/sbin/ufslabels.sh +++ b/usr/local/sbin/ufslabels.sh @@ -61,11 +61,11 @@ find_fs_device() { DEV=${DEV##/dev/} } -FSTAB=/etc/fstab +FSTAB=${DESTDIR}/etc/fstab unset NEED_CHANGES cp ${FSTAB} ${FSTAB}.tmp -ALL_FILESYSTEMS=$(/usr/bin/awk '/ufs/ && !(/dev\/mirror\// || /dev\/ufsid\// || /dev\/label\// || /dev\/geom\//) {print $2}' /etc/fstab) +ALL_FILESYSTEMS=$(/usr/bin/awk '/ufs/ && !(/dev\/mirror\// || /dev\/ufsid\// || /dev\/label\// || /dev\/geom\//) {print $2}' ${DESTDIR}/etc/fstab) for FS in ${ALL_FILESYSTEMS} do @@ -86,7 +86,7 @@ do echo "FS: ${FS} on device ${DEV} with ufsid ${UFSID}" done -ALL_SWAPFS=$(/usr/bin/awk '/swap/ && !(/dev\/mirror\// || /dev\/ufsid\// || /dev\/label\// || /dev\/geom\//) {print $1}' /etc/fstab) +ALL_SWAPFS=$(/usr/bin/awk '/swap/ && !(/dev\/mirror\// || /dev\/ufsid\// || /dev\/label\// || /dev\/geom\//) {print $1}' ${DESTDIR}/etc/fstab) SWAPNUM=0 for SFS in ${ALL_SWAPFS} do From 4f009171d55096b05a9c968383bdcab7dd12a92b Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Tue, 27 Jan 2015 11:57:11 -0200 Subject: [PATCH 012/257] Simplify use of other serial ports setting all of them as onifconsole when serial is enabled --- etc/inc/pfsense-utils.inc | 9 +++++---- etc/ttys | 8 ++++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/etc/inc/pfsense-utils.inc b/etc/inc/pfsense-utils.inc index 6fbb20c136..9bc94cd767 100644 --- a/etc/inc/pfsense-utils.inc +++ b/etc/inc/pfsense-utils.inc @@ -1019,7 +1019,7 @@ function setup_serial_port($when="save", $path="") { $ttys_split = explode("\n", $ttys); $fd = fopen($ttys_file, "w"); - $on_off = (is_serial_enabled() ? 'on' : 'off'); + $on_off = (is_serial_enabled() ? 'onifconsole' : 'off'); if (isset($config['system']['disableconsolemenu'])) { $console_type = 'Pc'; @@ -1031,9 +1031,10 @@ function setup_serial_port($when="save", $path="") { foreach($ttys_split as $tty) { if (stristr($tty, "ttyv0")) fwrite($fd, "ttyv0 \"/usr/libexec/getty {$console_type}\" cons25 on secure\n"); - else if (stristr($tty, "ttyu0")) - fwrite($fd, "ttyu0 \"/usr/libexec/getty {$serial_type}\" cons25 {$on_off} secure\n"); - else + else if (stristr($tty, "ttyu")) { + $ttyn = substr($tty, 0, 5); + fwrite($fd, "{$ttyn} \"/usr/libexec/getty {$serial_type}\" cons25 {$on_off} secure\n"); + } else fwrite($fd, $tty . "\n"); } unset($on_off, $console_type, $serial_type); diff --git a/etc/ttys b/etc/ttys index f04ca75c8d..382c6a777e 100644 --- a/etc/ttys +++ b/etc/ttys @@ -41,9 +41,9 @@ ttyv7 "/usr/libexec/getty Pc" xterm off secure ttyv8 "/usr/local/bin/xdm -nodaemon" xterm off secure # Serial terminals # The 'dialup' keyword identifies dialin lines to login, fingerd etc. -ttyu0 "/usr/libexec/getty al.115200" cons25 on secure -ttyu1 "/usr/libexec/getty std.9600" dialup off secure -ttyu2 "/usr/libexec/getty std.9600" dialup off secure -ttyu3 "/usr/libexec/getty std.9600" dialup off secure +ttyu0 "/usr/libexec/getty al.115200" cons25 onifconsole secure +ttyu1 "/usr/libexec/getty al.115200" cons25 onifconsole secure +ttyu2 "/usr/libexec/getty al.115200" cons25 onifconsole secure +ttyu3 "/usr/libexec/getty al.115200" cons25 onifconsole secure # Dumb console dcons "/usr/libexec/getty std.9600" vt100 off secure From 7efe99b592a4ee07d098990bbd3939ba0f7a10d0 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Wed, 28 Jan 2015 00:02:26 +0545 Subject: [PATCH 013/257] Traffic Shaper Wizard Upstream SIP Server Not being remembered and actioned. Bug #4314 --- usr/local/www/wizards/traffic_shaper_wizard_dedicated.xml | 3 ++- usr/local/www/wizards/traffic_shaper_wizard_multi_all.xml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/usr/local/www/wizards/traffic_shaper_wizard_dedicated.xml b/usr/local/www/wizards/traffic_shaper_wizard_dedicated.xml index 37751424d1..5eff89c6ac 100755 --- a/usr/local/www/wizards/traffic_shaper_wizard_dedicated.xml +++ b/usr/local/www/wizards/traffic_shaper_wizard_dedicated.xml @@ -121,7 +121,8 @@ - Upstream SIP Server + Upstream SIP Server + upstream_sip_server inputalias (Optional) If this is chosen, the provider field will be overridden. This allows you to provide the IP address of the <strong>remote</strong> PBX or SIP Trunk to prioritize. <br />NOTE: You can also use a Firewall Alias in this location. ezshaper->step3->address diff --git a/usr/local/www/wizards/traffic_shaper_wizard_multi_all.xml b/usr/local/www/wizards/traffic_shaper_wizard_multi_all.xml index 52e7f0dd3c..028cf4899b 100755 --- a/usr/local/www/wizards/traffic_shaper_wizard_multi_all.xml +++ b/usr/local/www/wizards/traffic_shaper_wizard_multi_all.xml @@ -129,7 +129,8 @@ - Upstream SIP Server + Upstream SIP Server + upstream_sip_server inputalias (Optional) If this is chosen, the provider field will be overridden. This allows you to provide the IP address of the <strong>remote</strong> PBX or SIP Trunk to prioritize. <br />NOTE: You can also use a Firewall Alias in this location. ezshaper->step3->address From 085136fe60d9a60d5a3e2f04e45ba2568b592b6f Mon Sep 17 00:00:00 2001 From: xbipin Date: Wed, 28 Jan 2015 12:46:51 +0400 Subject: [PATCH 014/257] multiple allow/deny entries for UPnP (rowhelper) This patch will allow the web GUI for UPnP to enter more user specified entries rather than just 4, I replaced the 4 boxes with one rowhelper control --- usr/local/pkg/miniupnpd.inc | 8 ++++---- usr/local/pkg/miniupnpd.xml | 34 +++++++++------------------------- 2 files changed, 13 insertions(+), 29 deletions(-) diff --git a/usr/local/pkg/miniupnpd.inc b/usr/local/pkg/miniupnpd.inc index 4cad0e5136..c48e767860 100644 --- a/usr/local/pkg/miniupnpd.inc +++ b/usr/local/pkg/miniupnpd.inc @@ -98,7 +98,7 @@ $input_errors[] = 'You must specify a valid traffic shaping queue.'; /* user permissions validation */ - for($i=1; $i<=4; $i++) { + for ($i=0; $i<500; $i++){ if($post["permuser{$i}"]) { $perm = explode(' ',$post["permuser{$i}"]); /* should explode to 4 args */ @@ -209,9 +209,9 @@ $config_text .= "model_number=".file_get_contents("/etc/version")."\n"; /* upnp access restrictions */ - for($i=1; $i<=4; $i++) { - if($upnp_config["permuser{$i}"]) - $config_text .= "{$upnp_config["permuser{$i}"]}\n"; + foreach($upnp_config['row'] as $row){ + if($row['permuser']) + $config_text .= "{$row["permuser"]}\n"; } if($upnp_config['permdefault']) diff --git a/usr/local/pkg/miniupnpd.xml b/usr/local/pkg/miniupnpd.xml index 9153e53cb5..be2c6e0179 100644 --- a/usr/local/pkg/miniupnpd.xml +++ b/usr/local/pkg/miniupnpd.xml @@ -116,34 +116,18 @@ checkbox - User specified permissions 1 - permuser1 + User specified permissions Format: [allow or deny] [ext port or range] [int ipaddr or ipaddr/CIDR] [int port or range] <br />Example: allow 1024-65535 192.168.0.0/24 1024-65535 - input - 60 + rowhelper + + + permuser + input + 60 + + - - User specified permissions 2 - permuser2 - Format: [allow or deny] [ext port or range] [int ipaddr or ipaddr/CIDR] [int port or range] - input - 60 - - - User specified permissions 3 - permuser3 - Format: [allow or deny] [ext port or range] [int ipaddr or ipaddr/CIDR] [int port or range] - input - 60 - - - User specified permissions 4 - permuser4 - Format: [allow or deny] [ext port or range] [int ipaddr or ipaddr/CIDR] [int port or range] - input - 60 - before_form_miniupnpd($pkg); From 04a893de744d23f3c4e28ee3f1d1a1ca34c2cfc7 Mon Sep 17 00:00:00 2001 From: xbipin Date: Wed, 28 Jan 2015 13:26:54 +0400 Subject: [PATCH 015/257] multiple allow/deny entries for UPnP (rowhelper) with this additional change we can allow infinite number of entries rather than just 500 due to the for loop set to a max of 500 because the rowhelper control doesnt post as an array but just adds a number at the end of the variable and we try and modify the pkg_edit.php file then it would affect other packages --- usr/local/pkg/miniupnpd.inc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/usr/local/pkg/miniupnpd.inc b/usr/local/pkg/miniupnpd.inc index c48e767860..34fab47841 100644 --- a/usr/local/pkg/miniupnpd.inc +++ b/usr/local/pkg/miniupnpd.inc @@ -98,7 +98,8 @@ $input_errors[] = 'You must specify a valid traffic shaping queue.'; /* user permissions validation */ - for ($i=0; $i<500; $i++){ + $j = substr_count(implode(array_keys($post)), "permuser"); + for ($i=0; $i<$j; $i++){ if($post["permuser{$i}"]) { $perm = explode(' ',$post["permuser{$i}"]); /* should explode to 4 args */ From 7094c303b7d46c9f7b24c3f1bd4432187832e85c Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 28 Jan 2015 11:38:25 -0200 Subject: [PATCH 016/257] Fix #4318 - gen_subnetv4_max() not working on 32bit --- etc/inc/util.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/util.inc b/etc/inc/util.inc index ded1d80d53..0e8ffe4e77 100644 --- a/etc/inc/util.inc +++ b/etc/inc/util.inc @@ -349,7 +349,7 @@ function gen_subnetv4_max($ipaddr, $bits) { if (is_ipaddrv4($ipaddr) && is_numericint($bits) && $bits <= 32) { if ($bits == 32) return $ipaddr; - return long2ip(ip2long($ipaddr) | (0xFFFFFFFF >> $bits)); + return long2ip32(ip2long($ipaddr) | ~gen_subnet_mask_long($bits)); } return ""; } From 1959e3d1d08747799229bacea10fbb906367c84f Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 28 Jan 2015 13:42:55 -0200 Subject: [PATCH 017/257] Reload filter when IPsec is disabled, fixes #4245 --- etc/inc/vpn.inc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index fa857bb130..9b7a6f8789 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -122,6 +122,8 @@ function vpn_ipsec_configure($ipchg = false) mwexec("/sbin/ifconfig enc0 down"); set_single_sysctl("net.inet.ip.ipsec_in_use", "0"); + filter_configure(); + return 0; } From 340e8bc5cf67a2e826df28d1ac3a1eb70ed2c5c5 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 28 Jan 2015 16:45:58 -0200 Subject: [PATCH 018/257] Accept port range on Outbound NAT. Fixes #4300 --- usr/local/www/firewall_nat_out_edit.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/firewall_nat_out_edit.php b/usr/local/www/firewall_nat_out_edit.php index eedcfb9af6..0c618deade 100644 --- a/usr/local/www/firewall_nat_out_edit.php +++ b/usr/local/www/firewall_nat_out_edit.php @@ -162,10 +162,10 @@ if ($_POST) { if ($_POST['natport']) $_POST['natport'] = trim($_POST['natport']); - if($protocol_uses_ports && $_POST['sourceport'] <> "" && !is_portoralias($_POST['sourceport'])) + if($protocol_uses_ports && $_POST['sourceport'] <> "" && !(is_portoralias($_POST['sourceport']) || is_portrange($_POST['sourceport']))) $input_errors[] = gettext("You must supply either a valid port or port alias for the source port entry."); - if($protocol_uses_ports && $_POST['dstport'] <> "" && !is_portoralias($_POST['dstport'])) + if($protocol_uses_ports && $_POST['dstport'] <> "" && !(is_portoralias($_POST['dstport']) || is_portrange($_POST['dstport']))) $input_errors[] = gettext("You must supply either a valid port or port alias for the destination port entry."); if($protocol_uses_ports && $_POST['natport'] <> "" && !is_port($_POST['natport']) && !isset($_POST['nonat'])) From b50baf79f18b21454dad25819d3a6656caf2abcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Wed, 28 Jan 2015 21:26:09 +0100 Subject: [PATCH 019/257] Fixes #4275 use double quotes on asn1dn specification so strongswan properly interprets it --- etc/inc/ipsec.inc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/etc/inc/ipsec.inc b/etc/inc/ipsec.inc index 5b7c7e41af..571e30c267 100644 --- a/etc/inc/ipsec.inc +++ b/etc/inc/ipsec.inc @@ -656,7 +656,8 @@ function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array()) { break; case 'asn1dn': $thisid_data = $id_data; - $thisid_data = "{$id_data}"; + if ($thisid_data && $thisid_data[0] != '"') + $thisid_data = "\"{$id_data}\""; break; } return array($thisid_type, $thisid_data); From 1abdf80b2d4abaf7fb0238ae21d554603149619e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Wed, 28 Jan 2015 22:53:54 +0100 Subject: [PATCH 020/257] Apparently yacc became more strict in FreeBSD 10. Fixes #4302 --- etc/inc/filter.inc | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index 6b044d6274..d874e130fb 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -2506,14 +2506,15 @@ function filter_generate_user_rule($rule) { $aline['tagged'] = " tagged " .$rule['tagged'] . " "; if (!empty($rule['dscp'])) { switch (strtolower($rule['dscp'])) { - case 'va': $aline['dscp'] = " dscp 44 "; break; - case 'cs1': $aline['dscp'] = " dscp 8 "; break; - case 'cs2': $aline['dscp'] = " dscp 16 "; break; - case 'cs3': $aline['dscp'] = " dscp 24 "; break; - case 'cs4': $aline['dscp'] = " dscp 32 "; break; - case 'cs5': $aline['dscp'] = " dscp 40 "; break; - case 'cs6': $aline['dscp'] = " dscp 48 "; break; - case 'cs7': $aline['dscp'] = " dscp 56 "; break; + case 'va': $aline['dscp'] = " dscp \"44\" "; break; + case 'VA': $aline['dscp'] = " dscp \"44\" "; break; + case 'cs1': $aline['dscp'] = " dscp \"8\" "; break; + case 'cs2': $aline['dscp'] = " dscp \"16\" "; break; + case 'cs3': $aline['dscp'] = " dscp \"24\" "; break; + case 'cs4': $aline['dscp'] = " dscp \"32\" "; break; + case 'cs5': $aline['dscp'] = " dscp \"40\" "; break; + case 'cs6': $aline['dscp'] = " dscp \"48\" "; break; + case 'cs7': $aline['dscp'] = " dscp \"56\" "; break; default: $aline['dscp'] = " dscp " . $rule['dscp'] . " "; break; } } From 6a2f0ad75063b9a0068b0a1983fb61fe3b408920 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Wed, 28 Jan 2015 23:01:34 +0100 Subject: [PATCH 021/257] Fixes #4274 same fix as #4302 enclose in double quotes to tell yacc this is a string to be parsed. --- etc/inc/filter.inc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index d874e130fb..53c4984637 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -2500,8 +2500,12 @@ function filter_generate_user_rule($rule) { $aline['icmp-type'] = "icmp-type {$rule['icmptype']} "; if (($rule['protocol'] == "icmp") && $rule['icmptype'] && ($rule['ipprotocol'] == "inet6")) $aline['icmp6-type'] = "icmp6-type {$rule['icmptype']} "; - if (!empty($rule['tag'])) - $aline['tag'] = " tag " .$rule['tag']. " "; + if (!empty($rule['tag'])) { + if (ctype_digit($rule['tag'])) + $aline['tag'] = " tag \"" .$rule['tag']. "\" "; + else + $aline['tag'] = " tag " .$rule['tag']. " "; + } if (!empty($rule['tagged'])) $aline['tagged'] = " tagged " .$rule['tagged'] . " "; if (!empty($rule['dscp'])) { From 427831ac67b80b7900f7327253dfd96c50132a4e Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 29 Jan 2015 03:05:28 -0600 Subject: [PATCH 022/257] fix input validation, = is OK here --- usr/local/www/system_advanced_misc.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/system_advanced_misc.php b/usr/local/www/system_advanced_misc.php index 0255d776a6..e7403a2538 100644 --- a/usr/local/www/system_advanced_misc.php +++ b/usr/local/www/system_advanced_misc.php @@ -102,10 +102,10 @@ if ($_POST) { if (!empty($_POST['thermal_hardware']) && !array_key_exists($_POST['thermal_hardware'], $thermal_hardware_modules)) $input_errors[] = gettext("Please select a valid Thermal Hardware Sensor."); - if (!empty($_POST['use_mfs_tmp_size']) && (!is_numeric($_POST['use_mfs_tmp_size']) || ($_POST['use_mfs_tmp_size'] <= 40))) + if (!empty($_POST['use_mfs_tmp_size']) && (!is_numeric($_POST['use_mfs_tmp_size']) || ($_POST['use_mfs_tmp_size'] < 40))) $input_errors[] = gettext("/tmp Size must be numeric and should not be less than 40MB."); - if (!empty($_POST['use_mfs_var_size']) && (!is_numeric($_POST['use_mfs_var_size']) || ($_POST['use_mfs_var_size'] <= 60))) + if (!empty($_POST['use_mfs_var_size']) && (!is_numeric($_POST['use_mfs_var_size']) || ($_POST['use_mfs_var_size'] < 60))) $input_errors[] = gettext("/var Size must be numeric and should not be less than 60MB."); if (!$input_errors) { From a95867a2ffb6c94b2dd0508ef4db35ad752aca29 Mon Sep 17 00:00:00 2001 From: xbipin Date: Thu, 29 Jan 2015 14:14:31 +0400 Subject: [PATCH 023/257] multiple allow/deny entries for UPnP (rowhelper) remove old permission box fields --- usr/local/pkg/miniupnpd.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/pkg/miniupnpd.xml b/usr/local/pkg/miniupnpd.xml index be2c6e0179..f5cf9ffff6 100644 --- a/usr/local/pkg/miniupnpd.xml +++ b/usr/local/pkg/miniupnpd.xml @@ -35,13 +35,13 @@ UPnP & NAT-PMP Settings listtopic - enable_upnp,enable_natpmp,iface_array,overridewanip,upnpqueue,logpackets,sysuptime,permdefault,permuser1,permuser2,permuser3,permuser4 + enable_upnp,enable_natpmp,ext_iface,iface_array,download,upload,overridewanip,upnpqueue,logpackets,sysuptime,permdefault Enable UPnP & NAT-PMP enable checkbox - enable_upnp,enable_natpmp,iface_array,overridewanip,upnpqueue,logpackets,sysuptime,permdefault,permuser1,permuser2,permuser3,permuser4 + enable_upnp,enable_natpmp,ext_iface,iface_array,download,upload,overridewanip,upnpqueue,logpackets,sysuptime,permdefault Allow UPnP Port Mapping From f5b23288160aebd53e5d983ab872b468c09934ed Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Thu, 29 Jan 2015 12:02:42 -0200 Subject: [PATCH 024/257] Set update_url and update_manifest automatically based on version being or not a RELEASE --- etc/inc/globals.inc | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/etc/inc/globals.inc b/etc/inc/globals.inc index f3233f97e7..150f160cc2 100644 --- a/etc/inc/globals.inc +++ b/etc/inc/globals.inc @@ -98,12 +98,19 @@ $tcpflags = array("syn", "ack", "fin", "rst", "psh", "urg", "ece", "cwr"); if(file_exists("/etc/platform")) { $arch = php_uname("m"); - /* Do not remove this, it is not needed for the snapshots URL but is needed later for the -RELEASE/stable URLs */ - //$arch = ($arch == "i386") ? "" : '/' . $arch; + $current_version = trim(file_get_contents("{$g['etc_path']}/version")); - /* Full installs and NanoBSD use the same update directory and manifest in 2.x */ - $g['update_url']="https://snapshots.pfsense.org/FreeBSD_releng/10.1/{$arch}/pfSense_HEAD/.updaters/"; - $g['update_manifest']="https://updates.pfSense.org/manifest"; + if (strstr($current_version, "-RELEASE")) { + /* This is only necessary for RELEASE */ + $arch = ($arch == "i386") ? "" : '/' . $arch; + /* Full installs and NanoBSD use the same update directory and manifest in 2.x */ + $g['update_url']="https://updates.pfsense.org/_updaters{$arch}"; + $g['update_manifest']="https://updates.pfsense.org/manifest"; + } else { + /* Full installs and NanoBSD use the same update directory and manifest in 2.x */ + $g['update_url']="https://snapshots.pfsense.org/FreeBSD_releng/10.1/{$arch}/pfSense_HEAD/.updaters/"; + $g['update_manifest']="https://updates.pfSense.org/manifest"; + } $g['platform'] = trim(file_get_contents("/etc/platform")); if($g['platform'] == "nanobsd") { From 091195f09e627f575bb195006d255ad4e85dfef7 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 29 Jan 2015 22:55:27 +0545 Subject: [PATCH 025/257] Firewall Log does not display logged IGMP packets If IGMP packets are logged (either pass or block) then parse_filter_line did not set their src and dst IP. Later in the subroutine, it zapped the filter line because it did not have a src and dst. This fixes it. Now the IGMP lines in /var/log/filter.log appear on the Firewall Log GUI. --- etc/inc/filter_log.inc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/etc/inc/filter_log.inc b/etc/inc/filter_log.inc index 073d44f286..46c9b130fb 100644 --- a/etc/inc/filter_log.inc +++ b/etc/inc/filter_log.inc @@ -238,6 +238,9 @@ function parse_filter_line($line) { break; } + } else if ($flent['protoid'] == '2') { // IGMP + $flent['src'] = $flent['srcip']; + $flent['dst'] = $flent['dstip']; } else if ($flent['protoid'] == '112') { // CARP $flent['type'] = $rule_data[$field++]; $flent['ttl'] = $rule_data[$field++]; From 5d60171d7217e9c69768b31fc14ed3d9869e6aea Mon Sep 17 00:00:00 2001 From: xbipin Date: Fri, 30 Jan 2015 10:36:19 +0400 Subject: [PATCH 026/257] unnecessary but lets just add this for safety unnecessary but lets just add this for safety --- usr/local/pkg/miniupnpd.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/usr/local/pkg/miniupnpd.xml b/usr/local/pkg/miniupnpd.xml index f5cf9ffff6..c26587be88 100644 --- a/usr/local/pkg/miniupnpd.xml +++ b/usr/local/pkg/miniupnpd.xml @@ -117,6 +117,7 @@ User specified permissions + none Format: [allow or deny] [ext port or range] [int ipaddr or ipaddr/CIDR] [int port or range] <br />Example: allow 1024-65535 192.168.0.0/24 1024-65535 rowhelper From 07b379525d8182e73f7fd46f39dcfca9b8e183e0 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Fri, 30 Jan 2015 22:45:27 +0545 Subject: [PATCH 027/257] Unbound domain override IP:port validation The domain override is IP:port is invalid if either the IP address OR port is invalid. Previously you could put an invalid IP with valid port, or valid IP with invalid port. --- usr/local/www/services_unbound_domainoverride_edit.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/services_unbound_domainoverride_edit.php b/usr/local/www/services_unbound_domainoverride_edit.php index b8c37a5fc1..821823b80f 100644 --- a/usr/local/www/services_unbound_domainoverride_edit.php +++ b/usr/local/www/services_unbound_domainoverride_edit.php @@ -86,7 +86,7 @@ if ($_POST) { if ($_POST['ip']) { if (strpos($_POST['ip'],'@') !== false) { $ip_details = explode("@", $_POST['ip']); - if (!is_ipaddr($ip_details[0]) && !is_port($ip_details[1])) + if (!is_ipaddr($ip_details[0]) || !is_port($ip_details[1])) $input_errors[] = gettext("A valid IP address and port must be specified, for example 192.168.100.10@5353."); } else if (!is_ipaddr($_POST['ip'])) $input_errors[] = gettext("A valid IP address must be specified, for example 192.168.100.10."); From fa77655557586453a0279566a84d01cd25645978 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Fri, 30 Jan 2015 20:59:16 +0100 Subject: [PATCH 028/257] Do not reuse reqid on copy of phase2 Fixes #4349 --- usr/local/www/vpn_ipsec_phase2.php | 1 + 1 file changed, 1 insertion(+) diff --git a/usr/local/www/vpn_ipsec_phase2.php b/usr/local/www/vpn_ipsec_phase2.php index 160b264aae..e6ce3f05e3 100644 --- a/usr/local/www/vpn_ipsec_phase2.php +++ b/usr/local/www/vpn_ipsec_phase2.php @@ -122,6 +122,7 @@ if (!empty($_GET['dup'])) { unset($uindex); unset($p2index); $pconfig['uniqid'] = uniqid(); + $pconfig['reqid'] = ipsec_new_reqid(); } if ($_POST) { From c67b75d19a9037fbec3f9768dc21291a77d4b3a0 Mon Sep 17 00:00:00 2001 From: xbipin Date: Sat, 31 Jan 2015 10:35:11 +0400 Subject: [PATCH 029/257] add schedule selection to pkg_edit.php this allows schedule selection to pkg_edit.php, this can then be utilized by packages to set schedules in many other places. This is the first set of changes, will further modify other files to make full use of schedules. --- usr/local/www/pkg_edit.php | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/usr/local/www/pkg_edit.php b/usr/local/www/pkg_edit.php index fbcd6b8152..b6011370e9 100644 --- a/usr/local/www/pkg_edit.php +++ b/usr/local/www/pkg_edit.php @@ -808,6 +808,33 @@ if ($pkg['tabs'] <> "") { echo $input ."\n
" . fixup_string($pkga['description']) . "\n"; break; + case "schedule_selection": + $input = "\n
\n" . fixup_string($pkga['description']) . "\n"; + if(isset($pkga['advancedfield']) && isset($adv_filed_count)) { + $js_array[] = $pkga['fieldname']; + $advanced .= display_advanced_field($pkga['fieldname']).$input; + $advanced .= "\n"; + } + else + echo $input; + break; + case "rowhelper": #$rowhelpername=($fields['fieldname'] ? $fields['fieldname'] : "row"); $rowhelpername="row"; From f55ef2e70ee262c9e5934b9177cd78848e7e4a85 Mon Sep 17 00:00:00 2001 From: xbipin Date: Sat, 31 Jan 2015 10:38:58 +0400 Subject: [PATCH 030/257] Update pkg_edit.php --- usr/local/www/pkg_edit.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/pkg_edit.php b/usr/local/www/pkg_edit.php index b6011370e9..5e717d59e9 100644 --- a/usr/local/www/pkg_edit.php +++ b/usr/local/www/pkg_edit.php @@ -811,7 +811,7 @@ if ($pkg['tabs'] <> "") { case "schedule_selection": $input = "
+ + \n"; + foreach ($ipsec_idhandling as $value => $lvalue) { + echo "\n"; + } + ?> + +
+ no and never is that the old IKE_SAs will be replaced when receiving an " . + "INITIAL_CONTACT notify if the option is no but will ignore these notifies if never is configured. " . + "The daemon also accepts the value keep to reject " . + "new IKE_SA setups and keep the duplicate established earlier."); ?> +
From 87808568a70404e04c306723cdd65f52e59003f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Sat, 31 Jan 2015 19:49:17 +0100 Subject: [PATCH 036/257] Fixes #4360 allow marking a connection as responder only, the same behviour as mobile connections --- etc/inc/vpn.inc | 3 +++ usr/local/www/vpn_ipsec_phase1.php | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 7db3a0a754..6fe684c6b6 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -597,6 +597,9 @@ EOD; $right_spec = "%any"; $passive = 'add'; } else { + if (isset($ph1ent['responderonly'])) + $passive = 'add'; + $right_spec = $ph1ent['remote-gateway']; if (is_ipaddr($right_spec)) $sourcehost = $right_spec; diff --git a/usr/local/www/vpn_ipsec_phase1.php b/usr/local/www/vpn_ipsec_phase1.php index 6e850463ae..07f8c8bca5 100644 --- a/usr/local/www/vpn_ipsec_phase1.php +++ b/usr/local/www/vpn_ipsec_phase1.php @@ -113,6 +113,8 @@ if (isset($p1index) && $a_phase1[$p1index]) { $pconfig['reauth_enable'] = true; if (isset($a_phase1[$p1index]['rekey_enable'])) $pconfig['rekey_enable'] = true; + if (isset($a_phase1[$p1index]['responderonly'])) + $pconfig['responderonly'] = true; if ($a_phase1[$p1index]['dpd_delay'] && $a_phase1[$p1index]['dpd_maxfail']) { $pconfig['dpd_enable'] = true; @@ -383,6 +385,11 @@ if ($_POST) { else unset($ph1ent['rekey_enable']); + if (isset($pconfig['responderonly'])) + $ph1ent['responderonly'] = true; + else + unset($ph1ent['responderonly']); + if (isset($pconfig['dpd_enable'])) { $ph1ent['dpd_delay'] = $pconfig['dpd_delay']; $ph1ent['dpd_maxfail'] = $pconfig['dpd_maxfail']; @@ -887,6 +894,13 @@ function dpdchkbox_change() {
+ /> +
+
From 69aeef21955e7f2d9b6b1ad897d3655bb43506fe Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Sat, 31 Jan 2015 16:30:19 -0600 Subject: [PATCH 037/257] Add input validation to prevent the use of AES > 128 where glxsb is enabled. Ticket #4361 --- usr/local/www/vpn_ipsec_phase1.php | 7 +++++++ usr/local/www/vpn_ipsec_phase2.php | 12 +++++++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/usr/local/www/vpn_ipsec_phase1.php b/usr/local/www/vpn_ipsec_phase1.php index 07f8c8bca5..87380381a6 100644 --- a/usr/local/www/vpn_ipsec_phase1.php +++ b/usr/local/www/vpn_ipsec_phase1.php @@ -328,6 +328,13 @@ if ($_POST) { if (!empty($pconfig['iketype']) && $pconfig['iketype'] != "ikev1" && $pconfig['iketype'] != "ikev2" && $pconfig['iketype'] != "auto") $input_errors[] = gettext("Valid arguments for IKE type is v1 or v2 or auto"); + + if (!empty($_POST['ealgo']) && isset($config['system']['crypto_hardware'])) { + if ($config['system']['crypto_hardware'] == "glxsb") { + if ($_POST['ealgo'] == "aes" && $_POST['ealgo_keylen'] != "128") + $input_errors[] = gettext("Only 128 bit AES can be used where the glxsb crypto accelerator is enabled."); + } + } /* build our encryption algorithms array */ $pconfig['ealgo'] = array(); diff --git a/usr/local/www/vpn_ipsec_phase2.php b/usr/local/www/vpn_ipsec_phase2.php index e6ce3f05e3..e42cc0b764 100644 --- a/usr/local/www/vpn_ipsec_phase2.php +++ b/usr/local/www/vpn_ipsec_phase2.php @@ -142,7 +142,7 @@ if ($_POST) { } do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); - + if(($pconfig['mode'] == "tunnel") || ($pconfig['mode'] == "tunnel6")) { switch ($pconfig['localid_type']) { @@ -300,8 +300,14 @@ if ($_POST) { if (!count($ealgos)) { $input_errors[] = gettext("At least one encryption algorithm must be selected."); } else { - if (empty($pconfig['halgos'])) { - foreach ($ealgos as $ealgo) { + foreach ($ealgos as $ealgo) { + if (isset($config['system']['crypto_hardware'])) { + if ($config['system']['crypto_hardware'] == "glxsb") { + if ($ealgo['name'] == "aes" && $ealgo['keylen'] != "128") + $input_errors[] = gettext("Only 128 bit AES can be used where the glxsb crypto accelerator is enabled."); + } + } + if (empty($pconfig['halgos'])) { if (!strpos($ealgo['name'], "gcm")) { $input_errors[] = gettext("At least one hashing algorithm needs to be selected."); break; From b051f1487aa2041c8f23342a895da46d9a7b46c2 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Sun, 1 Feb 2015 01:33:27 -0600 Subject: [PATCH 038/257] need $g here so product_name is set in user agent --- etc/inc/pfsense-utils.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/pfsense-utils.inc b/etc/inc/pfsense-utils.inc index 9bc94cd767..36640aaa73 100644 --- a/etc/inc/pfsense-utils.inc +++ b/etc/inc/pfsense-utils.inc @@ -1680,7 +1680,7 @@ function download_file($url, $destination, $verify_ssl = false, $connect_timeout } function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) { - global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update; + global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update, $g; $file_size = 1; $downloaded = 1; $first_progress_update = TRUE; From 8820a3aa8f2cb4881e13f032efae0d8e8bc369d9 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Mon, 2 Feb 2015 08:25:36 +0545 Subject: [PATCH 039/257] Remove latin-1 encoding of RSS feed Many thanks to Gertjan in forum https://forum.pfsense.org/index.php?topic=87504.msg484017#msg484017 Specifically setting the output encoding to latin-1 was causing the "black diamonds" for special characters in the http://blog.pfsense.org RSS feed (e.g. the registered trademark sign after pfSense did not come out). It should all work by letting simplepie do its default stuff with the RSS feed. --- usr/local/www/widgets/widgets/rss.widget.php | 1 - 1 file changed, 1 deletion(-) diff --git a/usr/local/www/widgets/widgets/rss.widget.php b/usr/local/www/widgets/widgets/rss.widget.php index c6920f916a..4c21a29535 100644 --- a/usr/local/www/widgets/widgets/rss.widget.php +++ b/usr/local/www/widgets/widgets/rss.widget.php @@ -157,7 +157,6 @@ else $feed->set_cache_location("/tmp/simplepie/"); $feed->set_feed_url($rss_feed_s); $feed->init(); - $feed->set_output_encoding('latin-1'); $feed->handle_content_type(); $counter = 1; foreach($feed->get_items() as $item) { From 1c4540dcac5527cca71f7e8ffd85914c3ccea23f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Mon, 2 Feb 2015 10:01:13 +0100 Subject: [PATCH 040/257] Ticket #4353 fix typo on unset var spotted-by: Phil Davis --- etc/inc/vpn.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 6fe684c6b6..d25ae07f4b 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -314,7 +314,7 @@ function vpn_ipsec_configure($restart = false) else $ifacesuse = ''; - unset($strongconf); + unset($stronconf); $strongswan = << Date: Mon, 2 Feb 2015 15:28:06 +0400 Subject: [PATCH 041/257] fix indent fix indent --- usr/local/www/pkg_edit.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/usr/local/www/pkg_edit.php b/usr/local/www/pkg_edit.php index 5e717d59e9..28ba66455e 100644 --- a/usr/local/www/pkg_edit.php +++ b/usr/local/www/pkg_edit.php @@ -816,22 +816,21 @@ if ($pkg['tabs'] <> "") { foreach ($config['schedules']['schedule'] as $schedule) { if ($schedule['name'] <> "") $schedules[] = $schedule['name']; - } } + } foreach($schedules as $schedule) { $selected = ($value == $schedule ? "selected=\"selected\"" : ""); if($schedule == "none") $input .= "\n"; else $input .= "\n"; - } + } $input .= "\n
\n" . fixup_string($pkga['description']) . "\n"; if(isset($pkga['advancedfield']) && isset($adv_filed_count)) { $js_array[] = $pkga['fieldname']; $advanced .= display_advanced_field($pkga['fieldname']).$input; $advanced .= "\n"; - } - else + } else echo $input; break; From f2b769d01df5461fb392f3fe27e3076de0dfb01c Mon Sep 17 00:00:00 2001 From: Tuyan Ozipek Date: Sun, 1 Feb 2015 20:04:37 -0500 Subject: [PATCH 042/257] Fixed not being able to save custom and custom-v6 dyndns entries due to "host" being posted empty, and thus failing is_domain() check. --- usr/local/www/services_dyndns_edit.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/services_dyndns_edit.php b/usr/local/www/services_dyndns_edit.php index c88e22df62..80ad352562 100644 --- a/usr/local/www/services_dyndns_edit.php +++ b/usr/local/www/services_dyndns_edit.php @@ -111,7 +111,7 @@ if ($_POST) { do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); - if (isset($_POST['host'])) { + if (isset($_POST['host']) && in_array("host", $reqdfields)) { /* Namecheap can have a @. in hostname */ if ($pconfig['type'] == "namecheap" && substr($_POST['host'], 0, 2) == '@.') $host_to_check = substr($_POST['host'], 2); From 5e964cfdd37513380327ad653db0310a0f8569ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Mon, 2 Feb 2015 17:46:01 +0100 Subject: [PATCH 043/257] Properly calculate the 6rd default gateway honoring netmasks other than /32 --- etc/inc/interfaces.inc | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index 76d29215be..c6184bb6ea 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -3296,7 +3296,11 @@ function interface_6rd_configure($interface = "wan", $wancfg) { $rd6prefix = explode("/", $wancfg['prefix-6rd']); $rd6prefixlen = $rd6prefix[1]; $brgw = explode('.', $wancfg['gateway-6rd']); - $rd6brgw = rtrim($rd6prefix[0], ':') . ':' . dechex($brgw[0]) . dechex($brgw[1]) . ':' . dechex($brgw[2]) . dechex($brgw[3]) . '::'; + $rd6brgw = substr(Net_IPv6::_ip2Bin($rd6prefix[0]), 0, $rd6prefixlen); + $rd6brgw .= str_pad(decbin($brgw[0]), 8, '0', STR_PAD_LEFT) . str_pad(decbin($brgw[1]), 8, '0', STR_PAD_LEFT) . str_pad(decbin($brgw[2]), 8, '0', STR_PAD_LEFT) . str_pad(decbin($brgw[3]), 8, '0', STR_PAD_LEFT); + if (strlen($rd6brgw) < 128) + $rd6brgw = str_pad($rd6brgw, 128, '0', STR_PAD_RIGHT); + $rd6brgw = Net_IPv6::compress(Net_IPv6::_bin2Ip($rd6brgw)); unset($brgw); $rd6prefix = Net_IPv6::uncompress($rd6prefix[0]); From 6672609b90a8e60a13ca471a3ad3e054eca542bd Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Mon, 2 Feb 2015 15:28:23 -0200 Subject: [PATCH 044/257] Fix aliases popup width when fields are hidden when page is loaded. It should fix #4238 --- usr/local/www/firewall_aliases_edit.php | 2 +- usr/local/www/firewall_nat_1to1_edit.php | 2 +- usr/local/www/firewall_nat_npt_edit.php | 2 +- usr/local/www/firewall_nat_out_edit.php | 2 +- usr/local/www/head.inc | 2 +- usr/local/www/javascript/autosuggest.js | 1 + usr/local/www/javascript/firewall_nat_edit/autosuggest.js | 1 + usr/local/www/javascript/firewall_rules_edit/autosuggest.js | 1 + usr/local/www/javascript/firewall_shaper_edit/autosuggest.js | 1 + usr/local/www/javascript/wizard/autosuggest.js | 1 + usr/local/www/load_balancer_pool_edit.php | 2 +- usr/local/www/load_balancer_virtual_server_edit.php | 2 +- usr/local/www/pkg_edit.php | 2 +- usr/local/www/services_router_advertisements.php | 2 +- usr/local/www/system_routes_edit.php | 2 +- 15 files changed, 15 insertions(+), 10 deletions(-) diff --git a/usr/local/www/firewall_aliases_edit.php b/usr/local/www/firewall_aliases_edit.php index c55658c2c5..1ae4e77add 100755 --- a/usr/local/www/firewall_aliases_edit.php +++ b/usr/local/www/firewall_aliases_edit.php @@ -672,7 +672,7 @@ EOD; - + diff --git a/usr/local/www/firewall_nat_1to1_edit.php b/usr/local/www/firewall_nat_1to1_edit.php index 2b1a829ff6..6700cd341d 100644 --- a/usr/local/www/firewall_nat_1to1_edit.php +++ b/usr/local/www/firewall_nat_1to1_edit.php @@ -231,7 +231,7 @@ include("head.inc"); - + - + diff --git a/usr/local/www/firewall_nat_out_edit.php b/usr/local/www/firewall_nat_out_edit.php index 0c618deade..21626953ac 100644 --- a/usr/local/www/firewall_nat_out_edit.php +++ b/usr/local/www/firewall_nat_out_edit.php @@ -347,7 +347,7 @@ include("head.inc"); ?> - + \n"; + echo "\t\n"; } closedir($dh); } diff --git a/usr/local/www/javascript/autosuggest.js b/usr/local/www/javascript/autosuggest.js index 6f0c10711d..d9b5ac088d 100644 --- a/usr/local/www/javascript/autosuggest.js +++ b/usr/local/www/javascript/autosuggest.js @@ -314,6 +314,7 @@ AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/ this.layer.style.left = this.getLeft() + "px"; this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px"; + this.layer.style.width = this.textbox.offsetWidth + "px"; this.layer.style.visibility = "visible"; }; diff --git a/usr/local/www/javascript/firewall_nat_edit/autosuggest.js b/usr/local/www/javascript/firewall_nat_edit/autosuggest.js index 6f0c10711d..d9b5ac088d 100644 --- a/usr/local/www/javascript/firewall_nat_edit/autosuggest.js +++ b/usr/local/www/javascript/firewall_nat_edit/autosuggest.js @@ -314,6 +314,7 @@ AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/ this.layer.style.left = this.getLeft() + "px"; this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px"; + this.layer.style.width = this.textbox.offsetWidth + "px"; this.layer.style.visibility = "visible"; }; diff --git a/usr/local/www/javascript/firewall_rules_edit/autosuggest.js b/usr/local/www/javascript/firewall_rules_edit/autosuggest.js index 6f0c10711d..d9b5ac088d 100644 --- a/usr/local/www/javascript/firewall_rules_edit/autosuggest.js +++ b/usr/local/www/javascript/firewall_rules_edit/autosuggest.js @@ -314,6 +314,7 @@ AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/ this.layer.style.left = this.getLeft() + "px"; this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px"; + this.layer.style.width = this.textbox.offsetWidth + "px"; this.layer.style.visibility = "visible"; }; diff --git a/usr/local/www/javascript/firewall_shaper_edit/autosuggest.js b/usr/local/www/javascript/firewall_shaper_edit/autosuggest.js index 6f0c10711d..d9b5ac088d 100644 --- a/usr/local/www/javascript/firewall_shaper_edit/autosuggest.js +++ b/usr/local/www/javascript/firewall_shaper_edit/autosuggest.js @@ -314,6 +314,7 @@ AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/ this.layer.style.left = this.getLeft() + "px"; this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px"; + this.layer.style.width = this.textbox.offsetWidth + "px"; this.layer.style.visibility = "visible"; }; diff --git a/usr/local/www/javascript/wizard/autosuggest.js b/usr/local/www/javascript/wizard/autosuggest.js index 6f0c10711d..d9b5ac088d 100644 --- a/usr/local/www/javascript/wizard/autosuggest.js +++ b/usr/local/www/javascript/wizard/autosuggest.js @@ -314,6 +314,7 @@ AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/ this.layer.style.left = this.getLeft() + "px"; this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px"; + this.layer.style.width = this.textbox.offsetWidth + "px"; this.layer.style.visibility = "visible"; }; diff --git a/usr/local/www/load_balancer_pool_edit.php b/usr/local/www/load_balancer_pool_edit.php index 8993dee1a5..f3b0dcac1b 100644 --- a/usr/local/www/load_balancer_pool_edit.php +++ b/usr/local/www/load_balancer_pool_edit.php @@ -187,7 +187,7 @@ function clearcombo(){ //]]> - + diff --git a/usr/local/www/load_balancer_virtual_server_edit.php b/usr/local/www/load_balancer_virtual_server_edit.php index b5ed1b051a..98303a0f21 100644 --- a/usr/local/www/load_balancer_virtual_server_edit.php +++ b/usr/local/www/load_balancer_virtual_server_edit.php @@ -153,7 +153,7 @@ include("head.inc"); - + diff --git a/usr/local/www/pkg_edit.php b/usr/local/www/pkg_edit.php index fbcd6b8152..66c597bd83 100644 --- a/usr/local/www/pkg_edit.php +++ b/usr/local/www/pkg_edit.php @@ -278,7 +278,7 @@ else - + "") { ?> diff --git a/usr/local/www/services_router_advertisements.php b/usr/local/www/services_router_advertisements.php index 3639eb6e8e..6fa92e7d9c 100644 --- a/usr/local/www/services_router_advertisements.php +++ b/usr/local/www/services_router_advertisements.php @@ -202,7 +202,7 @@ include("head.inc"); - diff --git a/usr/local/www/system_routes_edit.php b/usr/local/www/system_routes_edit.php index c1f32e4c72..43de3266da 100644 --- a/usr/local/www/system_routes_edit.php +++ b/usr/local/www/system_routes_edit.php @@ -216,7 +216,7 @@ include("head.inc"); - + From bfcb1e4a1cb43c8102978d98804adb53643a3c03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Mon, 2 Feb 2015 20:36:42 +0100 Subject: [PATCH 045/257] Allow IPseec clients to properly connect and not stomp over each other. Reported-by https://forum.pfsense.org/index.php?topic=87980.0 --- etc/inc/vpn.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index d25ae07f4b..632ea9b462 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -980,7 +980,7 @@ EOD; if (!empty($reqids[$idx])) $ipsecfin .= "\treqid = " . $reqids[0] . "\n"; $ipsecfin .= $ipsecconnect; - if (!empty($rightsubnet_spec)) { + if (!isset($ph1ent['mobile']) && !empty($rightsubnet_spec)) { $tempsubnets = array(); foreach ($rightsubnet_spec as $rightsubnet) $tempsubnets[$rightsubnet] = $rightsubnet; From e829fcbb91a79b8aab19d9ef3bd3a834bb431eaa Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Mon, 2 Feb 2015 21:32:31 -0600 Subject: [PATCH 046/257] fix text --- .../share/locale/en/LC_MESSAGES/pfSense.pot | 4 ++-- .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo | Bin 643026 -> 643027 bytes .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po | 4 ++-- .../share/locale/tr/LC_MESSAGES/pfSense.po | 4 ++-- usr/local/www/interfaces.php | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot index c9ba3be5bf..721d0bbce1 100644 --- a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot +++ b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot @@ -13948,11 +13948,11 @@ msgid "Request a IPv6 prefix/information through the IPv4 connectivity link" msgstr "" #: usr/local/www/interfaces.php:2229 -msgid "Request only a IPv6 prefix" +msgid "Request only an IPv6 prefix" msgstr "" #: usr/local/www/interfaces.php:2232 -msgid "Only request a IPv6 prefix, do not request a IPv6 address" +msgid "Only request an IPv6 prefix, do not request an IPv6 address" msgstr "" #: usr/local/www/interfaces.php:2236 diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo index 6be72ae0b08e9b4bd1ec64a7edbe28abe00dfe41..5c213a6ba98f7e128124f12a749409d70722b99b 100644 GIT binary patch delta 43 tcmcaKU;XlY^@bM47N#xC5g!@z+9N(P12GE_vjQ<25VLQO_{dRp4*;h66SV*U delta 41 rcmcaSU;Wa2^@bM47N#xC5g*$lKQaR`3lOscF&hxGZ;$-QQFRXhjwcgL diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po index 2ffb829845..ef7596bb9e 100644 --- a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po @@ -41220,11 +41220,11 @@ msgid "Request a IPv6 prefix/information through the IPv4 connectivity link" msgstr "" #: usr/local/www/interfaces.php:1815 -msgid "Request only a IPv6 prefix" +msgid "Request only an IPv6 prefix" msgstr "Requesita somente um prefixo IPv6" #: usr/local/www/interfaces.php:1818 -msgid "Only request a IPv6 prefix, do not request a IPv6 address" +msgid "Only request an IPv6 prefix, do not request an IPv6 address" msgstr "" #: etc/inc/pkg-utils.inc:1267 diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po index 0edc757af7..1da024e6e5 100644 --- a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po @@ -14515,11 +14515,11 @@ msgid "Request a IPv6 prefix/information through the IPv4 connectivity link" msgstr "" #: usr/local/www/interfaces.php:2229 -msgid "Request only a IPv6 prefix" +msgid "Request only an IPv6 prefix" msgstr "" #: usr/local/www/interfaces.php:2232 -msgid "Only request a IPv6 prefix, do not request a IPv6 address" +msgid "Only request an IPv6 prefix, do not request an IPv6 address" msgstr "" #: usr/local/www/interfaces.php:2236 diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 981b2530f4..78e6d37e15 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -2224,10 +2224,10 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"),
/> -
+

-
-
+
+
+

-
-
-
+
+
+
 
From 8fd42722fad2d447f42a0efe9f88906750a82c83 Mon Sep 17 00:00:00 2001 From: Daniel Becker Date: Mon, 9 Feb 2015 01:28:28 -0800 Subject: [PATCH 061/257] add dhcp6.name-servers option with DHCPD-PD regardless of PD length The existing code only includes a v6 name server IP in the automatically generated dhcpdv6 configuration for tracking interfaces if there are additional prefixes that can be delegated on to the next router (i.e., if PD length > 2). The correct behavior is for this option to be included regardless of the PD length, as implemented in this change. --- etc/inc/services.inc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/etc/inc/services.inc b/etc/inc/services.inc index 6b90753db1..258f62776a 100644 --- a/etc/inc/services.inc +++ b/etc/inc/services.inc @@ -1091,8 +1091,8 @@ function services_dhcpdv6_configure($blacklist = array()) { $dhcpdv6cfg[$ifname]['prefixrange']['from'] = Net_IPv6::compress($range['start']); $dhcpdv6cfg[$ifname]['prefixrange']['to'] = Net_IPv6::compress($range['end']); - $dhcpdv6cfg[$ifname]['dns6ip'] = get_interface_ipv6($ifname); } + $dhcpdv6cfg[$ifname]['dns6ip'] = get_interface_ipv6($ifname); } } @@ -1210,7 +1210,7 @@ EOD; $dhcpdv6conf .= " prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n"; } if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) { - $dhcpdv6conf .= " option dhcp6.name-servers {$dhcpv6ifconf['dns6ip']};\n"; + $dhcpdv6conf .= " option dhcp6.name-servers {$dhcpv6ifconf['dns6ip']};\n"; } // default-lease-time if ($dhcpv6ifconf['defaultleasetime']) From 09c7e42c07c3a0d72508e1a26d0e7550ccbfc21d Mon Sep 17 00:00:00 2001 From: Daniel Becker Date: Sun, 8 Feb 2015 22:26:26 -0800 Subject: [PATCH 062/257] fix Net_IPv6::compress() to properly handle all-zeros address The existing implementation of Net_IPv6::compress produces an empty string when compressing the all-zeros ("::") address; fix this by checking for empty return values and replacing them with "::". --- etc/inc/IPv6.inc | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/etc/inc/IPv6.inc b/etc/inc/IPv6.inc index e4f86bd3f8..519cbcd09e 100644 --- a/etc/inc/IPv6.inc +++ b/etc/inc/IPv6.inc @@ -748,6 +748,12 @@ class Net_IPv6 $cip = preg_replace('/((^:)|(:$))/', '', $cip); $cip = preg_replace('/((^:)|(:$))/', '::', $cip); + if (empty($cip)) { + + $cip = "::"; + + } + if ('' != $netmask) { $cip = $cip.'/'.$netmask; From 936bfd8436ab14ae84b10074f2dcc5ba465a2454 Mon Sep 17 00:00:00 2001 From: Daniel Becker Date: Sun, 8 Feb 2015 18:32:24 -0800 Subject: [PATCH 063/257] make computation of start of DHCPv6 range consistent with actual check When computing the start IP for the 'available range' field, services_dhcpv6.php attempts to increment a colon-formatted v6 address. Since this always fails, so the value that's printed is not actually incremented, so remove the bogus addition. Note that this is actually matches the behavior of the range checks that services_dhcpv6.php performs: The actual check uses the range [gen_subnetv6()..gen_subnetv6_max()], which does include the first (= all-zeroes host part) v6 address in the prefix. --- usr/local/www/services_dhcpv6.php | 1 - 1 file changed, 1 deletion(-) diff --git a/usr/local/www/services_dhcpv6.php b/usr/local/www/services_dhcpv6.php index aeb21e0ec4..393f211bbd 100644 --- a/usr/local/www/services_dhcpv6.php +++ b/usr/local/www/services_dhcpv6.php @@ -568,7 +568,6 @@ display_top_tabs($tab_array); From f7dddc868b3dcd1d017b40f85da5f81f4ede1905 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Mon, 9 Feb 2015 18:10:51 -0600 Subject: [PATCH 065/257] also add v6 IPs to hosts in the same manner v4 IPs are added. Ticket #4395 --- etc/inc/system.inc | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/etc/inc/system.inc b/etc/inc/system.inc index 7b58cfc788..0848590aae 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -307,15 +307,26 @@ function system_hosts_generate() { $cfgip = get_interface_ip("lan"); if (is_ipaddr($cfgip)) $hosts .= "{$cfgip} {$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n"; + $cfgipv6 = get_interface_ipv6("lan"); + if (is_ipaddrv6($cfgipv6)) + $hosts .= "{$cfgipv6} {$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n"; } else { $sysiflist = get_configured_interface_list(); + $hosts_if_found = false; foreach ($sysiflist as $sysif) { if (!interface_has_gateway($sysif)) { $cfgip = get_interface_ip($sysif); if (is_ipaddr($cfgip)) { $hosts .= "{$cfgip} {$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n"; - break; + $hosts_if_found = true; } + $cfgipv6 = get_interface_ipv6($sysif); + if (is_ipaddrv6($cfgipv6)) { + $hosts .= "{$cfgipv6} {$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n"; + $hosts_if_found = true; + } + if ($hosts_if_found == true) + break; } } } From ef120e878558f84ed14369a484c0938ccd1b6db5 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Mon, 9 Feb 2015 22:28:15 -0600 Subject: [PATCH 066/257] Update Unbound defaults --- conf.default/config.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/conf.default/config.xml b/conf.default/config.xml index bb94cd8713..a728142cef 100644 --- a/conf.default/config.xml +++ b/conf.default/config.xml @@ -272,5 +272,9 @@ + + + + From 74ab379dac6ad64dfaa70b96952337ba5b987046 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Mon, 9 Feb 2015 22:34:00 -0600 Subject: [PATCH 067/257] touch up Unbound text --- usr/local/www/services_unbound_advanced.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/services_unbound_advanced.php b/usr/local/www/services_unbound_advanced.php index e560d1e5d9..0bd7bfc365 100644 --- a/usr/local/www/services_unbound_advanced.php +++ b/usr/local/www/services_unbound_advanced.php @@ -254,14 +254,14 @@ include_once("head.inc"); From 02376f6f23ae06add4bfa545325a1ed0fd2d6bc8 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Tue, 10 Feb 2015 23:35:16 +0545 Subject: [PATCH 068/257] Check if notification is disabled in send_smtp_message() Other packages like arpwatch sm.php and cron job output as reported in forum https://forum.pfsense.org/index.php?topic=88347.0 call send_smtp_message() directly, currently bypassing notification disabled checks. I think those packages [are intended to | should be] respecting the notifications disabled setting. People in the forum certainly expect them to respect this setting. If we add the $force parameter here, passing it through from notify_via_smtp() then the default behavior of send_smtp_message() can be to respect the "disable" setting. That should stop other package callers from spamming people who have disabled SMTP notifications. If a package really wants/needs to send regardless, then it can set $force, just like the "Test SMTP" button does. --- etc/inc/notices.inc | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/etc/inc/notices.inc b/etc/inc/notices.inc index 044453533d..bad3a32600 100644 --- a/etc/inc/notices.inc +++ b/etc/inc/notices.inc @@ -295,15 +295,18 @@ function notify_via_smtp($message, $force = false) { fwrite($fd, $message); fclose($fd); - send_smtp_message($message, "{$config['system']['hostname']}.{$config['system']['domain']} - Notification"); + send_smtp_message($message, "{$config['system']['hostname']}.{$config['system']['domain']} - Notification", $force); return; } -function send_smtp_message($message, $subject = "(no subject)") { +function send_smtp_message($message, $subject = "(no subject)", $force = false) { global $config, $g; require_once("sasl.inc"); require_once("smtp.inc"); + if(isset($config['notifications']['smtp']['disable']) && !$force) + return; + if(!$config['notifications']['smtp']['ipaddress']) return; From afb388159bc5a55d784404411ef1a7c7d22625a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Tue, 10 Feb 2015 20:40:56 +0100 Subject: [PATCH 069/257] Fixes #4397 Make mtu configuration before the ip address assignment. This fixes the issues of link routes having the wrong mtu configured on them. --- etc/inc/interfaces.inc | 91 +++++++++++++++++++++--------------------- 1 file changed, 46 insertions(+), 45 deletions(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index c6184bb6ea..36a6a89419 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -2931,6 +2931,52 @@ function interface_configure($interface = "wan", $reloadall = false, $linkupeven unset($interface_snv6_arr_cache[$realif]); $tunnelif = substr($realif, 0, 3); + + if (does_interface_exist($wancfg['if'])) + interfaces_bring_up($wancfg['if']); + + if (!empty($wancfg['mtu'])) { + if (stristr($realif, "_vlan")) { + $assignedparent = convert_real_interface_to_friendly_interface_name($realhwif); + if (!empty($assignedparent) && !empty($config['interfaces'][$assignedparent]['mtu'])) { + $parentmtu = $config['interfaces'][$assignedparent]['mtu']; + if ($wancfg['mtu'] > $parentmtu) + log_error("There is a conflict on MTU between parent {$realhwif} and VLAN({$realif})"); + } else + $parentmtu = 0; + + $parentmtu = interface_vlan_mtu_configured($realhwif, $parentmtu); + + if (get_interface_mtu($realhwif) != $parentmtu) + pfSense_interface_mtu($realhwif, $parentmtu); + + /* All vlans need to use the same mtu value as their parent. */ + interface_vlan_adapt_mtu(link_interface_to_vlans($realhwif), $parentmtu); + } else if (substr($realif, 0, 4) == 'lagg') { + /* LAGG interface must be destroyed and re-created to change MTU */ + if ($wancfg['mtu'] != get_interface_mtu($realif)) { + if (isset($config['laggs']['lagg']) && is_array($config['laggs']['lagg'])) { + foreach ($config['laggs']['lagg'] as $lagg) { + if ($lagg['laggif'] == $realif) { + interface_lagg_configure($lagg); + break; + } + } + } + } + } else { + if ($wancfg['mtu'] != get_interface_mtu($realif)) + pfSense_interface_mtu($realif, $wancfg['mtu']); + + /* This case is needed when the parent of vlans is being configured */ + $vlans = link_interface_to_vlans($realif); + if (is_array($vlans)) + interface_vlan_adapt_mtu($vlans, $wancfg['mtu']); + unset($vlans); + } + /* XXX: What about gre/gif/.. ? */ + } + switch ($wancfg['ipaddr']) { case 'dhcp': interface_dhcp_configure($interface); @@ -2976,51 +3022,6 @@ function interface_configure($interface = "wan", $reloadall = false, $linkupeven break; } - if (!empty($wancfg['mtu'])) { - if (stristr($realif, "_vlan")) { - $assignedparent = convert_real_interface_to_friendly_interface_name($realhwif); - if (!empty($assignedparent) && !empty($config['interfaces'][$assignedparent]['mtu'])) { - $parentmtu = $config['interfaces'][$assignedparent]['mtu']; - if ($wancfg['mtu'] > $parentmtu) - log_error("There is a conflict on MTU between parent {$realhwif} and VLAN({$realif})"); - } else - $parentmtu = 0; - - $parentmtu = interface_vlan_mtu_configured($realhwif, $parentmtu); - - if (get_interface_mtu($realhwif) != $parentmtu) - pfSense_interface_mtu($realhwif, $parentmtu); - - /* All vlans need to use the same mtu value as their parent. */ - interface_vlan_adapt_mtu(link_interface_to_vlans($realhwif), $parentmtu); - } else if (substr($realif, 0, 4) == 'lagg') { - /* LAGG interface must be destroyed and re-created to change MTU */ - if ($wancfg['mtu'] != get_interface_mtu($realif)) { - if (isset($config['laggs']['lagg']) && is_array($config['laggs']['lagg'])) { - foreach ($config['laggs']['lagg'] as $lagg) { - if ($lagg['laggif'] == $realif) { - interface_lagg_configure($lagg); - break; - } - } - } - } - } else { - if ($wancfg['mtu'] != get_interface_mtu($realif)) - pfSense_interface_mtu($realif, $wancfg['mtu']); - - /* This case is needed when the parent of vlans is being configured */ - $vlans = link_interface_to_vlans($realif); - if (is_array($vlans)) - interface_vlan_adapt_mtu($vlans, $wancfg['mtu']); - unset($vlans); - } - /* XXX: What about gre/gif/.. ? */ - } - - if (does_interface_exist($wancfg['if'])) - interfaces_bring_up($wancfg['if']); - interface_netgraph_needed($interface); if (!platform_booting()) { From ed56ce5a1d12b5a065e2c375a182adc1b2d8f91d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Tue, 10 Feb 2015 20:47:21 +0100 Subject: [PATCH 070/257] Fixes #4329, Fix even tls.auth script by using proper isset() test as the fixes for other authentication scripts. --- etc/inc/openvpn.tls-verify.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/etc/inc/openvpn.tls-verify.php b/etc/inc/openvpn.tls-verify.php index 1ef0f9a859..9fd896b29a 100644 --- a/etc/inc/openvpn.tls-verify.php +++ b/etc/inc/openvpn.tls-verify.php @@ -49,7 +49,7 @@ require_once("interfaces.inc"); openlog("openvpn", LOG_ODELAY, LOG_AUTH); /* read data from command line */ -if (isset($_GET)) { +if (isset($_GET['certdepth'])) { $cert_depth = $_GET['certdepth']; $cert_subject = urldecode($_GET['certsubject']); $allowed_depth = $_GET['depth']; @@ -73,7 +73,7 @@ foreach ($subj at $s) { if (isset($allowed_depth) && ($cert_depth > $allowed_depth)) { syslog(LOG_WARNING, "Certificate depth {$cert_depth} exceeded max allowed depth of {$allowed_depth}.\n"); - if (isset($_GET)) { + if (isset($_GET['certdepth'])) { echo "FAILED"; closelog(); return; @@ -87,7 +87,7 @@ if (isset($allowed_depth) && ($cert_depth > $allowed_depth)) { //syslog(LOG_WARNING, "Found certificate {$argv[2]} with depth {$cert_depth}\n"); closelog(); -if (isset($_GET)) +if (isset($_GET['certdepth'])) echo "OK"; else exit(0); From 8fa0a5349a2fb7516a5397417d73029738e8007b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Tue, 10 Feb 2015 20:50:38 +0100 Subject: [PATCH 071/257] Actually fix even the openvpn auth user script with proper checks. I thought this was fixes already! --- etc/inc/openvpn.auth-user.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/etc/inc/openvpn.auth-user.php b/etc/inc/openvpn.auth-user.php index e212fb3a99..3a077b7fdb 100644 --- a/etc/inc/openvpn.auth-user.php +++ b/etc/inc/openvpn.auth-user.php @@ -82,7 +82,7 @@ function getNasIP() /* setup syslog logging */ openlog("openvpn", LOG_ODELAY, LOG_AUTH); -if (isset($_GET)) { +if (isset($_GET['username'])) { $authmodes = explode(",", $_GET['authcfg']); $username = base64_decode(str_replace('%3D', '=', $_GET['username'])); $password = base64_decode(str_replace('%3D', '=', $_GET['password'])); @@ -98,7 +98,7 @@ if (isset($_GET)) { if (!$username || !$password) { syslog(LOG_ERR, "invalid user authentication environment"); - if (isset($_GET)) { + if (isset($_GET['username'])) { echo "FAILED"; closelog(); return; @@ -120,7 +120,7 @@ $authenticated = false; if (($strictusercn === true) && ($common_name != $username)) { syslog(LOG_WARNING, "Username does not match certificate common name ({$username} != {$common_name}), access denied.\n"); - if (isset($_GET)) { + if (isset($_GET['username'])) { echo "FAILED"; closelog(); return; @@ -132,7 +132,7 @@ if (($strictusercn === true) && ($common_name != $username)) { if (!is_array($authmodes)) { syslog(LOG_WARNING, "No authentication server has been selected to authenticate against. Denying authentication for user {$username}"); - if (isset($_GET)) { + if (isset($_GET['username'])) { echo "FAILED"; closelog(); return; @@ -155,7 +155,7 @@ foreach ($authmodes as $authmode) { if ($authenticated == false) { syslog(LOG_WARNING, "user '{$username}' could not authenticate.\n"); - if (isset($_GET)) { + if (isset($_GET['username'])) { echo "FAILED"; closelog(); return; @@ -198,7 +198,7 @@ if (!empty($content)) syslog(LOG_NOTICE, "user '{$username}' authenticated\n"); closelog(); -if (isset($_GET)) +if (isset($_GET['username'])) echo "OK"; else return (0); From 51e76899e66360dc9d8e35f68282c54ccd9a4759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Tue, 10 Feb 2015 21:08:40 +0100 Subject: [PATCH 072/257] Fixes #4370 Use the curlies to not confuse php --- etc/inc/system.inc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/etc/inc/system.inc b/etc/inc/system.inc index 0848590aae..72ae21d416 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -1727,12 +1727,12 @@ function system_ntp_configure($start_ntpd=true) { } - if (empty($config['ntpd']['interface'])) + if (empty($config['ntpd']['interface'])) { if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) $interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']); else $interfaces = array(); - else + } else $interfaces = explode(",", $config['ntpd']['interface']); if (is_array($interfaces) && count($interfaces)) { From f416763bf064543850524f1d6436166d8be72a5b Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Wed, 11 Feb 2015 12:52:14 +0545 Subject: [PATCH 073/257] Random text typos that I noticed. --- etc/inc/captiveportal.inc | 2 +- etc/inc/interfaces.inc | 16 ++++++++-------- etc/inc/system.inc | 6 +++--- etc/inc/upgrade_config.inc | 6 +++--- etc/inc/voucher.inc | 16 ++++++++-------- usr/local/www/system_camanager.php | 2 +- usr/local/www/system_certmanager.php | 2 +- 7 files changed, 25 insertions(+), 25 deletions(-) diff --git a/etc/inc/captiveportal.inc b/etc/inc/captiveportal.inc index 73b805eb80..35bbeff3ee 100644 --- a/etc/inc/captiveportal.inc +++ b/etc/inc/captiveportal.inc @@ -785,7 +785,7 @@ function captiveportal_prune_old() { captiveportal_prune_old_automac(); if ($voucher_needs_sync == true) - /* Triger a sync of the vouchers on config */ + /* Trigger a sync of the vouchers on config */ send_event("service sync vouchers"); /* write database */ diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index 36a6a89419..524dccd477 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -171,7 +171,7 @@ function interface_netgraph_needed($interface = "wan") { pfSense_ngctl_detach("{$realif}:", $realif); } /* NOTE: We make sure for this on interface_ppps_configure() - * no need to do it here agan. + * no need to do it here again. * else * pfSense_ngctl_attach(".", $realif); */ @@ -1513,7 +1513,7 @@ function interface_ppps_configure($interface) { } break; default: - log_error(sprintf(gettext("Unkown %s configured as ppp interface."), $type)); + log_error(sprintf(gettext("Unknown %s configured as ppp interface."), $type)); break; } } @@ -2119,7 +2119,7 @@ function interface_carp_configure(&$vip) { if ($vip['mode'] != "carp") return; - /* NOTE: Maybe its useless nowdays */ + /* NOTE: Maybe its useless nowadays */ $realif = get_real_interface($vip['interface']); if (!does_interface_exist($realif)) { file_notice("CARP", sprintf(gettext("Interface specified for the virtual IP address %s does not exist. Skipping this VIP."), $vip['subnet']), "Firewall: Virtual IP", ""); @@ -2375,7 +2375,7 @@ function interface_wireless_configure($if, &$wl, &$wlcfg) { $wlcmd[] = "-mediaopt adhoc"; } - /* Not neccesary to set BSS mode as this is default if adhoc and/or hostap is NOT set */ + /* Not necessary to set BSS mode as this is default if adhoc and/or hostap is NOT set */ /* handle hide ssid option */ if(isset($wlcfg['hidessid']['enable'])) { @@ -3126,10 +3126,10 @@ function interface_track6_configure($interface = "lan", $wancfg, $linkupevent = case "dhcp6": if ($linkupevent == true) { /* - * NOTE: Usually come here from rc.linkup calling so just call directly intead of generating event + * NOTE: Usually come here from rc.linkup calling so just call directly instead of generating event * Instead of disrupting all other v4 configuration just restart DHCPv6 client for now * - * XXX: Probably DHCPv6 client should handle this autmagically itself? + * XXX: Probably DHCPv6 client should handle this automagically itself? */ $parentrealif = get_real_interface($wancfg['track6-interface']); $pidv6 = find_dhcp6c_process($parentrealif); @@ -3913,7 +3913,7 @@ function DHCP_Config_File_Substitutions($wancfg, $wanif, $dhclientconf) { $res = stripos($dhclientconf, $various_mac_type . $various_mac_case . $various_mac_delimiter); if ($res !== false) { - /* Get MAC Address as ASCII String With Colon (:) Celimiters */ + /* Get MAC Address as ASCII String With Colon (:) delimiters */ if ("$various_mac_case" == "U") $dhcpclientconf_mac = strtoupper(get_interface_mac($wanif)); if ("$various_mac_case" == "L") $dhcpclientconf_mac = strtolower(get_interface_mac($wanif)); @@ -4231,7 +4231,7 @@ function get_real_interface($interface = "wan", $family = "all", $realv6iface = $interface = substr($interface, 5); } else if (does_interface_exist($interface, $flush)) { /* - * If a real interface was alread passed simply + * If a real interface was already passed simply * pass the real interface back. This encourages * the usage of this function in more cases so that * we can combine logic for more flexibility. diff --git a/etc/inc/system.inc b/etc/inc/system.inc index 72ae21d416..3a050ad9f6 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -939,7 +939,7 @@ function system_webgui_create_certificate() { 'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate", 'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}", 'commonName' => "{$config['system']['hostname']}-{$cert['refid']}"); - $old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warings directly to a page screwing menu tab */ + $old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */ if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")){ while($ssl_err = openssl_error_string()){ log_error("Error creating WebGUI Certificate: openssl library returns: " . $ssl_err); @@ -1235,7 +1235,7 @@ mimetype.assign = ( url.access-deny = ( "~", ".inc" ) -######### Options that are good to be but not neccesary to be changed ####### +######### Options that are good to be but not necessary to be changed ####### ## bind to port (default: 80) @@ -1746,7 +1746,7 @@ function system_ntp_configure($start_ntpd=true) { } } - /* open configuration for wrting or bail */ + /* open configuration for writing or bail */ if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) { log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing"); return; diff --git a/etc/inc/upgrade_config.inc b/etc/inc/upgrade_config.inc index e06c2590bd..71b97c8396 100644 --- a/etc/inc/upgrade_config.inc +++ b/etc/inc/upgrade_config.inc @@ -1869,7 +1869,7 @@ function upgrade_052_to_053() { if (!is_array($config['cert'])) $config['cert'] = array(); - /* migrate advanced admin page webui ssl to certifcate mngr */ + /* migrate advanced admin page webui ssl to certificate manager */ if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) { @@ -2631,7 +2631,7 @@ function upgrade_078_to_079() { function upgrade_079_to_080() { global $config; - /* Upgrade config in 1.2.3 specifying a username other than admin for synching. */ + /* Upgrade config in 1.2.3 specifying a username other than admin for syncing. */ if (!empty($config['system']['username']) && is_array($config['installedpackages']['carpsettings']) && is_array($config['installedpackages']['carpsettings']['config'])) { $config['installedpackages']['carpsettings']['config'][0]['username'] = $config['system']['username']; @@ -2985,7 +2985,7 @@ function upgrade_088_to_089() { if (!is_array($config['cert'])) $config['cert'] = array(); - /* migrate captive portal ssl to certifcate mngr */ + /* migrate captive portal ssl to certificate manager */ if (is_array($config['captiveportal'])) { foreach ($config['captiveportal'] as $id => &$setting) { if (isset($setting['httpslogin'])) { diff --git a/etc/inc/voucher.inc b/etc/inc/voucher.inc index f9b41b35f5..f6b7248a20 100644 --- a/etc/inc/voucher.inc +++ b/etc/inc/voucher.inc @@ -284,7 +284,7 @@ function voucher_expire($voucher_received) { $unsetindexes[] = $cpentry[5]; } } else - captiveportal_syslog("$voucher ($roll/$nr): not found on any registererd Roll"); + captiveportal_syslog("$voucher ($roll/$nr): not found on any registered Roll"); } else // hmm, thats weird ... not what I expected captiveportal_syslog("$voucher invalid: {$output[0]}!!"); @@ -296,7 +296,7 @@ function voucher_expire($voucher_received) { voucher_write_active_db($roll, $active); unset($active_vouchers); - /* Triger a sync of the vouchers on config */ + /* Trigger a sync of the vouchers on config */ send_event("service sync vouchers"); } @@ -412,8 +412,8 @@ function voucher_auth($voucher_received, $test = 0) { } } } else { - $test_result[] = "$voucher ($roll/$nr): not found on any registererd Roll"; - captiveportal_syslog("$voucher ($roll/$nr): not found on any registererd Roll"); + $test_result[] = "$voucher ($roll/$nr): not found on any registered Roll"; + captiveportal_syslog("$voucher ($roll/$nr): not found on any registered Roll"); } } else { // hmm, thats weird ... not what I expected @@ -480,7 +480,7 @@ function voucher_auth($voucher_received, $test = 0) { $active_vouchers[$first_voucher_roll][$first_voucher] = "$timestamp,$minutes"; voucher_write_active_db($first_voucher_roll, $active_vouchers[$first_voucher_roll]); - /* Triger a sync of the vouchers on config */ + /* Trigger a sync of the vouchers on config */ send_event("service sync vouchers"); unlock($voucherlck); @@ -560,7 +560,7 @@ function voucher_configure_zone($sync = false) { $timestamp = $activent['timestamp']; $minutes = $activent['minutes']; // its tempting to check for expired timestamps, but during - // bootup, we most likely don't have the correct time time. + // bootup, we most likely don't have the correct time. $active_vouchers[$voucher] = "$timestamp,$minutes"; } } @@ -613,7 +613,7 @@ function voucher_read_active_db($roll) { if ($dirty) { // if we found expired entries, lets save our snapshot voucher_write_active_db($roll, $active); - /* Triger a sync of the vouchers on config */ + /* Trigger a sync of the vouchers on config */ send_event("service sync vouchers"); } } @@ -735,7 +735,7 @@ function voucher_save_db_to_config_zone() { unlock($voucherlck); - write_config("Synching vouchers"); + write_config("Syncing vouchers"); return; } diff --git a/usr/local/www/system_camanager.php b/usr/local/www/system_camanager.php index a4bcea64d7..cc73b519e0 100644 --- a/usr/local/www/system_camanager.php +++ b/usr/local/www/system_camanager.php @@ -253,7 +253,7 @@ if ($_POST) { if (!empty($pconfig['key'])) $ca['prv'] = base64_encode($pconfig['key']); } else { - $old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warings directly to a page screwing menu tab */ + $old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */ if ($pconfig['method'] == "existing") ca_import($ca, $pconfig['cert'], $pconfig['key'], $pconfig['serial']); diff --git a/usr/local/www/system_certmanager.php b/usr/local/www/system_certmanager.php index 8082cd69d9..e6c7551b48 100644 --- a/usr/local/www/system_certmanager.php +++ b/usr/local/www/system_certmanager.php @@ -339,7 +339,7 @@ if ($_POST) { $cert['descr'] = $pconfig['descr']; - $old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warings directly to a page screwing menu tab */ + $old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */ if ($pconfig['method'] == "import") cert_import($cert, $pconfig['cert'], $pconfig['key']); From 06e847a72929245fd8bc71c26b309bb3b7d71921 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 11 Feb 2015 01:13:17 -0600 Subject: [PATCH 074/257] Check if Unbound is enabled and using the same port before allowing dnsmasq to be enabled. part of Ticket #4332 --- usr/local/www/services_dnsmasq.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/usr/local/www/services_dnsmasq.php b/usr/local/www/services_dnsmasq.php index 273f81d4b7..a758a48cd0 100644 --- a/usr/local/www/services_dnsmasq.php +++ b/usr/local/www/services_dnsmasq.php @@ -87,6 +87,11 @@ if ($_POST) { $config['dnsmasq']['custom_options'] = str_replace("\r\n", "\n", $_POST['custom_options']); $config['dnsmasq']['strictbind'] = ($_POST['strictbind']) ? true : false; + if (isset($_POST['enable']) && isset($config['unbound']['enable'])) { + if ($_POST['port'] == $config['unbound']['port']) + $input_errors[] = "The DNS Resolver is enabled using this port. Choose a non-conflicting port, or disable DNS Resolver."; + } + if ($_POST['port']) if(is_port($_POST['port'])) $config['dnsmasq']['port'] = $_POST['port']; From 0c6db320bdaeee0c4264c6b65b6cdf0a03444267 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Wed, 11 Feb 2015 13:13:58 +0545 Subject: [PATCH 075/257] Fix typo in class in bridge edit Fixing this makes nice little pencil icons appear in front of the text entry fields. --- usr/local/www/interfaces_bridge_edit.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/usr/local/www/interfaces_bridge_edit.php b/usr/local/www/interfaces_bridge_edit.php index 0fd62f0863..bb68e63b26 100644 --- a/usr/local/www/interfaces_bridge_edit.php +++ b/usr/local/www/interfaces_bridge_edit.php @@ -344,7 +344,7 @@ function show_source_port_range() { "; echo ""; From e2caaee8ef59a1dd2e0389564f6c59798a54664b Mon Sep 17 00:00:00 2001 From: k-paulius Date: Sun, 15 Feb 2015 23:31:00 -0600 Subject: [PATCH 091/257] Fixing issues with NTP RRD graph state changes - only call enable_rrd_graphing() after $config['ntpd']['statsgraph'] is set - fix if condition; empty and isset are each other's opposites --- usr/local/www/services_ntpd.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/usr/local/www/services_ntpd.php b/usr/local/www/services_ntpd.php index 948ef6ef8e..fb7820f927 100644 --- a/usr/local/www/services_ntpd.php +++ b/usr/local/www/services_ntpd.php @@ -148,12 +148,14 @@ if ($_POST) { elseif (isset($config['ntpd']['notrap'])) unset($config['ntpd']['notrap']); - if ((empty($_POST['statsgraph'])) != (isset($config['ntpd']['statsgraph']))); - enable_rrd_graphing(); + if ((empty($_POST['statsgraph'])) == (isset($config['ntpd']['statsgraph']))) + $enable_rrd_graphing = true; if (!empty($_POST['statsgraph'])) $config['ntpd']['statsgraph'] = $_POST['statsgraph']; elseif (isset($config['ntpd']['statsgraph'])) unset($config['ntpd']['statsgraph']); + if (!empty($enable_rrd_graphing)) + enable_rrd_graphing(); if (!empty($_POST['leaptxt'])) $config['ntpd']['leapsec'] = base64_encode($_POST['leaptxt']); From 7138390188d962723b7bcb30df29af3797586715 Mon Sep 17 00:00:00 2001 From: k-paulius Date: Mon, 16 Feb 2015 22:13:48 -0600 Subject: [PATCH 092/257] Do not request prefix delegation if no tracking interfaces are setup to use it. Ticket #4436 --- etc/inc/interfaces.inc | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index ef6cb46ebe..8271058b27 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -3459,10 +3459,16 @@ function interface_dhcpv6_configure($interface = "wan", $wancfg) { $dhcp6cconf .= " script \"{$g['varetc_path']}/dhcp6c_{$interface}_script.sh\"; # we'd like some nameservers please\n"; $dhcp6cconf .= "};\n"; } else { + $iflist = link_interface_to_track6($interface); + foreach ($iflist as $ifname => $ifcfg) { + if (is_numeric($ifcfg['track6-prefix-id'])) + $trackiflist[$ifname] = $ifcfg; + } + /* skip address request if this is set */ if(!isset($wancfg['dhcp6prefixonly'])) $dhcp6cconf .= " send ia-na 0; # request stateful address\n"; - if(is_numeric($wancfg['dhcp6-ia-pd-len'])) + if(is_numeric($wancfg['dhcp6-ia-pd-len']) && !empty($trackiflist)) $dhcp6cconf .= " send ia-pd 0; # request prefix delegation\n"; $dhcp6cconf .= "\trequest domain-name-servers;\n"; @@ -3474,25 +3480,22 @@ function interface_dhcpv6_configure($interface = "wan", $wancfg) { if(!isset($wancfg['dhcp6prefixonly'])) $dhcp6cconf .= "id-assoc na 0 { };\n"; - if(is_numeric($wancfg['dhcp6-ia-pd-len'])) { + if(is_numeric($wancfg['dhcp6-ia-pd-len']) && !empty($trackiflist)) { /* Setup the prefix delegation */ $dhcp6cconf .= "id-assoc pd 0 {\n"; $preflen = 64 - $wancfg['dhcp6-ia-pd-len']; if (isset($wancfg['dhcp6-ia-pd-send-hint'])) $dhcp6cconf .= " prefix ::/{$preflen} infinity;\n"; - $iflist = link_interface_to_track6($interface); - foreach ($iflist as $friendly => $ifcfg) { - if (is_numeric($ifcfg['track6-prefix-id'])) { - if ($g['debug']) - log_error("setting up $ifdescr - {$ifcfg['track6-prefix-id']}"); - $realif = get_real_interface($friendly); - $dhcp6cconf .= " prefix-interface {$realif} {\n"; - $dhcp6cconf .= " sla-id {$ifcfg['track6-prefix-id']};\n"; - $dhcp6cconf .= " sla-len {$wancfg['dhcp6-ia-pd-len']};\n"; - $dhcp6cconf .= " };\n"; - } + foreach ($trackiflist as $friendly => $ifcfg) { + if ($g['debug']) + log_error("setting up $ifdescr - {$ifcfg['track6-prefix-id']}"); + $realif = get_real_interface($friendly); + $dhcp6cconf .= " prefix-interface {$realif} {\n"; + $dhcp6cconf .= " sla-id {$ifcfg['track6-prefix-id']};\n"; + $dhcp6cconf .= " sla-len {$wancfg['dhcp6-ia-pd-len']};\n"; + $dhcp6cconf .= " };\n"; } - unset($preflen, $iflist, $ifcfg); + unset($preflen, $iflist, $ifcfg, $ifname, $trackiflist); $dhcp6cconf .= "};\n"; } } From 31495068477761fa9219c448517e935387b85db1 Mon Sep 17 00:00:00 2001 From: stilez Date: Tue, 17 Feb 2015 17:20:39 +0000 Subject: [PATCH 093/257] Three minor improvements to IP functions 1) Most is_ip***() functions can return 4 or 6 to indicate type of IP, for benefit of calling code (both evaluate to boolean TRUE for backwards compatibility). But is_ipddr() doesn't. Fix is_ipaddr() so it follows same result schema. This saves calling code having to retest same data to determine type. 2) clarify comment - is_linklocal() applies to IPv6 only 3) similarly improve is_ipaddrwithport(). Although a few lines longer, it should be faster as it avoids an unnecessary explode-pop-implode (both IPv4 and IPv6 just need one split, in the same place, on the final colon). Also improve like other is_***() functions, to now return 4 or 6 to indicate IP type detected, for benefit of calling code . --- etc/inc/util.inc | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/etc/inc/util.inc b/etc/inc/util.inc index b12bc9a7e8..993c4df774 100644 --- a/etc/inc/util.inc +++ b/etc/inc/util.inc @@ -561,13 +561,15 @@ function is_iprange($range) { return false; } -/* returns true if $ipaddr is a valid dotted IPv4 address or a IPv6 */ +/* returns true if $ipaddr is a valid dotted IPv4 address or a IPv6 + false - not valid + true (numeric 4 or 6) - if valid, gives type of address */ function is_ipaddr($ipaddr) { if(is_ipaddrv4($ipaddr)) { - return true; + return 4; } if(is_ipaddrv6($ipaddr)) { - return true; + return 6; } return false; } @@ -597,7 +599,7 @@ function is_ipaddrv4($ipaddr) { return false; } -/* returns true if $ipaddr is a valid linklocal address */ +/* returns true if $ipaddr is a valid IPv6 linklocal address */ function is_linklocal($ipaddr) { return (strtolower(substr($ipaddr, 0, 5)) == "fe80:"); } @@ -620,16 +622,24 @@ function is_literalipaddrv6($ipaddr) { return is_ipaddrv6($ipaddr); } +/* returns true if $iport is a valid IPv4/IPv6 address + port + false - not valid + true (numeric 4 or 6) - if valid, gives type of address */ function is_ipaddrwithport($ipport) { - $parts = explode(":", $ipport); - $port = array_pop($parts); - if (count($parts) == 1) { - return is_ipaddrv4($parts[0]) && is_port($port); - } elseif (count($parts) > 1) { - return is_literalipaddrv6(implode(":", $parts)) && is_port($port); - } else { + $c = strrpos($ipport, ":"); + if ($c === false) + return false; // can't split at final colon if no colon exists + + if (!is_port(substr($ipport, $c + 1))) + return false; // no valid port after last colon + + $ip = substr($ipport, 0, $c); // else is text before last colon a valid IP + if (is_literalipaddrv6($ip)) + return 6; + elseif (is_ipaddrv4($ip)) + return 4; + else return false; - } } function is_hostnamewithport($hostport) { From 209ba3aad61e4ad23eed85e70af4f0a074f7fbe6 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Tue, 17 Feb 2015 22:30:55 -0600 Subject: [PATCH 094/257] Wait a bit after sending a TERM to syslogd as in some instances it can take too long to stop, and it fails to restart because it's still running at that point. Add a KILL in case it's still running after that. Ticket #4393 --- etc/inc/system.inc | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/etc/inc/system.inc b/etc/inc/system.inc index 3a050ad9f6..b099ed1416 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -906,8 +906,17 @@ EOD; $syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}"; } - if (isvalidpid("{$g['varrun_path']}/syslog.pid")) + if (isvalidpid("{$g['varrun_path']}/syslog.pid")) { sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM"); + usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful + } + + if (isvalidpid("{$g['varrun_path']}/syslog.pid")) { + // if it still hasn't responded to the TERM, KILL it. + sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL"); + usleep(100000); + } + $retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}"); From 065e78b3a96eb56022b2b028dd3d2b803eed800d Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 18 Feb 2015 00:38:23 -0600 Subject: [PATCH 095/257] Add GUI control for MOBIKE. Hide it when IKEv1 selected. Enable toggling of NAT-T field display so it's on for IKEv1, off for IKEv2. Do same for reauth while here. Ticket #3979 --- etc/inc/vpn.inc | 6 ++++++ usr/local/www/vpn_ipsec_phase1.php | 31 ++++++++++++++++++++++++++---- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 2f137c7a93..1be37deafe 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -769,6 +769,11 @@ EOD; $forceencaps = 'forceencaps = yes'; else $forceencaps = 'forceencaps = no'; + + if ($ph1ent['mobike'] == 'on') + $mobike = 'mobike = yes'; + else + $mobike = 'mobike = no'; $ipseclifetime = 0; $rightsubnet_spec = array(); @@ -928,6 +933,7 @@ EOD; keyexchange = {$keyexchange} {$reauth} {$forceencaps} + {$mobike} {$rekey} installpolicy = yes {$tunneltype} diff --git a/usr/local/www/vpn_ipsec_phase1.php b/usr/local/www/vpn_ipsec_phase1.php index e7c5cdb8b0..4630828048 100644 --- a/usr/local/www/vpn_ipsec_phase1.php +++ b/usr/local/www/vpn_ipsec_phase1.php @@ -108,6 +108,7 @@ if (isset($p1index) && $a_phase1[$p1index]) { $pconfig['descr'] = $a_phase1[$p1index]['descr']; $pconfig['nat_traversal'] = $a_phase1[$p1index]['nat_traversal']; + $pconfig['mobike'] = $a_phase1[$p1index]['mobike']; if (isset($a_phase1[$p1index]['reauth_enable'])) $pconfig['reauth_enable'] = true; @@ -136,6 +137,7 @@ if (isset($p1index) && $a_phase1[$p1index]) { $pconfig['dhgroup'] = "2"; $pconfig['lifetime'] = "28800"; $pconfig['nat_traversal'] = 'on'; + $pconfig['mobike'] = 'off'; $pconfig['dpd_enable'] = true; $pconfig['iketype'] = "ikev1"; @@ -382,6 +384,7 @@ if ($_POST) { $ph1ent['authentication_method'] = $pconfig['authentication_method']; $ph1ent['descr'] = $pconfig['descr']; $ph1ent['nat_traversal'] = $pconfig['nat_traversal']; + $ph1ent['mobike'] = $pconfig['mobike']; if (isset($pconfig['reauth_enable'])) $ph1ent['reauth_enable'] = true; @@ -447,10 +450,17 @@ function myidsel_change() { function iketype_change() { index = document.iform.iketype.selectedIndex; value = document.iform.iketype.options[index].value; - if (value == 'ikev2') + if (value == 'ikev2') { document.getElementById('negmode').style.display= 'none'; - else + document.getElementById('mobike').style.display= ''; + document.getElementById('natt').style.display= 'none'; + document.getElementById('disablereauth').style.display= ''; + } else { document.getElementById('negmode').style.display = ''; + document.getElementById('mobike').style.display = 'none'; + document.getElementById('natt').style.display= ''; + document.getElementById('disablereauth').style.display= 'none'; + } } function peeridsel_change() { @@ -894,7 +904,7 @@ function dpdchkbox_change() {
- + - + + + + + From 559c8d3df1ad092096b04cd19baa3eb0d2c51540 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 18 Feb 2015 01:57:15 -0600 Subject: [PATCH 096/257] Don't hard code harden-referral-path. It defaults to no, so no behavior change, and that setting is unlikely to ever become a default. This allows users to configure an override to enable this option if desired. part of Ticket #4399 --- etc/inc/unbound.inc | 1 - 1 file changed, 1 deletion(-) diff --git a/etc/inc/unbound.inc b/etc/inc/unbound.inc index b77f09a2ef..8641ddb3e8 100644 --- a/etc/inc/unbound.inc +++ b/etc/inc/unbound.inc @@ -277,7 +277,6 @@ port: {$port} verbosity: {$verbosity} hide-identity: {$hide_identity} hide-version: {$hide_version} -harden-referral-path: no harden-glue: {$harden_glue} do-ip4: yes do-ip6: yes From 6777fc3b6efb59bf42ee709508cf384ec5890dcf Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Wed, 18 Feb 2015 14:33:13 +0545 Subject: [PATCH 097/257] diag_arp allow underscore in resolved host names is_hostname() and is_domain() allow underscore in the names. So it is possible to have underscore in host names, for example in DHCP server static mapped entries I have some things like: 10.42.3.4 client-pc-01_LAN 10.42.3.5 client-pc-01_WIFI These reverse-resolve fine - 10.42.3.4 becomes client-pc-01_LAN But the preg_match here misses such names that have an underscore in them. I noticed this when looking into forum post: https://forum.pfsense.org/index.php?topic=88956.0 --- usr/local/www/diag_arp.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/diag_arp.php b/usr/local/www/diag_arp.php index ffe960ff67..16b3303f0f 100644 --- a/usr/local/www/diag_arp.php +++ b/usr/local/www/diag_arp.php @@ -251,7 +251,7 @@ function _getHostName($mac,$ip) { return $dhcpip[$ip]; else{ exec("host -W 1 " . escapeshellarg($ip), $output); - if (preg_match('/.*pointer ([A-Za-z0-9.-]+)\..*/',$output[0],$matches)) { + if (preg_match('/.*pointer ([A-Za-z_0-9.-]+)\..*/',$output[0],$matches)) { if ($matches[1] <> $ip) return $matches[1]; } From 153613e3fdfa87c20dc200342597c2e5188179ff Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Wed, 18 Feb 2015 16:42:26 +0545 Subject: [PATCH 098/257] Handle reverse lookup domain overrides that match exactly a whole block of private address space. e.g. if the user has checked "Do not forward private reverse lookups" and also adds adds a domain override that matches a whole block of private address space, such as: 10.in-addr.arpa -> 10.42.1.1 then we want all reverse lookups in the "10" network to be referred to their DNS server at 10.42.1.1 and reverse lookups of other private addresses to immediately return NXDOMAIN. Without this change, those referrals were not happening, because there was a "-server=10.in-addr.arpa" to nowhere put on the command line and that was effectively overriding the user-specified domain override! --- etc/inc/services.inc | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/etc/inc/services.inc b/etc/inc/services.inc index 5ef7c6613b..b185983520 100644 --- a/etc/inc/services.inc +++ b/etc/inc/services.inc @@ -1825,18 +1825,34 @@ function services_dnsmasq_configure() { } /* If selected, then first forward reverse lookups for private IPv4 addresses to nowhere. */ - /* If any of these are duplicated by a user-specified domain override (e.g. 10.in-addr.arpa) then */ - /* the user-specified entry made later on the command line below will be the one that is effective. */ + /* Only make entries for reverse domains that do not have a matching domain override. */ if (isset($config['dnsmasq']['no_private_reverse'])) { /* Note: Carrier Grade NAT (CGN) addresses 100.64.0.0/10 are intentionally not here. */ /* End-users should not be aware of CGN addresses, so reverse lookups for these should not happen. */ /* Just the pfSense WAN might get a CGN address from an ISP. */ - $args .= " --server=/10.in-addr.arpa/ "; - $args .= " --server=/168.192.in-addr.arpa/ "; - /* Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme. */ - for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) { - $args .= " --server=/" . $subnet_num . ".172.in-addr.arpa/ "; + + // Build an array of domain overrides to help in checking for matches. + $override_a = array(); + if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) { + foreach ($config['dnsmasq']['domainoverrides'] as $override) { + $override_a[$override['domain']] = "y"; + } } + + // Build an array of the private reverse lookup domain names + $reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa"); + // Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme. + for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) { + $reverse_domain_a[] = "$subnet_num.172.in-addr.arpa"; + } + + // Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override. + foreach ($reverse_domain_a as $reverse_domain) { + if (!isset($override_a[$reverse_domain])) + $args .= " --server=/$reverse_domain/ "; + } + unset($override_a); + unset($reverse_domain_a); } /* Setup forwarded domains */ From 0778191eca79fee8ac6673e915308479151525f0 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 18 Feb 2015 19:41:44 -0600 Subject: [PATCH 099/257] remove unused dfuife files. --- etc/pfSense.obsoletedfiles | 3 +++ 1 file changed, 3 insertions(+) diff --git a/etc/pfSense.obsoletedfiles b/etc/pfSense.obsoletedfiles index 08e1fba6e4..f0d1d44529 100644 --- a/etc/pfSense.obsoletedfiles +++ b/etc/pfSense.obsoletedfiles @@ -877,6 +877,9 @@ /usr/local/www/auto_complete_helper.js /usr/local/www/csrf/csrf-secret.php /usr/local/www/datetimepicker.js +/usr/local/www/dfuife.cgi +/usr/local/www/dfuife.css +/usr/local/www/dfuife.js /usr/local/www/diag_dhcp_leases.php /usr/local/www/diag_logs_slbd.php /usr/local/www/diag_showbogons.php From e0c1bfd7421c5a805b27a80247c4095c8efeab99 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 18 Feb 2015 19:52:58 -0600 Subject: [PATCH 100/257] add a couple unnecessary bsdinstaller files to obsoletedfiles --- etc/pfSense.obsoletedfiles | 2 ++ 1 file changed, 2 insertions(+) diff --git a/etc/pfSense.obsoletedfiles b/etc/pfSense.obsoletedfiles index f0d1d44529..a8a7f54a04 100644 --- a/etc/pfSense.obsoletedfiles +++ b/etc/pfSense.obsoletedfiles @@ -877,6 +877,7 @@ /usr/local/www/auto_complete_helper.js /usr/local/www/csrf/csrf-secret.php /usr/local/www/datetimepicker.js +/usr/local/www/dfly-pg.gif /usr/local/www/dfuife.cgi /usr/local/www/dfuife.css /usr/local/www/dfuife.js @@ -896,6 +897,7 @@ /usr/local/www/firewall_shaper_edit.php /usr/local/www/firewall_shaper_queues_edit.php /usr/local/www/fred.png +/usr/local/www/fred-bg.png /usr/local/www/ifstats.cgi /usr/local/www/includes/javascript.inc.php /usr/local/www/includes/log.inc.php From e5a67d33db79a7efc0de100ca1fa838753c517c7 Mon Sep 17 00:00:00 2001 From: jim-p Date: Fri, 20 Feb 2015 13:42:23 -0500 Subject: [PATCH 101/257] Clean up some old, possibly stale, files when restarting php-fpm --- etc/rc.php-fpm_restart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/etc/rc.php-fpm_restart b/etc/rc.php-fpm_restart index 79ae41decb..fff4455988 100755 --- a/etc/rc.php-fpm_restart +++ b/etc/rc.php-fpm_restart @@ -8,6 +8,8 @@ sleep 2 # /usr/local/etc/php.ini and /usr/local/lib/php.ini /etc/rc.conf_mount_rw /etc/rc.php_ini_setup 2>/tmp/php_errors.txt +/bin/rm -f /var/run/php-fpm.pid 2>/dev/null +/bin/rm -f /var/run/php-fpm.socket 2>/dev/null /etc/rc.conf_mount_ro echo ">>> Restarting php-fpm" | /usr/bin/logger -p daemon.info -i -t rc.php-fpm_restart echo ">>> Starting php-fpm" From f5bea14281438c99e9c22f94ac5bd0c05549255c Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sun, 22 Feb 2015 11:21:56 +0545 Subject: [PATCH 102/257] Status_dhcp_leases fix edit button for static entries with no IP address The edit button for static entries always has an index id=0 and thus pressing the edit button goes to (mostly) edit the wrong entry. It was easier and made the code cleaner to get rid of the looping through the staticmap array every time trying to matach IP, MAC address... That data ('if' and 'staticmap_array_index') is easily gathered further up, the first time the staticmap array for each DHCP interface is traversed. I think this should also be more efficient when there are many static mapping entries. Forum: https://forum.pfsense.org/index.php?topic=89072.msg493241#msg493241 --- usr/local/www/status_dhcp_leases.php | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/usr/local/www/status_dhcp_leases.php b/usr/local/www/status_dhcp_leases.php index 88803c4224..191d9f5d30 100644 --- a/usr/local/www/status_dhcp_leases.php +++ b/usr/local/www/status_dhcp_leases.php @@ -274,17 +274,21 @@ if(count($pools) > 0) { foreach($config['interfaces'] as $ifname => $ifarr) { if (is_array($config['dhcpd'][$ifname]) && is_array($config['dhcpd'][$ifname]['staticmap'])) { + $staticmap_array_index = 0; foreach($config['dhcpd'][$ifname]['staticmap'] as $static) { $slease = array(); $slease['ip'] = $static['ipaddr']; $slease['type'] = "static"; $slease['mac'] = $static['mac']; + $slease['if'] = $ifname; $slease['start'] = ""; $slease['end'] = ""; $slease['hostname'] = htmlentities($static['hostname']); $slease['act'] = "static"; $slease['online'] = in_array(strtolower($slease['mac']), $arpdata_mac) ? 'online' : 'offline'; + $slease['staticmap_array_index'] = $staticmap_array_index; $leases[] = $slease; + $staticmap_array_index++; } } } @@ -349,23 +353,7 @@ foreach ($leases as $data) { $fspane = " "; } $lip = ip2ulong($data['ip']); - if ($data['act'] == "static") { - foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) { - if(is_array($dhcpifconf['staticmap'])) { - $staticmap_array_index = 0; - foreach ($dhcpifconf['staticmap'] as $staticent) { - if ($data['ip'] == $staticent['ipaddr']) { - $data['if'] = $dhcpif; - break; - } - $staticmap_array_index++; - } - } - /* exit as soon as we have an interface */ - if ($data['if'] != "") - break; - } - } else { + if ($data['act'] != "static") { foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) { if (!is_array($dhcpifconf['range'])) continue; @@ -407,7 +395,7 @@ foreach ($leases as $data) { echo ""; echo "\"add\" \n"; } else { - echo ""; + echo ""; echo "\"add\" \n"; } From 1862040059e4e64859f2fc8cd8395c367ec59a57 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sun, 22 Feb 2015 11:47:06 +0545 Subject: [PATCH 103/257] Mention interface name on DHCP edit GUI IMHO it can be confusing on the DHCP edit page for static mapped entries to know which interface the entry is being edited/added for. Specially if the user comes from the Status DHCP Leases page, the lease they are editing/adding could be for 1 of many LAN-style interfaces. This also made it easier for me to see which interface entry I was editing when I was testing https://github.com/pfsense/pfsense/pull/1504 --- usr/local/www/services_dhcp_edit.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/services_dhcp_edit.php b/usr/local/www/services_dhcp_edit.php index c044185d8d..e91a23d4d2 100644 --- a/usr/local/www/services_dhcp_edit.php +++ b/usr/local/www/services_dhcp_edit.php @@ -368,7 +368,7 @@ include("head.inc");
From 758b51a0213a08ab4d2189f9f1513cf34608da1b Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Mon, 9 Feb 2015 14:20:17 -0600 Subject: [PATCH 064/257] Use appropriate interface field description when working with floating rules, it was confusing and potentially incorrect for floating rule purposes. --- usr/local/www/firewall_rules_edit.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/usr/local/www/firewall_rules_edit.php b/usr/local/www/firewall_rules_edit.php index 376b2ed749..37a694cd3b 100644 --- a/usr/local/www/firewall_rules_edit.php +++ b/usr/local/www/firewall_rules_edit.php @@ -945,7 +945,11 @@ include("head.inc");
- + + + + +
/>
- ", "");?> + ", "");?>
/>
- +
- +
- +
- +
- +
- +
$ifdescr) - echo ""; + echo ""; ?>
{$ifdescr}
{$ifdescr}
@@ -407,7 +407,7 @@ function show_source_port_range() {
$ifdescr) - echo ""; + echo ""; ?>
{$ifdescr}
{$ifdescr}
@@ -424,7 +424,7 @@ function show_source_port_range() {
/> @@ -908,7 +918,7 @@ function dpdchkbox_change() {
+ +
+ + . + +
- + From d82b2a6fb9fa0a5409e22cfb64f9d2929e19ad4c Mon Sep 17 00:00:00 2001 From: k-paulius Date: Sun, 22 Feb 2015 21:47:16 -0600 Subject: [PATCH 104/257] Fix broken links to dhcp6c.conf man page. manpath FreeBSD+Ports no longer exits and needs to be replaced with FreeBSD+10.1-RELEASE+and+Ports --- usr/local/share/locale/en/LC_MESSAGES/pfSense.pot | 12 ++++++------ usr/local/share/locale/tr/LC_MESSAGES/pfSense.po | 12 ++++++------ usr/local/www/interfaces.php | 12 ++++++------ 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot index 7419f47d6b..c9ba827cd8 100644 --- a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot +++ b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot @@ -13978,7 +13978,7 @@ msgstr "" msgid "" "Interface Statement" +"+10.1-RELEASE+and+Ports#Interface_statement\">Interface Statement" msgstr "" #: usr/local/www/interfaces.php:2265 @@ -14025,7 +14025,7 @@ msgstr "" msgid "" "Identity Association Statement" +"+10.1-RELEASE+and+Ports#Identity_association_statement\">Identity Association Statement" msgstr "" #: usr/local/www/interfaces.php:2299 @@ -14080,7 +14080,7 @@ msgstr "" msgid "" "Prefix Interface Statement" +"+10.1-RELEASE+and+Ports#Prefix_interface_statement\">Prefix Interface Statement" msgstr "" #: usr/local/www/interfaces.php:2338 @@ -14099,7 +14099,7 @@ msgstr "" msgid "" "Authentication Statement" +"+10.1-RELEASE+and+Ports#Authentication_statement\">Authentication Statement" msgstr "" #: usr/local/www/interfaces.php:2351 @@ -14122,7 +14122,7 @@ msgstr "" msgid "" "Keyinfo Statement" +"+10.1-RELEASE+and+Ports#Keyinfo_statement\">Keyinfo Statement" msgstr "" #: usr/local/www/interfaces.php:2367 @@ -14148,7 +14148,7 @@ msgstr "" #: usr/local/www/interfaces.php:2383 msgid "" "Configuration File Override" msgstr "" diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po index c384e17a00..e3753eb14c 100644 --- a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po @@ -14547,7 +14547,7 @@ msgstr "" msgid "" "Interface Statement" +"+10.1-RELEASE+and+Ports#Interface_statement\">Interface Statement" msgstr "" #: usr/local/www/interfaces.php:2265 @@ -14594,7 +14594,7 @@ msgstr "" msgid "" "Identity Association Statement" +"+10.1-RELEASE+and+Ports#Identity_association_statement\">Identity Association Statement" msgstr "" #: usr/local/www/interfaces.php:2299 @@ -14649,7 +14649,7 @@ msgstr "" msgid "" "Prefix Interface Statement" +"+10.1-RELEASE+and+Ports#Prefix_interface_statement\">Prefix Interface Statement" msgstr "" #: usr/local/www/interfaces.php:2338 @@ -14668,7 +14668,7 @@ msgstr "" msgid "" "Authentication Statement" +"+10.1-RELEASE+and+Ports#Authentication_statement\">Authentication Statement" msgstr "" #: usr/local/www/interfaces.php:2351 @@ -14691,7 +14691,7 @@ msgstr "" msgid "" "Keyinfo Statement" +"+10.1-RELEASE+and+Ports#Keyinfo_statement\">Keyinfo Statement" msgstr "" #: usr/local/www/interfaces.php:2367 @@ -14717,7 +14717,7 @@ msgstr "" #: usr/local/www/interfaces.php:2383 msgid "" "Configuration File Override" msgstr "" diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 78e6d37e15..69e19bf54c 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -2257,7 +2257,7 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), - - + - + foreach ($auth_servers as $auth_server_key => $auth_server): + $selected = ""; + if (in_array($auth_server_key, $authmodes)) + $selected = "selected=\"selected\""; + ?> + + + + + + - + + + + + + @@ -1089,13 +1089,13 @@ if ($savemsg) $desc): - $selected = ""; - if ($name == $pconfig['digest']) - $selected = " selected=\"selected\""; + $selected = ""; + if ($name == $pconfig['digest']) + $selected = " selected=\"selected\""; ?> - +
@@ -1108,13 +1108,13 @@ if ($savemsg) $desc): - $selected = ""; - if ($name == $pconfig['engine']) - $selected = " selected=\"selected\""; + $selected = ""; + if ($name == $pconfig['engine']) + $selected = " selected=\"selected\""; ?> - + @@ -1128,11 +1128,11 @@ if ($savemsg) $depthdesc): - $selected = ""; - if ($depth == $pconfig['cert_depth']) - $selected = " selected=\"selected\""; + $selected = ""; + if ($depth == $pconfig['cert_depth']) + $selected = " selected=\"selected\""; ?> - + @@ -1177,7 +1177,7 @@ if ($savemsg) "communications between this server and client " . "hosts expressed using CIDR (eg. 10.0.8.0/24). " . "The first network address will be assigned to " . - "the server virtual interface. The remaining " . + "the server virtual interface. The remaining " . "network addresses can optionally be assigned " . "to connecting clients. (see Address Pool)"); ?> @@ -1351,11 +1351,11 @@ if ($savemsg)
@@ -1690,7 +1690,7 @@ if ($savemsg)
. @@ -1785,8 +1785,8 @@ if ($savemsg) - - + +
@@ -824,28 +824,28 @@ if ($savemsg) -
-
@@ -994,20 +994,20 @@ if ($savemsg)
+
@@ -1914,10 +1914,10 @@ tuntap_change(); /* local utility functions */ function set_checked($var,& $chk) { - if($var) - $chk = "checked=\"checked\""; - else - $chk = ""; + if($var) + $chk = "checked=\"checked\""; + else + $chk = ""; } ?> From a087e197e6b1d93f5673b7c03f80cd6406eb06e4 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Mon, 23 Feb 2015 22:16:12 +0545 Subject: [PATCH 108/257] OpenVPN server improve handling of authmode Currently if the user is clicking around while they are setting up an OpenVPN server, they can do stuff like this: a) Select Server Mode - Remote Access (SSL/TLS + User Auth) b) Select something in Backend for authentication c) Change their mind and select Server Mode - Peer to Peer (SSL/TLS) d) Enter the other settings and Save Now the OpenVPN server config has an 'authmode' key in it. Probably does no harm, I suspect it will simply not be used when building the server.conf for Peer to Peer, but it looks a bit odd when analysing/diagnosing a config for problems. Other fields that are mode-specific have tests to only save the values at the end if the appropriate mode is the one finally selected. While I am here, I also constantly forget to click on "Local Database" authmode when setting up a new server. It gives the validation error message, then I click on "Local Database" again and save. Seems unnecessary - when defining a new OpenVPN server why not default this to have the first entry in the list be the one selected? So I did that. What do you think? 1 place less for many users to need to click. --- usr/local/www/vpn_openvpn_server.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/usr/local/www/vpn_openvpn_server.php b/usr/local/www/vpn_openvpn_server.php index 0777cb648e..cb38156419 100644 --- a/usr/local/www/vpn_openvpn_server.php +++ b/usr/local/www/vpn_openvpn_server.php @@ -370,7 +370,7 @@ if ($_POST) { if ($_POST['disable'] == "yes") $server['disable'] = true; $server['mode'] = $pconfig['mode']; - if (!empty($pconfig['authmode'])) + if (!empty($pconfig['authmode']) && (($pconfig['mode'] == "server_user") || ($pconfig['mode'] == "server_tls_user"))) $server['authmode'] = implode(",", $pconfig['authmode']); $server['protocol'] = $pconfig['protocol']; $server['dev_mode'] = $pconfig['dev_mode']; @@ -798,9 +798,13 @@ if ($savemsg)
From 5fd42bbb8332faee5fd5cefa8a765e2911883587 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Mon, 23 Feb 2015 22:31:34 +0545 Subject: [PATCH 110/257] Fix display style typo I could not see any difference in rendering of the page after fixing this, but it looks it it should be fixed. --- usr/local/www/vpn_openvpn_client.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/vpn_openvpn_client.php b/usr/local/www/vpn_openvpn_client.php index 2f46ca62bd..faf89f9812 100644 --- a/usr/local/www/vpn_openvpn_client.php +++ b/usr/local/www/vpn_openvpn_client.php @@ -1171,7 +1171,7 @@ if ($savemsg) $i++; endforeach; ?> - + From 3f141c9dc8e6610a7e4533742c1397b11c5e5f8e Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Tue, 24 Feb 2015 00:18:07 +0545 Subject: [PATCH 111/257] Preserve "add routers" value across loop for each interface Forum: https://forum.pfsense.org/index.php?topic=89302.0 If the user put "none" in the 'gateway' field for the DHCP settings of an interface, that would set $add_routers to false at line 742. Coming around the loop again for a subsequent interface, and going through the else line 744, nothing would set $add_routers back to true (actually back to the value originally calculated at line 461). Use a different var to remember the boolean value calculated at line 461 so it can be remembered and used as needed each time through the loop. I set Gateway "none" on my LAN and left it blank on OPT1 and came up with the same problem as the forum post - OPT1 got no " option routers" statement in dhcpd.conf After this code fix it looks good. --- etc/inc/services.inc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/etc/inc/services.inc b/etc/inc/services.inc index 37933585b5..42341033e6 100644 --- a/etc/inc/services.inc +++ b/etc/inc/services.inc @@ -458,13 +458,13 @@ EOD; $dhcpdconf .= "always-broadcast on\n"; $dhcpdifs = array(); - $add_routers = false; + $enable_add_routers = false; $gateways_arr = return_gateways_array(); /* only add a routers line if the system has any IPv4 gateway at all */ /* a static route has a gateway, manually overriding this field always works */ foreach($gateways_arr as $gwitem) { if($gwitem['ipprotocol'] == "inet") { - $add_routers = true; + $enable_add_routers = true; break; } } @@ -741,6 +741,7 @@ EOPP; } elseif ($dhcpifconf['gateway'] == "none") { $add_routers = false; } else { + $add_routers = $enable_add_routers; $routers = $ifcfgip; } if($add_routers) From 916d683eb92fd9c12a03d6bbf595015a392fb64e Mon Sep 17 00:00:00 2001 From: surrural Date: Mon, 9 Feb 2015 14:03:15 -0500 Subject: [PATCH 112/257] Add support for DNSimple (dnsimple.com) --- etc/inc/dyndns.class | 63 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 53 insertions(+), 10 deletions(-) diff --git a/etc/inc/dyndns.class b/etc/inc/dyndns.class index 2c6f944d0e..53e340c1e1 100644 --- a/etc/inc/dyndns.class +++ b/etc/inc/dyndns.class @@ -30,7 +30,8 @@ * - Eurodns (eurodns.com) * - GratisDNS (gratisdns.dk) * - City Network (citynetwork.se) - * - GleSYS (glesys.com) + * - GleSYS (glesys.com + * - DNSimple (dnsimple.com) * +----------------------------------------------------+ * Requirements: * - PHP version 4.0.2 or higher with the CURL Library and the PCRE Library @@ -67,13 +68,14 @@ * HE.net Tunnel - Last Tested: 28 June 2011 * SelfHost - Last Tested: 26 December 2011 * Amazon Route 53 - Last tested: 01 April 2012 - * DNS-O-Matic - Last Tested: 9 September 2010 - * CloudFlare - Last Tested: 30 May 2013 - * Eurodns - Last Tested: 27 June 2013 - * GratisDNS - Last Tested: 15 August 2012 - * OVH DynHOST - Last Tested: NEVER - * City Network - Last Tested: 13 November 2013 - * GleSYS - Last Tested: 3 February 2015 + * DNS-O-Matic - Last Tested: 9 September 2010 + * CloudFlare - Last Tested: 30 May 2013 + * Eurodns - Last Tested: 27 June 2013 + * GratisDNS - Last Tested: 15 August 2012 + * OVH DynHOST - Last Tested: NEVER + * City Network - Last Tested: 13 November 2013 + * GleSYS - Last Tested: 3 February 2015 + * DNSimple - Last Tested: 09 February 2015 * +====================================================+ * * @author E.Kristensen @@ -243,7 +245,8 @@ case 'eurodns': case 'gratisdns': case 'ovh-dynhost': - case 'citynetwork': + case 'citynetwork': + case 'dnsimple': $this->_update(); if($this->_dnsDummyUpdateDone == true) { // If a dummy update was needed, then sleep a while and do the update again to put the proper address back. @@ -670,6 +673,21 @@ $port = ":" . $this->_dnsPort; curl_setopt($ch, CURLOPT_URL, $server .$port . '?hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP); break; + case 'dnsimple': + /* Uses DNSimple's REST API + Requires username and Account API token passed in header + Piggybacks on Route 53's ZoneID field for DNSimple record ID + Data sent as JSON */ + $needsIP = TRUE; + $server = 'https://api.dnsimple.com/v1/domains/'; + $token = $this->_dnsUser . ':' . $this->_dnsPass; + $jsondata = '{"record":{"content":"' . $this->_dnsIP . '","ttl":"' . $this->_dnsTTL . '"}}'; + curl_setopt($ch, CURLOPT_HEADER, 1); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); + curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json','X-DNSimple-Token: ' . $token)); + curl_setopt($ch, CURLOPT_URL, $server . $this->_dnsHost . '/records/' . $this->_dnsZoneID); + curl_setopt($ch, CURLOPT_POSTFIELDS, $jsondata); + break; default: break; } @@ -1191,8 +1209,33 @@ $this->_debug($data); } break; + case 'dnsimple': + /* Responds with HTTP 200 on success. + Responds with HTTP 4xx on error. + Returns JSON data as body */ + $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); + $header = substr($data, 0, $header_size); + $body = substr($data, $header_size); + if (preg_match("/Status: 200\s/i", $header)) { + $status = "phpDynDNS ({$this->_dnsHost}): (Success) IP Address Updated Successfully!"; + $successful_update = true; + } else if (preg_match("/Status: 4\d\d\s/i", $header)) { + $arrbody = json_decode($body, true); + $message = $arrbody['message'] . "."; + if (isset($arrbody['errors']['content'])) { + foreach($arrbody['errors']['content'] as $key => $content) { + $message .= " " . $content . "."; + } + } + $status = "phpDynDNS ({$this->_dnsHost}): (Error) " . $message; + } else { + $status = "phpDynDNS ({$this->_dnsHost}): (Unknown Response)"; + log_error("phpDynDNS ({$this->_dnsHost}): PAYLOAD: {$body}"); + $this->_debug($body); + } + break; } - + if($successful_update == true) { /* Write WAN IP to cache file */ $wan_ip = $this->_checkIP(); From e29543d68692ad669faa4646abf8580301157768 Mon Sep 17 00:00:00 2001 From: surrural Date: Mon, 9 Feb 2015 14:05:06 -0500 Subject: [PATCH 113/257] Add support for DNSimple (dnsimple.com) --- etc/inc/services.inc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/etc/inc/services.inc b/etc/inc/services.inc index 42341033e6..cac21c46c6 100644 --- a/etc/inc/services.inc +++ b/etc/inc/services.inc @@ -38,8 +38,8 @@ pfSense_MODULE: utils */ -define('DYNDNS_PROVIDER_VALUES', 'citynetwork cloudflare custom custom-v6 dhs dnsexit dnsomatic dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns glesys gratisdns he-net he-net-v6 he-net-tunnelbroker loopia namecheap noip noip-free ods opendns ovh-dynhost route53 selfhost zoneedit'); -define('DYNDNS_PROVIDER_DESCRIPTIONS', 'City Network,CloudFlare,Custom,Custom (v6),DHS,DNSexit,DNS-O-Matic,DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,easyDNS,Euro Dns,freeDNS,GleSYS,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,SelfHost,ZoneEdit'); +define('DYNDNS_PROVIDER_VALUES', 'citynetwork cloudflare custom custom-v6 dhs dnsexit dnsimple dnsomatic dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns glesys gratisdns he-net he-net-v6 he-net-tunnelbroker loopia namecheap noip noip-free ods opendns ovh-dynhost route53 selfhost zoneedit'); +define('DYNDNS_PROVIDER_DESCRIPTIONS', 'City Network,CloudFlare,Custom,Custom (v6),DHS,DNSexit,DNSimple,DNS-O-Matic,DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,easyDNS,Euro Dns,freeDNS,GleSYS,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,SelfHost,ZoneEdit'); /* implement ipv6 route advertising daemon */ function services_radvd_configure($blacklist = array()) { From a39b78b50675e3809253ce6dd6937d1089ddbf0a Mon Sep 17 00:00:00 2001 From: surrural Date: Mon, 9 Feb 2015 14:09:21 -0500 Subject: [PATCH 114/257] Add support for DNSimple (dnsimple.com) --- usr/local/www/services_dyndns_edit.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/usr/local/www/services_dyndns_edit.php b/usr/local/www/services_dyndns_edit.php index 0cf95f1df2..80d1743f51 100644 --- a/usr/local/www/services_dyndns_edit.php +++ b/usr/local/www/services_dyndns_edit.php @@ -205,6 +205,7 @@ function _onTypeChange(type){ document.getElementById("r53_zoneid").style.display='none'; document.getElementById("r53_ttl").style.display='none'; break; + case "dnsimple": case "route53": document.getElementById("_resulttr").style.display = 'none'; document.getElementById("_urltr").style.display = 'none'; @@ -320,7 +321,8 @@ function _onTypeChange(type){

- +
+ @@ -373,6 +375,7 @@ function _onTypeChange(type){

+
@@ -381,6 +384,7 @@ function _onTypeChange(type){
+
From c19250a5b382546ccf9eb55e2827673a4dbba7ac Mon Sep 17 00:00:00 2001 From: surrural Date: Mon, 9 Feb 2015 14:14:00 -0500 Subject: [PATCH 115/257] Update dyndns.class --- etc/inc/dyndns.class | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/dyndns.class b/etc/inc/dyndns.class index 53e340c1e1..2430d67cb5 100644 --- a/etc/inc/dyndns.class +++ b/etc/inc/dyndns.class @@ -30,7 +30,7 @@ * - Eurodns (eurodns.com) * - GratisDNS (gratisdns.dk) * - City Network (citynetwork.se) - * - GleSYS (glesys.com + * - GleSYS (glesys.com) * - DNSimple (dnsimple.com) * +----------------------------------------------------+ * Requirements: From e0a4147b3b5eda4d0d859d0c81ee127677d746a0 Mon Sep 17 00:00:00 2001 From: surrural Date: Mon, 9 Feb 2015 14:17:03 -0500 Subject: [PATCH 116/257] Add support for DNSimple (dnsimple.com) --- etc/inc/dyndns.class | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/dyndns.class b/etc/inc/dyndns.class index 2430d67cb5..9f54403bc3 100644 --- a/etc/inc/dyndns.class +++ b/etc/inc/dyndns.class @@ -30,7 +30,7 @@ * - Eurodns (eurodns.com) * - GratisDNS (gratisdns.dk) * - City Network (citynetwork.se) - * - GleSYS (glesys.com) + * - GleSYS (glesys.com) * - DNSimple (dnsimple.com) * +----------------------------------------------------+ * Requirements: From d5b1a27904df2da0de16218eab9a1a6f59cd45f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Mon, 23 Feb 2015 21:20:41 +0100 Subject: [PATCH 117/257] Ticket #4445 do not write config and remove its cache when applying settings its just behaviour from dinosaur era and should have been cleanded long time ago. --- usr/local/www/firewall_nat.php | 3 --- usr/local/www/firewall_nat_out.php | 2 -- 2 files changed, 5 deletions(-) diff --git a/usr/local/www/firewall_nat.php b/usr/local/www/firewall_nat.php index f25bae9fe1..dcdfa46fee 100644 --- a/usr/local/www/firewall_nat.php +++ b/usr/local/www/firewall_nat.php @@ -63,11 +63,8 @@ if ($_POST) { if ($_POST['apply']) { - write_config(); - $retval = 0; - unlink_if_exists("/tmp/config.cache"); $retval |= filter_configure(); $savemsg = get_std_save_message($retval); diff --git a/usr/local/www/firewall_nat_out.php b/usr/local/www/firewall_nat_out.php index 4a4779e771..96d7a7bdda 100644 --- a/usr/local/www/firewall_nat_out.php +++ b/usr/local/www/firewall_nat_out.php @@ -64,8 +64,6 @@ if (!isset($config['nat']['outbound']['mode'])) $mode = $config['nat']['outbound']['mode']; if ($_POST['apply']) { - write_config(); - $retval = 0; $retval |= filter_configure(); From f29610b0cc5cebf73d99cbde8b1b94b6361bc874 Mon Sep 17 00:00:00 2001 From: Lorenz Schori Date: Tue, 24 Feb 2015 10:31:37 +0100 Subject: [PATCH 118/257] Fix PTR records for aliases in host overrides --- etc/inc/unbound.inc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/etc/inc/unbound.inc b/etc/inc/unbound.inc index 027375b20e..bbe802771c 100644 --- a/etc/inc/unbound.inc +++ b/etc/inc/unbound.inc @@ -513,9 +513,9 @@ function unbound_add_host_entries() { else continue; - if(!$added_ptr[$host['ip']]) { + if(!$added_ptr[$host['ipaddr']]) { $unbound_entries .= "local-data-ptr: \"{$host['ipaddr']} {$host['fqdn']}\"\n"; - $added_ptr[$host['ip']] = true; + $added_ptr[$host['ipaddr']] = true; } $unbound_entries .= "local-data: \"{$host['fqdn']} {$type} {$host['ipaddr']}\"\n"; if (isset($host['name'])) From 5a27b146335d174321fe9b46b45e3c4cb9bc8743 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Tue, 24 Feb 2015 15:40:29 -0300 Subject: [PATCH 119/257] isset is a better check here --- usr/local/www/services_ntpd.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/services_ntpd.php b/usr/local/www/services_ntpd.php index fb7820f927..05cc0a1e2b 100644 --- a/usr/local/www/services_ntpd.php +++ b/usr/local/www/services_ntpd.php @@ -154,7 +154,7 @@ if ($_POST) { $config['ntpd']['statsgraph'] = $_POST['statsgraph']; elseif (isset($config['ntpd']['statsgraph'])) unset($config['ntpd']['statsgraph']); - if (!empty($enable_rrd_graphing)) + if (isset($enable_rrd_graphing)) enable_rrd_graphing(); if (!empty($_POST['leaptxt'])) From 8104c3df32ae429dd8bf554dcc9b8dcafd09b796 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Tue, 24 Feb 2015 15:45:07 -0300 Subject: [PATCH 120/257] Initialize var and move unset outside the loop --- etc/inc/interfaces.inc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index 8271058b27..1f95f87779 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -3459,6 +3459,7 @@ function interface_dhcpv6_configure($interface = "wan", $wancfg) { $dhcp6cconf .= " script \"{$g['varetc_path']}/dhcp6c_{$interface}_script.sh\"; # we'd like some nameservers please\n"; $dhcp6cconf .= "};\n"; } else { + $trackiflist = array(); $iflist = link_interface_to_track6($interface); foreach ($iflist as $ifname => $ifcfg) { if (is_numeric($ifcfg['track6-prefix-id'])) @@ -3495,9 +3496,10 @@ function interface_dhcpv6_configure($interface = "wan", $wancfg) { $dhcp6cconf .= " sla-len {$wancfg['dhcp6-ia-pd-len']};\n"; $dhcp6cconf .= " };\n"; } - unset($preflen, $iflist, $ifcfg, $ifname, $trackiflist); + unset($preflen, $iflist, $ifcfg, $ifname); $dhcp6cconf .= "};\n"; } + unset($trackiflist); } // DHCP6 Config File Advanced From 10b92c5756c5d9aa4e183fa08fe8fe0ad2c12bd0 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Tue, 24 Feb 2015 16:08:19 -0300 Subject: [PATCH 121/257] When RADIUS auth is selected, radius protocol and server ip/host are mandatory. Fixes #4384 --- usr/local/www/services_captiveportal.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/usr/local/www/services_captiveportal.php b/usr/local/www/services_captiveportal.php index 41a904274e..a56a6fc4cd 100644 --- a/usr/local/www/services_captiveportal.php +++ b/usr/local/www/services_captiveportal.php @@ -210,6 +210,13 @@ if ($_POST) { $reqdfields = explode(" ", "zone cinterface"); $reqdfieldsn = array(gettext("Zone name"), gettext("Interface")); + if (isset($_POST['auth_method']) && $_POST['auth_method'] == "radius") { + $reqdfields[] = "radius_protocol"; + $reqdfieldsn[] = gettext("RADIUS Protocol"); + $reqdfields[] = "radiusip"; + $reqdfieldsn[] = gettext("Primary RADIUS server IP address"); + } + do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); /* make sure no interfaces are bridged or used on other zones */ From e173dd74fd009a4771552fb0e2cb3ee508072d30 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Wed, 25 Feb 2015 01:08:35 +0545 Subject: [PATCH 122/257] Code style for etc files --- etc/rc | 38 ++--- etc/rc.backup_rrd.sh | 2 +- etc/rc.banner | 73 ++++----- etc/rc.bootup | 101 ++++++------ etc/rc.captiveportal_configure | 42 ++--- etc/rc.captiveportal_configure_mac | 42 ++--- etc/rc.carpbackup | 60 +++---- etc/rc.carpmaster | 56 ++++--- etc/rc.cdrom | 20 +-- etc/rc.conf_mount_ro | 42 ++--- etc/rc.conf_mount_rw | 42 ++--- etc/rc.dhclient_cron | 46 +++--- etc/rc.dyndns.update | 52 +++--- etc/rc.expireaccounts | 21 +-- etc/rc.filter_configure | 42 ++--- etc/rc.filter_configure_sync | 42 ++--- etc/rc.filter_configure_xmlrpc | 52 +++--- etc/rc.filter_synchronize | 150 +++++++++++------- etc/rc.firmware | 100 ++++++------ etc/rc.firmware_auto | 82 +++++----- etc/rc.initial | 118 +++++++------- etc/rc.initial.defaults | 2 +- etc/rc.initial.firmware_update | 62 ++++---- etc/rc.initial.halt | 4 +- etc/rc.initial.password | 11 +- etc/rc.initial.ping | 16 +- etc/rc.initial.reboot | 2 +- etc/rc.initial.setlanip | 128 ++++++++------- etc/rc.initial.setports | 4 +- ...c.initial.store_config_to_removable_device | 14 +- etc/rc.initial.toggle_sshd | 4 +- etc/rc.interfaces_carp_configure | 46 +++--- etc/rc.interfaces_lan_configure | 46 +++--- etc/rc.interfaces_opt_configure | 48 +++--- etc/rc.interfaces_wan_configure | 58 +++---- etc/rc.kill_states | 11 +- etc/rc.linkup | 96 ++++++----- etc/rc.newipsecdns | 20 +-- etc/rc.newroutedns | 8 +- etc/rc.newwanip | 64 +++++--- etc/rc.newwanipv6 | 57 ++++--- etc/rc.notify_message | 52 +++--- etc/rc.ntpdate | 10 +- etc/rc.openvpn | 53 ++++--- etc/rc.packages | 42 ++--- etc/rc.php-fpm_restart | 2 +- etc/rc.php_ini_setup | 14 +- etc/rc.prunecaptiveportal | 18 +-- etc/rc.reload_all | 42 ++--- etc/rc.reload_interfaces | 42 ++--- etc/rc.restart_webgui | 4 +- etc/rc.restore_config_backup | 14 +- etc/rc.restore_full_backup | 2 +- etc/rc.savevoucher | 12 +- etc/rc.shutdown | 2 +- etc/rc.start_packages | 65 ++++---- etc/rc.update_alias_url_data | 14 +- etc/rc.update_bogons.sh | 28 ++-- etc/rc.update_urltables | 8 +- etc/sshd | 35 ++-- 60 files changed, 1266 insertions(+), 1117 deletions(-) diff --git a/etc/rc b/etc/rc index 52d342df95..820fa97af1 100755 --- a/etc/rc +++ b/etc/rc @@ -102,8 +102,8 @@ else # If /conf is a directory, convert it to a symlink to /cf/conf if [ -d "/conf" ]; then # If item is not a symlink then rm and recreate - CONFPOINTSTO=`readlink /conf` - if ! test "x$CONFPOINTSTO" = "x/cf/conf"; then + CONFPOINTSTO=`readlink /conf` + if ! test "x$CONFPOINTSTO" = "x/cf/conf"; then /bin/rm -rf /conf /bin/ln -s /cf/conf /conf fi @@ -225,8 +225,8 @@ if [ "$PLATFORM" = "cdrom" ] ; then /bin/mkdir /tmp/unionfs/confdefault /sbin/mount_unionfs /tmp/unionfs/usr /usr/ /sbin/mount_unionfs /tmp/unionfs/root /root/ - /sbin/mount_unionfs /tmp/unionfs/bin /bin/ - /sbin/mount_unionfs /tmp/unionfs/sbin /sbin/ + /sbin/mount_unionfs /tmp/unionfs/bin /bin/ + /sbin/mount_unionfs /tmp/unionfs/sbin /sbin/ /sbin/mount_unionfs /tmp/unionfs/boot /boot/ /sbin/mount_unionfs /tmp/unionfs/confdefault /conf.default/ echo "done." @@ -269,22 +269,22 @@ if [ ! -L /etc/hosts ]; then fi if [ ! -L /etc/resolv.conf ]; then - /bin/rm -rf /etc/resolv.conf - /bin/ln -s /var/etc/resolv.conf /etc/resolv.conf + /bin/rm -rf /etc/resolv.conf + /bin/ln -s /var/etc/resolv.conf /etc/resolv.conf fi if [ ! -L /etc/resolvconf.conf ]; then - /bin/rm -rf /etc/resolvconf.conf - /bin/ln -s /var/etc/resolvconf.conf /etc/resolvconf.conf + /bin/rm -rf /etc/resolvconf.conf + /bin/ln -s /var/etc/resolvconf.conf /etc/resolvconf.conf fi # Setup compatibility link for packages that # have trouble overriding the PREFIX configure # argument since we build our packages in a # separated PREFIX area -# Only create if symlink does not exist. +# Only create if symlink does not exist. if [ ! -h /tmp/tmp ]; then - /bin/ln -hfs / /tmp/tmp + /bin/ln -hfs / /tmp/tmp fi # Make sure our /tmp is 777 + Sticky @@ -296,13 +296,13 @@ fi if [ ! "$PLATFORM" = "cdrom" ] ; then # Malloc debugging check if [ -L /etc/malloc.conf ]; then - #ln -s aj /etc/malloc.conf + #ln -s aj /etc/malloc.conf /bin/rm /etc/malloc.conf fi fi if [ ! -L /etc/dhclient.conf ]; then - /bin/rm -rf /etc/dhclient.conf + /bin/rm -rf /etc/dhclient.conf fi if [ ! -d /var/tmp ]; then @@ -310,7 +310,7 @@ if [ ! -d /var/tmp ]; then fi if [ ! -d /cf/conf/backup/ ]; then - /bin/mkdir -p /cf/conf/backup/ + /bin/mkdir -p /cf/conf/backup/ fi set -T @@ -334,18 +334,18 @@ if [ ! ${DEFAULT_LOG_FILE_SIZE} ]; then fi for logfile in $LOG_FILES; do - if [ "$DISABLESYSLOGCLOG" -gt "0" ]; then + if [ "$DISABLESYSLOGCLOG" -gt "0" ]; then /usr/bin/touch /var/log/$logfile.log - else + else if [ ! -f /var/log/$logfile.log ]; then if [ "$ENABLEFIFOLOG" -gt "0" ]; then # generate fifolog files /usr/sbin/fifolog_create -s ${DEFAULT_LOG_FILE_SIZE} /var/log/$logfile.log - else + else /usr/local/sbin/clog -i -s ${DEFAULT_LOG_FILE_SIZE} /var/log/$logfile.log fi fi - fi + fi done # change permissions on newly created fifolog files. @@ -368,7 +368,7 @@ echo -n "." # Make sure /etc/rc.conf doesn't exist. if [ -f /etc/rc.conf ]; then - /bin/rm -rf /etc/rc.conf + /bin/rm -rf /etc/rc.conf fi if [ ! "$PLATFORM" = "jail" ]; then @@ -429,7 +429,7 @@ if [ -f $varrunpath/booting ]; then /bin/rm $varrunpath/booting fi -# If a shell was selected from recovery +# If a shell was selected from recovery # console then just drop to the shell now. if [ -f "/tmp/donotbootup" ]; then echo "Dropping to recovery shell." diff --git a/etc/rc.backup_rrd.sh b/etc/rc.backup_rrd.sh index 408068a6da..c14ffc714c 100755 --- a/etc/rc.backup_rrd.sh +++ b/etc/rc.backup_rrd.sh @@ -7,7 +7,7 @@ if [ -d "${RRDDBPATH}" ]; then [ -z "$NO_REMOUNT" ] && /etc/rc.conf_mount_rw [ -f "${CF_CONF_PATH}/rrd.tgz" ] && /bin/rm -f "${CF_CONF_PATH}"/rrd.tgz - + tgzlist="" for rrdfile in "${RRDDBPATH}"/*.rrd ; do diff --git a/etc/rc.banner b/etc/rc.banner index 901286f8c9..5fd95c242f 100755 --- a/etc/rc.banner +++ b/etc/rc.banner @@ -42,50 +42,51 @@ $product = $g['product_name']; $machine = trim(`uname -m`); $hideplatform = $g['hideplatform']; - - if(!$hideplatform) + + if (!$hideplatform) { $platformbanner = "-{$platform}"; - + } + print "*** Welcome to {$product} {$version}{$platformbanner} ({$machine}) on {$hostname} ***\n"; $iflist = get_configured_interface_with_descr(false, true); - foreach($iflist as $ifname => $friendly) { + foreach ($iflist as $ifname => $friendly) { /* point to this interface's config */ $ifconf = $config['interfaces'][$ifname]; /* look for 'special cases' */ - switch($ifconf['ipaddr']) { - case "dhcp": - $class = "/DHCP4"; - break; - case "pppoe": - $class = "/PPPoE"; - break; - case "pptp": - $class = "/PPTP"; - break; - case "l2tp": - $class = "/L2TP"; - break; - default: - $class = ""; - break; + switch ($ifconf['ipaddr']) { + case "dhcp": + $class = "/DHCP4"; + break; + case "pppoe": + $class = "/PPPoE"; + break; + case "pptp": + $class = "/PPTP"; + break; + case "l2tp": + $class = "/L2TP"; + break; + default: + $class = ""; + break; } - switch($ifconf['ipaddrv6']) { - case "dhcp6": - $class6 = "/DHCP6"; - break; - case "slaac": - $class6 = "/SLAAC"; - break; - case "6rd": - $class6 = "/6RD"; - break; - case "6to4": - $class6 = "/6to4"; - break; - case "track6": - $class6 = "/t6"; - break; + switch ($ifconf['ipaddrv6']) { + case "dhcp6": + $class6 = "/DHCP6"; + break; + case "slaac": + $class6 = "/SLAAC"; + break; + case "6rd": + $class6 = "/6RD"; + break; + case "6to4": + $class6 = "/6to4"; + break; + case "track6": + $class6 = "/t6"; + break; } $ipaddr = get_interface_ip($ifname); $subnet = get_interface_subnet($ifname); diff --git a/etc/rc.bootup b/etc/rc.bootup index 1adbe15716..ef26679e42 100755 --- a/etc/rc.bootup +++ b/etc/rc.bootup @@ -38,8 +38,8 @@ function rescue_detect_keypress() { // How long do you want the script to wait before moving on (in seconds) $timeout=9; echo "\n"; - echo "[ Press R to enter recovery mode or ]\n"; - echo "[ press I to launch the installer ]\n\n"; + echo "[ Press R to enter recovery mode or ]\n"; + echo "[ press I to launch the installer ]\n\n"; echo "(R)ecovery mode can assist by rescuing config.xml\n"; echo "from a broken hard disk installation, etc.\n\n"; echo "(I)nstaller may be invoked now if you do \n"; @@ -48,30 +48,31 @@ function rescue_detect_keypress() { echo "Timeout before auto boot continues (seconds): {$timeout}"; $key = null; exec("/bin/stty erase " . chr(8)); - while(!in_array($key, array("c", "C", "r","R", "i", "I", "~", "!"))) { - echo chr(8) . "{$timeout}"; - `/bin/stty -icanon min 0 time 25`; - $key = trim(`KEY=\`dd count=1 2>/dev/null\`; echo \$KEY`); - `/bin/stty icanon`; - // Decrement our timeout value - $timeout--; - // If we have reached 0 exit and continue on - if ($timeout == 0) - break; + while (!in_array($key, array("c", "C", "r","R", "i", "I", "~", "!"))) { + echo chr(8) . "{$timeout}"; + `/bin/stty -icanon min 0 time 25`; + $key = trim(`KEY=\`dd count=1 2>/dev/null\`; echo \$KEY`); + `/bin/stty icanon`; + // Decrement our timeout value + $timeout--; + // If we have reached 0 exit and continue on + if ($timeout == 0) { + break; + } } // If R or I was pressed do our logic here if (in_array($key, array("r", "R"))) { - putenv("TERM=cons25"); - echo "\n\nRecovery mode selected...\n"; - passthru("/usr/bin/env TERM=cons25 /bin/tcsh -c /scripts/lua_installer_rescue"); + putenv("TERM=cons25"); + echo "\n\nRecovery mode selected...\n"; + passthru("/usr/bin/env TERM=cons25 /bin/tcsh -c /scripts/lua_installer_rescue"); } elseif (in_array($key, array("i", "I"))) { - putenv("TERM=cons25"); - echo "\n\nInstaller mode selected...\n"; - passthru("/usr/bin/env TERM=cons25 /bin/tcsh -c /scripts/lua_installer"); - if(file_exists("/tmp/install_complete")) { - passthru("/etc/rc.reboot"); - exit; - } + putenv("TERM=cons25"); + echo "\n\nInstaller mode selected...\n"; + passthru("/usr/bin/env TERM=cons25 /bin/tcsh -c /scripts/lua_installer"); + if (file_exists("/tmp/install_complete")) { + passthru("/etc/rc.reboot"); + exit; + } } elseif (in_array($key, array("!", "~"))) { putenv("TERM=cons25"); echo "\n\nRecovery shell selected...\n"; @@ -141,8 +142,9 @@ system_dmesg_save(); system_check_reset_button(); /* remove previous firmware upgrade if present */ -if (file_exists("/root/firmware.tgz")) +if (file_exists("/root/firmware.tgz")) { unlink("/root/firmware.tgz"); +} /* start devd (dhclient now uses it) */ echo "Starting device manager (devd)..."; @@ -153,14 +155,15 @@ unmute_kernel_msgs(); echo "done.\n"; // Display rescue configuration option -if($g['platform'] == "cdrom") - rescue_detect_keypress(); +if ($g['platform'] == "cdrom") { + rescue_detect_keypress(); +} echo "Loading configuration..."; parse_config_bootup(); echo "done.\n"; -if($g['platform'] == "jail") { +if ($g['platform'] == "jail") { /* We must determine what network settings have been configured for us */ $wanif = "lo0"; /* defaults, if the jail admin hasn't set us up */ $ipaddr = "127.0.0.1"; @@ -181,28 +184,32 @@ if($g['platform'] == "jail") { $config['interfaces']['wan']['ipaddr'] = $ipaddr; $config['interfaces']['wan']['subnet'] = "32"; /* XXX right? */ $config['interfaces']['wan']['enable'] = true; - if($config['dhcpd']['lan']) + if ($config['dhcpd']['lan']) { unset($config['dhcpd']['lan']['enable']); + } unlink_if_exists('/conf/trigger_initial_wizard'); write_config(); } else { /* - * Determine if we need to throw a interface exception - * and ask the user to reassign interfaces. This will - * avoid a reboot and thats a good thing. + * Determine if we need to throw a interface exception + * and ask the user to reassign interfaces. This will + * avoid a reboot and that is a good thing. */ - while(is_interface_mismatch() == true) { + while (is_interface_mismatch() == true) { led_assigninterfaces(); if (isset($config['revision'])) { - if (file_exists("{$g['tmp_path']}/missing_interfaces")) + if (file_exists("{$g['tmp_path']}/missing_interfaces")) { echo "Warning: Configuration references interfaces that do not exist: " . file_get_contents("{$g['tmp_path']}/missing_interfaces") . "\n"; + } echo "\nNetwork interface mismatch -- Running interface assignment option.\n"; - } else + } else { echo "\nDefault interfaces not found -- Running interface assignment option.\n"; + } $ifaces = get_interface_list(); if (is_array($ifaces)) { - foreach($ifaces as $iface => $ifdata) + foreach ($ifaces as $iface => $ifdata) { interfaces_bring_up($iface); + } } set_networking_interfaces_ports(); led_kitt(); @@ -262,12 +269,14 @@ setup_microcode(); echo "done.\n"; /* set up interfaces */ -if(!$debugging) +if (!$debugging) { mute_kernel_msgs(); +} interfaces_configure(); interfaces_sync_setup(); -if(!$debugging) +if (!$debugging) { unmute_kernel_msgs(); +} /* re-make hosts file after configuring interfaces */ system_hosts_generate(); @@ -297,7 +306,7 @@ echo "Synchronizing user settings..."; local_sync_accounts(); echo "done.\n"; -if($realmem > 0 and $realmem < 65) { +if ($realmem > 0 and $realmem < 65) { echo "System has less than 65 megabytes of ram {$realmem}. Delaying webConfigurator startup.\n"; /* start webConfigurator up on final pass */ mwexec("/usr/local/sbin/pfSctl -c 'service restart webgui'"); @@ -339,7 +348,7 @@ system_console_configure(); /* start DHCP service */ services_dhcpd_configure(); -/* start dhcpleases dhpcp hosts leases program */ +/* start dhcpleases dhcp hosts leases program */ system_dhcpleases_configure(); /* start DHCP relay */ @@ -385,12 +394,12 @@ enable_rrd_graphing(); enable_watchdog(); /* if exists, execute the command */ -if($config['system']['afterbootupshellcmd'] <> "") { +if ($config['system']['afterbootupshellcmd'] <> "") { echo "Running afterbootupshellcmd {$config['system']['afterbootupshellcmd']}\n"; mwexec($config['system']['afterbootupshellcmd']); } -if($physmem < $g['minimum_ram_warning']) { +if ($physmem < $g['minimum_ram_warning']) { require_once("/etc/inc/notices.inc"); file_notice("{$g['product_name']}MemoryRequirements", "{$g['product_name']} requires at least {$g['minimum_ram_warning_text']} of RAM. Expect unusual performance. This platform is not supported.", "Memory", "", 1); set_sysctl(array( @@ -404,8 +413,9 @@ if($physmem < $g['minimum_ram_warning']) { $kern_hz = get_single_sysctl('kern.clockrate'); $kern_hz = substr($kern_hz, strpos($kern_hz, "hz = ") + 5); $kern_hz = substr($kern_hz, 0, strpos($kern_hz, ",")); -if($kern_hz == "1000") +if ($kern_hz == "1000") { set_single_sysctl("net.inet.tcp.rexmit_min" , "30"); +} /* start the igmpproxy daemon */ services_igmpproxy_configure(); @@ -420,14 +430,15 @@ activate_powerd(); prefer_ipv4_or_ipv6(); /* Remove the old shutdown binary if we kept it. */ -if (file_exists("/sbin/shutdown.old")) +if (file_exists("/sbin/shutdown.old")) { @unlink("/sbin/shutdown.old"); +} /* Resync / Reinstall packages if need be */ -if(file_exists('/conf/needs_package_sync')) { - if($config['installedpackages'] <> '' && is_array($config['installedpackages']['package'])) { +if (file_exists('/conf/needs_package_sync')) { + if ($config['installedpackages'] <> '' && is_array($config['installedpackages']['package'])) { require_once("pkg-utils.inc"); - if($g['platform'] == "pfSense" || $g['platform'] == "nanobsd") { + if ($g['platform'] == "pfSense" || $g['platform'] == "nanobsd") { mark_subsystem_dirty('packagelock'); pkg_reinstall_all(); clear_subsystem_dirty('packagelock'); diff --git a/etc/rc.captiveportal_configure b/etc/rc.captiveportal_configure index bd59361a18..c20dbdd1db 100755 --- a/etc/rc.captiveportal_configure +++ b/etc/rc.captiveportal_configure @@ -2,31 +2,31 @@ $dhcpv6ifconf) { - if ($dhcpv6ifconf['rainterface'] != $carp_iface) + if ($dhcpv6ifconf['rainterface'] != $carp_iface) { continue; + } $found = true; break; } - if ($found === true) + if ($found === true) { services_radvd_configure(); + } } $pluginparams = array(); diff --git a/etc/rc.carpmaster b/etc/rc.carpmaster index 93f60041cd..d313b31c31 100755 --- a/etc/rc.carpmaster +++ b/etc/rc.carpmaster @@ -2,31 +2,31 @@ $dhcpv6ifconf) { - if ($dhcpv6ifconf['rainterface'] != $carp_iface) + if ($dhcpv6ifconf['rainterface'] != $carp_iface) { continue; + } $found = true; break; } - if ($found === true) + if ($found === true) { services_radvd_configure(); + } } $pluginparams = array(); diff --git a/etc/rc.cdrom b/etc/rc.cdrom index 2018fe9ee7..f368644ba8 100755 --- a/etc/rc.cdrom +++ b/etc/rc.cdrom @@ -12,9 +12,9 @@ partsize="6m" export VARMFS_COPYDBPKG=yes for i in tmp varmfs etcmfs; do - if [ -f /etc/rc.d/$i ]; then - sh /etc/rc.d/$i start - fi + if [ -f /etc/rc.d/$i ]; then + sh /etc/rc.d/$i start + fi done # Start PFI @@ -24,13 +24,13 @@ done # a tiny mfs under /conf and populate with stock # configuration. if [ ! -f /conf/config.xml ]; then - echo -n "Generating a MFS /conf partition... " - device=$(mdconfig -a -t malloc -s ${partsize}) - newfs /dev/${device} > /dev/null 2>&1 - mount /dev/${device} /conf - cp /conf.default/* /conf - mount_nullfs /conf /cf/conf - echo "done." + echo -n "Generating a MFS /conf partition... " + device=$(mdconfig -a -t malloc -s ${partsize}) + newfs /dev/${device} > /dev/null 2>&1 + mount /dev/${device} /conf + cp /conf.default/* /conf + mount_nullfs /conf /cf/conf + echo "done." fi echo -n "Generating a MFS /home partition... " diff --git a/etc/rc.conf_mount_ro b/etc/rc.conf_mount_ro index 9e82fecdf8..f1d95c43cf 100755 --- a/etc/rc.conf_mount_ro +++ b/etc/rc.conf_mount_ro @@ -2,31 +2,31 @@ $interface) { $real_interface = get_real_interface($ifname); - if($config['interfaces'][$ifname]['ipaddr'] == "dhcp") { + if ($config['interfaces'][$ifname]['ipaddr'] == "dhcp") { $pid = find_dhclient_process($real_interface); - if($pid == 0 or !$pid) { + if ($pid == 0 or !$pid) { /* dhclient is not running for interface, kick it */ log_error("DHCLIENT was not running for {$real_interface} ... Launching new instance."); exec("/sbin/dhclient $real_interface"); diff --git a/etc/rc.dyndns.update b/etc/rc.dyndns.update index b350c224b4..717d71a032 100755 --- a/etc/rc.dyndns.update +++ b/etc/rc.dyndns.update @@ -2,31 +2,31 @@ strtotime($user['expires'])) { + if (strtotime("-1 day") > strtotime($user['expires'])) { echo "Disabling user {$user['name']} at index #{$index}\n"; //unset($config['system']['user'][$index]); $user['disabled'] = true; @@ -58,8 +58,9 @@ } } - if($removed > 0) + if ($removed > 0) { write_config("Expired {$removed} user accounts"); + } //print_r($config); diff --git a/etc/rc.filter_configure b/etc/rc.filter_configure index 92be68da1c..4fb1a45ddb 100755 --- a/etc/rc.filter_configure +++ b/etc/rc.filter_configure @@ -2,31 +2,31 @@ . - All rights reserved. + originally part of m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2004 Manuel Kasper . + All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. */ diff --git a/etc/rc.filter_synchronize b/etc/rc.filter_synchronize index a17e50e049..e411e7ea89 100755 --- a/etc/rc.filter_synchronize +++ b/etc/rc.filter_synchronize @@ -3,9 +3,9 @@ /* rc.filter_synchronize Copyright (C) 2004-2006 Scott Ullrich - Copyright (C) 2005 Bill Marquette - Copyright (C) 2006 Peter Allgeyer - Copyright (C) 2008 Ermal Luci + Copyright (C) 2005 Bill Marquette + Copyright (C) 2006 Peter Allgeyer + Copyright (C) 2008 Ermal Luci All rights reserved. originally part of m0n0wall (http://m0n0.ch/wall) @@ -54,7 +54,7 @@ function backup_vip_config_section() { return; $temp = array(); $temp['vip'] = array(); - foreach($config['virtualip']['vip'] as $section) { + foreach ($config['virtualip']['vip'] as $section) { if (($section['mode'] == 'proxyarp' || $section['mode'] == 'ipalias') && (strpos($section['interface'], '_vip') === FALSE) && (strpos($section['interface'], 'lo0') === FALSE)) @@ -62,14 +62,16 @@ function backup_vip_config_section() { if ($section['advskew'] <> "") { $section_val = intval($section['advskew']); $section_val=$section_val+100; - if ($section_val > 254) + if ($section_val > 254) { $section_val = 254; + } $section['advskew'] = $section_val; } if ($section['advbase'] <> "") { $section_val = intval($section['advbase']); - if ($section_val > 254) + if ($section_val > 254) { $section_val = 254; + } $section['advbase'] = $section_val; } $temp['vip'][] = $section; @@ -82,8 +84,9 @@ function remove_special_characters($string) { preg_match_all("/[a-zA-Z0-9\_\-]+/",$string,$match_array); $string = ""; foreach ($match_array[0] as $ma) { - if ($string <> "") + if ($string <> "") { $string .= " "; + } $string .= $ma; } return $string; @@ -92,7 +95,7 @@ function remove_special_characters($string) { function carp_check_version($url, $username, $password, $port = 80, $method = 'pfsense.host_firmware_version') { global $config, $g; - if(file_exists("{$g['varrun_path']}/booting") || platform_booting()) + if (file_exists("{$g['varrun_path']}/booting") || platform_booting()) return; $params = array( @@ -104,17 +107,18 @@ function carp_check_version($url, $username, $password, $port = 80, $method = 'p $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials($username, $password); - if($numberofruns > 0) + if ($numberofruns > 0) { $cli->setDebug(1); + } /* send our XMLRPC message and timeout after 240 seconds */ $resp = $cli->send($msg, "240"); - if(!is_object($resp)) { + if (!is_object($resp)) { $error = "A communications error occurred while attempting XMLRPC sync with username {$username} {$url}:{$port}."; - } elseif($resp->faultCode()) { + } elseif ($resp->faultCode()) { $error = "An error code was received while attempting XMLRPC sync with username {$username} {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); } else { $parsed_response = XML_RPC_decode($resp->value()); - if(!is_array($parsed_response)) { + if (!is_array($parsed_response)) { if (trim($parsed_response) == "Authentication failed") { $error = "An authentication failure occurred while trying to access {$url}:{$port} ({$method})."; log_error($error); @@ -127,8 +131,9 @@ function carp_check_version($url, $username, $password, $port = 80, $method = 'p update_filter_reload_status("The other member is on older configuration version of {$g['product_name']}. Sync will not be done to prevent problems!"); log_error("The other member is on older configuration version of {$g['product_name']}. Sync will not be done to prevent problems!"); return false; - } else + } else { return true; + } } } log_error($error); @@ -142,7 +147,7 @@ function carp_check_version($url, $username, $password, $port = 80, $method = 'p function carp_sync_xml($url, $username, $password, $sections, $port = 80, $method = 'pfsense.restore_config_section') { global $config, $g; - if(file_exists("{$g['varrun_path']}/booting") || platform_booting()) + if (file_exists("{$g['varrun_path']}/booting") || platform_booting()) return; update_filter_reload_status("Syncing CARP data to {$url}"); @@ -155,54 +160,60 @@ function carp_sync_xml($url, $username, $password, $sections, $port = 80, $metho $rulescnt = count($config_copy['nat']['outbound']['rule']); for ($x = 0; $x < $rulescnt; $x++) { $config_copy['nat']['outbound']['rule'][$x]['descr'] = remove_special_characters($config_copy['nat']['outbound']['rule'][$x]['descr']); - if (isset ($config_copy['nat']['outbound']['rule'][$x]['nosync'])) + if (isset ($config_copy['nat']['outbound']['rule'][$x]['nosync'])) { unset ($config_copy['nat']['outbound']['rule'][$x]); + } } } if (is_array($config_copy['nat']['rule'])) { $natcnt = count($config_copy['nat']['rule']); for ($x = 0; $x < $natcnt; $x++) { $config_copy['nat']['rule'][$x]['descr'] = remove_special_characters($config_copy['nat']['rule'][$x]['descr']); - if (isset ($config_copy['nat']['rule'][$x]['nosync'])) + if (isset ($config_copy['nat']['rule'][$x]['nosync'])) { unset ($config_copy['nat']['rule'][$x]); + } } } if (is_array($config_copy['filter']['rule'])) { $filtercnt = count($config_copy['filter']['rule']); for ($x = 0; $x < $filtercnt; $x++) { $config_copy['filter']['rule'][$x]['descr'] = remove_special_characters($config_copy['filter']['rule'][$x]['descr']); - if (isset ($config_copy['filter']['rule'][$x]['nosync'])) + if (isset ($config_copy['filter']['rule'][$x]['nosync'])) { unset ($config_copy['filter']['rule'][$x]); + } } } if (is_array($config_copy['aliases']['alias'])) { $aliascnt = count($config_copy['aliases']['alias']); for ($x = 0; $x < $aliascnt; $x++) { $config_copy['aliases']['alias'][$x]['descr'] = remove_special_characters($config_copy['aliases']['alias'][$x]['descr']); - if (isset ($config_copy['aliases']['alias'][$x]['nosync'])) + if (isset ($config_copy['aliases']['alias'][$x]['nosync'])) { unset ($config_copy['aliases']['alias'][$x]); + } } } if (is_array($config_copy['dnsmasq']['hosts'])) { $dnscnt = count($config_copy['dnsmasq']['hosts']); for ($x = 0; $x < $dnscnt; $x++) { $config_copy['dnsmasq']['hosts'][$x]['descr'] = remove_special_characters($config_copy['dnsmasq']['hosts'][$x]['descr']); - if (isset ($config_copy['dnsmasq']['hosts'][$x]['nosync'])) + if (isset ($config_copy['dnsmasq']['hosts'][$x]['nosync'])) { unset ($config_copy['dnsmasq']['hosts'][$x]); + } } } if (is_array($config_copy['ipsec']['tunnel'])) { $ipseccnt = count($config_copy['ipsec']['tunnel']); for ($x = 0; $x < $ipseccnt; $x++) { $config_copy['ipsec']['tunnel'][$x]['descr'] = remove_special_characters($config_copy['ipsec']['tunnel'][$x]['descr']); - if (isset ($config_copy['ipsec']['tunnel'][$x]['nosync'])) + if (isset ($config_copy['ipsec']['tunnel'][$x]['nosync'])) { unset ($config_copy['ipsec']['tunnel'][$x]); + } } } if (is_array($config_copy['dhcpd'])) { - foreach($config_copy['dhcpd'] as $dhcpif => $dhcpifconf) { - if($dhcpifconf['failover_peerip'] <> "") { + foreach ($config_copy['dhcpd'] as $dhcpif => $dhcpifconf) { + if ($dhcpifconf['failover_peerip'] <> "") { $int = guess_interface_from_ip($dhcpifconf['failover_peerip']); $intip = find_interface_ip($int); $config_copy['dhcpd'][$dhcpif]['failover_peerip'] = $intip; @@ -244,21 +255,22 @@ function carp_sync_xml($url, $username, $password, $sections, $port = 80, $metho $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials($username, $password); - if($numberofruns > 0) + if ($numberofruns > 0) { $cli->setDebug(1); + } /* send our XMLRPC message and timeout after 240 seconds */ $resp = $cli->send($msg, "240"); - if(!is_object($resp)) { + if (!is_object($resp)) { $error = "A communications error occurred while attempting XMLRPC sync with username {$username} {$url}:{$port}."; log_error($error); file_notice("sync_settings", $error, "Settings Sync", ""); - } elseif($resp->faultCode()) { + } elseif ($resp->faultCode()) { $error = "An error code was received while attempting XMLRPC sync with username {$username} {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "Settings Sync", ""); } else { $parsed_response = XML_RPC_decode($resp->value()); - if(!is_array($parsed_response) && trim($parsed_response) == "Authentication failed") { + if (!is_array($parsed_response) && trim($parsed_response) == "Authentication failed") { $error = "An authentication failure occurred while trying to access {$url}:{$port} ($method)."; log_error($error); file_notice("sync_settings", $error, "Settings Sync", ""); @@ -297,118 +309,144 @@ if (is_array($config['hasync'])) { /* if port is empty lets rely on the protocol selection */ $port = $config['system']['webgui']['port']; if (empty($port)) { - if ($config['system']['webgui']['protocol'] == "http") + if ($config['system']['webgui']['protocol'] == "http") { $port = "80"; - else + } else { $port = "443"; + } } - if(is_ipaddrv6($hasync['synchronizetoip'])) + if (is_ipaddrv6($hasync['synchronizetoip'])) { $hasync['synchronizetoip'] = "[{$hasync['synchronizetoip']}]"; + } $synchronizetoip .= $hasync['synchronizetoip']; if ($hasync['synchronizerules'] != "") { - if (!is_array($config['filter'])) + if (!is_array($config['filter'])) { $config['filter'] = array(); + } $sections[] = 'filter'; } if ($hasync['synchronizenat'] != "") { - if (!is_array($config['nat'])) + if (!is_array($config['nat'])) { $config['nat'] = array(); + } $sections[] = 'nat'; } if ($hasync['synchronizealiases'] != "") { - if (!is_array($config['aliases'])) + if (!is_array($config['aliases'])) { $config['aliases'] = array(); + } $sections[] = 'aliases'; } - if ($hasync['synchronizedhcpd'] != "" and is_array($config['dhcpd'])) + if ($hasync['synchronizedhcpd'] != "" and is_array($config['dhcpd'])) { $sections[] = 'dhcpd'; + } if ($hasync['synchronizewol'] != "") { - if (!is_array($config['wol'])) + if (!is_array($config['wol'])) { $config['wol'] = array(); + } $sections[] = 'wol'; } - if ($hasync['synchronizetrafficshaper'] != "" and is_array($config['shaper'])) + if ($hasync['synchronizetrafficshaper'] != "" and is_array($config['shaper'])) { $sections[] = 'shaper'; - if ($hasync['synchronizetrafficshaperlimiter'] != "" and is_array($config['dnshaper'])) + } + if ($hasync['synchronizetrafficshaperlimiter'] != "" and is_array($config['dnshaper'])) { $sections[] = 'dnshaper'; - if ($hasync['synchronizetrafficshaperlayer7'] != "" and is_array($config['l7shaper'])) + } + if ($hasync['synchronizetrafficshaperlayer7'] != "" and is_array($config['l7shaper'])) { $sections[] = 'l7shaper'; + } if ($hasync['synchronizestaticroutes'] != "") { - if (!is_array($config['staticroutes'])) + if (!is_array($config['staticroutes'])) { $config['staticroutes'] = array(); - if (!is_array($config['staticroutes']['route'])) + } + if (!is_array($config['staticroutes']['route'])) { $config['staticroutes']['route'] = array(); + } $sections[] = 'staticroutes'; - if (!is_array($config['gateways'])) + if (!is_array($config['gateways'])) { $config['gateways'] = array(); + } $sections[] = 'gateways'; } if ($hasync['synchronizevirtualip'] != "") { - if (!is_array($config['virtualip'])) + if (!is_array($config['virtualip'])) { $config['virtualip'] = array(); + } $sections[] = 'virtualip'; } if ($hasync['synchronizelb'] != "") { - if (!is_array($config['load_balancer'])) + if (!is_array($config['load_balancer'])) { $config['load_balancer'] = array(); + } $sections[] = 'load_balancer'; } if ($hasync['synchronizeipsec'] != "") { - if (!is_array($config['ipsec'])) + if (!is_array($config['ipsec'])) { $config['ipsec'] = array(); + } $sections[] = 'ipsec'; } if ($hasync['synchronizeopenvpn'] != "") { - if (!is_array($config['openvpn'])) + if (!is_array($config['openvpn'])) { $config['openvpn'] = array(); + } $sections[] = 'openvpn'; } if ($hasync['synchronizecerts'] != "" || $hasync['synchronizeopenvpn'] != "") { - if (!is_array($config['cert'])) + if (!is_array($config['cert'])) { $config['cert'] = array(); + } $sections[] = 'cert'; - if (!is_array($config['ca'])) + if (!is_array($config['ca'])) { $config['ca'] = array(); + } $sections[] = 'ca'; - if (!is_array($config['crl'])) + if (!is_array($config['crl'])) { $config['crl'] = array(); + } $sections[] = 'crl'; } if ($hasync['synchronizeusers'] != "") { $sections[] = 'user'; $sections[] = 'group'; - } + } if ($hasync['synchronizeauthservers'] != "") { $sections[] = 'authserver'; } if ($hasync['synchronizednsforwarder'] != "") { - if (is_array($config['dnsmasq'])) + if (is_array($config['dnsmasq'])) { $sections[] = 'dnsmasq'; - if (is_array($config['unbound'])) + } + if (is_array($config['unbound'])) { $sections[] = 'unbound'; + } } if ($hasync['synchronizeschedules'] != "" || $hasync['synchronizerules'] != "") { - if (!is_array($config['schedules'])) + if (!is_array($config['schedules'])) { $config['schedules'] = array(); + } $sections[] = 'schedules'; } - if ($hasync['synchronizecaptiveportal'] != "" and is_array($config['captiveportal'])) + if ($hasync['synchronizecaptiveportal'] != "" and is_array($config['captiveportal'])) { $sections[] = 'captiveportal'; - if ($hasync['synchronizecaptiveportal'] != "" and is_array($config['vouchers'])) + } + if ($hasync['synchronizecaptiveportal'] != "" and is_array($config['vouchers'])) { $sections[] = 'vouchers'; + } if (count($sections) <= 0) { log_error("Nothing has been configured to be synched. Skipping...."); return; } - if (empty($hasync['username'])) + if (empty($hasync['username'])) { $username = "admin"; - else + } else { $username = $hasync['username']; + } if (!carp_check_version($synchronizetoip, $username, $hasync['password'], $port)) return; @@ -429,7 +467,7 @@ if (is_array($config['hasync'])) { $error = "A communications error occurred while attempting Filter sync with username {$username} {$synchronizetoip}:{$port}."; log_error($error); file_notice("sync_settings", $error, "Settings Sync", ""); - } elseif($resp->faultCode()) { + } elseif ($resp->faultCode()) { $error = "An error code was received while attempting Filter sync with username {$username} {$synchronizetoip}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "Settings Sync", ""); diff --git a/etc/rc.firmware b/etc/rc.firmware index 3912291c0c..bde99dbca6 100755 --- a/etc/rc.firmware +++ b/etc/rc.firmware @@ -29,7 +29,7 @@ fi file_notice() { /usr/local/bin/php -q -d auto_prepend_file=config.inc < @@ -39,7 +39,7 @@ ENDOFF output_env_to_log() { date >> /conf/upgrade_log.txt echo "" >> /conf/upgrade_log.txt - + ls -lah /dev/ >> /conf/upgrade_log.txt echo "" >> /conf/upgrade_log.txt @@ -59,7 +59,7 @@ output_env_to_log() { backup_chflags() { TOPROCESS="bin lib libexec sbin usr" for files in $TOPROCESS; do - /usr/sbin/mtree -Pcp /${files} | bzip2 -9 > /tmp/chflags.dist.${files}.bz2 2>> /conf/upgrade_log.txt + /usr/sbin/mtree -Pcp /${files} | bzip2 -9 > /tmp/chflags.dist.${files}.bz2 2>> /conf/upgrade_log.txt done } @@ -89,30 +89,30 @@ binary_update() { remove_chflags cd /tmp/patches for i in `/usr/bin/tar tvzf $TGZ | egrep -v "(^d|_md5)" | nawk '{print $9;}'`; - do - FILE=`basename ${i}` - echo "Working on ${i}" - # Untar patch file and md5 files - /usr/bin/tar xzf ${TGZ} ${i} ${i}.old_file_md5 ${i}.new_patch_md5 ${i}.new_file_md5 2>>${ERR_F} + do + FILE=`basename ${i}` + echo "Working on ${i}" + # Untar patch file and md5 files + /usr/bin/tar xzf ${TGZ} ${i} ${i}.old_file_md5 ${i}.new_patch_md5 ${i}.new_file_md5 2>>${ERR_F} - # Apply patch - oldfile newfile patchfile - /usr/local/bin/bspatch /${i} /tmp/patched/${FILE} /tmp/patches/${i} 2>>${ERR_F} + # Apply patch - oldfile newfile patchfile + /usr/local/bin/bspatch /${i} /tmp/patched/${FILE} /tmp/patches/${i} 2>>${ERR_F} - OLD_FILE_MD5=`cat /tmp/patches/${i}.old_file_md5 2>/dev/null` - NEW_PATCH_MD5=`cat /tmp/patches/${i}.new_patch_md5 2>/dev/null` - NEW_FILE_MD5=`cat /tmp/patches/${i}.new_file_md5 2>/dev/null` - PATCHED_MD5=`/sbin/md5 -q /tmp/patched/${FILE} 2>/dev/null` + OLD_FILE_MD5=`cat /tmp/patches/${i}.old_file_md5 2>/dev/null` + NEW_PATCH_MD5=`cat /tmp/patches/${i}.new_patch_md5 2>/dev/null` + NEW_FILE_MD5=`cat /tmp/patches/${i}.new_file_md5 2>/dev/null` + PATCHED_MD5=`/sbin/md5 -q /tmp/patched/${FILE} 2>/dev/null` - if [ "$PATCHED_MD5" = "$NEW_PATCH_MD5" ]; then - /usr/bin/install -S /tmp/patched/${FILE} /${i} - else - #echo "${i} file does not match intended final md5." - echo "${i} file does not match intended final md5." >> ${ERR_F} - fi + if [ "$PATCHED_MD5" = "$NEW_PATCH_MD5" ]; then + /usr/bin/install -S /tmp/patched/${FILE} /${i} + else + #echo "${i} file does not match intended final md5." + echo "${i} file does not match intended final md5." >> ${ERR_F} + fi - /bin/rm /tmp/patched/${FILE} >> ${ERR_F} - /bin/rm /tmp/patches/${i} >> ${ERR_F} - /bin/rm /tmp/patches/${i}.* >> ${ERR_F} + /bin/rm /tmp/patched/${FILE} >> ${ERR_F} + /bin/rm /tmp/patches/${i} >> ${ERR_F} + /bin/rm /tmp/patches/${i}.* >> ${ERR_F} done /bin/rm -rf /tmp/patched /tmp/patches >> ${ERR_F} restore_chflags @@ -123,7 +123,7 @@ enable) touch /conf/upgrade_log.txt echo "" >> /conf/upgrade_log.txt echo "Enable" >> /conf/upgrade_log.txt - echo "" >> /conf/upgrade_log.txt + echo "" >> /conf/upgrade_log.txt /etc/rc.conf_mount_ro ;; auto) @@ -148,7 +148,7 @@ pfSenseNanoBSDupgrade) echo "You cannot use a full file for upgrade. Please use a file labelled nanobsd upgrade." file_notice "NanoBSDUpgradeFailure" "You have attempted to use a full NanoBSD installation file as an upgrade. Please use a NanoBSD file labelled 'upgrade' instead." rm -f $IMG - /etc/rc.conf_mount_ro + /etc/rc.conf_mount_ro exit 1 fi @@ -157,7 +157,7 @@ pfSenseNanoBSDupgrade) echo "NanoBSD Firmware upgrade in progress..." >> /conf/upgrade_log.txt 2>&1 echo "NanoBSD Firmware upgrade in progress..." | wall /etc/rc.notify_message -e -g -m "NanoBSD Firmware upgrade in progress..." - + # backup config /bin/mkdir -p /tmp/configbak cp -Rp /conf/* /tmp/configbak 2>/dev/null @@ -177,7 +177,7 @@ pfSenseNanoBSDupgrade) # grab the boot device, example ad1, ad0 BOOT_DRIVE=`/sbin/glabel list | /usr/bin/grep -B2 ufs/pfsense | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' ' | /usr/bin/cut -d's' -f1` # test the slice. if we are on slice 1 we need to flash 2 and vice versa - if [ `echo $REAL_BOOT_DEVICE | /usr/bin/grep "s1"` ]; then + if [ `echo $REAL_BOOT_DEVICE | /usr/bin/grep "s1"` ]; then SLICE="2" OLDSLICE="1" TOFLASH="${BOOT_DRIVE}s${SLICE}" @@ -187,7 +187,7 @@ pfSenseNanoBSDupgrade) OLD_UFS_ID="0" else SLICE="1" - OLDSLICE="2" + OLDSLICE="2" TOFLASH="${BOOT_DRIVE}s${SLICE}" COMPLETE_PATH="${BOOT_DRIVE}s${SLICE}a" GLABEL_SLICE="pfsense0" @@ -202,7 +202,7 @@ pfSenseNanoBSDupgrade) echo "COMPLETE_PATH ${COMPLETE_PATH}" >> /conf/upgrade_log.txt echo "GLABEL_SLICE ${GLABEL_SLICE}" >> /conf/upgrade_log.txt - # First ensure the new file can fit inside the + # First ensure the new file can fit inside the # slice that we are going to be operating on. NEW_IMG_SIZE=`echo $((\`gzip -l ${IMG} | grep -v compressed | awk '{ print $2}'\` / 1024 / 1024))` SIZE=`/sbin/fdisk ${COMPLETE_PATH} | /usr/bin/grep Meg | /usr/bin/awk '{ print $5 }' | /usr/bin/cut -d"(" -f2` @@ -218,13 +218,13 @@ pfSenseNanoBSDupgrade) rm -f /var/run/firmwarelock.dirty rm -f /var/run/firmware.lock rm -f ${IMG} - /etc/rc.conf_mount_ro + /etc/rc.conf_mount_ro exit 1 fi # Output environment information to log file output_env_to_log - + # Grab a before upgrade look at fdisk echo "" >> /conf/fdisk_upgrade_log.txt echo "Before upgrade fdisk/bsdlabel" >> /conf/fdisk_upgrade_log.txt @@ -234,7 +234,7 @@ pfSenseNanoBSDupgrade) bsdlabel -A ${BOOT_DRIVE}s3 >> /conf/fdisk_upgrade_log.txt echo "---------------------------------------------------------------" >> /conf/fdisk_upgrade_log.txt echo "" >> /conf/fdisk_upgrade_log.txt - + # Log that we are really doing a NanoBSD upgrade echo "" >> /conf/upgrade_log.txt echo "NanoBSD upgrade starting" >> /conf/upgrade_log.txt @@ -242,7 +242,7 @@ pfSenseNanoBSDupgrade) # Remove TOFLASH and get ready for new flash image echo "" >> /conf/upgrade_log.txt - echo "dd if=/dev/zero of=/dev/${TOFLASH} bs=1m count=1" >> /conf/upgrade_log.txt + echo "dd if=/dev/zero of=/dev/${TOFLASH} bs=1m count=1" >> /conf/upgrade_log.txt dd if=/dev/zero of=/dev/${TOFLASH} bs=1m count=1 >> /conf/upgrade_log.txt 2>&1 # Stream gzipped image to dd and explode image to new area @@ -259,7 +259,7 @@ pfSenseNanoBSDupgrade) bsdlabel -A ${BOOT_DRIVE}s3 >> /conf/fdisk_upgrade_log.txt echo "---------------------------------------------------------------" >> /conf/fdisk_upgrade_log.txt echo "" >> /conf/fdisk_upgrade_log.txt - + # Ensure that our new system is sound and bail if it is not and file a notice echo "" >> /conf/upgrade_log.txt echo "/sbin/fsck_ufs -y /dev/${COMPLETE_PATH}" >> /conf/upgrade_log.txt @@ -269,7 +269,7 @@ pfSenseNanoBSDupgrade) rm -f $IMG rm -f /var/run/firmwarelock.dirty rm -f /var/run/firmware.lock - /etc/rc.conf_mount_ro + /etc/rc.conf_mount_ro exit 1 fi @@ -297,7 +297,7 @@ pfSenseNanoBSDupgrade) cp /boot/loader.conf.local /tmp/$GLABEL_SLICE/boot/loader.conf.local fi - # If /tmp/$GLABEL_SLICE/tmp/post_upgrade_command exists + # If /tmp/$GLABEL_SLICE/tmp/post_upgrade_command exists # after update then execute the command. echo "Checking for post_upgrade_command..." >> /conf/upgrade_log.txt if [ -f /tmp/$GLABEL_SLICE/tmp/post_upgrade_command ]; then @@ -327,7 +327,7 @@ pfSenseNanoBSDupgrade) # Unmount newly prepared slice umount /tmp/$GLABEL_SLICE - + sync # Set active mount slice in fdisk @@ -417,7 +417,7 @@ pfSenseupgrade) remove_chflags # Do we have a pre-upgrade hook in the update file? - if [ `tar tvzf $IMG | grep /tmp/pre_upgrade_command | wc -l` -gt 0 ]; then + if [ `tar tvzf $IMG | grep /tmp/pre_upgrade_command | wc -l` -gt 0 ]; then tar xzvf $IMG -C / ./tmp/pre_upgrade_command >> /conf/upgrade_log.txt 2>&1 chmod a+rx /tmp/pre_upgrade_command >> /conf/upgrade_log.txt 2>&1 sh /tmp/pre_upgrade_command >> /conf/upgrade_log.txt 2>&1 @@ -426,7 +426,7 @@ pfSenseupgrade) echo "Firmware upgrade in progress..." >> /conf/upgrade_log.txt 2>&1 echo "Firmware upgrade in progress..." | wall /etc/rc.notify_message -e -g -m "Firmware upgrade in progress..." - + # backup config [ -d /tmp/configbak ] && rm -rf /tmp/configbak /bin/mkdir -p /tmp/configbak @@ -443,17 +443,17 @@ pfSenseupgrade) /usr/local/sbin/check_reload_status echo "Image installed $IMG." >> /conf/upgrade_log.txt 2>&1 - # process custom image if its passed - if [ $# -eq 3 ]; then - if [ -f $CUSTOMIMG ]; then - echo "Custom image $CUSTOMIMG found." >> /conf/upgrade_log.txt 2>&1 - echo "Custom image ($CUSTOMIMG) found." >> /conf/upgrade_log.txt 2>&1 - PWD_DIR=`pwd` - cd / && /usr/bin/tar xzPUf $CUSTOMIMG >> /conf/upgrade_log.txt 2>&1 - cd $PWD_DIR - echo "Custom image $CUSTOMIMG installed." >> /conf/upgrade_log.txt 2>&1 - fi - fi + # process custom image if its passed + if [ $# -eq 3 ]; then + if [ -f $CUSTOMIMG ]; then + echo "Custom image $CUSTOMIMG found." >> /conf/upgrade_log.txt 2>&1 + echo "Custom image ($CUSTOMIMG) found." >> /conf/upgrade_log.txt 2>&1 + PWD_DIR=`pwd` + cd / && /usr/bin/tar xzPUf $CUSTOMIMG >> /conf/upgrade_log.txt 2>&1 + cd $PWD_DIR + echo "Custom image $CUSTOMIMG installed." >> /conf/upgrade_log.txt 2>&1 + fi + fi # restore config cp -Rp /tmp/configbak/* /conf 2>/dev/null diff --git a/etc/rc.firmware_auto b/etc/rc.firmware_auto index be5da9196a..33ef2b66d1 100755 --- a/etc/rc.firmware_auto +++ b/etc/rc.firmware_auto @@ -34,53 +34,53 @@ echo " Package MD5: ${PMD}" | logger -p daemon.info -i -t AutoUpgrade echo "Downloaded MD5: ${MD}" | logger -p daemon.info -i -t AutoUpgrade if [ "$PMD" = "" ]; then - echo "Package MD5 is null md5. Require proxy auth?" | logger -p daemon.info -i -t AutoUpgrade - exit 1 + echo "Package MD5 is null md5. Require proxy auth?" | logger -p daemon.info -i -t AutoUpgrade + exit 1 fi if [ "$MD" = "" ]; then - echo "Downloaded MD5 is null md5. Require proxy auth?" | logger -p daemon.info -i -t AutoUpgrade - exit 1 + echo "Downloaded MD5 is null md5. Require proxy auth?" | logger -p daemon.info -i -t AutoUpgrade + exit 1 fi if [ "$PMD" = "$MD" ]; then - echo "MD5's match." | logger -p daemon.info -i -t AutoUpgrade - echo "Beginning ${product} upgrade." | wall - if [ "$PLATFORM" = "net45xx" ]; then - /usr/local/bin/php /etc/rc.conf_mount_rw - fi - if [ "$PLATFORM" = "wrap" ]; then - /usr/local/bin/php /etc/rc.conf_mount_rw - fi - if [ "$PLATFORM" = "nanobsd" ]; then - /usr/local/bin/php /etc/rc.conf_mount_rw - fi - if [ -r "/tmp/custom.tgz" ]; then - sh /etc/rc.firmware pfSenseupgrade /tmp/latest.tgz /tmp/custom.tgz - else - if [ "$PLATFORM" = "nanobsd" ]; then - sh /etc/rc.firmware pfSenseNanoBSDupgrade /tmp/latest.tgz - else - sh /etc/rc.firmware pfSenseupgrade /tmp/latest.tgz - fi - fi - if [ "$PLATFORM" = "wrap" ]; then - /bin/sync - sleep 5 - /usr/local/bin/php /etc/rc.conf_mount_ro - if [ -e /etc/init_bootloader.sh ]; then - sh /etc/init_bootloader.sh - fi - fi - if [ "$PLATFORM" = "net45xx" ]; then - /bin/sync - sleep 5 - /usr/local/bin/php /etc/rc.conf_mount_ro - if [ -e /etc/init_bootloader.sh ]; then - sh /etc/init_bootloader.sh - fi - fi - exit 0 + echo "MD5's match." | logger -p daemon.info -i -t AutoUpgrade + echo "Beginning ${product} upgrade." | wall + if [ "$PLATFORM" = "net45xx" ]; then + /usr/local/bin/php /etc/rc.conf_mount_rw + fi + if [ "$PLATFORM" = "wrap" ]; then + /usr/local/bin/php /etc/rc.conf_mount_rw + fi + if [ "$PLATFORM" = "nanobsd" ]; then + /usr/local/bin/php /etc/rc.conf_mount_rw + fi + if [ -r "/tmp/custom.tgz" ]; then + sh /etc/rc.firmware pfSenseupgrade /tmp/latest.tgz /tmp/custom.tgz + else + if [ "$PLATFORM" = "nanobsd" ]; then + sh /etc/rc.firmware pfSenseNanoBSDupgrade /tmp/latest.tgz + else + sh /etc/rc.firmware pfSenseupgrade /tmp/latest.tgz + fi + fi + if [ "$PLATFORM" = "wrap" ]; then + /bin/sync + sleep 5 + /usr/local/bin/php /etc/rc.conf_mount_ro + if [ -e /etc/init_bootloader.sh ]; then + sh /etc/init_bootloader.sh + fi + fi + if [ "$PLATFORM" = "net45xx" ]; then + /bin/sync + sleep 5 + /usr/local/bin/php /etc/rc.conf_mount_ro + if [ -e /etc/init_bootloader.sh ]; then + sh /etc/init_bootloader.sh + fi + fi + exit 0 fi echo "MD5's do not match. Upgrade aborted." | logger -p daemon.info -i -t AutoUpgrade diff --git a/etc/rc.initial b/etc/rc.initial index df42588fe8..45b781caf3 100755 --- a/etc/rc.initial +++ b/etc/rc.initial @@ -69,14 +69,14 @@ else fi for i in /var/db/pfi/capable_*; do - if [ -f $i -a ! -L /cf/conf ]; then - option98="98) Move configuration file to removable device" - break - fi + if [ -f $i -a ! -L /cf/conf ]; then + option98="98) Move configuration file to removable device" + break + fi done if [ "$PLATFORM" = "cdrom" ]; then - option99="99) Install ${product} to a hard drive, etc." + option99="99) Install ${product} to a hard drive, etc." fi # display a cheap menu @@ -103,78 +103,78 @@ echo # see what the user has chosen case ${opmode} in 0) - exit && exit && logout - ;; + exit && exit && logout + ;; 1) - /etc/rc.initial.setports - ;; + /etc/rc.initial.setports + ;; 2) - /etc/rc.initial.setlanip - ;; + /etc/rc.initial.setlanip + ;; 3) - /etc/rc.initial.password - ;; + /etc/rc.initial.password + ;; 4) - /etc/rc.initial.defaults - ;; + /etc/rc.initial.defaults + ;; 5) - /etc/rc.initial.reboot - ;; + /etc/rc.initial.reboot + ;; 6) - /etc/rc.initial.halt - ;; + /etc/rc.initial.halt + ;; 7) - /etc/rc.initial.ping - ;; + /etc/rc.initial.ping + ;; 8) - /bin/tcsh - ;; + /bin/tcsh + ;; 9) - /usr/local/sbin/pftop - ;; + /usr/local/sbin/pftop + ;; 10) - /usr/local/sbin/clog -f /var/log/filter.log - ;; + /usr/local/sbin/clog -f /var/log/filter.log + ;; 11 | 111) - /etc/rc.restart_webgui - ;; + /etc/rc.restart_webgui + ;; 12) - /usr/local/sbin/pfSsh.php - ;; -13) - php -f /etc/rc.initial.firmware_update - ;; -14) - php -f /etc/rc.initial.toggle_sshd - ;; + /usr/local/sbin/pfSsh.php + ;; +13) + php -f /etc/rc.initial.firmware_update + ;; +14) + php -f /etc/rc.initial.toggle_sshd + ;; 15) - /etc/rc.restore_config_backup - ;; + /etc/rc.restore_config_backup + ;; 16) - /etc/rc.php-fpm_restart - ;; + /etc/rc.php-fpm_restart + ;; 98) - if [ ! -f /tmp/config_moved ]; then - /etc/rc.initial.store_config_to_removable_device - fi - ;; + if [ ! -f /tmp/config_moved ]; then + /etc/rc.initial.store_config_to_removable_device + fi + ;; 99) - if [ -e /dev/ukbd0 ]; then - env TERM=cons25 /scripts/lua_installer - else - /scripts/lua_installer - fi - ;; + if [ -e /dev/ukbd0 ]; then + env TERM=cons25 /scripts/lua_installer + else + /scripts/lua_installer + fi + ;; 100) - if grep "$WORD" "$CONFIG"; then - links "https://localhost" - else - links "http://localhost" - fi - ;; + if grep "$WORD" "$CONFIG"; then + links "https://localhost" + else + links "http://localhost" + fi + ;; "") - kill $PPID ; exit - ;; + kill $PPID ; exit + ;; esac done diff --git a/etc/rc.initial.defaults b/etc/rc.initial.defaults index 5e7442c1a1..6c7d13dbe1 100755 --- a/etc/rc.initial.defaults +++ b/etc/rc.initial.defaults @@ -57,6 +57,6 @@ EOD; system_reboot_sync(); } - + fclose($fp); ?> diff --git a/etc/rc.initial.firmware_update b/etc/rc.initial.firmware_update index 5c8a3e8a2f..3c6a4ee0c9 100755 --- a/etc/rc.initial.firmware_update +++ b/etc/rc.initial.firmware_update @@ -11,17 +11,19 @@ echo "Starting the {$g['product_name']} console firmware update system"; require("functions.inc"); echo "."; -if(isset($config['system']['firmware']['alturl']['enable'])) +if(isset($config['system']['firmware']['alturl']['enable'])) { $updater_url = "{$config['system']['firmware']['alturl']['firmwareurl']}"; -else +} else { $updater_url = $g['update_url']; +} $nanosize = ""; if ($g['platform'] == "nanobsd") { - if (file_exists("/etc/nano_use_vga.txt")) + if (file_exists("/etc/nano_use_vga.txt")) { $nanosize = "-nanobsd-vga-"; - else + } else { $nanosize = "-nanobsd-"; + } $nanosize .= strtolower(trim(file_get_contents("/etc/nanosize.txt"))); $update_filename = "latest{$nanosize}.img.gz"; @@ -55,28 +57,28 @@ switch ($command) { case "1": echo "\nEnter the URL to the .tgz or .img.gz update file. \nType 'auto' to use {$autoupdateurl}\n> "; $url = chop(fgets($fp)); - if(!$url) { + if (!$url) { fclose($fp); die; } - if($url == "auto") { + if ($url == "auto") { $url = $autoupdateurl; } $status = does_url_exist($url); - if($status) { + if ($status) { conf_mount_rw(); mark_subsystem_dirty('firmware'); unlink_if_exists("/root/firmware.tgz"); echo "\nFetching file... "; download_file_with_progress_bar($url, '/root/firmware.tgz'); - if(!file_exists("/root/firmware.tgz")) { + if (!file_exists("/root/firmware.tgz")) { echo "Something went wrong during file transfer. Exiting.\n\n"; fclose($fp); clear_subsystem_dirty('firmware'); die; } $status = does_url_exist("$url.sha256"); - if($status) { + if ($status) { echo "\nFetching sha256... "; download_file_with_progress_bar($url . ".sha256", '/root/firmware.tgz.sha256'); echo "\n"; @@ -92,12 +94,12 @@ switch ($command) { die; } } - if(file_exists("/root/firmware.tgz.sha256")) { + if (file_exists("/root/firmware.tgz.sha256")) { $source_sha256 = trim(`cat /root/firmware.tgz.sha256 | awk '{ print \$4 }'`,"\r"); $file_sha256 = trim(`sha256 /root/firmware.tgz | awk '{ print \$4 }'`,"\r"); echo "URL sha256: $source_sha256\n"; echo "Downloaded file sha256: $file_sha256\n"; - if($source_sha256 <> $file_sha256) { + if ($source_sha256 <> $file_sha256) { echo "\n\nsha256 checksum does not match. Cancelling upgrade.\n\n"; unlink_if_exists("/root/firmware.tgz.sha256"); fclose($fp); @@ -107,10 +109,10 @@ switch ($command) { echo "\nsha256 checksum matches.\n"; unlink_if_exists("/root/firmware.tgz.sha256"); } - if(strstr($url,"bdiff")) { + if (strstr($url,"bdiff")) { echo "Binary DIFF upgrade file detected...\n"; $type = "bdiff"; - } elseif(strstr($url,"nanobsd")) { + } elseif (strstr($url,"nanobsd")) { echo "NanoBSD upgrade file detected...\n"; $type = "nanobsd"; } else { @@ -123,15 +125,17 @@ switch ($command) { case "2": echo "\nEnter the complete path to the .tgz or .img.gz update file: "; $path = chop(fgets($fp)); - if(!$path) { + if (!$path) { fclose($fp); die; } - if(stristr($path,"bdiff")) + if (stristr($path,"bdiff")) { $type = "bdiff"; - if(stristr($path,"nanobsd")) - $type = "nanobsd"; - if(file_exists($path)) { + } + if (stristr($path,"nanobsd")) { + $type = "nanobsd"; + } + if (file_exists($path)) { mark_subsystem_dirty('firmware'); do_upgrade($path, $type); clear_subsystem_dirty('firmware'); @@ -144,15 +148,16 @@ switch ($command) { function do_upgrade($path, $type) { global $g, $fp; - + $sigchk = verify_digital_signature($path); - if ($sigchk == 1) + if ($sigchk == 1) { $sig_warning = "The digital signature on this image is invalid."; - else if ($sigchk == 2) + } elseif ($sigchk == 2) { $sig_warning = "This image is not digitally signed."; - else if (($sigchk == 3) || ($sigchk == 4)) + } elseif (($sigchk == 3) || ($sigchk == 4)) { $sig_warning = "There has been an error verifying the signature on this image."; - if($sig_warning) { + } + if ($sig_warning) { $sig_warning = "\nWARNING! ACHTUNG! DANGER!\n\n{$sig_warning}\n\n" . "This means that the image you uploaded is not an official/supported image and\n" . "may lead to unexpected behavior or security compromises.\n\n" . @@ -161,7 +166,7 @@ function do_upgrade($path, $type) { "Do you want to install this image anyway at your own risk [n]?"; echo $sig_warning; $command = strtoupper(chop(fgets($fp))); - if(strtoupper($command) == "Y" or strtoupper($command) == "Y" or strtoupper($command) == "YES") { + if (strtoupper($command) == "Y" or strtoupper($command) == "Y" or strtoupper($command) == "YES") { echo "\nContinuing upgrade..."; } else { echo "\nUpgrade cancelled.\n\n"; @@ -170,14 +175,15 @@ function do_upgrade($path, $type) { } mark_subsystem_dirty('firmwarelock'); echo "\nOne moment please...\nInvoking firmware upgrade..."; - if($type == "bdiff") + if ($type == "bdiff") { mwexec_bg("/etc/rc.firmware delta_update $path"); - elseif($type == "nanobsd") + } elseif ($type == "nanobsd") { mwexec_bg("/etc/rc.firmware pfSenseNanoBSDupgrade $path"); - else + } else { mwexec_bg("/etc/rc.firmware pfSenseupgrade $path"); + } sleep(10); - while(is_subsystem_dirty('firmwarelock')) { + while (is_subsystem_dirty('firmwarelock')) { sleep(1); echo "."; } diff --git a/etc/rc.initial.halt b/etc/rc.initial.halt index b26a49e0fd..39c408692f 100755 --- a/etc/rc.initial.halt +++ b/etc/rc.initial.halt @@ -55,7 +55,7 @@ EOD; system_halt(); } - + fclose($fp); - + ?> diff --git a/etc/rc.initial.password b/etc/rc.initial.password index 1de1a798b9..f694739b02 100755 --- a/etc/rc.initial.password +++ b/etc/rc.initial.password @@ -45,20 +45,22 @@ The webConfigurator admin password and privileges will be reset to the default ( if (strcasecmp(chop(fgets($fp)), "y") == 0) { if (isset($config['system']['webgui']['authmode']) && - $config['system']['webgui']['authmode'] != "Local Database") { + $config['system']['webgui']['authmode'] != "Local Database") { echo "\n" . gettext(' The User manager authentication server is set to "' . $config['system']['webgui']['authmode'] . '".') . "\n" . gettext('Do you want to set it back to Local Database [y|n]?'); - if (strcasecmp(chop(fgets($fp)), "y") == 0) + if (strcasecmp(chop(fgets($fp)), "y") == 0) { $config['system']['webgui']['authmode'] = "Local Database"; + } } $admin_user =& getUserEntryByUID(0); if (!$admin_user) { echo "Failed to locate the admin user account! Attempting to restore access.\n"; $admin_user = array(); $admin_user['uid'] = 0; - if (!is_array($config['system']['user'])) + if (!is_array($config['system']['user'])) { $config['system']['user'] = array(); + } $config['system']['user'][] = $admin_user; } @@ -66,8 +68,9 @@ The User manager authentication server is set to "' . $config['system']['webgui' $admin_user['scope'] = "system"; $admin_user['priv'] = array("user-shell-access"); - if (isset($admin_user['disabled'])) + if (isset($admin_user['disabled'])) { unset($admin_user['disabled']); + } local_user_set_password($admin_user, strtolower($g['product_name'])); local_user_set($admin_user); diff --git a/etc/rc.initial.ping b/etc/rc.initial.ping index ff10487740..32bd756e37 100755 --- a/etc/rc.initial.ping +++ b/etc/rc.initial.ping @@ -4,20 +4,20 @@ /* rc.initial.ping part of m0n0wall (http://m0n0.ch/wall) - + Copyright (C) 2003-2004 Manuel Kasper . All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE @@ -33,9 +33,9 @@ /* parse the configuration and include all functions used below */ require_once("config.inc"); require_once("functions.inc"); - + $fp = fopen('php://stdin', 'r'); - + echo "\nEnter a host name or IP address: "; $pinghost = chop(fgets($fp)); @@ -50,6 +50,6 @@ echo "\nPress ENTER to continue.\n"; fgets($fp); } - + fclose($fp); ?> diff --git a/etc/rc.initial.reboot b/etc/rc.initial.reboot index f3143e0ba5..fdc426ea84 100755 --- a/etc/rc.initial.reboot +++ b/etc/rc.initial.reboot @@ -55,7 +55,7 @@ EOD; system_reboot_sync(); } - + fclose($fp); ?> diff --git a/etc/rc.initial.setlanip b/etc/rc.initial.setlanip index 01f2676449..62ca93bb69 100755 --- a/etc/rc.initial.setlanip +++ b/etc/rc.initial.setlanip @@ -30,8 +30,6 @@ POSSIBILITY OF SUCH DAMAGE. */ - - $options = getopt("hn", array("dry-run", "help")); if (isset($options["h"]) || isset($options["help"])) { @@ -46,8 +44,6 @@ if ($dry_run) { echo "DRY RUN MODE IS ON\n"; } - - /* parse the configuration and include all functions used below */ require_once("config.inc"); require_once("functions.inc"); @@ -93,9 +89,10 @@ function console_get_interface_from_ppp($realif) { function prompt_for_enable_dhcp_server($version = 4) { global $config, $fp, $interface; - if($interface == "wan") { - if($config['interfaces']['lan']) + if ($interface == "wan") { + if ($config['interfaces']['lan']) { return false; + } } /* only allow DHCP server to be enabled when static IP is configured on this interface */ @@ -116,7 +113,9 @@ function prompt_for_enable_dhcp_server($version = 4) { function get_interface_config_description($iface) { global $config; $c = $config['interfaces'][$iface]; - if (!$c) { return null; } + if (!$c) { + return null; + } $if = $c['if']; $result = $if; $result2 = array(); @@ -143,28 +142,27 @@ $fp = fopen('php://stdin', 'r'); /* build an interface collection */ $ifdescrs = get_configured_interface_with_descr(false, true); $count = count($ifdescrs); - -/* grab interface that we will operate on, unless there is only one - interface */ + +/* grab interface that we will operate on, unless there is only one interface */ if ($count > 1) { echo "Available interfaces:\n\n"; $x=1; - foreach($ifdescrs as $iface => $ifdescr) { + foreach ($ifdescrs as $iface => $ifdescr) { $config_descr = get_interface_config_description($iface); echo "{$x} - {$ifdescr} ({$config_descr})\n"; $x++; } echo "\nEnter the number of the interface you wish to configure: "; - $intnum = chop(fgets($fp)); + $intnum = chop(fgets($fp)); } else { $intnum = $count; } - -if($intnum < 1) + +if ($intnum < 1) return; -if($intnum > $count) +if ($intnum > $count) return; - + $index = 1; foreach ($ifdescrs as $ifname => $ifdesc) { if ($intnum == $index) { @@ -173,8 +171,8 @@ foreach ($ifdescrs as $ifname => $ifdesc) { } else { $index++; } -} -if(!$interface) { +} +if (!$interface) { echo "Invalid interface!\n"; return; } @@ -185,7 +183,9 @@ function next_unused_gateway_name($interface) { global $g, $config; $new_name = "GW_" . strtoupper($interface); - if (!is_array($config['gateways']['gateway_item'])) { return $new_name; } + if (!is_array($config['gateways']['gateway_item'])) { + return $new_name; + } $count = 1; do { $existing = false; @@ -216,10 +216,12 @@ function add_gateway_to_config($interface, $gatewayip, $inet_type) { $is_default = true; foreach ($a_gateways as $item) { if ($item['ipprotocol'] === $inet_type) { - if (isset($item['defaultgw'])) + if (isset($item['defaultgw'])) { $is_default = false; - if (($item['interface'] === $interface) && ($item['gateway'] === $gatewayip)) + } + if (($item['interface'] === $interface) && ($item['gateway'] === $gatewayip)) { $new_name = $item['name']; + } } } if ($new_name == '') { @@ -252,34 +254,36 @@ function console_configure_ip_address($version) { $upperifname = strtoupper($interface); - if($interface == "wan") { + if ($interface == "wan") { if (console_prompt_for_yn (sprintf(gettext("Configure %s address %s interface via %s?"), $label_IPvX, $upperifname, $label_DHCP))) { $ifppp = console_get_interface_from_ppp(get_real_interface("wan")); - if (!empty($ifppp)) + if (!empty($ifppp)) { $ifaceassigned = $ifppp; + } $intip = ($version === 6) ? "dhcp6" : "dhcp"; $intbits = ""; $isintdhcp = true; $restart_dhcpd = true; - } + } } - - if($isintdhcp == false or $interface <> "wan") { - while(true) { + + if ($isintdhcp == false or $interface <> "wan") { + while (true) { do { echo "\n" . sprintf(gettext("Enter the new %s %s address. Press for none:"), - $upperifname, $label_IPvX) . "\n> "; + $upperifname, $label_IPvX) . "\n> "; $intip = chop(fgets($fp)); $is_ipaddr = ($version === 6) ? is_ipaddrv6($intip) : is_ipaddrv4($intip); if ($is_ipaddr && is_ipaddr_configured($intip, $interface, true)) { $ip_conflict = true; echo gettext("This IP address conflicts with another interface or a VIP") . "\n"; - } else + } else { $ip_conflict = false; + } } while (($ip_conflict === true) || !($is_ipaddr || $intip == '')); if ($intip != '') { echo "\n" . sprintf(gettext("Subnet masks are entered as bit counts (as in CIDR notation) in %s."), - $g['product_name']) . "\n"; + $g['product_name']) . "\n"; if ($version === 6) { echo "e.g. ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00 = 120\n"; echo " ffff:ffff:ffff:ffff:ffff:ffff:ffff:0 = 112\n"; @@ -294,7 +298,7 @@ function console_configure_ip_address($version) { do { $upperifname = strtoupper($interface); echo "\n" . sprintf(gettext("Enter the new %s %s subnet bit count (1 to %s):"), - $upperifname, $label_IPvX, $maxbits) . "\n> "; + $upperifname, $label_IPvX, $maxbits) . "\n> "; $intbits = chop(fgets($fp)); $intbits_ok = is_numeric($intbits) && (($intbits >= 1) && ($intbits <= $maxbits)); $restart_dhcpd = true; @@ -338,8 +342,9 @@ function console_configure_ip_address($version) { } } $ifppp = console_get_interface_from_ppp(get_real_interface($interface)); - if (!empty($ifppp)) + if (!empty($ifppp)) { $ifaceassigned = $ifppp; + } break; } } @@ -350,8 +355,9 @@ function console_configure_ip_address($version) { list($intip, $intbits, $gwname) = console_configure_ip_address(4); list($intip6, $intbits6, $gwname6) = console_configure_ip_address(6); -if (!empty($ifaceassigned)) +if (!empty($ifaceassigned)) { $config['interfaces'][$interface]['if'] = $ifaceassigned; +} $config['interfaces'][$interface]['ipaddr'] = $intip; $config['interfaces'][$interface]['subnet'] = $intbits; $config['interfaces'][$interface]['gateway'] = $gwname; @@ -366,7 +372,7 @@ function console_configure_dhcpd($version = 4) { $label_IPvX = ($version === 6) ? "IPv6" : "IPv4"; $dhcpd = ($version === 6) ? "dhcpdv6" : "dhcpd"; - if($g['services_dhcp_server_enable'] && prompt_for_enable_dhcp_server($version)) { + if ($g['services_dhcp_server_enable'] && prompt_for_enable_dhcp_server($version)) { $subnet_start = ($version === 6) ? gen_subnetv6($intip6, $intbits6) : gen_subnet($intip, $intbits); $subnet_end = ($version === 6) ? gen_subnetv6_max($intip6, $intbits6) : gen_subnet_max($intip, $intbits); do { @@ -379,8 +385,9 @@ function console_configure_dhcpd($version = 4) { } $is_ipaddr = ($version === 6) ? is_ipaddrv6($dhcpstartip) : is_ipaddrv4($dhcpstartip); $is_inrange = is_inrange($dhcpstartip, $subnet_start, $subnet_end); - if (!$is_inrange) + if (!$is_inrange) { echo gettext("This IP address must be in the interface's subnet") . "\n"; + } } while (!$is_ipaddr || !$is_inrange); do { @@ -392,8 +399,9 @@ function console_configure_dhcpd($version = 4) { } $is_ipaddr = ($version === 6) ? is_ipaddrv6($dhcpendip) : is_ipaddrv4($dhcpendip); $is_inrange = is_inrange($dhcpendip, $subnet_start, $subnet_end); - if (!$is_inrange) + if (!$is_inrange) { echo gettext("This IP address must be in the interface's subnet") . "\n"; + } $not_inorder = ($version === 6) ? (inet_pton($dhcpendip) < inet_pton($dhcpstartip)) : ip_less_than($dhcpendip, $dhcpstartip); if ($not_inorder) { echo gettext("The end address of the DHCP range must be >= the start address") . "\n"; @@ -405,7 +413,7 @@ function console_configure_dhcpd($version = 4) { $config[$dhcpd][$interface]['range']['from'] = $dhcpstartip; $config[$dhcpd][$interface]['range']['to'] = $dhcpendip; } else { - if(isset($config[$dhcpd][$interface]['enable'])) { + if (isset($config[$dhcpd][$interface]['enable'])) { unset($config[$dhcpd][$interface]['enable']); printf(gettext("Disabling %s DHCPD..."), $label_IPvX); $restart_dhcpd = true; @@ -418,7 +426,7 @@ if (console_configure_dhcpd(4) == 0) return 0; if (console_configure_dhcpd(6) == 0) return 0; - + //***************************************************************************** if ($config['system']['webgui']['protocol'] == "https") { @@ -434,21 +442,27 @@ if (isset($config['system']['webgui']['noantilockout'])) { unset($config['system']['webgui']['noantilockout']); } -if($config['interfaces']['lan']) { - if($config['dhcpd']) - if($config['dhcpd']['wan']) - unset($config['dhcpd']['wan']); - if($config['dhcpdv6']) - if($config['dhcpdv6']['wan']) +if ($config['interfaces']['lan']) { + if ($config['dhcpd']) { + if ($config['dhcpd']['wan']) { + unset($config['dhcpd']['wan']); + } + } + if ($config['dhcpdv6']) { + if ($config['dhcpdv6']['wan']) { unset($config['dhcpdv6']['wan']); + } + } } -if(!$config['interfaces']['lan']) { +if (!$config['interfaces']['lan']) { unset($config['interfaces']['lan']); - if($config['dhcpd']['lan']) + if ($config['dhcpd']['lan']) { unset($config['dhcpd']['lan']); - if($config['dhcpdv6']['lan']) + } + if ($config['dhcpdv6']['lan']) { unset($config['dhcpdv6']['lan']); + } unset($config['shaper']); unset($config['ezshaper']); unset($config['nat']); @@ -467,32 +481,32 @@ if (!$dry_run) { filter_configure_sync(); echo "\n Reloading routing configuration..."; system_routing_configure(); - if($restart_dhcpd) { - echo "\n DHCPD..."; + if ($restart_dhcpd) { + echo "\n DHCPD..."; services_dhcpd_configure(); } - if($restart_webgui) { + if ($restart_webgui) { echo "\n Restarting webConfigurator... "; mwexec("/etc/rc.restart_webgui"); } } - + if ($intip != '') { if (is_ipaddr($intip)) { echo "\n\n" . sprintf(gettext("The IPv4 %s address has been set to %s"), - $upperifname, "{$intip}/{$intbits}") . "\n"; + $upperifname, "{$intip}/{$intbits}") . "\n"; } else { echo "\n\n" . sprintf(gettext("The IPv4 %s address has been set to %s"), - $upperifname, $intip) . "\n"; + $upperifname, $intip) . "\n"; } } if ($intip6 != '') { if (is_ipaddr($intip6)) { echo "\n\n" . sprintf(gettext("The IPv6 %s address has been set to %s"), - $upperifname, "${intip6}/${intbits6}") . "\n"; + $upperifname, "${intip6}/${intbits6}") . "\n"; } else { echo "\n\n" . sprintf(gettext("The IPv6 %s address has been set to %s"), - $upperifname, $intip6) . "\n"; + $upperifname, $intip6) . "\n"; } } @@ -503,7 +517,7 @@ if ($intip != '' || $intip6 != '') { echo "interface is {$interface} \n"; } echo gettext('You can now access the webConfigurator by opening the following URL in your web browser:') . "\n"; - if(!empty($config['system']['webgui']['port'])) { + if (!empty($config['system']['webgui']['port'])) { $webuiport = $config['system']['webgui']['port']; if ($intip != '') { echo " {$config['system']['webgui']['protocol']}://{$intip}:{$webuiport}/\n"; @@ -534,5 +548,5 @@ echo "\n" . gettext('Press to continue.'); fgets($fp); fclose($fp); - + ?> diff --git a/etc/rc.initial.setports b/etc/rc.initial.setports index aca5419343..e85e3239e9 100755 --- a/etc/rc.initial.setports +++ b/etc/rc.initial.setports @@ -44,8 +44,8 @@ set_networking_interfaces_ports(); reload_interfaces_sync(); - + /* reload graphing functions */ - enable_rrd_graphing(); + enable_rrd_graphing(); ?> \ No newline at end of file diff --git a/etc/rc.initial.store_config_to_removable_device b/etc/rc.initial.store_config_to_removable_device index aacc512e7d..bd92446445 100755 --- a/etc/rc.initial.store_config_to_removable_device +++ b/etc/rc.initial.store_config_to_removable_device @@ -40,15 +40,15 @@ do { $dirs = array(); $dirs = return_dir_as_array("/var/db/pfi/"); - if(!is_array($dirs)) { + if (!is_array($dirs)) { echo "\nNo capable storage devices detected.\n"; fclose($fp); return; } echo "\nDevices capable of config.xml storage:\n"; - foreach($dirs as $dir) { + foreach ($dirs as $dir) { preg_match_all("/capable\_(.*)/",$dir,$match_array); - echo $match_array[1][0] . " "; + echo $match_array[1][0] . " "; } echo "\n\n"; echo "Enter the device that you wish the"; @@ -58,13 +58,13 @@ if ($move_config_to_device == "") { fclose($fp); return 0; - } + } } while (!$move_config_to_device); - + mwexec("/bin/mkdir -p /tmp/mnt/cf"); $status = mwexec("/sbin/mount -w -t msdosfs /dev/{$move_config_to_device} /tmp/mnt/cf"); - if(!$status) { + if (!$status) { echo "Error while mounting {$move_config_to_device}.\n"; fclose($fp); return; @@ -79,7 +79,7 @@ echo " nullfs... "; system("/sbin/umount /cf/conf"); system("/sbin/umount /conf"); - mwexec("/bin/rm -rf /conf/*.*"); + mwexec("/bin/rm -rf /conf/*.*"); /* use nullfs to mount */ system("/sbin/mount_nullfs /tmp/mnt/cf/conf /conf"); system("/sbin/mount_nullfs /tmp/mnt/cf /cf"); diff --git a/etc/rc.initial.toggle_sshd b/etc/rc.initial.toggle_sshd index ad1d868acb..997f3c195e 100755 --- a/etc/rc.initial.toggle_sshd +++ b/etc/rc.initial.toggle_sshd @@ -53,7 +53,7 @@ if (isset($config['system']['enablesshd'])) { echo " done.\n"; exec("ps awux | grep '/usr/sbin/sshd' | grep -v grep | awk '{print $2}' | xargs kill"); } - + } else { echo "SSHD is currently disabled. Would you like to enable? [y/n]? "; $yn = chop(fgets($fp)); @@ -67,7 +67,7 @@ if (isset($config['system']['enablesshd'])) { echo "\nReloading firewall rules."; filter_configure(); echo " done.\n\n"; - } + } } fclose($fp); diff --git a/etc/rc.interfaces_carp_configure b/etc/rc.interfaces_carp_configure index fb1f1131a0..050fbc88ed 100755 --- a/etc/rc.interfaces_carp_configure +++ b/etc/rc.interfaces_carp_configure @@ -2,37 +2,37 @@ diff --git a/etc/rc.interfaces_wan_configure b/etc/rc.interfaces_wan_configure index c291ee8ad6..7e7eb7b16e 100755 --- a/etc/rc.interfaces_wan_configure +++ b/etc/rc.interfaces_wan_configure @@ -2,47 +2,49 @@ diff --git a/etc/rc.kill_states b/etc/rc.kill_states index a20753afac..fe5a296bac 100755 --- a/etc/rc.kill_states +++ b/etc/rc.kill_states @@ -51,8 +51,9 @@ if (empty($interface) || !does_interface_exist($interface)) { if (!empty($local_ip)) { list($local_ip, $subnet_bits) = explode("/", $local_ip); - if (empty($subnet_bits)) + if (empty($subnet_bits)) { $subnet_bits = "32"; + } if (!is_ipaddr($local_ip)) { log_error("rc.kill_states: Invalid IP address '{$local_ip}'"); @@ -67,15 +68,17 @@ if (!isset($config['system']['kill_states'])) { "/usr/bin/egrep '\-> +{$local_ip}:[0-9]+ +\->'"); $cleared_states = array(); - foreach(explode("\n", $nat_states) as $nat_state) { - if (preg_match_all('/([\d\.]+):[\d]+[\s->]+/i', $nat_state, $matches, PREG_SET_ORDER) != 3) + foreach (explode("\n", $nat_states) as $nat_state) { + if (preg_match_all('/([\d\.]+):[\d]+[\s->]+/i', $nat_state, $matches, PREG_SET_ORDER) != 3) { continue; + } $src = $matches[0][1]; $dst = $matches[2][1]; - if (empty($src) || empty($dst) || in_array("{$src},{$dst}", $cleared_states)) + if (empty($src) || empty($dst) || in_array("{$src},{$dst}", $cleared_states)) { continue; + } $cleared_states[] = "{$src},{$dst}"; pfSense_kill_states($src, $dst); diff --git a/etc/rc.linkup b/etc/rc.linkup index aa5e0d8398..f5d4034ab1 100755 --- a/etc/rc.linkup +++ b/etc/rc.linkup @@ -32,15 +32,16 @@ /* parse the configuration and include all functions used below */ require_once("globals.inc"); require_once("config.inc"); -require_once("filter.inc"); -require_once("shaper.inc"); +require_once("filter.inc"); +require_once("shaper.inc"); require_once("interfaces.inc"); -if (platform_booting()) +if (platform_booting()) { return; +} function handle_argument_group($iface, $argument2) { - global $config; + global $config; if (!is_array($config['interfaces'][$iface])) { log_error("Cannot find interface configuration for {$iface}"); @@ -48,59 +49,64 @@ function handle_argument_group($iface, $argument2) { } if (!isset($config['interfaces'][$iface]['enable'])) { - if (!platform_booting()) + if (!platform_booting()) { log_error("Linkup detected on disabled interface...Ignoring"); + } return; } $ipaddr = $config['interfaces'][$iface]['ipaddr']; $ip6addr = $config['interfaces'][$iface]['ipaddrv6']; $staticv4 = false; - if (empty($ipaddr)) + if (empty($ipaddr)) { $staticv4 = true; - else + } else { $staticv4 = is_ipaddrv4($ipaddr); + } $staticv6 = false; - if (empty($ip6addr)) + if (empty($ip6addr)) { $staticv6 = true; - else + } else { $staticv6 = is_ipaddrv6($ip6addr); + } if ($staticv4 === true && $staticv6 === true) { $friendly = convert_friendly_interface_to_friendly_descr($iface); log_error("Hotplug event detected for {$friendly}({$iface}) but ignoring since interface is configured with static IP ({$ipaddr} {$ip6addr})"); interfaces_staticarp_configure($iface); switch ($argument2) { - case 'start': - case 'up': - $iface = get_real_interface($iface); - /* NOTE: Do not generate event for OpenVPN since the daemon does that for us. */ - if (substr($iface, 0, 4) != "ovpn") - send_event("interface newip {$iface}"); - break; + case 'start': + case 'up': + $iface = get_real_interface($iface); + /* NOTE: Do not generate event for OpenVPN since the daemon does that for us. */ + if (substr($iface, 0, 4) != "ovpn") { + send_event("interface newip {$iface}"); + } + break; } } else { switch ($argument2) { - case "stop": - case "down": - log_error("DEVD Ethernet detached event for {$iface}"); - interface_bring_down($iface); - break; - case "start": - case "up": - log_error("DEVD Ethernet attached event for {$iface}"); - log_error("HOTPLUG: Configuring interface {$iface}"); - require_once("vpn.inc"); - require_once("captiveportal.inc"); - // Do not try to readd to bridge otherwise em(4) has problems - interface_configure($iface, true, true); - break; + case "stop": + case "down": + log_error("DEVD Ethernet detached event for {$iface}"); + interface_bring_down($iface); + break; + case "start": + case "up": + log_error("DEVD Ethernet attached event for {$iface}"); + log_error("HOTPLUG: Configuring interface {$iface}"); + require_once("vpn.inc"); + require_once("captiveportal.inc"); + // Do not try to readd to bridge otherwise em(4) has problems + interface_configure($iface, true, true); + break; } } } if (isset($_GET['interface'])) { - if (!empty($_GET['interface'])) + if (!empty($_GET['interface'])) { $realiface = $_GET['interface']; + } $action = $_GET['action']; } else { if ($argc < 3) { @@ -112,14 +118,14 @@ if (isset($_GET['interface'])) { } switch($action) { -case "start": -case "stop": - break; -default: - log_error("HOTPLUG event: Action parameter ($action) passed is wrong - only start/stop/up/down are allowed!"); - return; - /* NOTREACHED */ - break; + case "start": + case "stop": + break; + default: + log_error("HOTPLUG event: Action parameter ($action) passed is wrong - only start/stop/up/down are allowed!"); + return; + /* NOTREACHED */ + break; } if (!empty($realiface)) { @@ -129,23 +135,27 @@ if (!empty($realiface)) { } $rclinkuplock = lock("rclinkup{$realiface}", LOCK_EX); $interface = convert_real_interface_to_friendly_interface_name($realiface); - if (!empty($interface)) + if (!empty($interface)) { handle_argument_group($interface, $action); + } if ($action == 'start') { /* Check if there is any child on this one as ppp types and trigger them */ if (is_array($config['ppps']['ppp'])) { foreach ($config['ppps']['ppp'] as $pppidx => $ppp) { - if ($ppp['type'] == 'ppp') + if ($ppp['type'] == 'ppp') { continue; + } $ports = explode(',', $ppp['ports']); foreach ($ports as $pid => $parent_if) { /* The loop here is because ppp types can have real and assigned interfaces as members */ $tmpiface = get_real_interface($parent_if); - if ($tmpiface != $realiface) + if ($tmpiface != $realiface) { continue; + } $tmpiface = convert_real_interface_to_friendly_interface_name($ppp['if']); - if (!empty($tmpiface)) + if (!empty($tmpiface)) { interface_configure($tmpiface, true, true); + } } } } diff --git a/etc/rc.newipsecdns b/etc/rc.newipsecdns index 870283a198..7fecff8345 100755 --- a/etc/rc.newipsecdns +++ b/etc/rc.newipsecdns @@ -3,21 +3,21 @@ /* rc.newipsecdns part of m0n0wall (http://m0n0.ch/wall) - + Copyright (C) 2007 Manuel Kasper . Copyright (C) 2009 Seth Mos . All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE @@ -35,20 +35,22 @@ require_once("util.inc"); require_once("config.inc"); require_once("gwlb.inc"); require_once("functions.inc"); -require_once("filter.inc"); -require_once("shaper.inc"); +require_once("filter.inc"); +require_once("shaper.inc"); require_once("ipsec.inc"); require_once("vpn.inc"); /* make sure to wait until the boot scripts have finished */ -if (file_exists("{$g['varrun_path']}/booting")) +if (file_exists("{$g['varrun_path']}/booting")) { return; +} if (isset($config['ipsec']['enable'])) { sleep(15); log_error("IPSEC: One or more IPsec tunnel endpoints has changed its IP. Refreshing."); -} else +} else { return; +} $ipseclck = lock('ipsecdns', LOCK_EX); diff --git a/etc/rc.newroutedns b/etc/rc.newroutedns index dfc766b57a..ba8ca32eb6 100755 --- a/etc/rc.newroutedns +++ b/etc/rc.newroutedns @@ -34,15 +34,17 @@ require_once("functions.inc"); require_once("system.inc"); /* make sure to wait until the boot scripts have finished */ -if (file_exists("{$g['varrun_path']}/booting")) +if (file_exists("{$g['varrun_path']}/booting")) { return; +} $staticroutes = get_staticroutes(); -if (count($staticroutes)) +if (count($staticroutes)) { log_error("Static Routes: One or more aliases used for routing has changed its IP. Refreshing."); -else +} else { return; +} $routelck = lock('routedns', LOCK_EX); diff --git a/etc/rc.newwanip b/etc/rc.newwanip index d992c7150b..79d07a4933 100755 --- a/etc/rc.newwanip +++ b/etc/rc.newwanip @@ -54,10 +54,11 @@ function restart_packages() { } /* Interface IP address has changed */ -if (isset($_GET['interface'])) +if (isset($_GET['interface'])) { $argument = $_GET['interface']; -else +} else { $argument = str_replace("\n", "", $argv[1]); +} log_error("rc.newwanip: Info: starting on {$argument}."); @@ -77,16 +78,18 @@ if (is_array($config['interfaces'][$interface]) && !isset($config['interfaces'][ return; } -if (empty($argument)) +if (empty($argument)) { $curwanip = get_interface_ip(); -else { +} else { $curwanip = find_interface_ip($interface_real, true); - if($curwanip == "") + if($curwanip == "") { $curwanip = get_interface_ip($interface); + } } -if (!platform_booting()) +if (!platform_booting()) { log_error("rc.newwanip: on (IP address: {$curwanip}) (interface: {$interface_descr}[{$interface}]) (real interface: {$interface_real})."); +} /* * NOTE: Take care of openvpn, no-ip or similar interfaces if you generate the event to reconfigure an interface. @@ -104,54 +107,64 @@ if ($curwanip == "0.0.0.0" || !is_ipaddr($curwanip)) { /* XXX: This really possible? */ if (empty($interface)) { - if (platform_booting()) + if (platform_booting()) { return; + } filter_configure(); restart_packages(); return; } $oldip = "0.0.0.0"; -if (file_exists("{$g['vardb_path']}/{$interface}_cacheip")) +if (file_exists("{$g['vardb_path']}/{$interface}_cacheip")) { $oldip = file_get_contents("{$g['vardb_path']}/{$interface}_cacheip"); +} /* regenerate resolv.conf if DNS overrides are allowed */ -if (!platform_booting()) +if (!platform_booting()) { system_resolvconf_generate(true); +} /* write the current interface IP to file */ -if (is_ipaddr($curwanip)) +if (is_ipaddr($curwanip)) { @file_put_contents("{$g['vardb_path']}/{$interface}_ip", $curwanip); +} link_interface_to_vips($interface, "update"); unset($gre); $gre = link_interface_to_gre($interface); -if (!empty($gre)) +if (!empty($gre)) { array_walk($gre, 'interface_gre_configure'); +} + unset($gif); $gif = link_interface_to_gif($interface); -if (!empty($gif)) +if (!empty($gif)) { array_walk($gif, 'interface_gif_configure'); +} $grouptmp = link_interface_to_group($interface); -if (!empty($grouptmp)) +if (!empty($grouptmp)) { array_walk($grouptmp, 'interface_group_add_member'); +} unset($bridgetmp); $bridgetmp = link_interface_to_bridge($interface); -if (!empty($bridgetmp)) +if (!empty($bridgetmp)) { interface_bridge_add_member($bridgetmp, $interface_real); +} // Do not process while booting -if (platform_booting()) +if (platform_booting()) { return; +} /* make new hosts file */ system_hosts_generate(); -/* check tunneled IPv6 interface tracking */ -switch($config['interfaces'][$interface]['ipaddrv6']) { +/* check tunnelled IPv6 interface tracking */ +switch ($config['interfaces'][$interface]['ipaddrv6']) { case "6to4": interface_6to4_configure($interface, $config['interfaces'][$interface]); break; @@ -159,14 +172,15 @@ switch($config['interfaces'][$interface]['ipaddrv6']) { interface_6rd_configure($interface, $config['interfaces'][$interface]); break; case "dhcp6": - if (isset($config['interfaces'][$interface]['dhcp6usev4iface'])) + if (isset($config['interfaces'][$interface]['dhcp6usev4iface'])) { interface_dhcpv6_configure($interface, $config['interfaces'][$interface]); + } break; } /* Check Gif tunnels */ if (!empty($gif)) { - foreach($gif as $giftun) { + foreach ($gif as $giftun) { $confif = convert_real_interface_to_friendly_interface_name($giftun['gifif']); if (!empty($confif)) { interface_configure($confif); @@ -200,9 +214,9 @@ if (!is_ipaddr($oldip) || $curwanip != $oldip || !is_ipaddrv4($config['interface filter_flush_state_table(); } } - + /* - * Some services (e.g. dyndns, see ticket #4066) depends of + * Some services (e.g. dyndns, see ticket #4066) depend on * filter_configure() to be called before, otherwise pass out * route-to rules have the old ip set in 'from' and connection * do not go through correct link @@ -214,12 +228,13 @@ if (!is_ipaddr($oldip) || $curwanip != $oldip || !is_ipaddrv4($config['interface /* reconfigure our gateway monitor */ setup_gateways_monitor(); - + /* reload unbound */ services_unbound_configure(); - if (is_ipaddr($curwanip)) + if (is_ipaddr($curwanip)) { @file_put_contents("{$g['vardb_path']}/{$interface}_cacheip", $curwanip); + } /* perform RFC 2136 DNS update */ services_dnsupdate_process($interface); @@ -231,8 +246,9 @@ if (!is_ipaddr($oldip) || $curwanip != $oldip || !is_ipaddrv4($config['interface vpn_ipsec_force_reload($interface); /* start OpenVPN server & clients */ - if (substr($interface_real, 0, 4) != "ovpn") + if (substr($interface_real, 0, 4) != "ovpn") { openvpn_resync_all($interface); + } /* reload graphing functions */ enable_rrd_graphing(); diff --git a/etc/rc.newwanipv6 b/etc/rc.newwanipv6 index 72aabf7133..827fcaa994 100755 --- a/etc/rc.newwanipv6 +++ b/etc/rc.newwanipv6 @@ -50,15 +50,16 @@ function restart_packages() { /* restart packages */ system_ntp_configure(false); mwexec_bg("/usr/local/sbin/ntpdate_sync_once.sh", true); - log_error("{$g['product_name']} package system has detected an IP change or dynamic WAN reconnection - $oldipv6 -> $curwanipv6 - Restarting packages."); + log_error("{$g['product_name']} package system has detected an IP change or dynamic WAN reconnection - $oldipv6 -> $curwanipv6 - Restarting packages."); send_event("service reload packages"); } /* Interface IP address has changed */ -if (isset($_GET['interface'])) +if (isset($_GET['interface'])) { $argument = $_GET['interface']; -else +} else { $argument = trim($argv[1], " \n\t"); +} log_error("rc.newwanipv6: Info: starting on {$argument}."); @@ -81,54 +82,65 @@ if (empty($interface)) { } //Do not process while booting -if (platform_booting() && $config['interfaces'][$interface]['ipaddrv6'] != "dhcp6") +if (platform_booting() && $config['interfaces'][$interface]['ipaddrv6'] != "dhcp6") { return; +} /* * NOTE: Take care of openvpn and similar if you generate the event to reconfigure an interface. * i.e. OpenVPN might be in tap mode and not have an ip. */ if ((empty($curwanipv6) || !is_ipaddrv6($curwanipv6)) && substr($interface_real, 0, 4) != "ovpn") { - log_error("rc.newwanipv6: Failed to update {$interface_descr}[{$interface}] IPv6, restarting..."); + log_error("rc.newwanipv6: Failed to update {$interface_descr}[{$interface}] IPv6, restarting..."); // send_event("interface reconfigure {$interface}"); - return; + return; } -if (isset($_GET['dmips'])) +if (isset($_GET['dmips'])) { $new_domain_name_servers = $_GET['dmips']; -else +} else { $new_domain_name_servers = getenv("new_domain_name_servers"); +} + if (!empty($new_domain_name_servers)) { $name_servers = explode(" ", $new_domain_name_servers); $valid_ns = array(); - foreach($name_servers as $ns) { - if (is_ipaddrv6(trim($ns))) + foreach ($name_servers as $ns) { + if (is_ipaddrv6(trim($ns))) { $valid_ns[] = trim($ns); + } } - if (count($valid_ns > 0)) + if (count($valid_ns > 0)) { file_put_contents("{$g['varetc_path']}/nameserver_v6{$interface}", implode("\n", $valid_ns)); + } } -if (isset($_GET['dmnames'])) +if (isset($_GET['dmnames'])) { $new_domain_name = $_GET['dmnames']; -else +} else { $new_domain_name = getenv("new_domain_name"); -if (!empty($new_domain_name)) +} + +if (!empty($new_domain_name)) { file_put_contents("{$g['varetc_path']}/searchdomain_v6{$interface}", $new_domain_name); +} /* write current WAN IPv6 to file */ -if (is_ipaddrv6($curwanipv6)) +if (is_ipaddrv6($curwanipv6)) { @file_put_contents("{$g['vardb_path']}/{$interface}_ipv6", $curwanipv6); +} log_error("rc.newwanipv6: on (IP address: {$curwanipv6}) (interface: {$interface}) (real interface: {$interface_real})."); $oldipv6 = ''; -if (file_exists("{$g['vardb_path']}/{$interface}_cacheipv6")) +if (file_exists("{$g['vardb_path']}/{$interface}_cacheipv6")) { $oldipv6 = file_get_contents("{$g['vardb_path']}/{$interface}_cacheipv6"); +} $grouptmp = link_interface_to_group($interface); -if (!empty($grouptmp)) +if (!empty($grouptmp)) { array_walk($grouptmp, 'interface_group_add_member'); +} link_interface_to_track6($interface, "update"); @@ -152,19 +164,21 @@ if (empty($oldipv6) || is_ipaddrv6($oldipv6)) { vpn_ipsec_force_reload($interface); /* start OpenVPN server & clients */ - if (substr($interface_real, 0, 4) != "ovpn") + if (substr($interface_real, 0, 4) != "ovpn") { openvpn_resync_all($interface); + } } return; - } else if (does_interface_exist($interface_real) && !empty($oldipv6)) + } else if (does_interface_exist($interface_real) && !empty($oldipv6)) { mwexec("/sbin/ifconfig {$interface_real} inet6 {$oldipv6} delete"); + } file_put_contents("{$g['vardb_path']}/{$interface}_cacheipv6", $curwanipv6); } /* reload unbound */ services_unbound_configure(); - + /* perform RFC 2136 DNS update */ services_dnsupdate_process($interface); @@ -175,8 +189,9 @@ services_dyndns_configure($interface); vpn_ipsec_force_reload($interface); /* start OpenVPN server & clients */ -if (substr($interface_real, 0, 4) != "ovpn") +if (substr($interface_real, 0, 4) != "ovpn") { openvpn_resync_all($interface); +} /* reload graphing functions */ enable_rrd_graphing(); diff --git a/etc/rc.notify_message b/etc/rc.notify_message index 5075e8bd2a..87988d3266 100755 --- a/etc/rc.notify_message +++ b/etc/rc.notify_message @@ -1,31 +1,31 @@ #!/usr/local/bin/php - All rights reserved. + rc.notify_message + part of pfSense (https://www.pfsense.org) + Copyright (C) 2010 Scott Ullrich + All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. */ require_once("config.inc"); @@ -38,8 +38,8 @@ $send_email = false; $send_growl = false; $message = ""; -foreach($arguments as $item => $arg) { - switch($item) { +foreach ($arguments as $item => $arg) { + switch ($item) { case "e": $send_email = true; break; @@ -52,11 +52,11 @@ foreach($arguments as $item => $arg) { } } -if($message) { - if($send_email) { +if ($message) { + if ($send_email) { notify_via_smtp($message); } - if($send_growl) { + if ($send_growl) { notify_via_growl($message); } } diff --git a/etc/rc.ntpdate b/etc/rc.ntpdate index 4d64577747..4272acbd76 100755 --- a/etc/rc.ntpdate +++ b/etc/rc.ntpdate @@ -6,17 +6,17 @@ part of m0n0wall (http://m0n0.ch/wall) Copyright (C) 2003-2004 Scott Ullrich . All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE @@ -34,6 +34,6 @@ require_once("functions.inc"); require_once("filter.inc"); require_once("shaper.inc"); - + system_ntp_configure(); ?> diff --git a/etc/rc.openvpn b/etc/rc.openvpn index 303f91c524..96a80a0cc5 100755 --- a/etc/rc.openvpn +++ b/etc/rc.openvpn @@ -3,21 +3,21 @@ /* rc.openvpn part of m0n0wall (http://m0n0.ch/wall) - + Copyright (C) 2007 Manuel Kasper . Copyright (C) 2009 Seth Mos . All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE @@ -54,8 +54,9 @@ function openvpn_resync_if_needed ($mode, $ovpn_settings, $interface) { $new_device = get_failover_interface($ovpn_settings['interface']); if (isset($config['interfaces'][$interface])) { $this_device = $config['interfaces'][$interface]['if']; - if (($current_device == $new_device) && ($current_device != $this_device)) + if (($current_device == $new_device) && ($current_device != $this_device)) { $resync_needed = false; + } } } } @@ -67,26 +68,29 @@ function openvpn_resync_if_needed ($mode, $ovpn_settings, $interface) { } /* make sure to wait until the boot scripts have finished */ -if (file_exists("{$g['varrun_path']}/booting")) +if (file_exists("{$g['varrun_path']}/booting")) { return; +} /* Input argument is a comma-separated list of gateway names, blank or "all". */ -if (isset($_GET['interface'])) +if (isset($_GET['interface'])) { $argument = $_GET['interface']; -else +} else { $argument = trim($argv[1], " \n"); +} -if((is_array($config['openvpn']['openvpn-server']) && count($config['openvpn']['openvpn-server'])) || - (is_array($config['openvpn']['openvpn-client']) && count($config['openvpn']['openvpn-client']))) { +if ((is_array($config['openvpn']['openvpn-server']) && count($config['openvpn']['openvpn-server'])) || + (is_array($config['openvpn']['openvpn-client']) && count($config['openvpn']['openvpn-client']))) { if (empty($argument) || $argument == "all") { - $argument = "all"; + $argument = "all"; $log_text = "all"; } else { $log_text = "endpoints that may use " . $argument; } log_error("OpenVPN: One or more OpenVPN tunnel endpoints may have changed its IP. Reloading " . $log_text . "."); -} else +} else { return; +} $openvpnlck = try_lock('openvpn', 10); if (!$openvpnlck) { @@ -98,29 +102,32 @@ if (!$openvpnlck) { $arg_array = explode(",",$argument); foreach ($arg_array as $arg_element) { $gwgroups = array(); - if ($arg_element == "all") - $interface = ""; - else { + if ($arg_element == "all") { + $interface = ""; + } else { // e.g. $arg_element = "WANGW", $interface = "wan" $interface = lookup_gateway_interface_by_name($arg_element); - if (empty($interface)) + if (empty($interface)) { $interface = $arg_element; - else + } else { // e.g. $arg_element = "WANGW", $gwgroups = array of gateway groups that use "wan" $gwgroups = gateway_is_gwgroup_member($arg_element); + } } - if(is_array($config['openvpn']['openvpn-server'])) { - foreach($config['openvpn']['openvpn-server'] as &$server) { - if ($server['interface'] == $interface || empty($interface) || (!empty($gwgroups) && in_array($server['interface'], $gwgroups))) + if (is_array($config['openvpn']['openvpn-server'])) { + foreach ($config['openvpn']['openvpn-server'] as &$server) { + if ($server['interface'] == $interface || empty($interface) || (!empty($gwgroups) && in_array($server['interface'], $gwgroups))) { openvpn_resync_if_needed('server', $server, $interface); + } } } if (is_array($config['openvpn']['openvpn-client'])) { - foreach($config['openvpn']['openvpn-client'] as &$client) { - if ($client['interface'] == $interface || empty($interface) || (!empty($gwgroups) && in_array($client['interface'], $gwgroups))) + foreach ($config['openvpn']['openvpn-client'] as &$client) { + if ($client['interface'] == $interface || empty($interface) || (!empty($gwgroups) && in_array($client['interface'], $gwgroups))) { openvpn_resync_if_needed('client', $client, $interface); + } } } } diff --git a/etc/rc.packages b/etc/rc.packages index c56cf84cae..7561c0ed2b 100755 --- a/etc/rc.packages +++ b/etc/rc.packages @@ -2,31 +2,31 @@ >> Killing php-fpm" -/bin/pkill -F /var/run/php-fpm.pid +/bin/pkill -F /var/run/php-fpm.pid sleep 2 # Run the php.ini setup file and populate diff --git a/etc/rc.php_ini_setup b/etc/rc.php_ini_setup index 94de766300..46ccb29ffa 100755 --- a/etc/rc.php_ini_setup +++ b/etc/rc.php_ini_setup @@ -40,7 +40,7 @@ fi # Grab amount of memory that is detected if [ -f /var/log/dmesg.boot ]; then AVAILMEM=`/bin/cat /var/log/dmesg.boot |/usr/bin/awk '/avail memory/ { memory=($4 / 1048576); printf("%0.0f\n", memory); exit}'` -else +else AVAILMEM=`/sbin/dmesg -a |/usr/bin/awk '/avail memory/ { memory=($4 / 1048576); printf("%0.0f\n", memory); exit}'` fi @@ -61,7 +61,7 @@ if [ ${REALMEM} -lt $MIN_REALMEM_FOR_APC ]; then echo ">>> Under $MIN_REALMEM_FOR_APC megabytes of ram detected. Not enabling APC." | /usr/bin/logger -p daemon.info -i -t rc.php_ini_setup else - # Calculate APC SHM size according + # Calculate APC SHM size according # to detected memory values if [ "$AVAILMEM" -gt "135" ]; then APCSHMEMSIZE="10M" @@ -83,11 +83,11 @@ fi # Set upload directory if [ "$PLATFORM" = "nanobsd" ]; then UPLOADTMPDIR=`/usr/bin/grep upload_path /etc/inc/globals.inc | /usr/bin/cut -d'"' -f4` -else +else UPLOADTMPDIR="/tmp" fi -# Define php modules. Do not add .so, it will +# Define php modules. Do not add .so, it will # be done automatically by the script below. PHPMODULES="standard" if [ "$LOWMEM" != "TRUE" ]; then @@ -98,7 +98,7 @@ PHPMODULES="$PHPMODULES xml libxml dom" PHPMODULES="$PHPMODULES simplexml xmlreader xmlwriter" # Downloading via HTTP/FTP (pkg mgr, etc) PHPMODULES="$PHPMODULES curl date" -# Internationalization +# Internationalization PHPMODULES="$PHPMODULES gettext" # User manager PHPMODULES="$PHPMODULES ldap openssl pcntl" @@ -379,7 +379,7 @@ fi # Remove old log file if it exists. if [ -f /var/run/php_modules_load_errors.txt ]; then /bin/rm /var/run/php_modules_load_errors.txt -fi +fi for EXT in $PHPMODULES; do PHPMODULESLC="$PHPMODULESLC `echo "$EXT" | /usr/bin/tr '[:upper:]' '[:lower:]'`" @@ -392,7 +392,7 @@ for EXT in $PHPMODULESLC; do for LM in $LOADED_MODULES; do if [ "$EXT" = "$LM" ]; then SHOULDREMOVE="false" - fi + fi done # Handle low memory situations if [ "$LOWMEM" = "TRUE" ]; then diff --git a/etc/rc.prunecaptiveportal b/etc/rc.prunecaptiveportal index c7011a55d3..7dff6a2fb8 100755 --- a/etc/rc.prunecaptiveportal +++ b/etc/rc.prunecaptiveportal @@ -4,20 +4,20 @@ /* rc.prunecaptiveportal part of m0n0wall (http://m0n0.ch/wall) - + Copyright (C) 2003-2004 Manuel Kasper . All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE @@ -31,7 +31,7 @@ */ /* parse the configuration and include all functions used below */ -/* config.inc retrives the util.inc and globals.inc */ +/* config.inc retrieves the util.inc and globals.inc */ require_once("config.inc"); require_once("functions.inc"); require_once("filter.inc"); @@ -51,10 +51,10 @@ $cpzoneid = $config['captiveportal'][$cpzone]['zoneid']; if (file_exists("{$g['tmp_path']}/.rc.prunecaptiveportal.{$cpzone}.running")) { $stat = stat("{$g['tmp_path']}/.rc.prunecaptiveportal.{$cpzone}.running"); - if (time() - $stat['mtime'] >= 120) + if (time() - $stat['mtime'] >= 120) { @unlink("{$g['tmp_path']}/.rc.prunecaptiveportal.{$cpzone}.running"); - else { - log_error("Skipping CP prunning process because previous/another instance is already running"); + } else { + log_error("Skipping CP pruning process because previous/another instance is already running"); return; } } diff --git a/etc/rc.reload_all b/etc/rc.reload_all index 00dc4efc5f..6dcc55b40e 100755 --- a/etc/rc.reload_all +++ b/etc/rc.reload_all @@ -2,31 +2,31 @@ = 0; $c--) { - if (is_numeric($which) && ($c != $which)) + if (is_numeric($which) && ($c != $which)) { continue; + } print_backup_info($confvers[$c], $c+1); echo "\n"; } @@ -70,7 +72,7 @@ function restore_history_backup($number) { $confirm = strtoupper(chop(fgets($fp))); if ($confirm == gettext("Y")) { conf_mount_rw(); - if(config_restore($g['conf_path'] . '/backup/config-' . $thisbackup['time'] . '.xml') == 0) { + if (config_restore($g['conf_path'] . '/backup/config-' . $thisbackup['time'] . '.xml') == 0) { echo "\n"; echo sprintf(gettext('Successfully reverted to timestamp %1$s with description "%2$s".'), date(gettext("n/j/y H:i:s"), $thisbackup['time']), $thisbackup['description']); echo "\n" . gettext("You may need to reboot the firewall or restart services before the restored configuration is fully active.") . "\n\n"; @@ -79,10 +81,10 @@ function restore_history_backup($number) { } conf_mount_ro(); } else { - echo gettext("Restore canceled.") . "\n"; + echo gettext("Restore cancelled.") . "\n"; } } else { - echo gettext("Restore canceled due to invalid input.") . "\n"; + echo gettext("Restore cancelled due to invalid input.") . "\n"; } } diff --git a/etc/rc.restore_full_backup b/etc/rc.restore_full_backup index 05bb060af8..57cf7cba09 100755 --- a/etc/rc.restore_full_backup +++ b/etc/rc.restore_full_backup @@ -8,7 +8,7 @@ if [ `tar tzPf $1 /etc/rc 2>/dev/null` ]; then EXCLUDE="--exclude /cf/conf/config.xml" rm /tmp/do_not_restore_config.xml else - EXCLUDE="" + EXCLUDE="" fi tar xzPfU $1 $EXCLUDE -C / 2>/var/etc/restore_log.txt echo "Restore of $1 complete." diff --git a/etc/rc.savevoucher b/etc/rc.savevoucher index 29b18d6968..8f2d88ddb6 100755 --- a/etc/rc.savevoucher +++ b/etc/rc.savevoucher @@ -2,20 +2,20 @@ . All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE @@ -35,6 +35,6 @@ require_once("shaper.inc"); require_once("captiveportal.inc"); require_once("voucher.inc"); - + voucher_save_db_to_config(); ?> diff --git a/etc/rc.shutdown b/etc/rc.shutdown index 2102ff476f..aa6468aa42 100755 --- a/etc/rc.shutdown +++ b/etc/rc.shutdown @@ -6,7 +6,7 @@ if ! /usr/bin/lockf -s -t 30 /tmp/config.lock /usr/bin/true; then fi product=`cat /etc/inc/globals.inc | grep product_name | cut -d'"' -f4` - + echo echo "${product} is now shutting down ..." echo diff --git a/etc/rc.start_packages b/etc/rc.start_packages index 37be6938b2..ba97974500 100755 --- a/etc/rc.start_packages +++ b/etc/rc.start_packages @@ -2,31 +2,31 @@ = 90) - @unlink("{$g['tmp_path']}/.rc.start_packages.running"); - else { - log_error("Skipping STARTing packages process because previous/another instance is already running"); - return; - } + $stat = stat("{$g['tmp_path']}/.rc.start_packages.running"); + if (time() - $stat['mtime'] >= 90) { + @unlink("{$g['tmp_path']}/.rc.start_packages.running"); + } else { + log_error("Skipping STARTing packages process because previous/another instance is already running"); + return; + } } @file_put_contents("{$g['tmp_path']}/.rc.start_packages.running", ""); @@ -53,16 +53,17 @@ if (file_exists("{$g['tmp_path']}/.rc.start_packages.running")) { log_error("Restarting/Starting all packages."); $rcfiles = glob(RCFILEPREFIX . "*.sh"); -if (!$rcfiles) +if (!$rcfiles) { $rcfiles = array(); -else { +} else { $rcfiles = array_flip($rcfiles); - if (!$rcfiles) + if (!$rcfiles) { $rcfiles = array(); + } } if (is_array($config['installedpackages']['package'])) { - foreach($config['installedpackages']['package'] as $pkgid => $package) { + foreach ($config['installedpackages']['package'] as $pkgid => $package) { echo " Starting package {$package['name']}..."; sync_package($pkgid); $internal_name = get_pkg_internal_name($package); diff --git a/etc/rc.update_alias_url_data b/etc/rc.update_alias_url_data index 2dfdc71965..bf4f48f8a7 100755 --- a/etc/rc.update_alias_url_data +++ b/etc/rc.update_alias_url_data @@ -2,22 +2,22 @@ All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE @@ -31,7 +31,7 @@ */ /* parse the configuration and include all functions used below */ -/* config.inc retrives the util.inc and globals.inc */ +/* config.inc retrieves the util.inc and globals.inc */ require_once("config.inc"); require_once("functions.inc"); diff --git a/etc/rc.update_bogons.sh b/etc/rc.update_bogons.sh index 6dd2a5fcd8..85cb7df9c5 100755 --- a/etc/rc.update_bogons.sh +++ b/etc/rc.update_bogons.sh @@ -13,14 +13,14 @@ process_url() { local url=$2 local filename=${url##*/} local ext=${filename#*.} - + /usr/bin/fetch -a -w 600 -T 30 -q -o $file "${url}" - + if [ ! -f $file ]; then echo "Could not download ${url}" | logger proc_error="true" fi - + case "$ext" in tar) mv $file $file.tmp @@ -41,11 +41,11 @@ process_url() { *) ;; esac - + if [ -f $file.tmp ]; then rm $file.tmp fi - + if [ ! -f $file ]; then echo "Could not extract ${filename}" | logger proc_error="true" @@ -56,11 +56,11 @@ echo "rc.update_bogons.sh is starting up." | logger # Sleep for some time, unless an argument is specified. if [ "$1" = "" ]; then - # Grab a random value - value=`od -A n -d -N2 /dev/random | awk '{ print $1 }'` - echo "rc.update_bogons.sh is sleeping for $value" | logger - sleep $value -fi + # Grab a random value + value=`od -A n -d -N2 /dev/random | awk '{ print $1 }'` + echo "rc.update_bogons.sh is sleeping for $value" | logger + sleep $value +fi echo "rc.update_bogons.sh is beginning the update cycle." | logger @@ -92,9 +92,9 @@ ON_DISK_V6_CKSUM=`md5 /tmp/bogonsv6 | awk '{ print $4 }'` if [ "$BOGON_V4_CKSUM" = "$ON_DISK_V4_CKSUM" ] || [ "$BOGON_V6_CKSUM" = "$ON_DISK_V6_CKSUM" ]; then # At least one of the downloaded checksums matches, so mount RW /etc/rc.conf_mount_rw - + ENTRIES_MAX=`pfctl -s memory | awk '/table-entries/ { print $4 }'` - + if [ "$BOGON_V4_CKSUM" = "$ON_DISK_V4_CKSUM" ]; then ENTRIES_TOT=`pfctl -vvsTables | awk '/Addresses/ {s+=$2}; END {print s}'` ENTRIES_V4=`pfctl -vvsTables | awk '/-\tbogons$/ {getline; print $2}'` @@ -138,14 +138,14 @@ if [ "$BOGON_V4_CKSUM" = "$ON_DISK_V4_CKSUM" ] || [ "$BOGON_V6_CKSUM" = "$ON_DIS echo "Could not download ${v6url} (checksum mismatch)" | logger checksum_error="true" fi - + # We mounted RW, so switch back to RO /etc/rc.conf_mount_ro fi if [ "$checksum_error" != "" ]; then # Relaunch and sleep - sh /etc/rc.update_bogons.sh & + sh /etc/rc.update_bogons.sh & exit fi diff --git a/etc/rc.update_urltables b/etc/rc.update_urltables index de40631fb4..1c2913a178 100755 --- a/etc/rc.update_urltables +++ b/etc/rc.update_urltables @@ -40,10 +40,11 @@ if (count($todo) > 0) { if ($r == 1) { $result = ""; // TODO: Change it when pf supports tables with ports - if ($t['type'] == "urltable") + if ($t['type'] == "urltable") { exec("/sbin/pfctl -t " . escapeshellarg($t['name']) . " -T replace -f /var/db/aliastables/" . escapeshellarg($t['name']) . ".txt 2>&1", $result); - else + } else { $filter_reload = true; + } log_error("{$argv[0]}: Updated {$t['name']} content from {$t['url']}: {$result[0]}"); } elseif ($r == -1) { log_error("{$argv[0]}: {$t['name']} does not need updating."); @@ -52,7 +53,8 @@ if (count($todo) > 0) { } } - if ($filter_reload) + if ($filter_reload) { send_event("filter reload"); + } } ?> diff --git a/etc/sshd b/etc/sshd index 6982554bbb..7fb0f7a10e 100755 --- a/etc/sshd +++ b/etc/sshd @@ -60,21 +60,22 @@ } /* restore ssh data for nanobsd platform */ - if($g['platform'] == "nanobsd" and file_exists("/conf/sshd/ssh_host_key") and !file_exists("{$sshConfigDir}/ssh_host_key.pub")) { + if ($g['platform'] == "nanobsd" and file_exists("/conf/sshd/ssh_host_key") and !file_exists("{$sshConfigDir}/ssh_host_key.pub")) { echo "Restoring SSH from /conf/sshd/"; exec("/bin/cp -p /conf/sshd/* {$sshConfigDir}/"); /* make sure host private key permissions aren't too open so sshd won't complain */ - foreach($keyfiles as $f2c) { - if(file_exists("{$sshConfigDir}/{$f2c}")) + foreach ($keyfiles as $f2c) { + if (file_exists("{$sshConfigDir}/{$f2c}")) { chmod("{$sshConfigDir}/{$f2c}", 0600); + } } } /* if any of these files are 0 bytes then they are corrupted. * remove them */ - foreach($keyfiles as $f2c) { + foreach ($keyfiles as $f2c) { if (!file_exists("{$sshConfigDir}/{$f2c}") || filesize("{$sshConfigDir}/{$f2c}") == 0) { /* Make sure we remove both files */ unlink_if_exists($sshConfigDir . '/' . basename($f2c, ".pub")); @@ -87,15 +88,16 @@ mkdir("/var/empty", 0555); } - if(!file_exists("/var/log/lastlog")) { + if (!file_exists("/var/log/lastlog")) { /* Login related files. */ @touch("/var/log/lastlog"); } - if (is_array($config['system']['ssh']) && !empty($config['system']['ssh']['port'])) + if (is_array($config['system']['ssh']) && !empty($config['system']['ssh']['port'])) { $sshport = $config['system']['ssh']['port']; - else + } else { $sshport = 22; + } /* Include default configuration for pfSense */ $sshconf = "# This file is automatically generated at startup\n"; @@ -124,7 +126,7 @@ $sshconf .= "Port $sshport\n"; /* Hide FreeBSD version */ $sshconf .= "VersionAddendum \n"; - + /* Apply package SSHDCond settings if config file exists */ if (file_exists("/etc/sshd_extra")) { $fdExtra = fopen("/etc/sshd_extra", 'r'); @@ -137,7 +139,7 @@ @file_put_contents("{$sshConfigDir}/sshd_config", $sshconf); /* mop up from a badly implemented ssh keys -> cf backup */ - if($config['ssh']['dsa_key'] <> "") { + if ($config['ssh']['dsa_key'] <> "") { unset($config['ssh']['dsa_key']); unset($config['ssh']['ecdsa_key']); unset($config['ssh']['ed25519_key']); @@ -151,16 +153,16 @@ } /* are we already running? if so exit */ - if(is_subsystem_dirty('sshdkeys')) { + if (is_subsystem_dirty('sshdkeys')) { unset($keys, $keyfiles); return; } - + // Check for all needed key files. If any are missing, the keys need to be regenerated. $generate_keys = array(); foreach ($keys as $key) { if (!file_exists("{$sshConfigDir}/ssh_host_{$key['suffix']}key") || - !file_exists("{$sshConfigDir}/ssh_host_{$key['suffix']}key.pub")) { + !file_exists("{$sshConfigDir}/ssh_host_{$key['suffix']}key.pub")) { $generate_keys[] = $key; } } @@ -179,13 +181,13 @@ /* kill existing sshd process, server only, not the childs */ $sshd_pid = exec("ps ax | egrep '/usr/sbin/[s]shd' | awk '{print $1}'"); - if($sshd_pid <> "") { + if ($sshd_pid <> "") { echo "stopping ssh process $sshd_pid \n"; @posix_kill($sshd_pid, SIGTERM); } /* Launch new server process */ $status = mwexec("/usr/sbin/sshd"); - if($status <> 0) { + if ($status <> 0) { file_notice("sshd_startup", "SSHD failed to start.", "SSHD Daemon", ""); echo "error!\n"; } else { @@ -193,9 +195,10 @@ } // NanoBSD - if($g['platform'] == "nanobsd") { - if(!is_dir("/conf/sshd")) + if ($g['platform'] == "nanobsd") { + if (!is_dir("/conf/sshd")) { mkdir("/conf/sshd", 0750); + } $_gb = exec("/bin/cp -p {$sshConfigDir}/ssh_host* /conf/sshd"); } conf_mount_ro(); From a8efbde4aa59a2384c26ef8b0a5b0a847abcabec Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Wed, 25 Feb 2015 01:43:04 +0545 Subject: [PATCH 123/257] Minor spacing edits to etc files --- etc/rc.bootup | 2 +- etc/rc.start_packages | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/etc/rc.bootup b/etc/rc.bootup index ef26679e42..50190e10a5 100755 --- a/etc/rc.bootup +++ b/etc/rc.bootup @@ -39,7 +39,7 @@ function rescue_detect_keypress() { $timeout=9; echo "\n"; echo "[ Press R to enter recovery mode or ]\n"; - echo "[ press I to launch the installer ]\n\n"; + echo "[ press I to launch the installer ]\n\n"; echo "(R)ecovery mode can assist by rescuing config.xml\n"; echo "from a broken hard disk installation, etc.\n\n"; echo "(I)nstaller may be invoked now if you do \n"; diff --git a/etc/rc.start_packages b/etc/rc.start_packages index ba97974500..c1edf195e2 100755 --- a/etc/rc.start_packages +++ b/etc/rc.start_packages @@ -41,10 +41,10 @@ require_once("service-utils.inc"); if (file_exists("{$g['tmp_path']}/.rc.start_packages.running")) { $stat = stat("{$g['tmp_path']}/.rc.start_packages.running"); if (time() - $stat['mtime'] >= 90) { - @unlink("{$g['tmp_path']}/.rc.start_packages.running"); + @unlink("{$g['tmp_path']}/.rc.start_packages.running"); } else { - log_error("Skipping STARTing packages process because previous/another instance is already running"); - return; + log_error("Skipping STARTing packages process because previous/another instance is already running"); + return; } } From e2d700da1d1e334eaf97936a5c5a0faeff0ef5d2 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 25 Feb 2015 00:25:51 -0600 Subject: [PATCH 124/257] remove old, unused code --- etc/inc/interfaces.inc | 2 -- 1 file changed, 2 deletions(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index 1f95f87779..2a07901f98 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -2203,8 +2203,6 @@ function interface_wireless_clone($realif, $wlcfg) { $newif = trim($out[0]); // Rename the interface to {$parentnic}_wlan{$number}#: EX: ath0_wlan0 pfSense_interface_rename($newif, $realif); - // FIXME: not sure what ngctl is for. Doesn't work. - // mwexec("/usr/sbin/ngctl name {$newif}: {$realif}", false); file_put_contents("{$g['tmp_path']}/{$realif}_oldmac", get_interface_mac($realif)); } return true; From e1c4a5ffca69242bb44b4f1841e555bbe2ef57f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Wed, 25 Feb 2015 16:16:02 +0100 Subject: [PATCH 125/257] Ticket #4418 Make the DNS names attr 28675 space separated as identified by Jeffrey Dvornek --- etc/inc/vpn.inc | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 1be37deafe..830661d69e 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -406,12 +406,27 @@ EOD; if (!empty($a_client['dns_domain'])) { $strongswan .= "\t\t\t# Search domain and default domain\n"; $strongswan .= "\t\t\t28674 = \"{$a_client['dns_domain']}\"\n"; - if (empty($a_client['dns_split'])) + if (empty($a_client['dns_split'])) { + $ipsec_dns = explode(',', $a_client['dns_domain']); + foreach ($ipsec_dns as $ipsecidx => $ipsecdns) { + $ipsec_dns[$ipsecidx] = trim($ipsecdns); + } + $a_client['dns_domain'] = implode(' ', $ipsec_dns); + unset($ipsec_dns); + $strongswan .= "\t\t\t28675 = \"{$a_client['dns_domain']}\""; + } $strongswan .= "\n"; } if (!empty($a_client['dns_split'])) { + $ipsec_dns = explode(',', $a_client['dns_split']); + foreach ($ipsec_dns as $ipsecidx => $ipsecdns) { + $ipsec_dns[$ipsecidx] = trim($ipsecdns); + } + $a_client['dns_split'] = implode(' ', $ipsec_dns); + unset($ipsec_dns); + $strongswan .= "\t\t\t28675 = \"{$a_client['dns_split']}\"\n"; } From 1f3d4db05e5e09cab6562a4b2c65ebbeee55ec45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Wed, 25 Feb 2015 16:19:26 +0100 Subject: [PATCH 126/257] Ticket #4418 make sure the dns_split is separated with spaces rather than space or comma to comply with strongswan requirements. --- etc/inc/vpn.inc | 7 ------- usr/local/www/vpn_ipsec_mobile.php | 2 +- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 830661d69e..a07bdd0907 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -407,13 +407,6 @@ EOD; $strongswan .= "\t\t\t# Search domain and default domain\n"; $strongswan .= "\t\t\t28674 = \"{$a_client['dns_domain']}\"\n"; if (empty($a_client['dns_split'])) { - $ipsec_dns = explode(',', $a_client['dns_domain']); - foreach ($ipsec_dns as $ipsecidx => $ipsecdns) { - $ipsec_dns[$ipsecidx] = trim($ipsecdns); - } - $a_client['dns_domain'] = implode(' ', $ipsec_dns); - unset($ipsec_dns); - $strongswan .= "\t\t\t28675 = \"{$a_client['dns_domain']}\""; } $strongswan .= "\n"; diff --git a/usr/local/www/vpn_ipsec_mobile.php b/usr/local/www/vpn_ipsec_mobile.php index 98072d810f..2b70809be1 100644 --- a/usr/local/www/vpn_ipsec_mobile.php +++ b/usr/local/www/vpn_ipsec_mobile.php @@ -146,7 +146,7 @@ if ($_POST['submit']) { if ($pconfig['dns_split_enable']) { if (!empty($pconfig['dns_split'])) { - $domain_array=preg_split("/[ ,]+/",$pconfig['dns_split']); + $domain_array=explode(' ', $pconfig['dns_split']); foreach ($domain_array as $curdomain) { if (!is_domain($curdomain)) { $input_errors[] = gettext("A valid split DNS domain list must be specified."); From 883096d8c634d2936266e04f29f79a145fc72a8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Wed, 25 Feb 2015 16:22:17 +0100 Subject: [PATCH 127/257] Ticket #4418 Actually make each entry a clear token to strongswan parser for dns_split --- etc/inc/vpn.inc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index a07bdd0907..cec286dffc 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -415,12 +415,13 @@ EOD; if (!empty($a_client['dns_split'])) { $ipsec_dns = explode(',', $a_client['dns_split']); foreach ($ipsec_dns as $ipsecidx => $ipsecdns) { - $ipsec_dns[$ipsecidx] = trim($ipsecdns); + $ipsecdns = trime($ipsecdns); + $ipsec_dns[$ipsecidx] = "\"{$ipsecdns}\""; } $a_client['dns_split'] = implode(' ', $ipsec_dns); unset($ipsec_dns); - $strongswan .= "\t\t\t28675 = \"{$a_client['dns_split']}\"\n"; + $strongswan .= "\t\t\t28675 = {$a_client['dns_split']}\n"; } if (!empty($a_client['login_banner'])) From 7af43cb02dcac5af8ed44ea1a65a91c6da7ee9c3 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Wed, 25 Feb 2015 23:06:32 +0545 Subject: [PATCH 128/257] interface_netgraph_needed can miss setting found equals true This routine seems to go looking to see if the passed-in interface is PPP-style. At the end, if it is not PPP-style then it calls pfsense_ngctl_detach. This foreach loop in its current state will always exit after the first iteration that is not mode "server". But it looks like it should look through all the 'pppoe' entries until it finds the interface or gets to the end. In theory the code will sometimes miss setting $found = true when it should have. And thus pfsense_ngctl_detach would get called later for a PPP-style interface. I noticed this while reviewing for code style guide - it is an example where the indenting shows the intention but there are no curlies to implement it. --- etc/inc/interfaces.inc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index 2a07901f98..2ca2bf3d10 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -134,9 +134,10 @@ function interface_netgraph_needed($interface = "wan") { foreach ($config['pppoes']['pppoe'] as $pppoe) { if ($pppoe['mode'] != "server") continue; - if ($pppoe['interface'] == $interface) + if ($pppoe['interface'] == $interface) { $found = true; break; + } } } if ($found == false) From 3d16300449b68833a4f37e8675871c0098fe4c5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Wed, 25 Feb 2015 21:26:53 +0100 Subject: [PATCH 129/257] Put the bits to use the new reset utility --- etc/inc/system.inc | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/etc/inc/system.inc b/etc/inc/system.inc index b099ed1416..f95e9f31d8 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -2012,6 +2012,7 @@ function system_check_reset_button() { case 'wrap': case 'FW7541': case 'APU': + case 'C2358': break; default: return 0; @@ -2064,6 +2065,9 @@ function system_identify_specific_platform() { case 'APU': return (array('name' => 'APU', 'descr' => 'Netgate APU')); break; + case 'RCC-VE': + return (array('name' => 'C2358', 'descr' => 'Netgate C2358')); + break; } /* the rest of the code only deals with 'embedded' platforms */ From 1022105058c4550508dc801bb6cd233625a17226 Mon Sep 17 00:00:00 2001 From: k-paulius Date: Wed, 25 Feb 2015 20:44:50 -0600 Subject: [PATCH 130/257] Check if variables are set before trying to pass them to function substr_count to avoid generating PHP alerts. --- usr/local/www/services_ntpd.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/services_ntpd.php b/usr/local/www/services_ntpd.php index 05cc0a1e2b..8c2dcaa6a0 100644 --- a/usr/local/www/services_ntpd.php +++ b/usr/local/www/services_ntpd.php @@ -297,10 +297,10 @@ include("head.inc"); echo " "; echo "\n prefer "; echo "\n noselect\n
\n\n"; } ?> From 1bfcf6f14df50e8b3948b45adf8c9590d1af38ef Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 26 Feb 2015 09:35:00 +0545 Subject: [PATCH 131/257] Code style guide changes for miscellaneous files under etc --- etc/phpshellsessions/disablecarp | 2 +- etc/phpshellsessions/enablecarp | 19 +-- etc/phpshellsessions/gitsync | 188 +++++++++++++++++------------- etc/phpshellsessions/installpkg | 14 ++- etc/phpshellsessions/listpkg | 5 +- etc/phpshellsessions/removeshaper | 3 +- etc/phpshellsessions/svc | 5 +- etc/phpshellsessions/uninstallpkg | 19 +-- etc/ssl/openssl.cnf | 6 +- 9 files changed, 149 insertions(+), 112 deletions(-) diff --git a/etc/phpshellsessions/disablecarp b/etc/phpshellsessions/disablecarp index 1ad71aea86..167326937e 100644 --- a/etc/phpshellsessions/disablecarp +++ b/etc/phpshellsessions/disablecarp @@ -4,7 +4,7 @@ require_once("interfaces.inc"); require_once("util.inc"); set_single_sysctl("net.inet.carp.allow", "0"); -if(is_array($config['virtualip']['vip'])) { +if (is_array($config['virtualip']['vip'])) { $viparr = &$config['virtualip']['vip']; foreach ($viparr as $vip) { switch ($vip['mode']) { diff --git a/etc/phpshellsessions/enablecarp b/etc/phpshellsessions/enablecarp index c02a606d6b..276f29a78f 100644 --- a/etc/phpshellsessions/enablecarp +++ b/etc/phpshellsessions/enablecarp @@ -3,18 +3,19 @@ require_once("config.inc"); require_once("interfaces.inc"); require_once("util.inc"); -if(is_array($config['virtualip']['vip'])) { +if (is_array($config['virtualip']['vip'])) { $viparr = &$config['virtualip']['vip']; foreach ($viparr as $vip) { switch ($vip['mode']) { - case "carp": - interface_carp_configure($vip); - sleep(1); - break; - case "ipalias": - if (strpos($vip['interface'], '_vip')) - interface_ipalias_configure($vip); - break; + case "carp": + interface_carp_configure($vip); + sleep(1); + break; + case "ipalias": + if (strpos($vip['interface'], '_vip')) { + interface_ipalias_configure($vip); + } + break; } } } diff --git a/etc/phpshellsessions/gitsync b/etc/phpshellsessions/gitsync index 14e169b4a8..617d816eee 100644 --- a/etc/phpshellsessions/gitsync +++ b/etc/phpshellsessions/gitsync @@ -10,7 +10,7 @@ require_once("filter.inc"); require_once("shaper.inc"); require_once("rrd.inc"); require_once("pfsense-utils.inc"); - + $GIT_PKG = "git"; // Either "git" or the full package URL $GIT_BIN= "/usr/pbi/bin/git"; $GIT_REPO = "git://github.com/pfsense/pfsense.git"; @@ -32,27 +32,29 @@ global $g; global $argv; global $command_split; -if(is_array($command_split)) +if (is_array($command_split)) { $temp_args = array_slice($command_split, 2); -else +} else { $temp_args = array_slice($argv, 3); +} $valid_args = array( "--minimal" => "\tPerform a minimal copy of only the updated files.\n" . - "\tNot recommended if the system has files modified by any method other\n" . - "\tthan gitsync.\n", + "\tNot recommended if the system has files modified by any method other\n" . + "\tthan gitsync.\n", "--help" => "\tDisplay this help list.\n" ); $args = array(); $arg_count = 0; -while(!empty($temp_args)) { +while (!empty($temp_args)) { $arg = array_shift($temp_args); - if($arg[0] == '-') { - switch($arg) { + if ($arg[0] == '-') { + switch ($arg) { case "--help": echo "Usage: playback gitsync [options] [[repository] ]\nOptions:\n"; - foreach($valid_args as $arg_name => $arg_desc) + foreach($valid_args as $arg_name => $arg_desc) { echo $arg_name . "\n" . $arg_desc; + } exit; case "--upgrading": // Disables all interactive functions and neither PHP @@ -73,7 +75,7 @@ while(!empty($temp_args)) { unlink_if_exists("/tmp/config.cache"); conf_mount_rw(); -if(!file_exists($GIT_BIN)) { +if (!file_exists($GIT_BIN)) { echo "Cannot find git, fetching...\n"; require_once("config.inc"); require_once("util.inc"); @@ -94,8 +96,9 @@ if(!file_exists($GIT_BIN)) { if (($g['platform'] == "nanobsd")) { $pkgtmpdir = "/usr/bin/env PKG_TMPDIR=/root/ "; $pkgstagingdir = "/root/tmp"; - if (!is_dir($pkgstagingdir)) + if (!is_dir($pkgstagingdir)) { mkdir($pkgstagingdir); + } $pkgstaging = "-t {$pkgstagingdir}/instmp.XXXXXX"; } system("{$pkgtmpdir}/usr/sbin/pkg_add {$pkgstaging} -r {$GIT_PKG}"); @@ -107,34 +110,38 @@ if(!file_exists($GIT_BIN)) { } # Remove mainline if exists (older) -if(is_dir("/root/pfsense/mainline")) +if (is_dir("/root/pfsense/mainline")) { exec("rm -rf /root/pfsense/mainline"); +} # Remove RELENG_1_2 if exists (older) -if(is_dir("/root/pfsense/RELENG_1_2")) +if (is_dir("/root/pfsense/RELENG_1_2")) { exec("rm -rf /root/pfsense/RELENG_1_2"); +} # Remove HEAD if exists (older) -if(is_dir("/root/pfsense/HEAD")) +if (is_dir("/root/pfsense/HEAD")) { exec("rm -rf /root/pfsense/HEAD"); +} -if(file_exists("/root/cvssync_backup.tgz")) { +if (file_exists("/root/cvssync_backup.tgz")) { $backup_date = `ls -lah /root/cvssync_backup.tgz | awk '{ print $6,$7,$8 }'`; $tmp = array("RESTORE" => "Restores prior CVSSync backup data performed at {$backup_date}"); $branches = array_merge($branches, $tmp); } -if(is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) { +if (is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) { exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} config remote.origin.url", $output_str, $ret); - if(is_array($output_str) && !empty($output_str[0])) + if (is_array($output_str) && !empty($output_str[0])) { $GIT_REPO = $output_str[0]; + } unset($output_str); } -if(!$args[0] && !$upgrading) { +if (!$args[0] && !$upgrading) { echo "\nCurrent repository is $GIT_REPO\n"; echo "\nPlease select which branch you would like to sync against:\n\n"; - foreach($branches as $branchname => $branchdesc) { + foreach ($branches as $branchname => $branchdesc) { echo "{$branchname} \t {$branchdesc}\n"; } echo "\nOr alternatively you may enter a custom RCS branch URL (Git or HTTP).\n\n"; @@ -144,51 +151,55 @@ if(!$args[0] && !$upgrading) { $branch = $args[0]; } -if($args[1] == "NOBACKUP") +if ($args[1] == "NOBACKUP") { $nobackup = true; -else +} else { $nobackup = false; +} // If the repository has been fetched before, build a list of its branches. -if(is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) { +if (is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) { exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} branch -r", $branch_list, $ret); - if($ret == 0 && is_array($branch_list)) { + if ($ret == 0 && is_array($branch_list)) { foreach ($branch_list as $branch_item) { $branch_item = substr(strrchr($branch_item, "/"), 1); - if (!isset($branches[$branch_item])) + if (!isset($branches[$branch_item])) { $branches[$branch_item] = " "; + } } } } $found = false; -foreach($branches as $branchname => $branchdesc) { - if($branchname == $branch) +foreach ($branches as $branchname => $branchdesc) { + if ($branchname == $branch) { $found = true; + } } -if(!$found) { - if(isURL($branch) && !$upgrading) { - if($args[1]) { +if (!$found) { + if (isURL($branch) && !$upgrading) { + if ($args[1]) { $GIT_REPO = $branch; $branch = $args[1]; $found = true; - } - else { + } else { echo "\n"; echo "NOTE: $branch was not found.\n\n"; $command = readline("Is this a custom GIT URL? [y]? "); - if(strtolower($command) == "y" or $command == "") { + if (strtolower($command) == "y" or $command == "") { $GIT_REPO = $branch; $command = readline("Checkout which branch [${DEFAULT_BRANCH}]? "); - if($command == "") + if ($command == "") { $branch = $DEFAULT_BRANCH; - if($command) + } + if ($command) { $branch = $command; + } $found = true; } } } - if(!$found) { + if (!$found) { echo "\nNo valid branch found. Exiting.\n\n"; conf_mount_ro(); exit; @@ -196,17 +207,18 @@ if(!$found) { } $merge_repos = array(); -if(file_exists($GITSYNC_MERGE)) { +if (file_exists($GITSYNC_MERGE)) { $gitsync_merges = file($GITSYNC_MERGE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - if(!empty($gitsync_merges) && is_array($gitsync_merges)) { + if (!empty($gitsync_merges) && is_array($gitsync_merges)) { echo "\n===> Automatic merge list read from ${GITSYNC_MERGE}\n"; - foreach($gitsync_merges as $merge_line_num => $merge_line) { + foreach ($gitsync_merges as $merge_line_num => $merge_line) { $merge_comments = explode("#", trim($merge_line)); - if(empty($merge_comments[0])) + if (empty($merge_comments[0])) { continue; + } $merge_line = explode(" ", trim($merge_comments[0])); - if(count($merge_line) != 2 || empty($merge_line[0]) || empty($merge_line[1])) { + if (count($merge_line) != 2 || empty($merge_line[0]) || empty($merge_line[1])) { echo "\nLine " . ($merge_line_num + 1) . " does not have the correct parameter count or has improper spacing.\n"; echo "Expected parameters: repository_url branch\n"; echo "Line read: " . implode(" ", $merge_line) . "\n\n"; @@ -218,22 +230,23 @@ if(file_exists($GITSYNC_MERGE)) { } } } -if(!$args[0] && !$upgrading) { +if (!$args[0] && !$upgrading) { do { echo "\nAdd a custom RCS branch URL (Git or HTTP) to merge in or press enter if done.\n\n"; $merge_repo = readline("> "); - if(!empty($merge_repo)) { + if (!empty($merge_repo)) { $merge_branch = readline("Merge which branch [${DEFAULT_BRANCH}]? "); - if($merge_branch == "") + if ($merge_branch == "") { $merge_repos[] = array('repo' => $merge_repo, 'branch' => $DEFAULT_BRANCH); - else if($merge_branch) + } else if ($merge_branch) { $merge_repos[] = array('repo' => $merge_repo, 'branch' => $merge_branch); + } } - } while(!empty($merge_repo)); + } while (!empty($merge_repo)); } -if($branch == "RESTORE" && $g['platform'] == "pfSense") { - if(!file_exists("/root/cvssync_backup.tgz")) { +if ($branch == "RESTORE" && $g['platform'] == "pfSense") { + if (!file_exists("/root/cvssync_backup.tgz")) { echo "Sorry, we could not find a previous CVSSync backup file.\n"; conf_mount_ro(); exit(); @@ -247,7 +260,7 @@ if($branch == "RESTORE" && $g['platform'] == "pfSense") { $nobackup = true; // do not backup embedded, livecd } -if($nobackup == false) { +if ($nobackup == false) { echo "===> Backing up current pfSense information...\n"; echo "===> Please wait... "; exec("tar czPf /root/cvssync_backup.tgz --exclude /root --exclude /dev --exclude /tmp --exclude /var/run --exclude /var/empty /"); @@ -259,7 +272,7 @@ if($nobackup == false) { echo "===> Checking out $branch\n"; // Git commands for resetting to the specified branch -if($branch == "build_commit") { +if ($branch == "build_commit") { $git_cmd = array( "cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} branch " . escapeshellarg($branch) . " 2>/dev/null", "cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} checkout -f " . escapeshellarg($branch) . " 2>/dev/null", @@ -274,28 +287,30 @@ if($branch == "build_commit") { } // Git 'er done! -if(is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) { +if (is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) { echo "===> Fetching updates...\n"; exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} config remote.origin.url " . escapeshellarg($GIT_REPO)); exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} fetch"); exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} clean -f -f -x -d"); run_cmds($git_cmd); } else { - exec("mkdir -p $CODIR/pfSenseGITREPO"); - echo "Executing cd $CODIR/pfSenseGITREPO && {$GIT_BIN} clone $GIT_REPO pfSenseGITREPO\n"; + exec("mkdir -p $CODIR/pfSenseGITREPO"); + echo "Executing cd $CODIR/pfSenseGITREPO && {$GIT_BIN} clone $GIT_REPO pfSenseGITREPO\n"; exec("cd $CODIR/pfSenseGITREPO && {$GIT_BIN} clone " . escapeshellarg($GIT_REPO) . " pfSenseGITREPO"); - if(is_dir("$CODIR/pfSenseGITREPO/pfSense")) + if (is_dir("$CODIR/pfSenseGITREPO/pfSense")) { exec("mv $CODIR/pfSenseGITREPO/pfSense $CODIR/pfSenseGITREPO/pfSenseGITREPO"); - if(is_dir("$CODIR/pfSenseGITREPO/mainline")) + } + if (is_dir("$CODIR/pfSenseGITREPO/mainline")) { exec("mv $CODIR/pfSenseGITREPO/mainline $CODIR/pfSenseGITREPO/pfSenseGITREPO"); + } run_cmds($git_cmd); } -foreach($merge_repos as $merge_repo) { +foreach ($merge_repos as $merge_repo) { echo "===> Merging branch {$merge_repo['branch']} from {$merge_repo['repo']}\n"; exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} pull " . escapeshellarg($merge_repo['repo']) . " " . escapeshellarg($merge_repo['branch']), $output_str, $ret); unset($output_str); - if($ret <> 0) { + if ($ret <> 0) { echo "\nMerge failed. Aborting sync.\n\n"; run_cmds($git_cmd); conf_mount_ro(); @@ -303,14 +318,16 @@ foreach($merge_repos as $merge_repo) { } } -if(isset($args["--minimal"])) { - if(file_exists("/etc/version.gitsync")) +if (isset($args["--minimal"])) { + if (file_exists("/etc/version.gitsync")) { $old_revision = trim(file_get_contents("/etc/version.gitsync")); - else if(file_exists("/etc/version.lastcommit")) + } else if (file_exists("/etc/version.lastcommit")) { $old_revision = trim(file_get_contents("/etc/version.lastcommit")); + } $files_to_copy = strtr(shell_exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} diff --name-only " . escapeshellarg($old_revision)), "\n", " "); -} else +} else { $files_to_copy = '--exclude .git .'; +} // Save new commit ID for later minimal file copies exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} rev-parse -q --verify HEAD > /etc/version.gitsync"); @@ -321,7 +338,7 @@ exec("mkdir -p /tmp/lighttpd/cache/compress/"); exec("cd ${CODIR}/pfSenseGITREPO/pfSenseGITREPO && find . -name CVS -exec rm -rf {} \; 2>/dev/null"); exec("cd ${CODIR}/pfSenseGITREPO/pfSenseGITREPO && find . -name pfSense.tgz -exec rm {} \; 2>/dev/null"); -// Remove files that we do not want to overwrite the system with +// Remove files that we do not want to overwrite the system with exec("rm ${CODIR}/pfSenseGITREPO/pfSenseGITREPO/etc/crontab 2>/dev/null"); exec("rm ${CODIR}/pfSenseGITREPO/pfSenseGITREPO/etc/master.passwd 2>/dev/null"); exec("rm ${CODIR}/pfSenseGITREPO/pfSenseGITREPO/etc/passwd 2>/dev/null"); @@ -341,13 +358,15 @@ exec("rm -f ${CODIR}/pfSenseGITREPO/pfSenseGITREPO/etc/syslog.conf 2>/dev/null") echo "===> Installing new files...\n"; -if($g['platform'] == "pfSense") +if ($g['platform'] == "pfSense") { $command = "cd $CODIR/pfSenseGITREPO/pfSenseGITREPO ; tar -cpf - {$files_to_copy} | (cd / ; tar -Uxpf -)"; -else +} else { $command = "cd $CODIR/pfSenseGITREPO/pfSenseGITREPO ; tar -cpf - {$files_to_copy} | (cd / ; tar -xpf -) 2>/dev/null"; -if(!empty($files_to_copy)) +} + +if (!empty($files_to_copy)) { exec($command); -else { +} else { echo "Already up-to-date.\n"; $upgrading = true; } @@ -357,19 +376,23 @@ exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} reset --hard >/dev/n // Remove obsolete files $files_to_remove = file("/etc/pfSense.obsoletedfiles"); -foreach($files_to_remove as $file_to_remove) - if(file_exists($file_to_remove)) +foreach ($files_to_remove as $file_to_remove) { + if (file_exists($file_to_remove)) { exec("/bin/rm -f $file_to_remove"); + } +} -if(!$upgrading) +if (!$upgrading) { post_cvssync_commands(); +} echo "===> Checkout complete.\n"; echo "\n"; -if(!$upgrading) +if (!$upgrading) { echo "Your system is now sync'd and PHP and Lighty will be restarted in 5 seconds.\n\n"; -else +} else { echo "Your system is now sync'd.\n\n"; +} function post_cvssync_commands() { echo "===> Removing FAST-CGI temporary files...\n"; @@ -386,7 +409,7 @@ function post_cvssync_commands() { exec("pfctl -f /tmp/rules.debug"); echo "\n"; - if(file_exists("/etc/rc.php_ini_setup")) { + if (file_exists("/etc/rc.php_ini_setup")) { echo "===> Running /etc/rc.php_ini_setup..."; exec("/etc/rc.php_ini_setup"); echo "\n"; @@ -395,14 +418,15 @@ function post_cvssync_commands() { /* lock down console if necessary */ echo "===> Locking down the console if needed...\n"; reload_ttys(); - + echo "===> Signaling PHP and Lighty restart..."; $fd = fopen("/tmp/restart_lighty", "w"); fwrite($fd, "#!/bin/sh\n"); fwrite($fd, "sleep 5\n"); fwrite($fd, "/usr/local/sbin/pfSctl -c 'service restart webgui'\n"); - if(file_exists("/var/etc/lighty-CaptivePortal.conf")) + if (file_exists("/var/etc/lighty-CaptivePortal.conf")) { fwrite($fd, "/usr/local/sbin/lighttpd -f /var/etc/lighty-CaptivePortal.conf\n"); + } fclose($fd); mwexec_bg("sh /tmp/restart_lighty"); echo "\n"; @@ -410,19 +434,23 @@ function post_cvssync_commands() { } function isUrl($url = "") { - if($url) - if(strstr($url, "rcs.pfsense.org") or - strstr($url, "mainline") or - strstr($url, ".git") or strstr($url, "git://")) - return true; + if ($url) { + if (strstr($url, "rcs.pfsense.org") or + strstr($url, "mainline") or + strstr($url, ".git") or + strstr($url, "git://")) { + return true; + } + } return false; } function run_cmds($cmds) { global $debug; - foreach($cmds as $cmd) { - if($debug) + foreach ($cmds as $cmd) { + if ($debug) { echo "Running $cmd"; + } exec($cmd); } } diff --git a/etc/phpshellsessions/installpkg b/etc/phpshellsessions/installpkg index 30228abc0e..07ff87995a 100644 --- a/etc/phpshellsessions/installpkg +++ b/etc/phpshellsessions/installpkg @@ -4,10 +4,11 @@ require_once("pkg-utils.inc"); global $g, $config, $argv, $command_split; -if(is_array($command_split)) +if (is_array($command_split)) { $args = array_slice($command_split, 2); -else +} else { $args = array_slice($argv, 3); +} $pkg_name = $args[0]; $install_type = empty($args[1]) ? "normal" : $args[1]; @@ -27,13 +28,14 @@ if ($pkg_info) { $static_output = ""; $pkg_interface = "console"; -if (empty($pkg_info[$pkg_name])) +if (empty($pkg_info[$pkg_name])) { echo "\nPackage not found.\n"; -elseif ($install_type == "normal") +} elseif ($install_type == "normal") { install_package($pkg_name, $pkg_info[$pkg_name], true); -elseif ($install_type == "xmlonly") +} elseif ($install_type == "xmlonly") { install_package_xml($pkg_name); -else +} else { echo "Invalid install type. Valid values are: normal, xmlonly.\n"; +} echo "\nDone.\n"; diff --git a/etc/phpshellsessions/listpkg b/etc/phpshellsessions/listpkg index 9c13b457a0..ed2c793755 100644 --- a/etc/phpshellsessions/listpkg +++ b/etc/phpshellsessions/listpkg @@ -5,11 +5,12 @@ global $g, $config; echo "Installed packages:\n"; -foreach($config['installedpackages']['package'] as $package) { +foreach ($config['installedpackages']['package'] as $package) { $name = str_pad("{$package['name']}-{$package['version']}", 30); $descr = $package['descr']; $line = "{$name} {$descr}"; - if (strlen($line) > 80) + if (strlen($line) > 80) { $line = substr($line, 0, 77) . "..."; + } echo "{$line}\n"; } diff --git a/etc/phpshellsessions/removeshaper b/etc/phpshellsessions/removeshaper index 2a221cd933..298e618080 100644 --- a/etc/phpshellsessions/removeshaper +++ b/etc/phpshellsessions/removeshaper @@ -13,8 +13,9 @@ unset($queue); unset($altq); foreach ($config['filter']['rule'] as $key => $rule) { - if (isset($rule['wizard']) && $rule['wizard'] == "yes") + if (isset($rule['wizard']) && $rule['wizard'] == "yes") { unset($config['filter']['rule'][$key]); + } } if (write_config()) { echo gettext("Shaper Successfully Removed.\n"); diff --git a/etc/phpshellsessions/svc b/etc/phpshellsessions/svc index 5c47507ea5..ee1ab40715 100644 --- a/etc/phpshellsessions/svc +++ b/etc/phpshellsessions/svc @@ -13,10 +13,11 @@ function usage() { global $g, $config, $argv, $command_split; -if(is_array($command_split)) +if (is_array($command_split)) { $args = array_slice($command_split, 2); -else +} else { $args = array_slice($argv, 3); +} if (empty($args[0])) { usage(); diff --git a/etc/phpshellsessions/uninstallpkg b/etc/phpshellsessions/uninstallpkg index 484ccc8ef1..fa4cee2264 100644 --- a/etc/phpshellsessions/uninstallpkg +++ b/etc/phpshellsessions/uninstallpkg @@ -4,10 +4,11 @@ require_once("pkg-utils.inc"); global $g, $config, $argv, $command_split; -if(is_array($command_split)) +if (is_array($command_split)) { $args = array_slice($command_split, 2); -else +} else { $args = array_slice($argv, 3); +} $pkg_name = $args[0]; $remove_type = empty($args[1]) ? "normal" : $args[1]; @@ -15,21 +16,23 @@ $pkg_info = array(); echo "Removing package \"{$pkg_name}\"...\n"; -foreach($config['installedpackages']['package'] as $package) { - if ($pkg_name == $package['name']) +foreach ($config['installedpackages']['package'] as $package) { + if ($pkg_name == $package['name']) { $pkg_info = $package; + } } $static_output = ""; $pkg_interface = "console"; -if (empty($pkg_info)) +if (empty($pkg_info)) { echo "\nPackage not installed.\n"; -elseif ($remove_type == "normal") +} elseif ($remove_type == "normal") { uninstall_package($pkg_name); -elseif ($remove_type == "xmlonly") +} elseif ($remove_type == "xmlonly") { delete_package_xml($pkg_name); -else +} else { echo "Invalid removal type. Valid values are: normal, xmlonly.\n"; +} echo "\nDone.\n"; \ No newline at end of file diff --git a/etc/ssl/openssl.cnf b/etc/ssl/openssl.cnf index 5f612fbd3b..b5672d4da5 100644 --- a/etc/ssl/openssl.cnf +++ b/etc/ssl/openssl.cnf @@ -44,7 +44,7 @@ certs = $dir/certs # Where the issued certs are kept crl_dir = $dir/crl # Where the issued crl are kept database = $dir/index.txt # database index file. #unique_subject = no # Set to 'no' to allow creation of - # several ctificates with same subject. + # several certificates with same subject. new_certs_dir = $dir/newcerts # default place for new certs. certificate = $dir/cacert.pem # The CA certificate @@ -55,7 +55,7 @@ crl = $dir/crl.pem # The current CRL private_key = $dir/private/cakey.pem# The private key RANDFILE = $dir/private/.rand # private random number file -x509_extensions = usr_cert # The extentions to add to the cert +x509_extensions = usr_cert # The extensions to add to the cert # Comment out the following two lines for the "traditional" # (and highly broken) format. @@ -111,7 +111,7 @@ default_bits = 2048 default_keyfile = privkey.pem distinguished_name = req_distinguished_name attributes = req_attributes -x509_extensions = v3_ca # The extentions to add to the self signed cert +x509_extensions = v3_ca # The extensions to add to the self signed cert # Passwords for private keys if not present they will be prompted for #input_password="" From 1e0b172713a6fd91f0bf63be078fdc6df1b7865a Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 26 Feb 2015 11:27:52 +0545 Subject: [PATCH 132/257] Code style guide etc in a to e --- etc/inc/auth.inc | 993 +++++++++++++++++++--------------- etc/inc/authgui.inc | 49 +- etc/inc/basic_sasl_client.inc | 8 +- etc/inc/captiveportal.inc | 569 +++++++++++-------- etc/inc/certs.inc | 325 +++++++---- etc/inc/config.console.inc | 248 +++++---- etc/inc/config.gui.inc | 21 +- etc/inc/config.inc | 53 +- etc/inc/config.lib.inc | 295 ++++++---- etc/inc/crypt.inc | 45 +- etc/inc/dyndns.class | 427 ++++++++------- etc/inc/easyrule.inc | 82 ++- 12 files changed, 1833 insertions(+), 1282 deletions(-) diff --git a/etc/inc/auth.inc b/etc/inc/auth.inc index ceaa9e53d6..a19a20cbbc 100644 --- a/etc/inc/auth.inc +++ b/etc/inc/auth.inc @@ -45,23 +45,24 @@ * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php * file courtesy of Michael Retterklieber. */ -if(!$do_not_include_config_gui_inc) +if (!$do_not_include_config_gui_inc) { require_once("config.gui.inc"); +} // Will be changed to false if security checks fail $security_passed = true; -/* If this function doesn't exist, we're being called from Captive Portal or +/* If this function doesn't exist, we're being called from Captive Portal or another internal subsystem which does not include authgui.inc */ if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) { /* DNS ReBinding attack prevention. https://redmine.pfsense.org/issues/708 */ $found_host = false; /* Either a IPv6 address with or without a alternate port */ - if(strstr($_SERVER['HTTP_HOST'], "]")) { + if (strstr($_SERVER['HTTP_HOST'], "]")) { $http_host_port = explode("]", $_SERVER['HTTP_HOST']); /* v6 address has more parts, drop the last part */ - if(count($http_host_port) > 1) { + if (count($http_host_port) > 1) { array_pop($http_host_port); $http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port)); } else { @@ -71,38 +72,45 @@ if (function_exists("display_error_form") && !isset($config['system']['webgui'][ $http_host = explode(":", $_SERVER['HTTP_HOST']); $http_host = $http_host[0]; } - if(is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or - strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") + if (is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or + strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") { $found_host = true; - if(strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or - strcasecmp($http_host, $config['system']['hostname']) == 0) + } + if (strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or + strcasecmp($http_host, $config['system']['hostname']) == 0) { $found_host = true; - - if(is_array($config['dyndnses']['dyndns']) && !$found_host) - foreach($config['dyndnses']['dyndns'] as $dyndns) - if(strcasecmp($dyndns['host'], $http_host) == 0) { - $found_host = true; - break; - } - - if(is_array($config['dnsupdates']['dnsupdate']) && !$found_host) - foreach($config['dnsupdates']['dnsupdate'] as $rfc2136) - if(strcasecmp($rfc2136['host'], $http_host) == 0) { - $found_host = true; - break; - } - - if(!empty($config['system']['webgui']['althostnames']) && !$found_host) { - $althosts = explode(" ", $config['system']['webgui']['althostnames']); - foreach ($althosts as $ah) - if(strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) { - $found_host = true; - break; - } } - if($found_host == false) { - if(!security_checks_disabled()) { + if (is_array($config['dyndnses']['dyndns']) && !$found_host) { + foreach ($config['dyndnses']['dyndns'] as $dyndns) { + if (strcasecmp($dyndns['host'], $http_host) == 0) { + $found_host = true; + break; + } + } + } + + if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) { + foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) { + if (strcasecmp($rfc2136['host'], $http_host) == 0) { + $found_host = true; + break; + } + } + } + + if (!empty($config['system']['webgui']['althostnames']) && !$found_host) { + $althosts = explode(" ", $config['system']['webgui']['althostnames']); + foreach ($althosts as $ah) { + if (strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) { + $found_host = true; + break; + } + } + } + + if ($found_host == false) { + if (!security_checks_disabled()) { display_error_form("501", gettext("Potential DNS Rebind attack detected, see http://en.wikipedia.org/wiki/DNS_rebinding
Try accessing the router by IP address instead of by hostname.")); exit; } @@ -111,10 +119,10 @@ if (function_exists("display_error_form") && !isset($config['system']['webgui'][ } // If the HTTP_REFERER is something other than ourselves then disallow. -if(function_exists("display_error_form") && !isset($config['system']['webgui']['nohttpreferercheck'])) { - if($_SERVER['HTTP_REFERER']) { - if(file_exists("{$g['tmp_path']}/setupwizard_lastreferrer")) { - if($_SERVER['HTTP_REFERER'] == file_get_contents("{$g['tmp_path']}/setupwizard_lastreferrer")) { +if (function_exists("display_error_form") && !isset($config['system']['webgui']['nohttpreferercheck'])) { + if ($_SERVER['HTTP_REFERER']) { + if (file_exists("{$g['tmp_path']}/setupwizard_lastreferrer")) { + if ($_SERVER['HTTP_REFERER'] == file_get_contents("{$g['tmp_path']}/setupwizard_lastreferrer")) { unlink("{$g['tmp_path']}/setupwizard_lastreferrer"); header("Refresh: 1; url=index.php"); echo ""; @@ -125,70 +133,77 @@ if(function_exists("display_error_form") && !isset($config['system']['webgui'][' $found_host = false; $referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST); $referrer_host = str_replace(array("[", "]"), "", $referrer_host); - if($referrer_host) { - if(strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 - || strcasecmp($referrer_host, $config['system']['hostname']) == 0) + if ($referrer_host) { + if (strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 + || strcasecmp($referrer_host, $config['system']['hostname']) == 0) { $found_host = true; + } - if(!empty($config['system']['webgui']['althostnames']) && !$found_host) { + if (!empty($config['system']['webgui']['althostnames']) && !$found_host) { $althosts = explode(" ", $config['system']['webgui']['althostnames']); foreach ($althosts as $ah) { - if(strcasecmp($referrer_host, $ah) == 0) { + if (strcasecmp($referrer_host, $ah) == 0) { $found_host = true; break; } } } - if(is_array($config['dyndnses']['dyndns']) && !$found_host) - foreach($config['dyndnses']['dyndns'] as $dyndns) - if(strcasecmp($dyndns['host'], $referrer_host) == 0) { + if (is_array($config['dyndnses']['dyndns']) && !$found_host) { + foreach ($config['dyndnses']['dyndns'] as $dyndns) { + if (strcasecmp($dyndns['host'], $referrer_host) == 0) { $found_host = true; break; } + } + } - if(is_array($config['dnsupdates']['dnsupdate']) && !$found_host) - foreach($config['dnsupdates']['dnsupdate'] as $rfc2136) - if(strcasecmp($rfc2136['host'], $referrer_host) == 0) { + if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) { + foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) { + if (strcasecmp($rfc2136['host'], $referrer_host) == 0) { $found_host = true; break; } + } + } - if(!$found_host) { + if (!$found_host) { $interface_list_ips = get_configured_ip_addresses(); - foreach($interface_list_ips as $ilips) { - if(strcasecmp($referrer_host, $ilips) == 0) { + foreach ($interface_list_ips as $ilips) { + if (strcasecmp($referrer_host, $ilips) == 0) { $found_host = true; break; } } $interface_list_ipv6s = get_configured_ipv6_addresses(); - foreach($interface_list_ipv6s as $ilipv6s) { - if(strcasecmp($referrer_host, $ilipv6s) == 0) { + foreach ($interface_list_ipv6s as $ilipv6s) { + if (strcasecmp($referrer_host, $ilipv6s) == 0) { $found_host = true; break; } } - if($referrer_host == "127.0.0.1" || $referrer_host == "localhost") { + if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") { // allow SSH port forwarded connections and links from localhost $found_host = true; } } } - if($found_host == false) { - if(!security_checks_disabled()) { + if ($found_host == false) { + if (!security_checks_disabled()) { display_error_form("501", "An HTTP_REFERER was detected other than what is defined in System -> Advanced (" . htmlspecialchars($_SERVER['HTTP_REFERER']) . "). You can disable this check if needed in System -> Advanced -> Admin."); exit; } $security_passed = false; } - } else + } else { $security_passed = false; + } } -if (function_exists("display_error_form") && $security_passed) +if (function_exists("display_error_form") && $security_passed) { /* Security checks passed, so it should be OK to turn them back on */ restore_security_checks(); +} unset($security_passed); $groupindex = index_groups(); @@ -201,7 +216,7 @@ function index_groups() { if (is_array($config['system']['group'])) { $i = 0; - foreach($config['system']['group'] as $groupent) { + foreach ($config['system']['group'] as $groupent) { $groupindex[$groupent['name']] = $i; $i++; } @@ -215,7 +230,7 @@ function index_users() { if (is_array($config['system']['user'])) { $i = 0; - foreach($config['system']['user'] as $userent) { + foreach ($config['system']['user'] as $userent) { $userindex[$userent['name']] = $i; $i++; } @@ -226,90 +241,105 @@ function index_users() { function & getUserEntry($name) { global $debug, $config, $userindex; - if (isset($userindex[$name])) + if (isset($userindex[$name])) { return $config['system']['user'][$userindex[$name]]; + } } function & getUserEntryByUID($uid) { global $debug, $config; - if (is_array($config['system']['user'])) - foreach ($config['system']['user'] as & $user) - if ($user['uid'] == $uid) + if (is_array($config['system']['user'])) { + foreach ($config['system']['user'] as & $user) { + if ($user['uid'] == $uid) { return $user; + } + } + } return false; } function & getGroupEntry($name) { global $debug, $config, $groupindex; - if (isset($groupindex[$name])) + if (isset($groupindex[$name])) { return $config['system']['group'][$groupindex[$name]]; + } } function & getGroupEntryByGID($gid) { global $debug, $config; - if (is_array($config['system']['group'])) - foreach ($config['system']['group'] as & $group) - if ($group['gid'] == $gid) + if (is_array($config['system']['group'])) { + foreach ($config['system']['group'] as & $group) { + if ($group['gid'] == $gid) { return $group; + } + } + } return false; } function get_user_privileges(& $user) { - $privs = $user['priv']; - if (!is_array($privs)) - $privs = array(); + $privs = $user['priv']; + if (!is_array($privs)) { + $privs = array(); + } - $names = local_user_get_groups($user, true); + $names = local_user_get_groups($user, true); - foreach ($names as $name) { - $group = getGroupEntry($name); - if (is_array($group['priv'])) - $privs = array_merge( $privs, $group['priv']); - } + foreach ($names as $name) { + $group = getGroupEntry($name); + if (is_array($group['priv'])) { + $privs = array_merge( $privs, $group['priv']); + } + } - return $privs; + return $privs; } function userHasPrivilege($userent, $privid = false) { - if (!$privid || !is_array($userent)) - return false; + if (!$privid || !is_array($userent)) { + return false; + } - $privs = get_user_privileges($userent); + $privs = get_user_privileges($userent); - if (!is_array($privs)) - return false; + if (!is_array($privs)) { + return false; + } - if (!in_array($privid, $privs)) - return false; + if (!in_array($privid, $privs)) { + return false; + } - return true; + return true; } function local_backed($username, $passwd) { $user = getUserEntry($username); - if (!$user) + if (!$user) { return false; - - if (is_account_disabled($username) || is_account_expired($username)) - return false; - - if ($user['password']) - { - if (crypt($passwd, $user['password']) == $user['password']) - return true; } - if ($user['md5-hash']) - { - if (md5($passwd) == $user['md5-hash']) + if (is_account_disabled($username) || is_account_expired($username)) { + return false; + } + + if ($user['password']) { + if (crypt($passwd, $user['password']) == $user['password']) { return true; + } + } + + if ($user['md5-hash']) { + if (md5($passwd) == $user['md5-hash']) { + return true; + } } return false; @@ -324,16 +354,18 @@ function local_sync_accounts() { if ($fd) { while (!feof($fd)) { $line = explode(":",fgets($fd)); - if (((!strncmp($line[0], "_", 1)) || ($line[2] < 2000) || ($line[2] > 65000)) && ($line[0] != "admin")) + if (((!strncmp($line[0], "_", 1)) || ($line[2] < 2000) || ($line[2] > 65000)) && ($line[0] != "admin")) { continue; + } /* * If a crontab was created to user, pw userdel will be interactive and * can cause issues. Just remove crontab before run it when necessary */ unlink_if_exists("/var/cron/tabs/{$line[0]}"); $cmd = "/usr/sbin/pw userdel -n '{$line[0]}'"; - if($debug) + if ($debug) { log_error(sprintf(gettext("Running: %s"), $cmd)); + } mwexec($cmd); } pclose($fd); @@ -345,15 +377,19 @@ function local_sync_accounts() { if ($fd) { while (!feof($fd)) { $line = explode(":",fgets($fd)); - if (!strncmp($line[0], "_", 1)) + if (!strncmp($line[0], "_", 1)) { continue; - if ($line[2] < 2000) + } + if ($line[2] < 2000) { continue; - if ($line[2] > 65000) + } + if ($line[2] > 65000) { continue; + } $cmd = "/usr/sbin/pw groupdel {$line[2]}"; - if($debug) + if ($debug) { log_error(sprintf(gettext("Running: %s"), $cmd)); + } mwexec($cmd); } pclose($fd); @@ -364,14 +400,18 @@ function local_sync_accounts() { local_group_set($allgrp, true); /* sync all local users */ - if (is_array($config['system']['user'])) - foreach ($config['system']['user'] as $user) + if (is_array($config['system']['user'])) { + foreach ($config['system']['user'] as $user) { local_user_set($user); + } + } /* sync all local groups */ - if (is_array($config['system']['group'])) - foreach ($config['system']['group'] as $group) + if (is_array($config['system']['group'])) { + foreach ($config['system']['group'] as $group) { local_group_set($group); + } + } conf_mount_ro(); @@ -387,7 +427,7 @@ function local_user_set(& $user) { conf_mount_rw(); - $home_base = "/home/"; + $home_base = "/home/"; $user_uid = $user['uid']; $user_name = $user['name']; $user_home = "{$home_base}{$user_name}"; @@ -395,8 +435,9 @@ function local_user_set(& $user) { $user_group = "nobody"; // Ensure $home_base exists and is writable - if (!is_dir($home_base)) + if (!is_dir($home_base)) { mkdir($home_base, 0755); + } $lock_account = false; /* configure shell type */ @@ -423,8 +464,9 @@ function local_user_set(& $user) { /* root user special handling */ if ($user_uid == 0) { $cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0"; - if($debug) + if ($debug) { log_error(sprintf(gettext("Running: %s"), $cmd)); + } $fd = popen($cmd, "w"); fwrite($fd, $user['password']); pclose($fd); @@ -446,14 +488,15 @@ function local_user_set(& $user) { $user_op = "usermod"; } - $comment = str_replace(array(":", "!", "@"), " ", $user['descr']); + $comment = str_replace(array(":", "!", "@"), " ", $user['descr']); /* add or mod pw db */ $cmd = "/usr/sbin/pw {$user_op} -q -u {$user_uid} -n {$user_name}". " -g {$user_group} -s {$user_shell} -d {$user_home}". " -c ".escapeshellarg($comment)." -H 0 2>&1"; - if($debug) + if ($debug) { log_error(sprintf(gettext("Running: %s"), $cmd)); + } $fd = popen($cmd, "w"); fwrite($fd, $user['password']); pclose($fd); @@ -467,7 +510,7 @@ function local_user_set(& $user) { @chgrp($user_home, $user_group); /* write out ssh authorized key file */ - if($user['authorizedkeys']) { + if ($user['authorizedkeys']) { if (!is_dir("{$user_home}/.ssh")) { @mkdir("{$user_home}/.ssh", 0700); @chown("{$user_home}/.ssh", $user_name); @@ -475,12 +518,13 @@ function local_user_set(& $user) { $keys = base64_decode($user['authorizedkeys']); @file_put_contents("{$user_home}/.ssh/authorized_keys", $keys); @chown("{$user_home}/.ssh/authorized_keys", $user_name); - } else + } else { unlink_if_exists("{$user_home}/.ssh/authorized_keys"); + } $un = $lock_account ? "" : "un"; exec("/usr/sbin/pw {$un}lock {$user_name} -q"); - + conf_mount_ro(); } @@ -491,8 +535,9 @@ function local_user_del($user) { local_user_set_groups($user); /* Don't remove /root */ - if ($user['uid'] != 0) + if ($user['uid'] != 0) { $rmhome = "-r"; + } /* read from pw db */ $fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r"); @@ -508,8 +553,9 @@ function local_user_del($user) { /* delete from pw db */ $cmd = "/usr/sbin/pw userdel -n {$user['name']} {$rmhome}"; - if($debug) + if ($debug) { log_error(sprintf(gettext("Running: %s"), $cmd)); + } mwexec($cmd); /* Delete user from groups needs a call to write_config() */ @@ -530,50 +576,60 @@ function local_user_set_password(& $user, $password) { } // Generate the NT-HASH from the unicode string - $user['nt-hash'] = bin2hex(hash("md4", $ustr)); + $user['nt-hash'] = bin2hex(hash("md4", $ustr)); } function local_user_get_groups($user, $all = false) { global $debug, $config; $groups = array(); - if (!is_array($config['system']['group'])) + if (!is_array($config['system']['group'])) { return $groups; + } - foreach ($config['system']['group'] as $group) - if ( $all || ( !$all && ($group['name'] != "all"))) - if (is_array($group['member'])) - if (in_array($user['uid'], $group['member'])) + foreach ($config['system']['group'] as $group) { + if ( $all || ( !$all && ($group['name'] != "all"))) { + if (is_array($group['member'])) { + if (in_array($user['uid'], $group['member'])) { $groups[] = $group['name']; + } + } + } + } - if ( $all ) + if ($all) { $groups[] = "all"; + } sort($groups); return $groups; - + } function local_user_set_groups($user, $new_groups = NULL ) { global $debug, $config, $groupindex; - if (!is_array($config['system']['group'])) + if (!is_array($config['system']['group'])) { return; + } $cur_groups = local_user_get_groups($user, true); $mod_groups = array(); - if (!is_array($new_groups)) + if (!is_array($new_groups)) { $new_groups = array(); + } - if (!is_array($cur_groups)) + if (!is_array($cur_groups)) { $cur_groups = array(); + } /* determine which memberships to add */ foreach ($new_groups as $groupname) { - if ($groupname == '' || in_array($groupname,$cur_groups)) + if ($groupname == '' || in_array($groupname,$cur_groups)) { continue; + } $group = & $config['system']['group'][$groupindex[$groupname]]; $group['member'][] = $user['uid']; $mod_groups[] = $group; @@ -582,10 +638,12 @@ function local_user_set_groups($user, $new_groups = NULL ) { /* determine which memberships to remove */ foreach ($cur_groups as $groupname) { - if (in_array($groupname,$new_groups)) + if (in_array($groupname,$new_groups)) { continue; - if (!isset($config['system']['group'][$groupindex[$groupname]])) + } + if (!isset($config['system']['group'][$groupindex[$groupname]])) { continue; + } $group = & $config['system']['group'][$groupindex[$groupname]]; if (is_array($group['member'])) { $index = array_search($user['uid'], $group['member']); @@ -596,21 +654,24 @@ function local_user_set_groups($user, $new_groups = NULL ) { unset($group); /* sync all modified groups */ - foreach ($mod_groups as $group) + foreach ($mod_groups as $group) { local_group_set($group); + } } function local_group_del_user($user) { global $config; - if (!is_array($config['system']['group'])) - return; + if (!is_array($config['system']['group'])) { + return; + } - foreach ($config['system']['group'] as $group) { + foreach ($config['system']['group'] as $group) { if (is_array($group['member'])) { foreach ($group['member'] as $idx => $uid) { - if ($user['uid'] == $uid) + if ($user['uid'] == $uid) { unset($config['system']['group']['member'][$idx]); + } } } } @@ -622,11 +683,13 @@ function local_group_set($group, $reset = false) { $group_name = $group['name']; $group_gid = $group['gid']; $group_members = ''; - if (!$reset && !empty($group['member']) && count($group['member']) > 0) + if (!$reset && !empty($group['member']) && count($group['member']) > 0) { $group_members = implode(",",$group['member']); + } - if (empty($group_name)) + if (empty($group_name)) { return; + } /* read from group db */ $fd = popen("/usr/sbin/pw groupshow {$group_name} 2>&1", "r"); @@ -634,16 +697,18 @@ function local_group_set($group, $reset = false) { pclose($fd); /* determine add or mod */ - if (!strncmp($pwread, "pw:", 3)) + if (!strncmp($pwread, "pw:", 3)) { $group_op = "groupadd"; - else + } else { $group_op = "groupmod"; + } /* add or mod group db */ $cmd = "/usr/sbin/pw {$group_op} {$group_name} -g {$group_gid} -M '{$group_members}' 2>&1"; - if($debug) + if ($debug) { log_error(sprintf(gettext("Running: %s"), $cmd)); + } mwexec($cmd); } @@ -654,8 +719,9 @@ function local_group_del($group) { /* delete from group db */ $cmd = "/usr/sbin/pw groupdel {$group['name']}"; - if($debug) + if ($debug) { log_error(sprintf(gettext("Running: %s"), $cmd)); + } mwexec($cmd); } @@ -663,36 +729,41 @@ function ldap_test_connection($authcfg) { global $debug, $config, $g; if ($authcfg) { - if (strstr($authcfg['ldap_urltype'], "Standard")) - $ldapproto = "ldap"; - else - $ldapproto = "ldaps"; - $ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']); - $ldapport = $authcfg['ldap_port']; - if (!empty($ldapport)) + if (strstr($authcfg['ldap_urltype'], "Standard")) { + $ldapproto = "ldap"; + } else { + $ldapproto = "ldaps"; + } + $ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']); + $ldapport = $authcfg['ldap_port']; + if (!empty($ldapport)) { $ldapserver .= ":{$ldapport}"; - $ldapbasedn = $authcfg['ldap_basedn']; - $ldapbindun = $authcfg['ldap_binddn']; - $ldapbindpw = $authcfg['ldap_bindpw']; - } else + } + $ldapbasedn = $authcfg['ldap_basedn']; + $ldapbindun = $authcfg['ldap_binddn']; + $ldapbindpw = $authcfg['ldap_bindpw']; + } else { return false; + } - /* first check if there is even an LDAP server populated */ - if(!$ldapserver) - return false; + /* first check if there is even an LDAP server populated */ + if ( !$ldapserver) { + return false; + } - /* Setup CA environment if needed. */ - ldap_setup_caenv($authcfg); + /* Setup CA environment if needed. */ + ldap_setup_caenv($authcfg); - /* connect and see if server is up */ - $error = false; - if (!($ldap = ldap_connect($ldapserver))) + /* connect and see if server is up */ + $error = false; + if (!($ldap = ldap_connect($ldapserver))) { $error = true; + } - if ($error == true) { - log_error(sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname)); - return false; - } + if ($error == true) { + log_error(sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname)); + return false; + } return true; } @@ -713,10 +784,12 @@ function ldap_setup_caenv($authcfg) { putenv('LDAPTLS_REQCERT=hard'); return; } - if (!is_dir("{$g['varrun_path']}/certs")) + if (!is_dir("{$g['varrun_path']}/certs")) { @mkdir("{$g['varrun_path']}/certs"); - if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) + } + if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) { @unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca"); + } file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", base64_decode($caref['crt'])); @chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600); putenv('LDAPTLS_REQCERT=hard'); @@ -730,46 +803,52 @@ function ldap_test_bind($authcfg) { global $debug, $config, $g; if ($authcfg) { - if (strstr($authcfg['ldap_urltype'], "Standard")) - $ldapproto = "ldap"; - else - $ldapproto = "ldaps"; - $ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']); - $ldapport = $authcfg['ldap_port']; - if (!empty($ldapport)) + if (strstr($authcfg['ldap_urltype'], "Standard")) { + $ldapproto = "ldap"; + } else { + $ldapproto = "ldaps"; + } + $ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']); + $ldapport = $authcfg['ldap_port']; + if (!empty($ldapport)) { $ldapserver .= ":{$ldapport}"; - $ldapbasedn = $authcfg['ldap_basedn']; - $ldapbindun = $authcfg['ldap_binddn']; - $ldapbindpw = $authcfg['ldap_bindpw']; - $ldapver = $authcfg['ldap_protver']; - if (empty($ldapbndun) || empty($ldapbindpw)) - $ldapanon = true; - else - $ldapanon = false; - } else + } + $ldapbasedn = $authcfg['ldap_basedn']; + $ldapbindun = $authcfg['ldap_binddn']; + $ldapbindpw = $authcfg['ldap_bindpw']; + $ldapver = $authcfg['ldap_protver']; + if (empty($ldapbndun) || empty($ldapbindpw)) { + $ldapanon = true; + } else { + $ldapanon = false; + } + } else { return false; + } /* first check if there is even an LDAP server populated */ - if(!$ldapserver) - return false; + if (!$ldapserver) { + return false; + } /* Setup CA environment if needed. */ ldap_setup_caenv($authcfg); - /* connect and see if server is up */ - $error = false; - if (!($ldap = ldap_connect($ldapserver))) + /* connect and see if server is up */ + $error = false; + if (!($ldap = ldap_connect($ldapserver))) { $error = true; + } - if ($error == true) { - log_error(sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname)); - return false; - } + if ($error == true) { + log_error(sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname)); + return false; + } ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0); ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING); ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver); - + $ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun; $ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw; if ($ldapanon == true) { @@ -790,52 +869,58 @@ function ldap_test_bind($authcfg) { function ldap_get_user_ous($show_complete_ou=true, $authcfg) { global $debug, $config, $g; - if(!function_exists("ldap_connect")) + if (!function_exists("ldap_connect")) { return; + } $ous = array(); if ($authcfg) { - if (strstr($authcfg['ldap_urltype'], "Standard")) - $ldapproto = "ldap"; - else - $ldapproto = "ldaps"; - $ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']); - $ldapport = $authcfg['ldap_port']; - if (!empty($ldapport)) + if (strstr($authcfg['ldap_urltype'], "Standard")) { + $ldapproto = "ldap"; + } else { + $ldapproto = "ldaps"; + } + $ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']); + $ldapport = $authcfg['ldap_port']; + if (!empty($ldapport)) { $ldapserver .= ":{$ldapport}"; - $ldapbasedn = $authcfg['ldap_basedn']; - $ldapbindun = $authcfg['ldap_binddn']; - $ldapbindpw = $authcfg['ldap_bindpw']; - $ldapver = $authcfg['ldap_protver']; - if (empty($ldapbindun) || empty($ldapbindpw)) - $ldapanon = true; - else - $ldapanon = false; - $ldapname = $authcfg['name']; - $ldapfallback = false; - $ldapscope = $authcfg['ldap_scope']; - } else + } + $ldapbasedn = $authcfg['ldap_basedn']; + $ldapbindun = $authcfg['ldap_binddn']; + $ldapbindpw = $authcfg['ldap_bindpw']; + $ldapver = $authcfg['ldap_protver']; + if (empty($ldapbindun) || empty($ldapbindpw)) { + $ldapanon = true; + } else { + $ldapanon = false; + } + $ldapname = $authcfg['name']; + $ldapfallback = false; + $ldapscope = $authcfg['ldap_scope']; + } else { return false; + } - /* first check if there is even an LDAP server populated */ - if(!$ldapserver) { - log_error(gettext("ERROR! ldap_get_user_ous() backed selected with no LDAP authentication server defined.")); - return $ous; - } + /* first check if there is even an LDAP server populated */ + if (!$ldapserver) { + log_error(gettext("ERROR! ldap_get_user_ous() backed selected with no LDAP authentication server defined.")); + return $ous; + } /* Setup CA environment if needed. */ ldap_setup_caenv($authcfg); /* connect and see if server is up */ - $error = false; - if (!($ldap = ldap_connect($ldapserver))) + $error = false; + if (!($ldap = ldap_connect($ldapserver))) { $error = true; + } - if ($error == true) { - log_error(sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname)); - return $ous; - } + if ($error == true) { + log_error(sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname)); + return $ous; + } $ldapfilter = "(|(ou=*)(cn=Users))"; @@ -846,10 +931,10 @@ function ldap_get_user_ous($show_complete_ou=true, $authcfg) { $ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun; $ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw; if ($ldapanon == true) { - if (!($res = @ldap_bind($ldap))) { + if (!($res = @ldap_bind($ldap))) { log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname)); @ldap_close($ldap); - return $ous; + return $ous; } } else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) { log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname)); @@ -857,10 +942,11 @@ function ldap_get_user_ous($show_complete_ou=true, $authcfg) { return $ous; } - if ($ldapscope == "one") + if ($ldapscope == "one") { $ldapfunc = "ldap_list"; - else + } else { $ldapfunc = "ldap_search"; + } $search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter); $info = @ldap_get_entries($ldap, $search); @@ -872,11 +958,14 @@ function ldap_get_user_ous($show_complete_ou=true, $authcfg) { $ou = $inf_split[0]; $ou = str_replace("OU=","", $ou); $ou = str_replace("CN=","", $ou); - } else - if($inf['dn']) + } else { + if ($inf['dn']) { $ou = $inf['dn']; - if($ou) + } + } + if ($ou) { $ous[] = $ou; + } } } @@ -887,71 +976,78 @@ function ldap_get_user_ous($show_complete_ou=true, $authcfg) { function ldap_get_groups($username, $authcfg) { global $debug, $config; - - if(!function_exists("ldap_connect")) - return; - - if(!$username) - return false; - if(!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) { - $username_split = explode("@", $username); - $username = $username_split[0]; + if (!function_exists("ldap_connect")) { + return; } - if(stristr($username, "\\")) { - $username_split = explode("\\", $username); - $username = $username_split[0]; - } - - //log_error("Getting LDAP groups for {$username}."); - if ($authcfg) { - if (strstr($authcfg['ldap_urltype'], "Standard")) - $ldapproto = "ldap"; - else - $ldapproto = "ldaps"; - $ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']); - $ldapport = $authcfg['ldap_port']; - if (!empty($ldapport)) - $ldapserver .= ":{$ldapport}"; - $ldapbasedn = $authcfg['ldap_basedn']; - $ldapbindun = $authcfg['ldap_binddn']; - $ldapbindpw = $authcfg['ldap_bindpw']; - $ldapauthcont = $authcfg['ldap_authcn']; - $ldapnameattribute = strtolower($authcfg['ldap_attr_user']); - $ldapgroupattribute = strtolower($authcfg['ldap_attr_member']); - $ldapfilter = "({$ldapnameattribute}={$username})"; - $ldaptype = ""; - $ldapver = $authcfg['ldap_protver']; - if (empty($ldapbindun) || empty($ldapbindpw)) - $ldapanon = true; - else - $ldapanon = false; - $ldapname = $authcfg['name']; - $ldapfallback = false; - $ldapscope = $authcfg['ldap_scope']; - } else + if (!$username) { return false; + } - $ldapdn = $_SESSION['ldapdn']; + if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) { + $username_split = explode("@", $username); + $username = $username_split[0]; + } + + if (stristr($username, "\\")) { + $username_split = explode("\\", $username); + $username = $username_split[0]; + } + + //log_error("Getting LDAP groups for {$username}."); + if ($authcfg) { + if (strstr($authcfg['ldap_urltype'], "Standard")) { + $ldapproto = "ldap"; + } else { + $ldapproto = "ldaps"; + } + $ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']); + $ldapport = $authcfg['ldap_port']; + if (!empty($ldapport)) { + $ldapserver .= ":{$ldapport}"; + } + $ldapbasedn = $authcfg['ldap_basedn']; + $ldapbindun = $authcfg['ldap_binddn']; + $ldapbindpw = $authcfg['ldap_bindpw']; + $ldapauthcont = $authcfg['ldap_authcn']; + $ldapnameattribute = strtolower($authcfg['ldap_attr_user']); + $ldapgroupattribute = strtolower($authcfg['ldap_attr_member']); + $ldapfilter = "({$ldapnameattribute}={$username})"; + $ldaptype = ""; + $ldapver = $authcfg['ldap_protver']; + if (empty($ldapbindun) || empty($ldapbindpw)) { + $ldapanon = true; + } else { + $ldapanon = false; + } + $ldapname = $authcfg['name']; + $ldapfallback = false; + $ldapscope = $authcfg['ldap_scope']; + } else { + return false; + } + + $ldapdn = $_SESSION['ldapdn']; /*Convert attribute to lowercase. php ldap arrays put everything in lowercase */ $ldapgroupattribute = strtolower($ldapgroupattribute); $memberof = array(); - /* Setup CA environment if needed. */ - ldap_setup_caenv($authcfg); + /* Setup CA environment if needed. */ + ldap_setup_caenv($authcfg); /* connect and see if server is up */ $error = false; - if (!($ldap = ldap_connect($ldapserver))) + if (!($ldap = ldap_connect($ldapserver))) { $error = true; + } if ($error == true) { log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname)); - return memberof; - } - + return memberof; + } + ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0); ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING); ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver); @@ -960,10 +1056,10 @@ function ldap_get_groups($username, $authcfg) { $ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun; $ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw; if ($ldapanon == true) { - if (!($res = @ldap_bind($ldap))) { + if (!($res = @ldap_bind($ldap))) { log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname)); @ldap_close($ldap); - return false; + return false; } } else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) { log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname)); @@ -975,17 +1071,18 @@ function ldap_get_groups($username, $authcfg) { /* use ldap_read instead of search so we don't have to do a bunch of extra work */ /* since we know the DN is in $_SESSION['ldapdn'] */ //$search = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute)); - if ($ldapscope == "one") - $ldapfunc = "ldap_list"; - else - $ldapfunc = "ldap_search"; + if ($ldapscope == "one") { + $ldapfunc = "ldap_list"; + } else { + $ldapfunc = "ldap_search"; + } - $search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute)); - $info = @ldap_get_entries($ldap, $search); + $search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute)); + $info = @ldap_get_entries($ldap, $search); - $countem = $info["count"]; - - if(is_array($info[0][$ldapgroupattribute])) { + $countem = $info["count"]; + + if (is_array($info[0][$ldapgroupattribute])) { /* Iterate through the groups and throw them into an array */ foreach ($info[0][$ldapgroupattribute] as $member) { if (stristr($member, "CN=") !== false) { @@ -994,14 +1091,14 @@ function ldap_get_groups($username, $authcfg) { } } } - + /* Time to close LDAP connection */ @ldap_unbind($ldap); - + $groups = print_r($memberof,true); - + //log_error("Returning groups ".$groups." for user $username"); - + return $memberof; } @@ -1011,72 +1108,75 @@ function ldap_format_host($host) { function ldap_backed($username, $passwd, $authcfg) { global $debug, $config; - - if(!$username) - return; - if(!function_exists("ldap_connect")) + if (!$username) { return; - - if(!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) { - $username_split = explode("@", $username); - $username = $username_split[0]; } - if(stristr($username, "\\")) { + + if (!function_exists("ldap_connect")) { + return; + } + + if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) { + $username_split = explode("@", $username); + $username = $username_split[0]; + } + if (stristr($username, "\\")) { $username_split = explode("\\", $username); - $username = $username_split[0]; + $username = $username_split[0]; } if ($authcfg) { - if (strstr($authcfg['ldap_urltype'], "Standard")) + if (strstr($authcfg['ldap_urltype'], "Standard")) { $ldapproto = "ldap"; - else + } else { $ldapproto = "ldaps"; - $ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']); - $ldapport = $authcfg['ldap_port']; - if (!empty($ldapport)) + } + $ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']); + $ldapport = $authcfg['ldap_port']; + if (!empty($ldapport)) { $ldapserver .= ":{$ldapport}"; - $ldapbasedn = $authcfg['ldap_basedn']; - $ldapbindun = $authcfg['ldap_binddn']; - $ldapbindpw = $authcfg['ldap_bindpw']; - if (empty($ldapbindun) || empty($ldapbindpw)) + } + $ldapbasedn = $authcfg['ldap_basedn']; + $ldapbindun = $authcfg['ldap_binddn']; + $ldapbindpw = $authcfg['ldap_bindpw']; + if (empty($ldapbindun) || empty($ldapbindpw)) { $ldapanon = true; - else + } else { $ldapanon = false; - $ldapauthcont = $authcfg['ldap_authcn']; - $ldapnameattribute = strtolower($authcfg['ldap_attr_user']); - $ldapextendedqueryenabled = $authcfg['ldap_extended_enabled']; - $ldapextendedquery = $authcfg['ldap_extended_query']; - $ldapfilter = ""; - if(!$ldapextendedqueryenabled) - { - $ldapfilter = "({$ldapnameattribute}={$username})"; - } - else - { - $ldapfilter = -"(&({$ldapnameattribute}={$username})({$ldapextendedquery}))"; - } - $ldaptype = ""; - $ldapver = $authcfg['ldap_protver']; - $ldapname = $authcfg['name']; - $ldapscope = $authcfg['ldap_scope']; - } else + } + $ldapauthcont = $authcfg['ldap_authcn']; + $ldapnameattribute = strtolower($authcfg['ldap_attr_user']); + $ldapextendedqueryenabled = $authcfg['ldap_extended_enabled']; + $ldapextendedquery = $authcfg['ldap_extended_query']; + $ldapfilter = ""; + if (!$ldapextendedqueryenabled) { + $ldapfilter = "({$ldapnameattribute}={$username})"; + } else { + $ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))"; + } + $ldaptype = ""; + $ldapver = $authcfg['ldap_protver']; + $ldapname = $authcfg['name']; + $ldapscope = $authcfg['ldap_scope']; + } else { return false; + } - /* first check if there is even an LDAP server populated */ - if(!$ldapserver) { + /* first check if there is even an LDAP server populated */ + if (!$ldapserver) { if ($ldapfallback) { log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined. Defaulting to local user database. Visit System -> User Manager.")); return local_backed($username, $passwd); - } else + } else { log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined.")); + } return false; } - - /* Setup CA environment if needed. */ - ldap_setup_caenv($authcfg); + + /* Setup CA environment if needed. */ + ldap_setup_caenv($authcfg); ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0); ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING); @@ -1084,8 +1184,9 @@ function ldap_backed($username, $passwd, $authcfg) { /* Make sure we can connect to LDAP */ $error = false; - if (!($ldap = ldap_connect($ldapserver))) + if (!($ldap = ldap_connect($ldapserver))) { $error = true; + } if ($error == true) { log_error(sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname)); @@ -1097,56 +1198,62 @@ function ldap_backed($username, $passwd, $authcfg) { $ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun; $ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw; if ($ldapanon == true) { - if (!($res = @ldap_bind($ldap))) - $error = true; - } else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) + if (!($res = @ldap_bind($ldap))) { + $error = true; + } + } else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) { $error = true; + } if ($error == true) { @ldap_close($ldap); log_error(sprintf(gettext("ERROR! Could not bind to server %s."), $ldapname)); return false; } - + /* Get LDAP Authcontainers and split em up. */ $ldac_splits = explode(";", $ldapauthcont); - + /* setup the usercount so we think we havn't found anyone yet */ $usercount = 0; /*****************************************************************/ /* We First find the user based on username and filter */ - /* Then, once we find the first occurance of that person */ - /* We set seesion variables to ponit to the OU and DN of the */ + /* Then, once we find the first occurrence of that person */ + /* We set session variables to point to the OU and DN of the */ /* Person. To later be used by ldap_get_groups. */ /* that way we don't have to search twice. */ /*****************************************************************/ - if ($debug) + if ($debug) { log_auth(sprintf(gettext("Now Searching for %s in directory."), $username)); + } /* Iterate through the user containers for search */ foreach ($ldac_splits as $i => $ldac_split) { $ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split; $ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter; $ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}"; /* Make sure we just use the first user we find */ - if ($debug) + if ($debug) { log_auth(sprintf(gettext('Now Searching in server %1$s, container %2$s with filter %3$s.'), $ldapname, utf8_decode($ldac_split), utf8_decode($ldapfilter))); - if ($ldapscope == "one") + } + if ($ldapscope == "one") { $ldapfunc = "ldap_list"; - else + } else { $ldapfunc = "ldap_search"; + } /* Support legacy auth container specification. */ - if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) + if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) { $search = @$ldapfunc($ldap,$ldac_split,$ldapfilter); - else + } else { $search = @$ldapfunc($ldap,$ldapsearchbasedn,$ldapfilter); + } if (!$search) { log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap))); continue; } - $info = ldap_get_entries($ldap,$search); + $info = ldap_get_entries($ldap,$search); $matches = $info['count']; - if ($matches == 1){ + if ($matches == 1) { $userdn = $_SESSION['ldapdn'] = $info[0]['dn']; $_SESSION['ldapou'] = $ldac_split[$i]; $_SESSION['ldapon'] = "true"; @@ -1155,10 +1262,10 @@ function ldap_backed($username, $passwd, $authcfg) { } } - if ($usercount != 1){ + if ($usercount != 1) { @ldap_unbind($ldap); log_error(gettext("ERROR! Either LDAP search failed, or multiple users were found.")); - return false; + return false; } /* Now lets bind as the user we found */ @@ -1193,10 +1300,11 @@ function radius_backed($username, $passwd, $authcfg, &$attributes = array()) { $radiusservers[0]['port'] = $authcfg['radius_auth_port']; $radiusservers[0]['sharedsecret'] = $authcfg['radius_secret']; $radiusservers[0]['timeout'] = $authcfg['radius_timeout']; - } else + } else { return false; + } - /* Add a new servers to our instance */ + /* Add new servers to our instance */ foreach ($radiusservers as $radsrv) { $timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5; $rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout); @@ -1205,8 +1313,9 @@ function radius_backed($username, $passwd, $authcfg, &$attributes = array()) { if (PEAR::isError($rauth->start())) { $retvalue['auth_val'] = 1; $retvalue['error'] = $rauth->getError(); - if ($debug) + if ($debug) { printf(gettext("Radius start: %s
\n"), $retvalue['error']); + } } // XXX - billm - somewhere in here we need to handle securid challenge/response @@ -1216,19 +1325,23 @@ function radius_backed($username, $passwd, $authcfg, &$attributes = array()) { if (PEAR::isError($result)) { $retvalue['auth_val'] = 1; $retvalue['error'] = $result->getMessage(); - if ($debug) + if ($debug) { printf(gettext("Radius send failed: %s
\n"), $retvalue['error']); + } } else if ($result === true) { - if ($rauth->getAttributes()) + if ($rauth->getAttributes()) { $attributes = $rauth->listAttributes(); + } $retvalue['auth_val'] = 2; - if ($debug) + if ($debug) { printf(gettext("Radius Auth succeeded")."
\n"); + } $ret = true; } else { $retvalue['auth_val'] = 3; - if ($debug) + if ($debug) { printf(gettext("Radius Auth rejected")."
\n"); + } } // close OO RADIUS_AUTHENTICATION @@ -1239,15 +1352,17 @@ function radius_backed($username, $passwd, $authcfg, &$attributes = array()) { function get_user_expiration_date($username) { $user = getUserEntry($username); - if ($user['expires']) + if ($user['expires']) { return $user['expires']; + } } function is_account_expired($username) { $expirydate = get_user_expiration_date($username); if ($expirydate) { - if (strtotime("-1 day") > strtotime(date("m/d/Y",strtotime($expirydate)))) + if (strtotime("-1 day") > strtotime(date("m/d/Y",strtotime($expirydate)))) { return true; + } } return false; @@ -1255,36 +1370,39 @@ function is_account_expired($username) { function is_account_disabled($username) { $user = getUserEntry($username); - if (isset($user['disabled'])) + if (isset($user['disabled'])) { return true; + } return false; } function auth_get_authserver($name) { - global $config; + global $config; - if (is_array($config['system']['authserver'])) { - foreach ($config['system']['authserver'] as $authcfg) { - if ($authcfg['name'] == $name) - return $authcfg; - } - } - if ($name == "Local Database") + if (is_array($config['system']['authserver'])) { + foreach ($config['system']['authserver'] as $authcfg) { + if ($authcfg['name'] == $name) { + return $authcfg; + } + } + } + if ($name == "Local Database") { return array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']); + } } function auth_get_authserver_list() { - global $config; + global $config; $list = array(); - if (is_array($config['system']['authserver'])) { - foreach ($config['system']['authserver'] as $authcfg) { + if (is_array($config['system']['authserver'])) { + foreach ($config['system']['authserver'] as $authcfg) { /* Add support for disabled entries? */ $list[$authcfg['name']] = $authcfg; - } - } + } + } $list["Local Database"] = array( "name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']); return $list; @@ -1295,23 +1413,25 @@ function getUserGroups($username, $authcfg) { $allowed_groups = array(); - switch($authcfg['type']) { - case 'ldap': - $allowed_groups = @ldap_get_groups($username, $authcfg); - break; - case 'radius': - break; - default: - $user = getUserEntry($username); - $allowed_groups = @local_user_get_groups($user, true); - break; + switch ($authcfg['type']) { + case 'ldap': + $allowed_groups = @ldap_get_groups($username, $authcfg); + break; + case 'radius': + break; + default: + $user = getUserEntry($username); + $allowed_groups = @local_user_get_groups($user, true); + break; } $member_groups = array(); - if (is_array($config['system']['group'])) { - foreach ($config['system']['group'] as $group) - if (in_array($group['name'], $allowed_groups)) + if (is_array($config['system']['group'])) { + foreach ($config['system']['group'] as $group) { + if (in_array($group['name'], $allowed_groups)) { $member_groups[] = $group['name']; + } + } } return $member_groups; @@ -1324,21 +1444,24 @@ function authenticate_user($username, $password, $authcfg = NULL, &$attributes = } $authenticated = false; - switch($authcfg['type']) { - case 'ldap': - if (ldap_backed($username, $password, $authcfg)) - $authenticated = true; - break; - case 'radius': - if (radius_backed($username, $password, $authcfg, $attributes)) - $authenticated = true; - break; - default: - /* lookup user object by name */ - if (local_backed($username, $password)) - $authenticated = true; - break; - } + switch ($authcfg['type']) { + case 'ldap': + if (ldap_backed($username, $password, $authcfg)) { + $authenticated = true; + } + break; + case 'radius': + if (radius_backed($username, $password, $authcfg, $attributes)) { + $authenticated = true; + } + break; + default: + /* lookup user object by name */ + if (local_backed($username, $password)) { + $authenticated = true; + } + break; + } return $authenticated; } @@ -1356,32 +1479,35 @@ function session_auth() { true ); - if (!session_id()) + if (!session_id()) { session_start(); + } // Detect protocol change - if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) + if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) { return false; + } /* Validate incoming login request */ if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) { $authcfg = auth_get_authserver($config['system']['webgui']['authmode']); - if (authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg) || - authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) { + if (authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg) || + authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) { // Generate a new id to avoid session fixation session_regenerate_id(); $_SESSION['Logged_In'] = "True"; $_SESSION['Username'] = $_POST['usernamefld']; $_SESSION['last_access'] = time(); $_SESSION['protocol'] = $config['system']['webgui']['protocol']; - if(! isset($config['system']['webgui']['quietlogin'])) { + if (!isset($config['system']['webgui']['quietlogin'])) { log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], $_SERVER['REMOTE_ADDR'])); } - if (isset($_POST['postafterlogin'])) + if (isset($_POST['postafterlogin'])) { return true; - else { - if (empty($page)) + } else { + if (empty($page)) { $page = "/"; + } header("Location: {$page}"); } exit; @@ -1389,7 +1515,7 @@ function session_auth() { /* give the user an error message */ $_SESSION['Login_Error'] = "Username or Password incorrect"; log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}"); - if(isAjax()) { + if (isAjax()) { echo "showajaxmessage('{$_SESSION['Login_Error']}');"; return; } @@ -1397,8 +1523,9 @@ function session_auth() { } /* Show login page if they aren't logged in */ - if (empty($_SESSION['Logged_In'])) + if (empty($_SESSION['Logged_In'])) { return false; + } /* If session timeout isn't set, we don't mark sessions stale */ if (!isset($config['system']['webgui']['session_timeout'])) { @@ -1406,12 +1533,14 @@ function session_auth() { if ($_SESSION['last_access'] < (time() - 14400)) { $_GET['logout'] = true; $_SESSION['Logout'] = true; - } else - $_SESSION['last_access'] = time(); + } else { + $_SESSION['last_access'] = time(); + } } else if (intval($config['system']['webgui']['session_timeout']) == 0) { /* only update if it wasn't ajax */ - if (!isAjax()) + if (!isAjax()) { $_SESSION['last_access'] = time(); + } } else { /* Check for stale session */ if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) { @@ -1419,24 +1548,27 @@ function session_auth() { $_SESSION['Logout'] = true; } else { /* only update if it wasn't ajax */ - if (!isAjax()) + if (!isAjax()) { $_SESSION['last_access'] = time(); + } } } /* user hit the logout button */ if (isset($_GET['logout'])) { - if ($_SESSION['Logout']) + if ($_SESSION['Logout']) { log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR'])); - else + } else { log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR'])); + } /* wipe out $_SESSION */ $_SESSION = array(); - if (isset($_COOKIE[session_name()])) + if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-42000, '/'); + } /* and destroy it */ session_destroy(); @@ -1445,8 +1577,9 @@ function session_auth() { $scriptElms = count($scriptName); $scriptName = $scriptName[$scriptElms-1]; - if (isAjax()) + if (isAjax()) { return false; + } /* redirect to page the user is on, it'll prompt them to login again */ header("Location: {$scriptName}"); @@ -1456,17 +1589,19 @@ function session_auth() { /* * this is for debugging purpose if you do not want to use Ajax - * to submit a HTML form. It basically diables the observation + * to submit a HTML form. It basically disables the observation * of the submit event and hence does not trigger Ajax. */ - if ($_GET['disable_ajax']) + if ($_GET['disable_ajax']) { $_SESSION['NO_AJAX'] = "True"; + } /* * Same to re-enable Ajax. */ - if ($_GET['enable_ajax']) + if ($_GET['enable_ajax']) { unset($_SESSION['NO_AJAX']); + } return true; } diff --git a/etc/inc/authgui.inc b/etc/inc/authgui.inc index 0999452c5b..7a3580040f 100644 --- a/etc/inc/authgui.inc +++ b/etc/inc/authgui.inc @@ -39,8 +39,9 @@ include_once("auth.inc"); include_once("priv.inc"); -if (!function_exists('platform_booting')) +if (!function_exists('platform_booting')) { require_once('globals.inc'); +} /* Authenticate user - exit if failed */ if (!session_auth()) { @@ -66,8 +67,9 @@ if (!isAllowedPage($_SERVER['REQUEST_URI'])) { pfSenseHeader("/{$page}"); $username = empty($_SESSION["Username"]) ? "(system)" : $_SESSION['Username']; - if (!empty($_SERVER['REMOTE_ADDR'])) + if (!empty($_SERVER['REMOTE_ADDR'])) { $username .= '@' . $_SERVER['REMOTE_ADDR']; + } log_error("{$username} attempted to access {$_SERVER['SCRIPT_NAME']} but does not have access to that page. Redirecting to {$page}."); exit; @@ -75,12 +77,13 @@ if (!isAllowedPage($_SERVER['REQUEST_URI'])) { display_error_form("201", gettext("No page assigned to this user! Click here to logout.")); exit; } -} else +} else { $_SESSION['Post_Login'] = true; +} /* * redirect browsers post-login to avoid pages - * taking action in reponse to a POST request + * taking action in response to a POST request */ if (!$_SESSION['Post_Login']) { $_SESSION['Post_Login'] = true; @@ -89,7 +92,7 @@ if (!$_SESSION['Post_Login']) { exit; } -/* +/* * Close session data to allow other scripts from same host to come in. * A session can be reactivated from calling session_start again */ @@ -101,7 +104,7 @@ session_commit(); function display_error_form($http_code, $desc) { global $config, $g; $g['theme'] = get_current_theme(); - if(isAjax()) { + if (isAjax()) { printf(gettext('Error: %1$s Description: %2$s'), $http_code, $desc); return; } @@ -126,8 +129,9 @@ function display_error_form($http_code, $desc) { // "True") { + if ($_SESSION['Logged_In'] <> "True") { isset($_SESSION['Login_Error']) ? $login_error = $_SESSION['Login_Error'] : $login_error = gettext("unknown reason"); printf("showajaxmessage('" . gettext("Invalid login (%s).") . "')", $login_error); } @@ -177,7 +181,7 @@ function display_login_form() { exit; } -/* Check against locally configured IP addresses, which will catch when someone +/* Check against locally configured IP addresses, which will catch when someone port forwards WebGUI access from WAN to an internal IP on the router. */ global $FilterIflist, $nifty_background; $local_ip = false; @@ -193,11 +197,11 @@ if (empty($FilterIflist)) { filter_generate_optcfg_array(); } foreach ($FilterIflist as $iflist) { - if ($iflist['ip'] == $http_host) + if ($iflist['ip'] == $http_host) { $local_ip = true; - else if ($iflist['ipv6'] == $http_host) + } else if ($iflist['ipv6'] == $http_host) { $local_ip = true; - else if (is_array($iflist['vips'])) { + } else if (is_array($iflist['vips'])) { foreach ($iflist['vips'] as $vip) { if ($vip['ip'] == $http_host) { $local_ip = true; @@ -206,8 +210,9 @@ foreach ($FilterIflist as $iflist) { } unset($vip); } - if ($local_ip == true) + if ($local_ip == true) { break; + } } unset($FilterIflist); unset($iflist); @@ -220,8 +225,9 @@ if ($local_ip == false) { } else if (is_ipaddrv6($http_host) && !empty($ovpns['tunnel_networkv6']) && ip_in_subnet($http_host, $ovpns['tunnel_networkv6'])) { $local_ip = true; } - if ($local_ip == true) + if ($local_ip == true) { break; + } } } } @@ -252,8 +258,9 @@ if ($local_ip == false) { //
-
If you did not setup this forwarding, you may be the target of a man-in-the-middle attack.")); + print_info_box(gettext("You are accessing this router by an IP address not configured locally, which may be forwarded by NAT or other means.

If you did not setup this forwarding, you may be the target of a man-in-the-middle attack.")); } $loginautocomplete = isset($config['system']['webgui']['loginautocomplete']) ? '' : 'autocomplete="off"'; ?> diff --git a/etc/inc/basic_sasl_client.inc b/etc/inc/basic_sasl_client.inc index b2972b5d8a..c817664899 100644 --- a/etc/inc/basic_sasl_client.inc +++ b/etc/inc/basic_sasl_client.inc @@ -21,7 +21,7 @@ class basic_sasl_client_class Function Start(&$client, &$message, &$interactions) { - if($this->state!=SASL_BASIC_STATE_START) + if ($this->state!=SASL_BASIC_STATE_START) { $client->error="Basic authentication state is not at the start"; return(SASL_FAIL); @@ -33,19 +33,21 @@ class basic_sasl_client_class $defaults=array( ); $status=$client->GetCredentials($this->credentials,$defaults,$interactions); - if($status==SASL_CONTINUE) + if ($status==SASL_CONTINUE) { $message=$this->credentials["user"].":".$this->credentials["password"]; $this->state=SASL_BASIC_STATE_DONE; } else + { Unset($message); + } return($status); } Function Step(&$client, $response, &$message, &$interactions) { - switch($this->state) + switch ($this->state) { case SASL_BASIC_STATE_DONE: $client->error="Basic authentication was finished without success"; diff --git a/etc/inc/captiveportal.inc b/etc/inc/captiveportal.inc index 35bbeff3ee..9608ac10b5 100644 --- a/etc/inc/captiveportal.inc +++ b/etc/inc/captiveportal.inc @@ -35,10 +35,10 @@ via returned RADIUS attributes. This page has been modified to delete any added rules which may have been created by other per-user code (index.php, etc). These changes are (c) 2004 Keycom PLC. - + pfSense_BUILDER_BINARIES: /sbin/ipfw /sbin/route pfSense_BUILDER_BINARIES: /usr/local/sbin/lighttpd /usr/local/bin/minicron /sbin/pfctl - pfSense_BUILDER_BINARIES: /bin/hostname /bin/cp + pfSense_BUILDER_BINARIES: /bin/hostname /bin/cp pfSense_MODULE: captiveportal */ @@ -53,9 +53,9 @@ function get_default_captive_portal_html() { global $config, $g, $cpzone; $htmltext = << - - + + +
@@ -102,8 +102,8 @@ function get_default_captive_portal_html() { EOD; - if(isset($config['voucher'][$cpzone]['enable'])) { - $htmltext .= << Enter Voucher Code: @@ -136,7 +136,7 @@ EOD;
- + EOD; @@ -183,7 +183,7 @@ function captiveportal_configure_zone($cpcfg) { global $config, $g, $cpzone, $cpzoneid; $captiveportallck = lock("captiveportal{$cpzone}", LOCK_EX); - + if (isset($cpcfg['enable'])) { if (platform_booting()) { @@ -191,8 +191,9 @@ function captiveportal_configure_zone($cpcfg) { /* remove old information */ unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db"); - } else + } else { captiveportal_syslog("Reconfiguring captive portal({$cpcfg['zone']})."); + } /* init ipfw rules */ captiveportal_init_rules(true); @@ -204,13 +205,14 @@ function captiveportal_configure_zone($cpcfg) { $croninterval = $cpcfg['croninterval'] ? $cpcfg['croninterval'] : 60; /* double check if the $croninterval is numeric and at least 10 seconds. If not we set it to 60 to avoid problems */ - if ((!is_numeric($croninterval)) || ($croninterval < 10)) + if ((!is_numeric($croninterval)) || ($croninterval < 10)) { $croninterval = 60; + } /* write portal page */ - if (is_array($cpcfg['page']) && $cpcfg['page']['htmltext']) + if (is_array($cpcfg['page']) && $cpcfg['page']['htmltext']) { $htmltext = base64_decode($cpcfg['page']['htmltext']); - else { + } else { /* example/template page */ $htmltext = get_default_captive_portal_html(); } @@ -226,7 +228,7 @@ function captiveportal_configure_zone($cpcfg) { $htmltext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $htmltext); $htmltext = str_replace("\$ORIGINAL_PORTAL_IP\$", "#ORIGINAL_PORTAL_IP#", $htmltext); $htmltext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $htmltext); - if($cpcfg['preauthurl']) { + if ($cpcfg['preauthurl']) { $htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext); $htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext); } @@ -236,9 +238,9 @@ function captiveportal_configure_zone($cpcfg) { unset($htmltext); /* write error page */ - if (is_array($cpcfg['page']) && $cpcfg['page']['errtext']) + if (is_array($cpcfg['page']) && $cpcfg['page']['errtext']) { $errtext = base64_decode($cpcfg['page']['errtext']); - else { + } else { /* example page */ $errtext = get_default_captive_portal_html(); } @@ -254,7 +256,7 @@ function captiveportal_configure_zone($cpcfg) { $errtext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $errtext); $errtext = str_replace("\$ORIGINAL_PORTAL_IP\$", "#ORIGINAL_PORTAL_IP#", $errtext); $errtext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $errtext); - if($cpcfg['preauthurl']) { + if ($cpcfg['preauthurl']) { $errtext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $errtext); $errtext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $errtext); } @@ -264,9 +266,9 @@ function captiveportal_configure_zone($cpcfg) { unset($errtext); /* write logout page */ - if (is_array($cpcfg['page']) && $cpcfg['page']['logouttext']) + if (is_array($cpcfg['page']) && $cpcfg['page']['logouttext']) { $logouttext = base64_decode($cpcfg['page']['logouttext']); - else { + } else { /* example page */ $logouttext = << @@ -321,8 +323,9 @@ EOD; captiveportal_init_webgui_zone($cpcfg); /* Kill any existing prunecaptiveportal processes */ - if (file_exists("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid")) + if (file_exists("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid")) { killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid"); + } /* start pruning process (interval defaults to 60 seconds) */ mwexec("/usr/local/bin/minicron $croninterval {$g['varrun_path']}/cp_prunedb_{$cpzone}.pid " . @@ -362,9 +365,9 @@ EOD; mwexec("/sbin/ipfw zone {$cpzoneid} destroy", true); - if (empty($config['captiveportal'])) + if (empty($config['captiveportal'])) { set_single_sysctl("net.link.ether.ipfw", "0"); - else { + } else { /* Deactivate ipfw(4) if not needed */ $cpactive = false; if (is_array($config['captiveportal'])) { @@ -375,14 +378,14 @@ EOD; } } } - if ($cpactive === false) + if ($cpactive === false) { set_single_sysctl("net.link.ether.ipfw", "0"); - + } } } unlock($captiveportallck); - + return 0; } @@ -399,7 +402,7 @@ function captiveportal_init_webgui() { function captiveportal_init_webgui_zonename($zone) { global $config, $cpzone; - + if (isset($config['captiveportal'][$zone])) { $cpzone = $zone; captiveportal_init_webgui_zone($config['captiveportal'][$zone]); @@ -409,8 +412,9 @@ function captiveportal_init_webgui_zonename($zone) { function captiveportal_init_webgui_zone($cpcfg) { global $g, $config, $cpzone; - if (!isset($cpcfg['enable'])) + if (!isset($cpcfg['enable'])) { return; + } if (isset($cpcfg['httpslogin'])) { $cert = lookup_cert($cpcfg['certref']); @@ -419,20 +423,22 @@ function captiveportal_init_webgui_zone($cpcfg) { $ca = ca_chain($cert); /* generate lighttpd configuration */ - if (!empty($cpcfg['listenporthttps'])) + if (!empty($cpcfg['listenporthttps'])) { $listenporthttps = $cpcfg['listenporthttps']; - else + } else { $listenporthttps = 8001 + $cpcfg['zoneid']; + } system_generate_lighty_config("{$g['varetc_path']}/lighty-{$cpzone}-CaptivePortal-SSL.conf", $crt, $key, $ca, "lighty-{$cpzone}-CaptivePortal-SSL.pid", $listenporthttps, "/usr/local/captiveportal", "cert-{$cpzone}-portal.pem", "ca-{$cpzone}-portal.pem", $cpzone); } /* generate lighttpd configuration */ - if (!empty($cpcfg['listenporthttp'])) + if (!empty($cpcfg['listenporthttp'])) { $listenporthttp = $cpcfg['listenporthttp']; - else + } else { $listenporthttp = 8000 + $cpcfg['zoneid']; + } system_generate_lighty_config("{$g['varetc_path']}/lighty-{$cpzone}-CaptivePortal.conf", "", "", "", "lighty-{$cpzone}-CaptivePortal.pid", $listenporthttp, "/usr/local/captiveportal", "", "", $cpzone); @@ -451,8 +457,9 @@ function captiveportal_init_webgui_zone($cpcfg) { function captiveportal_init_rules_byinterface($interface) { global $cpzone, $cpzoneid, $config; - if (!is_array($config['captiveportal'])) + if (!is_array($config['captiveportal'])) { return; + } foreach ($config['captiveportal'] as $cpkey => $cp) { $cpzone = $cpkey; @@ -469,8 +476,9 @@ function captiveportal_init_rules_byinterface($interface) { function captiveportal_init_rules($reinit = false) { global $config, $g, $cpzone, $cpzoneid; - if (!isset($config['captiveportal'][$cpzone]['enable'])) + if (!isset($config['captiveportal'][$cpzone]['enable'])) { return; + } captiveportal_load_modules(); mwexec("/sbin/ipfw zone {$cpzoneid} create", true); @@ -484,8 +492,9 @@ function captiveportal_init_rules($reinit = false) { $cpinterfaces = explode(",", $config['captiveportal'][$cpzone]['interface']); $firsttime = 0; foreach ($cpinterfaces as $cpifgrp) { - if (!isset($ifaces[$cpifgrp])) + if (!isset($ifaces[$cpifgrp])) { continue; + } $tmpif = get_real_interface($cpifgrp); if (!empty($tmpif)) { $cpipm = get_interface_ip($cpifgrp); @@ -496,8 +505,9 @@ function captiveportal_init_rules($reinit = false) { foreach ($carpsif as $cpcarp) { mwexec("/sbin/ipfw zone {$cpzoneid} madd {$cpcarp}", true); $carpip = find_interface_ip($cpcarp); - if (is_ipaddr($carpip)) + if (is_ipaddr($carpip)) { $cpips[] = $carpip; + } } } $cpips[] = $cpipm; @@ -507,11 +517,13 @@ function captiveportal_init_rules($reinit = false) { } if (count($cpips) > 0) { $cpactive = true; - } else + } else { return false; + } - if ($reinit == false) + if ($reinit == false) { $captiveportallck = lock("captiveportal{$cpzone}"); + } $cprules = << 0) { $lastact = captiveportal_get_last_activity($cpentry[2], $cpentry[3]); /* If the user has logged on but not sent any traffic they will never be logged out. - * We "fix" this by setting lastact to the login timestamp. + * We "fix" this by setting lastact to the login timestamp. */ $lastact = $lastact ? $lastact : $cpentry[0]; if ($lastact && (($pruning_time - $lastact) >= $uidletimeout)) { @@ -742,13 +762,15 @@ function captiveportal_prune_old() { $cpentry[3]); // clientmac } else if ($cpcfg['reauthenticateacct'] == "interimupdate") { $session_time = $pruning_time - $cpentry[0]; - if (!empty($cpentry[10]) && $cpentry[10] > 60) + if (!empty($cpentry[10]) && $cpentry[10] > 60) { $interval = $cpentry[10]; - else + } else { $interval = 0; + } $past_interval_min = ($session_time > $interval); - if ($interval != 0) + if ($interval != 0) { $within_interval = ($session_time % $interval >= 0 && $session_time % $interval <= 59); + } if ($interval === 0 || ($interval > 0 && $past_interval_min && $within_interval)) { RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno $cpentry[4], // username @@ -775,8 +797,9 @@ function captiveportal_prune_old() { captiveportal_disconnect($cpentry, $radiusservers, 17); captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "RADIUS_DISCONNECT", $auth_list['reply_message']); $unsetindexes[] = $cpentry[5]; - } else if ($auth_list['auth_val'] == 2) + } else if ($auth_list['auth_val'] == 2) { captiveportal_reapply_attributes($cpentry, $auth_list); + } } } } @@ -784,13 +807,15 @@ function captiveportal_prune_old() { captiveportal_prune_old_automac(); - if ($voucher_needs_sync == true) + if ($voucher_needs_sync == true) { /* Trigger a sync of the vouchers on config */ send_event("service sync vouchers"); + } /* write database */ - if (!empty($unsetindexes)) + if (!empty($unsetindexes)) { captiveportal_remove_entries($unsetindexes); + } } function captiveportal_prune_old_automac() { @@ -852,8 +877,9 @@ function captiveportal_prune_old_automac() { unset($macrules); mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/macentry.prunerules.tmp"); } - if ($writecfg === true) + if ($writecfg === true) { write_config("Prune session for auto-added macs"); + } } } @@ -876,7 +902,7 @@ function captiveportal_disconnect($dbent, $radiusservers,$term_cause = 1,$stop_t false, $stop_time); } - + if (is_ipaddr($dbent[2])) { /* Delete client's ip entry from tables 1 and 2. */ $clientsn = (is_ipaddrv6($dbent[2])) ? 128 : 32; @@ -887,7 +913,7 @@ function captiveportal_disconnect($dbent, $radiusservers,$term_cause = 1,$stop_t $_gb = @pfSense_kill_srcstates($dbent[2]); } - /* + /* * These are the pipe numbers we use to control traffic shaping for each logged in user via captive portal * We could get an error if the pipe doesn't exist but everything should still be fine */ @@ -900,7 +926,7 @@ function captiveportal_disconnect($dbent, $radiusservers,$term_cause = 1,$stop_t } // XMLRPC Call over to the master Voucher node - if(!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { + if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { $syncip = $config['voucher'][$cpzone]['vouchersyncdbip']; $syncport = $config['voucher'][$cpzone]['vouchersyncport']; $syncpass = $config['voucher'][$cpzone]['vouchersyncpass']; @@ -924,8 +950,9 @@ function captiveportal_disconnect_client($sessionid, $term_cause = 1, $logoutRea captiveportal_write_db("DELETE FROM captiveportal WHERE sessionid = '{$sessionid}'"); foreach ($result as $cpentry) { - if (empty($cpentry[11])) + if (empty($cpentry[11])) { $cpentry[11] = 'first'; + } captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], $term_cause); captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "DISCONNECT"); } @@ -937,15 +964,17 @@ function captiveportal_disconnect_client($sessionid, $term_cause = 1, $logoutRea function captiveportal_radius_stop_all() { global $config, $cpzone; - if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) + if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) { return; + } $radiusservers = captiveportal_get_radius_servers(); if (!empty($radiusservers)) { $cpdb = captiveportal_read_db(); foreach ($cpdb as $cpentry) { - if (empty($cpentry[11])) + if (empty($cpentry[11])) { $cpentry[11] = 'first'; + } if (!empty($radiusservers[$cpentry[11]])) { RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno $cpentry[4], // username @@ -964,15 +993,17 @@ function captiveportal_passthrumac_configure_entry($macent, $pipeinrule = false) global $config, $g, $cpzone; $bwUp = 0; - if (!empty($macent['bw_up'])) + if (!empty($macent['bw_up'])) { $bwUp = $macent['bw_up']; - else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) + } else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) { $bwUp = $config['captiveportal'][$cpzone]['bwdefaultup']; + } $bwDown = 0; - if (!empty($macent['bw_down'])) + if (!empty($macent['bw_down'])) { $bwDown = $macent['bw_down']; - else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) + } else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) { $bwDown = $config['captiveportal'][$cpzone]['bwdefaultdn']; + } $ruleno = captiveportal_get_next_ipfw_ruleno(); @@ -981,16 +1012,18 @@ function captiveportal_passthrumac_configure_entry($macent, $pipeinrule = false) $pipeno = captiveportal_get_next_dn_ruleno(); $pipeup = $pipeno; - if ($pipeinrule == true) + if ($pipeinrule == true) { $_gb = @pfSense_pipe_action("pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16"); - else + } else { $rules .= "pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16\n"; - + } + $pipedown = $pipeno + 1; - if ($pipeinrule == true) + if ($pipeinrule == true) { $_gb = @pfSense_pipe_action("pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16"); - else + } else { $rules .= "pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16\n"; + } $rules .= "add {$ruleno} pipe {$pipeup} ip from any to any MAC any {$macent['mac']}\n"; $ruleno++; @@ -1006,8 +1039,9 @@ function captiveportal_passthrumac_delete_entry($macent) { if ($macent['action'] == 'pass') { $ruleno = captiveportal_get_ipfw_passthru_ruleno($macent['mac']); - if (!$ruleno) + if (!$ruleno) { return $rules; + } captiveportal_free_ipfw_ruleno($ruleno); @@ -1048,13 +1082,16 @@ function captiveportal_passthrumac_configure($filename = false, $startindex = 0, if ($nentries > 2000) { $nloops = $nentries / 1000; $remainder= $nentries % 1000; - for ($i = 0; $i < $nloops; $i++) + for ($i = 0; $i < $nloops; $i++) { mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . ((($i+1) * 1000) - 1) . "\""); - if ($remainder > 0) + } + if ($remainder > 0) { mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . (($i* 1000) + $remainder) ."\""); + } } else { - foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) + foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) { $rules .= captiveportal_passthrumac_configure_entry($macent, true); + } } } } @@ -1067,14 +1104,15 @@ function captiveportal_passthrumac_findbyname($username) { if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) { foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) { - if ($macent['username'] == $username) + if ($macent['username'] == $username) { return $macent; + } } } return NULL; } -/* +/* * table (3=IN)/(4=OUT) hold allowed ip's without bw limits */ function captiveportal_allowedip_configure_entry($ipent, $ishostname = false) { @@ -1086,25 +1124,30 @@ function captiveportal_allowedip_configure_entry($ipent, $ishostname = false) { if ($ishostname === true) { if (!platform_booting()) { $ipaddress = gethostbyname($ipent['hostname']); - if (!is_ipaddr($ipaddress)) + if (!is_ipaddr($ipaddress)) { return; - } else + } + } else { $ipaddress = ""; - } else + } + } else { $ipaddress = $ipent['ip']; + } $rules = ""; $cp_filterdns_conf = ""; $enBwup = 0; - if (!empty($ipent['bw_up'])) + if (!empty($ipent['bw_up'])) { $enBwup = intval($ipent['bw_up']); - else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) + } else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) { $enBwup = $config['captiveportal'][$cpzone]['bwdefaultup']; + } $enBwdown = 0; - if (!empty($ipent['bw_down'])) + if (!empty($ipent['bw_down'])) { $enBwdown = intval($ipent['bw_down']); - else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) + } else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) { $enBwdown = $config['captiveportal'][$cpzone]['bwdefaultdn']; + } $pipeno = captiveportal_get_next_dn_ruleno(); $_gb = @pfSense_pipe_action("pipe {$pipeno} config bw {$enBwup}Kbit/s queue 100 buckets 16"); @@ -1113,19 +1156,22 @@ function captiveportal_allowedip_configure_entry($ipent, $ishostname = false) { if ($ishostname === true) { $cp_filterdns_conf .= "ipfw {$ipent['hostname']} 3 pipe {$pipeno}\n"; $cp_filterdns_conf .= "ipfw {$ipent['hostname']} 4 pipe {$pipedown}\n"; - if (!is_ipaddr($ipaddress)) + if (!is_ipaddr($ipaddress)) { return array("", $cp_filterdns_conf); + } } $subnet = ""; - if (!empty($ipent['sn'])) + if (!empty($ipent['sn'])) { $subnet = "/{$ipent['sn']}"; + } $rules .= "table 3 add {$ipaddress}{$subnet} {$pipeno}\n"; $rules .= "table 4 add {$ipaddress}{$subnet} {$pipedown}\n"; - if ($ishostname === true) + if ($ishostname === true) { return array($rules, $cp_filterdns_conf); - else + } else { return $rules; + } } function captiveportal_allowedhostname_configure() { @@ -1143,10 +1189,11 @@ function captiveportal_allowedhostname_configure() { $cp_filterdns_filename = "{$g['varetc_path']}/filterdns-{$cpzone}-captiveportal.conf"; @file_put_contents($cp_filterdns_filename, $cp_filterdns_conf); unset($cp_filterdns_conf); - if (isvalidpid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid")) + if (isvalidpid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid")) { sigkillbypid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid", "HUP"); - else + } else { mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid -i 300 -c {$cp_filterdns_filename} -y {$cpzone} -d 1"); + } } else { killbypid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid"); @unlink("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid"); @@ -1160,8 +1207,9 @@ function captiveportal_allowedip_configure() { $rules = ""; if (is_array($config['captiveportal'][$cpzone]['allowedip'])) { - foreach ($config['captiveportal'][$cpzone]['allowedip'] as $ipent) + foreach ($config['captiveportal'][$cpzone]['allowedip'] as $ipent) { $rules .= captiveportal_allowedip_configure_entry($ipent); + } } return $rules; @@ -1191,26 +1239,31 @@ function captiveportal_init_radius_servers() { $radiusip3 = ($config['captiveportal'][$cpzone]['radiusip3']) ? $config['captiveportal'][$cpzone]['radiusip3'] : null; $radiusip4 = ($config['captiveportal'][$cpzone]['radiusip4']) ? $config['captiveportal'][$cpzone]['radiusip4'] : null; - if ($config['captiveportal'][$cpzone]['radiusport']) + if ($config['captiveportal'][$cpzone]['radiusport']) { $radiusport = $config['captiveportal'][$cpzone]['radiusport']; - else + } else { $radiusport = 1812; - if ($config['captiveportal'][$cpzone]['radiusacctport']) + } + if ($config['captiveportal'][$cpzone]['radiusacctport']) { $radiusacctport = $config['captiveportal'][$cpzone]['radiusacctport']; - else + } else { $radiusacctport = 1813; - if ($config['captiveportal'][$cpzone]['radiusport2']) + } + if ($config['captiveportal'][$cpzone]['radiusport2']) { $radiusport2 = $config['captiveportal'][$cpzone]['radiusport2']; - else + } else { $radiusport2 = 1812; - if ($config['captiveportal'][$cpzone]['radiusport3']) + } + if ($config['captiveportal'][$cpzone]['radiusport3']) { $radiusport3 = $config['captiveportal'][$cpzone]['radiusport3']; - else + } else { $radiusport3 = 1812; - if ($config['captiveportal'][$cpzone]['radiusport4']) + } + if ($config['captiveportal'][$cpzone]['radiusport4']) { $radiusport4 = $config['captiveportal'][$cpzone]['radiusport4']; - else + } else { $radiusport4 = 1812; + } $radiuskey = $config['captiveportal'][$cpzone]['radiuskey']; $radiuskey2 = $config['captiveportal'][$cpzone]['radiuskey2']; @@ -1224,15 +1277,18 @@ function captiveportal_init_radius_servers() { unlock($cprdsrvlck); return 1; } - if (isset($radiusip)) + if (isset($radiusip)) { fwrite($fd,$radiusip . "," . $radiusport . "," . $radiusacctport . "," . $radiuskey . ",first"); - if (isset($radiusip2)) + } + if (isset($radiusip2)) { fwrite($fd,"\n" . $radiusip2 . "," . $radiusport2 . "," . $radiusacctport . "," . $radiuskey2 . ",first"); - if (isset($radiusip3)) + } + if (isset($radiusip3)) { fwrite($fd,"\n" . $radiusip3 . "," . $radiusport3 . "," . $radiusacctport . "," . $radiuskey3 . ",second"); - if (isset($radiusip4)) + } + if (isset($radiusip4)) { fwrite($fd,"\n" . $radiusip4 . "," . $radiusport4 . "," . $radiusacctport . "," . $radiuskey4 . ",second"); - + } fclose($fd); unlock($cprdsrvlck); @@ -1246,22 +1302,24 @@ function captiveportal_get_radius_servers() { $cprdsrvlck = lock("captiveportalradius{$cpzone}"); if (file_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db")) { $radiusservers = array(); - $cpradiusdb = file("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db", + $cpradiusdb = file("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if ($cpradiusdb) { - foreach($cpradiusdb as $cpradiusentry) { + foreach ($cpradiusdb as $cpradiusentry) { $line = trim($cpradiusentry); if ($line) { $radsrv = array(); list($radsrv['ipaddr'],$radsrv['port'],$radsrv['acctport'],$radsrv['key'], $context) = explode(",",$line); } if (empty($context)) { - if (!is_array($radiusservers['first'])) + if (!is_array($radiusservers['first'])) { $radiusservers['first'] = array(); + } $radiusservers['first'] = $radsrv; } else { - if (!is_array($radiusservers[$context])) + if (!is_array($radiusservers[$context])) { $radiusservers[$context] = array(); + } $radiusservers[$context][] = $radsrv; } } @@ -1278,9 +1336,9 @@ function captiveportal_get_radius_servers() { /* part of this code from php.net */ function captiveportal_logportalauth($user,$mac,$ip,$status, $message = null) { // Log it - if (!$message) + if (!$message) { $message = "{$status}: {$user}, {$mac}, {$ip}"; - else { + } else { $message = trim($message); $message = "{$status}: {$user}, {$mac}, {$ip}, {$message}"; } @@ -1314,8 +1372,9 @@ function radius($username,$password,$clientip,$clientmac,$type, $radiusctx = nul $radiusservers = captiveportal_get_radius_servers(); - if (is_null($radiusctx)) + if (is_null($radiusctx)) { $radiusctx = 'first'; + } $auth_list = RADIUS_AUTHENTICATION($username, $password, @@ -1334,8 +1393,8 @@ function radius($username,$password,$clientip,$clientmac,$type, $radiusctx = nul $pipeno, $radiusctx); } else { - captiveportal_free_dn_ruleno($pipeno); - } + captiveportal_free_dn_ruleno($pipeno); + } return $auth_list; } @@ -1345,14 +1404,15 @@ function captiveportal_opendb() { $DB = new SQLite3("{$g['vardb_path']}/captiveportal{$cpzone}.db"); if (! $DB->exec("CREATE TABLE IF NOT EXISTS captiveportal (" . - "allow_time INTEGER, pipeno INTEGER, ip TEXT, mac TEXT, username TEXT, " . - "sessionid TEXT, bpassword TEXT, session_timeout INTEGER, idle_timeout INTEGER, " . - "session_terminate_time INTEGER, interim_interval INTEGER, radiusctx TEXT); " . - "CREATE UNIQUE INDEX IF NOT EXISTS idx_active ON captiveportal (sessionid, username); " . - "CREATE INDEX IF NOT EXISTS user ON captiveportal (username); " . - "CREATE INDEX IF NOT EXISTS ip ON captiveportal (ip); " . - "CREATE INDEX IF NOT EXISTS starttime ON captiveportal (allow_time)")) + "allow_time INTEGER, pipeno INTEGER, ip TEXT, mac TEXT, username TEXT, " . + "sessionid TEXT, bpassword TEXT, session_timeout INTEGER, idle_timeout INTEGER, " . + "session_terminate_time INTEGER, interim_interval INTEGER, radiusctx TEXT); " . + "CREATE UNIQUE INDEX IF NOT EXISTS idx_active ON captiveportal (sessionid, username); " . + "CREATE INDEX IF NOT EXISTS user ON captiveportal (username); " . + "CREATE INDEX IF NOT EXISTS ip ON captiveportal (ip); " . + "CREATE INDEX IF NOT EXISTS starttime ON captiveportal (allow_time)")) { captiveportal_syslog("Error during table {$cpzone} creation. Error message: {$DB->lastErrorMsg()}"); + } return $DB; } @@ -1365,8 +1425,9 @@ function captiveportal_read_db($query = "") { if ($DB) { $response = $DB->query("SELECT * FROM captiveportal {$query}"); if ($response != FALSE) { - while ($row = $response->fetchArray()) + while ($row = $response->fetchArray()) { $cpdb[] = $row; + } } $DB->close(); } @@ -1376,14 +1437,16 @@ function captiveportal_read_db($query = "") { function captiveportal_remove_entries($remove) { - if (!is_array($remove) || empty($remove)) + if (!is_array($remove) || empty($remove)) { return; + } $query = "DELETE FROM captiveportal WHERE sessionid in ("; - foreach($remove as $idx => $unindex) { + foreach ($remove as $idx => $unindex) { $query .= "'{$unindex}'"; - if ($idx < (count($remove) - 1)) + if ($idx < (count($remove) - 1)) { $query .= ","; + } } $query .= ")"; captiveportal_write_db($query); @@ -1393,32 +1456,36 @@ function captiveportal_remove_entries($remove) { function captiveportal_write_db($queries) { global $g; - if (is_array($queries)) + if (is_array($queries)) { $query = implode(";", $queries); - else + } else { $query = $queries; + } $DB = captiveportal_opendb(); if ($DB) { $DB->exec("BEGIN TRANSACTION"); $result = $DB->exec($query); - if (!$result) + if (!$result) { captiveportal_syslog("Trying to modify DB returned error: {$DB->lastErrorMsg()}"); - else + } else { $DB->exec("END TRANSACTION"); + } $DB->close(); return $result; - } else + } else { return true; + } } function captiveportal_write_elements() { global $g, $config, $cpzone; - + $cpcfg = $config['captiveportal'][$cpzone]; - if (!is_dir($g['captiveportal_element_path'])) + if (!is_dir($g['captiveportal_element_path'])) { @mkdir($g['captiveportal_element_path']); + } if (is_array($cpcfg['element'])) { conf_mount_rw(); @@ -1427,12 +1494,13 @@ function captiveportal_write_elements() { printf(gettext("Error: cannot open '%s' in captiveportal_write_elements()%s"), $data['name'], "\n"); return 1; } - if (!file_exists("{$g['captiveportal_path']}/{$data['name']}")) + if (!file_exists("{$g['captiveportal_path']}/{$data['name']}")) { @symlink("{$g['captiveportal_element_path']}/{$data['name']}", "{$g['captiveportal_path']}/{$data['name']}"); + } } conf_mount_ro(); } - + return 0; } @@ -1449,8 +1517,9 @@ function captiveportal_free_dnrules($rulenos_start = 2000, $rulenos_range_max = $ridx++; $rules[$ridx] = false; $ridx++; - } else + } else { $ridx += 2; + } } file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules)); unset($rules); @@ -1510,8 +1579,9 @@ function captiveportal_get_dn_passthru_ruleno($value) { global $config, $g, $cpzone, $cpzoneid; $cpcfg = $config['captiveportal'][$cpzone]; - if(!isset($cpcfg['enable'])) + if (!isset($cpcfg['enable'])) { return NULL; + } $cpruleslck = lock("captiveportalrulesdn", LOCK_EX); $ruleno = NULL; @@ -1520,8 +1590,9 @@ function captiveportal_get_dn_passthru_ruleno($value) { unset($output); $_gb = exec("/sbin/ipfw -x {$cpzoneid} show | /usr/bin/grep " . escapeshellarg($value) . " | /usr/bin/grep -v grep | /usr/bin/awk '{print $5}' | /usr/bin/head -n 1", $output); $ruleno = intval($output[0]); - if (!$rules[$ruleno]) + if (!$rules[$ruleno]) { $ruleno = NULL; + } unset($rules); } unlock($cpruleslck); @@ -1538,8 +1609,9 @@ function captiveportal_get_next_ipfw_ruleno($rulenos_start = 2, $rulenos_range_m global $config, $g, $cpzone; $cpcfg = $config['captiveportal'][$cpzone]; - if(!isset($cpcfg['enable'])) + if (!isset($cpcfg['enable'])) { return NULL; + } $cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX); $ruleno = 0; @@ -1554,8 +1626,8 @@ function captiveportal_get_next_ipfw_ruleno($rulenos_start = 2, $rulenos_range_m $rules[$ridx] = $cpzone; break; } else { - /* - * This allows our traffic shaping pipes to be the in pipe the same as ruleno + /* + * This allows our traffic shaping pipes to be the in pipe the same as ruleno * and the out pipe ruleno + 1. */ $ridx += 2; @@ -1579,8 +1651,9 @@ function captiveportal_free_ipfw_ruleno($ruleno) { global $config, $g, $cpzone; $cpcfg = $config['captiveportal'][$cpzone]; - if(!isset($cpcfg['enable'])) + if (!isset($cpcfg['enable'])) { return NULL; + } $cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX); if (file_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules")) { @@ -1598,8 +1671,9 @@ function captiveportal_get_ipfw_passthru_ruleno($value) { global $config, $g, $cpzone, $cpzoneid; $cpcfg = $config['captiveportal'][$cpzone]; - if(!isset($cpcfg['enable'])) + if (!isset($cpcfg['enable'])) { return NULL; + } $cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX); $ruleno = NULL; @@ -1608,8 +1682,9 @@ function captiveportal_get_ipfw_passthru_ruleno($value) { unset($output); $_gb = exec("/sbin/ipfw -x {$cpzoneid} show | /usr/bin/grep " . escapeshellarg($value) . " | /usr/bin/grep -v grep | /usr/bin/awk '{print $1}' | /usr/bin/head -n 1", $output); $ruleno = intval($output[0]); - if (!$rules[$ruleno]) + if (!$rules[$ruleno]) { $ruleno = NULL; + } unset($rules); } unlock($cpruleslck); @@ -1677,14 +1752,16 @@ function getNasIP() if (empty($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) { $nasIp = get_interface_ip(); } else { - if (is_ipaddr($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) + if (is_ipaddr($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) { $nasIp = $config['captiveportal'][$cpzone]['radiussrcip_attribute']; - else + } else { $nasIp = get_interface_ip($config['captiveportal'][$cpzone]['radiussrcip_attribute']); + } } - - if(!is_ipaddr($nasIp)) + + if (!is_ipaddr($nasIp)) { $nasIp = "0.0.0.0"; + } return $nasIp; } @@ -1702,8 +1779,9 @@ function portal_ip_from_client_ip($cliip) { $ip = get_interface_ip($cpif); $sn = get_interface_subnet($cpif); } - if (ip_in_subnet($cliip, "{$ip}/{$sn}")) + if (ip_in_subnet($cliip, "{$ip}/{$sn}")) { return $ip; + } } $inet = ($isipv6) ? '-inet6' : '-inet'; @@ -1711,19 +1789,21 @@ function portal_ip_from_client_ip($cliip) { $iface = trim($iface, "\n"); if (!empty($iface)) { $ip = ($isipv6) ? find_interface_ipv6($iface) : find_interface_ip($iface); - if (is_ipaddr($ip)) + if (is_ipaddr($ip)) { return $ip; + } } // doesn't match up to any particular interface - // so let's set the portal IP to what PHP says - // the server IP issuing the request is. - // allows same behavior as 1.2.x where IP isn't + // so let's set the portal IP to what PHP says + // the server IP issuing the request is. + // allows same behavior as 1.2.x where IP isn't // in the subnet of any CP interface (static routes, etc.) // rather than forcing to DNS hostname resolution $ip = $_SERVER['SERVER_ADDR']; - if (is_ipaddr($ip)) + if (is_ipaddr($ip)) { return $ip; + } return false; } @@ -1736,21 +1816,24 @@ function portal_hostname_from_client_ip($cliip) { if (isset($cpcfg['httpslogin'])) { $listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 8001); $ourhostname = $cpcfg['httpsname']; - - if ($listenporthttps != 443) + + if ($listenporthttps != 443) { $ourhostname .= ":" . $listenporthttps; + } } else { $listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : ($cpcfg['zoneid'] + 8000); $ifip = portal_ip_from_client_ip($cliip); - if (!$ifip) + if (!$ifip) { $ourhostname = "{$config['system']['hostname']}.{$config['system']['domain']}"; - else + } else { $ourhostname = (is_ipaddrv6($ifip)) ? "[{$ifip}]" : "{$ifip}"; - - if ($listenporthttp != 80) + } + + if ($listenporthttp != 80) { $ourhostname .= ":" . $listenporthttp; + } } - + return $ourhostname; } @@ -1763,10 +1846,11 @@ function portal_reply_page($redirurl, $type = null, $message = null, $clientmac if ($type == "redir") { header("Location: {$redirurl}"); return; - } else if ($type == "login") + } else if ($type == "login") { $htmltext = get_include_contents("{$g['varetc_path']}/captiveportal_{$cpzone}.html"); - else + } else { $htmltext = get_include_contents("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html"); + } $cpcfg = $config['captiveportal'][$cpzone]; @@ -1788,7 +1872,7 @@ function portal_reply_page($redirurl, $type = null, $message = null, $clientmac $htmltext = str_replace("\$CLIENT_MAC\$", htmlspecialchars($clientmac), $htmltext); $htmltext = str_replace("\$CLIENT_IP\$", htmlspecialchars($clientip), $htmltext); - // Special handling case for captive portal master page so that it can be ran + // Special handling case for captive portal master page so that it can be ran // through the PHP interpreter using the include method above. We convert the // $VARIABLE$ case to #VARIABLE# in /etc/inc/captiveportal.inc before writing out. $htmltext = str_replace("#PORTAL_ZONE#", htmlspecialchars($cpzone), $htmltext); @@ -1810,11 +1894,13 @@ function portal_mac_radius($clientmac,$clientip) { /* authentication against the radius server */ $username = mac_format($clientmac); $auth_list = radius($username,$radmac_secret,$clientip,$clientmac,"MACHINE LOGIN"); - if ($auth_list['auth_val'] == 2) + if ($auth_list['auth_val'] == 2) { return TRUE; + } - if (!empty($auth_list['url_redirection'])) + if (!empty($auth_list['url_redirection'])) { portal_reply_page($auth_list['url_redirection'], "redir"); + } return FALSE; } @@ -1825,8 +1911,9 @@ function captiveportal_reapply_attributes($cpentry, $attributes) { if (isset($config['captiveportal'][$cpzone]['peruserbw'])) { $dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0; $dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0; - } else + } else { $dwfaultbw_up = $dwfaultbw_down = 0; + } $bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up; $bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down; $bw_up_pipeno = $cpentry[1]; @@ -1843,16 +1930,18 @@ function portal_allow($clientip,$clientmac,$username,$password = null, $attribut global $redirurl, $g, $config, $type, $passthrumac, $_POST, $cpzone, $cpzoneid; // Ensure we create an array if we are missing attributes - if (!is_array($attributes)) + if (!is_array($attributes)) { $attributes = array(); + } unset($sessionid); /* Do not allow concurrent login execution. */ $cpdblck = lock("captiveportaldb{$cpzone}", LOCK_EX); - if ($attributes['voucher']) + if ($attributes['voucher']) { $remaining_time = $attributes['session_timeout']; + } $writecfg = false; /* Find an existing session */ @@ -1903,16 +1992,18 @@ function portal_allow($clientip,$clientmac,$username,$password = null, $attribut /* read in client database */ $query = "WHERE ip = '{$clientip}'"; $tmpusername = strtolower($username); - if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) + if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) { $query .= " OR (username != 'unauthenticated' AND lower(username) = '{$tmpusername}')"; + } $cpdb = captiveportal_read_db($query); /* Snapshot the timestamp */ $allow_time = time(); $radiusservers = captiveportal_get_radius_servers(); $unsetindexes = array(); - if (is_null($radiusctx)) + if (is_null($radiusctx)) { $radiusctx = 'first'; + } foreach ($cpdb as $cpentry) { if (empty($cpentry[11])) { @@ -1920,27 +2011,27 @@ function portal_allow($clientip,$clientmac,$username,$password = null, $attribut } /* on the same ip */ if ($cpentry[2] == $clientip) { - if (isset($config['captiveportal'][$cpzone]['nomacfilter']) || $cpentry[3] == $clientmac) + if (isset($config['captiveportal'][$cpzone]['nomacfilter']) || $cpentry[3] == $clientmac) { captiveportal_logportalauth($cpentry[4],$cpentry[3],$cpentry[2],"CONCURRENT LOGIN - REUSING OLD SESSION"); - else + } else { captiveportal_logportalauth($cpentry[4],$cpentry[3],$cpentry[2],"CONCURRENT LOGIN - REUSING IP {$cpentry[2]} WITH DIFFERENT MAC ADDRESS {$cpentry[3]}"); + } $sessionid = $cpentry[5]; break; - } - elseif (($attributes['voucher']) && ($username != 'unauthenticated') && ($cpentry[4] == $username)) { - // user logged in with an active voucher. Check for how long and calculate + } elseif (($attributes['voucher']) && ($username != 'unauthenticated') && ($cpentry[4] == $username)) { + // user logged in with an active voucher. Check for how long and calculate // how much time we can give him (voucher credit - used time) $remaining_time = $cpentry[0] + $cpentry[7] - $allow_time; - if ($remaining_time < 0) // just in case. + if ($remaining_time < 0) { // just in case. $remaining_time = 0; + } /* This user was already logged in so we disconnect the old one */ captiveportal_disconnect($cpentry,$radiusservers[$cpentry[11]],13); captiveportal_logportalauth($cpentry[4],$cpentry[3],$cpentry[2],"CONCURRENT LOGIN - TERMINATING OLD SESSION"); $unsetindexes[] = $cpentry[5]; break; - } - elseif ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && ($username != 'unauthenticated')) { + } elseif ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && ($username != 'unauthenticated')) { /* on the same username */ if (strcasecmp($cpentry[4], $username) == 0) { /* This user was already logged in so we disconnect the old one */ @@ -1953,11 +2044,13 @@ function portal_allow($clientip,$clientmac,$username,$password = null, $attribut } unset($cpdb); - if (!empty($unsetindexes)) + if (!empty($unsetindexes)) { captiveportal_remove_entries($unsetindexes); + } - if ($attributes['voucher'] && $remaining_time <= 0) + if ($attributes['voucher'] && $remaining_time <= 0) { return 0; // voucher already used and no time left + } if (!isset($sessionid)) { /* generate unique session ID */ @@ -1971,19 +2064,24 @@ function portal_allow($clientip,$clientmac,$username,$password = null, $attribut $mac['ip'] = $clientip; /* Used only for logging */ if (isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) { $mac['username'] = $username; - if ($attributes['voucher']) + if ($attributes['voucher']) { $mac['logintype'] = "voucher"; + } } - if ($username = "unauthenticated") + if ($username = "unauthenticated") { $mac['descr'] = "Auto-added"; - else + } else { $mac['descr'] = "Auto-added for user {$username}"; - if (!empty($bw_up)) + } + if (!empty($bw_up)) { $mac['bw_up'] = $bw_up; - if (!empty($bw_down)) + } + if (!empty($bw_down)) { $mac['bw_down'] = $bw_down; - if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) + } + if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) { $config['captiveportal'][$cpzone]['passthrumac'] = array(); + } $config['captiveportal'][$cpzone]['passthrumac'][] = $mac; unlock($cpdblck); $macrules = captiveportal_passthrumac_configure_entry($mac); @@ -1992,8 +2090,9 @@ function portal_allow($clientip,$clientmac,$username,$password = null, $attribut $writecfg = true; } else { /* See if a pipeno is passed, if not start sessions because this means there isn't one atm */ - if (is_null($pipeno)) + if (is_null($pipeno)) { $pipeno = captiveportal_get_next_dn_ruleno(); + } /* if the pool is empty, return appropriate message and exit */ if (is_null($pipeno)) { @@ -2006,8 +2105,9 @@ function portal_allow($clientip,$clientmac,$username,$password = null, $attribut if (isset($config['captiveportal'][$cpzone]['peruserbw'])) { $dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0; $dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0; - } else + } else { $dwfaultbw_up = $dwfaultbw_down = 0; + } $bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up; $bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down; @@ -2018,19 +2118,22 @@ function portal_allow($clientip,$clientmac,$username,$password = null, $attribut $_gb = @pfSense_pipe_action("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16"); $clientsn = (is_ipaddrv6($clientip)) ? 128 : 32; - if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) + if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) { $_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 1, $clientip, $clientsn, $clientmac, $bw_up_pipeno); - else + } else { $_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 1, $clientip, $clientsn, NULL, $bw_up_pipeno); + } - if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) + if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) { $_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 2, $clientip, $clientsn, $clientmac, $bw_down_pipeno); - else + } else { $_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 2, $clientip, $clientsn, NULL, $bw_down_pipeno); + } - if ($attributes['voucher']) + if ($attributes['voucher']) { $attributes['session_timeout'] = $remaining_time; - + } + /* handle empty attributes */ $session_timeout = (!empty($attributes['session_timeout'])) ? $attributes['session_timeout'] : 'NULL'; $idle_timeout = (!empty($attributes['idle_timeout'])) ? $attributes['idle_timeout'] : 'NULL'; @@ -2053,38 +2156,43 @@ function portal_allow($clientip,$clientmac,$username,$password = null, $attribut if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers[$radiusctx])) { $acct_val = RADIUS_ACCOUNTING_START($pipeno, $username, $sessionid, $radiusservers[$radiusctx], $clientip, $clientmac); - if ($acct_val == 1) + if ($acct_val == 1) { captiveportal_logportalauth($username,$clientmac,$clientip,$type,"RADIUS ACCOUNTING FAILED"); + } } } } else { /* NOTE: #3062-11 If the pipeno has been allocated free it to not DoS the CP and maintain proper operation as in radius() case */ - if (!is_null($pipeno)) + if (!is_null($pipeno)) { captiveportal_free_dn_ruleno($pipeno); + } unlock($cpdblck); } - if ($writecfg == true) + if ($writecfg == true) { write_config(); + } /* redirect user to desired destination */ - if (!empty($attributes['url_redirection'])) + if (!empty($attributes['url_redirection'])) { $my_redirurl = $attributes['url_redirection']; - else if (!empty($redirurl)) + } else if (!empty($redirurl)) { $my_redirurl = $redirurl; - else if (!empty($config['captiveportal'][$cpzone]['redirurl'])) + } else if (!empty($config['captiveportal'][$cpzone]['redirurl'])) { $my_redirurl = $config['captiveportal'][$cpzone]['redirurl']; + } - if(isset($config['captiveportal'][$cpzone]['logoutwin_enable']) && !$passthrumac) { + if (isset($config['captiveportal'][$cpzone]['logoutwin_enable']) && !$passthrumac) { $ourhostname = portal_hostname_from_client_ip($clientip); $protocol = (isset($config['captiveportal'][$cpzone]['httpslogin'])) ? 'https://' : 'http://'; $logouturl = "{$protocol}{$ourhostname}/"; - if (isset($attributes['reply_message'])) + if (isset($attributes['reply_message'])) { $message = $attributes['reply_message']; - else + } else { $message = 0; + } include("{$g['varetc_path']}/captiveportal-{$cpzone}-logout.html"); @@ -2105,18 +2213,21 @@ function portal_allow($clientip,$clientmac,$username,$password = null, $attribut function portal_consume_passthrough_credit($clientmac) { global $config, $cpzone; - if (!empty($config['captiveportal'][$cpzone]['freelogins_count']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_count'])) + if (!empty($config['captiveportal'][$cpzone]['freelogins_count']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_count'])) { $freeloginscount = $config['captiveportal'][$cpzone]['freelogins_count']; - else + } else { return false; + } - if (!empty($config['captiveportal'][$cpzone]['freelogins_resettimeout']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_resettimeout'])) + if (!empty($config['captiveportal'][$cpzone]['freelogins_resettimeout']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_resettimeout'])) { $resettimeout = $config['captiveportal'][$cpzone]['freelogins_resettimeout']; - else + } else { return false; + } - if ($freeloginscount < 1 || $resettimeout <= 0 || !$clientmac) + if ($freeloginscount < 1 || $resettimeout <= 0 || !$clientmac) { return false; + } $updatetimeouts = isset($config['captiveportal'][$cpzone]['freelogins_updatetimeouts']); @@ -2148,12 +2259,14 @@ function portal_consume_passthrough_credit($clientmac) { } $found = true; - } else + } else { unset($usedmacs[$key]); + } break; - } else if ($usedmac[0] + ($resettimeout * 3600) <= $currenttime) - unset($usedmacs[$key]); + } else if ($usedmac[0] + ($resettimeout * 3600) <= $currenttime) { + unset($usedmacs[$key]); + } } if (!$found) { @@ -2171,10 +2284,12 @@ function captiveportal_read_usedmacs_db() { $cpumaclck = lock("captiveusedmacs{$cpzone}"); if (file_exists("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db")) { $usedmacs = file("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - if (!$usedmacs) + if (!$usedmacs) { $usedmacs = array(); - } else + } + } else { $usedmacs = array(); + } unlock($cpumaclck); return $usedmacs; @@ -2191,16 +2306,20 @@ function captiveportal_write_usedmacs_db($usedmacs) { function captiveportal_blocked_mac($mac) { global $config, $g, $cpzone; - if (empty($mac) || !is_macaddr($mac)) + if (empty($mac) || !is_macaddr($mac)) { return false; + } - if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) + if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) { return false; + } - foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac) + foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac) { if (($passthrumac['action'] == 'block') && - ($passthrumac['mac'] == strtolower($mac))) + ($passthrumac['mac'] == strtolower($mac))) { return true; + } + } return false; diff --git a/etc/inc/certs.inc b/etc/inc/certs.inc index 27916fb7b6..ce320a98e4 100644 --- a/etc/inc/certs.inc +++ b/etc/inc/certs.inc @@ -52,10 +52,13 @@ $openssl_crl_status = array( function & lookup_ca($refid) { global $config; - if (is_array($config['ca'])) - foreach ($config['ca'] as & $ca) - if ($ca['refid'] == $refid) + if (is_array($config['ca'])) { + foreach ($config['ca'] as & $ca) { + if ($ca['refid'] == $refid) { return $ca; + } + } + } return false; } @@ -63,13 +66,14 @@ function & lookup_ca($refid) { function & lookup_ca_by_subject($subject) { global $config; - if (is_array($config['ca'])) - foreach ($config['ca'] as & $ca) - { + if (is_array($config['ca'])) { + foreach ($config['ca'] as & $ca) { $ca_subject = cert_get_subject($ca['crt']); - if ($ca_subject == $subject) + if ($ca_subject == $subject) { return $ca; + } } + } return false; } @@ -77,46 +81,57 @@ function & lookup_ca_by_subject($subject) { function & lookup_cert($refid) { global $config; - if (is_array($config['cert'])) - foreach ($config['cert'] as & $cert) - if ($cert['refid'] == $refid) + if (is_array($config['cert'])) { + foreach ($config['cert'] as & $cert) { + if ($cert['refid'] == $refid) { return $cert; + } + } + } return false; } function & lookup_cert_by_name($name) { global $config; - if (is_array($config['cert'])) - foreach ($config['cert'] as & $cert) - if ($cert['descr'] == $name) + if (is_array($config['cert'])) { + foreach ($config['cert'] as & $cert) { + if ($cert['descr'] == $name) { return $cert; + } + } + } } function & lookup_crl($refid) { global $config; - if (is_array($config['crl'])) - foreach ($config['crl'] as & $crl) - if ($crl['refid'] == $refid) + if (is_array($config['crl'])) { + foreach ($config['crl'] as & $crl) { + if ($crl['refid'] == $refid) { return $crl; + } + } + } return false; } function ca_chain_array(& $cert) { - if($cert['caref']) { + if ($cert['caref']) { $chain = array(); $crt = lookup_ca($cert['caref']); $chain[] = $crt; while ($crt) { $caref = $crt['caref']; - if($caref) + if ($caref) { $crt = lookup_ca($caref); - else + } else { $crt = false; - if($crt) + } + if ($crt) { $chain[] = $crt; + } } return $chain; } @@ -124,15 +139,15 @@ function ca_chain_array(& $cert) { } function ca_chain(& $cert) { - if($cert['caref']) { + if ($cert['caref']) { $ca = ""; $cas = ca_chain_array($cert); - if (is_array($cas)) - foreach ($cas as & $ca_cert) - { + if (is_array($cas)) { + foreach ($cas as & $ca_cert) { $ca .= base64_decode($ca_cert['crt']); $ca .= "\n"; } + } return $ca; } return ""; @@ -142,35 +157,40 @@ function ca_import(& $ca, $str, $key="", $serial=0) { global $config; $ca['crt'] = base64_encode($str); - if (!empty($key)) + if (!empty($key)) { $ca['prv'] = base64_encode($key); - if (!empty($serial)) + } + if (!empty($serial)) { $ca['serial'] = $serial; + } $subject = cert_get_subject($str, false); $issuer = cert_get_issuer($str, false); - + // Find my issuer unless self-signed - if($issuer <> $subject) { + if ($issuer <> $subject) { $issuer_crt =& lookup_ca_by_subject($issuer); - if($issuer_crt) + if ($issuer_crt) { $ca['caref'] = $issuer_crt['refid']; + } } /* Correct if child certificate was loaded first */ - if (is_array($config['ca'])) - foreach ($config['ca'] as & $oca) - { + if (is_array($config['ca'])) { + foreach ($config['ca'] as & $oca) { $issuer = cert_get_issuer($oca['crt']); - if($ca['refid']<>$oca['refid'] && $issuer==$subject) + if ($ca['refid']<>$oca['refid'] && $issuer==$subject) { $oca['caref'] = $ca['refid']; + } } - if (is_array($config['cert'])) - foreach ($config['cert'] as & $cert) - { + } + if (is_array($config['cert'])) { + foreach ($config['cert'] as & $cert) { $issuer = cert_get_issuer($cert['crt']); - if($issuer==$subject) + if ($issuer==$subject) { $cert['caref'] = $ca['refid']; + } } + } return true; } @@ -185,20 +205,27 @@ function ca_create(& $ca, $keylen, $lifetime, $dn, $digest_alg = "sha256") { // generate a new key pair $res_key = openssl_pkey_new($args); - if (!$res_key) return false; + if (!$res_key) { + return false; + } // generate a certificate signing request $res_csr = openssl_csr_new($dn, $res_key, $args); - if (!$res_csr) return false; + if (!$res_csr) { + return false; + } // self sign the certificate $res_crt = openssl_csr_sign($res_csr, null, $res_key, $lifetime, $args); - if (!$res_crt) return false; + if (!$res_crt) { + return false; + } // export our certificate data if (!openssl_pkey_export($res_key, $str_key) || - !openssl_x509_export($res_crt, $str_crt)) + !openssl_x509_export($res_crt, $str_crt)) { return false; + } // return our ca information $ca['crt'] = base64_encode($str_crt); @@ -211,12 +238,15 @@ function ca_create(& $ca, $keylen, $lifetime, $dn, $digest_alg = "sha256") { function ca_inter_create(& $ca, $keylen, $lifetime, $dn, $caref, $digest_alg = "sha256") { // Create Intermediate Certificate Authority $signing_ca =& lookup_ca($caref); - if (!$signing_ca) + if (!$signing_ca) { return false; + } $signing_ca_res_crt = openssl_x509_read(base64_decode($signing_ca['crt'])); $signing_ca_res_key = openssl_pkey_get_private(array(0 => base64_decode($signing_ca['prv']) , 1 => "")); - if (!$signing_ca_res_crt || !$signing_ca_res_key) return false; + if (!$signing_ca_res_crt || !$signing_ca_res_key) { + return false; + } $signing_ca_serial = ++$signing_ca['serial']; $args = array( @@ -228,20 +258,27 @@ function ca_inter_create(& $ca, $keylen, $lifetime, $dn, $caref, $digest_alg = " // generate a new key pair $res_key = openssl_pkey_new($args); - if (!$res_key) return false; + if (!$res_key) { + return false; + } // generate a certificate signing request $res_csr = openssl_csr_new($dn, $res_key, $args); - if (!$res_csr) return false; + if (!$res_csr) { + return false; + } // Sign the certificate $res_crt = openssl_csr_sign($res_csr, $signing_ca_res_crt, $signing_ca_res_key, $lifetime, $args, $signing_ca_serial); - if (!$res_crt) return false; + if (!$res_crt) { + return false; + } // export our certificate data if (!openssl_pkey_export($res_key, $str_key) || - !openssl_x509_export($res_crt, $str_crt)) + !openssl_x509_export($res_crt, $str_crt)) { return false; + } // return our ca information $ca['crt'] = base64_encode($str_crt); @@ -258,12 +295,13 @@ function cert_import(& $cert, $crt_str, $key_str) { $subject = cert_get_subject($crt_str, false); $issuer = cert_get_issuer($crt_str, false); - + // Find my issuer unless self-signed - if($issuer <> $subject) { + if ($issuer <> $subject) { $issuer_crt =& lookup_ca_by_subject($issuer); - if($issuer_crt) + if ($issuer_crt) { $cert['caref'] = $issuer_crt['refid']; + } } return true; } @@ -275,14 +313,17 @@ function cert_create(& $cert, $caref, $keylen, $lifetime, $dn, $type="user", $di if ($type != "self-signed") { $cert['caref'] = $caref; $ca =& lookup_ca($caref); - if (!$ca) + if (!$ca) { return false; + } $ca_str_crt = base64_decode($ca['crt']); $ca_str_key = base64_decode($ca['prv']); $ca_res_crt = openssl_x509_read($ca_str_crt); $ca_res_key = openssl_pkey_get_private(array(0 => $ca_str_key, 1 => "")); - if(!$ca_res_key) return false; + if (!$ca_res_key) { + return false; + } $ca_serial = ++$ca['serial']; } @@ -316,7 +357,9 @@ function cert_create(& $cert, $caref, $keylen, $lifetime, $dn, $type="user", $di // generate a new key pair $res_key = openssl_pkey_new($args); - if(!$res_key) return false; + if (!$res_key) { + return false; + } // If this is a self-signed cert, blank out the CA and sign with the cert's key if ($type == "self-signed") { @@ -329,17 +372,22 @@ function cert_create(& $cert, $caref, $keylen, $lifetime, $dn, $type="user", $di // generate a certificate signing request $res_csr = openssl_csr_new($dn, $res_key, $args); - if(!$res_csr) return false; + if (!$res_csr) { + return false; + } // sign the certificate using an internal CA $res_crt = openssl_csr_sign($res_csr, $ca_res_crt, $ca_res_key, $lifetime, $args, $ca_serial); - if(!$res_crt) return false; + if (!$res_crt) { + return false; + } // export our certificate data if (!openssl_pkey_export($res_key, $str_key) || - !openssl_x509_export($res_crt, $str_crt)) + !openssl_x509_export($res_crt, $str_crt)) { return false; + } // return our certificate information $cert['crt'] = base64_encode($str_crt); @@ -359,16 +407,21 @@ function csr_generate(& $cert, $keylen, $dn, $digest_alg = "sha256") { // generate a new key pair $res_key = openssl_pkey_new($args); - if(!$res_key) return false; + if (!$res_key) { + return false; + } // generate a certificate signing request $res_csr = openssl_csr_new($dn, $res_key, $args); - if(!$res_csr) return false; + if (!$res_csr) { + return false; + } // export our request data if (!openssl_pkey_export($res_key, $str_key) || - !openssl_csr_export($res_csr, $str_csr)) + !openssl_csr_export($res_csr, $str_csr)) { return false; + } // return our request information $cert['csr'] = base64_encode($str_csr); @@ -388,20 +441,23 @@ function csr_complete(& $cert, $str_crt) { function csr_get_subject($str_crt, $decode = true) { - if ($decode) + if ($decode) { $str_crt = base64_decode($str_crt); + } $components = openssl_csr_get_subject($str_crt); - if (empty($components) || !is_array($components)) + if (empty($components) || !is_array($components)) { return "unknown"; + } ksort($components); foreach ($components as $a => $v) { - if (!strlen($subject)) + if (!strlen($subject)) { $subject = "{$a}={$v}"; - else + } else { $subject = "{$a}={$v}, {$subject}"; + } } return $subject; @@ -409,14 +465,16 @@ function csr_get_subject($str_crt, $decode = true) { function cert_get_subject($str_crt, $decode = true) { - if ($decode) + if ($decode) { $str_crt = base64_decode($str_crt); + } $inf_crt = openssl_x509_parse($str_crt); $components = $inf_crt['subject']; - if (empty($components) || !is_array($components)) + if (empty($components) || !is_array($components)) { return "unknown"; + } ksort($components); foreach ($components as $a => $v) { @@ -440,13 +498,15 @@ function cert_get_subject_array($crt) { $inf_crt = openssl_x509_parse($str_crt); $components = $inf_crt['subject']; - if (!is_array($components)) + if (!is_array($components)) { return; + } $subject_array = array(); - foreach($components as $a => $v) + foreach ($components as $a => $v) { $subject_array[] = array('a' => $a, 'v' => $v); + } return $subject_array; } @@ -459,14 +519,16 @@ function cert_get_subject_hash($crt) { function cert_get_issuer($str_crt, $decode = true) { - if ($decode) + if ($decode) { $str_crt = base64_decode($str_crt); + } $inf_crt = openssl_x509_parse($str_crt); $components = $inf_crt['issuer']; - - if (empty($components) || !is_array($components)) + + if (empty($components) || !is_array($components)) { return "unknown"; + } ksort($components); foreach ($components as $a => $v) { @@ -486,24 +548,26 @@ function cert_get_issuer($str_crt, $decode = true) { } /* this function works on x509 (crt), rsa key (prv), and req(csr) */ -function cert_get_modulus($str_crt, $decode = true, $type = "crt"){ - if ($decode) +function cert_get_modulus($str_crt, $decode = true, $type = "crt") { + if ($decode) { $str_crt = base64_decode($str_crt); + } $modulus = ""; if ( in_array($type, array("crt", "prv", "csr")) ) { - $type = str_replace( array("crt","prv","csr"), array("x509","rsa","req"), $type); - $modulus = exec("echo \"{$str_crt}\" | openssl {$type} -noout -modulus"); + $type = str_replace( array("crt","prv","csr"), array("x509","rsa","req"), $type); + $modulus = exec("echo \"{$str_crt}\" | openssl {$type} -noout -modulus"); } return $modulus; } -function csr_get_modulus($str_crt, $decode = true){ +function csr_get_modulus($str_crt, $decode = true) { return cert_get_modulus($str_crt, $decode, "csr"); } function cert_get_purpose($str_crt, $decode = true) { - if ($decode) + if ($decode) { $str_crt = base64_decode($str_crt); + } $crt_details = openssl_x509_parse($str_crt); $purpose = array(); $purpose['ca'] = (stristr($crt_details['extensions']['basicConstraints'], 'CA:TRUE') === false) ? 'No': 'Yes'; @@ -512,40 +576,48 @@ function cert_get_purpose($str_crt, $decode = true) { } function cert_get_dates($str_crt, $decode = true) { - if ($decode) + if ($decode) { $str_crt = base64_decode($str_crt); + } $crt_details = openssl_x509_parse($str_crt); - if ($crt_details['validFrom_time_t'] > 0) + if ($crt_details['validFrom_time_t'] > 0) { $start = date('r', $crt_details['validFrom_time_t']); - if ($crt_details['validTo_time_t'] > 0) + } + if ($crt_details['validTo_time_t'] > 0) { $end = date('r', $crt_details['validTo_time_t']); + } return array($start, $end); } function cert_get_serial($str_crt, $decode = true) { - if ($decode) + if ($decode) { $str_crt = base64_decode($str_crt); + } $crt_details = openssl_x509_parse($str_crt); - if (isset($crt_details['serialNumber']) && !empty($crt_details['serialNumber'])) + if (isset($crt_details['serialNumber']) && !empty($crt_details['serialNumber'])) { return $crt_details['serialNumber']; - else + } else { return NULL; + } } -function prv_get_modulus($str_crt, $decode = true){ +function prv_get_modulus($str_crt, $decode = true) { return cert_get_modulus($str_crt, $decode, "prv"); } function is_user_cert($certref) { global $config; - if (!is_array($config['system']['user'])) + if (!is_array($config['system']['user'])) { return; + } foreach ($config['system']['user'] as $user) { - if (!is_array($user['cert'])) + if (!is_array($user['cert'])) { continue; + } foreach ($user['cert'] as $cert) { - if ($certref == $cert) + if ($certref == $cert) { return true; + } } } return false; @@ -553,33 +625,39 @@ function is_user_cert($certref) { function is_openvpn_server_cert($certref) { global $config; - if (!is_array($config['openvpn']['openvpn-server'])) + if (!is_array($config['openvpn']['openvpn-server'])) { return; + } foreach ($config['openvpn']['openvpn-server'] as $ovpns) { - if ($ovpns['certref'] == $certref) + if ($ovpns['certref'] == $certref) { return true; + } } return false; } function is_openvpn_client_cert($certref) { global $config; - if (!is_array($config['openvpn']['openvpn-client'])) + if (!is_array($config['openvpn']['openvpn-client'])) { return; + } foreach ($config['openvpn']['openvpn-client'] as $ovpnc) { - if ($ovpnc['certref'] == $certref) + if ($ovpnc['certref'] == $certref) { return true; + } } return false; } function is_ipsec_cert($certref) { global $config; - if (!is_array($config['ipsec']['phase1'])) + if (!is_array($config['ipsec']['phase1'])) { return; + } foreach ($config['ipsec']['phase1'] as $ipsec) { - if ($ipsec['certref'] == $certref) + if ($ipsec['certref'] == $certref) { return true; + } } return false; } @@ -587,17 +665,20 @@ function is_ipsec_cert($certref) { function is_webgui_cert($certref) { global $config; if (($config['system']['webgui']['ssl-certref'] == $certref) - && ($config['system']['webgui']['protocol'] != "http")) + && ($config['system']['webgui']['protocol'] != "http")) { return true; + } } function is_captiveportal_cert($certref) { global $config; - if (!is_array($config['captiveportal'])) + if (!is_array($config['captiveportal'])) { return; + } foreach ($config['captiveportal'] as $portal) { - if (isset($portal['enable']) && isset($portal['httpslogin']) && ($portal['certref'] == $certref)) + if (isset($portal['enable']) && isset($portal['httpslogin']) && ($portal['certref'] == $certref)) { return true; + } } return false; } @@ -614,8 +695,9 @@ function cert_in_use($certref) { function crl_create(& $crl, $caref, $name, $serial=0, $lifetime=9999) { global $config; $ca =& lookup_ca($caref); - if (!$ca) + if (!$ca) { return false; + } $crl['descr'] = $name; $crl['caref'] = $caref; $crl['serial'] = $serial; @@ -629,11 +711,13 @@ function crl_create(& $crl, $caref, $name, $serial=0, $lifetime=9999) { function crl_update(& $crl) { global $config; $ca =& lookup_ca($crl['caref']); - if (!$ca) + if (!$ca) { return false; + } // If we have text but no certs, it was imported and cannot be updated. - if (($crl["method"] != "internal") && (!empty($crl['text']) && empty($crl['cert']))) + if (($crl["method"] != "internal") && (!empty($crl['text']) && empty($crl['cert']))) { return false; + } $crl['serial']++; $ca_str_crt = base64_decode($ca['crt']); $ca_str_key = base64_decode($ca['prv']); @@ -650,11 +734,13 @@ function crl_update(& $crl) { function cert_revoke($cert, & $crl, $reason=OCSP_REVOKED_STATUS_UNSPECIFIED) { global $config; - if (is_cert_revoked($cert, $crl['refid'])) + if (is_cert_revoked($cert, $crl['refid'])) { return true; + } // If we have text but no certs, it was imported and cannot be updated. - if (!is_crl_internal($crl)) + if (!is_crl_internal($crl)) { return false; + } $cert["reason"] = $reason; $cert["revoke_time"] = time(); $crl["cert"][] = $cert; @@ -664,18 +750,21 @@ function cert_revoke($cert, & $crl, $reason=OCSP_REVOKED_STATUS_UNSPECIFIED) { function cert_unrevoke($cert, & $crl) { global $config; - if (!is_crl_internal($crl)) + if (!is_crl_internal($crl)) { return false; + } foreach ($crl['cert'] as $id => $rcert) { if (($rcert['refid'] == $cert['refid']) || ($rcert['descr'] == $cert['descr'])) { unset($crl['cert'][$id]); if (count($crl['cert']) == 0) { // Protect against accidentally switching the type to imported, for older CRLs - if (!isset($crl['method'])) + if (!isset($crl['method'])) { $crl['method'] = "internal"; + } crl_update($crl); - } else + } else { crl_update($crl); + } return true; } } @@ -693,31 +782,37 @@ function cert_compare($cert1, $cert2) { if ((cert_get_issuer($c1, false) == cert_get_issuer($c2, false)) && (cert_get_subject($c1, false) == cert_get_subject($c2, false)) && (cert_get_serial($c1, false) == cert_get_serial($c2, false)) - && (cert_get_modulus($c1, false) == cert_get_modulus($c2, false))) + && (cert_get_modulus($c1, false) == cert_get_modulus($c2, false))) { return true; + } return false; } function is_cert_revoked($cert, $crlref = "") { global $config; - if (!is_array($config['crl'])) + if (!is_array($config['crl'])) { return false; + } if (!empty($crlref)) { $crl = lookup_crl($crlref); - if (!is_array($crl['cert'])) + if (!is_array($crl['cert'])) { return false; + } foreach ($crl['cert'] as $rcert) { - if (cert_compare($rcert, $cert)) + if (cert_compare($rcert, $cert)) { return true; + } } } else { foreach ($config['crl'] as $crl) { - if (!is_array($crl['cert'])) + if (!is_array($crl['cert'])) { continue; + } foreach ($crl['cert'] as $rcert) { - if (cert_compare($rcert, $cert)) + if (cert_compare($rcert, $cert)) { return true; + } } } } @@ -726,11 +821,13 @@ function is_cert_revoked($cert, $crlref = "") { function is_openvpn_server_crl($crlref) { global $config; - if (!is_array($config['openvpn']['openvpn-server'])) + if (!is_array($config['openvpn']['openvpn-server'])) { return; + } foreach ($config['openvpn']['openvpn-server'] as $ovpns) { - if (!empty($ovpns['crlref']) && ($ovpns['crlref'] == $crlref)) + if (!empty($ovpns['crlref']) && ($ovpns['crlref'] == $crlref)) { return true; + } } return false; } @@ -749,8 +846,9 @@ function cert_get_cn($crt, $isref = false) { if ($isref) { $cert = lookup_cert($crt); /* If it's not a valid cert, bail. */ - if (!(is_array($cert) && !empty($cert['crt']))) + if (!(is_array($cert) && !empty($cert['crt']))) { return ""; + } $cert = $cert['crt']; } else { $cert = $crt; @@ -758,8 +856,9 @@ function cert_get_cn($crt, $isref = false) { $sub = cert_get_subject_array($cert); if (is_array($sub)) { foreach ($sub as $s) { - if (strtoupper($s['a']) == "CN") + if (strtoupper($s['a']) == "CN") { return $s['v']; + } } } return ""; diff --git a/etc/inc/config.console.inc b/etc/inc/config.console.inc index bd46e6c1dc..85fbc1085c 100644 --- a/etc/inc/config.console.inc +++ b/etc/inc/config.console.inc @@ -54,7 +54,7 @@ function set_networking_interfaces_ports() { $physmem = $memory[0]; $realmem = $memory[1]; - if($physmem < $g['minimum_ram_warning']) { + if ($physmem < $g['minimum_ram_warning']) { echo "\n\n\n"; echo gettext("DANGER! WARNING! ACHTUNG!") . "\n\n"; printf(gettext("%s requires *AT LEAST* %s RAM to function correctly.%s"), $g['product_name'], $g['minimum_ram_warning_text'], "\n"); @@ -66,12 +66,13 @@ function set_networking_interfaces_ports() { $iflist = get_interface_list(); -/* Function flow is based on $key and $auto_assign or the lack thereof */ + /* Function flow is based on $key and $auto_assign or the lack thereof */ $key = null; -/* Only present auto interface option if running from LiveCD and interface mismatch*/ - if ((preg_match("/cdrom/", $g['platform'])) && is_interface_mismatch()) + /* Only present auto interface option if running from LiveCD and interface mismatch*/ + if ((preg_match("/cdrom/", $g['platform'])) && is_interface_mismatch()) { $auto_assign = false; + } echo << $ifa) { - if ($ifa['up']) + if ($ifa['up']) { $plugged_in[] = $iface; - + } } $lanif = array_shift($plugged_in); $wanif = array_shift($plugged_in); - if(isset($lanif) && !isset($wanif)) { + if (isset($lanif) && !isset($wanif)) { foreach ($iflist as $iface => $ifa) { if ($iface != $lanif) { $wanif = $iface; @@ -158,110 +159,115 @@ EOD; echo << "") { + + if ($lanif <> "") { while (1) { - if ($optif[$i]) + if ($optif[$i]) { $i++; + } $io = $i + 1; - if($config['interfaces']['opt' . $io]['descr']) + if ($config['interfaces']['opt' . $io]['descr']) { printf(gettext("%sOptional interface %s description found: %s"), "\n", $io, $config['interfaces']['opt' . $io]['descr']); - + } + printf(gettext("%sEnter the Optional %s interface name or 'a' for auto-detection%s" . "(or nothing if finished):%s"), "\n", $io, "\n", " "); - + $optif[$i] = chop(fgets($fp)); - + if ($optif[$i]) { if ($optif[$i] === "a") { $ad = autodetect_interface(gettext("Optional") . " " . $io, $fp); - if ($ad) + if ($ad) { $optif[$i] = $ad; - else + } else { unset($optif[$i]); + } } else if (!array_key_exists($optif[$i], $iflist)) { printf(gettext("%sInvalid interface name '%s'%s"), "\n", $optif[$i], "\n"); unset($optif[$i]); @@ -273,44 +279,46 @@ EOD; } } } - + /* check for double assignments */ $ifarr = array_merge(array($lanif, $wanif), $optif); - + for ($i = 0; $i < (count($ifarr)-1); $i++) { for ($j = ($i+1); $j < count($ifarr); $j++) { if ($ifarr[$i] == $ifarr[$j]) { echo << " . $wanif . "\n"; - if ($lanif != "") + if ($lanif != "") { echo "LAN -> " . $lanif . "\n"; + } for ($i = 0; $i < count($optif); $i++) { echo "OPT" . ($i+1) . " -> " . $optif[$i] . "\n"; } - + echo <<") == true) { + if (stristr($config_contents, "") == true) { echo "."; - /* user has just upgraded to m0n0wall, replace root xml tags */ + /* user has just upgraded from m0n0wall, replace root xml tags */ log_error(gettext("Upgrading m0n0wall configuration to pfSense... ")); $config_contents = str_replace("m0n0wall","pfsense", $config_contents); - if (!config_validate("{$g['conf_path']}/config.xml")) + if (!config_validate("{$g['conf_path']}/config.xml")) { log_error(gettext("ERROR! Could not convert m0n0wall -> pfsense in config.xml")); + } conf_mount_rw(); file_put_contents("/cf/conf/config.xml", $config_contents); conf_mount_ro(); @@ -116,7 +121,7 @@ if(platform_booting(true)) { /* config is on floppy disk for CD-ROM version */ $cfgdevice = $cfgpartition = "fd0"; $_gb = exec('/sbin/dmesg -a', $dmesg); - if(preg_match("/da0/", $dmesg) == true) { + if (preg_match("/da0/", $dmesg) == true) { $cfgdevice = $cfgpartition = "da0" ; if (mwexec("/sbin/mount -r /dev/{$cfgdevice} /cf")) { /* could not mount, fallback to floppy */ @@ -135,8 +140,9 @@ if(platform_booting(true)) { $disks = explode(" ", get_single_sysctl("kern.disks")); foreach ($disks as $mountdisk) { /* skip mfs mounted filesystems */ - if (strstr($mountdisk, "md")) + if (strstr($mountdisk, "md")) { continue; + } if (mwexec("/sbin/mount -r /dev/{$mountdisk}a {$g['cf_path']}") == 0) { if (file_exists("{$g['cf_conf_path']}/config.xml")) { /* found it */ @@ -148,11 +154,14 @@ if(platform_booting(true)) { mwexec("/sbin/umount -f {$g['cf_path']}"); - if ($cfgdevice) + if ($cfgdevice) { break; + } } if (mwexec("/sbin/mount -r /dev/{$mountdisk}d {$g['cf_path']}") == 0) { - if(platform_booting()) echo "."; + if (platform_booting()) { + echo "."; + } if (file_exists("{$g['cf_conf_path']}/config.xml")) { /* found it */ $cfgdevice = $mountdisk; @@ -163,15 +172,16 @@ if(platform_booting(true)) { mwexec("/sbin/umount -f {$g['cf_path']}"); - if ($cfgdevice) + if ($cfgdevice) { break; + } } } } echo "."; if (!$cfgdevice) { $last_backup = discover_last_backup(); - if($last_backup) { + if ($last_backup) { log_error(gettext("No config.xml found, attempting last known config restore.")); file_notice("config.xml", gettext("No config.xml found, attempting last known config restore."), "pfSenseConfigurator", ""); restore_backup("/cf/conf/backup/{$last_backup}"); @@ -201,13 +211,14 @@ $config = parse_config(); /* set timezone */ $timezone = $config['system']['timezone']; -if (!$timezone) +if (!$timezone) { $timezone = "Etc/UTC"; +} date_default_timezone_set("$timezone"); -if($config_parsed == true) { +if ($config_parsed == true) { /* process packager manager custom rules */ - if(is_dir("/usr/local/pkg/parse_config")) { + if (is_dir("/usr/local/pkg/parse_config")) { run_plugins("/usr/local/pkg/parse_config/"); } } diff --git a/etc/inc/config.lib.inc b/etc/inc/config.lib.inc index aede42d3d1..922f774f32 100644 --- a/etc/inc/config.lib.inc +++ b/etc/inc/config.lib.inc @@ -54,24 +54,27 @@ function encrypted_configxml() { global $g, $config; - if (!file_exists($g['conf_path'] . "/config.xml")) + if (!file_exists($g['conf_path'] . "/config.xml")) { return; + } - if (!platform_booting()) + if (!platform_booting()) { return; + } - $configtxt = file_get_contents($g['conf_path'] . "/config.xml"); - if(tagfile_deformat($configtxt, $configtxt, "config.xml")) { + $configtxt = file_get_contents($g['conf_path'] . "/config.xml"); + if (tagfile_deformat($configtxt, $configtxt, "config.xml")) { $fp = fopen('php://stdin', 'r'); $data = ""; echo "\n\n*** Encrypted config.xml detected ***\n"; - while($data == "") { + while ($data == "") { echo "\nEnter the password to decrypt config.xml: "; $decrypt_password = chop(fgets($fp)); $data = decrypt_data($configtxt, $decrypt_password); - if(!strstr($data, "")) + if (!strstr($data, "")) { $data = ""; - if($data) { + } + if ($data) { $fd = fopen($g['conf_path'] . "/config.xml.tmp", "w"); fwrite($fd, $data); fclose($fd); @@ -101,7 +104,7 @@ function parse_config($parse = false) { if (!file_exists("{$g['conf_path']}/config.xml") || filesize("{$g['conf_path']}/config.xml") == 0) { $last_backup = discover_last_backup(); - if($last_backup) { + if ($last_backup) { log_error(gettext("No config.xml found, attempting last known config restore.")); file_notice("config.xml", gettext("No config.xml found, attempting last known config restore."), "pfSenseConfigurator", ""); restore_backup("{$g['conf_path']}/backup/{$last_backup}"); @@ -117,35 +120,38 @@ function parse_config($parse = false) { // Check for encrypted config.xml encrypted_configxml(); - if(!$parse) { + if (!$parse) { if (file_exists($g['tmp_path'] . '/config.cache')) { $config = unserialize(file_get_contents($g['tmp_path'] . '/config.cache')); - if (is_null($config)) + if (is_null($config)) { $parse = true; - } else + } + } else { $parse = true; + } } if ($parse == true) { - if(!file_exists($g['conf_path'] . "/config.xml")) { - if (platform_booting(true)) + if (!file_exists($g['conf_path'] . "/config.xml")) { + if (platform_booting(true)) { echo "."; + } log_error("No config.xml found, attempting last known config restore."); file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", ""); $last_backup = discover_last_backup(); - if ($last_backup) + if ($last_backup) { restore_backup("/cf/conf/backup/{$last_backup}"); - else { + } else { log_error(gettext("Could not restore config.xml.")); unlock($lockkey); die(gettext("Config.xml is corrupted and is 0 bytes. Could not restore a previous backup.")); } } $config = parse_xml_config($g['conf_path'] . '/config.xml', array($g['xml_rootobj'], 'pfsense')); - if($config == -1) { + if ($config == -1) { $last_backup = discover_last_backup(); - if ($last_backup) + if ($last_backup) { restore_backup("/cf/conf/backup/{$last_backup}"); - else { + } else { log_error(gettext("Could not restore config.xml.")); unlock($lockkey); die("Config.xml is corrupted and is 0 bytes. Could not restore a previous backup."); @@ -154,8 +160,9 @@ function parse_config($parse = false) { generate_config_cache($config); } - if (platform_booting(true)) + if (platform_booting(true)) { echo "."; + } $config_parsed = true; unlock($lockkey); @@ -181,10 +188,10 @@ function generate_config_cache($config) { fclose($configcache); unset($configcache); /* Used for config.extra.xml */ - if(file_exists($g['tmp_path'] . '/config.extra.cache') && $config_extra) { + if (file_exists($g['tmp_path'] . '/config.extra.cache') && $config_extra) { $configcacheextra = fopen($g['tmp_path'] . '/config.extra.cache', "w"); fwrite($configcacheextra, serialize($config_extra)); - fclose($configcacheextra); + fclose($configcacheextra); unset($configcacheextra); } } @@ -193,8 +200,8 @@ function discover_last_backup() { $backups = glob('/cf/conf/backup/*.xml'); $last_backup = ""; $last_mtime = 0; - foreach($backups as $backup) { - if(filemtime($backup) > $last_mtime) { + foreach ($backups as $backup) { + if (filemtime($backup) > $last_mtime) { $last_mtime = filemtime($backup); $last_backup = $backup; } @@ -226,8 +233,9 @@ function restore_backup($file) { function parse_config_bootup() { global $config, $g; - if (platform_booting()) + if (platform_booting()) { echo "."; + } $lockkey = lock('config'); if (!file_exists("{$g['conf_path']}/config.xml")) { @@ -244,12 +252,12 @@ function parse_config_bootup() { } } else { $last_backup = discover_last_backup(); - if($last_backup) { + if ($last_backup) { log_error("No config.xml found, attempting last known config restore."); file_notice("config.xml", gettext("No config.xml found, attempting last known config restore."), "pfSenseConfigurator", ""); restore_backup("/cf/conf/backup/{$last_backup}"); } - if(!file_exists("{$g['conf_path']}/config.xml")) { + if (!file_exists("{$g['conf_path']}/config.xml")) { echo sprintf(gettext("XML configuration file not found. %s cannot continue booting."), $g['product_name']) . "\n"; unlock($lockkey); mwexec("/sbin/halt"); @@ -267,7 +275,7 @@ function parse_config_bootup() { if (filesize("{$g['conf_path']}/config.xml") == 0) { $last_backup = discover_last_backup(); - if($last_backup) { + if ($last_backup) { log_error(gettext("No config.xml found, attempting last known config restore.")); file_notice("config.xml", gettext("No config.xml found, attempting last known config restore."), "pfSenseConfigurator", ""); restore_backup("{$g['conf_path']}/backup/{$last_backup}"); @@ -311,31 +319,34 @@ function conf_mount_rw() { global $g, $config; /* do not mount on cdrom platform */ - if($g['platform'] == "cdrom" or $g['platform'] == "pfSense") + if ($g['platform'] == "cdrom" or $g['platform'] == "pfSense") { return; + } - if ((refcount_reference(1000) > 1) && is_writable("/")) + if ((refcount_reference(1000) > 1) && is_writable("/")) { return; + } $status = mwexec("/sbin/mount -u -w -o sync,noatime {$g['cf_path']}"); - if($status <> 0) { - if (platform_booting()) + if ($status <> 0) { + if (platform_booting()) { echo gettext("Disk is dirty. Running fsck -y") . "\n"; + } mwexec("/sbin/fsck -y {$g['cf_path']}"); $status = mwexec("/sbin/mount -u -w -o sync,noatime {$g['cf_path']}"); } /* if the platform is soekris or wrap or pfSense, lets mount the * compact flash cards root. - */ + */ $status = mwexec("/sbin/mount -u -w -o sync,noatime /"); /* we could not mount this correctly. kick off fsck */ - if($status <> 0) { + if ($status <> 0) { log_error(gettext("File system is dirty. Launching FSCK for /")); mwexec("/sbin/fsck -y /"); $status = mwexec("/sbin/mount -u -w -o sync,noatime /"); } - + mark_subsystem_dirty('mount'); } @@ -351,17 +362,21 @@ function conf_mount_ro() { /* Do not trust $g['platform'] since this can be clobbered during factory reset. */ $platform = trim(file_get_contents("/etc/platform")); /* do not umount on cdrom or pfSense platforms */ - if($platform == "cdrom" or $platform == "pfSense") + if ($platform == "cdrom" or $platform == "pfSense") { return; + } - if (refcount_unreference(1000) > 0) + if (refcount_unreference(1000) > 0) { return; + } - if(isset($config['system']['nanobsd_force_rw'])) + if (isset($config['system']['nanobsd_force_rw'])) { return; + } - if (platform_booting()) + if (platform_booting()) { return; + } clear_subsystem_dirty('mount'); /* sync data, then force a remount of /cf */ @@ -393,45 +408,51 @@ function convert_config() { if (is_array($config['cron'])) { $cron_item_count = count($config['cron']['item']); for($x=0; $x<$cron_item_count; $x++) { - if(stristr($config['cron']['item'][$x]['command'], "rc.update_bogons.sh")) { - if($config['cron']['item'][$x]['hour'] == "*" ) { - $config['cron']['item'][$x]['hour'] = "3"; + if (stristr($config['cron']['item'][$x]['command'], "rc.update_bogons.sh")) { + if ($config['cron']['item'][$x]['hour'] == "*" ) { + $config['cron']['item'][$x]['hour'] = "3"; write_config(gettext("Updated bogon update frequency to 3am")); log_error(gettext("Updated bogon update frequency to 3am")); - } + } } } } - if ($config['version'] == $g['latest_config']) + if ($config['version'] == $g['latest_config']) { return; /* already at latest version */ + } // Save off config version $prev_version = $config['version']; - + include_once('auth.inc'); include_once('upgrade_config.inc'); - if (file_exists("/etc/inc/upgrade_config_custom.inc")) + if (file_exists("/etc/inc/upgrade_config_custom.inc")) { include_once("upgrade_config_custom.inc"); + } /* Loop and run upgrade_VER_to_VER() until we're at current version */ while ($config['version'] < $g['latest_config']) { $cur = $config['version'] * 10; $next = $cur + 1; $migration_function = sprintf('upgrade_%03d_to_%03d', $cur, $next); - if (function_exists($migration_function)) + if (function_exists($migration_function)) { $migration_function(); + } $migration_function = "{$migration_function}_custom"; - if (function_exists($migration_function)) + if (function_exists($migration_function)) { $migration_function(); + } $config['version'] = sprintf('%.1f', $next / 10); - if (platform_booting()) + if (platform_booting()) { echo "."; + } } $now = date("H:i:s"); log_error(sprintf(gettext("Ended Configuration upgrade at %s"), $now)); - if ($prev_version != $config['version']) + if ($prev_version != $config['version']) { write_config(sprintf(gettext('Upgraded config version level from %1$s to %2$s'), $prev_version, $config['version'])); + } } /****f* config/safe_write_file @@ -457,7 +478,7 @@ function safe_write_file($file, $content, $force_binary) { if (!$fd) { // Unable to open temporary file for writing return false; - } + } if (!fwrite($fd, $content)) { // Unable to write to temporary file fclose($fd); @@ -495,8 +516,9 @@ function write_config($desc="Unknown", $backup = true) { global $config, $g; if (!empty($_SERVER['REMOTE_ADDR'])) { - if (!session_id()) + if (!session_id()) { @session_start(); + } if (!empty($_SESSION['Username']) && ($_SESSION['Username'] != "admin")) { $user = getUserEntry($_SESSION['Username']); if (is_array($user) && userHasPrivilege($user, "user-config-readonly")) { @@ -506,11 +528,13 @@ function write_config($desc="Unknown", $backup = true) { } } - if (!isset($argc)) + if (!isset($argc)) { session_commit(); + } - if($backup) + if ($backup) { backup_config(); + } $config['revision'] = make_config_revision_entry($desc); @@ -527,7 +551,7 @@ function write_config($desc="Unknown", $backup = true) { file_notice("config.xml", sprintf(gettext("Unable to open %s/config.xml for writing in write_config()%s"), $g['cf_conf_path'], "\n")); return -1; } - + cleanup_backupcache(true); /* re-read configuration */ @@ -544,10 +568,12 @@ function write_config($desc="Unknown", $backup = true) { echo "\n\n Configuration could not be validated. A previous configuration was restored. \n"; echo "\n The failed configuration file has been saved as {$g['conf_path']}/config.xml.bad \n\n"; } - } else + } else { log_error(gettext("Could not restore config.xml.")); - } else + } + } else { generate_config_cache($config); + } unlock($lockkey); @@ -559,7 +585,7 @@ function write_config($desc="Unknown", $backup = true) { /* sync carp entries to other firewalls */ carp_sync_client(); - if(is_dir("/usr/local/pkg/write_config")) { + if (is_dir("/usr/local/pkg/write_config")) { /* process packager manager custom rules */ run_plugins("/usr/local/pkg/write_config/"); } @@ -577,8 +603,9 @@ function reset_factory_defaults($lock = false) { global $g; conf_mount_rw(); - if (!$lock) + if (!$lock) { $lockkey = lock('config', LOCK_EX); + } /* create conf directory, if necessary */ safe_mkdir("{$g['cf_conf_path']}"); @@ -600,8 +627,9 @@ function reset_factory_defaults($lock = false) { /* call the wizard */ touch("/conf/trigger_initial_wizard"); - if (!$lock) + if (!$lock) { unlock($lockkey); + } conf_mount_ro(); setup_serial_port(); return 0; @@ -610,13 +638,14 @@ function reset_factory_defaults($lock = false) { function config_restore($conffile) { global $config, $g; - if (!file_exists($conffile)) + if (!file_exists($conffile)) { return 1; + } backup_config(); conf_mount_rw(); - + $lockkey = lock('config', LOCK_EX); unlink_if_exists("{$g['tmp_path']}/config.cache"); @@ -638,16 +667,19 @@ function config_restore($conffile) { function config_install($conffile) { global $config, $g; - if (!file_exists($conffile)) + if (!file_exists($conffile)) { return 1; + } - if (!config_validate("{$conffile}")) + if (!config_validate("{$conffile}")) { return 1; + } - if (platform_booting()) + if (platform_booting()) { echo gettext("Installing configuration...") . "\n"; - else + } else { log_error(gettext("Installing configuration ....")); + } conf_mount_rw(); $lockkey = lock('config', LOCK_EX); @@ -657,13 +689,14 @@ function config_install($conffile) { disable_security_checks(); /* unlink cache file if it exists */ - if(file_exists("{$g['tmp_path']}/config.cache")) + if (file_exists("{$g['tmp_path']}/config.cache")) { unlink("{$g['tmp_path']}/config.cache"); + } unlock($lockkey); conf_mount_ro(); - return 0; + return 0; } /* @@ -723,8 +756,9 @@ function cleanup_backupcache($lock = false) { $revisions = get_config_backup_count(); - if (!$lock) + if (!$lock) { $lockkey = lock('config'); + } conf_mount_rw(); @@ -740,9 +774,9 @@ function cleanup_backupcache($lock = false) { $bakfiles = glob($g['cf_conf_path'] . "/backup/config-*"); $tocache = array(); - foreach($bakfiles as $backup) { // Check for backups in the directory not represented in the cache. + foreach ($bakfiles as $backup) { // Check for backups in the directory not represented in the cache. $backupsize = filesize($backup); - if($backupsize == 0) { + if ($backupsize == 0) { unlink($backup); continue; } @@ -750,39 +784,45 @@ function cleanup_backupcache($lock = false) { $backupexp = explode('.', array_pop($backupexp)); $tocheck = array_shift($backupexp); unset($backupexp); - if(!in_array($tocheck, $baktimes)) { + if (!in_array($tocheck, $baktimes)) { $i = true; - if (platform_booting()) + if (platform_booting()) { echo "."; + } $newxml = parse_xml_config($backup, array($g['xml_rootobj'], 'pfsense')); - if($newxml == "-1") { + if ($newxml == "-1") { log_error(sprintf(gettext("The backup cache file %s is corrupted. Unlinking."), $backup)); unlink($backup); log_error(sprintf(gettext("The backup cache file %s is corrupted. Unlinking."), $backup)); continue; } - if($newxml['revision']['description'] == "") + if ($newxml['revision']['description'] == "") { $newxml['revision']['description'] = "Unknown"; - if($newxml['version'] == "") + } + if ($newxml['version'] == "") { $newxml['version'] = "?"; + } $tocache[$tocheck] = array('description' => $newxml['revision']['description'], 'version' => $newxml['version'], 'filesize' => $backupsize); } } - foreach($backups as $checkbak) { - if(count(preg_grep('/' . $checkbak['time'] . '/i', $bakfiles)) != 0) { + foreach ($backups as $checkbak) { + if (count(preg_grep('/' . $checkbak['time'] . '/i', $bakfiles)) != 0) { $newbaks[] = $checkbak; } else { $i = true; if (platform_booting()) print " " . $tocheck . "r"; } } - foreach($newbaks as $todo) $tocache[$todo['time']] = array('description' => $todo['description'], 'version' => $todo['version'], 'filesize' => $todo['filesize']); - if(is_int($revisions) and (count($tocache) > $revisions)) { + foreach ($newbaks as $todo) { + $tocache[$todo['time']] = array('description' => $todo['description'], 'version' => $todo['version'], 'filesize' => $todo['filesize']); + } + if (is_int($revisions) and (count($tocache) > $revisions)) { $toslice = array_slice(array_keys($tocache), 0, $revisions); - foreach($toslice as $sliced) + foreach ($toslice as $sliced) { $newcache[$sliced] = $tocache[$sliced]; - foreach($tocache as $version => $versioninfo) { - if(!in_array($version, array_keys($newcache))) { + } + foreach ($tocache as $version => $versioninfo) { + if (!in_array($version, array_keys($newcache))) { unlink_if_exists($g['conf_path'] . '/backup/config-' . $version . '.xml'); } } @@ -793,20 +833,22 @@ function cleanup_backupcache($lock = false) { fclose($bakout); conf_mount_ro(); - if (!$lock) + if (!$lock) { unlock($lockkey); + } } function get_backups() { global $g; - if(file_exists("{$g['cf_conf_path']}/backup/backup.cache")) { + if (file_exists("{$g['cf_conf_path']}/backup/backup.cache")) { $confvers = unserialize(file_get_contents("{$g['cf_conf_path']}/backup/backup.cache")); $bakvers = array_keys($confvers); $toreturn = array(); sort($bakvers); // $bakvers = array_reverse($bakvers); - foreach(array_reverse($bakvers) as $bakver) + foreach (array_reverse($bakvers) as $bakver) { $toreturn[] = array('time' => $bakver, 'description' => $confvers[$bakver]['description'], 'version' => $confvers[$bakver]['version'], 'filesize' => $confvers[$bakver]['filesize']); + } } else { return false; } @@ -817,37 +859,38 @@ function get_backups() { function backup_config() { global $config, $g; - if($g['platform'] == "cdrom") + if ($g['platform'] == "cdrom") { return; + } conf_mount_rw(); /* Create backup directory if needed */ safe_mkdir("{$g['cf_conf_path']}/backup"); - if($config['revision']['time'] == "") { - $baktime = 0; - } else { - $baktime = $config['revision']['time']; - } - if($config['revision']['description'] == "") { - $bakdesc = "Unknown"; - } else { - $bakdesc = $config['revision']['description']; - } + if ($config['revision']['time'] == "") { + $baktime = 0; + } else { + $baktime = $config['revision']['time']; + } + if ($config['revision']['description'] == "") { + $bakdesc = "Unknown"; + } else { + $bakdesc = $config['revision']['description']; + } $bakver = ($config['version'] == "") ? "?" : $config['version']; $bakfilename = $g['cf_conf_path'] . '/backup/config-' . $baktime . '.xml'; copy($g['cf_conf_path'] . '/config.xml', $bakfilename); - if(file_exists($g['cf_conf_path'] . '/backup/backup.cache')) { - $backupcache = unserialize(file_get_contents($g['cf_conf_path'] . '/backup/backup.cache')); - } else { - $backupcache = array(); - } + if (file_exists($g['cf_conf_path'] . '/backup/backup.cache')) { + $backupcache = unserialize(file_get_contents($g['cf_conf_path'] . '/backup/backup.cache')); + } else { + $backupcache = array(); + } $backupcache[$baktime] = array('description' => $bakdesc, 'version' => $bakver, 'filesize' => filesize($bakfilename)); - $bakout = fopen($g['cf_conf_path'] . '/backup/backup.cache', "w"); - fwrite($bakout, serialize($backupcache)); - fclose($bakout); + $bakout = fopen($g['cf_conf_path'] . '/backup/backup.cache', "w"); + fwrite($bakout, serialize($backupcache)); + fclose($bakout); conf_mount_ro(); @@ -874,33 +917,40 @@ function set_device_perms() { function get_config_user() { if (empty($_SESSION["Username"])) { $username = getenv("USER"); - if (empty($conuser) || $conuser == "root") + if (empty($conuser) || $conuser == "root") { $username = "(system)"; - } else + } + } else { $username = $_SESSION["Username"]; + } - if (!empty($_SERVER['REMOTE_ADDR'])) + if (!empty($_SERVER['REMOTE_ADDR'])) { $username .= '@' . $_SERVER['REMOTE_ADDR']; + } return $username; } function make_config_revision_entry($desc = null, $override_user = null) { - if (empty($override_user)) + if (empty($override_user)) { $username = get_config_user(); - else + } else { $username = $override_user; + } $revision = array(); - if (time() > mktime(0, 0, 0, 9, 1, 2004)) /* make sure the clock settings are plausible */ + if (time() > mktime(0, 0, 0, 9, 1, 2004)) { /* make sure the clock settings are plausible */ $revision['time'] = time(); + } /* Log the running script so it's not entirely unlogged what changed */ - if ($desc == "Unknown") + if ($desc == "Unknown") { $desc = sprintf(gettext("%s made unknown change"), $_SERVER['SCRIPT_NAME']); - if (!empty($desc)) + } + if (!empty($desc)) { $revision['description'] = "{$username}: " . $desc; + } $revision['username'] = $username; return $revision; } @@ -920,9 +970,9 @@ function pfSense_clear_globals() { global $config, $FilterIfList, $GatewaysList, $filterdns, $aliases, $aliastable; $error = error_get_last(); - - if ( $error !== NULL) { - if ( $error['type'] != E_NOTICE ) { + + if ($error !== NULL) { + if ($error['type'] != E_NOTICE) { $errorstr = "PHP ERROR: Type: {$error['type']}, File: {$error['file']}, Line: {$error['line']}, Message: {$error['message']}"; // XXX: comment out for now, should re-enable post-2.2 //print($errorstr); @@ -930,21 +980,26 @@ function pfSense_clear_globals() { } } - if (isset($FilterIfList)) + if (isset($FilterIfList)) { unset($FilterIfList); + } - if (isset($GatewaysList)) + if (isset($GatewaysList)) { unset($GatewaysList); + } /* Used for the hostname dns resolver */ - if (isset($filterdns)) + if (isset($filterdns)) { unset($filterdns); + } /* Used for aliases and interface macros */ - if (isset($aliases)) + if (isset($aliases)) { unset($aliases); - if (isset($aliastable)) + } + if (isset($aliastable)) { unset($aliastable); + } unset($config); } diff --git a/etc/inc/crypt.inc b/etc/inc/crypt.inc index 225d3b0ace..8d96b266d9 100644 --- a/etc/inc/crypt.inc +++ b/etc/inc/crypt.inc @@ -2,29 +2,29 @@ /* $Id$ */ /* - Copyright (C) 2008 Shrew Soft Inc - All rights reserved. + Copyright (C) 2008 Shrew Soft Inc + All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. pfSense_BUILDER_BINARIES: /usr/bin/openssl pfSense_MODULE: crypto @@ -35,9 +35,9 @@ $file = tempnam("/tmp", "php-encrypt"); file_put_contents("{$file}.dec", $val); exec("/usr/bin/openssl enc {$opt} -aes-256-cbc -in {$file}.dec -out {$file}.enc -k " . escapeshellarg($pass)); - if (file_exists("{$file}.enc")) + if (file_exists("{$file}.enc")) { $result = file_get_contents("{$file}.enc"); - else { + } else { $result = ""; log_error("Failed to encrypt/decrypt data!"); } @@ -84,8 +84,9 @@ $btag_pos = stripos($in, $btag_val); $etag_pos = stripos($in, $etag_val); - if (($btag_pos === false) || ($etag_pos === false)) + if (($btag_pos === false) || ($etag_pos === false)) { return false; + } $body_pos = $btag_pos + $btag_len; $body_len = strlen($in); diff --git a/etc/inc/dyndns.class b/etc/inc/dyndns.class index 9f54403bc3..8576b9c234 100644 --- a/etc/inc/dyndns.class +++ b/etc/inc/dyndns.class @@ -27,8 +27,8 @@ * - Custom DDNS (any URL) * - Custom DDNS IPv6 (any URL) * - CloudFlare (www.cloudflare.com) - * - Eurodns (eurodns.com) - * - GratisDNS (gratisdns.dk) + * - Eurodns (eurodns.com) + * - GratisDNS (gratisdns.dk) * - City Network (citynetwork.se) * - GleSYS (glesys.com) * - DNSimple (dnsimple.com) @@ -68,14 +68,14 @@ * HE.net Tunnel - Last Tested: 28 June 2011 * SelfHost - Last Tested: 26 December 2011 * Amazon Route 53 - Last tested: 01 April 2012 - * DNS-O-Matic - Last Tested: 9 September 2010 - * CloudFlare - Last Tested: 30 May 2013 - * Eurodns - Last Tested: 27 June 2013 - * GratisDNS - Last Tested: 15 August 2012 - * OVH DynHOST - Last Tested: NEVER - * City Network - Last Tested: 13 November 2013 - * GleSYS - Last Tested: 3 February 2015 - * DNSimple - Last Tested: 09 February 2015 + * DNS-O-Matic - Last Tested: 9 September 2010 + * CloudFlare - Last Tested: 30 May 2013 + * Eurodns - Last Tested: 27 June 2013 + * GratisDNS - Last Tested: 15 August 2012 + * OVH DynHOST - Last Tested: NEVER + * City Network - Last Tested: 13 November 2013 + * GleSYS - Last Tested: 3 February 2015 + * DNSimple - Last Tested: 09 February 2015 * +====================================================+ * * @author E.Kristensen @@ -120,24 +120,24 @@ var $_dnsDummyUpdateDone; var $_forceUpdateNeeded; var $_useIPv6; - - /* + + /* * Public Constructor Function (added 12 July 05) [beta] - * - Gets the dice rolling for the update. + * - Gets the dice rolling for the update. * - $dnsResultMatch should only be used with $dnsService = 'custom' - * - $dnsResultMatch is parsed for '%IP%', which is the IP the provider was updated to, + * - $dnsResultMatch is parsed for '%IP%', which is the IP the provider was updated to, * - it is otherwise expected to be exactly identical to what is returned by the Provider. * - $dnsUser, and $dnsPass indicate HTTP Auth for custom DNS, if they are needed in the URL (GET Variables), include them in $dnsUpdateURL. * - $For custom requests, $dnsUpdateURL is parsed for '%IP%', which is replaced with the new IP. */ function updatedns ($dnsService = '', $dnsHost = '', $dnsUser = '', $dnsPass = '', - $dnsWildcard = 'OFF', $dnsMX = '', $dnsIf = '', $dnsBackMX = '', - $dnsServer = '', $dnsPort = '', $dnsUpdateURL = '', $forceUpdate = false, - $dnsZoneID ='', $dnsTTL='', $dnsResultMatch = '', $dnsRequestIf = '', - $dnsID = '', $dnsVerboseLog = false, $curlIpresolveV4 = false, $curlSslVerifypeer = true) { - + $dnsWildcard = 'OFF', $dnsMX = '', $dnsIf = '', $dnsBackMX = '', + $dnsServer = '', $dnsPort = '', $dnsUpdateURL = '', $forceUpdate = false, + $dnsZoneID ='', $dnsTTL='', $dnsResultMatch = '', $dnsRequestIf = '', + $dnsID = '', $dnsVerboseLog = false, $curlIpresolveV4 = false, $curlSslVerifypeer = true) { + global $config, $g; - + $this->_cacheFile = "{$g['conf_path']}/dyndns_{$dnsIf}{$dnsService}" . escapeshellarg($dnsHost) . "{$dnsID}.cache"; $this->_cacheFile_v6 = "{$g['conf_path']}/dyndns_{$dnsIf}{$dnsService}" . escapeshellarg($dnsHost) . "{$dnsID}_v6.cache"; $this->_debugFile = "{$g['varetc_path']}/dyndns_{$dnsIf}{$dnsService}" . escapeshellarg($dnsHost) . "{$dnsID}.debug"; @@ -145,8 +145,9 @@ $this->_curlIpresolveV4 = $curlIpresolveV4; $this->_curlSslVerifypeer = $curlSslVerifypeer; $this->_dnsVerboseLog = $dnsVerboseLog; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("DynDns: updatedns() starting"); + } $dyndnslck = lock("DDNS".$dnsID, LOCK_EX); @@ -171,14 +172,14 @@ if (!$dnsPass) $this->_error(4); if (!$dnsHost) $this->_error(5); } - + switch ($dnsService) { - case 'he-net-v6': - case 'custom-v6': - $this->_useIPv6 = true; - break; - default: - $this->_useIPv6 = false; + case 'he-net-v6': + case 'custom-v6': + $this->_useIPv6 = true; + break; + default: + $this->_useIPv6 = false; } $this->_dnsService = strtolower($dnsService); $this->_dnsUser = $dnsUser; @@ -195,86 +196,88 @@ $this->_dnsUpdateURL = $dnsUpdateURL; $this->_dnsResultMatch = $dnsResultMatch; $this->_dnsRequestIf = get_failover_interface($dnsRequestIf); - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("DynDNS ({$this->_dnsHost}): running get_failover_interface for {$dnsRequestIf}. found {$this->_dnsRequestIf}"); + } $this->_dnsRequestIfIP = get_interface_ip($dnsRequestIf); $this->_dnsMaxCacheAgeDays = 25; $this->_dnsDummyUpdateDone = false; $this->_forceUpdateNeeded = $forceUpdate; - + // Ensure that we were able to lookup the IP - if(!is_ipaddr($this->_dnsIP)) { + if (!is_ipaddr($this->_dnsIP)) { log_error("DynDNS ({$this->_dnsHost}) There was an error trying to determine the public IP for interface - {$dnsIf}({$this->_if}). Probably interface is not a WAN interface."); unlock($dyndnslck); return; } $this->_debugID = rand(1000000, 9999999); - + if ($forceUpdate == false && $this->_detectChange() == false) { $this->_error(10); } else { switch ($this->_dnsService) { - case 'glesys': - case 'dnsomatic': - case 'dyndns': - case 'dyndns-static': - case 'dyndns-custom': - case 'dhs': - case 'noip': - case 'noip-free': - case 'easydns': - case 'hn': - case 'zoneedit': - case 'dyns': - case 'ods': - case 'freedns': - case 'loopia': - case 'staticcling': - case 'dnsexit': - case 'custom': - case 'custom-v6': - case 'opendns': - case 'namecheap': - case 'he-net': - case 'he-net-v6': - case 'selfhost': - case 'he-net-tunnelbroker': - case 'route53': - case 'cloudflare': - case 'eurodns': - case 'gratisdns': - case 'ovh-dynhost': - case 'citynetwork': - case 'dnsimple': - $this->_update(); - if($this->_dnsDummyUpdateDone == true) { - // If a dummy update was needed, then sleep a while and do the update again to put the proper address back. - // Some providers (e.g. No-IP free accounts) need to have at least 1 address change every month. - // If the address has not changed recently, or the user did "Force Update", then the code does - // a dummy address change for providers like this. - sleep(10); + case 'glesys': + case 'dnsomatic': + case 'dyndns': + case 'dyndns-static': + case 'dyndns-custom': + case 'dhs': + case 'noip': + case 'noip-free': + case 'easydns': + case 'hn': + case 'zoneedit': + case 'dyns': + case 'ods': + case 'freedns': + case 'loopia': + case 'staticcling': + case 'dnsexit': + case 'custom': + case 'custom-v6': + case 'opendns': + case 'namecheap': + case 'he-net': + case 'he-net-v6': + case 'selfhost': + case 'he-net-tunnelbroker': + case 'route53': + case 'cloudflare': + case 'eurodns': + case 'gratisdns': + case 'ovh-dynhost': + case 'citynetwork': + case 'dnsimple': $this->_update(); - } - break; - default: - $this->_error(6); - break; + if ($this->_dnsDummyUpdateDone == true) { + // If a dummy update was needed, then sleep a while and do the update again to put the proper address back. + // Some providers (e.g. No-IP free accounts) need to have at least 1 address change every month. + // If the address has not changed recently, or the user did "Force Update", then the code does + // a dummy address change for providers like this. + sleep(10); + $this->_update(); + } + break; + default: + $this->_error(6); + break; } } unlock($dyndnslck); } - + /* * Private Function (added 12 July 05) [beta] * Send Update To Selected Service. */ function _update() { - - if ($this->_dnsVerboseLog) + + if ($this->_dnsVerboseLog) { log_error("DynDNS ({$this->_dnsHost}): DynDns _update() starting."); - + } + if ($this->_dnsService != 'ods' and $this->_dnsService != 'route53 ') { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); @@ -287,8 +290,9 @@ switch ($this->_dnsService) { case 'glesys': $needsIP = TRUE; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("DynDNS: ({$this->_dnsHost}) DNS update() starting."); + } $server = 'https://api.glesys.com/domain/updaterecord/format/json'; curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); $post_data['recordid'] = $this->_dnsHost; @@ -300,16 +304,21 @@ case 'dyndns-static': case 'dyndns-custom': $needsIP = FALSE; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("DynDNS: ({$this->_dnsHost}) DNS update() starting."); - if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") $this->_dnsWildcard = "ON"; + } + if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") { + $this->_dnsWildcard = "ON"; + } curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); $server = "https://members.dyndns.org/nic/update"; $port = ""; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) + } + if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, $server .$port . '?system=dyndns&hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP . '&wildcard='.$this->_dnsWildcard . '&mx=' . $this->_dnsMX . '&backmx=NO'); break; case 'dhs': @@ -330,10 +339,12 @@ $post_data['submit'] = 'Update'; $server = "https://members.dhs.org/nic/hosts"; $port = ""; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) - $port = ":" . $this->_dnsPort; + } + if ($this->_dnsPort) { + $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, '{$server}{$port}'); curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); @@ -343,13 +354,15 @@ $needsIP = TRUE; $server = "https://dynupdate.no-ip.com/ducupdate.php"; $port = ""; - if($this->_dnsServer) - $server = $this->_dnsServer; - if($this->_dnsPort) + if ($this->_dnsServer) { + $server = $this->_dnsServer + } + if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; - if(($this->_dnsService == "noip-free") && - ($this->_forceUpdateNeeded == true) && - ($this->_dnsDummyUpdateDone == false)) { + } + if (($this->_dnsService == "noip-free") && + ($this->_forceUpdateNeeded == true) && + ($this->_dnsDummyUpdateDone == false)) { // Update the IP to a dummy value to force No-IP free accounts to see a change. $iptoset = "192.168.1.1"; $this->_dnsDummyUpdateDone = true; @@ -364,10 +377,12 @@ curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); $server = "https://members.easydns.com/dyn/dyndns.php"; $port = ""; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) + } + if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, $server . $port . '?hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP . '&wildcard=' . $this->_dnsWildcard . '&mx=' . $this->_dnsMX . '&backmx=' . $this->_dnsBackMX); break; case 'hn': @@ -375,10 +390,12 @@ curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); $server = "http://dup.hn.org/vanity/update"; $port = ""; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) + } + if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, $server . $port . '?ver=1&IP=' . $this->_dnsIP); break; case 'zoneedit': @@ -387,20 +404,24 @@ $server = "https://dynamic.zoneedit.com/auth/dynamic.html"; $port = ""; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) + } + if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, "{$server}{$port}?host=" .$this->_dnsHost); break; case 'dyns': $needsIP = FALSE; $server = "https://www.dyns.cx/postscript011.php"; $port = ""; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) - $port = ":" . $this->_dnsPort; + } + if ($this->_dnsPort) { + $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, $server . $port . '?username=' . urlencode($this->_dnsUser) . '&password=' . $this->_dnsPass . '&host=' . $this->_dnsHost); break; case 'ods': @@ -409,10 +430,12 @@ $misc_error = ""; $server = "ods.org"; $port = ""; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) - $port = ":" . $this->_dnsPort; + } + if ($this->_dnsPort) { + $port = ":" . $this->_dnsPort; + } $this->con['socket'] = fsockopen("{$server}{$port}", "7070", $misc_errno, $misc_error, 30); /* Check that we have connected */ if (!$this->con['socket']) { @@ -424,7 +447,7 @@ $this->con['buffer']['all'] = trim(fgets($this->con['socket'], 4096)); $code = substr($this->con['buffer']['all'], 0, 3); sleep(1); - switch($code) { + switch ($code) { case 100: fputs($this->con['socket'], "LOGIN ".$this->_dnsUser." ".$this->_dnsPass."\n"); break; @@ -460,25 +483,30 @@ curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); $server = "https://updates.opendns.com/nic/update?hostname=". $this->_dnsHost; $port = ""; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) + } + if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, $server .$port); break; case 'staticcling': $needsIP = FALSE; curl_setopt($ch, CURLOPT_URL, 'https://www.staticcling.org/update.html?login='.$this->_dnsUser.'&pass='.$this->_dnsPass); - break; + break; case 'dnsomatic': - /* Example syntax + /* Example syntax https://username:password@updates.dnsomatic.com/nic/update?hostname=yourhostname&myip=ipaddress&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG */ $needsIP = FALSE; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("DNS-O-Matic: DNS update() starting."); - if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") $this->_dnsWildcard = "ON"; + } + if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") { + $this->_dnsWildcard = "ON"; + } /* Reference: https://www.dnsomatic.com/wiki/api DNS-O-Matic usernames are 3-25 characters. @@ -489,10 +517,12 @@ Encodes the given string according to RFC 3986. */ $server = "https://" . rawurlencode($this->_dnsUser) . ":" . rawurlencode($this->_dnsPass) . "@updates.dnsomatic.com/nic/update?hostname="; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) + } + if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, $server . $this->_dnsHost . '&myip=' . $this->_dnsIP . '&wildcard='.$this->_dnsWildcard . '&mx=' . $this->_dnsMX . '&backmx=NOCHG'); break; case 'namecheap': @@ -500,8 +530,9 @@ https://dynamicdns.park-your-domain.com/update?host=[host_name]&domain=[domain.com]&password=[domain_password]&ip=[your_ip] */ $needsIP = FALSE; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("Namecheap ({$this->_dnsHost}): DNS update() starting."); + } $dparts = explode(".", trim($this->_dnsHost)); $domain_part_count = ($dparts[count($dparts)-1] == "uk") ? 3 : 2; $domain_offset = count($dparts) - $domain_part_count; @@ -514,8 +545,9 @@ case 'he-net': case 'he-net-v6': $needsIP = FALSE; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("HE.net ({$this->_dnsHost}): DNS update() starting."); + } $server = "https://dyn.dns.he.net/nic/update?"; curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); @@ -523,30 +555,37 @@ break; case 'he-net-tunnelbroker': $needsIP = FALSE; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("HE.net Tunnelbroker: DNS update() starting."); + } $server = "https://ipv4.tunnelbroker.net/ipv4_end.php?"; curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser . ':' . $this->_dnsPass); curl_setopt($ch, CURLOPT_URL, $server . 'tid=' . $this->_dnsHost); break; case 'selfhost': $needsIP = FALSE; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("SelfHost: DNS update() starting."); - if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") $this->_dnsWildcard = "ON"; + } + if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") { + $this->_dnsWildcard = "ON"; + } curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); $server = "https://carol.selfhost.de/nic/update"; $port = ""; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) + } + if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, $server .$port . '?system=dyndns&hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP . '&wildcard='.$this->_dnsWildcard . '&mx=' . $this->_dnsMX . '&backmx=NO'); break; case 'route53': - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("Route53 ({$this->_dnsHost}): DNS update() starting."); - + } + /* Setting Variables */ $hostname = "{$this->_dnsHost}."; $ZoneID = $this->_dnsZoneID; @@ -562,11 +601,11 @@ $r53 = new Route53($AccessKeyId, $SecretAccessKey); /* Function to find old values of records in Route 53 */ - if(!function_exists('Searchrecords')) { + if (!function_exists('Searchrecords')) { function SearchRecords($records, $name) { $result = array(); - foreach($records as $record) { - if(strtolower($record['Name']) == strtolower($name)) { + foreach ($records as $record) { + if (strtolower($record['Name']) == strtolower($name)) { $result [] = $record; } } @@ -577,7 +616,7 @@ $records = $r53->listResourceRecordSets("/hostedzone/$ZoneID"); /* Get IP for your hostname in Route 53 */ - if(false !== ($a_result = SearchRecords($records['ResourceRecordSets'], "$hostname"))) { + if (false !== ($a_result = SearchRecords($records['ResourceRecordSets'], "$hostname"))) { $OldTTL=$a_result[0][TTL]; $OldIP=$a_result[0][ResourceRecords][0]; } else { @@ -586,7 +625,7 @@ /* Check if we need to update DNS Record */ if ($OldIP !== $NewIP) { - if(!empty($OldIP)) { + if (!empty($OldIP)) { /* Your Hostname already exists, deleting and creating it again */ $changes = array(); $changes[] = $r53->prepareChange(DELETE, $hostname, A, $OldTTL, $OldIP); @@ -602,22 +641,26 @@ break; case 'custom': case 'custom-v6': - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("Custom DDNS ({$this->_dnsHost}): DNS update() starting."); + } if (strstr($this->dnsUpdateURL, "%IP%")) {$needsIP = TRUE;} else {$needsIP = FALSE;} if ($this->_dnsUser != '') { - if ($this->_curlIpresolveV4) + if ($this->_curlIpresolveV4) { curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); - if ($this->_curlSslVerifypeer) + } + if ($this->_curlSslVerifypeer) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE); - else + } else { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); + } + curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_USERPWD, "{$this->_dnsUser}:{$this->_dnsPass}"); } $server = str_replace("%IP%", $this->_dnsIP, $this->_dnsUpdateURL); - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("Sending request to: ".$server); + } curl_setopt($ch, CURLOPT_URL, $server); break; case 'cloudflare': @@ -627,50 +670,59 @@ $URL = "https://{$dnsServer}/api.html?a=DIUP&email={$this->_dnsUser}&tkn={$this->_dnsPass}&ip={$this->_dnsIP}&hosts={$dnsHost}"; curl_setopt($ch, CURLOPT_URL, $URL); break; - case 'eurodns': + case 'eurodns': $needsIP = TRUE; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("EuroDynDns ({$this->_dnsHost}) DNS update() starting."); + } curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); $server = "https://update.eurodyndns.org/update/"; $port = ""; - if($this->_dnsPort) + if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, $server .$port . '?hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP); break; case 'gratisdns': $needsIP = FALSE; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("GratisDNS.dk ({$this->_dnsHost}): DNS update() starting."); + } $server = "https://ssl.gratisdns.dk/ddns.phtml"; list($hostname, $domain) = explode(".", $this->_dnsHost, 2); curl_setopt($ch, CURLOPT_URL, $server . '?u=' . $this->_dnsUser . '&p=' . $this->_dnsPass . '&h=' . $this->_dnsHost . '&d=' . $domain); break; case 'ovh-dynhost': $needsIP = FALSE; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("OVH DynHOST: ({$this->_dnsHost}) DNS update() starting."); + } if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") $this->_dnsWildcard = "ON"; curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); $server = "https://www.ovh.com/nic/update"; $port = ""; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) + } + if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, $server .$port . '?system=dyndns&hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP . '&wildcard='.$this->_dnsWildcard . '&mx=' . $this->_dnsMX . '&backmx=NO'); break; case 'citynetwork': $needsIP = TRUE; - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("City Network: ({$this->_dnsHost}) DNS update() starting."); + } curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass); $server = 'https://dyndns.citynetwork.se/nic/update'; $port = ""; - if($this->_dnsServer) + if ($this->_dnsServer) { $server = $this->_dnsServer; - if($this->_dnsPort) + } + if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; + } curl_setopt($ch, CURLOPT_URL, $server .$port . '?hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP); break; case 'dnsimple': @@ -733,7 +785,7 @@ } else if (preg_match('/nohost/i', $data)) { $status = "DNS-O-Matic ({$this->_dnsHost}): The hostname passed could not be matched to any services configured. The service field will be blank in the return code."; } else if (preg_match('/numhost/i', $data)) { - $status = "DNS-O-Matic ({$this->_dnsHost}): You may update up to 20 hosts. numhost is returned if you try to update more than 20 or update a round-robin."; + $status = "DNS-O-Matic ({$this->_dnsHost}): You may update up to 20 hosts. numhost is returned if you try to update more than 20 or update a round-robin."; } else if (preg_match('/abuse/i', $data)) { $status = "DNS-O-Matic ({$this->_dnsHost}): The hostname is blocked for update abuse."; } else if (preg_match('/good/i', $data)) { @@ -908,7 +960,7 @@ break; case 'zoneedit': if (preg_match('/799/i', $data)) { - $status = "phpDynDNS ({$this->_dnsHost}): (Error 799) Update Failed!"; + $status = "phpDynDNS ({$this->_dnsHost}): (Error 799) Update Failed!"; } else if (preg_match('/700/i', $data)) { $status = "phpDynDNS ({$this->_dnsHost}): (Error 700) Update Failed!"; } else if (preg_match('/200/i', $data)) { @@ -916,7 +968,7 @@ $successful_update = true; } else if (preg_match('/201/i', $data)) { $status = "phpDynDNS ({$this->_dnsHost}): (Success) IP Address Updated Successfully!"; - $successful_update = true; + $successful_update = true; } else { $status = "phpDynDNS ({$this->_dnsHost}): (Unknown Response)"; log_error("phpDynDNS ({$this->_dnsHost}): PAYLOAD: {$data}"); @@ -962,7 +1014,7 @@ $status = "phpDynDNS ({$this->_dnsHost}): (Unknown Response)"; log_error("phpDynDNS ({$this->_dnsHost}): PAYLOAD: {$data}"); $this->_debug($data); - } + } break; case 'dnsexit': if (preg_match("/is the same/i", $data)) { @@ -1054,7 +1106,7 @@ $this->_debug($data); } break; - + case 'he-net': case 'he-net-v6': if (preg_match("/badip/i", $data)) { @@ -1127,20 +1179,22 @@ $successful_update = false; if ($this->_dnsResultMatch == "") { $successful_update = true; - }else { + } else { $this->_dnsResultMatch = str_replace("%IP%", $this->_dnsIP, $this->_dnsResultMatch); $matches = preg_split("/(?_dnsResultMatch); - foreach($matches as $match) { + foreach ($matches as $match) { $match= str_replace("\\|", "|", $match); - if(strcmp($match, trim($data, "\t\n\r")) == 0) + if (strcmp($match, trim($data, "\t\n\r")) == 0) { $successful_update = true; + } } unset ($matches); } - if ($successful_update == true) + if ($successful_update == true) { $status = "phpDynDNS: (Success) IP Address Updated Successfully!"; - else + } else { $status = "phpDynDNS: (Error) Result did not match."; + } break; case 'cloudflare': // receive multiple results @@ -1148,7 +1202,7 @@ $lines = count($data)-1; // loop over the lines - for ($pos=0; ($successful_update || $pos == 0) && $pos < $lines; $pos++){ + for ($pos=0; ($successful_update || $pos == 0) && $pos < $lines; $pos++) { $resp = $data[$pos]; if (preg_match('/UAUTH/i', $resp)) { $status = "DynDNS: The username specified is not authorized to update this hostname and domain."; @@ -1193,20 +1247,20 @@ break; case 'gratisdns': if (preg_match('/Forkerte værdier/i', $data)) { - $status = "phpDynDNS: (Error) Wrong values - Update could not be completed."; + $status = "phpDynDNS: (Error) Wrong values - Update could not be completed."; } else if (preg_match('/Bruger login: Bruger eksistere ikke/i', $data)) { - $status = "phpDynDNS: (Error) Unknown username - User does not exist."; + $status = "phpDynDNS: (Error) Unknown username - User does not exist."; } else if (preg_match('/Bruger login: 1Fejl i kodeord/i', $data)) { - $status = "phpDynDNS: (Error) Wrong password - Remember password is case sensitive."; + $status = "phpDynDNS: (Error) Wrong password - Remember password is case sensitive."; } else if (preg_match('/Domæne kan IKKE administreres af bruger/i', $data)) { - $status = "phpDynDNS: (Error) User unable to administer the selected domain."; + $status = "phpDynDNS: (Error) User unable to administer the selected domain."; } else if (preg_match('/OK/i', $data)) { - $status = "phpDynDNS: (Success) IP Address Updated Successfully!"; - $successful_update = true; + $status = "phpDynDNS: (Success) IP Address Updated Successfully!"; + $successful_update = true; } else { - $status = "phpDynDNS: (Unknown Response)"; - log_error("phpDynDNS: PAYLOAD: {$data}"); - $this->_debug($data); + $status = "phpDynDNS: (Unknown Response)"; + log_error("phpDynDNS: PAYLOAD: {$data}"); + $this->_debug($data); } break; case 'dnsimple': @@ -1223,7 +1277,7 @@ $arrbody = json_decode($body, true); $message = $arrbody['message'] . "."; if (isset($arrbody['errors']['content'])) { - foreach($arrbody['errors']['content'] as $key => $content) { + foreach ($arrbody['errors']['content'] as $key => $content) { $message .= " " . $content . "."; } } @@ -1236,7 +1290,7 @@ break; } - if($successful_update == true) { + if ($successful_update == true) { /* Write WAN IP to cache file */ $wan_ip = $this->_checkIP(); conf_mount_rw(); @@ -1245,15 +1299,17 @@ notify_all_remote(sprintf(gettext("DynDNS updated IP Address on %s (%s) to %s"), convert_real_interface_to_friendly_descr($this->_if), $this->_if, $wan_ip)); log_error("phpDynDNS: updating cache file {$this->_cacheFile}: {$wan_ip}"); @file_put_contents($this->_cacheFile, "{$wan_ip}:{$currentTime}"); - } else + } else { @unlink($this->_cacheFile); + } if ($this->_useIPv6 == true && $wan_ip > 0) { $currentTime = time(); notify_all_remote(sprintf(gettext("DynDNS updated IPv6 Address on %s (%s) to %s"), convert_real_interface_to_friendly_descr($this->_if), $this->_if, $wan_ip)); log_error("phpDynDNS: updating cache file {$this->_cacheFile_v6}: {$wan_ip}"); @file_put_contents($this->_cacheFile_v6, "{$wan_ip}|{$currentTime}"); - } else + } else { @unlink($this->_cacheFile_v6); + } conf_mount_ro(); } $this->status = $status; @@ -1291,7 +1347,7 @@ break; case 9: $status = "Route 53: (Error) Invalid TTL"; - break; + break; case 10: $error = "phpDynDNS ({$this->_dnsHost}): No change in my IP address and/or " . $this->_dnsMaxCacheAgeDays . " days has not passed. Not updating dynamic DNS entry."; break; @@ -1314,9 +1370,10 @@ function _detectChange() { global $debug; - if ($debug) + if ($debug) { log_error("DynDns ({$this->_dnsHost}): _detectChange() starting."); - + } + $currentTime = time(); $wan_ip = $this->_checkIP(); @@ -1359,8 +1416,9 @@ $log_error .= "No Cached IP found."; } } - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error($log_error); + } // Convert seconds = days * hr/day * min/hr * sec/min $maxCacheAgeSecs = $this->_dnsMaxCacheAgeDays * 24 * 60 * 60; @@ -1392,7 +1450,7 @@ return true; } - return false; + return false; } /* @@ -1404,8 +1462,9 @@ function _debug($data) { global $g; - if (!$g['debug']) + if (!$g['debug']) { return; + } $string = date('m-d-y h:i:s').' - ('.$this->_debugID.') - ['.$this->_dnsService.'] - '.$data."\n"; conf_mount_rw(); $file = fopen($this->_debugFile, 'a'); @@ -1416,25 +1475,29 @@ function _checkIP() { global $debug; - if ($debug) + if ($debug) { log_error("DynDns ({$this->_dnsHost}): _checkIP() starting."); + } if ($this->_useIPv6 == true) { $ip_address = find_interface_ipv6($this->_if); - if (!is_ipaddrv6($ip_address)) + if (!is_ipaddrv6($ip_address)) { return 0; + } } else { $ip_address = find_interface_ip($this->_if); - if (!is_ipaddr($ip_address)) + if (!is_ipaddr($ip_address)) { return 0; + } } if ($this->_useIPv6 == false && is_private_ip($ip_address)) { $hosttocheck = "checkip.dyndns.org"; $try = 0; while ($try < 3) { $checkip = gethostbyname($hosttocheck); - if (is_ipaddr($checkip)) + if (is_ipaddr($checkip)) { break; + } $try++; } if ($try >= 3) { @@ -1456,15 +1519,17 @@ preg_match('/Current IP Address: (.*)<\/body>/', $ip_result_decoded, $matches); $ip_address = trim($matches[1]); if (is_ipaddr($ip_address)) { - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("DynDns ({$this->_dnsHost}): {$ip_address} extracted from {$hosttocheck}"); + } } else { log_error("DynDns ({$this->_dnsHost}): IP address could not be extracted from {$hosttocheck}"); return 0; } } else { - if ($this->_dnsVerboseLog) + if ($this->_dnsVerboseLog) { log_error("DynDns ({$this->_dnsHost}): {$ip_address} extracted from local system."); + } } $this->_dnsIP = $ip_address; diff --git a/etc/inc/easyrule.inc b/etc/inc/easyrule.inc index 25219ce535..fe78f939dc 100644 --- a/etc/inc/easyrule.inc +++ b/etc/inc/easyrule.inc @@ -43,30 +43,36 @@ function easyrule_find_rule_interface($int) { /* Borrowed from firewall_rules.php */ $iflist = get_configured_interface_with_descr(false, true); - if ($config['pptpd']['mode'] == "server") + if ($config['pptpd']['mode'] == "server") { $iflist['pptp'] = "PPTP VPN"; + } - if ($config['pppoe']['mode'] == "server") + if ($config['pppoe']['mode'] == "server") { $iflist['pppoe'] = "PPPoE Server"; + } - if ($config['l2tp']['mode'] == "server") - $iflist['l2tp'] = "L2TP VPN"; + if ($config['l2tp']['mode'] == "server") { + $iflist['l2tp'] = "L2TP VPN"; + } /* add ipsec interfaces */ if (isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable'])){ $iflist["enc0"] = "IPSEC"; } - if (isset($iflist[$int])) + if (isset($iflist[$int])) { return $int; - - foreach ($iflist as $if => $ifd) { - if (strtolower($int) == strtolower($ifd)) - return $if; } - if (substr($int, 0, 4) == "ovpn") + foreach ($iflist as $if => $ifd) { + if (strtolower($int) == strtolower($ifd)) { + return $if; + } + } + + if (substr($int, 0, 4) == "ovpn") { return "openvpn"; + } return false; } @@ -80,11 +86,13 @@ function easyrule_block_rule_exists($int = 'wan', $ipproto = "inet") { /* Search through the rules for one referencing our alias */ foreach ($config['filter']['rule'] as $rule) { - if (!is_array($rule) || !is_array($rule['source'])) + if (!is_array($rule) || !is_array($rule['source'])) { continue; + } $checkproto = isset($rule['ipprotocol']) ? $rule['ipprotocol'] : "inet"; - if ($rule['source']['address'] == $blockaliasname . strtoupper($int) && ($rule['interface'] == $int) && ($checkproto == $ipproto)) + if ($rule['source']['address'] == $blockaliasname . strtoupper($int) && ($rule['interface'] == $int) && ($checkproto == $ipproto)) { return true; + } } return false; } @@ -93,12 +101,14 @@ function easyrule_block_rule_create($int = 'wan', $ipproto = "inet") { global $blockaliasname, $config; /* If the alias doesn't exist, exit. * Can't create an empty alias, and we don't know a host */ - if (easyrule_block_alias_getid($int) === false) + if (easyrule_block_alias_getid($int) === false) { return false; + } /* If the rule already exists, no need to do it again */ - if (easyrule_block_rule_exists($int, $ipproto)) + if (easyrule_block_rule_exists($int, $ipproto)) { return true; + } /* No rules, start a new array */ if (!is_array($config['filter']['rule'])) { @@ -125,13 +135,16 @@ function easyrule_block_rule_create($int = 'wan', $ipproto = "inet") { function easyrule_block_alias_getid($int = 'wan') { global $blockaliasname, $config; - if (!is_array($config['aliases'])) + if (!is_array($config['aliases'])) { return false; + } /* Hunt down an alias with the name we want, return its id */ - foreach ($config['aliases']['alias'] as $aliasid => $alias) - if ($alias['name'] == $blockaliasname . strtoupper($int)) + foreach ($config['aliases']['alias'] as $aliasid => $alias) { + if ($alias['name'] == $blockaliasname . strtoupper($int)) { return $aliasid; + } + } return false; } @@ -140,19 +153,22 @@ function easyrule_block_alias_add($host, $int = 'wan') { global $blockaliasname, $config; /* If the host isn't a valid IP address, bail */ $host = trim($host, "[]"); - if (!is_ipaddr($host) && !is_subnet($host)) + if (!is_ipaddr($host) && !is_subnet($host)) { return false; + } /* If there are no aliases, start an array */ - if (!is_array($config['aliases']['alias'])) + if (!is_array($config['aliases']['alias'])) { $config['aliases']['alias'] = array(); + } $a_aliases = &$config['aliases']['alias']; /* Try to get the ID if the alias already exists */ $id = easyrule_block_alias_getid($int); - if ($id === false) + if ($id === false) { unset($id); + } $alias = array(); @@ -168,8 +184,9 @@ function easyrule_block_alias_add($host, $int = 'wan') { if (isset($id) && $a_aliases[$id]) { /* Make sure this IP isn't already in the list. */ - if (in_array($host.'/'.$mask, explode(" ", $a_aliases[$id]['address']))) + if (in_array($host.'/'.$mask, explode(" ", $a_aliases[$id]['address']))) { return true; + } /* Since the alias already exists, just add to it. */ $alias['name'] = $a_aliases[$id]['name']; $alias['type'] = $a_aliases[$id]['type']; @@ -179,8 +196,8 @@ function easyrule_block_alias_add($host, $int = 'wan') { $alias['detail'] = $a_aliases[$id]['detail'] . gettext('Entry added') . ' ' . date('r') . '||'; } else { /* Create a new alias with all the proper information */ - $alias['name'] = $blockaliasname . strtoupper($int); - $alias['type'] = 'network'; + $alias['name'] = $blockaliasname . strtoupper($int); + $alias['type'] = 'network'; $alias['descr'] = gettext("Hosts blocked from Firewall Log view"); $alias['address'] = $host . '/' . $mask; @@ -188,10 +205,11 @@ function easyrule_block_alias_add($host, $int = 'wan') { } /* Replace the old alias if needed, otherwise tack it on the end */ - if (isset($id) && $a_aliases[$id]) + if (isset($id) && $a_aliases[$id]) { $a_aliases[$id] = $alias; - else + } else { $a_aliases[] = $alias; + } // Sort list $a_aliases = msort($a_aliases, "name"); @@ -203,8 +221,9 @@ function easyrule_block_host_add($host, $int = 'wan', $ipproto = "inet") { global $retval; /* Bail if the supplied host is not a valid IP address */ $host = trim($host, "[]"); - if (!is_ipaddr($host) && !is_subnet($host)) + if (!is_ipaddr($host) && !is_subnet($host)) { return false; + } /* Flag whether or not we need to reload the filter */ $dirty = false; @@ -263,18 +282,21 @@ function easyrule_pass_rule_add($int, $proto, $srchost, $dsthost, $dstport, $ipp $filterent['ipprotocol'] = $ipproto; $filterent['descr'] = gettext("Easy Rule: Passed from Firewall Log View"); - if ($proto != "any") + if ($proto != "any") { $filterent['protocol'] = $proto; - else + } else { unset($filterent['protocol']); + } /* Default to only allow echo requests, since that's what most people want and * it should be a safe choice. */ - if ($proto == "icmp") + if ($proto == "icmp") { $filterent['icmptype'] = 'echoreq'; + } - if ((strtolower($proto) == "icmp6") || (strtolower($proto) == "icmpv6")) + if ((strtolower($proto) == "icmp6") || (strtolower($proto) == "icmpv6")) { $filterent['protocol'] = "icmp"; + } if (is_subnet($srchost)) { list($srchost, $srcmask) = explode("/", $srchost); From 95d2d24b1dde7d34d5e61e53afa0ae216159176a Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 26 Feb 2015 01:32:06 -0600 Subject: [PATCH 133/257] Log ifconfig commands used to setup wireless interfaces --- etc/inc/interfaces.inc | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index 2a07901f98..e524936ead 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -2299,6 +2299,8 @@ function interface_wireless_configure($if, &$wl, &$wlcfg) { $fd_set = fopen("{$g['tmp_path']}/{$if}_setup.sh","w"); fwrite($fd_set, "#!/bin/sh\n"); fwrite($fd_set, "# {$g['product_name']} wireless configuration script.\n\n"); + + $wlan_setup_log = fopen("{$g['tmp_path']}/{$if}_setup.log","w"); /* set values for /path/program */ $hostapd = "/usr/sbin/hostapd"; @@ -2657,6 +2659,7 @@ EOD; /* apply the regulatory settings */ mwexec("{$ifconfig} " . escapeshellarg($if) . " {$wlregcmd_args}"); + fwrite($wlan_setup_log, "$ifconfig" . escapeshellarg($if) . "$wlregcmd_args \n"); /* bring the clones back up that were previously up */ foreach ($clones_up as $clone_if) { @@ -2681,10 +2684,14 @@ EOD; /* The mode must be specified in a separate command before ifconfig * will allow the mode and channel at the same time in the next. */ mwexec("/sbin/ifconfig " . escapeshellarg($if) . " mode " . escapeshellarg($standard)); + fwrite($wlan_setup_log, "/sbin/ifconfig " . escapeshellarg($if) . " mode " . escapeshellarg($standard) . "\n"); /* configure wireless */ $wlcmd_args = implode(" ", $wlcmd); mwexec("/sbin/ifconfig " . escapeshellarg($if) . " " . $wlcmd_args, false); + fwrite($wlan_setup_log, "/sbin/ifconfig " . escapeshellarg($if) . " " . "$wlcmd_args \n"); + fclose($wlan_setup_log); + unset($wlcmd_args, $wlcmd); From 777291a29349ae5e58891aa7898f07044cf747ab Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 26 Feb 2015 01:36:12 -0600 Subject: [PATCH 134/257] remove unused legacy code --- etc/inc/filter.inc | 6 ------ 1 file changed, 6 deletions(-) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index 4d863b5fd5..6efb5da9d2 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -657,12 +657,6 @@ function filter_generate_aliases() { if(isset($config['aliases']['alias'])) { foreach ($config['aliases']['alias'] as $aliased) { $extralias = ""; - /* - * XXX: i am not sure what this does so I am commenting it out for now, because as it is - * its quite dangerous! - * $ip = find_interface_ip($aliased['address']); - * $extraalias = " " . link_ip_to_carp_interface($ip); - */ $aliasnesting = array(); $aliasaddrnesting = array(); $addrlist = filter_generate_nested_alias($aliased['name'], $aliased['address'], $aliasnesting, $aliasaddrnesting); From 9ba8799777c7f9e73cce3f1c2b9c9b303ffd9557 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 26 Feb 2015 14:10:53 +0545 Subject: [PATCH 135/257] Code Style Guide etc inc f to g --- etc/inc/filter_log.inc | 187 +++++++++++-------- etc/inc/functions.inc | 179 +++++++++--------- etc/inc/globals.inc | 110 +++++------ etc/inc/gmirror.inc | 59 ++++-- etc/inc/growl.class | 180 +++++++++--------- etc/inc/gwlb.inc | 415 +++++++++++++++++++++++++---------------- 6 files changed, 639 insertions(+), 491 deletions(-) diff --git a/etc/inc/filter_log.inc b/etc/inc/filter_log.inc index 46c9b130fb..60f4ed5d30 100644 --- a/etc/inc/filter_log.inc +++ b/etc/inc/filter_log.inc @@ -45,33 +45,36 @@ function conv_log_filter($logfile, $nentries, $tail = 50, $filtertext = "", $fil global $config, $g; /* Make sure this is a number before using it in a system call */ - if (!(is_numeric($tail))) + if (!(is_numeric($tail))) { return; + } - if ($filtertext) + if ($filtertext) { $tail = 5000; + } /* Always do a reverse tail, to be sure we're grabbing the 'end' of the log. */ $logarr = ""; - if(isset($config['system']['usefifolog'])) + if (isset($config['system']['usefifolog'])) { exec("/usr/sbin/fifolog_reader " . escapeshellarg($logfile) . " | /usr/bin/grep 'filterlog:' | /usr/bin/tail -r -n {$tail}", $logarr); - else + } else { exec("/usr/local/sbin/clog " . escapeshellarg($logfile) . " | grep -v \"CLOG\" | grep -v \"\033\" | /usr/bin/grep 'filterlog:' | /usr/bin/tail -r -n {$tail}", $logarr); + } $filterlog = array(); $counter = 0; $filterinterface = strtoupper($filterinterface); foreach ($logarr as $logent) { - if($counter >= $nentries) + if ($counter >= $nentries) { break; + } $flent = parse_filter_line($logent); - if (!$filterinterface || ($filterinterface == $flent['interface'])) - { - if ( ( ($flent != "") && (!is_array($filtertext)) && (match_filter_line ($flent, $filtertext))) || - ( ($flent != "") && ( is_array($filtertext)) && (match_filter_field($flent, $filtertext)) ) ) { + if (!$filterinterface || ($filterinterface == $flent['interface'])) { + if ((($flent != "") && (!is_array($filtertext)) && (match_filter_line ($flent, $filtertext))) || + (($flent != "") && ( is_array($filtertext)) && (match_filter_field($flent, $filtertext)))) { $counter++; $filterlog[] = $flent; } @@ -88,34 +91,40 @@ function escape_filter_regex($filtertext) { } function match_filter_line($flent, $filtertext = "") { - if (!$filtertext) + if (!$filtertext) { return true; + } $filtertext = escape_filter_regex(str_replace(' ', '\s+', $filtertext)); return @preg_match("/{$filtertext}/i", implode(" ", array_values($flent))); } function match_filter_field($flent, $fields) { foreach ($fields as $key => $field) { - if ($field == "All") + if ($field == "All") { continue; + } if ((strpos($field, '!') === 0)) { $field = substr($field, 1); if (strtolower($key) == 'act') { - if (in_arrayi($flent[$key], explode(" ", $field))) + if (in_arrayi($flent[$key], explode(" ", $field))) { return false; + } } else { $field_regex = escape_filter_regex($field); - if (@preg_match("/{$field_regex}/i", $flent[$key])) + if (@preg_match("/{$field_regex}/i", $flent[$key])) { return false; + } } } else { if (strtolower($key) == 'act') { - if (!in_arrayi($flent[$key], explode(" ", $field))) + if (!in_arrayi($flent[$key], explode(" ", $field))) { return false; + } } else { $field_regex = escape_filter_regex($field); - if (!@preg_match("/{$field_regex}/i", $flent[$key])) + if (!@preg_match("/{$field_regex}/i", $flent[$key])) { return false; + } } } } @@ -133,8 +142,9 @@ function parse_filter_line($line) { $flent = array(); $log_split = ""; - if (!preg_match("/(.*)\s(.*)\sfilterlog:\s(.*)$/", $line, $log_split)) + if (!preg_match("/(.*)\s(.*)\sfilterlog:\s(.*)$/", $line, $log_split)) { return ""; + } list($all, $flent['time'], $host, $rule) = $log_split; @@ -197,45 +207,45 @@ function parse_filter_line($line) { $flent['icmp_type'] = $rule_data[$field++]; switch ($flent['icmp_type']) { - case "request": - case "reply": - $flent['icmp_id'] = $rule_data[$field++]; - $flent['icmp_seq'] = $rule_data[$field++]; - break; - case "unreachproto": - $flent['icmp_dstip'] = $rule_data[$field++]; - $flent['icmp_protoid'] = $rule_data[$field++]; - break; - case "unreachport": - $flent['icmp_dstip'] = $rule_data[$field++]; - $flent['icmp_protoid'] = $rule_data[$field++]; - $flent['icmp_port'] = $rule_data[$field++]; - break; - case "unreach": - case "timexceed": - case "paramprob": - case "redirect": - case "maskreply": - $flent['icmp_descr'] = $rule_data[$field++]; - break; - case "needfrag": - $flent['icmp_dstip'] = $rule_data[$field++]; - $flent['icmp_mtu'] = $rule_data[$field++]; - break; - case "tstamp": - $flent['icmp_id'] = $rule_data[$field++]; - $flent['icmp_seq'] = $rule_data[$field++]; - break; - case "tstampreply": - $flent['icmp_id'] = $rule_data[$field++]; - $flent['icmp_seq'] = $rule_data[$field++]; - $flent['icmp_otime'] = $rule_data[$field++]; - $flent['icmp_rtime'] = $rule_data[$field++]; - $flent['icmp_ttime'] = $rule_data[$field++]; - break; - default : - $flent['icmp_descr'] = $rule_data[$field++]; - break; + case "request": + case "reply": + $flent['icmp_id'] = $rule_data[$field++]; + $flent['icmp_seq'] = $rule_data[$field++]; + break; + case "unreachproto": + $flent['icmp_dstip'] = $rule_data[$field++]; + $flent['icmp_protoid'] = $rule_data[$field++]; + break; + case "unreachport": + $flent['icmp_dstip'] = $rule_data[$field++]; + $flent['icmp_protoid'] = $rule_data[$field++]; + $flent['icmp_port'] = $rule_data[$field++]; + break; + case "unreach": + case "timexceed": + case "paramprob": + case "redirect": + case "maskreply": + $flent['icmp_descr'] = $rule_data[$field++]; + break; + case "needfrag": + $flent['icmp_dstip'] = $rule_data[$field++]; + $flent['icmp_mtu'] = $rule_data[$field++]; + break; + case "tstamp": + $flent['icmp_id'] = $rule_data[$field++]; + $flent['icmp_seq'] = $rule_data[$field++]; + break; + case "tstampreply": + $flent['icmp_id'] = $rule_data[$field++]; + $flent['icmp_seq'] = $rule_data[$field++]; + $flent['icmp_otime'] = $rule_data[$field++]; + $flent['icmp_rtime'] = $rule_data[$field++]; + $flent['icmp_ttime'] = $rule_data[$field++]; + break; + default : + $flent['icmp_descr'] = $rule_data[$field++]; + break; } } else if ($flent['protoid'] == '2') { // IGMP @@ -250,8 +260,9 @@ function parse_filter_line($line) { $flent['advbase'] = $rule_data[$field++]; } } else { - if($g['debug']) + if ($g['debug']) { log_error(sprintf(gettext("There was a error parsing rule number: %s. Please report to mailing list or forum."), $flent['rulenum'])); + } return ""; } @@ -259,7 +270,7 @@ function parse_filter_line($line) { if (!((trim($flent['src']) == "") || (trim($flent['dst']) == "") || (trim($flent['time']) == ""))) { return $flent; } else { - if($g['debug']) { + if ($g['debug']) { log_error(sprintf(gettext("There was a error parsing rule: %s. Please report to mailing list or forum."), $errline)); } return ""; @@ -267,8 +278,9 @@ function parse_filter_line($line) { } function get_port_with_service($port, $proto) { - if (!$port) + if (!$port) { return ''; + } $service = getservbyport($port, $proto); $portstr = ""; @@ -284,27 +296,31 @@ function find_rule_by_number($rulenum, $trackernum, $type="block") { global $g; /* Passing arbitrary input to grep could be a Very Bad Thing(tm) */ - if (!is_numeric($rulenum) || !is_numeric($trackernum) || !in_array($type, array('pass', 'block', 'match', 'rdr'))) + if (!is_numeric($rulenum) || !is_numeric($trackernum) || !in_array($type, array('pass', 'block', 'match', 'rdr'))) { return; + } - if ($trackernum == "0") + if ($trackernum == "0") { $lookup_pattern = "^@{$rulenum}\([0-9]+\)[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]]"; - else + } else { $lookup_pattern = "^@[0-9]+\({$trackernum}\)[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]]"; + } /* At the moment, miniupnpd is the only thing I know of that generates logging rdr rules */ unset($buffer); - if ($type == "rdr") + if ($type == "rdr") { $_gb = exec("/sbin/pfctl -vvPsn -a \"miniupnpd\" | /usr/bin/egrep " . escapeshellarg("^@{$rulenum}"), $buffer); - else { - if (file_exists("{$g['tmp_path']}/rules.debug")) + } else { + if (file_exists("{$g['tmp_path']}/rules.debug")) { $_gb = exec("/sbin/pfctl -vvPnf {$g['tmp_path']}/rules.debug 2>/dev/null | /usr/bin/egrep " . escapeshellarg($lookup_pattern), $buffer); - else + } else { $_gb = exec("/sbin/pfctl -vvPsr | /usr/bin/egrep " . escapeshellarg($lookup_pattern), $buffer); + } } - if (is_array($buffer)) + if (is_array($buffer)) { return $buffer[0]; + } return ""; } @@ -325,10 +341,11 @@ function buffer_rules_load() { } } unset($buffer, $_gb); - if (file_exists("{$g['tmp_path']}/rules.debug")) + if (file_exists("{$g['tmp_path']}/rules.debug")) { $_gb = exec("/sbin/pfctl -vvPnf {$g['tmp_path']}/rules.debug 2>/dev/null | /usr/bin/egrep '^@[0-9]+\([0-9]+\)[[:space:]].*[[:space:]]log[[:space:]]' | /usr/bin/egrep -v '^@[0-9]+\([0-9]+\)[[:space:]](nat|rdr|binat|no|scrub)'", $buffer); - else + } else { $_gb = exec("/sbin/pfctl -vvPsr | /usr/bin/egrep '^@[0-9]+\([0-9]+\)[[:space:]].*[[:space:]]log[[:space:]]'", $buffer); + } if (is_array($buffer)) { foreach ($buffer as $line) { @@ -336,10 +353,11 @@ function buffer_rules_load() { # pfctl rule number output with tracker number: @dd(dddddddddd) $matches = array(); if (preg_match('/\@(?P\d+)\((?\d+)\)/', $key, $matches) == 1) { - if ($matches['trackernum'] > 0) + if ($matches['trackernum'] > 0) { $key = $matches['trackernum']; - else + } else { $key = "@{$matches['rulenum']}"; + } } $buffer_rules_normal[$key] = $value; } @@ -352,13 +370,14 @@ function buffer_rules_clear() { unset($GLOBALS['buffer_rules_rdr']); } -function find_rule_by_number_buffer($rulenum, $trackernum, $type){ +function find_rule_by_number_buffer($rulenum, $trackernum, $type) { global $g, $buffer_rules_rdr, $buffer_rules_normal; - if ($trackernum == "0") + if ($trackernum == "0") { $lookup_key = "@{$rulenum}"; - else + } else { $lookup_key = $trackernum; + } if ($type == "rdr") { $ruleString = $buffer_rules_rdr[$lookup_key]; @@ -374,23 +393,26 @@ function find_rule_by_number_buffer($rulenum, $trackernum, $type){ function find_action_image($action) { global $g; - if ((strstr(strtolower($action), "p")) || (strtolower($action) == "rdr")) + if ((strstr(strtolower($action), "p")) || (strtolower($action) == "rdr")) { return "/themes/{$g['theme']}/images/icons/icon_pass.gif"; - else if(strstr(strtolower($action), "r")) + } else if (strstr(strtolower($action), "r")) { return "/themes/{$g['theme']}/images/icons/icon_reject.gif"; - else + } else { return "/themes/{$g['theme']}/images/icons/icon_block.gif"; + } } /* AJAX specific handlers */ function handle_ajax($nentries, $tail = 50) { global $config; - if($_GET['lastsawtime'] or $_POST['lastsawtime']) { + if ($_GET['lastsawtime'] or $_POST['lastsawtime']) { global $filter_logfile,$filterent; - if($_GET['lastsawtime']) + if ($_GET['lastsawtime']) { $lastsawtime = $_GET['lastsawtime']; - if($_POST['lastsawtime']) + } + if ($_POST['lastsawtime']) { $lastsawtime = $_POST['lastsawtime']; + } /* compare lastsawrule's time stamp to filter logs. * afterwards return the newer records so that client * can update AJAX interface screen. @@ -399,12 +421,13 @@ function handle_ajax($nentries, $tail = 50) { $filterlog = conv_log_filter($filter_logfile, $nentries, $tail); /* We need this to always be in forward order for the AJAX update to work properly */ $filterlog = isset($config['syslog']['reverse']) ? array_reverse($filterlog) : $filterlog; - foreach($filterlog as $log_row) { + foreach ($filterlog as $log_row) { $row_time = strtotime($log_row['time']); $img = "{$log_row['act']}"; - if($row_time > $lastsawtime) { - if ($log_row['proto'] == "TCP") + if ($row_time > $lastsawtime) { + if ($log_row['proto'] == "TCP") { $log_row['proto'] .= ":{$log_row['tcpflags']}"; + } $img = "{$img}"; $new_rules .= "{$img}||{$log_row['time']}||{$log_row['interface']}||{$log_row['srcip']}||{$log_row['srcport']}||{$log_row['dstip']}||{$log_row['dstport']}||{$log_row['proto']}||{$log_row['version']}||" . time() . "||\n"; diff --git a/etc/inc/functions.inc b/etc/inc/functions.inc index a89aeff4a4..ab9b73dc62 100644 --- a/etc/inc/functions.inc +++ b/etc/inc/functions.inc @@ -1,47 +1,47 @@ . - All rights reserved. + originally part of m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2004 Manuel Kasper . + All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. pfSense_MODULE: utils */ /* BEGIN compatibility goo with HEAD */ -if(!function_exists("gettext")) { +if (!function_exists("gettext")) { function gettext($text) { return $text; } } -if(!function_exists("pfSenseHeader")) { +if (!function_exists("pfSenseHeader")) { /****f* pfsense-utils/pfSenseHeader * NAME * pfSenseHeader @@ -51,30 +51,33 @@ if(!function_exists("pfSenseHeader")) { * Javascript header change or browser Location: ******/ function pfSenseHeader($text) { - global $_SERVER; - if (isAjax()) { - if ($_SERVER['HTTPS'] == "on") - $protocol = "https"; - else - $protocol = "http"; - - $port = ":{$_SERVER['SERVER_PORT']}"; - if ($_SERVER['SERVER_PORT'] == "80" && $protocol == "http") - $port = ""; - if ($_SERVER['SERVER_PORT'] == "443" && $protocol == "https") - $port = ""; - $complete_url = "{$protocol}://{$_SERVER['SERVER_NAME']}{$port}/{$text}"; - echo "\ndocument.location.href = '{$complete_url}';\n"; - } else { - header("Location: $text"); - } + global $_SERVER; + if (isAjax()) { + if ($_SERVER['HTTPS'] == "on") { + $protocol = "https"; + } else { + $protocol = "http"; + } + + $port = ":{$_SERVER['SERVER_PORT']}"; + if ($_SERVER['SERVER_PORT'] == "80" && $protocol == "http") { + $port = ""; + } + if ($_SERVER['SERVER_PORT'] == "443" && $protocol == "https") { + $port = ""; + } + $complete_url = "{$protocol}://{$_SERVER['SERVER_NAME']}{$port}/{$text}"; + echo "\ndocument.location.href = '{$complete_url}';\n"; + } else { + header("Location: $text"); + } } } /* END compatibility goo with HEAD */ /*fetch menu notices function*/ -if(!function_exists("get_menu_messages")) { - function get_menu_messages(){ +if (!function_exists("get_menu_messages")) { + function get_menu_messages() { global $g,$config; if (are_notices_pending()) { $notices = get_notices(); @@ -82,63 +85,67 @@ if(!function_exists("get_menu_messages")) { ## Get Query Arguments from URL ### foreach ($_REQUEST as $key => $value) { - if ($key != "PHPSESSID") + if ($key != "PHPSESSID") { $requests[] = $key.'='.$value; } - if(is_array($requests)) + } + if (is_array($requests)) { $request_string = implode("&", $requests); + } - if(is_array($notices)) { - $notice_msgs = ""; - $alert_style="style=\'color:#ffffff; filter:Glow(color=#ff0000, strength=12);\' "; - $notice = "".gettext("Acknowledge All Notices").""; - $alert_link="title=\'".gettext("Click to Acknowledge")."\' {$alert_style}"; - $domtt_width=500; - foreach ($notices as $key => $value) { - $date = date("m-d-y H:i:s", $key); - $noticemsg = ($value['notice'] != "" ? $value['notice'] : $value['id']); - $noticemsg = preg_replace("/(\"|\'|\n|<.?\w+>)/i","",$noticemsg); - if ((strlen($noticemsg)* 8) > $domtt_width) - $domtt_width=(strlen($noticemsg) *8); - if ((strlen($noticemsg)* 8) > 900) - $domtt_width= 900; - $alert_action ="onclick=notice_action(\'acknowledge\',\'{$key}\');domTT_close(this);jQuery(this).parent().parent().remove();"; - $notice_msgs .= ""; - } - $notice_msgs .="
{$date}[ ".htmlspecialchars($noticemsg)."]
"; - - $domtt= "onclick=\"domTT_activate(this, event, 'caption', '{$notice}','content', '
{$notice_msgs}', 'trail', false, 'delay', 0, 'fade', 'both', 'fadeMax', 93, 'styleClass', 'niceTitle','width','{$domtt_width}','y',5,'type', 'sticky');\""; - $menu_messages="
\n"; - if(count($notices)==1) - $msg= sprintf("%1$02d",count($notices))." ".gettext("unread notice"); - else - $msg= sprintf("%1$02d",count($notices))." ".gettext("unread notices"); - $menu_messages.="\n"; - $menu_messages.="
\n"; - } + if (is_array($notices)) { + $notice_msgs = ""; + $alert_style="style=\'color:#ffffff; filter:Glow(color=#ff0000, strength=12);\' "; + $notice = "".gettext("Acknowledge All Notices").""; + $alert_link="title=\'".gettext("Click to Acknowledge")."\' {$alert_style}"; + $domtt_width=500; + foreach ($notices as $key => $value) { + $date = date("m-d-y H:i:s", $key); + $noticemsg = ($value['notice'] != "" ? $value['notice'] : $value['id']); + $noticemsg = preg_replace("/(\"|\'|\n|<.?\w+>)/i","",$noticemsg); + if ((strlen($noticemsg)* 8) > $domtt_width) { + $domtt_width=(strlen($noticemsg) *8); + } + if ((strlen($noticemsg)* 8) > 900) { + $domtt_width= 900; + } + $alert_action ="onclick=notice_action(\'acknowledge\',\'{$key}\');domTT_close(this);jQuery(this).parent().parent().remove();"; + $notice_msgs .= ""; + } + $notice_msgs .="
{$date}[ ".htmlspecialchars($noticemsg)."]
"; + + $domtt= "onclick=\"domTT_activate(this, event, 'caption', '{$notice}','content', '
{$notice_msgs}', 'trail', false, 'delay', 0, 'fade', 'both', 'fadeMax', 93, 'styleClass', 'niceTitle','width','{$domtt_width}','y',5,'type', 'sticky');\""; + $menu_messages="
\n"; + if (count($notices)==1) { + $msg= sprintf("%1$02d",count($notices))." ".gettext("unread notice"); + } else { + $msg= sprintf("%1$02d",count($notices))." ".gettext("unread notices"); + } + $menu_messages.="\n"; + $menu_messages.="
\n"; } - else { + } else { $menu_messages='
'; - $menu_messages.=$config['system']['hostname'] . "." . $config['system']['domain']; + $menu_messages.=$config['system']['hostname'] . "." . $config['system']['domain']; $menu_messages.='
'; - } - return ($menu_messages); } + return ($menu_messages); + } } - -if(!function_exists("dom_title")) { - function dom_title($title_msg,$width=NULL){ + +if (!function_exists("dom_title")) { + function dom_title($title_msg,$width=NULL) { $width=preg_replace("/\D+/","",$width); - if (!empty($width)){ + if (!empty($width)) { $width=",'width',$width"; - } - if (!empty($title_msg)){ + } + if (!empty($title_msg)) { $title_msg=preg_replace("/\s+/"," ",$title_msg); - $title_msg=preg_replace("/'/","\'",$title_msg); + $title_msg=preg_replace("/'/","\'",$title_msg); return "onmouseout=\"this.style.color = ''; domTT_mouseout(this, event);\" onmouseover=\"domTT_activate(this, event, 'content', '{$title_msg}', 'trail', true, 'delay', 250, 'fade', 'both', 'fadeMax', 93, 'styleClass', 'niceTitle' $width);\""; - } } } +} /* include all configuration functions */ require_once("interfaces.inc"); require_once("gwlb.inc"); diff --git a/etc/inc/globals.inc b/etc/inc/globals.inc index 1d16e70feb..2194de1639 100644 --- a/etc/inc/globals.inc +++ b/etc/inc/globals.inc @@ -1,34 +1,34 @@ . - All rights reserved. + Originally Part of m0n0wall + Copyright (C) 2003-2004 Manuel Kasper . + All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. pfSense_MODULE: utils @@ -36,7 +36,7 @@ global $g; $g = array( - "base_packages" => "siproxd", + "base_packages" => "siproxd", "event_address" => "unix:///var/run/check_reload_status", "factory_shipped_username" => "admin", "factory_shipped_password" => "pfsense", @@ -77,7 +77,7 @@ $g = array( "nopkg_platforms" => array("cdrom"), "minimum_ram_warning" => "101", "minimum_ram_warning_text" => "128 MB", - "wan_interface_name" => "wan", + "wan_interface_name" => "wan", "nopccard_platforms" => array("wrap", "net48xx"), "xmlrpcbaseurl" => "https://packages.pfsense.org", "captiveportal_path" => "/usr/local/captiveportal", @@ -96,7 +96,7 @@ $iptos = array("lowdelay", "throughput", "reliability"); /* TCP flags */ $tcpflags = array("syn", "ack", "fin", "rst", "psh", "urg", "ece", "cwr"); -if(file_exists("/etc/platform")) { +if (file_exists("/etc/platform")) { $arch = php_uname("m"); $current_version = trim(file_get_contents("{$g['etc_path']}/version")); @@ -113,7 +113,7 @@ if(file_exists("/etc/platform")) { } $g['platform'] = trim(file_get_contents("/etc/platform")); - if($g['platform'] == "nanobsd") { + if ($g['platform'] == "nanobsd") { $g['firmware_update_text']="pfSense-*.img.gz"; $g['hidedownloadbackup'] = true; $g['hidebackupbeforeupgrade'] = true; @@ -124,30 +124,30 @@ if(file_exists("/etc/platform")) { } /* Default sysctls */ -$sysctls = array("net.inet.ip.portrange.first" => "1024", - "net.inet.tcp.blackhole" => "2", - "net.inet.udp.blackhole" => "1", - "net.inet.ip.random_id" => "1", - "net.inet.tcp.drop_synfin" => "1", - "net.inet.ip.redirect" => "1", - "net.inet6.ip6.redirect" => "1", +$sysctls = array("net.inet.ip.portrange.first" => "1024", + "net.inet.tcp.blackhole" => "2", + "net.inet.udp.blackhole" => "1", + "net.inet.ip.random_id" => "1", + "net.inet.tcp.drop_synfin" => "1", + "net.inet.ip.redirect" => "1", + "net.inet6.ip6.redirect" => "1", "net.inet6.ip6.use_tempaddr" => "0", "net.inet6.ip6.prefer_tempaddr" => "0", - "net.inet.tcp.syncookies" => "1", - "net.inet.tcp.recvspace" => "65228", - "net.inet.tcp.sendspace" => "65228", - "net.inet.ip.fastforwarding" => "0", - "net.inet.tcp.delayed_ack" => "0", - "net.inet.udp.maxdgram" => "57344", - "net.link.bridge.pfil_onlyip" => "0", - "net.link.bridge.pfil_member" => "1", - "net.link.bridge.pfil_bridge" => "0", - "net.link.tap.user_open" => "1", - "kern.randompid" => "347", - "net.inet.ip.intr_queue_maxlen" => "1000", - "hw.syscons.kbd_reboot" => "0", - "net.inet.tcp.log_debug" => "0", - "net.inet.tcp.tso" => "1", + "net.inet.tcp.syncookies" => "1", + "net.inet.tcp.recvspace" => "65228", + "net.inet.tcp.sendspace" => "65228", + "net.inet.ip.fastforwarding" => "0", + "net.inet.tcp.delayed_ack" => "0", + "net.inet.udp.maxdgram" => "57344", + "net.link.bridge.pfil_onlyip" => "0", + "net.link.bridge.pfil_member" => "1", + "net.link.bridge.pfil_bridge" => "0", + "net.link.tap.user_open" => "1", + "kern.randompid" => "347", + "net.inet.ip.intr_queue_maxlen" => "1000", + "hw.syscons.kbd_reboot" => "0", + "net.inet.tcp.log_debug" => "0", + "net.inet.tcp.tso" => "1", "net.inet.icmp.icmplim" => "0", "vfs.read_max" => "32", "kern.ipc.maxsockbuf" => "4262144", @@ -169,21 +169,25 @@ $sysctls = array("net.inet.ip.portrange.first" => "1024", ); /* Include override values for the above if needed. If the file doesn't exist, don't try to load it. */ -if (file_exists("/etc/inc/globals_override.inc")) +if (file_exists("/etc/inc/globals_override.inc")) { @include("globals_override.inc"); +} function platform_booting($on_console = false) { global $g; - if ($g['booting'] || file_exists("{$g['varrun_path']}/booting")) - if ($on_console == false || php_sapi_name() != 'fpm-fcgi') + if ($g['booting'] || file_exists("{$g['varrun_path']}/booting")) { + if ($on_console == false || php_sapi_name() != 'fpm-fcgi') { return true; + } + } return false; } -if (file_exists("{$g['cf_conf_path']}/enableserial_force")) +if (file_exists("{$g['cf_conf_path']}/enableserial_force")) { $g['enableserial_force'] = true; +} $config_parsed = false; diff --git a/etc/inc/gmirror.inc b/etc/inc/gmirror.inc index 01d21c4e91..9e26dfbf6c 100644 --- a/etc/inc/gmirror.inc +++ b/etc/inc/gmirror.inc @@ -46,13 +46,14 @@ function gmirror_get_status() { $currentmirror = basename($all[0]); $mirrors[$currentmirror]['name'] = basename($all[0]); $mirrors[$currentmirror]['status'] = $all[1]; - if (!is_array($mirrors[$currentmirror]['components'])) + if (!is_array($mirrors[$currentmirror]['components'])) { $mirrors[$currentmirror]['components'] = array(); + } $mirrors[$currentmirror]['components'][] = $all[2]; } } } - /* Return an hash of mirrors and components */ + /* Return an hash of mirrors and components */ return $mirrors; } @@ -113,8 +114,9 @@ function gmirror_get_unused_consumers() { $all_consumers = array(); foreach ($consumerlist as $cl) { $parts = explode(" ", $cl); - foreach ($parts as $part) + foreach ($parts as $part) { $all_consumers[] = $part; + } } foreach ($disklist as $d) { if (!is_consumer_used($d) && !in_array($d, $all_consumers)) { @@ -134,8 +136,9 @@ function gmirror_get_mirrors() { /* List all consumers for a given mirror */ function gmirror_get_consumers_in_mirror($mirror) { - if (!is_valid_mirror($mirror)) + if (!is_valid_mirror($mirror)) { return array(); + } $consumers = array(); exec("/sbin/gmirror status -s " . escapeshellarg($mirror) . " | /usr/bin/awk '{print $3;}'", $consumers); @@ -144,8 +147,9 @@ function gmirror_get_consumers_in_mirror($mirror) { /* Test if a given consumer is a member of an existing mirror */ function is_consumer_in_mirror($consumer, $mirror) { - if (!is_valid_consumer($consumer) || !is_valid_mirror($mirror)) + if (!is_valid_consumer($consumer) || !is_valid_mirror($mirror)) { return false; + } $mirrorconsumers = gmirror_get_consumers_in_mirror($mirror); return in_array(basename($consumer), $mirrorconsumers); @@ -169,8 +173,9 @@ function is_consumer_used($consumer) { $mirrors = gmirror_get_mirrors(); foreach ($mirrors as $mirror) { $consumers = gmirror_get_consumers_in_mirror($mirror); - if (in_array($consumer, $consumers)) + if (in_array($consumer, $consumers)) { return true; + } } return false; } @@ -188,36 +193,41 @@ function is_valid_consumer($consumer) { /* Remove all disconnected drives from a mirror */ function gmirror_forget_disconnected($mirror) { - if (!is_valid_mirror($mirror)) + if (!is_valid_mirror($mirror)) { return false; + } return mwexec("/sbin/gmirror forget " . escapeshellarg($mirror)); } /* Insert another consumer into a mirror */ function gmirror_insert_consumer($mirror, $consumer) { - if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) + if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) { return false; + } return mwexec("/sbin/gmirror insert " . escapeshellarg($mirror) . " " . escapeshellarg($consumer)); } /* Remove consumer from a mirror and clear its metadata */ function gmirror_remove_consumer($mirror, $consumer) { - if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) + if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) { return false; + } return mwexec("/sbin/gmirror remove " . escapeshellarg($mirror) . " " . escapeshellarg($consumer)); } /* Wipe geom info from drive (if mirror is not running) */ function gmirror_clear_consumer($consumer) { - if (!is_valid_consumer($consumer)) + if (!is_valid_consumer($consumer)) { return false; + } return mwexec("/sbin/gmirror clear " . escapeshellarg($consumer)); } /* Find the balance method used by a given mirror */ function gmirror_get_mirror_balance($mirror) { - if (!is_valid_mirror($mirror)) + if (!is_valid_mirror($mirror)) { return false; + } $balancemethod = ""; exec("/sbin/gmirror list " . escapeshellarg($mirror) . " | /usr/bin/grep '^Balance:' | /usr/bin/awk '{print $2;}'", $balancemethod); return $balancemethod[0]; @@ -226,22 +236,25 @@ function gmirror_get_mirror_balance($mirror) { /* Change balance algorithm of the mirror */ function gmirror_configure_balance($mirror, $balancemethod) { global $balance_methods; - if (!is_valid_mirror($mirror) || !in_array($balancemethod, $balance_methods)) + if (!is_valid_mirror($mirror) || !in_array($balancemethod, $balance_methods)) { return false; + } return mwexec("/sbin/gmirror configure -b " . escapeshellarg($balancemethod) . " " . escapeshellarg($mirror)); } /* Force a mirror member to rebuild */ function gmirror_force_rebuild($mirror, $consumer) { - if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) + if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) { return false; + } return mwexec("/sbin/gmirror rebuild " . escapeshellarg($mirror) . " " . escapeshellarg($consumer)); } /* Show all metadata on the physical consumer */ function gmirror_get_consumer_metadata($consumer) { - if (!is_valid_consumer($consumer)) + if (!is_valid_consumer($consumer)) { return array(); + } $output = ""; exec("/sbin/gmirror dump " . escapeshellarg($consumer), $output); return array_map('trim', $output); @@ -254,8 +267,9 @@ function gmirror_consumer_has_metadata($consumer) { /* Find the mirror to which this consumer belongs */ function gmirror_get_consumer_metadata_mirror($consumer) { - if (!is_valid_consumer($consumer)) + if (!is_valid_consumer($consumer)) { return array(); + } $metadata = gmirror_get_consumer_metadata($consumer); foreach ($metadata as $line) { if (substr($line, 0, 5) == "name:") { @@ -267,22 +281,25 @@ function gmirror_get_consumer_metadata_mirror($consumer) { /* Deactivate consumer, removing it from service in the mirror, but leave metadata intact */ function gmirror_deactivate_consumer($mirror, $consumer) { - if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) + if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) { return false; + } return mwexec("/sbin/gmirror deactivate " . escapeshellarg($mirror) . " " . escapeshellarg($consumer)); } /* Reactivate a deactivated consumer */ function gmirror_activate_consumer($mirror, $consumer) { - if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) + if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) { return false; + } return mwexec("/sbin/gmirror activate " . escapeshellarg($mirror) . " " . escapeshellarg($consumer)); } /* Find the size of the given mirror */ function gmirror_get_mirror_size($mirror) { - if (!is_valid_mirror($mirror)) + if (!is_valid_mirror($mirror)) { return false; + } $mirrorsize = ""; exec("/sbin/gmirror list " . escapeshellarg($mirror) . " | /usr/bin/grep 'Mediasize:' | /usr/bin/head -n 1 | /usr/bin/awk '{print $2;}'", $mirrorsize); return $mirrorsize[0]; @@ -292,8 +309,9 @@ function gmirror_get_mirror_size($mirror) { list output is a little odd, we can't get the output for just the disk, if the disk contains slices those get output also. */ function gmirror_get_all_unused_consumer_sizes_on_disk($disk) { - if (!is_valid_disk($disk) || !is_consumer_unused($disk)) + if (!is_valid_disk($disk) || !is_consumer_unused($disk)) { return array(); + } $output = ""; exec("/sbin/geom part list " . escapeshellarg($disk) . " | /usr/bin/egrep '(Name:|Mediasize:)' | /usr/bin/cut -c4- | /usr/bin/sed -l -e 'N;s/\\nMediasize://;P;D;' | /usr/bin/cut -c7-", $output); if (empty($output)) { @@ -315,8 +333,9 @@ function gmirror_get_all_unused_consumer_sizes_on_disk($disk) { function gmirror_get_unused_consumer_size($consumer) { $consumersizes = gmirror_get_all_unused_consumer_sizes_on_disk($consumer); foreach ($consumersizes as $csize) { - if ($csize['name'] == $consumer) + if ($csize['name'] == $consumer) { return $csize['size']; + } } return -1; } diff --git a/etc/inc/growl.class b/etc/inc/growl.class index 33650ca8d0..8f639e56c6 100644 --- a/etc/inc/growl.class +++ b/etc/inc/growl.class @@ -3,100 +3,100 @@ pfSense_MODULE: notifications */ - class Growl - { - const GROWL_PRIORITY_LOW = -2; - const GROWL_PRIORITY_MODERATE = -1; - const GROWL_PRIORITY_NORMAL = 0; - const GROWL_PRIORITY_HIGH = 1; - const GROWL_PRIORITY_EMERGENCY = 2; + class Growl + { + const GROWL_PRIORITY_LOW = -2; + const GROWL_PRIORITY_MODERATE = -1; + const GROWL_PRIORITY_NORMAL = 0; + const GROWL_PRIORITY_HIGH = 1; + const GROWL_PRIORITY_EMERGENCY = 2; - private $appName; - private $address; - private $notifications; - private $password; - private $port; + private $appName; + private $address; + private $notifications; + private $password; + private $port; - public function __construct($address, $password = '', $app_name = 'PHP-Growl') - { - $this->appName = utf8_encode($app_name); - $this->address = $address; - $this->notifications = array(); - $this->password = $password; - $this->port = 9887; - } - - public function addNotification($name, $enabled = true) - { - $this->notifications[] = array('name' => utf8_encode($name), 'enabled' => $enabled); - } - - public function register() - { - $data = ''; - $defaults = ''; - $num_defaults = 0; - - for($i = 0; $i < count($this->notifications); $i++) - { - $data .= pack('n', strlen($this->notifications[$i]['name'])) . $this->notifications[$i]['name']; - if($this->notifications[$i]['enabled']) - { - $defaults .= pack('c', $i); - $num_defaults++; - } - } - - // pack(Protocol version, type, app name, number of notifications to register) - $data = pack('c2nc2', 1, 0, strlen($this->appName), count($this->notifications), $num_defaults) . $this->appName . $data . $defaults; - $data .= pack('H32', md5($data . $this->password)); - - return $this->send($data); - } - - public function notify($name, $title, $message, $priority = 0, $sticky = false) - { - $name = utf8_encode($name); - $title = utf8_encode($title); - $message = utf8_encode($message); - $priority = intval($priority); - - $flags = ($priority & 7) * 2; - if($priority < 0) $flags |= 8; - if($sticky) $flags |= 1; - - // pack(protocol version, type, priority/sticky flags, notification name length, title length, message length. app name length) - $data = pack('c2n5', 1, 1, $flags, strlen($name), strlen($title), strlen($message), strlen($this->appName)); - $data .= $name . $title . $message . $this->appName; - $data .= pack('H32', md5($data . $this->password)); - - return $this->send($data); - } - - private function send($data) - { - if(function_exists('socket_create') && function_exists('socket_sendto')) - { - $sck = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); - if ($sck) { - socket_sendto($sck, $data, strlen($data), 0x100, $this->address, $this->port); - return true; + public function __construct($address, $password = '', $app_name = 'PHP-Growl') + { + $this->appName = utf8_encode($app_name); + $this->address = $address; + $this->notifications = array(); + $this->password = $password; + $this->port = 9887; } - } - elseif(function_exists('fsockopen')) - { - if ($this->address) { - $fp = @fsockopen('udp://' . $this->address, $this->port); - if ($fp) { - fwrite($fp, $data); - fclose($fp); - return true; + + public function addNotification($name, $enabled = true) + { + $this->notifications[] = array('name' => utf8_encode($name), 'enabled' => $enabled); + } + + public function register() + { + $data = ''; + $defaults = ''; + $num_defaults = 0; + + for ($i = 0; $i < count($this->notifications); $i++) + { + $data .= pack('n', strlen($this->notifications[$i]['name'])) . $this->notifications[$i]['name']; + if ($this->notifications[$i]['enabled']) + { + $defaults .= pack('c', $i); + $num_defaults++; + } } - } - } - return false; - } - } + // pack(Protocol version, type, app name, number of notifications to register) + $data = pack('c2nc2', 1, 0, strlen($this->appName), count($this->notifications), $num_defaults) . $this->appName . $data . $defaults; + $data .= pack('H32', md5($data . $this->password)); + + return $this->send($data); + } + + public function notify($name, $title, $message, $priority = 0, $sticky = false) + { + $name = utf8_encode($name); + $title = utf8_encode($title); + $message = utf8_encode($message); + $priority = intval($priority); + + $flags = ($priority & 7) * 2; + if ($priority < 0) $flags |= 8; + if ($sticky) $flags |= 1; + + // pack(protocol version, type, priority/sticky flags, notification name length, title length, message length. app name length) + $data = pack('c2n5', 1, 1, $flags, strlen($name), strlen($title), strlen($message), strlen($this->appName)); + $data .= $name . $title . $message . $this->appName; + $data .= pack('H32', md5($data . $this->password)); + + return $this->send($data); + } + + private function send($data) + { + if (function_exists('socket_create') && function_exists('socket_sendto')) + { + $sck = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); + if ($sck) { + socket_sendto($sck, $data, strlen($data), 0x100, $this->address, $this->port); + return true; + } + } + elseif (function_exists('fsockopen')) + { + if ($this->address) { + $fp = @fsockopen('udp://' . $this->address, $this->port); + if ($fp) { + fwrite($fp, $data); + fclose($fp); + return true; + } + } + } + + return false; + } + } ?> \ No newline at end of file diff --git a/etc/inc/gwlb.inc b/etc/inc/gwlb.inc index df6a6132b3..a1aedb1b7c 100644 --- a/etc/inc/gwlb.inc +++ b/etc/inc/gwlb.inc @@ -63,8 +63,9 @@ function setup_gateways_monitor() { } $apinger_debug = ""; - if (isset($config['system']['apinger_debug'])) + if (isset($config['system']['apinger_debug'])) { $apinger_debug = "debug on"; + } $apinger_default = return_apinger_defaults(); $apingerconfig = << $gateway) { + foreach ($gateways_arr as $name => $gateway) { /* Do not monitor if such was requested */ - if (isset($gateway['monitor_disable'])) + if (isset($gateway['monitor_disable'])) { continue; + } if (empty($gateway['monitor']) || !is_ipaddr($gateway['monitor'])) { - if (is_ipaddr($gateway['gateway'])) + if (is_ipaddr($gateway['gateway'])) { $gateway['monitor'] = $gateway['gateway']; - else /* No chance to get an ip to monitor skip target. */ + } else { /* No chance to get an ip to monitor skip target. */ continue; + } } /* if the monitor address is already used before, skip */ - if(in_array($gateway['monitor'], $monitor_ips)) + if (in_array($gateway['monitor'], $monitor_ips)) { continue; + } - /* Interface ip is needed since apinger will bind a socket to it. - * However the config GUI should already have checked this and when + /* Interface ip is needed since apinger will bind a socket to it. + * However the config GUI should already have checked this and when * PPoE is used the IP address is set to "dynamic". So using is_ipaddrv4 * or is_ipaddrv6 to identify packet type would be wrong, especially as * further checks (that can cope with the "dynamic" case) are present inside @@ -177,11 +181,13 @@ EOD; */ if ($gateway['ipprotocol'] == "inet") { // This is an IPv4 gateway... $gwifip = find_interface_ip($gateway['interface'], true); - if (!is_ipaddrv4($gwifip)) + if (!is_ipaddrv4($gwifip)) { continue; //Skip this target + } - if ($gwifip == "0.0.0.0") + if ($gwifip == "0.0.0.0") { continue; //Skip this target - the gateway is still waiting for DHCP + } /* * If the gateway is the same as the monitor we do not add a @@ -191,12 +197,13 @@ EOD; */ if (is_ipaddrv4($gateway['gateway']) && $gateway['monitor'] != $gateway['gateway']) { log_error("Removing static route for monitor {$gateway['monitor']} and adding a new route through {$gateway['gateway']}"); - if (interface_isppp_type($gateway['friendlyiface'])) + if (interface_isppp_type($gateway['friendlyiface'])) { mwexec("/sbin/route change -host " . escapeshellarg($gateway['monitor']) . " -iface " . escapeshellarg($gateway['interface']), true); - else + } else { mwexec("/sbin/route change -host " . escapeshellarg($gateway['monitor']) . " " . escapeshellarg($gateway['gateway']), true); + } pfSense_kill_states("0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmp"); } @@ -204,8 +211,9 @@ EOD; if ($gateway['monitor'] == $gateway['gateway']) { /* link locals really need a different src ip */ if (is_linklocal($gateway['gateway'])) { - if (!strpos($gateway['gateway'], '%')) + if (!strpos($gateway['gateway'], '%')) { $gateway['gateway'] .= '%' . $gateway['interface']; + } $gwifip = find_interface_ipv6_ll($gateway['interface'], true); } else { $gwifip = find_interface_ipv6($gateway['interface'], true); @@ -220,13 +228,16 @@ EOD; } /* Make sure srcip and target have scope defined when they are ll */ - if (is_linklocal($gwifip) && !strpos($gwifip, '%')) + if (is_linklocal($gwifip) && !strpos($gwifip, '%')) { $gwifip .= '%' . $gateway['interface']; - if (is_linklocal($gateway['monitor']) && !strpos($gateway['monitor'], '%')) + } + if (is_linklocal($gateway['monitor']) && !strpos($gateway['monitor'], '%')) { $gateway['monitor'] .= "%{$gateway['interface']}"; + } - if (!is_ipaddrv6($gwifip)) + if (!is_ipaddrv6($gwifip)) { continue; //Skip this target + } /* * If the gateway is the same as the monitor we do not add a @@ -236,17 +247,19 @@ EOD; */ if ($gateway['gateway'] != $gateway['monitor']) { log_error("Removing static route for monitor {$gateway['monitor']} and adding a new route through {$gateway['gateway']}"); - if (interface_isppp_type($gateway['friendlyiface'])) + if (interface_isppp_type($gateway['friendlyiface'])) { mwexec("/sbin/route change -host -inet6 " . escapeshellarg($gateway['monitor']) . " -iface " . escapeshellarg($gateway['interface']), true); - else + } else { mwexec("/sbin/route change -host -inet6 " . escapeshellarg($gateway['monitor']) . " " . escapeshellarg($gateway['gateway']), true); + } pfSense_kill_states("::0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmpv6"); } - } else + } else { continue; + } $monitor_ips[] = $gateway['monitor']; $apingercfg = "target \"{$gateway['monitor']}\" {\n"; @@ -261,7 +274,7 @@ EOD; $apingercfg .= " interval " . $interval . "s\n"; } - ## How many replies should be used to compute average delay + ## How many replies should be used to compute average delay ## for controlling "delay" alarms if (!empty($gateway['avg_delay_samples']) && is_numeric($gateway['avg_delay_samples'])) { $avg_delay_samples = intval($gateway['avg_delay_samples']); # Restrict to Integer @@ -273,18 +286,24 @@ EOD; ## How many probes should be used to compute average loss if (!empty($gateway['avg_loss_samples']) && is_numeric($gateway['avg_loss_samples'])) { $avg_loss_samples = intval($gateway['avg_loss_samples']); # Restrict to Integer - if ($avg_loss_samples < 1) $avg_loss_samples = 1; # Minimum - if ($avg_loss_samples != $apinger_default['avg_loss_samples']) # If not default value + if ($avg_loss_samples < 1) { + $avg_loss_samples = 1; # Minimum + } + if ($avg_loss_samples != $apinger_default['avg_loss_samples']) { # If not default value $apingercfg .= " avg_loss_samples " . $avg_loss_samples . "\n"; + } } ## The delay (in samples) after which loss is computed ## without this delays larger than interval would be treated as loss if (!empty($gateway['avg_loss_delay_samples']) && is_numeric($gateway['avg_loss_delay_samples'])) { $avg_loss_delay_samples = intval($gateway['avg_loss_delay_samples']); # Restrict to Integer - if ($avg_loss_delay_samples < 1) $avg_loss_delay_samples = 1; # Minimum - if ($avg_loss_delay_samples != $apinger_default['avg_loss_delay_samples']) # If not default value + if ($avg_loss_delay_samples < 1) { + $avg_loss_delay_samples = 1; # Minimum + } + if ($avg_loss_delay_samples != $apinger_default['avg_loss_delay_samples']) { # If not default value $apingercfg .= " avg_loss_delay_samples " . $avg_loss_delay_samples . "\n"; + } } $alarms = ""; @@ -298,8 +317,9 @@ EOD; $alarms .= "\"{$name}loss\""; $override = true; } else { - if ($override == true) + if ($override == true) { $alarms .= ","; + } $alarms .= "\"loss\""; $override = true; } @@ -308,13 +328,15 @@ EOD; $alarmscfg .= "\tdelay_low {$gateway['latencylow']}ms\n"; $alarmscfg .= "\tdelay_high {$gateway['latencyhigh']}ms\n"; $alarmscfg .= "}\n"; - if ($override == true) + if ($override == true) { $alarms .= ","; + } $alarms .= "\"{$name}delay\""; $override = true; } else { - if ($override == true) + if ($override == true) { $alarms .= ","; + } $alarms .= "\"delay\""; $override = true; } @@ -322,21 +344,25 @@ EOD; $alarmscfg .= "alarm down \"{$name}down\" {\n"; $alarmscfg .= "\ttime {$gateway['down']}s\n"; $alarmscfg .= "}\n"; - if ($override == true) + if ($override == true) { $alarms .= ","; + } $alarms .= "\"{$name}down\""; $override = true; } else { - if ($override == true) + if ($override == true) { $alarms .= ","; + } $alarms .= "\"down\""; $override = true; } - if ($override == true) + if ($override == true) { $apingercfg .= "\talarms override {$alarms};\n"; + } - if (isset($gateway['force_down'])) + if (isset($gateway['force_down'])) { $apingercfg .= "\tforce_down on\n"; + } $apingercfg .= " rrd file \"{$g['vardb_path']}/rrd/{$gateway['name']}-quality.rrd\"\n"; $apingercfg .= "}\n"; @@ -345,18 +371,18 @@ EOD; $apingerconfig .= $alarmscfg; $apingerconfig .= $apingercfg; - # Create gateway quality RRD with settings more suitable for pfSense graph set, - # since apinger uses default step (300; 5 minutes) and other settings that don't + # Create gateway quality RRD with settings more suitable for pfSense graph set, + # since apinger uses default step (300; 5 minutes) and other settings that don't # match the pfSense gateway quality graph set. create_gateway_quality_rrd("{$g['vardb_path']}/rrd/{$gateway['name']}-quality.rrd"); } @file_put_contents("{$g['varetc_path']}/apinger.conf", $apingerconfig); unset($apingerconfig); - /* Restart apinger process */ - if (isvalidpid("{$g['varrun_path']}/apinger.pid")) + /* Restart apinger process */ + if (isvalidpid("{$g['varrun_path']}/apinger.pid")) { sigkillbypid("{$g['varrun_path']}/apinger.pid", "HUP"); - else { + } else { /* start a new apinger process */ @unlink("{$g['varrun_path']}/apinger.status"); sleep(1); @@ -374,20 +400,23 @@ function return_gateways_status($byname = false) { $apingerstatus = array(); /* Always get the latest status from apinger */ - if (file_exists("{$g['varrun_path']}/apinger.pid")) - sigkillbypid("{$g['varrun_path']}/apinger.pid", "USR1"); + if (file_exists("{$g['varrun_path']}/apinger.pid")) { + sigkillbypid("{$g['varrun_path']}/apinger.pid", "USR1"); + } if (file_exists("{$g['varrun_path']}/apinger.status")) { $apingerstatus = file("{$g['varrun_path']}/apinger.status"); - } else + } else { $apingerstatus = array(); + } $status = array(); - foreach($apingerstatus as $line) { + foreach ($apingerstatus as $line) { $info = explode("|", $line); - if ($byname == false) + if ($byname == false) { $target = $info[0]; - else + } else { $target = $info[2]; + } $status[$target] = array(); $status[$target]['monitorip'] = $info[0]; @@ -402,26 +431,29 @@ function return_gateways_status($byname = false) { /* tack on any gateways that have monitoring disabled * or are down, which could cause gateway groups to fail */ $gateways_arr = return_gateways_array(); - foreach($gateways_arr as $gwitem) { - if(!isset($gwitem['monitor_disable'])) + foreach ($gateways_arr as $gwitem) { + if (!isset($gwitem['monitor_disable'])) { continue; - if(!is_ipaddr($gwitem['monitorip'])) { + } + if (!is_ipaddr($gwitem['monitorip'])) { $realif = $gwitem['interface']; $tgtip = get_interface_gateway($realif); - if (!is_ipaddr($tgtip)) + if (!is_ipaddr($tgtip)) { $tgtip = "none"; + } $srcip = find_interface_ip($realif); } else { $tgtip = $gwitem['monitorip']; $srcip = find_interface_ip($realif); } - if($byname == true) + if ($byname == true) { $target = $gwitem['name']; - else + } else { $target = $tgtip; + } /* failsafe for down interfaces */ - if($target == "none") { + if ($target == "none") { $target = $gwitem['name']; $status[$target]['name'] = $gwitem['name']; $status[$target]['lastcheck'] = date('r'); @@ -464,16 +496,18 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive $i++; if (empty($config['interfaces'][$gateway['interface']])) { - if ($inactive === false) + if ($inactive === false) { continue; - else + } else { $gateway['inactive'] = true; + } } $wancfg = $config['interfaces'][$gateway['interface']]; /* skip disabled interfaces */ - if ($disabled === false && (!isset($wancfg['enable']))) + if ($disabled === false && (!isset($wancfg['enable']))) { continue; + } /* if the gateway is dynamic and we can find the IPv4, Great! */ if (empty($gateway['gateway']) || $gateway['gateway'] == "dynamic") { @@ -481,8 +515,9 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive /* we know which interfaces is dynamic, this should be made a function */ $gateway['gateway'] = get_interface_gateway($gateway['interface']); /* no IP address found, set to dynamic */ - if (!is_ipaddrv4($gateway['gateway'])) + if (!is_ipaddrv4($gateway['gateway'])) { $gateway['gateway'] = "dynamic"; + } $gateway['dynamic'] = true; } @@ -491,23 +526,26 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive /* we know which interfaces is dynamic, this should be made a function, and for v6 too */ $gateway['gateway'] = get_interface_gateway_v6($gateway['interface']); /* no IPv6 address found, set to dynamic */ - if (!is_ipaddrv6($gateway['gateway'])) + if (!is_ipaddrv6($gateway['gateway'])) { $gateway['gateway'] = "dynamic"; + } $gateway['dynamic'] = true; } } else { /* getting this detection right is hard at this point because we still don't * store the address family in the gateway item */ - if (is_ipaddrv4($gateway['gateway'])) + if (is_ipaddrv4($gateway['gateway'])) { $gateway['ipprotocol'] = "inet"; - else if(is_ipaddrv6($gateway['gateway'])) + } else if (is_ipaddrv6($gateway['gateway'])) { $gateway['ipprotocol'] = "inet6"; + } } - if (isset($gateway['monitor_disable'])) + if (isset($gateway['monitor_disable'])) { $gateway['monitor_disable'] = true; - else if (empty($gateway['monitor'])) + } else if (empty($gateway['monitor'])) { $gateway['monitor'] = $gateway['gateway']; + } $gateway['friendlyiface'] = $gateway['interface']; @@ -538,38 +576,45 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive $gateways_arr_temp[$gateway['name']] = $gateway; /* skip disabled gateways if the caller has not asked for them to be returned. */ - if (!($disabled === false && isset($gateway['disabled']))) + if (!($disabled === false && isset($gateway['disabled']))) { $gateways_arr[$gateway['name']] = $gateway; + } } } unset($gateway); /* Loop through all interfaces with a gateway and add it to a array */ - if ($disabled == false) + if ($disabled == false) { $iflist = get_configured_interface_with_descr(); - else + } else { $iflist = get_configured_interface_with_descr(false, true); + } /* Process/add dynamic v4 gateways. */ - foreach($iflist as $ifname => $friendly ) { - if(! interface_has_gateway($ifname)) + foreach ($iflist as $ifname => $friendly ) { + if (! interface_has_gateway($ifname)) { continue; + } - if (empty($config['interfaces'][$ifname])) + if (empty($config['interfaces'][$ifname])) { continue; + } $ifcfg = &$config['interfaces'][$ifname]; - if(!isset($ifcfg['enable'])) + if (!isset($ifcfg['enable'])) { continue; + } - if(!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr'])) + if (!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr'])) { continue; + } - if (isset($interfaces_v4[$ifname])) + if (isset($interfaces_v4[$ifname])) { continue; + } $ctype = ""; - switch($ifcfg['ipaddr']) { + switch ($ifcfg['ipaddr']) { case "dhcp": case "pppoe": case "pptp": @@ -585,15 +630,17 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive if (is_array($config['openvpn']['openvpn-server'])) { foreach ($config['openvpn']['openvpn-server'] as & $ovpnserverconf) { if ($ovpnserverconf['vpnid'] == $ovpnid) { - if ($ovpnserverconf['dev_mode'] == "tap") + if ($ovpnserverconf['dev_mode'] == "tap") { continue 3; + } } } } } $ctype = "VPNv4"; - } else if ($tunnelif == "gif" || $tunnelif == "gre") + } else if ($tunnelif == "gif" || $tunnelif == "gre") { $ctype = "TUNNELv4"; + } break; } $ctype = "_". strtoupper($ctype); @@ -613,18 +660,21 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive $found_defaultv4 = 1; } /* Loopback dummy for dynamic interfaces without a IP */ - if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true) + if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true) { $gateway['gateway'] = "dynamic"; - - /* automatically skip known static and dynamic gateways that were previously processed */ - foreach($gateways_arr_temp as $gateway_item) { - if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) || - ($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) - continue 2; } - if (is_ipaddrv4($gateway['gateway'])) + /* automatically skip known static and dynamic gateways that were previously processed */ + foreach ($gateways_arr_temp as $gateway_item) { + if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) || + ($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) { + continue 2; + } + } + + if (is_ipaddrv4($gateway['gateway'])) { $gateway['monitor'] = $gateway['gateway']; + } $gateway['descr'] = "Interface {$friendly}{$ctype} Gateway"; $gateways_arr[$gateway['name']] = $gateway; @@ -632,29 +682,35 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive unset($gateway); /* Process/add dynamic v6 gateways. */ - foreach($iflist as $ifname => $friendly ) { + foreach ($iflist as $ifname => $friendly ) { /* If the user has disabled IPv6, they probably don't want any IPv6 gateways. */ - if (!isset($config['system']['ipv6allow'])) + if (!isset($config['system']['ipv6allow'])) { break; + } - if(! interface_has_gatewayv6($ifname)) + if (! interface_has_gatewayv6($ifname)) { continue; + } - if (empty($config['interfaces'][$ifname])) + if (empty($config['interfaces'][$ifname])) { continue; + } $ifcfg = &$config['interfaces'][$ifname]; - if(!isset($ifcfg['enable'])) + if (!isset($ifcfg['enable'])) { continue; + } - if(!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) + if (!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) { continue; + } - if(isset($interfaces_v6[$ifname])) + if (isset($interfaces_v6[$ifname])) { continue; + } $ctype = ""; - switch($ifcfg['ipaddrv6']) { + switch ($ifcfg['ipaddrv6']) { case "slaac": case "dhcp6": case "6to4": @@ -670,15 +726,17 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive if (is_array($config['openvpn']['openvpn-server'])) { foreach ($config['openvpn']['openvpn-server'] as & $ovpnserverconf) { if ($ovpnserverconf['vpnid'] == $ovpnid) { - if ($ovpnserverconf['dev_mode'] == "tap") + if ($ovpnserverconf['dev_mode'] == "tap") { continue 3; + } } } } } $ctype = "VPNv6"; - } else if ($tunnelif == "gif" || $tunnelif == "gre") + } else if ($tunnelif == "gif" || $tunnelif == "gre") { $ctype = "TUNNELv6"; + } break; } $ctype = "_". strtoupper($ctype); @@ -688,7 +746,7 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive $gateway['ipprotocol'] = "inet6"; $gateway['gateway'] = get_interface_gateway_v6($ifname, $gateway['dynamic']); $gateway['interface'] = get_real_interface($ifname, "inet6"); - switch($ifcfg['ipaddrv6']) { + switch ($ifcfg['ipaddrv6']) { case "6rd": case "6to4": $gateway['dynamic'] = "default"; @@ -705,18 +763,21 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive } /* Loopback dummy for dynamic interfaces without a IP */ - if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true) + if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true) { $gateway['gateway'] = "dynamic"; - - /* automatically skip known static and dynamic gateways that were previously processed */ - foreach($gateways_arr_temp as $gateway_item) { - if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) || - ($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) - continue 2; } - if (is_ipaddrv6($gateway['gateway'])) + /* automatically skip known static and dynamic gateways that were previously processed */ + foreach ($gateways_arr_temp as $gateway_item) { + if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) || + ($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) { + continue 2; + } + } + + if (is_ipaddrv6($gateway['gateway'])) { $gateway['monitor'] = $gateway['gateway']; + } $gateway['descr'] = "Interface {$friendly}{$ctype} Gateway"; $gateways_arr[$gateway['name']] = $gateway; @@ -744,7 +805,7 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive } } - if($localhost === true) { + if ($localhost === true) { /* attach localhost for Null routes */ $gwlo4 = array(); $gwlo4['name'] = "Null4"; @@ -776,27 +837,32 @@ function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) { if (($gwsttng['ipprotocol'] == $ipprotocol) && isset($gwsttng['defaultgw'])) { $dfltgwfound = true; $dfltgwname = $gwname; - if (!isset($gwsttng['monitor_disable']) && stristr($gateways_status[$gwname]['status'], "down")) + if (!isset($gwsttng['monitor_disable']) && stristr($gateways_status[$gwname]['status'], "down")) { $dfltgwdown = true; + } } /* Keep a record of the last up gateway */ /* XXX: Blacklist lan for now since it might cause issues to those who have a gateway set for it */ - if (empty($upgw) && ($gwsttng['ipprotocol'] == $ipprotocol) && (isset($gwsttng['monitor_disable']) || !stristr($gateways_status[$gwname]['status'], "down")) && $gwsttng[$gwname]['friendlyiface'] != "lan") + if (empty($upgw) && ($gwsttng['ipprotocol'] == $ipprotocol) && (isset($gwsttng['monitor_disable']) || !stristr($gateways_status[$gwname]['status'], "down")) && $gwsttng[$gwname]['friendlyiface'] != "lan") { $upgw = $gwname; - if ($dfltgwdown == true && !empty($upgw)) + } + if ($dfltgwdown == true && !empty($upgw)) { break; + } } if ($dfltgwfound == false) { $gwname = convert_friendly_interface_to_friendly_descr("wan"); - if (!empty($gateways_status[$gwname]) && stristr($gateways_status[$gwname]['status'], "down")) + if (!empty($gateways_status[$gwname]) && stristr($gateways_status[$gwname]['status'], "down")) { $dfltgwdown = true; + } } if ($dfltgwdown == true && !empty($upgw)) { - if ($gateways_arr[$upgw]['gateway'] == "dynamic") + if ($gateways_arr[$upgw]['gateway'] == "dynamic") { $gateways_arr[$upgw]['gateway'] = get_interface_gateway($gateways_arr[$upgw]['friendlyiface']); + } if (is_ipaddr($gateways_arr[$upgw]['gateway'])) { log_error("Default gateway down setting {$upgw} as default!"); - if(is_ipaddrv6($gateways_arr[$upgw]['gateway'])) { + if (is_ipaddrv6($gateways_arr[$upgw]['gateway'])) { $inetfamily = "-inet6"; } else { $inetfamily = "-inet"; @@ -805,12 +871,15 @@ function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) { } } else if (!empty($dfltgwname)) { $defaultgw = trim(exec("/sbin/route -n get -{$ipprotocol} default | /usr/bin/awk '/gateway:/ {print $2}'"), " \n"); - if ($ipprotocol == 'inet6' && !is_ipaddrv6($gateways_arr[$dfltgwname]['gateway'])) + if ($ipprotocol == 'inet6' && !is_ipaddrv6($gateways_arr[$dfltgwname]['gateway'])) { return; - if ($ipprotocol == 'inet' && !is_ipaddrv4($gateways_arr[$dfltgwname]['gateway'])) + } + if ($ipprotocol == 'inet' && !is_ipaddrv4($gateways_arr[$dfltgwname]['gateway'])) { return; - if ($defaultgw != $gateways_arr[$dfltgwname]['gateway']) + } + if ($defaultgw != $gateways_arr[$dfltgwname]['gateway']) { mwexec("/sbin/route change -{$ipprotocol} default {$gateways_arr[$dfltgwname]['gateway']}"); + } } } @@ -841,14 +910,16 @@ function return_gateway_groups_array() { list($gwname, $tier, $vipname) = explode("|", $item); if (is_ipaddr($carplist[$vipname])) { - if (!is_array($gwvip_arr[$group['name']])) + if (!is_array($gwvip_arr[$group['name']])) { $gwvip_arr[$group['name']] = array(); + } $gwvip_arr[$group['name']][$gwname] = $vipname; } /* Do it here rather than reiterating again the group in case no member is up. */ - if (!is_array($backupplan[$tier])) + if (!is_array($backupplan[$tier])) { $backupplan[$tier] = array(); + } $backupplan[$tier][] = $gwname; /* check if the gateway is available before adding it to the array */ @@ -873,12 +944,14 @@ function return_gateway_groups_array() { notify_via_smtp($msg); } else { /* Online add member */ - if (!is_array($tiers[$tier])) + if (!is_array($tiers[$tier])) { $tiers[$tier] = array(); + } $tiers[$tier][] = $gwname; } - } else if (isset($gateways_arr[$gwname]['monitor_disable'])) + } else if (isset($gateways_arr[$gwname]['monitor_disable'])) { $tiers[$tier][] = $gwname; + } } $tiers_count = count($tiers); if ($tiers_count == 0) { @@ -903,10 +976,11 @@ function return_gateway_groups_array() { $gateway = $gateways_arr[$member]; $int = $gateway['interface']; $gatewayip = ""; - if(is_ipaddr($gateway['gateway'])) + if (is_ipaddr($gateway['gateway'])) { $gatewayip = $gateway['gateway']; - else if (!empty($int)) + } else if (!empty($int)) { $gatewayip = get_interface_gateway($gateway['friendlyiface']); + } if (!empty($int)) { $gateway_groups_array[$group['name']]['ipprotocol'] = $gateway['ipprotocol']; @@ -915,18 +989,20 @@ function return_gateway_groups_array() { $groupmember['int'] = $int; $groupmember['gwip'] = $gatewayip; $groupmember['weight'] = isset($gateway['weight']) ? $gateway['weight'] : 1; - if (is_array($gwvip_arr[$group['name']])&& !empty($gwvip_arr[$group['name']][$member])) + if (is_array($gwvip_arr[$group['name']])&& !empty($gwvip_arr[$group['name']][$member])) { $groupmember['vip'] = $gwvip_arr[$group['name']][$member]; + } $gateway_groups_array[$group['name']][] = $groupmember; } } } } /* we should have the 1st available tier now, exit stage left */ - if (count($gateway_groups_array[$group['name']]) > 0) + if (count($gateway_groups_array[$group['name']]) > 0) { break; - else + } else { log_error("GATEWAYS: Group {$group['name']} did not have any gateways up on tier {$tieridx}!"); + } } } } @@ -937,25 +1013,27 @@ function return_gateway_groups_array() { /* Update DHCP WAN Interface ip address in gateway group item */ function dhclient_update_gateway_groups_defaultroute($interface = "wan") { global $config, $g; - foreach($config['gateways']['gateway_item'] as & $gw) { - if($gw['interface'] == $interface) { + foreach ($config['gateways']['gateway_item'] as & $gw) { + if ($gw['interface'] == $interface) { $current_gw = get_interface_gateway($interface); - if($gw['gateway'] <> $current_gw) { + if ($gw['gateway'] <> $current_gw) { $gw['gateway'] = $current_gw; $changed = true; } } } - if($changed && $current_gw) + if ($changed && $current_gw) { write_config(sprintf(gettext('Updating gateway group gateway for %1$s - new gateway is %2$s'), $interfac, $current_gw)); + } } function lookup_gateway_ip_by_name($name) { $gateways_arr = return_gateways_array(false, true); foreach ($gateways_arr as $gname => $gw) { - if ($gw['name'] === $name || $gname === $name) + if ($gw['name'] === $name || $gname === $name) { return $gw['gateway']; + } } return false; @@ -966,8 +1044,9 @@ function lookup_gateway_monitor_ip_by_name($name) { $gateways_arr = return_gateways_array(false, true); if (!empty($gateways_arr[$name])) { $gateway = $gateways_arr[$name]; - if(!is_ipaddr($gateway['monitor'])) + if (!is_ipaddr($gateway['monitor'])) { return $gateway['gateway']; + } return $gateway['monitor']; } @@ -989,14 +1068,15 @@ function lookup_gateway_interface_by_name($name) { function get_interface_gateway($interface, &$dynamic = false) { global $config, $g; - if (substr($interface, 0, 4) == '_vip') + if (substr($interface, 0, 4) == '_vip') { $interface = get_configured_carp_interface_list($interface, 'inet', 'iface'); + } $gw = NULL; $gwcfg = $config['interfaces'][$interface]; if (!empty($gwcfg['gateway']) && is_array($config['gateways']['gateway_item'])) { - foreach($config['gateways']['gateway_item'] as $gateway) { - if(($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) { + foreach ($config['gateways']['gateway_item'] as $gateway) { + if (($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) { $gw = $gateway['gateway']; break; } @@ -1007,11 +1087,12 @@ function get_interface_gateway($interface, &$dynamic = false) { if (($gw == NULL || !is_ipaddrv4($gw)) && !is_ipaddrv4($gwcfg['ipaddr'])) { $realif = get_real_interface($interface); if (file_exists("{$g['tmp_path']}/{$realif}_router")) { - $gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n"); + $gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n"); $dynamic = true; } - if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw")) + if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw")) { $dynamic = "default"; + } } @@ -1022,14 +1103,15 @@ function get_interface_gateway($interface, &$dynamic = false) { function get_interface_gateway_v6($interface, &$dynamic = false) { global $config, $g; - if (substr($interface, 0, 4) == '_vip') + if (substr($interface, 0, 4) == '_vip') { $interface = get_configured_carp_interface_list($interface, 'inet6', 'iface'); + } $gw = NULL; $gwcfg = $config['interfaces'][$interface]; if (!empty($gwcfg['gatewayv6']) && is_array($config['gateways']['gateway_item'])) { - foreach($config['gateways']['gateway_item'] as $gateway) { - if(($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) { + foreach ($config['gateways']['gateway_item'] as $gateway) { + if (($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) { $gw = $gateway['gateway']; break; } @@ -1038,14 +1120,14 @@ function get_interface_gateway_v6($interface, &$dynamic = false) { // for dynamic interfaces we handle them through the $interface_router file. if (($gw == NULL || !is_ipaddrv6($gw)) && !is_ipaddrv6($gwcfg['ipaddrv6'])) { - $realif = get_real_interface($interface); - if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) { - $gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n"); - $dynamic = true; - } - if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6")) - $dynamic = "default"; - + $realif = get_real_interface($interface); + if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) { + $gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n"); + $dynamic = true; + } + if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6")) { + $dynamic = "default"; + } } /* return gateway */ return ($gw); @@ -1059,29 +1141,37 @@ function validate_address_family($ipaddr, $gwname) { $v4gw = false; $v6gw = false; - if(is_ipaddrv4($ipaddr)) + if (is_ipaddrv4($ipaddr)) { $v4ip = true; - if(is_ipaddrv6($ipaddr)) + } + if (is_ipaddrv6($ipaddr)) { $v6ip = true; - if(is_ipaddrv4($gwname)) + } + if (is_ipaddrv4($gwname)) { $v4gw = true; - if(is_ipaddrv6($gwname)) + } + if (is_ipaddrv6($gwname)) { $v6gw = true; + } - if($v4ip && $v4gw) + if ($v4ip && $v4gw) { return true; - if($v6ip && $v6gw) + } + if ($v6ip && $v6gw) { return true; + } /* still no match, carry on, lookup gateways */ - if(is_ipaddrv4(lookup_gateway_ip_by_name($gwname))) + if (is_ipaddrv4(lookup_gateway_ip_by_name($gwname))) { $v4gw = true; - if(is_ipaddrv6(lookup_gateway_ip_by_name($gwname))) + } + if (is_ipaddrv6(lookup_gateway_ip_by_name($gwname))) { $v6gw = true; + } $gw_array = return_gateways_array(); - if(is_array($gw_array[$gwname])) { - switch($gw_array[$gwname]['ipprotocol']) { + if (is_array($gw_array[$gwname])) { + switch ($gw_array[$gwname]['ipprotocol']) { case "inet": $v4gw = true; break; @@ -1091,10 +1181,12 @@ function validate_address_family($ipaddr, $gwname) { } } - if($v4ip && $v4gw) + if ($v4ip && $v4gw) { return true; - if($v6ip && $v6gw) + } + if ($v6ip && $v6gw) { return true; + } return false; } @@ -1103,15 +1195,16 @@ function validate_address_family($ipaddr, $gwname) { function interface_gateway_group_member($interface) { global $config; - if (is_array($config['gateways']['gateway_group'])) + if (is_array($config['gateways']['gateway_group'])) { $groups = $config['gateways']['gateway_group']; - else + } else { return false; + } $gateways_arr = return_gateways_array(false, true); - foreach($groups as $group) { - if(is_array($group['item'])) { - foreach($group['item'] as $item) { + foreach ($groups as $group) { + if (is_array($group['item'])) { + foreach ($group['item'] as $item) { $elements = explode("|", $item); $gwname = $elements[0]; if ($interface == $gateways_arr[$gwname]['interface']) { @@ -1129,19 +1222,21 @@ function interface_gateway_group_member($interface) { function gateway_is_gwgroup_member($name) { global $config; - if (is_array($config['gateways']['gateway_group'])) + if (is_array($config['gateways']['gateway_group'])) { $groups = $config['gateways']['gateway_group']; - else + } else { return false; + } $members = array(); - foreach($groups as $group) { + foreach ($groups as $group) { if (is_array($group['item'])) { - foreach($group['item'] as $item) { + foreach ($group['item'] as $item) { $elements = explode("|", $item); $gwname = $elements[0]; - if ($name == $elements[0]) + if ($name == $elements[0]) { $members[] = $group['name']; + } } } } From ae52d165da3aa89188b3806643cf3d5b4b207bd7 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Thu, 26 Feb 2015 10:12:56 -0300 Subject: [PATCH 136/257] Fix indent and remove some unecessary () --- etc/inc/auth.inc | 10 +++++----- etc/inc/captiveportal.inc | 8 ++++---- etc/inc/certs.inc | 20 ++++++++++---------- etc/inc/config.console.inc | 6 +++--- etc/inc/dyndns.class | 4 ++-- 5 files changed, 24 insertions(+), 24 deletions(-) diff --git a/etc/inc/auth.inc b/etc/inc/auth.inc index a19a20cbbc..2cb2ff1ee4 100644 --- a/etc/inc/auth.inc +++ b/etc/inc/auth.inc @@ -73,11 +73,11 @@ if (function_exists("display_error_form") && !isset($config['system']['webgui'][ $http_host = $http_host[0]; } if (is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or - strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") { + strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") { $found_host = true; } if (strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or - strcasecmp($http_host, $config['system']['hostname']) == 0) { + strcasecmp($http_host, $config['system']['hostname']) == 0) { $found_host = true; } @@ -134,8 +134,8 @@ if (function_exists("display_error_form") && !isset($config['system']['webgui'][ $referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST); $referrer_host = str_replace(array("[", "]"), "", $referrer_host); if ($referrer_host) { - if (strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 - || strcasecmp($referrer_host, $config['system']['hostname']) == 0) { + if (strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 || + strcasecmp($referrer_host, $config['system']['hostname']) == 0) { $found_host = true; } @@ -1492,7 +1492,7 @@ function session_auth() { if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) { $authcfg = auth_get_authserver($config['system']['webgui']['authmode']); if (authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg) || - authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) { + authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) { // Generate a new id to avoid session fixation session_regenerate_id(); $_SESSION['Logged_In'] = "True"; diff --git a/etc/inc/captiveportal.inc b/etc/inc/captiveportal.inc index 9608ac10b5..002195f102 100644 --- a/etc/inc/captiveportal.inc +++ b/etc/inc/captiveportal.inc @@ -656,7 +656,7 @@ function captiveportal_prune_old() { /* Is there any job to do? */ if (!$timeout && !$idletimeout && !isset($cpcfg['reauthenticate']) && - !isset($cpcfg['radiussession_timeout']) && !isset($vcpcfg['enable'])) { + !isset($cpcfg['radiussession_timeout']) && !isset($vcpcfg['enable'])) { return; } @@ -1232,8 +1232,8 @@ function captiveportal_init_radius_servers() { global $config, $g, $cpzone; /* generate radius server database */ - if ($config['captiveportal'][$cpzone]['radiusip'] && (!isset($config['captiveportal'][$cpzone]['auth_method']) || - ($config['captiveportal'][$cpzone]['auth_method'] == "radius"))) { + if ($config['captiveportal'][$cpzone]['radiusip'] && + (!isset($config['captiveportal'][$cpzone]['auth_method']) || $config['captiveportal'][$cpzone]['auth_method'] == "radius")) { $radiusip = $config['captiveportal'][$cpzone]['radiusip']; $radiusip2 = ($config['captiveportal'][$cpzone]['radiusip2']) ? $config['captiveportal'][$cpzone]['radiusip2'] : null; $radiusip3 = ($config['captiveportal'][$cpzone]['radiusip3']) ? $config['captiveportal'][$cpzone]['radiusip3'] : null; @@ -2316,7 +2316,7 @@ function captiveportal_blocked_mac($mac) { foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac) { if (($passthrumac['action'] == 'block') && - ($passthrumac['mac'] == strtolower($mac))) { + ($passthrumac['mac'] == strtolower($mac))) { return true; } } diff --git a/etc/inc/certs.inc b/etc/inc/certs.inc index ce320a98e4..0bdc1fcddd 100644 --- a/etc/inc/certs.inc +++ b/etc/inc/certs.inc @@ -223,7 +223,7 @@ function ca_create(& $ca, $keylen, $lifetime, $dn, $digest_alg = "sha256") { // export our certificate data if (!openssl_pkey_export($res_key, $str_key) || - !openssl_x509_export($res_crt, $str_crt)) { + !openssl_x509_export($res_crt, $str_crt)) { return false; } @@ -276,7 +276,7 @@ function ca_inter_create(& $ca, $keylen, $lifetime, $dn, $caref, $digest_alg = " // export our certificate data if (!openssl_pkey_export($res_key, $str_key) || - !openssl_x509_export($res_crt, $str_crt)) { + !openssl_x509_export($res_crt, $str_crt)) { return false; } @@ -385,7 +385,7 @@ function cert_create(& $cert, $caref, $keylen, $lifetime, $dn, $type="user", $di // export our certificate data if (!openssl_pkey_export($res_key, $str_key) || - !openssl_x509_export($res_crt, $str_crt)) { + !openssl_x509_export($res_crt, $str_crt)) { return false; } @@ -419,7 +419,7 @@ function csr_generate(& $cert, $keylen, $dn, $digest_alg = "sha256") { // export our request data if (!openssl_pkey_export($res_key, $str_key) || - !openssl_csr_export($res_csr, $str_csr)) { + !openssl_csr_export($res_csr, $str_csr)) { return false; } @@ -664,8 +664,8 @@ function is_ipsec_cert($certref) { function is_webgui_cert($certref) { global $config; - if (($config['system']['webgui']['ssl-certref'] == $certref) - && ($config['system']['webgui']['protocol'] != "http")) { + if (($config['system']['webgui']['ssl-certref'] == $certref) && + ($config['system']['webgui']['protocol'] != "http")) { return true; } } @@ -779,10 +779,10 @@ function cert_compare($cert1, $cert2) { being identical. */ $c1 = base64_decode($cert1['crt']); $c2 = base64_decode($cert2['crt']); - if ((cert_get_issuer($c1, false) == cert_get_issuer($c2, false)) - && (cert_get_subject($c1, false) == cert_get_subject($c2, false)) - && (cert_get_serial($c1, false) == cert_get_serial($c2, false)) - && (cert_get_modulus($c1, false) == cert_get_modulus($c2, false))) { + if ((cert_get_issuer($c1, false) == cert_get_issuer($c2, false)) && + (cert_get_subject($c1, false) == cert_get_subject($c2, false)) && + (cert_get_serial($c1, false) == cert_get_serial($c2, false)) && + (cert_get_modulus($c1, false) == cert_get_modulus($c2, false))) { return true; } return false; diff --git a/etc/inc/config.console.inc b/etc/inc/config.console.inc index 85fbc1085c..8640628cd9 100644 --- a/etc/inc/config.console.inc +++ b/etc/inc/config.console.inc @@ -385,7 +385,7 @@ EODD; } if (preg_match($g['wireless_regex'], $lanif)) { if (is_array($config['interfaces']['lan']) && - (!is_array($config['interfaces']['lan']['wireless']))) { + !is_array($config['interfaces']['lan']['wireless'])) { $config['interfaces']['lan']['wireless'] = array(); } } else { @@ -401,7 +401,7 @@ EODD; $config['interfaces']['wan']['enable'] = true; if (preg_match($g['wireless_regex'], $wanif)) { if (is_array($config['interfaces']['wan']) && - (!is_array($config['interfaces']['wan']['wireless']))) { + !is_array($config['interfaces']['wan']['wireless'])) { $config['interfaces']['wan']['wireless'] = array(); } } else { @@ -535,7 +535,7 @@ EOD; if ($vlan['if']) { if (!array_key_exists($vlan['if'], $iflist) or - !is_jumbo_capable($vlan['if'])) { + !is_jumbo_capable($vlan['if'])) { printf(gettext("%sInvalid interface name '%s'%s"), "\n", $vlan['if'], "\n"); continue; } diff --git a/etc/inc/dyndns.class b/etc/inc/dyndns.class index 8576b9c234..50114aa436 100644 --- a/etc/inc/dyndns.class +++ b/etc/inc/dyndns.class @@ -361,8 +361,8 @@ $port = ":" . $this->_dnsPort; } if (($this->_dnsService == "noip-free") && - ($this->_forceUpdateNeeded == true) && - ($this->_dnsDummyUpdateDone == false)) { + ($this->_forceUpdateNeeded == true) && + ($this->_dnsDummyUpdateDone == false)) { // Update the IP to a dummy value to force No-IP free accounts to see a change. $iptoset = "192.168.1.1"; $this->_dnsDummyUpdateDone = true; From a41d910c6e2ed0cc050a96b38a4816e3fd660d17 Mon Sep 17 00:00:00 2001 From: jim-p Date: Thu, 26 Feb 2015 08:26:31 -0500 Subject: [PATCH 137/257] Fix type (trime->trim) --- etc/inc/vpn.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index cec286dffc..283e455069 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -415,7 +415,7 @@ EOD; if (!empty($a_client['dns_split'])) { $ipsec_dns = explode(',', $a_client['dns_split']); foreach ($ipsec_dns as $ipsecidx => $ipsecdns) { - $ipsecdns = trime($ipsecdns); + $ipsecdns = trim($ipsecdns); $ipsec_dns[$ipsecidx] = "\"{$ipsecdns}\""; } $a_client['dns_split'] = implode(' ', $ipsec_dns); From aa2370d8341b9ece91c30a500aac4c19a4e78795 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Thu, 26 Feb 2015 10:33:39 -0300 Subject: [PATCH 138/257] Fix track6 prefix id range in error message, reported on Pull Request #1517 --- usr/local/www/interfaces.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 69e19bf54c..795569c6f0 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -611,7 +611,8 @@ if ($_POST['apply']) { } else { $track6_prefix_id = intval($_POST['track6-prefix-id--hex'], 16); if ($track6_prefix_id < 0 || $track6_prefix_id > $_POST['ipv6-num-prefix-ids-' . $_POST['track6-interface']]) { - $input_errors[] = gettext("You specified an IPv6 prefix ID that is out of range. ({$_POST['track6-interface']}) - ({$_POST['ipv6-num-prefix-ids-' . $_POST['track6-interface']]}) - ({$ipv6_delegation_length})"); + $input_errors[] = gettext("You specified an IPv6 prefix ID that is out of range.") . + " ({$_POST['track6-interface']}) - (0) - (" . sprintf('%x', $_POST['ipv6-num-prefix-ids-' . $_POST['track6-interface']]) . ")"; } else { foreach ($ifdescrs as $ifent => $ifdescr) { if ($if == $ifent) From e6cbfb6528aa47ccaae90dd809d60e13a448eb92 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 26 Feb 2015 21:44:30 +0545 Subject: [PATCH 139/257] Code style guide changes for filter.inc 2nd version This is the changes to filter.inc as per the commits in https://github.com/pfsense/pfsense/pull/1521 but done in just 1 clean commit. --- etc/inc/filter.inc | 1870 ++++++++++++++++++++++++++------------------ 1 file changed, 1104 insertions(+), 766 deletions(-) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index 6efb5da9d2..3e3fb25e8b 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -5,7 +5,7 @@ Copyright (C) 2004-2006 Scott Ullrich Copyright (C) 2005 Bill Marquette Copyright (C) 2006 Peter Allgeyer - Copyright (C) 2008-2010 Ermal Luci + Copyright (C) 2008-2010 Ermal Luci All rights reserved. originally part of m0n0wall (http://m0n0.ch/wall) @@ -52,7 +52,7 @@ $FilterIflist = array(); $GatewaysList = array(); /* Used for the hostname dns resolver */ -$filterdns = array(); +$filterdns = array(); /* Used for aliases and interface macros */ $aliases = ""; @@ -130,10 +130,11 @@ function filter_rule_tracker($tracker) { function fix_rule_label($descr) { $descr = str_replace('"', '', $descr); - if (strlen($descr) > 63) + if (strlen($descr) > 63) { return substr($descr, 0, 60) . "..."; - else + } else { return $descr; + } } function is_bogonsv6_used() { @@ -142,7 +143,7 @@ function is_bogonsv6_used() { $usebogonsv6 = false; if (isset($config['system']['ipv6allow'])) { foreach ($config['interfaces'] as $ifacedata) { - if(isset($ifacedata['enable']) && isset($ifacedata['blockbogons'])) { + if (isset($ifacedata['enable']) && isset($ifacedata['blockbogons'])) { $usebogonsv6 = true; break; } @@ -153,22 +154,24 @@ function is_bogonsv6_used() { function filter_pflog_start($kill_first = false) { global $config, $g; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; - if(isset($config['system']['developerspew'])) { + } + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_pflog_start() being called $mt\n"; } - if (!file_exists("{$g['varrun_path']}/filterlog.pid") || - !isvalidpid("{$g['varrun_path']}/filterlog.pid")) + if ((!file_exists("{$g['varrun_path']}/filterlog.pid")) || + (!isvalidpid("{$g['varrun_path']}/filterlog.pid"))) { mwexec("/usr/local/sbin/filterlog -i pflog0 -p {$g['varrun_path']}/filterlog.pid"); + } } /* reload filter async */ function filter_configure() { global $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_configure() being called $mt\n"; } @@ -177,28 +180,34 @@ function filter_configure() { * NOTE: Check here for bootup status since this should not be triggered during bootup. * The reason is that rc.bootup calls filter_configure_sync directly which does this too. */ - if (!platform_booting()) + if (!platform_booting()) { send_event("filter reload"); + } } function filter_delete_states_for_down_gateways() { global $config, $GatewaysList; - if (isset($config['system']['kill_states'])) + if (isset($config['system']['kill_states'])) { return; + } $any_gateway_down = false; $a_gateways = return_gateways_status(); if (is_array($GatewaysList)) { foreach ($GatewaysList as $gwname => $gateway) { - if (empty($gateway['monitor'])) + if (empty($gateway['monitor'])) { continue; - if (!is_ipaddr($gateway['monitor'])) + } + if (!is_ipaddr($gateway['monitor'])) { continue; - if (strstr($gateway['monitor'], "127.0.0.")) + } + if (strstr($gateway['monitor'], "127.0.0.")) { continue; - if (empty($a_gateways[$gateway['monitor']])) + } + if (empty($a_gateways[$gateway['monitor']])) { continue; + } $gwstatus =& $a_gateways[$gateway['monitor']]; if (strstr($gwstatus['status'], "down")) { $any_gateway_down = true; @@ -206,8 +215,9 @@ function filter_delete_states_for_down_gateways() { } } } - if ($any_gateway_down == true) + if ($any_gateway_down == true) { mwexec("/sbin/pfctl -Fs"); + } } /* reload filter sync */ @@ -218,81 +228,90 @@ function filter_configure_sync($delete_states_if_needed = true) { /* Use filter lock to not allow concurrent filter reloads during this run. */ $filterlck = lock('filter', LOCK_EX); - filter_pflog_start(); update_filter_reload_status(gettext("Initializing")); /* invalidate interface cache */ get_interface_arr(true); - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_configure_sync() being called $mt\n"; } /* Get interface list to work with. */ filter_generate_optcfg_array(); - if(platform_booting() == true) + if (platform_booting() == true) { echo gettext("Configuring firewall"); + } /* generate aliases */ - if(platform_booting() == true) + if (platform_booting() == true) { echo "."; + } update_filter_reload_status(gettext("Creating aliases")); $aliases = filter_generate_aliases(); $gateways = filter_generate_gateways(); - if(platform_booting() == true) + if (platform_booting() == true) { echo "."; + } update_filter_reload_status(gettext("Generating Limiter rules")); $dummynet_rules = filter_generate_dummynet_rules(); $dummynet_name_list = get_unique_dnqueue_list(); update_filter_reload_status(gettext("Generating NAT rules")); /* generate nat rules */ $natrules = filter_nat_rules_generate(); - if(platform_booting() == true) + if (platform_booting() == true) { echo "."; + } update_filter_reload_status(gettext("Generating filter rules")); /* generate pfctl rules */ $pfrules = filter_rules_generate(); /* generate altq, limiter */ - if(platform_booting() == true) + if (platform_booting() == true) { echo "."; + } update_filter_reload_status(gettext("Generating ALTQ queues")); $altq_queues = filter_generate_altq_queues(); update_filter_reload_status(gettext("Generating Layer7 rules")); generate_layer7_files(); - if(platform_booting() == true) + if (platform_booting() == true) { echo "."; + } update_filter_reload_status(gettext("Loading filter rules")); /* enable pf if we need to, otherwise disable */ - if(!isset ($config['system']['disablefilter'])) { + if (!isset ($config['system']['disablefilter'])) { mwexec("/sbin/pfctl -e", true); } else { mwexec("/sbin/pfctl -d", true); unlink_if_exists("{$g['tmp_path']}/filter_loading"); update_filter_reload_status(gettext("Filter is disabled. Not loading rules.")); - if(platform_booting() == true) + if (platform_booting() == true) { echo gettext("done.") . "\n"; + } unlock($filterlck); return; } $limitrules = ""; /* User defined maximum table entries in Advanced menu. */ - if ($config['system']['maximumtableentries'] <> "" && is_numeric($config['system']['maximumtableentries'])) + if ($config['system']['maximumtableentries'] <> "" && is_numeric($config['system']['maximumtableentries'])) { $limitrules .= "set limit table-entries {$config['system']['maximumtableentries']}\n"; + } if ($config['system']['optimization'] <> "") { $limitrules .= "set optimization {$config['system']['optimization']}\n"; - if($config['system']['optimization'] == "conservative") { + if ($config['system']['optimization'] == "conservative") { $limitrules .= "set timeout { udp.first 300, udp.single 150, udp.multiple 900 }\n"; } - } else + } else { $limitrules .= "set optimization normal\n"; + } - if (!empty($config['system']['adaptivestart']) && !empty($config['system']['adaptiveend'])) + if (!empty($config['system']['adaptivestart']) && !empty($config['system']['adaptiveend'])) { $limitrules .= "set timeout { adaptive.start {$config['system']['adaptivestart']}, adaptive.end {$config['system']['adaptiveend']} }\n"; - else + } else { $limitrules .= "set timeout { adaptive.start 0, adaptive.end 0 }\n"; + } if ($config['system']['maximumstates'] <> "" && is_numeric($config['system']['maximumstates'])) { /* User defined maximum states in Advanced menu. */ @@ -304,8 +323,9 @@ function filter_configure_sync($delete_states_if_needed = true) { $limitrules .= "set limit src-nodes {$max_states}\n"; } - if (isset($config['system']['lb_use_sticky']) && is_numeric($config['system']['srctrack']) && ($config['system']['srctrack'] > 0)) + if (isset($config['system']['lb_use_sticky']) && is_numeric($config['system']['srctrack']) && ($config['system']['srctrack'] > 0)) { $limitrules .= "set timeout src.track {$config['system']['srctrack']}\n"; + } $rules = ""; $rules = "{$limitrules}\n"; @@ -327,8 +347,9 @@ function filter_configure_sync($delete_states_if_needed = true) { unset($aliases, $gateways, $altq_queues, $natrules, $pfrules); // Copy rules.debug to rules.debug.old - if(file_exists("{$g['tmp_path']}/rules.debug")) + if (file_exists("{$g['tmp_path']}/rules.debug")) { @copy("{$g['tmp_path']}/rules.debug", "{$g['tmp_path']}/rules.debug.old"); + } if (!@file_put_contents("{$g['tmp_path']}/rules.debug", $rules, LOCK_EX)) { log_error("WARNING: Could not write new rules!"); @@ -340,13 +361,13 @@ function filter_configure_sync($delete_states_if_needed = true) { mwexec("/sbin/pfctl -Of {$g['tmp_path']}/rules.limits"); unset($rules, $limitrules); - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "pfctl being called at $mt\n"; } unset($rules_loading, $rules_error); $_grbg = exec("/sbin/pfctl -o basic -f {$g['tmp_path']}/rules.debug 2>&1", $rules_error, $rules_loading); - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "pfctl done at $mt\n"; } @@ -354,13 +375,14 @@ function filter_configure_sync($delete_states_if_needed = true) { * check for a error while loading the rules file. if an error has occurred * then output the contents of the error to the caller */ - if($rules_loading <> 0) { + if ($rules_loading <> 0) { $saved_line_error = $rules_error[0]; $line_error = explode(":", $rules_error[0]); $line_number = $line_error[1]; $line_split = file("{$g['tmp_path']}/rules.debug"); - if(is_array($line_split)) + if (is_array($line_split)) { $line_error = sprintf(gettext('The line in question reads [%1$d]: %2$s'), $line_number, $line_split[$line_number-1]); + } unset($line_split); /* Brutal ugly hack but required -- PF is stuck, unwedge */ @@ -382,26 +404,28 @@ function filter_configure_sync($delete_states_if_needed = true) { } # If we are not using bogonsv6 then we can remove any bogonsv6 table from the running pf (if the table is not there, the kill is still fine). - if (!is_bogonsv6_used()) + if (!is_bogonsv6_used()) { $_grbg = exec("/sbin/pfctl -t bogonsv6 -T kill 2>/dev/null"); + } update_filter_reload_status(gettext("Starting up layer7 daemon")); layer7_start_l7daemon(); - if(!empty($filterdns)) { + if (!empty($filterdns)) { @file_put_contents("{$g['varetc_path']}/filterdns.conf", implode("", $filterdns)); unset($filterdns); - if (isvalidpid("{$g['varrun_path']}/filterdns.pid")) + if (isvalidpid("{$g['varrun_path']}/filterdns.pid")) { sigkillbypid("{$g['varrun_path']}/filterdns.pid", "HUP"); - else { + } else { /* * FilterDNS has three debugging levels. The default chosen is 1. * Available are level 2 and greater then 2. */ - if (isset($config['system']['aliasesresolveinterval']) && is_numeric($config['system']['aliasesresolveinterval'])) + if (isset($config['system']['aliasesresolveinterval']) && is_numeric($config['system']['aliasesresolveinterval'])) { $resolve_interval = $config['system']['aliasesresolveinterval']; - else + } else { $resolve_interval = 300; + } mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns.pid -i {$resolve_interval} -c {$g['varetc_path']}/filterdns.conf -d 1"); } } else { @@ -411,10 +435,11 @@ function filter_configure_sync($delete_states_if_needed = true) { /* run items scheduled for after filter configure run */ $fda = fopen("{$g['tmp_path']}/commands.txt", "w"); - if($fda) { - if($after_filter_configure_run) { - foreach($after_filter_configure_run as $afcr) + if ($fda) { + if ($after_filter_configure_run) { + foreach ($after_filter_configure_run as $afcr) { fwrite($fda, $afcr . "\n"); + } unset($after_filter_configure_run); } @@ -423,34 +448,37 @@ function filter_configure_sync($delete_states_if_needed = true) { * filter_configure() call. run this xml command after * each change. */ - if($config['system']['afterfilterchangeshellcmd'] <> "") + if ($config['system']['afterfilterchangeshellcmd'] <> "") { fwrite($fda, $config['system']['afterfilterchangeshellcmd'] . "\n"); + } fclose($fda); } - if(file_exists("{$g['tmp_path']}/commands.txt")) { + if (file_exists("{$g['tmp_path']}/commands.txt")) { mwexec("sh {$g['tmp_path']}/commands.txt &"); unlink("{$g['tmp_path']}/commands.txt"); } /* if time based rules are enabled then swap in the set */ - if($time_based_rules == true) + if ($time_based_rules == true) { filter_tdr_install_cron(true); - else + } else { filter_tdr_install_cron(false); + } - if(platform_booting() == true) + if (platform_booting() == true) { echo "."; + } - if($delete_states_if_needed) { + if ($delete_states_if_needed) { update_filter_reload_status(gettext("Processing down interface states")); filter_delete_states_for_down_gateways(); } update_filter_reload_status(gettext("Running plugins")); - if(is_dir("/usr/local/pkg/pf/")) { + if (is_dir("/usr/local/pkg/pf/")) { /* process packager manager custom rules */ update_filter_reload_status(gettext("Running plugins (pf)")); run_plugins("/usr/local/pkg/pf/"); @@ -458,8 +486,9 @@ function filter_configure_sync($delete_states_if_needed = true) { } update_filter_reload_status(gettext("Done")); - if(platform_booting() == true) + if (platform_booting() == true) { echo gettext("done.") . "\n"; + } unlock($filterlck); return 0; @@ -471,35 +500,44 @@ function filter_generate_scrubing() { if (isset($config['system']['maxmss_enable'])) { $maxmss = 1400; - if (!empty($config['system']['maxmss'])) + if (!empty($config['system']['maxmss'])) { $maxmss = $config['system']['maxmss']; + } $scrubrules .= "scrub from any to max-mss {$maxmss}\n"; $scrubrules .= "scrub from to any max-mss {$maxmss}\n"; } /* disable scrub option */ foreach ($FilterIflist as $scrubif => $scrubcfg) { - if(isset($scrubcfg['virtual']) || empty($scrubcfg['descr'])) + if (isset($scrubcfg['virtual']) || empty($scrubcfg['descr'])) { continue; + } /* set up MSS clamping */ - if($scrubcfg['mss'] <> "" && is_numeric($scrubcfg['mss']) && $scrubcfg['if'] != "pppoe" && $scrubcfg['if'] != "pptp" && - $scrubif['if'] != "l2tp") + if (($scrubcfg['mss'] <> "") && + (is_numeric($scrubcfg['mss'])) && + ($scrubcfg['if'] != "pppoe") && + ($scrubcfg['if'] != "pptp") && + ($scrubif['if'] != "l2tp")) { $mssclamp = "max-mss " . (intval($scrubcfg['mss'] - 40)); - else + } else { $mssclamp = ""; + } /* configure no-df for linux nfs and others */ - if($config['system']['scrubnodf']) + if ($config['system']['scrubnodf']) { $scrubnodf = "no-df"; - else + } else { $scrubnodf = ""; - if($config['system']['scrubrnid']) + } + if ($config['system']['scrubrnid']) { $scrubrnid = "random-id"; - else + } else { $scrubrnid = ""; - if(!isset($config['system']['disablescrub'])) + } + if (!isset($config['system']['disablescrub'])) { $scrubrules .= "scrub on \${$scrubcfg['descr']} all {$scrubnodf} {$scrubrnid} {$mssclamp} fragment reassemble\n"; // reassemble all directions - else if(!empty($mssclamp)) + } else if (!empty($mssclamp)) { $scrubrules .= "scrub on \${$scrubcfg['descr']} {$mssclamp}\n"; + } } return $scrubrules; } @@ -514,17 +552,18 @@ function filter_generate_nested_alias($name, $alias, &$aliasnesting, &$aliasaddr $urltable_nesting = ""; $aliasnesting[$name] = $name; foreach ($addresses as $address) { - if (empty($address)) + if (empty($address)) { continue; + } $linelength = strlen($builtlist); $tmpline = ""; - if(is_alias($address)) { + if (is_alias($address)) { if (alias_get_type($address) == 'urltable') { // Feature#1603. For this type of alias we do not need to recursively call filter_generate_nested_alias. Just load IPs from the file. $urltable_netsting = alias_expand_urltable($address); if (!empty($urltable_nesting)) { $urlfile_as_arr = file($urltable_nesting); - foreach($urlfile_as_arr as $line) { + foreach ($urlfile_as_arr as $line) { $address= rtrim($line); if ((strlen($tmpline) + $linelength) > 4036) { $finallist .= "{$tmpline} \\\n"; @@ -535,9 +574,10 @@ function filter_generate_nested_alias($name, $alias, &$aliasnesting, &$aliasaddr } } /* We already expanded this alias so there is no necessity to do it again. */ - else if(!isset($aliasnesting[$address])) + else if (!isset($aliasnesting[$address])) { $tmpline = filter_generate_nested_alias($name, $aliastable[$address], $aliasnesting, $aliasaddrnesting); - } else if(!isset($aliasaddrnesting[$address])) { + } + } else if (!isset($aliasaddrnesting[$address])) { if (!is_ipaddr($address) && !is_subnet($address) && !is_port($address) && !is_portrange($address) && is_hostname($address)) { if (!isset($filterdns["{$address}{$name}"])) { $use_filterdns = true; @@ -552,17 +592,20 @@ function filter_generate_nested_alias($name, $alias, &$aliasnesting, &$aliasaddr $finallist .= "{$builtlist} \\\n"; $builtlist = ""; } - if (!empty($tmpline)) + if (!empty($tmpline)) { $builtlist .= " {$tmpline}"; + } } $finallist .= $builtlist; if ($use_filterdns === true && !empty($finallist)) { foreach (explode(" ", $finallist) as $address) { - if (empty($address)) + if (empty($address)) { continue; - if ((is_ipaddr($address) || is_subnet($address)) && !isset($filterdns["{$address}{$name}"])) + } + if ((is_ipaddr($address) || is_subnet($address)) && !isset($filterdns["{$address}{$name}"])) { $filterdns["{$address}{$name}"] = "pf {$address} {$name}\n"; + } } $finallist = ''; } @@ -574,9 +617,9 @@ function filter_expand_alias($alias_name) { global $config; - if(isset($config['aliases']['alias'])) { + if (isset($config['aliases']['alias'])) { foreach ($config['aliases']['alias'] as $aliased) { - if($aliased['name'] == $alias_name) { + if ($aliased['name'] == $alias_name) { $aliasnesting = array(); $aliasaddrnesting = array(); return filter_generate_nested_alias($aliased['name'], $aliased['address'], $aliasnesting, $aliasaddrnesting); @@ -593,7 +636,7 @@ function filter_expand_alias_array($alias_name) { function filter_generate_aliases() { global $config, $FilterIflist, $after_filter_configure_run; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_generate_aliases() being called $mt\n"; } @@ -608,11 +651,11 @@ function filter_generate_aliases() { $aliases .= " }\"\n"; } } elseif (!empty($ifcfg['descr']) && !empty($ifcfg['if'])) { - if ($ifcfg['type6'] == '6rd') + if ($ifcfg['type6'] == '6rd') { $aliases .= "{$ifcfg['descr']} = \"{ {$ifcfg['if']} {$if}_stf"; - else if ($ifcfg['type6'] == '6to4') + } else if ($ifcfg['type6'] == '6to4') { $aliases .= "{$ifcfg['descr']} = \"{ {$ifcfg['if']} {$if}_stf"; - else { + } else { $aliases .= "{$ifcfg['descr']} = \"{ {$ifcfg['if']}"; if ($ifcfg['type'] == 'pptp') { @@ -634,27 +677,32 @@ function filter_generate_aliases() { $aliases .= "#Snort tables\n"; $aliases .= "table \n"; $aliases .= "table \n"; - if (!file_exists("/etc/bogons")) + if (!file_exists("/etc/bogons")) { @file_put_contents("/etc/bogons", ""); - if (!file_exists("/etc/bogonsv6")) + } + if (!file_exists("/etc/bogonsv6")) { @file_put_contents("/etc/bogonsv6", ""); + } $aliases .= "table persist file \"/etc/bogons\"\n"; - if (is_bogonsv6_used()) + if (is_bogonsv6_used()) { $aliases .= "table persist file \"/etc/bogonsv6\"\n"; + } $vpns_list = filter_get_vpns_list(); - if($vpns_list) + if ($vpns_list) { $aliases .= "table { $vpns_list }\n"; + } /* add a Negate_networks table */ $aliases .= "table "; - if($vpns_list) + if ($vpns_list) { $aliases .= "{ $vpns_list }"; + } $aliases .= "\n"; $aliases .= "\n# User Aliases \n"; /* Setup pf groups */ - if(isset($config['aliases']['alias'])) { + if (isset($config['aliases']['alias'])) { foreach ($config['aliases']['alias'] as $aliased) { $extralias = ""; $aliasnesting = array(); @@ -665,27 +713,30 @@ function filter_generate_aliases() { case "network": case "url": $tableaddrs = "{$addrlist}{$extralias}"; - if(empty($tableaddrs)) { + if (empty($tableaddrs)) { $aliases .= "table <{$aliased['name']}> persist\n"; - if (empty($aliased['address'])) + if (empty($aliased['address'])) { $after_filter_configure_run[] = "/sbin/pfctl -T flush -t " . escapeshellarg($aliased['name']); - } else + } + } else { $aliases .= "table <{$aliased['name']}> { {$addrlist}{$extralias} } \n"; + } $aliases .= "{$aliased['name']} = \"<{$aliased['name']}>\"\n"; break; case "openvpn": $openvpncfg = array(); - if($config['openvpn']['user']) { + if ($config['openvpn']['user']) { /* XXX: Check if we have a correct ip? */ - foreach ($config['openvpn']['user'] as $openvpn) + foreach ($config['openvpn']['user'] as $openvpn) { $openvpncfg[$openvpn['name']] = $openvpn['ip']; + } } $vpn_lines = explode("\n", $addrlist); foreach ($vpn_lines as $vpn_line) { $vpn_address_split = explode(" ", $vpn_line); - foreach($vpn_address_split as $vpnsplit) { - if(isset($openvpncfg[$vpnsplit])) { + foreach ($vpn_address_split as $vpnsplit) { + if (isset($openvpncfg[$vpnsplit])) { $newaddress .= " "; $newaddress .= $openvpn[$vpnsplit]; break; @@ -705,8 +756,9 @@ function filter_generate_aliases() { case "urltable_ports": // TODO: Change it when pf supports tables with ports $urlfn = alias_expand_urltable($aliased['name']); - if ($urlfn) + if ($urlfn) { $aliases .= "{$aliased['name']} = \"{ " . preg_replace("/\n/", " ", file_get_contents($urlfn)) . " }\"\n"; + } break; case "port": case "url_ports": @@ -740,14 +792,17 @@ function filter_generate_gateways() { $int = $gateway['interface']; $gwip = $gateway['gateway']; $route = ""; - if (!is_ipaddr($gwip)) + if (!is_ipaddr($gwip)) { $gwip = get_interface_gateway($gateway['friendlyiface']); - if (is_ipaddr($gwip) && !empty($int)) + } + if (is_ipaddr($gwip) && !empty($int)) { $route = "route-to ( {$int} {$gwip} )"; - if (($route === "") && isset($config['system']['skip_rules_gw_down'])) + } + if (($route === "") && isset($config['system']['skip_rules_gw_down'])) { unset($GatewaysList[$gwname]); - else + } else { $rules .= "GW{$gwname} = \" {$route} \"\n"; + } } } @@ -759,34 +814,39 @@ function filter_generate_gateways() { if (count($members) > 0) { $foundlb = 0; $routeto = ""; - foreach($members as $idx => $member) { + foreach ($members as $idx => $member) { $int = $member['int']; $gatewayip = $member['gwip']; if (($int <> "") && is_ipaddr($gatewayip)) { - if ($g['debug']) + if ($g['debug']) { log_error(sprintf(gettext('Setting up route with %1$s on %2$s'), $gatewayip, $int)); + } if ($member['weight'] > 1) { $routeto .= str_repeat("( {$int} {$gatewayip} ) ", $member['weight']); - } else + } else { $routeto .= "( {$int} {$gatewayip} ) "; + } $foundlb++; - } else + } else { log_error(sprintf(gettext("An error occurred while trying to find the interface got %s . The rule has not been added."), $gatewayip)); + } } $route = ""; if ($foundlb > 0) { $route = " route-to { {$routeto} } "; - if($foundlb > 1) { + if ($foundlb > 1) { $route .= " round-robin "; - if (isset($config['system']['lb_use_sticky'])) + if (isset($config['system']['lb_use_sticky'])) { $route .= " sticky-address "; + } } } } - if (($route === "") && isset($config['system']['skip_rules_gw_down'])) + if (($route === "") && isset($config['system']['skip_rules_gw_down'])) { unset($GatewayGroupsList[$gateway]); - else + } else { $rules .= "GW{$gateway} = \" {$route} \"\n"; + } } } @@ -810,14 +870,17 @@ function filter_get_vpns_list() { if (is_array($config['ipsec']['phase2'])) { foreach ($config['ipsec']['phase2'] as $ph2ent) { if ((!$ph2ent['mobile']) && ($ph2ent['mode'] != 'transport')) { - if (!function_exists('ipsec_idinfo_to_cidr')) + if (!function_exists('ipsec_idinfo_to_cidr')) { require_once("ipsec.inc"); - if (!is_array($ph2ent['remoteid'])) + } + if (!is_array($ph2ent['remoteid'])) { continue; + } $ph2ent['remoteid']['mode'] = $ph2ent['mode']; $vpns_subnet = ipsec_idinfo_to_cidr($ph2ent['remoteid']); - if (!is_subnet($vpns_subnet) || $vpns_subnet == "0.0.0.0/0") + if (!is_subnet($vpns_subnet) || $vpns_subnet == "0.0.0.0/0") { continue; + } $vpns_arr[] = $vpns_subnet; } } @@ -826,17 +889,19 @@ function filter_get_vpns_list() { /* openvpn */ foreach (array('client', 'server') as $type) { - if(is_array($config['openvpn']["openvpn-$type"])) { + if (is_array($config['openvpn']["openvpn-$type"])) { foreach ($config['openvpn']["openvpn-$type"] as $settings) { - if(is_array($settings)) { + if (is_array($settings)) { if (!isset($settings['disable'])) { $remote_networks = explode(',', $settings['remote_network']); foreach ($remote_networks as $remote_network) { - if (is_subnet($remote_network) && ($remote_network <> "0.0.0.0/0")) + if (is_subnet($remote_network) && ($remote_network <> "0.0.0.0/0")) { $vpns_arr[] = $remote_network; + } } - if (is_subnet($settings['tunnel_network']) && $settings['tunnel_network'] <> "0.0.0.0/0") + if (is_subnet($settings['tunnel_network']) && $settings['tunnel_network'] <> "0.0.0.0/0") { $vpns_arr[] = $settings['tunnel_network']; + } } } } @@ -844,19 +909,21 @@ function filter_get_vpns_list() { } /* pppoe */ if (is_array($config['pppoes']['pppoe'])) { - foreach($config['pppoes']['pppoe'] as $pppoe) { + foreach ($config['pppoes']['pppoe'] as $pppoe) { if ($pppoe['mode'] == "server") { - if(is_ipaddr($pppoe['remoteip'])) { + if (is_ipaddr($pppoe['remoteip'])) { $pppoesub = gen_subnet($pppoe['remoteip'], $pppoe['pppoe_subnet']); - if (is_subnet($pppoesub)) + if (is_subnet($pppoesub)) { $vpns_arr[] = $pppoesub; + } } } } } - if (!empty($vpns_arr)) + if (!empty($vpns_arr)) { $vpns = implode(" ", $vpns_arr); + } return $vpns; } @@ -869,13 +936,13 @@ function filter_get_direct_networks_list($returnsubnetsonly = true) { /* build list of directly connected interfaces and networks */ $networks = ""; $networks_arr = array(); - if(empty($FilterIflist)) { + if (empty($FilterIflist)) { filter_generate_optcfg_array(); } foreach ($FilterIflist as $ifent => $ifcfg) { $subnet = "{$ifcfg['sa']}/{$ifcfg['sn']}"; - if(is_subnet($subnet)) { - if($returnsubnetsonly) { + if (is_subnet($subnet)) { + if ($returnsubnetsonly) { $networks_arr[] = $subnet; } else { $networks_arr[] = array( @@ -885,14 +952,15 @@ function filter_get_direct_networks_list($returnsubnetsonly = true) { } } } - foreach(get_configured_ip_aliases_list(true) as $vip) { + foreach (get_configured_ip_aliases_list(true) as $vip) { $subnet = "{$vip['subnet']}/{$vip['subnet_bits']}"; - if(is_subnet($subnet) && !(is_subnetv4($subnet) && $vip['subnet_bits'] == 32) && !(is_subnetv6($subnet) && $vip['subnet_bits'] == 128)) { - if(is_subnetv4($subnet)) + if (is_subnet($subnet) && !(is_subnetv4($subnet) && $vip['subnet_bits'] == 32) && !(is_subnetv6($subnet) && $vip['subnet_bits'] == 128)) { + if (is_subnetv4($subnet)) { $subnet = gen_subnet($vip['subnet'], $vip['subnet_bits']) . "/{$vip['subnet_bits']}"; - else if(is_subnetv6($subnet)) + } else if (is_subnetv6($subnet)) { $subnet = gen_subnetv6($vip['subnet'], $vip['subnet_bits']) . "/{$vip['subnet_bits']}"; - if($returnsubnetsonly) { + } + if ($returnsubnetsonly) { $networks_arr[] = $subnet; } else { $networks_arr[] = array( @@ -902,11 +970,11 @@ function filter_get_direct_networks_list($returnsubnetsonly = true) { } } } - foreach(get_staticroutes() as $netent) { - if(is_subnet($netent['network'])) { - if($returnsubnetsonly) { + foreach (get_staticroutes() as $netent) { + if (is_subnet($netent['network'])) { + if ($returnsubnetsonly) { $networks_arr[] = $netent['network']; - } else if(isset($GatewaysList[$netent['gateway']])) { + } else if (isset($GatewaysList[$netent['gateway']])) { $networks_arr[] = array( 'subnet' => $netent['network'], 'if' => $GatewaysList[$netent['gateway']]['friendlyiface'], @@ -914,8 +982,8 @@ function filter_get_direct_networks_list($returnsubnetsonly = true) { } } } - if($returnsubnetsonly) { - if(!empty($networks_arr)) { + if ($returnsubnetsonly) { + if (!empty($networks_arr)) { $networks = implode(" ", $networks_arr); } return $networks; @@ -926,7 +994,7 @@ function filter_get_direct_networks_list($returnsubnetsonly = true) { function filter_generate_optcfg_array() { global $config, $FilterIflist; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_generate_optcfg_array() being called $mt\n"; } @@ -938,17 +1006,21 @@ function filter_generate_optcfg_array() { $oc = $config['interfaces'][$if]; $oic = array(); $oic['if'] = get_real_interface($if); - if (!does_interface_exist($oic['if'])) + if (!does_interface_exist($oic['if'])) { continue; + } $oic['ifv6'] = get_real_interface($if, "inet6"); $oic['ip'] = get_interface_ip($if); $oic['ipv6'] = get_interface_ipv6($if); - if(!is_ipaddrv4($oc['ipaddr']) && !empty($oc['ipaddr'])) + if (!is_ipaddrv4($oc['ipaddr']) && !empty($oc['ipaddr'])) { $oic['type'] = $oc['ipaddr']; - if(!is_ipaddrv6($oc['ipaddrv6']) && !empty($oc['ipaddrv6'])) + } + if (!is_ipaddrv6($oc['ipaddrv6']) && !empty($oc['ipaddrv6'])) { $oic['type6'] = $oc['ipaddrv6']; - if (!empty($oc['track6-interface'])) + } + if (!empty($oc['track6-interface'])) { $oic['track6-interface'] = $oc['track6-interface']; + } $oic['sn'] = get_interface_subnet($if); $oic['snv6'] = get_interface_subnetv6($if); $oic['mtu'] = empty($oc['mtu']) ? 1500 : $oc['mtu']; @@ -967,21 +1039,25 @@ function filter_generate_optcfg_array() { if (!empty($vips)) { foreach ($vips as $vipidx => $vip) { if (is_ipaddrv4($vip['subnet'])) { - if (!is_array($oic['vips'])) + if (!is_array($oic['vips'])) { $oic['vips'] = array(); + } $oic['vips'][$vipidx]['ip'] = $vip['subnet']; - if (empty($vip['subnet_bits'])) + if (empty($vip['subnet_bits'])) { $oic['vips'][$vipidx]['sn'] = 32; - else + } else { $oic['vips'][$vipidx]['sn'] = $vip['subnet_bits']; + } } else if (is_ipaddrv6($vip['subnet'])) { - if (!is_array($oic['vips6'])) + if (!is_array($oic['vips6'])) { $oic['vips6'] = array(); + } $oic['vips6'][$vipidx]['ip'] = $vip['subnet']; - if (empty($vip['subnet_bits'])) + if (empty($vip['subnet_bits'])) { $oic['vips6'][$vipidx]['sn'] = 128; - else + } else { $oic['vips6'][$vipidx]['sn'] = $vip['subnet_bits']; + } } } } @@ -989,7 +1065,7 @@ function filter_generate_optcfg_array() { $FilterIflist[$if] = $oic; } - if($config['pptpd']['mode'] == "server" || $config['pptpd']['mode'] == "redir") { + if ($config['pptpd']['mode'] == "server" || $config['pptpd']['mode'] == "redir") { $oic = array(); $oic['if'] = 'pptp'; $oic['descr'] = 'pptp'; @@ -997,29 +1073,31 @@ function filter_generate_optcfg_array() { $oic['sa'] = $config['pptpd']['remoteip']; $oic['mode'] = $config['pptpd']['mode']; $oic['virtual'] = true; - if($config['pptpd']['pptp_subnet'] <> "") + if ($config['pptpd']['pptp_subnet'] <> "") { $oic['sn'] = $config['pptpd']['pptp_subnet']; - else + } else { $oic['sn'] = "32"; + } $FilterIflist['pptp'] = $oic; } - if($config['l2tp']['mode'] == "server") { + if ($config['l2tp']['mode'] == "server") { $oic = array(); $oic['if'] = 'l2tp'; $oic['descr'] = 'L2TP'; $oic['ip'] = $config['l2tp']['localip']; $oic['sa'] = $config['l2tp']['remoteip']; - if($config['l2tp']['l2tp_subnet'] <> "") + if ($config['l2tp']['l2tp_subnet'] <> "") { $oic['sn'] = $config['l2tp']['l2tp_subnet']; - else + } else { $oic['sn'] = "32"; + } $oic['mode'] = $config['l2tp']['mode']; $oic['virtual'] = true; $FilterIflist['l2tp'] = $oic; } if (is_array($config['pppoes']['pppoe']) && (count($config['pppoes']['pppoe']) > 0)) { $pppoeifs = array(); - foreach($config['pppoes']['pppoe'] as $pppoe) { + foreach ($config['pppoes']['pppoe'] as $pppoe) { if ($pppoe['mode'] == "server") { $oic = array(); $oic['if'] = 'pppoe'; @@ -1028,18 +1106,20 @@ function filter_generate_optcfg_array() { $oic['sa'] = $pppoe['remoteip']; $oic['mode'] = $pppoe['mode']; $oic['virtual'] = true; - if($pppoe['pppoe_subnet'] <> "") + if ($pppoe['pppoe_subnet'] <> "") { $oic['sn'] = $pppoe['pppoe_subnet']; - else + } else { $oic['sn'] = "32"; + } $pppoeifs[] = $oic; } } - if (count($pppoeifs)) + if (count($pppoeifs)) { $FilterIflist['pppoe'] = $pppoeifs; + } } /* add ipsec interfaces */ - if(isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable'])) { + if (isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable'])) { $oic = array(); $oic['if'] = 'enc0'; $oic['descr'] = 'IPsec'; @@ -1048,7 +1128,7 @@ function filter_generate_optcfg_array() { $FilterIflist['enc0'] = $oic; } /* add openvpn interfaces */ - if($config['openvpn']['openvpn-server'] || $config['openvpn']['openvpn-client']) { + if ($config['openvpn']['openvpn-server'] || $config['openvpn']['openvpn-client']) { $oic = array(); $oic['if'] = "openvpn"; $oic['descr'] = 'OpenVPN'; @@ -1057,8 +1137,8 @@ function filter_generate_optcfg_array() { $FilterIflist['openvpn'] = $oic; } /* add interface groups */ - if(is_array($config['ifgroups']['ifgroupentry'])) { - foreach($config['ifgroups']['ifgroupentry'] as $ifgen) { + if (is_array($config['ifgroups']['ifgroupentry'])) { + foreach ($config['ifgroups']['ifgroupentry'] as $ifgen) { $oc = array(); $oc['if'] = $ifgen['ifname']; $oc['descr'] = $ifgen['ifname']; @@ -1070,7 +1150,7 @@ function filter_generate_optcfg_array() { function filter_flush_nat_table() { global $config, $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_flush_nat_table() being called $mt\n"; } @@ -1087,12 +1167,14 @@ function filter_get_reflection_interfaces($natif = "") { $nat_if_list = array(); foreach ($FilterIflist as $ifent => $ifname) { - if($ifname['if'] == $natif) + if ($ifname['if'] == $natif) { continue; + } /* Do not add reflection redirects for interfaces with gateways */ - if(interface_has_gateway($ifent)) + if (interface_has_gateway($ifent)) { continue; + } $nat_if_list[] = $ifname['if']; } @@ -1103,8 +1185,9 @@ function filter_get_reflection_interfaces($natif = "") { function filter_generate_reflection_nat($rule, &$route_table, $nat_ifs, $protocol, $target, $target_ip, $target_subnet = "") { global $config, $FilterIflist; - if(!isset($config['system']['enablenatreflectionhelper'])) + if (!isset($config['system']['enablenatreflectionhelper'])) { return ""; + } // Initialize natrules holder string $natrules = ""; @@ -1112,37 +1195,40 @@ function filter_generate_reflection_nat($rule, &$route_table, $nat_ifs, $protoco update_filter_reload_status(sprintf(gettext("Creating reflection NAT rule for %s..."), $rule['descr'])); /* TODO: Add this option to port forwards page. */ - if(isset($rule['staticnatport'])) { + if (isset($rule['staticnatport'])) { $static_port = " static-port"; } else { $static_port = " port 1024:65535"; } - if(!empty($protocol)) { + if (!empty($protocol)) { $protocol_text = " proto {$protocol}"; } else { $protocol_text = ""; } - if(empty($target_subnet) || !is_numeric($target_subnet)) + if (empty($target_subnet) || !is_numeric($target_subnet)) { $target_subnet = 32; + } - if(!is_array($route_table)) { + if (!is_array($route_table)) { /* get a simulated IPv4-only route table based on the config */ $route_table = filter_get_direct_networks_list(false); - foreach($route_table as $rt_key => $rt_ent) { - if(!is_subnetv4($rt_ent['subnet'])) + foreach ($route_table as $rt_key => $rt_ent) { + if (!is_subnetv4($rt_ent['subnet'])) { unset($route_table[$rt_key]); - if(isset($route_table[$rt_key]) && isset($FilterIflist[$rt_ent['if']]['if'])) + } + if (isset($route_table[$rt_key]) && isset($FilterIflist[$rt_ent['if']]['if'])) { $route_table[$rt_key]['if'] = $FilterIflist[$rt_ent['if']]['if']; + } } } /* Check if the target is accessed through a static route */ - foreach($route_table as $route) { - if(isset($route['gateway']) && is_ipaddr($route['gateway'])) { + foreach ($route_table as $route) { + if (isset($route['gateway']) && is_ipaddr($route['gateway'])) { $subnet_split = explode("/", $route['subnet']); - if(in_array($route['if'], $nat_ifs) && check_subnets_overlap($target_ip, $target_subnet, $subnet_split[0], $subnet_split[1])) { + if (in_array($route['if'], $nat_ifs) && check_subnets_overlap($target_ip, $target_subnet, $subnet_split[0], $subnet_split[1])) { $target_ip = $route['gateway']; $target_subnet = 32; break; @@ -1151,36 +1237,39 @@ function filter_generate_reflection_nat($rule, &$route_table, $nat_ifs, $protoco } /* Search for matching subnets in the routing table */ - foreach($route_table as $route) { + foreach ($route_table as $route) { $subnet = $route['subnet']; $subnet_split = explode("/", $subnet); $subnet_if = $route['if']; - if(in_array($subnet_if, $nat_ifs) && check_subnets_overlap($target_ip, $target_subnet, $subnet_split[0], $subnet_split[1])) { + if (in_array($subnet_if, $nat_ifs) && check_subnets_overlap($target_ip, $target_subnet, $subnet_split[0], $subnet_split[1])) { $ifsubnet_ip = ""; /* Find interface IP to use for NAT */ foreach ($route_table as $ifnetwork) { - if(isset($ifnetwork['ip']) && is_ipaddr($ifnetwork['ip']) && $ifnetwork['if'] == $subnet_if && ip_in_subnet($ifnetwork['ip'], $subnet)) { + if (isset($ifnetwork['ip']) && is_ipaddr($ifnetwork['ip']) && $ifnetwork['if'] == $subnet_if && ip_in_subnet($ifnetwork['ip'], $subnet)) { $ifsubnet_ip = $ifnetwork['ip']; break; } } - if(!empty($ifsubnet_ip)) { + if (!empty($ifsubnet_ip)) { $subnets = array($subnet); /* Find static routes that also need to be referenced in the NAT rule */ - foreach($route_table as $rtentry) { - if(isset($rtentry['gateway']) && is_ipaddr($rtentry['gateway']) && $rtentry['if'] == $subnet_if && ip_in_subnet($rtentry['gateway'], $subnet)) + foreach ($route_table as $rtentry) { + if (isset($rtentry['gateway']) && is_ipaddr($rtentry['gateway']) && $rtentry['if'] == $subnet_if && ip_in_subnet($rtentry['gateway'], $subnet)) { $subnets[] = $rtentry['subnet']; + } } - if(count($subnets) > 1) + if (count($subnets) > 1) { $subnet = "{ " . implode(" ", $subnets) . " }"; + } $natrules .= "no nat on {$subnet_if}{$protocol_text} from {$subnet_if} to {$target}\n"; $natrules .= "nat on {$subnet_if}{$protocol_text} from {$subnet} to {$target} -> {$ifsubnet_ip}{$static_port}\n"; } } } - if(!empty($natrules)) + if (!empty($natrules)) { $natrules .= "\n"; + } return $natrules; } @@ -1192,22 +1281,24 @@ function filter_generate_reflection_proxy($rule, $nordr, $rdr_ifs, $srcaddr, $ds $natrules = ""; $reflection_txt = array(); - if(!empty($rdr_ifs)) { - if($config['system']['reflectiontimeout']) + if (!empty($rdr_ifs)) { + if ($config['system']['reflectiontimeout']) { $reflectiontimeout = $config['system']['reflectiontimeout']; - else + } else { $reflectiontimeout = "2000"; + } update_filter_reload_status(sprintf(gettext("Creating reflection rule for %s..."), $rule['descr'])); $rdr_if_list = implode(" ", $rdr_ifs); - if(count($rdr_ifs) > 1) + if (count($rdr_ifs) > 1) { $rdr_if_list = "{ {$rdr_if_list} }"; + } $natrules .= "\n# Reflection redirects\n"; $localport = $rule['local-port']; - if(!empty($localport) && is_alias($localport)) { + if (!empty($localport) && is_alias($localport)) { $localport = filter_expand_alias($localport); $localport = explode(" ", trim($localport)); // The translation port for rdr, when specified, does not support more than one port or range. @@ -1215,138 +1306,152 @@ function filter_generate_reflection_proxy($rule, $nordr, $rdr_ifs, $srcaddr, $ds $localport = $localport[0]; } - if(is_alias($rule['destination']['port'])) { - if(empty($localport) || $rule['destination']['port'] == $rule['local-port']) { + if (is_alias($rule['destination']['port'])) { + if (empty($localport) || $rule['destination']['port'] == $rule['local-port']) { $dstport = filter_expand_alias($rule['destination']['port']); $dstport = array_filter(explode(" ", trim($dstport))); $localport = ""; - } else if(!empty($localport)) { + } else if (!empty($localport)) { $dstport = array($localport); } } else { $dstport = array(str_replace("-", ":", $rule['destination']['port'])); $dstport_split = explode(":", $dstport[0]); - if(!empty($localport) && $dstport_split[0] != $rule['local-port']) { - if(!is_alias($rule['local-port']) && $dstport_split[1] && $dstport_split[0] != $dstport_split[1]) { + if (!empty($localport) && $dstport_split[0] != $rule['local-port']) { + if (!is_alias($rule['local-port']) && $dstport_split[1] && $dstport_split[0] != $dstport_split[1]) { $localendport = $localport + ($dstport_split[1] - $dstport_split[0]); $localport .= ":$localendport"; } $dstport = array($localport); - } else + } else { $localport = ""; + } } $dstaddr = explode(" ", $dstaddr_port); - if($dstaddr[2]) { + if ($dstaddr[2]) { $rflctintrange = array_pop($dstaddr); array_pop($dstaddr); - } else + } else { return ""; + } $dstaddr = implode(" ", $dstaddr); - if(empty($dstaddr) || trim($dstaddr) == "0.0.0.0" || strtolower(trim($dstaddr)) == "port") + if (empty($dstaddr) || trim($dstaddr) == "0.0.0.0" || strtolower(trim($dstaddr)) == "port") { return ""; + } - if(isset($rule['destination']['any'])) { - if(!$rule['interface']) + if (isset($rule['destination']['any'])) { + if (!$rule['interface']) { $natif = "wan"; - else + } else { $natif = $rule['interface']; + } - if(!isset($FilterIflist[$natif])) + if (!isset($FilterIflist[$natif])) { return ""; - if(is_ipaddr($FilterIflist[$natif]['ip'])) + } + if (is_ipaddr($FilterIflist[$natif]['ip'])) { $dstaddr = $FilterIflist[$natif]['ip']; - else + } else { return ""; + } - if(!empty($FilterIflist[$natif]['sn'])) + if (!empty($FilterIflist[$natif]['sn'])) { $dstaddr = gen_subnet($dstaddr, $FilterIflist[$natif]['sn']) . '/' . $FilterIflist[$natif]['sn']; + } } - switch($rule['protocol']) { - case "tcp/udp": - $protocol = "{ tcp udp }"; - $reflect_protos = array('tcp', 'udp'); - break; - case "tcp": - case "udp": - $protocol = $rule['protocol']; - $reflect_protos = array($rule['protocol']); - break; - default: - return ""; - break; + switch ($rule['protocol']) { + case "tcp/udp": + $protocol = "{ tcp udp }"; + $reflect_protos = array('tcp', 'udp'); + break; + case "tcp": + case "udp": + $protocol = $rule['protocol']; + $reflect_protos = array($rule['protocol']); + break; + default: + return ""; + break; } - if(!empty($nordr)) { + if (!empty($nordr)) { $natrules .= "no rdr on {$rdr_if_list} proto {$protocol} from {$srcaddr} to {$dstaddr} port {$rflctintrange}\n"; return $natrules; } - if (is_alias($rule['target'])) + if (is_alias($rule['target'])) { $target = filter_expand_alias($rule['target']); - else if(is_ipaddr($rule['target'])) + } else if (is_ipaddr($rule['target'])) { $target = $rule['target']; - else if (is_ipaddr($FilterIflist[$rule['target']]['ip'])) + } else if (is_ipaddr($FilterIflist[$rule['target']]['ip'])) { $target = $FilterIflist[$rule['target']]['ip']; - else + } else { return ""; + } $starting_localhost_port_tmp = $starting_localhost_port; $toomanyports = false; /* only install reflection rules for < 19991 items */ - foreach($dstport as $loc_pt) { - if($starting_localhost_port < 19991) { + foreach ($dstport as $loc_pt) { + if ($starting_localhost_port < 19991) { $toadd_array = array(); $inetdport = $starting_localhost_port; $rflctrange = $starting_localhost_port; $loc_pt = explode(":", $loc_pt); - if($loc_pt[1] && $loc_pt[1] > $loc_pt[0]) + if ($loc_pt[1] && $loc_pt[1] > $loc_pt[0]) { $delta = $loc_pt[1] - $loc_pt[0]; - else + } else { $delta = 0; + } - if(($inetdport + $delta + 1) - $starting_localhost_port_tmp > 500) { + if (($inetdport + $delta + 1) - $starting_localhost_port_tmp > 500) { log_error("Not installing NAT reflection rules for a port range > 500"); $inetdport = $starting_localhost_port; $toadd_array = array(); $toomanyports = true; break; - } else if(($inetdport + $delta) > 19990) { + } else if (($inetdport + $delta) > 19990) { log_error("Installing partial NAT reflection rules. Maximum 1,000 reached."); $delta = 19990 - $inetdport; $loc_pt[1] = $loc_pt[0] + $delta; - if($delta == 0) + if ($delta == 0) { unset($loc_pt[1]); + } $toomanyports = true; - if(!empty($localport)) { - if(is_alias($rule['destination']['port'])) { + if (!empty($localport)) { + if (is_alias($rule['destination']['port'])) { $rflctintrange = alias_expand($rule['destination']['port']); } else { - if($dstport_split[1]) + if ($dstport_split[1]) { $dstport_split[1] = $dstport_split[0] + $inetdport + $delta - $starting_localhost_port; + } $rflctintrange = implode(":", $dstport_split); } } } - if(empty($localport)) + if (empty($localport)) { $rflctintrange = implode(":", $loc_pt); - if($inetdport + $delta > $starting_localhost_port) + } + if ($inetdport + $delta > $starting_localhost_port) { $rflctrange .= ":" . ($inetdport + $delta); + } $starting_localhost_port = $inetdport + $delta + 1; $toadd_array = array_merge($toadd_array, range($loc_pt[0], $loc_pt[0] + $delta)); - if(!empty($toadd_array)) { + if (!empty($toadd_array)) { $rtarget = explode(" ", trim($target)); - foreach($toadd_array as $tda) { - if (empty($tda)) + foreach ($toadd_array as $tda) { + if (empty($tda)) { continue; - foreach($reflect_protos as $reflect_proto) { - if($reflect_proto == "udp") { + } + foreach ($reflect_protos as $reflect_proto) { + if ($reflect_proto == "udp") { $socktype = "dgram"; $dash_u = "-u "; $wait = "wait\t"; @@ -1356,8 +1461,9 @@ function filter_generate_reflection_proxy($rule, $nordr, $rdr_ifs, $srcaddr, $ds $wait = "nowait/0"; } foreach ($rtarget as $targip) { - if (empty($targip)) + if (empty($targip)) { continue; + } $reflection_txt[] = "{$inetdport}\t{$socktype}\t{$reflect_proto}\t{$wait}\tnobody\t/usr/bin/nc\tnc {$dash_u}-w {$reflectiontimeout} {$targip} {$tda}\n"; } } @@ -1367,8 +1473,9 @@ function filter_generate_reflection_proxy($rule, $nordr, $rdr_ifs, $srcaddr, $ds } } - if($toomanyports) + if ($toomanyports) { break; + } } $reflection_txt = array_unique($reflection_txt); @@ -1387,7 +1494,7 @@ function filter_nat_rules_automatic_tonathosts($with_descr = false) { $netip = explode("/", $route['network']); if (isset($GatewaysList[$route['gateway']])) { $gateway =& $GatewaysList[$route['gateway']]; - if(!interface_has_gateway($gateway['interface']) && is_private_ip($netip[0])) { + if (!interface_has_gateway($gateway['interface']) && is_private_ip($netip[0])) { $tonathosts[] = $route['network']; $descriptions[] = gettext("static route"); } @@ -1395,25 +1502,29 @@ function filter_nat_rules_automatic_tonathosts($with_descr = false) { } /* create outbound nat entries for all local networks */ - foreach($FilterIflist as $ocname => $oc) { - if(interface_has_gateway($ocname)) + foreach ($FilterIflist as $ocname => $oc) { + if (interface_has_gateway($ocname)) { continue; - if(is_ipaddr($oc['alias-address'])) { + } + if (is_ipaddr($oc['alias-address'])) { $tonathosts[] = "{$oc['alias-address']}/{$oc['alias-subnet']}"; $descriptions[] = $oc['descr'] . " " . gettext("DHCP alias address"); } - if($oc['sa']) { + if ($oc['sa']) { $tonathosts[] = "{$oc['sa']}/{$oc['sn']}"; $descriptions[] = $oc['descr']; if (isset($oc['vips']) && is_array($oc['vips'])) { $if_subnets = array("{$oc['sa']}/{$oc['sn']}"); foreach ($oc['vips'] as $vip) { - if (!is_ipaddrv4($vip['ip'])) + if (!is_ipaddrv4($vip['ip'])) { continue; + } - foreach ($if_subnets as $subnet) - if (ip_in_subnet($vip['ip'], $subnet)) + foreach ($if_subnets as $subnet) { + if (ip_in_subnet($vip['ip'], $subnet)) { continue 2; + } + } $network = gen_subnet($vip['ip'], $vip['sn']); array_unshift($tonathosts, $network . '/' . $vip['sn']); @@ -1427,13 +1538,14 @@ function filter_nat_rules_automatic_tonathosts($with_descr = false) { } /* PPTP subnet */ - if(($config['pptpd']['mode'] == "server" ) && is_private_ip($config['pptpd']['remoteip'])) { - if (isset($config['pptpd']['n_pptp_units']) && is_numeric($config['pptpd']['n_pptp_units'])) + if (($config['pptpd']['mode'] == "server" ) && is_private_ip($config['pptpd']['remoteip'])) { + if (isset($config['pptpd']['n_pptp_units']) && is_numeric($config['pptpd']['n_pptp_units'])) { $pptp_subnets = ip_range_to_subnet_array($config['pptpd']['remoteip'], long2ip32(ip2long($config['pptpd']['remoteip'])+($config['pptpd']['n_pptp_units']-1))); - else + } else { $pptp_subnets = ip_range_to_subnet_array($config['pptpd']['remoteip'], long2ip32(ip2long($config['pptpd']['remoteip']))); + } foreach ($pptp_subnets as $subnet) { $tonathosts[] = $subnet; @@ -1442,42 +1554,48 @@ function filter_nat_rules_automatic_tonathosts($with_descr = false) { } /* PPPoE subnet */ - if (is_array($FilterIflist['pppoe'])) - foreach ($FilterIflist['pppoe'] as $pppoe) - if(is_private_ip($pppoe['ip'])) { + if (is_array($FilterIflist['pppoe'])) { + foreach ($FilterIflist['pppoe'] as $pppoe) { + if (is_private_ip($pppoe['ip'])) { $tonathosts[] = "{$pppoe['sa']}/{$pppoe['sn']}"; $descriptions[] = gettext("PPPoE server"); } + } + } /* L2TP subnet */ - if(isset($FilterIflist['l2tp']) && $FilterIflist['l2tp']['mode'] == "server") { + if (isset($FilterIflist['l2tp']) && $FilterIflist['l2tp']['mode'] == "server") { $l2tp_sa = $FilterIflist['l2tp']['sa']; $l2tp_sn = $FilterIflist['l2tp']['sn']; - if(is_private_ip($l2tp_sa) && !empty($l2tp_sn)) { + if (is_private_ip($l2tp_sa) && !empty($l2tp_sn)) { $tonathosts[] = "{$l2tp_sa}/{$l2tp_sn}"; $descriptions[] = gettext("L2TP server"); } } /* add openvpn interfaces */ - if(is_array($config['openvpn']['openvpn-server'])) - foreach ($config['openvpn']['openvpn-server'] as $ovpnsrv) + if (is_array($config['openvpn']['openvpn-server'])) { + foreach ($config['openvpn']['openvpn-server'] as $ovpnsrv) { if (!isset($ovpnsrv['disable']) && !empty($ovpnsrv['tunnel_network'])) { $tonathosts[] = $ovpnsrv['tunnel_network']; $descriptions[] = gettext("OpenVPN server"); } + } + } - if(is_array($config['openvpn']['openvpn-client'])) - foreach ($config['openvpn']['openvpn-client'] as $ovpncli) + if (is_array($config['openvpn']['openvpn-client'])) { + foreach ($config['openvpn']['openvpn-client'] as $ovpncli) { if (!isset($ovpncli['disable']) && !empty($ovpncli['tunnel_network'])) { $tonathosts[] = $ovpncli['tunnel_network']; $descriptions[] = gettext("OpenVPN client"); } + } + } /* IPsec mode_cfg subnet */ - if (isset($config['ipsec']['client']['enable']) && - !empty($config['ipsec']['client']['pool_address']) && - !empty($config['ipsec']['client']['pool_netbits'])) { + if ((isset($config['ipsec']['client']['enable'])) && + (!empty($config['ipsec']['client']['pool_address'])) && + (!empty($config['ipsec']['client']['pool_netbits']))) { $tonathosts[] = "{$config['ipsec']['client']['pool_address']}/{$config['ipsec']['client']['pool_netbits']}"; $descriptions[] = gettext("IPsec client"); } @@ -1491,8 +1609,9 @@ function filter_nat_rules_automatic_tonathosts($with_descr = false) { } return $combined; - } else + } else { return $tonathosts; + } } function filter_nat_rules_outbound_automatic($src) { @@ -1500,10 +1619,12 @@ function filter_nat_rules_outbound_automatic($src) { $rules = array(); foreach ($FilterIflist as $if => $ifcfg) { - if (substr($ifcfg['if'], 0, 4) == "ovpn") + if (substr($ifcfg['if'], 0, 4) == "ovpn") { continue; - if (!interface_has_gateway($if)) + } + if (!interface_has_gateway($if)) { continue; + } $natent = array(); $natent['interface'] = $if; @@ -1523,8 +1644,9 @@ function filter_nat_rules_outbound_automatic($src) { $natent['destination']['any'] = true; $natent['natport'] = ""; $natent['descr'] = gettext('Auto created rule'); - if (isset($ifcfg['nonat'])) + if (isset($ifcfg['nonat'])) { $natent['nonat'] = true; + } $rules[] = $natent; } @@ -1532,70 +1654,82 @@ function filter_nat_rules_outbound_automatic($src) { } /* Generate a 'nat on' or 'no nat on' rule for given interface */ -function filter_nat_rules_generate_if($if, $src = "any", $srcport = "", $dst = "any", $dstport = "", $natip = "", $natport = "", $nonat = false, $staticnatport = false, $proto = "", $poolopts = "") { +function filter_nat_rules_generate_if ($if, $src = "any", $srcport = "", $dst = "any", $dstport = "", $natip = "", $natport = "", $nonat = false, $staticnatport = false, $proto = "", $poolopts = "") { global $config, $FilterIflist; /* XXX: billm - any idea if this code is needed? */ - if($src == "/32" || $src{0} == "/") + if ($src == "/32" || $src{0} == "/") { return "# src incorrectly specified\n"; - if($natip != "") { - if (is_subnet($natip)) + } + if ($natip != "") { + if (is_subnet($natip)) { $tgt = $natip; - elseif (is_alias($natip)) + } elseif (is_alias($natip)) { $tgt = "\${$natip}"; - else + } else { $tgt = "{$natip}/32"; + } } else { $natip = get_interface_ip($if); - if(is_ipaddr($natip)) + if (is_ipaddr($natip)) { $tgt = "{$natip}/32"; - else + } else { $tgt = "(" . $FilterIflist[$if]['if'] . ")"; + } } /* Add the protocol, if defined */ if (!empty($proto) && $proto != "any") { - if ($proto == "tcp/udp") + if ($proto == "tcp/udp") { $protocol = " proto { tcp udp }"; - else + } else { $protocol = " proto {$proto}"; - } else + } + } else { $protocol = ""; - /* Set tgt for IPv6 */ + } + /* Set tgt for IPv6 */ if ($proto == "ipv6") { $natip = get_interface_ipv6($if); - if(is_ipaddrv6($natip)) + if (is_ipaddrv6($natip)) { $tgt = "{$natip}/128"; + } } /* Add the hard set source port (useful for ISAKMP) */ - if($natport != "") + if ($natport != "") { $tgt .= " port {$natport}"; + } /* sometimes this gets called with "" instead of a value */ - if($src == "") + if ($src == "") { $src = "any"; + } /* Match on this source port */ - if($srcport != "") { + if ($srcport != "") { $srcportexpand = alias_expand($srcport); - if(!$srcportexpand) + if (!$srcportexpand) { $srcportexpand = $srcport; + } $src .= " port {$srcportexpand}"; } /* sometimes this gets called with "" instead of a value */ - if($dst == "") + if ($dst == "") { $dst = "any"; + } /* Match on this dest port */ - if($dstport != "") { + if ($dstport != "") { $dstportexpand = alias_expand($dstport); - if(!$dstportexpand) + if (!$dstportexpand) { $dstportexpand = $dstport; + } $dst .= " port {$dstportexpand}"; } /* outgoing static-port option, hamachi, Grandstream, VOIP, etc */ $staticnatport_txt = ""; - if($staticnatport) + if ($staticnatport) { $staticnatport_txt = "static-port"; - elseif(!$natport) + } elseif (!$natport) { $tgt .= " port 1024:65535"; // set source port range + } /* Allow for negating NAT entries */ - if($nonat) { + if ($nonat) { $nat = "no nat"; $target = ""; $staticnatport_txt = ""; @@ -1606,10 +1740,11 @@ function filter_nat_rules_generate_if($if, $src = "any", $srcport = "", $dst = " } $if_friendly = $FilterIflist[$if]['descr']; /* Put all the pieces together */ - if($if_friendly) + if ($if_friendly) { $natrule = "{$nat} on \${$if_friendly} {$protocol} from {$src} to {$dst} {$target} {$poolopts} {$staticnatport_txt}\n"; - else + } else { $natrule .= "# Could not convert {$if} to friendly name(alias)\n"; + } return $natrule; } @@ -1627,10 +1762,11 @@ function filter_nat_rules_generate() { $route_table = ""; /* any 1:1 mappings? */ - if(is_array($config['nat']['onetoone'])) { + if (is_array($config['nat']['onetoone'])) { foreach ($config['nat']['onetoone'] as $rule) { - if (isset($rule['disabled'])) + if (isset($rule['disabled'])) { continue; + } $sn = ""; $sn1 = ""; @@ -1640,17 +1776,20 @@ function filter_nat_rules_generate() { continue; /* unresolvable alias */ } - if (!$rule['interface']) + if (!$rule['interface']) { $natif = "wan"; - else + } else { $natif = $rule['interface']; - if (!isset($FilterIflist[$natif])) + } + if (!isset($FilterIflist[$natif])) { continue; + } $srcaddr = filter_generate_address($rule, 'source'); $dstaddr = filter_generate_address($rule, 'destination'); - if(!$dstaddr) + if (!$dstaddr) { $dstaddr = $FilterIflist[$natif]['ip']; + } $srcaddr = trim($srcaddr); $dstaddr = trim($dstaddr); @@ -1668,11 +1807,12 @@ function filter_nat_rules_generate() { * If reflection is enabled, turn on extra redirections * for this rule by adding other interfaces to an rdr rule. */ - if ((isset($config['system']['enablebinatreflection']) || $rule['natreflection'] == "enable") - && $rule['natreflection'] != "disable") + if ((isset($config['system']['enablebinatreflection']) || $rule['natreflection'] == "enable") && + ($rule['natreflection'] != "disable")) { $nat_if_list = filter_get_reflection_interfaces($natif); - else + } else { $nat_if_list = array(); + } $natrules .= "binat on {$natif} from {$srcaddr} to {$dstaddr} -> {$target}{$sn1}\n"; if (!empty($nat_if_list)) { @@ -1687,17 +1827,20 @@ function filter_nat_rules_generate() { } /* Add binat rules for Network Prefix translation */ - if(is_array($config['nat']['npt'])) { + if (is_array($config['nat']['npt'])) { foreach ($config['nat']['npt'] as $rule) { - if (isset($rule['disabled'])) + if (isset($rule['disabled'])) { continue; + } - if (!$rule['interface']) + if (!$rule['interface']) { $natif = "wan"; - else + } else { $natif = $rule['interface']; - if (!isset($FilterIflist[$natif])) + } + if (!isset($FilterIflist[$natif])) { continue; + } $srcaddr = filter_generate_address($rule, 'source'); $dstaddr = filter_generate_address($rule, 'destination'); @@ -1718,43 +1861,55 @@ function filter_nat_rules_generate() { if (is_array($config['ipsec']['phase2'])) { foreach ($config['ipsec']['phase2'] as $ph2ent) { if ($ph2ent['mode'] != 'transport' && !empty($ph2ent['natlocalid'])) { - if (!function_exists('ipsec_idinfo_to_cidr')) + if (!function_exists('ipsec_idinfo_to_cidr')) { require_once("ipsec.inc"); - if (!is_array($ph2ent['localid'])) + } + if (!is_array($ph2ent['localid'])) { $ph2ent['localid'] = array(); + } $ph2ent['localid']['mode'] = $ph2ent['mode']; $local_subnet = ipsec_idinfo_to_cidr($ph2ent['localid']); - if (empty($local_subnet) || $local_subnet == "0.0.0.0/0") + if (empty($local_subnet) || $local_subnet == "0.0.0.0/0") { continue; - if (!is_subnet($local_subnet) && !is_ipaddr($local_subnet)) + } + if (!is_subnet($local_subnet) && !is_ipaddr($local_subnet)) { continue; - if (!is_array($ph2ent['natlocalid'])) + } + if (!is_array($ph2ent['natlocalid'])) { $ph2ent['natlocalid'] = array(); + } $ph2ent['natlocalid']['mode'] = $ph2ent['mode']; $natlocal_subnet = ipsec_idinfo_to_cidr($ph2ent['natlocalid']); - if (empty($natlocal_subnet) || $natlocal_subnet == "0.0.0.0/0") + if (empty($natlocal_subnet) || $natlocal_subnet == "0.0.0.0/0") { continue; - if (!is_subnet($natlocal_subnet) && !is_ipaddr($natlocal_subnet)) + } + if (!is_subnet($natlocal_subnet) && !is_ipaddr($natlocal_subnet)) { continue; - if (!is_array($ph2ent['remoteid'])) + } + if (!is_array($ph2ent['remoteid'])) { $ph2ent['remoteid'] = array(); + } $ph2ent['remoteid']['mode'] = $ph2ent['mode']; $remote_subnet = ipsec_idinfo_to_cidr($ph2ent['remoteid']); - if (empty($remote_subnet)) + if (empty($remote_subnet)) { continue; - if (!is_subnet($remote_subnet) && !is_ipaddr($remote_subnet)) + } + if (!is_subnet($remote_subnet) && !is_ipaddr($remote_subnet)) { continue; - if ($remote_subnet == "0.0.0.0/0") + } + if ($remote_subnet == "0.0.0.0/0") { $remote_subnet = "any"; - if (is_ipaddr($natlocal_subnet) && !is_ipaddr($local_subnet) ) + } + if (is_ipaddr($natlocal_subnet) && !is_ipaddr($local_subnet) ) { $nattype = "nat"; - else { + } else { list($natnet, $natmask) = explode('/', $natlocal_subnet); list($locnet, $locmask) = explode('/', $local_subnet); - if (intval($natmask) != intval($locmask)) + if (intval($natmask) != intval($locmask)) { $nattype = "nat"; - else + } else { $nattype = "binat"; + } unset($natnet, $natmask, $locnet, $locmask); } $natrules .= "{$nattype} on enc0 from {$local_subnet} to {$remote_subnet} -> {$natlocal_subnet}\n"; @@ -1763,28 +1918,34 @@ function filter_nat_rules_generate() { } } - if ($config['nat']['outbound']['mode'] == "disabled") + if ($config['nat']['outbound']['mode'] == "disabled") { $natrules .= "\n# Outbound NAT rules are disabled\n"; + } if ($config['nat']['outbound']['mode'] == "advanced" || $config['nat']['outbound']['mode'] == "hybrid") { $natrules .= "\n# Outbound NAT rules (manual)\n"; /* advanced outbound rules */ - if(is_array($config['nat']['outbound']['rule'])) { + if (is_array($config['nat']['outbound']['rule'])) { foreach ($config['nat']['outbound']['rule'] as $obent) { - if (isset($obent['disabled'])) + if (isset($obent['disabled'])) { continue; + } update_filter_reload_status(sprintf(gettext("Creating advanced outbound rule %s"), $obent['descr'])); $src = alias_expand($obent['source']['network']); - if(!$src) + if (!$src) { $src = $obent['source']['network']; + } $dst = alias_expand($obent['destination']['address']); - if(!$dst) + if (!$dst) { $dst = $obent['destination']['address']; - if(isset($obent['destination']['not']) && !isset($obent['destination']['any'])) + } + if (isset($obent['destination']['not']) && !isset($obent['destination']['any'])) { $dst = "!" . $dst; + } - if(!$obent['interface'] || !isset($FilterIflist[$obent['interface']])) + if (!$obent['interface'] || !isset($FilterIflist[$obent['interface']])) { continue; + } $obtarget = ($obent['target'] == "other-subnet") ? $obent['targetip'] . '/' . $obent['targetip_subnet']: $obent['target']; $poolopts = (is_subnet($obtarget) || is_alias($obtarget)) ? $obent['poolopts'] : ""; @@ -1806,9 +1967,9 @@ function filter_nat_rules_generate() { } /* outbound rules */ - if (!isset($config['nat']['outbound']['mode']) || - $config['nat']['outbound']['mode'] == "automatic" || - $config['nat']['outbound']['mode'] == "hybrid") { + if ((!isset($config['nat']['outbound']['mode'])) || + ($config['nat']['outbound']['mode'] == "automatic") || + ($config['nat']['outbound']['mode'] == "hybrid")) { $natrules .= "\n# Outbound NAT rules (automatic)\n"; /* standard outbound rules (one for each interface) */ update_filter_reload_status(gettext("Creating outbound NAT rules")); @@ -1854,58 +2015,62 @@ function filter_nat_rules_generate() { if (!empty($config['system']['tftpinterface'])) { $tftpifs = explode(",", $config['system']['tftpinterface']); - foreach($tftpifs as $tftpif) { - if ($FilterIflist[$tftpif]) + foreach ($tftpifs as $tftpif) { + if ($FilterIflist[$tftpif]) { $natrules .= "rdr pass on {$FilterIflist[$tftpif]['if']} proto udp from any to any port tftp -> 127.0.0.1 port 6969\n"; + } } } /* DIAG: add ipv6 NAT, if requested */ - if(isset($config['diag']['ipv6nat']['enable']) && - is_ipaddr($config['diag']['ipv6nat']['ipaddr']) && - is_array($FilterIflist['wan'])) { + if ((isset($config['diag']['ipv6nat']['enable'])) && + (is_ipaddr($config['diag']['ipv6nat']['ipaddr'])) && + (is_array($FilterIflist['wan']))) { /* XXX: FIX ME! IPV6 */ $natrules .= "rdr on \${$FilterIflist['wan']['descr']} proto ipv6 from any to any -> {$config['diag']['ipv6nat']['ipaddr']}\n"; } - if(file_exists("/var/etc/inetd.conf")) + if (file_exists("/var/etc/inetd.conf")) { @unlink("/var/etc/inetd.conf"); + } // Open inetd.conf write handle $inetd_fd = fopen("/var/etc/inetd.conf","w"); /* add tftp protocol helper */ fwrite($inetd_fd, "tftp-proxy\tdgram\tudp\twait\t\troot\t/usr/libexec/tftp-proxy\ttftp-proxy -v\n"); - if(isset($config['nat']['rule'])) { + if (isset($config['nat']['rule'])) { /* start reflection redirects on port 19000 of localhost */ $starting_localhost_port = 19000; $natrules .= "# NAT Inbound Redirects\n"; foreach ($config['nat']['rule'] as $rule) { update_filter_reload_status(sprintf(gettext("Creating NAT rule %s"), $rule['descr'])); - if(isset($rule['disabled'])) + if (isset($rule['disabled'])) { continue; + } /* if item is an alias, expand */ $dstport = ""; $dstport[0] = alias_expand($rule['destination']['port']); - if(!$dstport[0]) + if (!$dstport[0]) { $dstport = explode("-", $rule['destination']['port']); + } /* if item is an alias, expand */ $localport = alias_expand($rule['local-port']); - if(!$localport || $dstport[0] == $localport) { + if (!$localport || $dstport[0] == $localport) { $localport = ""; - } else if(is_alias($rule['local-port'])) { + } else if (is_alias($rule['local-port'])) { $localport = filter_expand_alias($rule['local-port']); - if($localport) { + if ($localport) { $localport = explode(" ", trim($localport)); $localport = $localport[0]; $localport = " port {$localport}"; } - } else if(is_alias($rule['destination']['port'])) { + } else if (is_alias($rule['destination']['port'])) { $localport = " port {$localport}"; } else { - if(($dstport[1]) && ($dstport[0] != $dstport[1])) { + if (($dstport[1]) && ($dstport[0] != $dstport[1])) { $localendport = $localport + ($dstport[1] - $dstport[0]); $localport .= ":$localendport"; @@ -1914,114 +2079,127 @@ function filter_nat_rules_generate() { $localport = " port {$localport}"; } - switch(strtolower($rule['protocol'])) { - case "tcp/udp": - $protocol = "{ tcp udp }"; - break; - case "tcp": - case "udp": - $protocol = strtolower($rule['protocol']); - break; - default: - $protocol = strtolower($rule['protocol']); - $localport = ""; - break; + switch (strtolower($rule['protocol'])) { + case "tcp/udp": + $protocol = "{ tcp udp }"; + break; + case "tcp": + case "udp": + $protocol = strtolower($rule['protocol']); + break; + default: + $protocol = strtolower($rule['protocol']); + $localport = ""; + break; } $target = alias_expand($rule['target']); - if(!$target && !isset($rule['nordr'])) { + if (!$target && !isset($rule['nordr'])) { $natrules .= "# Unresolvable alias {$rule['target']}\n"; continue; /* unresolvable alias */ } - if(is_alias($rule['target'])) + if (is_alias($rule['target'])) { $target_ip = filter_expand_alias($rule['target']); - else if(is_ipaddr($rule['target'])) + } else if (is_ipaddr($rule['target'])) { $target_ip = $rule['target']; - else if(is_ipaddr($FilterIflist[$rule['target']]['ip'])) + } else if (is_ipaddr($FilterIflist[$rule['target']]['ip'])) { $target_ip = $FilterIflist[$rule['target']]['ip']; - else + } else { $target_ip = $rule['target']; + } $target_ip = trim($target_ip); - if($rule['associated-rule-id'] == "pass") + if ($rule['associated-rule-id'] == "pass") { $rdrpass = "pass "; - else + } else { $rdrpass = ""; + } if (isset($rule['nordr'])) { $nordr = "no "; $rdrpass = ""; - } else + } else { $nordr = ""; + } - if(!$rule['interface']) + if (!$rule['interface']) { $natif = "wan"; - else + } else { $natif = $rule['interface']; + } - if (!isset($FilterIflist[$natif])) + if (!isset($FilterIflist[$natif])) { continue; + } $srcaddr = filter_generate_address($rule, 'source', true); $dstaddr = filter_generate_address($rule, 'destination', true); $srcaddr = trim($srcaddr); $dstaddr = trim($dstaddr); - if(!$dstaddr) + if (!$dstaddr) { $dstaddr = $FilterIflist[$natif]['ip']; + } $dstaddr_port = explode(" ", $dstaddr); - if(empty($dstaddr_port[0]) || strtolower(trim($dstaddr_port[0])) == "port") + if (empty($dstaddr_port[0]) || strtolower(trim($dstaddr_port[0])) == "port") { continue; // Skip port forward if no destination address found + } $dstaddr_reflect = $dstaddr; - if(isset($rule['destination']['any'])) { + if (isset($rule['destination']['any'])) { /* With reflection enabled, destination of 'any' has side effects * that most people would not expect, so change it on reflection rules. */ $dstaddr_reflect = $FilterIflist[$natif]['ip']; - if(!empty($FilterIflist[$natif]['sn'])) + if (!empty($FilterIflist[$natif]['sn'])) { $dstaddr_reflect = gen_subnet($dstaddr_reflect, $FilterIflist[$natif]['sn']) . '/' . $FilterIflist[$natif]['sn']; + } - if($dstaddr_port[2]) + if ($dstaddr_port[2]) { $dstaddr_reflect .= " port " . $dstaddr_port[2]; + } } $natif = $FilterIflist[$natif]['if']; $reflection_type = "none"; - if($rule['natreflection'] != "disable" && $dstaddr_port[0] != "0.0.0.0") { - if($rule['natreflection'] == "enable") + if ($rule['natreflection'] != "disable" && $dstaddr_port[0] != "0.0.0.0") { + if ($rule['natreflection'] == "enable") { $reflection_type = "proxy"; - else if($rule['natreflection'] == "purenat") + } else if ($rule['natreflection'] == "purenat") { $reflection_type = "purenat"; - else if(!isset($config['system']['disablenatreflection'])) { - if(isset($config['system']['enablenatreflectionpurenat'])) + } else if (!isset($config['system']['disablenatreflection'])) { + if (isset($config['system']['enablenatreflectionpurenat'])) { $reflection_type = "purenat"; - else + } else { $reflection_type = "proxy"; + } } } - if($reflection_type != "none") + if ($reflection_type != "none") { $nat_if_list = filter_get_reflection_interfaces($natif); - else + } else { $nat_if_list = array(); + } - if(empty($nat_if_list)) + if (empty($nat_if_list)) { $reflection_type = "none"; + } $localport_nat = $localport; - if(empty($localport_nat) && $dstaddr_port[2]) + if (empty($localport_nat) && $dstaddr_port[2]) { $localport_nat = " port " . $dstaddr_port[2]; + } - if($srcaddr <> "" && $dstaddr <> "" && $natif) { + if ($srcaddr <> "" && $dstaddr <> "" && $natif) { $natrules .= "{$nordr}rdr {$rdrpass}on {$natif} proto {$protocol} from {$srcaddr} to {$dstaddr}" . ($nordr == "" ? " -> {$target}{$localport}" : ""); /* Does this rule redirect back to a internal host? */ - if(isset($rule['destination']['any']) && !isset($rule['nordr']) && !isset($config['system']['enablenatreflectionhelper']) && !interface_has_gateway($rule['interface'])) { + if (isset($rule['destination']['any']) && !isset($rule['nordr']) && !isset($config['system']['enablenatreflectionhelper']) && !interface_has_gateway($rule['interface'])) { $rule_interface_ip = find_interface_ip($natif); $rule_interface_subnet = find_interface_subnet($natif); - if(!empty($rule_interface_ip) && !empty($rule_interface_subnet)) { + if (!empty($rule_interface_ip) && !empty($rule_interface_subnet)) { $rule_subnet = gen_subnet($rule_interface_ip, $rule_interface_subnet); $natrules .= "\n"; $natrules .= "no nat on {$natif} proto tcp from ({$natif}) to {$rule_subnet}/{$rule_interface_subnet}\n"; @@ -2030,27 +2208,31 @@ function filter_nat_rules_generate() { } if ($reflection_type != "none") { - if($reflection_type == "proxy" && !isset($rule['nordr'])) { + if ($reflection_type == "proxy" && !isset($rule['nordr'])) { $natrules .= filter_generate_reflection_proxy($rule, $nordr, $nat_if_list, $srcaddr, $dstaddr, $starting_localhost_port, $reflection_rules); $nat_if_list = array($natif); - foreach ($reflection_rules as $txtline) + foreach ($reflection_rules as $txtline) { fwrite($inetd_fd, $txtline); - } else if($reflection_type == "purenat" || isset($rule['nordr'])) { + } + } else if ($reflection_type == "purenat" || isset($rule['nordr'])) { $rdr_if_list = implode(" ", $nat_if_list); - if(count($nat_if_list) > 1) + if (count($nat_if_list) > 1) { $rdr_if_list = "{ {$rdr_if_list} }"; + } $natrules .= "\n# Reflection redirect\n"; $natrules .= "{$nordr}rdr {$rdrpass}on {$rdr_if_list} proto {$protocol} from {$srcaddr} to {$dstaddr_reflect}" . ($nordr == "" ? " -> {$target}{$localport}" : ""); $nat_if_list = array_merge(array($natif), $nat_if_list); } } - if(empty($nat_if_list)) + if (empty($nat_if_list)) { $nat_if_list = array($natif); + } $natrules .= "\n"; - if(!isset($rule['nordr'])) + if (!isset($rule['nordr'])) { $natrules .= filter_generate_reflection_nat($rule, $route_table, $nat_if_list, $protocol, "{$target}{$localport_nat}", $target_ip); + } } } } @@ -2070,16 +2252,18 @@ function filter_nat_rules_generate() { $natrules .= "# UPnPd rdr anchor\n"; $natrules .= "rdr-anchor \"miniupnpd\"\n"; - if(!empty($reflection_txt)) + if (!empty($reflection_txt)) { $natrules .= "\n# Reflection redirects and NAT for 1:1 mappings\n" . $reflection_txt; + } // Check if inetd is running, if not start it. If so, restart it gracefully. $helpers = isvalidproc("inetd"); - if(file_exists("/var/etc/inetd.conf")) { - if(!$helpers) + if (file_exists("/var/etc/inetd.conf")) { + if (!$helpers) { mwexec("/usr/sbin/inetd -wW -R 0 -a 127.0.0.1 /var/etc/inetd.conf"); - else + } else { sigkillbypid("/var/run/inetd.pid", "HUP"); + } } return $natrules; @@ -2092,10 +2276,11 @@ function filter_generate_user_rule_arr($rule) { $line = filter_generate_user_rule($rule); $ret['rule'] = $line; $ret['interface'] = $rule['interface']; - if($rule['descr'] != "" and $line != "") + if ($rule['descr'] != "" and $line != "") { $ret['descr'] = "label \"" . fix_rule_label("USER_RULE: {$rule['descr']}") . "\""; - else + } else { $ret['descr'] = "label \"USER_RULE\""; + } return $ret; } @@ -2105,22 +2290,22 @@ function filter_generate_port(& $rule, $target = "source", $isnat = false) { $src = ""; $rule['protocol'] = strtolower($rule['protocol']); - if(in_array($rule['protocol'], array("tcp","udp","tcp/udp"))) { - if($rule[$target]['port']) { + if (in_array($rule['protocol'], array("tcp","udp","tcp/udp"))) { + if ($rule[$target]['port']) { $srcport = explode("-", $rule[$target]['port']); $srcporta = alias_expand($srcport[0]); - if(!$srcporta) + if (!$srcporta) { log_error(sprintf(gettext("filter_generate_port: %s is not a valid {$target} port."), $srcport[0])); - else if((!$srcport[1]) || ($srcport[0] == $srcport[1])) { + } else if ((!$srcport[1]) || ($srcport[0] == $srcport[1])) { $src .= " port {$srcporta} "; - } else if(($srcport[0] == 1) && ($srcport[1] == 65535)) { + } else if (($srcport[0] == 1) && ($srcport[1] == 65535)) { /* no need for a port statement here */ } else if ($isnat) { $src .= " port {$srcport[0]}:{$srcport[1]}"; } else { - if(is_port($srcporta) && $srcport[1] == 65535) { + if (is_port($srcporta) && $srcport[1] == 65535) { $src .= " port >= {$srcporta} "; - } else if($srcport[0] == 1) { + } else if ($srcport[0] == 1) { $src .= " port <= {$srcport[1]} "; } else { $srcport[0]--; @@ -2139,102 +2324,120 @@ function filter_address_add_vips_subnets(&$subnets, $if, $not) { $if_subnets = array($subnets); - if ($not == true) + if ($not == true) { $subnets = "!{$subnets}"; + } - if (!isset($FilterIflist[$if]['vips']) || !is_array($FilterIflist[$if]['vips'])) + if (!isset($FilterIflist[$if]['vips']) || !is_array($FilterIflist[$if]['vips'])) { return; + } foreach ($FilterIflist[$if]['vips'] as $vip) { - foreach ($if_subnets as $subnet) - if (ip_in_subnet($vip['ip'], $subnet)) + foreach ($if_subnets as $subnet) { + if (ip_in_subnet($vip['ip'], $subnet)) { continue 2; + } + } if (is_ipaddrv4($vip['ip'])) { - if (!is_subnetv4($if_subnets[0])) + if (!is_subnetv4($if_subnets[0])) { continue; + } $network = gen_subnet($vip['ip'], $vip['sn']); } else if (is_ipaddrv6($vip['ip'])) { - if (!is_subnetv6($if_subnets[0])) + if (!is_subnetv6($if_subnets[0])) { continue; + } $network = gen_subnetv6($vip['ip'], $vip['sn']); - } else + } else { continue; + } $subnets .= ' ' . ($not == true ? '!' : '') . $network . '/' . $vip['sn']; $if_subnets[] = $network . '/' . $vip['sn']; } unset($if_subnets); - if (strpos($subnets, ' ') !== false) + if (strpos($subnets, ' ') !== false) { $subnets = "{ {$subnets} }"; + } } function filter_generate_address(& $rule, $target = "source", $isnat = false) { global $FilterIflist, $config; $src = ""; - if(isset($rule[$target]['any'])) { + if (isset($rule[$target]['any'])) { $src = "any"; - } else if($rule[$target]['network']) { - if(strstr($rule[$target]['network'], "opt")) { + } else if ($rule[$target]['network']) { + if (strstr($rule[$target]['network'], "opt")) { $optmatch = ""; $matches = ""; - if($rule['ipprotocol'] == "inet6") { - if(preg_match("/opt([0-9]*)$/", $rule[$target]['network'], $optmatch)) { + if ($rule['ipprotocol'] == "inet6") { + if (preg_match("/opt([0-9]*)$/", $rule[$target]['network'], $optmatch)) { $opt_ip = $FilterIflist["opt{$optmatch[1]}"]['ipv6']; - if(!is_ipaddrv6($opt_ip)) + if (!is_ipaddrv6($opt_ip)) { return ""; + } $src = $opt_ip . "/" . $FilterIflist["opt{$optmatch[1]}"]['snv6']; /* check for opt$NUMip here */ - } else if(preg_match("/opt([0-9]*)ip/", $rule[$target]['network'], $matches)) { + } else if (preg_match("/opt([0-9]*)ip/", $rule[$target]['network'], $matches)) { $src = $FilterIflist["opt{$matches[1]}"]['ipv6']; - if(!is_ipaddrv6($src)) + if (!is_ipaddrv6($src)) { return ""; - if(isset($rule[$target]['not'])) + } + if (isset($rule[$target]['not'])) { $src = " !{$src}"; + } } } else { - if(preg_match("/opt([0-9]*)$/", $rule[$target]['network'], $optmatch)) { + if (preg_match("/opt([0-9]*)$/", $rule[$target]['network'], $optmatch)) { $opt_ip = $FilterIflist["opt{$optmatch[1]}"]['ip']; - if(!is_ipaddrv4($opt_ip)) + if (!is_ipaddrv4($opt_ip)) { return ""; + } $src = $opt_ip . "/" . $FilterIflist["opt{$optmatch[1]}"]['sn']; /* check for opt$NUMip here */ - } else if(preg_match("/opt([0-9]*)ip/", $rule[$target]['network'], $matches)) { + } else if (preg_match("/opt([0-9]*)ip/", $rule[$target]['network'], $matches)) { $src = $FilterIflist["opt{$matches[1]}"]['ip']; - if(!is_ipaddrv4($src)) + if (!is_ipaddrv4($src)) { return ""; - if(isset($rule[$target]['not'])) + } + if (isset($rule[$target]['not'])) { $src = " !{$src}"; + } } } } else { - if($rule['ipprotocol'] == "inet6") { + if ($rule['ipprotocol'] == "inet6") { switch ($rule[$target]['network']) { case 'wan': $wansa = $FilterIflist['wan']['sav6']; - if (!is_ipaddrv6($wansa)) + if (!is_ipaddrv6($wansa)) { return ""; + } $wansn = $FilterIflist['wan']['snv6']; $src = "{$wansa}/{$wansn}"; break; case 'wanip': $src = $FilterIflist["wan"]['ipv6']; - if (!is_ipaddrv6($src)) + if (!is_ipaddrv6($src)) { return ""; + } break; case 'lanip': $src = $FilterIflist["lan"]['ipv6']; - if (!is_ipaddrv6($src)) + if (!is_ipaddrv6($src)) { return ""; + } break; case 'lan': $lansa = $FilterIflist['lan']['sav6']; - if (!is_ipaddrv6($lansa)) + if (!is_ipaddrv6($lansa)) { return ""; + } $lansn = $FilterIflist['lan']['snv6']; $src = "{$lansa}/{$lansn}"; break; @@ -2253,14 +2456,16 @@ function filter_generate_address(& $rule, $target = "source", $isnat = false) { $src = "{$pppoesav6}/{$pppoesnv6}"; } } - if(isset($rule[$target]['not']) && !is_subnet($src)) + if (isset($rule[$target]['not']) && !is_subnet($src)) { $src = " !{$src}"; + } } else { switch ($rule[$target]['network']) { case 'wan': $wansa = $FilterIflist['wan']['sa']; - if (!is_ipaddrv4($wansa)) + if (!is_ipaddrv4($wansa)) { return ""; + } $wansn = $FilterIflist['wan']['sn']; $src = "{$wansa}/{$wansn}"; break; @@ -2272,8 +2477,9 @@ function filter_generate_address(& $rule, $target = "source", $isnat = false) { break; case 'lan': $lansa = $FilterIflist['lan']['sa']; - if (!is_ipaddrv4($lansa)) + if (!is_ipaddrv4($lansa)) { return ""; + } $lansn = $FilterIflist['lan']['sn']; $src = "{$lansa}/{$lansn}"; break; @@ -2281,16 +2487,19 @@ function filter_generate_address(& $rule, $target = "source", $isnat = false) { $src = "(self)"; break; case 'pptp': - if (isset($config['pptpd']['n_pptp_units']) && is_numeric($config['pptpd']['n_pptp_units'])) + if (isset($config['pptpd']['n_pptp_units']) && is_numeric($config['pptpd']['n_pptp_units'])) { $pptp_subnets = ip_range_to_subnet_array($config['pptpd']['remoteip'], long2ip32(ip2long($config['pptpd']['remoteip'])+($config['pptpd']['n_pptp_units']-1))); - else + } else { $pptp_subnets = ip_range_to_subnet_array($config['pptpd']['remoteip'], long2ip32(ip2long($config['pptpd']['remoteip']))); - if (empty($pptp_subnets)) + } + if (empty($pptp_subnets)) { return ""; - if(isset($rule[$target]['not'])) + } + if (isset($rule[$target]['not'])) { array_walk($pptp_subnets, function (&$value, $key) { $value="!{$value}"; }); + } $src = "{ " . implode(" ", $pptp_subnets) . " }"; break; case 'pppoe': @@ -2302,19 +2511,23 @@ function filter_generate_address(& $rule, $target = "source", $isnat = false) { } break; } - if(isset($rule[$target]['not']) && !is_subnet($src) && - (strpos($src, '{') === false)) + if ((isset($rule[$target]['not'])) && + (!is_subnet($src)) && + (strpos($src, '{') === false)) { $src = " !{$src}"; + } } } - if (is_subnet($src)) + if (is_subnet($src)) { filter_address_add_vips_subnets($src, $rule[$target]['network'], isset($rule[$target]['not'])); - } else if($rule[$target]['address']) { + } + } else if ($rule[$target]['address']) { $expsrc = alias_expand($rule[$target]['address']); - if(isset($rule[$target]['not'])) + if (isset($rule[$target]['not'])) { $not = "!"; - else + } else { $not = ""; + } $src = " {$not} {$expsrc}"; } @@ -2327,12 +2540,12 @@ function filter_generate_user_rule($rule) { global $config, $g, $FilterIflist, $GatewaysList; global $layer7_rules_list, $dummynet_name_list; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_generate_user_rule() being called $mt\n"; } /* don't include disabled rules */ - if(isset($rule['disabled'])) { + if (isset($rule['disabled'])) { return "# rule " . $rule['descr'] . " disabled \n"; } update_filter_reload_status("Creating filter rules {$rule['descr']} ..."); @@ -2341,125 +2554,139 @@ function filter_generate_user_rule($rule) { $aline = array(); /* Check to see if the interface is in our list */ - if(isset($rule['floating'])) { - if(isset($rule['interface']) && $rule['interface'] <> "") { + if (isset($rule['floating'])) { + if (isset($rule['interface']) && $rule['interface'] <> "") { $interfaces = explode(",", $rule['interface']); $ifliste = ""; foreach ($interfaces as $iface) { - if(array_key_exists($iface, $FilterIflist)) + if (array_key_exists($iface, $FilterIflist)) { $ifliste .= " " . $FilterIflist[$iface]['if'] . " "; + } } - if($ifliste <> "") + if ($ifliste <> "") { $aline['interface'] = " on { {$ifliste} } "; - else + } else { $aline['interface'] = ""; + } } else $aline['interface'] = ""; - } else if(!array_key_exists($rule['interface'], $FilterIflist)) { - foreach($FilterIflist as $oc) + } else if (!array_key_exists($rule['interface'], $FilterIflist)) { + foreach ($FilterIflist as $oc) { $items .= $oc['descr'] . " "; + } return "# array key \"{$rule['interface']}\" does not exist for \"" . $rule['descr'] . "\" in array: {{$items}}"; - } else if((array_key_exists($rule['interface'], $FilterIflist)) - && (is_array($FilterIflist[$rule['interface']])) - && (is_array($FilterIflist[$rule['interface']][0]))) { - /* Currently this only case for this is the pppoe server. There should be an existing macro with this name. */ + } else if ((array_key_exists($rule['interface'], $FilterIflist)) && + (is_array($FilterIflist[$rule['interface']])) && + (is_array($FilterIflist[$rule['interface']][0]))) { + /* Currently the only case for this is the pppoe server. There should be an existing macro with this name. */ $aline['interface'] = " on \$" . $rule['interface'] . " "; - } else + } else { $aline['interface'] = " on \$" . $FilterIflist[$rule['interface']]['descr'] . " "; + } $ifcfg = $FilterIflist[$rule['interface']]; - if($pptpdcfg['mode'] != "server") { - if(($rule['source']['network'] == "pptp") || - ($rule['destination']['network'] == "pptp")) - return "# source network or destination network == pptp on " . $rule['descr']; + if ($pptpdcfg['mode'] != "server") { + if (($rule['source']['network'] == "pptp") || + ($rule['destination']['network'] == "pptp")) { + return "# source network or destination network == pptp on " . $rule['descr']; + } } - switch($rule['ipprotocol']) { - case "inet": - $aline['ipprotocol'] = "inet"; - break; - case "inet6": - $aline['ipprotocol'] = "inet6"; - break; - default: - $aline['ipprotocol'] = ""; - break; + switch ($rule['ipprotocol']) { + case "inet": + $aline['ipprotocol'] = "inet"; + break; + case "inet6": + $aline['ipprotocol'] = "inet6"; + break; + default: + $aline['ipprotocol'] = ""; + break; } /* check for unresolvable aliases */ - if($rule['source']['address'] && !alias_expand($rule['source']['address'])) { + if ($rule['source']['address'] && !alias_expand($rule['source']['address'])) { $error_text = "Unresolvable source alias '{$rule['source']['address']}' for rule '{$rule['descr']}'"; file_notice("Filter_Reload", $error_text); return "# {$error_text}"; } - if($rule['destination']['address'] && !alias_expand($rule['destination']['address'])) { + if ($rule['destination']['address'] && !alias_expand($rule['destination']['address'])) { $error_text = "Unresolvable destination alias '{$rule['destination']['address']}' for rule '{$rule['descr']}'"; file_notice("Filter_Reload", $error_text); return "# {$error_text}"; } update_filter_reload_status("Setting up pass/block rules"); $type = $rule['type']; - if($type != "pass" && $type != "block" && $type != "reject" && $type != "match") { + if ($type != "pass" && $type != "block" && $type != "reject" && $type != "match") { /* default (for older rules) is pass */ $type = "pass"; } - if($type == "reject") { + if ($type == "reject") { $aline['type'] = "block return "; - } else + } else { $aline['type'] = $type . " "; - if(isset($rule['floating']) && $rule['floating'] == "yes") { - if($rule['direction'] != "any") + } + if (isset($rule['floating']) && $rule['floating'] == "yes") { + if ($rule['direction'] != "any") { $aline['direction'] = " " . $rule['direction'] . " "; + } } else { /* ensure the direction is in */ $aline['direction'] = " in "; } - if(isset($rule['log'])) + if (isset($rule['log'])) { $aline['log'] = "log "; - if(!isset($rule['floating']) || isset($rule['quick'])) + } + if (!isset($rule['floating']) || isset($rule['quick'])) { $aline['quick'] = " quick "; + } /* set the gateway interface */ update_filter_reload_status(sprintf(gettext("Setting up pass/block rules %s"), $rule['descr'])); /* do not process reply-to for gateway'd rules */ - if($rule['gateway'] == "" && $aline['direction'] <> "" && (interface_has_gateway($rule['interface']) || interface_has_gatewayv6($rule['interface'])) && !isset($config['system']['disablereplyto']) && !isset($rule['disablereplyto']) && $type != "match") { + if ($rule['gateway'] == "" && $aline['direction'] <> "" && (interface_has_gateway($rule['interface']) || interface_has_gatewayv6($rule['interface'])) && !isset($config['system']['disablereplyto']) && !isset($rule['disablereplyto']) && $type != "match") { if ($rule['ipprotocol'] == "inet6") { $rg = get_interface_gateway_v6($rule['interface']); - if (is_ipaddrv6($rg)) + if (is_ipaddrv6($rg)) { $aline['reply'] = "reply-to ( {$ifcfg['ifv6']} {$rg} ) "; - else if ($rule['interface'] <> "pptp") + } else if ($rule['interface'] <> "pptp") { log_error(sprintf(gettext("Could not find IPv6 gateway for interface (%s)."), $rule['interface'])); + } } else { $rg = get_interface_gateway($rule['interface']); - if (is_ipaddrv4($rg)) + if (is_ipaddrv4($rg)) { $aline['reply'] = "reply-to ( {$ifcfg['if']} {$rg} ) "; - else if ($rule['interface'] <> "pptp") + } else if ($rule['interface'] <> "pptp") { log_error(sprintf(gettext("Could not find IPv4 gateway for interface (%s)."), $rule['interface'])); + } } } /* if user has selected a custom gateway, lets work with it */ - else if($rule['gateway'] <> "" && $type == "pass") { - if (isset($GatewaysList[$rule['gateway']])) + else if ($rule['gateway'] <> "" && $type == "pass") { + if (isset($GatewaysList[$rule['gateway']])) { /* Add the load balanced gateways */ $aline['route'] = " \$GW{$rule['gateway']} "; - else if (isset($config['system']['skip_rules_gw_down'])) + } else if (isset($config['system']['skip_rules_gw_down'])) { return "# rule " . $rule['descr'] . " disabled because gateway " . $rule['gateway'] . " is down "; - else + } else { log_error("The gateway: {$rule['gateway']} is invalid or unknown, not using it."); + } } if (isset($rule['protocol']) && !empty($rule['protocol'])) { - if($rule['protocol'] == "tcp/udp") + if ($rule['protocol'] == "tcp/udp") { $aline['prot'] = " proto { tcp udp } "; - elseif(($rule['protocol'] == "icmp") && ($rule['ipprotocol'] == "inet6")) + } elseif (($rule['protocol'] == "icmp") && ($rule['ipprotocol'] == "inet6")) { $aline['prot'] = " proto ipv6-icmp "; - elseif($rule['protocol'] == "icmp") + } elseif ($rule['protocol'] == "icmp") { $aline['prot'] = " proto icmp "; - else + } else { $aline['prot'] = " proto {$rule['protocol']} "; + } } else { - if($rule['source']['port'] <> "" || $rule['destination']['port'] <> "") + if ($rule['source']['port'] <> "" || $rule['destination']['port'] <> "") { $aline['prot'] = " proto tcp "; + } } update_filter_reload_status(sprintf(gettext("Creating rule %s"), $rule['descr'])); @@ -2471,8 +2698,9 @@ function filter_generate_user_rule($rule) { $aline['src'] = " from $src "; /* OS signatures */ - if(($rule['protocol'] == "tcp") && ($rule['os'] <> "")) + if (($rule['protocol'] == "tcp") && ($rule['os'] <> "")) { $aline['os'] = " os \"{$rule['os']}\" "; + } /* destination address */ $dst = trim(filter_generate_address($rule, "destination")); @@ -2484,60 +2712,88 @@ function filter_generate_user_rule($rule) { //Layer7 support $l7_present = false; $l7_structures = array(); - if(isset($rule['l7container']) && $rule['l7container'] != "none") { + if (isset($rule['l7container']) && $rule['l7container'] != "none") { $l7_present = true; $l7rule =& $layer7_rules_list[$rule['l7container']]; $l7_structures = $l7rule->get_unique_structures(); $aline['divert'] = "divert-to " . $l7rule->GetRPort() . " "; } - if (($rule['protocol'] == "icmp") && $rule['icmptype'] && ($rule['ipprotocol'] == "inet")) + if (($rule['protocol'] == "icmp") && $rule['icmptype'] && ($rule['ipprotocol'] == "inet")) { $aline['icmp-type'] = "icmp-type {$rule['icmptype']} "; - if (($rule['protocol'] == "icmp") && $rule['icmptype'] && ($rule['ipprotocol'] == "inet6")) - $aline['icmp6-type'] = "icmp6-type {$rule['icmptype']} "; - if (!empty($rule['tag'])) { - if (ctype_digit($rule['tag'])) - $aline['tag'] = " tag \"" .$rule['tag']. "\" "; - else - $aline['tag'] = " tag " .$rule['tag']. " "; } - if (!empty($rule['tagged'])) - $aline['tagged'] = " tagged " .$rule['tagged'] . " "; - if (!empty($rule['dscp'])) { - switch (strtolower($rule['dscp'])) { - case 'va': $aline['dscp'] = " dscp \"44\" "; break; - case 'VA': $aline['dscp'] = " dscp \"44\" "; break; - case 'cs1': $aline['dscp'] = " dscp \"8\" "; break; - case 'cs2': $aline['dscp'] = " dscp \"16\" "; break; - case 'cs3': $aline['dscp'] = " dscp \"24\" "; break; - case 'cs4': $aline['dscp'] = " dscp \"32\" "; break; - case 'cs5': $aline['dscp'] = " dscp \"40\" "; break; - case 'cs6': $aline['dscp'] = " dscp \"48\" "; break; - case 'cs7': $aline['dscp'] = " dscp \"56\" "; break; - default: $aline['dscp'] = " dscp " . $rule['dscp'] . " "; break; + if (($rule['protocol'] == "icmp") && $rule['icmptype'] && ($rule['ipprotocol'] == "inet6")) { + $aline['icmp6-type'] = "icmp6-type {$rule['icmptype']} "; + } + if (!empty($rule['tag'])) { + if (ctype_digit($rule['tag'])) { + $aline['tag'] = " tag \"" .$rule['tag']. "\" "; + } else { + $aline['tag'] = " tag " .$rule['tag']. " "; } } - if (!empty($rule['vlanprio']) && ($rule['vlanprio'] != "none")) + if (!empty($rule['tagged'])) { + $aline['tagged'] = " tagged " .$rule['tagged'] . " "; + } + if (!empty($rule['dscp'])) { + switch (strtolower($rule['dscp'])) { + case 'va': + $aline['dscp'] = " dscp \"44\" "; + break; + case 'VA': + $aline['dscp'] = " dscp \"44\" "; + break; + case 'cs1': + $aline['dscp'] = " dscp \"8\" "; + break; + case 'cs2': + $aline['dscp'] = " dscp \"16\" "; + break; + case 'cs3': + $aline['dscp'] = " dscp \"24\" "; + break; + case 'cs4': + $aline['dscp'] = " dscp \"32\" "; + break; + case 'cs5': + $aline['dscp'] = " dscp \"40\" "; + break; + case 'cs6': + $aline['dscp'] = " dscp \"48\" "; + break; + case 'cs7': + $aline['dscp'] = " dscp \"56\" "; + break; + default: + $aline['dscp'] = " dscp " . $rule['dscp'] . " "; + break; + } + } + if (!empty($rule['vlanprio']) && ($rule['vlanprio'] != "none")) { $aline['vlanprio'] = " ieee8021q-pcp " . $rule['vlanprio'] . " "; - if (!empty($rule['vlanprioset']) && ($rule['vlanprioset'] != "none")) + } + if (!empty($rule['vlanprioset']) && ($rule['vlanprioset'] != "none")) { $aline['vlanprioset'] = " ieee8021q-setpcp " . $rule['vlanprioset'] . " "; + } if ($type == "pass") { - if (isset($rule['allowopts'])) + if (isset($rule['allowopts'])) { $aline['allowopts'] = " allow-opts "; + } } $aline['flags'] = ""; if ($rule['protocol'] == "tcp") { - if (isset($rule['tcpflags_any'])) + if (isset($rule['tcpflags_any'])) { $aline['flags'] = "flags any "; - else if (!empty($rule['tcpflags2'])) { + } else if (!empty($rule['tcpflags2'])) { $aline['flags'] = "flags "; if (!empty($rule['tcpflags1'])) { $flags1 = explode(",", $rule['tcpflags1']); foreach ($flags1 as $flag1) { // CWR flag needs special treatment - if($flag1[0] == "c") + if ($flag1[0] == "c") { $aline['flags'] .= "W"; - else + } else { $aline['flags'] .= strtoupper($flag1[0]); + } } } $aline['flags'] .= "/"; @@ -2545,10 +2801,11 @@ function filter_generate_user_rule($rule) { $flags2 = explode(",", $rule['tcpflags2']); foreach ($flags2 as $flag2) { // CWR flag needs special treatment - if($flag2[0] == "c") + if ($flag2[0] == "c") { $aline['flags'] .= "W"; - else + } else { $aline['flags'] .= strtoupper($flag2[0]); + } } } $aline['flags'] .= " "; @@ -2572,15 +2829,16 @@ function filter_generate_user_rule($rule) { */ $noadvoptions = false; if (isset($rule['statetype']) && $rule['statetype'] <> "") { - switch($rule['statetype']) { + switch ($rule['statetype']) { case "none": $noadvoptions = true; $aline['flags'] .= " no state "; break; case "modulate state": case "synproxy state": - if ($rule['protocol'] == "tcp") + if ($rule['protocol'] == "tcp") { $aline['flags'] .= "{$rule['statetype']} "; + } break; case "sloppy state": $aline['flags'] .= "keep state "; @@ -2590,13 +2848,15 @@ function filter_generate_user_rule($rule) { $aline['flags'] .= "{$rule['statetype']} "; break; } - } else + } else { $aline['flags'] .= "keep state "; + } - if ($noadvoptions == false && isset($rule['nopfsync'])) + if ($noadvoptions == false && isset($rule['nopfsync'])) { $rule['nopfsync'] = true; + } - if ($noadvoptions == false || $l7_present) + if ($noadvoptions == false || $l7_present) { if ((isset($rule['source-track']) and $rule['source-track'] <> "") or (isset($rule['max']) and $rule['max'] <> "") or (isset($rule['max-src-nodes']) and $rule['max-src-nodes'] <> "") or @@ -2606,76 +2866,93 @@ function filter_generate_user_rule($rule) { (isset($rule['max-src-conn']) and $rule['max-src-conn'] <> "") or (isset($rule['max-src-conn-rate']) and $rule['max-src-conn-rate'] <> "") or (isset($rule['max-src-conn-rates']) and $rule['max-src-conn-rates'] <> ""))) or - isset($rule['sloppy']) or isset($rule['nopfsync']) or $l7_present) { - $aline['flags'] .= "( "; - if (isset($rule['sloppy'])) - $aline['flags'] .= "sloppy "; - if (isset($rule['nopfsync'])) - $aline['flags'] .= "no-sync "; - if (isset($rule['source-track']) and $rule['source-track'] <> "") - $aline['flags'] .= "source-track rule "; - if (isset($rule['max']) and $rule['max'] <> "") - $aline['flags'] .= "max " . $rule['max'] . " "; - if (isset($rule['max-src-nodes']) and $rule['max-src-nodes'] <> "") - $aline['flags'] .= "max-src-nodes " . $rule['max-src-nodes'] . " "; - if ((in_array($rule['protocol'], array("tcp","tcp/udp"))) - and isset($rule['max-src-conn']) - and $rule['max-src-conn'] <> "") - $aline['flags'] .= "max-src-conn " . $rule['max-src-conn'] . " "; - if (isset($rule['max-src-states']) and $rule['max-src-states'] <> "") - $aline['flags'] .= "max-src-states " . $rule['max-src-states'] . " "; - if ((in_array($rule['protocol'], array("tcp","tcp/udp"))) - and isset($rule['statetimeout']) - and $rule['statetimeout'] <> "") - $aline['flags'] .= "tcp.established " . $rule['statetimeout'] . " "; - if ((in_array($rule['protocol'], array("tcp","tcp/udp"))) - and isset($rule['max-src-conn-rate']) - and $rule['max-src-conn-rate'] <> "" - and isset($rule['max-src-conn-rates']) - and $rule['max-src-conn-rates'] <> "") { - $aline['flags'] .= "max-src-conn-rate " . $rule['max-src-conn-rate'] . " "; - $aline['flags'] .= "/" . $rule['max-src-conn-rates'] . ", overload flush global "; - } - - if(!empty($aline['divert'])) - $aline['flags'] .= "max-packets 8 "; - - $aline['flags'] .= " ) "; + (isset($rule['sloppy'])) or + (isset($rule['nopfsync'])) or + ($l7_present)) { + $aline['flags'] .= "( "; + if (isset($rule['sloppy'])) { + $aline['flags'] .= "sloppy "; } + if (isset($rule['nopfsync'])) { + $aline['flags'] .= "no-sync "; + } + if (isset($rule['source-track']) and $rule['source-track'] <> "") { + $aline['flags'] .= "source-track rule "; + } + if (isset($rule['max']) and $rule['max'] <> "") { + $aline['flags'] .= "max " . $rule['max'] . " "; + } + if (isset($rule['max-src-nodes']) and $rule['max-src-nodes'] <> "") { + $aline['flags'] .= "max-src-nodes " . $rule['max-src-nodes'] . " "; + } + if ((in_array($rule['protocol'], array("tcp","tcp/udp"))) and + (isset($rule['max-src-conn'])) and + ($rule['max-src-conn'] <> "")) { + $aline['flags'] .= "max-src-conn " . $rule['max-src-conn'] . " "; + } + if (isset($rule['max-src-states']) and $rule['max-src-states'] <> "") { + $aline['flags'] .= "max-src-states " . $rule['max-src-states'] . " "; + } + if ((in_array($rule['protocol'], array("tcp","tcp/udp"))) and + (isset($rule['statetimeout'])) and + ($rule['statetimeout'] <> "")) { + $aline['flags'] .= "tcp.established " . $rule['statetimeout'] . " "; + } + if ((in_array($rule['protocol'], array("tcp","tcp/udp"))) and + (isset($rule['max-src-conn-rate'])) and + ($rule['max-src-conn-rate'] <> "") and + (isset($rule['max-src-conn-rates'])) and + ($rule['max-src-conn-rates'] <> "")) { + $aline['flags'] .= "max-src-conn-rate " . $rule['max-src-conn-rate'] . " "; + $aline['flags'] .= "/" . $rule['max-src-conn-rates'] . ", overload flush global "; + } + + if (!empty($aline['divert'])) { + $aline['flags'] .= "max-packets 8 "; + } + + $aline['flags'] .= " ) "; + } + } } - if($rule['defaultqueue'] <> "") { + if ($rule['defaultqueue'] <> "") { $aline['queue'] = " queue (".$rule['defaultqueue']; - if($rule['ackqueue'] <> "") + if ($rule['ackqueue'] <> "") { $aline['queue'] .= ",".$rule['ackqueue']; + } $aline['queue'] .= ") "; } - if($rule['dnpipe'] <> "") { + if ($rule['dnpipe'] <> "") { if (!empty($dummynet_name_list[$rule['dnpipe']])) { - if($dummynet_name_list[$rule['dnpipe']][0] == "?") { + if ($dummynet_name_list[$rule['dnpipe']][0] == "?") { $aline['dnpipe'] = " dnqueue( "; $aline['dnpipe'] .= substr($dummynet_name_list[$rule['dnpipe']],1); - if($rule['pdnpipe'] <> "") + if ($rule['pdnpipe'] <> "") { $aline['dnpipe'] .= ",".substr($dummynet_name_list[$rule['pdnpipe']], 1); + } } else { $aline['dnpipe'] = " dnpipe ( " . $dummynet_name_list[$rule['dnpipe']]; - if($rule['pdnpipe'] <> "") + if ($rule['pdnpipe'] <> "") { $aline['dnpipe'] .= "," . $dummynet_name_list[$rule['pdnpipe']]; + } } $aline['dnpipe'] .= ") "; } } /* is a time based rule schedule attached? */ - if(!empty($rule['sched']) && !empty($config['schedules'])) { + if (!empty($rule['sched']) && !empty($config['schedules'])) { $aline['schedlabel'] = ""; foreach ($config['schedules']['schedule'] as $sched) { - if($sched['name'] == $rule['sched']) { - if(!filter_get_time_based_rule_status($sched)) { - if(!isset($config['system']['schedule_states'])) + if ($sched['name'] == $rule['sched']) { + if (!filter_get_time_based_rule_status($sched)) { + if (!isset($config['system']['schedule_states'])) { mwexec("/sbin/pfctl -y {$sched['schedlabel']}"); + } return "# schedule finished - {$rule['descr']}"; - } else if($g['debug']) + } else if ($g['debug']) { log_error("[TDR DEBUG] status true -- rule type '$type'"); + } $aline['schedlabel'] = " schedule \"{$sched['schedlabel']}\" "; break; @@ -2683,13 +2960,14 @@ function filter_generate_user_rule($rule) { } } - if (!empty($rule['tracker'])) + if (!empty($rule['tracker'])) { $aline['tracker'] = "tracker {$rule['tracker']} "; + } $line = ""; /* exception(s) to a user rules can go here. */ /* rules with a gateway or pool should create another rule for routing to vpns */ - if((($aline['route'] <> "") && (trim($aline['type']) == "pass") && strstr($dst, "any")) && (!isset($config['system']['disablenegate']))) { + if ((($aline['route'] <> "") && (trim($aline['type']) == "pass") && strstr($dst, "any")) && (!isset($config['system']['disablenegate']))) { /* negate VPN/PPTP/PPPoE/Static Route networks for load balancer/gateway rules */ $negate_networks = " to " . filter_generate_port($rule, "destination"); $line .= $aline['type'] . $aline['direction'] . $aline['log'] . $aline['quick'] . @@ -2718,7 +2996,7 @@ function filter_rules_generate() { $increment_tracker = 'filter_rule_tracker'; update_filter_reload_status(gettext("Creating default rules")); - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_rules_generate() being called $mt\n"; } @@ -2736,15 +3014,17 @@ function filter_rules_generate() { $ipfrules .= "anchor \"ipsec/*\"\n"; # BEGIN OF firewall rules /* default block logging? */ - $log = array(); - if(!isset($config['syslog']['nologdefaultblock'])) + $log = array(); + if (!isset($config['syslog']['nologdefaultblock'])) { $log['block'] = "log"; - if(isset($config['syslog']['nologdefaultpass'])) + } + if (isset($config['syslog']['nologdefaultpass'])) { $log['pass'] = "log"; + } $saved_tracker = $tracker; - if(!isset($config['system']['ipv6allow'])) { + if (!isset($config['system']['ipv6allow'])) { $ipfrules .= "# Allow IPv6 on loopback\n"; $ipfrules .= "pass in {$log['pass']} quick on \$loopback inet6 all tracker {$increment_tracker($tracker)} label \"pass IPv6 loopback\"\n"; $ipfrules .= "pass out {$log['pass']} quick on \$loopback inet6 all tracker {$increment_tracker($tracker)} label \"pass IPv6 loopback\"\n"; @@ -2810,33 +3090,37 @@ EOD; $tracker = $saved_tracker; $ipfrules .= "\n# SSH lockout\n"; - if(is_array($config['system']['ssh']) && !empty($config['system']['ssh']['port'])) { + if (is_array($config['system']['ssh']) && !empty($config['system']['ssh']['port'])) { $ipfrules .= "block in {$log['block']} quick proto tcp from to (self) port "; $ipfrules .= $config['system']['ssh']['port']; $ipfrules .= " tracker {$increment_tracker($tracker)} label \"sshlockout\"\n"; } else { - if($config['system']['ssh']['port'] <> "") + if ($config['system']['ssh']['port'] <> "") { $sshport = $config['system']['ssh']['port']; - else + } else { $sshport = 22; - if($sshport) + } + if ($sshport) { $ipfrules .= "block in {$log['block']} quick proto tcp from to (self) port {$sshport} tracker {$increment_tracker($tracker)} label \"sshlockout\"\n"; + } } $saved_tracker += 50; $tracker = $saved_tracker; $ipfrules .= "\n# webConfigurator lockout\n"; - if(!$config['system']['webgui']['port']) { - if($config['system']['webgui']['protocol'] == "http") + if (!$config['system']['webgui']['port']) { + if ($config['system']['webgui']['protocol'] == "http") { $webConfiguratorlockoutport = "80"; - else + } else { $webConfiguratorlockoutport = "443"; + } } else { $webConfiguratorlockoutport = $config['system']['webgui']['port']; } - if($webConfiguratorlockoutport) + if ($webConfiguratorlockoutport) { $ipfrules .= "block in {$log['block']} quick proto tcp from to (self) port {$webConfiguratorlockoutport} tracker {$increment_tracker($tracker)} label \"webConfiguratorlockout\"\n"; + } $saved_tracker += 100; $tracker = $saved_tracker; @@ -2853,29 +3137,32 @@ EOD; /* if captive portal is enabled, ensure that access to this port * is allowed on a locked down interface */ - if(is_array($config['captiveportal'])) { + if (is_array($config['captiveportal'])) { foreach ($config['captiveportal'] as $cpcfg) { - if(!isset($cpcfg['enable'])) + if (!isset($cpcfg['enable'])) { continue; + } $cpinterfaces = explode(",", $cpcfg['interface']); $cpiflist = array(); $cpiplist = array(); foreach ($cpinterfaces as $cpifgrp) { - if(!isset($FilterIflist[$cpifgrp])) + if (!isset($FilterIflist[$cpifgrp])) { continue; + } $tmpif = get_real_interface($cpifgrp); - if(!empty($tmpif)) { + if (!empty($tmpif)) { $cpiflist[] = "{$tmpif}"; $cpipm = get_interface_ip($cpifgrp); - if(is_ipaddr($cpipm)) { + if (is_ipaddr($cpipm)) { $carpif = link_ip_to_carp_interface($cpipm); if (!empty($carpif)) { $cpiflist[] = $carpif; $carpsif = explode(" ", $carpif); foreach ($carpsif as $cpcarp) { $carpip = find_interface_ip($cpcarp); - if (is_ipaddr($carpip)) + if (is_ipaddr($carpip)) { $cpiplist[] = $carpip; + } } } $cpiplist[] = $cpipm; @@ -2900,8 +3187,8 @@ EOD; $saved_tracker += 10; $tracker = $saved_tracker; - if(isset($config['system']['ipv6allow']) && ($oc['type6'] == "slaac" || $oc['type6'] == "dhcp6")) { - // The DHCPv6 client rules ***MUST BE ABOVE BOGONSV6!*** https://redmine.pfsense.org/issues/3395 + if (isset($config['system']['ipv6allow']) && ($oc['type6'] == "slaac" || $oc['type6'] == "dhcp6")) { + // The DHCPv6 client rules ***MUST BE ABOVE BOGONSV6!*** https://redmine.pfsense.org/issues/3395 $ipfrules .= << to any tracker {$incr EOD; - if(isset($config['system']['ipv6allow'])) { + if (isset($config['system']['ipv6allow'])) { $ipfrules .= << "") { - $ipfrules .= << "") { + $ipfrules .= << $ifcfg) { - if(isset($ifcfg['virtual'])) + if (isset($ifcfg['virtual'])) { continue; + } $gw = get_interface_gateway($ifdescr); if (is_ipaddrv4($gw) && is_ipaddrv4($ifcfg['ip'])) { $ipfrules .= "pass out {$log['pass']} route-to ( {$ifcfg['if']} {$gw} ) from {$ifcfg['ip']} to !{$ifcfg['sa']}/{$ifcfg['sn']} tracker {$increment_tracker($tracker)} keep state allow-opts label \"let out anything from firewall host itself\"\n"; if (is_array($ifcfg['vips'])) { - foreach ($ifcfg['vips'] as $vip) - if (ip_in_subnet($vip['ip'], "{$ifcfg['sa']}/{$ifcfg['sn']}")) + foreach ($ifcfg['vips'] as $vip) { + if (ip_in_subnet($vip['ip'], "{$ifcfg['sa']}/{$ifcfg['sn']}")) { $ipfrules .= "pass out {$log['pass']} route-to ( {$ifcfg['if']} {$gw} ) from {$vip['ip']} to !{$ifcfg['sa']}/{$ifcfg['sn']} tracker {$increment_tracker($tracker)} keep state allow-opts label \"let out anything from firewall host itself\"\n"; - else + } else { $ipfrules .= "pass out {$log['pass']} route-to ( {$ifcfg['if']} {$gw} ) from {$vip['ip']} to !" . gen_subnet($vip['ip'], $vip['sn']) . "/{$vip['sn']} tracker {$increment_tracker($tracker)} keep state allow-opts label \"let out anything from firewall host itself\"\n"; + } + } } } @@ -3141,8 +3435,9 @@ EOD; if (is_ipaddrv6($gwv6) && is_ipaddrv6($ifcfg['ipv6'])) { $ipfrules .= "pass out {$log['pass']} route-to ( {$stf} {$gwv6} ) inet6 from {$ifcfg['ipv6']} to !{$ifcfg['ipv6']}/{$pdlen} tracker {$increment_tracker($tracker)} keep state allow-opts label \"let out anything from firewall host itself\"\n"; if (is_array($ifcfg['vips6'])) { - foreach ($ifcfg['vips6'] as $vip) + foreach ($ifcfg['vips6'] as $vip) { $ipfrules .= "pass out {$log['pass']} route-to ( {$stf} {$gwv6} ) inet6 from {$vip['ip']} to !{$vip['ip']}/{$pdlen} tracker {$increment_tracker($tracker)} keep state allow-opts label \"let out anything from firewall host itself\"\n"; + } } } } @@ -3151,20 +3446,21 @@ EOD; $saved_tracker += 300; $tracker = $saved_tracker; /* add ipsec interfaces */ - if(isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable'])) + if (isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable'])) { $ipfrules .= "pass out {$log['pass']} on \$IPsec all tracker {$increment_tracker($tracker)} tracker {$increment_tracker($tracker)} keep state label \"IPsec internal host to host\"\n"; + } $saved_tracker += 10; $tracker = $saved_tracker; - if(is_array($config['system']['webgui']) && !isset($config['system']['webgui']['noantilockout'])) { + if (is_array($config['system']['webgui']) && !isset($config['system']['webgui']['noantilockout'])) { $alports = filter_get_antilockout_ports(); - if(count($config['interfaces']) > 1 && !empty($FilterIflist['lan']['if'])) { - /* if antilockout is enabled, LAN exists and has - * an IP and subnet mask assigned - */ - $lanif = $FilterIflist['lan']['if']; - $ipfrules .= << 1 && !empty($FilterIflist['lan']['if'])) { + /* if antilockout is enabled, LAN exists and has + * an IP and subnet mask assigned + */ + $lanif = $FilterIflist['lan']['if']; + $ipfrules .= <<= $starting_time and $now < $ending_time) + } + if ($now >= $starting_time and $now < $ending_time) { return true; + } return false; } @@ -3555,14 +3874,17 @@ function filter_tdr_position($schedule) { * ... */ $weekday = date("w"); - if($g['debug']) + if ($g['debug']) { log_error("[TDR DEBUG] filter_tdr_position($schedule) $weekday"); - if($weekday == 0) + } + if ($weekday == 0) { $weekday = 7; + } $schedule_days = explode(",", $schedule); - foreach($schedule_days as $day) { - if($day == $weekday) + foreach ($schedule_days as $day) { + if ($day == $weekday) { return true; + } } return false; } @@ -3575,11 +3897,13 @@ function filter_tdr_month($schedule) { */ $todays_month = date("n"); $months = explode(",", $schedule); - if($g['debug']) + if ($g['debug']) { log_error("[TDR DEBUG] filter_tdr_month($schedule)"); - foreach($months as $month) { - if($month == $todays_month) + } + foreach ($months as $month) { + if ($month == $todays_month) { return true; + } } return false; } @@ -3587,15 +3911,16 @@ function filter_tdr_month($schedule) { function filter_setup_logging_interfaces() { global $config, $FilterIflist; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_setup_logging_interfaces() being called $mt\n"; } $rules = ""; - if (isset($FilterIflist['lan'])) + if (isset($FilterIflist['lan'])) { $rules .= "set loginterface {$FilterIflist['lan']['if']}\n"; - else if (isset($FilterIflist['wan'])) + } else if (isset($FilterIflist['wan'])) { $rules .= "set loginterface {$FilterIflist['wan']['if']}\n"; + } return $rules; } @@ -3603,7 +3928,7 @@ function filter_setup_logging_interfaces() { function filter_process_carp_rules($log) { global $g, $config, $tracker; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_process_carp_rules() being called $mt\n"; } @@ -3622,63 +3947,72 @@ function filter_process_carp_rules($log) { function filter_generate_ipsec_rules($log = array()) { global $config, $g, $FilterIflist, $tracker; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "filter_generate_ipsec_rules() being called $mt\n"; } - if (isset($config['system']['disablevpnrules'])) + if (isset($config['system']['disablevpnrules'])) { return "\n# VPN Rules not added disabled in System->Advanced.\n"; + } $increment_tracker = 'filter_rule_tracker'; $ipfrules = "\n# VPN Rules\n"; - if(isset($config['ipsec']['enable']) && - is_array($config['ipsec']['phase1'])) { + if ((isset($config['ipsec']['enable'])) && + (is_array($config['ipsec']['phase1']))) { /* step through all phase1 entries */ foreach ($config['ipsec']['phase1'] as $ph1ent) { $tracker += 10; - if(isset ($ph1ent['disabled'])) + if (isset ($ph1ent['disabled'])) { continue; + } /* determine local and remote peer addresses */ - if(!isset($ph1ent['mobile'])) { - if (!function_exists('ipsec_get_phase1_dst')) + if (!isset($ph1ent['mobile'])) { + if (!function_exists('ipsec_get_phase1_dst')) { require_once("ipsec.inc"); + } $rgip = ipsec_get_phase1_dst($ph1ent); - if(!$rgip) { + if (!$rgip) { $ipfrules .= "# ERROR! Unable to determine remote IPsec peer address for {$ph1ent['remote-gateway']}\n"; continue; } - } else + } else { $rgip = " any "; + } /* Determine best description */ - if($ph1ent['descr']) + if ($ph1ent['descr']) { $descr = $ph1ent['descr']; - else + } else { $descr = $rgip; + } /* * Step through all phase2 entries and determine * which protocols are in use with this peer */ $prot_used_esp = false; $prot_used_ah = false; - if(is_array($config['ipsec']['phase2'])) { + if (is_array($config['ipsec']['phase2'])) { foreach ($config['ipsec']['phase2'] as $ph2ent) { /* only evaluate ph2's bound to our ph1 */ - if($ph2ent['ikeid'] != $ph1ent['ikeid']) + if ($ph2ent['ikeid'] != $ph1ent['ikeid']) { continue; - if($ph2ent['protocol'] == 'esp') + } + if ($ph2ent['protocol'] == 'esp') { $prot_used_esp = true; - if($ph2ent['protocol'] == 'ah') + } + if ($ph2ent['protocol'] == 'ah') { $prot_used_ah = true; + } } } - if (strpos($ph1ent['interface'], "_vip")) + if (strpos($ph1ent['interface'], "_vip")) { $parentinterface = get_configured_carp_interface_list($ph1ent['interface'], '', 'iface'); - else + } else { $parentinterface = $ph1ent['interface']; + } if (empty($FilterIflist[$parentinterface]['descr'])) { $ipfrules .= "# Could not locate interface for IPsec: {$descr}\n"; continue; @@ -3687,42 +4021,42 @@ function filter_generate_ipsec_rules($log = array()) { unset($gateway); /* add endpoint routes to correct gateway on interface if the remote endpoint is not on this interface's subnet */ - if((is_ipaddrv4($rgip)) && (interface_has_gateway($parentinterface))) { + if ((is_ipaddrv4($rgip)) && (interface_has_gateway($parentinterface))) { $parentifsubnet = get_interface_ip($parentinterface) . "/" . get_interface_subnet($parentinterface); if (!ip_in_subnet($rgip, $parentifsubnet)) { $gateway = get_interface_gateway($parentinterface); $interface = $FilterIflist[$parentinterface]['if']; - + $route_to = " route-to ( $interface $gateway ) "; - $reply_to = " reply-to ( $interface $gateway ) "; + $reply_to = " reply-to ( $interface $gateway ) "; } } - if((is_ipaddrv6($rgip)) && (interface_has_gatewayv6($parentinterface))) { + if ((is_ipaddrv6($rgip)) && (interface_has_gatewayv6($parentinterface))) { $parentifsubnet = get_interface_ipv6($parentinterface) . "/" . get_interface_subnetv6($parentinterface); if (!ip_in_subnet($rgip, $parentifsubnet)) { $gateway = get_interface_gateway_v6($parentinterface); $interface = $FilterIflist[$parentinterface]['if']; - + $route_to = " route-to ( $interface $gateway ) "; $reply_to = " reply-to ( $interface $gateway ) "; } } /* Just in case */ - if((!is_ipaddr($gateway) || empty($interface))) { + if ((!is_ipaddr($gateway) || empty($interface))) { $route_to = " "; $reply_to = " "; } /* Add rules to allow IKE to pass */ $shorttunneldescr = substr($descr, 0, 35); - $ipfrules .= << \ No newline at end of file +?> From 918bdf0d45e032dd4413fd5051eb781accb6a86c Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 26 Feb 2015 22:24:00 +0545 Subject: [PATCH 140/257] More style guide changes In gwlb.inc at line 676 and 779 I added an extra set of brackets. In the "if" clause as a whole there were a mix of && and || used that were relying on the PHP standard that && has precedence over || In actual fact the original code should have been working fine, the extra brackets make sure that the intention is clear. --- etc/inc/filter_log.inc | 2 +- etc/inc/gwlb.inc | 18 ++++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/etc/inc/filter_log.inc b/etc/inc/filter_log.inc index 60f4ed5d30..f4d9841625 100644 --- a/etc/inc/filter_log.inc +++ b/etc/inc/filter_log.inc @@ -74,7 +74,7 @@ function conv_log_filter($logfile, $nentries, $tail = 50, $filtertext = "", $fil $flent = parse_filter_line($logent); if (!$filterinterface || ($filterinterface == $flent['interface'])) { if ((($flent != "") && (!is_array($filtertext)) && (match_filter_line ($flent, $filtertext))) || - (($flent != "") && ( is_array($filtertext)) && (match_filter_field($flent, $filtertext)))) { + (($flent != "") && ( is_array($filtertext)) && (match_filter_field($flent, $filtertext)))) { $counter++; $filterlog[] = $flent; } diff --git a/etc/inc/gwlb.inc b/etc/inc/gwlb.inc index a1aedb1b7c..68af1ffad5 100644 --- a/etc/inc/gwlb.inc +++ b/etc/inc/gwlb.inc @@ -269,18 +269,24 @@ EOD; ## How often the probe should be sent if (!empty($gateway['interval']) && is_numeric($gateway['interval'])) { $interval = intval($gateway['interval']); # Restrict to Integer - if ($interval < 1) $interval = 1; # Minimum - if ($interval != $apinger_default['interval']) # If not default value + if ($interval < 1) { + $interval = 1; # Minimum + } + if ($interval != $apinger_default['interval']) { # If not default value $apingercfg .= " interval " . $interval . "s\n"; + } } ## How many replies should be used to compute average delay ## for controlling "delay" alarms if (!empty($gateway['avg_delay_samples']) && is_numeric($gateway['avg_delay_samples'])) { $avg_delay_samples = intval($gateway['avg_delay_samples']); # Restrict to Integer - if ($avg_delay_samples < 1) $avg_delay_samples = 1; # Minimum - if ($avg_delay_samples != $apinger_default['avg_delay_samples']) # If not default value + if ($avg_delay_samples < 1) { + $avg_delay_samples = 1; # Minimum + } + if ($avg_delay_samples != $apinger_default['avg_delay_samples']) { # If not default value $apingercfg .= " avg_delay_samples " . $avg_delay_samples . "\n"; + } } ## How many probes should be used to compute average loss @@ -667,7 +673,7 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive /* automatically skip known static and dynamic gateways that were previously processed */ foreach ($gateways_arr_temp as $gateway_item) { if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) || - ($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) { + (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) { continue 2; } } @@ -770,7 +776,7 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive /* automatically skip known static and dynamic gateways that were previously processed */ foreach ($gateways_arr_temp as $gateway_item) { if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) || - ($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) { + (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) { continue 2; } } From cf73302fd7d0b2ce8c0cfc74a9c5bdfa21e1d9a6 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Fri, 27 Feb 2015 11:13:45 +0545 Subject: [PATCH 141/257] Code style guide interfaces.inc This is another big file that has many diffs so Github refuses to display them. I thought it best to keep doing individual commit-pull for ones like this. --- etc/inc/interfaces.inc | 2548 +++++++++++++++++++++++----------------- 1 file changed, 1492 insertions(+), 1056 deletions(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index 03a3f223d5..c27958a934 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -47,7 +47,7 @@ require_once("util.inc"); require_once("gwlb.inc"); function interfaces_bring_up($interface) { - if(!$interface) { + if (!$interface) { log_error(gettext("interfaces_bring_up() was called but no variable defined.")); log_error( "Backtrace: " . debug_backtrace() ); return; @@ -62,8 +62,9 @@ function get_interface_arr($flush = false) { global $interface_arr_cache; /* If the cache doesn't exist, build it */ - if (!isset($interface_arr_cache) or $flush) + if (!isset($interface_arr_cache) or $flush) { $interface_arr_cache = pfSense_interface_listget(); + } return $interface_arr_cache; } @@ -75,14 +76,16 @@ function get_interface_arr($flush = false) { function does_interface_exist($interface, $flush = true) { global $config; - if(!$interface) + if (!$interface) { return false; + } $ints = get_interface_arr($flush); - if (in_array($interface, $ints)) + if (in_array($interface, $ints)) { return true; - else + } else { return false; + } } /* @@ -92,29 +95,31 @@ function does_interface_exist($interface, $flush = true) { function does_vip_exist($vip) { global $config; - if(!$vip) + if (!$vip) { return false; + } switch ($vip['mode']) { - case "carp": - case "ipalias": - /* XXX: Make proper checks? */ - $realif = get_real_interface($vip['interface']); - if (!does_interface_exist($realif)) { + case "carp": + case "ipalias": + /* XXX: Make proper checks? */ + $realif = get_real_interface($vip['interface']); + if (!does_interface_exist($realif)) { + return false; + } + break; + case "proxyarp": + /* XXX: Implement this */ + default: return false; - } - break; - case "proxyarp": - /* XXX: Implement this */ - default: - return false; } $ifacedata = pfSense_getall_interface_addresses($realif); foreach ($ifacedata as $vipips) { - if ($vipips == "{$vip['subnet']}/{$vip['subnet_bits']}") + if ($vipips == "{$vip['subnet']}/{$vip['subnet_bits']}") { return true; + } } return false; @@ -125,30 +130,34 @@ function interface_netgraph_needed($interface = "wan") { $found = false; if (!empty($config['pptpd']) && - $config['pptpd']['mode'] == "server") + $config['pptpd']['mode'] == "server") { $found = true; + } if ($found == false && !empty($config['l2tp']) && - $config['l2tp']['mode'] == "server") + $config['l2tp']['mode'] == "server") { $found = true; + } if ($found == false && is_array($config['pppoes']['pppoe'])) { foreach ($config['pppoes']['pppoe'] as $pppoe) { - if ($pppoe['mode'] != "server") + if ($pppoe['mode'] != "server") { continue; + } if ($pppoe['interface'] == $interface) { $found = true; break; } } } - if ($found == false) + if ($found == false) { $found = interface_isppp_type($interface); + } if ($found == false) { $realif = get_real_interface($interface); if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) { foreach ($config['ppps']['ppp'] as $pppid => $ppp) { $ports = explode(',',$ppp['ports']); - foreach($ports as $pid => $port){ + foreach ($ports as $pid => $port) { $port = get_real_interface($port); if ($realif == $port) { $found = true; @@ -181,34 +190,41 @@ function interface_netgraph_needed($interface = "wan") { function interfaces_loopback_configure() { global $g; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; - if (platform_booting()) + } + if (platform_booting()) { echo gettext("Configuring loopback interface..."); + } pfSense_interface_setaddress("lo0", "127.0.0.1"); interfaces_bring_up("lo0"); - if (platform_booting()) + if (platform_booting()) { echo gettext("done.") . "\n"; + } return 0; } function interfaces_vlan_configure($realif = "") { global $config, $g; - if (platform_booting()) + if (platform_booting()) { echo gettext("Configuring VLAN interfaces..."); + } if (is_array($config['vlans']['vlan']) && count($config['vlans']['vlan'])) { foreach ($config['vlans']['vlan'] as $vlan) { - if (empty($vlan['vlanif'])) + if (empty($vlan['vlanif'])) { $vlan['vlanif'] = "{$vlan['if']}_vlan{$vlan['tag']}"; - if (!empty($realif) && $realif != $vlan['vlanif']) + } + if (!empty($realif) && $realif != $vlan['vlanif']) { continue; + } /* XXX: Maybe we should report any errors?! */ interface_vlan_configure($vlan); } } - if (platform_booting()) + if (platform_booting()) { echo gettext("done.") . "\n"; + } } function interface_vlan_configure(&$vlan) { @@ -263,12 +279,12 @@ function interface_qinq_configure(&$vlan, $fd = NULL) { $qinqif = $vlan['if']; $tag = $vlan['tag']; - if(empty($qinqif)) { + if (empty($qinqif)) { log_error(sprintf(gettext("interface_qinq_configure called with if undefined.%s"), "\n")); return; } - if(!does_interface_exist($qinqif)) { + if (!does_interface_exist($qinqif)) { log_error(sprintf(gettext("interface_qinq_configure called with invalid if.%s"), "\n")); return; } @@ -278,8 +294,9 @@ function interface_qinq_configure(&$vlan, $fd = NULL) { if ($fd == NULL) { $exec = true; $fd = fopen("{$g['tmp_path']}/netgraphcmd", "w"); - } else + } else { $exec = false; + } /* make sure the parent is converted to ng_vlan(4) and is up */ interfaces_bring_up($qinqif); @@ -301,8 +318,9 @@ function interface_qinq_configure(&$vlan, $fd = NULL) { /* invalidate interface cache */ get_interface_arr(true); - if (!stristr($qinqif, "_vlan")) + if (!stristr($qinqif, "_vlan")) { mwexec("/sbin/ifconfig {$qinqif} promisc\n"); + } $macaddr = get_interface_mac($qinqif); if (!empty($vlan['members'])) { @@ -322,8 +340,9 @@ function interface_qinq_configure(&$vlan, $fd = NULL) { interfaces_bring_up($qinqif); if (!empty($vlan['members'])) { $members = explode(" ", $vlan['members']); - foreach ($members as $qif) + foreach ($members as $qif) { interfaces_bring_up("{$vlanif}_{$qif}"); + } } return $vlanif; @@ -331,16 +350,18 @@ function interface_qinq_configure(&$vlan, $fd = NULL) { function interfaces_qinq_configure() { global $config, $g; - if (platform_booting()) + if (platform_booting()) { echo gettext("Configuring QinQ interfaces..."); + } if (is_array($config['qinqs']['qinqentry']) && count($config['qinqs']['qinqentry'])) { foreach ($config['qinqs']['qinqentry'] as $qinq) { /* XXX: Maybe we should report any errors?! */ interface_qinq_configure($qinq); } } - if (platform_booting()) + if (platform_booting()) { echo gettext( "done.") . "\n"; + } } function interface_qinq2_configure(&$qinq, $fd, $macaddr) { @@ -354,7 +375,7 @@ function interface_qinq2_configure(&$qinq, $fd, $macaddr) { $if = $qinq['if']; $tag = $qinq['tag']; $vlanif = "{$if}_{$tag}"; - if(empty($if)) { + if (empty($if)) { log_error(sprintf(gettext("interface_qinq2_configure called with if undefined.%s"), "\n")); return; } @@ -375,29 +396,34 @@ function interface_qinq2_configure(&$qinq, $fd, $macaddr) { function interfaces_create_wireless_clones() { global $config, $g; - if (platform_booting()) + if (platform_booting()) { echo gettext("Creating wireless clone interfaces..."); + } $iflist = get_configured_interface_list(); foreach ($iflist as $if) { $realif = $config['interfaces'][$if]['if']; - if (is_interface_wireless($realif)) + if (is_interface_wireless($realif)) { interface_wireless_clone(interface_get_wireless_clone($realif), $config['interfaces'][$if]); + } } if (isset($config['wireless']['clone']) && is_array($config['wireless']['clone']) && count($config['wireless']['clone'])) { foreach ($config['wireless']['clone'] as $clone) { - if(empty($clone['cloneif'])) + if (empty($clone['cloneif'])) { continue; - if(does_interface_exist($clone['cloneif'])) + } + if (does_interface_exist($clone['cloneif'])) { continue; + } /* XXX: Maybe we should report any errors?! */ interface_wireless_clone($clone['cloneif'], $clone); } } - if (platform_booting()) + if (platform_booting()) { echo gettext("done.") . "\n"; + } } @@ -407,26 +433,31 @@ function interfaces_bridge_configure($checkmember = 0, $realif = "") { $i = 0; if (is_array($config['bridges']['bridged']) && count($config['bridges']['bridged'])) { foreach ($config['bridges']['bridged'] as $bridge) { - if (empty($bridge['bridgeif'])) + if (empty($bridge['bridgeif'])) { $bridge['bridgeif'] = "bridge{$i}"; - if (!empty($realif) && $realif != $bridge['bridgeif']) + } + if (!empty($realif) && $realif != $bridge['bridgeif']) { continue; + } if ($checkmember == 1) { /* XXX: It should not be possible no? */ - if (strstr($bridge['if'], '_vip')) + if (strstr($bridge['if'], '_vip')) { continue; + } $members = explode(',', $bridge['members']); foreach ($members as $member) { - if (!empty($config['interfaces'][$bridge['if']]) && $config['interfaces'][$bridge['if']]['ipaddrv6'] == "track6") + if (!empty($config['interfaces'][$bridge['if']]) && $config['interfaces'][$bridge['if']]['ipaddrv6'] == "track6") { continue 2; + } } } else if ($checkmember == 2) { $members = explode(',', $bridge['members']); foreach ($members as $member) { - if (empty($config['interfaces'][$bridge['if']]) || $config['interfaces'][$bridge['if']]['ipaddrv6'] != "track6") + if (empty($config['interfaces'][$bridge['if']]) || $config['interfaces'][$bridge['if']]['ipaddrv6'] != "track6") { continue 2; + } } } /* XXX: Maybe we should report any errors?! */ @@ -439,8 +470,9 @@ function interfaces_bridge_configure($checkmember = 0, $realif = "") { function interface_bridge_configure(&$bridge, $checkmember = 0) { global $config, $g; - if (!is_array($bridge)) + if (!is_array($bridge)) { return; + } if (empty($bridge['members'])) { log_error(sprintf(gettext("No members found on %s"), $bridge['bridgeif'])); @@ -448,8 +480,9 @@ function interface_bridge_configure(&$bridge, $checkmember = 0) { } $members = explode(',', $bridge['members']); - if (!count($members)) + if (!count($members)) { return; + } /* Calculate smaller mtu and enforce it */ $smallermtu = 0; @@ -461,22 +494,27 @@ function interface_bridge_configure(&$bridge, $checkmember = 0) { $mtu = get_interface_mtu($realif); if (substr($realif, 0, 3) == "gif") { $foundgif = true; - if ($checkmember == 1) + if ($checkmember == 1) { return; - if ($mtu <= 1500) + } + if ($mtu <= 1500) { continue; + } } - if ($smallermtu == 0 && !empty($mtu)) + if ($smallermtu == 0 && !empty($mtu)) { $smallermtu = $mtu; - else if (!empty($mtu) && $mtu < $smallermtu) + } else if (!empty($mtu) && $mtu < $smallermtu) { $smallermtu = $mtu; + } } - if ($foundgif == false && $checkmember == 2) + if ($foundgif == false && $checkmember == 2) { return; + } /* Just in case anything is not working well */ - if ($smallermtu == 0) + if ($smallermtu == 0) { $smallermtu = 1500; + } if (platform_booting() || !empty($bridge['bridgeif'])) { pfSense_interface_destroy($bridge['bridgeif']); @@ -488,15 +526,17 @@ function interface_bridge_configure(&$bridge, $checkmember = 0) { } $bridgemtu = interface_find_child_cfgmtu($bridge['bridgeif']); - if ($bridgemtu > $smallermtu) + if ($bridgemtu > $smallermtu) { $smallermtu = $bridgemtu; + } $checklist = get_configured_interface_list(); /* Add interfaces to bridge */ foreach ($members as $member) { - if (empty($checklist[$member])) + if (empty($checklist[$member])) { continue; + } $realif = get_real_interface($member); if (!$realif) { log_error(gettext("realif not defined in interfaces bridge - up")); @@ -520,23 +560,29 @@ function interface_bridge_configure(&$bridge, $checkmember = 0) { mwexec("/sbin/ifconfig {$bridgeif} stp {$realif}"); } } - if (!empty($bridge['maxage'])) + if (!empty($bridge['maxage'])) { mwexec("/sbin/ifconfig {$bridgeif} maxage " . escapeshellarg($bridge['maxage'])); - if (!empty($bridge['fwdelay'])) + } + if (!empty($bridge['fwdelay'])) { mwexec("/sbin/ifconfig {$bridgeif} fwddelay " . escapeshellarg($bridge['fwdelay'])); - if (!empty($bridge['hellotime'])) + } + if (!empty($bridge['hellotime'])) { mwexec("/sbin/ifconfig {$bridgeif} hellotime " . escapeshellarg($bridge['hellotime'])); - if (!empty($bridge['priority'])) + } + if (!empty($bridge['priority'])) { mwexec("/sbin/ifconfig {$bridgeif} priority " . escapeshellarg($bridge['priority'])); - if (!empty($bridge['holdcnt'])) + } + if (!empty($bridge['holdcnt'])) { mwexec("/sbin/ifconfig {$bridgeif} holdcnt " . escapeshellarg($bridge['holdcnt'])); + } if (!empty($bridge['ifpriority'])) { $pconfig = explode(",", $bridge['ifpriority']); $ifpriority = array(); foreach ($pconfig as $cfg) { $embcfg = explode_assoc(":", $cfg); - foreach ($embcfg as $key => $value) + foreach ($embcfg as $key => $value) { $ifpriority[$key] = $value; + } } foreach ($ifpriority as $key => $value) { $realif = get_real_interface($key); @@ -548,8 +594,9 @@ function interface_bridge_configure(&$bridge, $checkmember = 0) { $ifpathcost = array(); foreach ($pconfig as $cfg) { $embcfg = explode_assoc(":", $cfg); - foreach ($embcfg as $key => $value) + foreach ($embcfg as $key => $value) { $ifpathcost[$key] = $value; + } } foreach ($ifpathcost as $key => $value) { $realif = get_real_interface($key); @@ -558,10 +605,12 @@ function interface_bridge_configure(&$bridge, $checkmember = 0) { } } - if ($bridge['maxaddr'] <> "") + if ($bridge['maxaddr'] <> "") { mwexec("/sbin/ifconfig {$bridgeif} maxaddr " . escapeshellarg($bridge['maxaddr'])); - if ($bridge['timeout'] <> "") + } + if ($bridge['timeout'] <> "") { mwexec("/sbin/ifconfig {$bridgeif} timeout " . escapeshellarg($bridge['timeout'])); + } if ($bridge['span'] <> "") { $realif = get_real_interface($bridge['span']); mwexec("/sbin/ifconfig {$bridgeif} span {$realif}"); @@ -609,22 +658,25 @@ function interface_bridge_configure(&$bridge, $checkmember = 0) { } } - if ($bridge['bridgeif']) + if ($bridge['bridgeif']) { interfaces_bring_up($bridge['bridgeif']); - else + } else { log_error(gettext("bridgeif not defined -- could not bring interface up")); + } } function interface_bridge_add_member($bridgeif, $interface, $flagsapplied = false) { - if (!does_interface_exist($bridgeif) || !does_interface_exist($interface)) + if (!does_interface_exist($bridgeif) || !does_interface_exist($interface)) { return; + } if ($flagsapplied == false) { $mtu = get_interface_mtu($bridgeif); $mtum = get_interface_mtu($interface); - if ($mtu != $mtum && !(substr($interface, 0, 3) == "gif" && $mtu <= 1500)) + if ($mtu != $mtum && !(substr($interface, 0, 3) == "gif" && $mtu <= 1500)) { pfSense_interface_mtu($interface, $mtu); + } hardware_offloading_applyflags($interface); interfaces_bring_up($interface); @@ -635,40 +687,47 @@ function interface_bridge_add_member($bridgeif, $interface, $flagsapplied = fals function interfaces_lagg_configure($realif = "") { global $config, $g; - if (platform_booting()) + if (platform_booting()) { echo gettext("Configuring LAGG interfaces..."); + } $i = 0; if (is_array($config['laggs']['lagg']) && count($config['laggs']['lagg'])) { foreach ($config['laggs']['lagg'] as $lagg) { - if(empty($lagg['laggif'])) + if (empty($lagg['laggif'])) { $lagg['laggif'] = "lagg{$i}"; - if (!empty($realif) && $realif != $lagg['laggif']) + } + if (!empty($realif) && $realif != $lagg['laggif']) { continue; + } /* XXX: Maybe we should report any errors?! */ interface_lagg_configure($lagg); $i++; } } - if (platform_booting()) + if (platform_booting()) { echo gettext("done.") . "\n"; + } } function interface_lagg_configure($lagg) { global $config, $g; - if (!is_array($lagg)) + if (!is_array($lagg)) { return -1; + } $members = explode(',', $lagg['members']); - if (!count($members)) + if (!count($members)) { return -1; + } if (platform_booting() || !(empty($lagg['laggif']))) { pfSense_interface_destroy($lagg['laggif']); pfSense_interface_create($lagg['laggif']); $laggif = $lagg['laggif']; - } else + } else { $laggif = pfSense_interface_create("lagg"); + } /* Check if MTU was defined for this lagg interface */ $lagg_mtu = interface_find_child_cfgmtu($laggif); @@ -677,21 +736,24 @@ function interface_lagg_configure($lagg) { $smallermtu = 0; foreach ($members as $member) { $mtu = get_interface_mtu($member); - if ($smallermtu == 0 && !empty($mtu)) + if ($smallermtu == 0 && !empty($mtu)) { $smallermtu = $mtu; - else if (!empty($mtu) && $mtu < $smallermtu) + } else if (!empty($mtu) && $mtu < $smallermtu) { $smallermtu = $mtu; + } } $lagg_mtu = $smallermtu; } /* Just in case anything is not working well */ - if ($lagg_mtu == 0) + if ($lagg_mtu == 0) { $lagg_mtu = 1500; + } foreach ($members as $member) { - if (!does_interface_exist($member)) + if (!does_interface_exist($member)) { continue; + } /* make sure the parent interface is up */ pfSense_interface_mtu($member, $lagg_mtu); interfaces_bring_up($member); @@ -713,23 +775,28 @@ function interfaces_gre_configure($checkparent = 0, $realif = "") { if (is_array($config['gres']['gre']) && count($config['gres']['gre'])) { foreach ($config['gres']['gre'] as $i => $gre) { - if (empty($gre['greif'])) + if (empty($gre['greif'])) { $gre['greif'] = "gre{$i}"; - if (!empty($realif) && $realif != $gre['greif']) + } + if (!empty($realif) && $realif != $gre['greif']) { continue; + } if ($checkparent == 1) { - if (substr($gre['if'], 0, 4) == '_vip') + if (substr($gre['if'], 0, 4) == '_vip') { continue; - if (substr($gre['if'], 0, 5) == '_lloc') + } + if (substr($gre['if'], 0, 5) == '_lloc') { continue; - if (!empty($config['interfaces'][$gre['if']]) && $config['interfaces'][$gre['if']]['ipaddrv6'] == "track6") + } + if (!empty($config['interfaces'][$gre['if']]) && $config['interfaces'][$gre['if']]['ipaddrv6'] == "track6") { continue; - } - else if ($checkparent == 2) { + } + } else if ($checkparent == 2) { if ((substr($gre['if'], 0, 4) != '_vip' && substr($gre['if'], 0, 5) != '_lloc') && - (empty($config['interfaces'][$gre['if']]) || $config['interfaces'][$gre['if']]['ipaddrv6'] != "track6")) + (empty($config['interfaces'][$gre['if']]) || $config['interfaces'][$gre['if']]['ipaddrv6'] != "track6")) { continue; + } } /* XXX: Maybe we should report any errors?! */ interface_gre_configure($gre); @@ -741,8 +808,9 @@ function interfaces_gre_configure($checkparent = 0, $realif = "") { function interface_gre_configure(&$gre, $grekey = "") { global $config, $g; - if (!is_array($gre)) + if (!is_array($gre)) { return -1; + } $realif = get_real_interface($gre['if']); $realifip = get_interface_ip($gre['if']); @@ -754,36 +822,44 @@ function interface_gre_configure(&$gre, $grekey = "") { pfSense_interface_destroy($gre['greif']); pfSense_interface_create($gre['greif']); $greif = $gre['greif']; - } else + } else { $greif = pfSense_interface_create("gre"); + } /* Do not change the order here for more see gre(4) NOTES section. */ mwexec("/sbin/ifconfig {$greif} tunnel {$realifip} " . escapeshellarg($gre['remote-addr'])); - if((is_ipaddrv6($gre['tunnel-local-addr'])) || (is_ipaddrv6($gre['tunnel-remote-addr']))) { + if ((is_ipaddrv6($gre['tunnel-local-addr'])) || (is_ipaddrv6($gre['tunnel-remote-addr']))) { /* XXX: The prefixlen argument for tunnels of ipv6 is useless since it needs to be 128 as enforced by kernel */ //mwexec("/sbin/ifconfig {$greif} inet6 " . escapeshellarg($gre['tunnel-local-addr']) . " " . escapeshellarg($gre['tunnel-remote-addr']) . " prefixlen /" . escapeshellarg($gre['tunnel-remote-net'])); mwexec("/sbin/ifconfig {$greif} inet6 " . escapeshellarg($gre['tunnel-local-addr']) . " " . escapeshellarg($gre['tunnel-remote-addr']) . " prefixlen 128"); } else { mwexec("/sbin/ifconfig {$greif} " . escapeshellarg($gre['tunnel-local-addr']) . " " . escapeshellarg($gre['tunnel-remote-addr']) . " netmask " . gen_subnet_mask($gre['tunnel-remote-net'])); } - if (isset($gre['link0'])) + if (isset($gre['link0'])) { pfSense_interface_flags($greif, IFF_LINK0); - if (isset($gre['link1'])) + } + if (isset($gre['link1'])) { pfSense_interface_flags($greif, IFF_LINK1); - if (isset($gre['link2'])) + } + if (isset($gre['link2'])) { pfSense_interface_flags($greif, IFF_LINK2); + } - if($greif) + if ($greif) { interfaces_bring_up($greif); - else + } else { log_error(gettext("Could not bring greif up -- variable not defined.")); + } - if (isset($gre['link1']) && $gre['link1']) + if (isset($gre['link1']) && $gre['link1']) { mwexec("/sbin/route add " . escapeshellarg($gre['tunnel-remote-addr']) . "/" . escapeshellarg($gre['tunnel-remote-net']) . " " . escapeshellarg($gre['tunnel-local-addr'])); - if(is_ipaddrv4($gre['tunnel-remote-addr'])) + } + if (is_ipaddrv4($gre['tunnel-remote-addr'])) { file_put_contents("{$g['tmp_path']}/{$greif}_router", $gre['tunnel-remote-addr']); - if(is_ipaddrv6($gre['tunnel-remote-addr'])) + } + if (is_ipaddrv6($gre['tunnel-remote-addr'])) { file_put_contents("{$g['tmp_path']}/{$greif}_routerv6", $gre['tunnel-remote-addr']); + } interfaces_bring_up($greif); @@ -795,23 +871,29 @@ function interfaces_gif_configure($checkparent = 0, $realif = "") { if (is_array($config['gifs']['gif']) && count($config['gifs']['gif'])) { foreach ($config['gifs']['gif'] as $i => $gif) { - if (empty($gif['gifif'])) + if (empty($gif['gifif'])) { $gre['gifif'] = "gif{$i}"; - if (!empty($realif) && $realif != $gif['gifif']) + } + if (!empty($realif) && $realif != $gif['gifif']) { continue; + } if ($checkparent == 1) { - if (substr($gif['if'], 0, 4) == '_vip') + if (substr($gif['if'], 0, 4) == '_vip') { continue; - if (substr($gif['if'], 0, 5) == '_lloc') + } + if (substr($gif['if'], 0, 5) == '_lloc') { continue; - if (!empty($config['interfaces'][$gif['if']]) && $config['interfaces'][$gif['if']]['ipaddrv6'] == "track6") + } + if (!empty($config['interfaces'][$gif['if']]) && $config['interfaces'][$gif['if']]['ipaddrv6'] == "track6") { continue; + } } else if ($checkparent == 2) { if ((substr($gif['if'], 0, 4) != '_vip' && substr($gif['if'], 0, 5) != '_lloc') && - (empty($config['interfaces'][$gif['if']]) || $config['interfaces'][$gif['if']]['ipaddrv6'] != "track6")) + (empty($config['interfaces'][$gif['if']]) || $config['interfaces'][$gif['if']]['ipaddrv6'] != "track6")) { continue; + } } /* XXX: Maybe we should report any errors?! */ interface_gif_configure($gif); @@ -823,65 +905,73 @@ function interfaces_gif_configure($checkparent = 0, $realif = "") { function interface_gif_configure(&$gif, $gifkey = "") { global $config, $g; - if (!is_array($gif)) + if (!is_array($gif)) { return -1; + } $realif = get_real_interface($gif['if']); $ipaddr = get_interface_ip($gif['if']); if (is_ipaddrv4($gif['remote-addr'])) { - if (is_ipaddrv4($ipaddr)) + if (is_ipaddrv4($ipaddr)) { $realifip = $ipaddr; - else + } else { $realifip = get_interface_ip($gif['if']); + } $realifgw = get_interface_gateway($gif['if']); } else if (is_ipaddrv6($gif['remote-addr'])) { - if (is_ipaddrv6($ipaddr)) + if (is_ipaddrv6($ipaddr)) { $realifip = $ipaddr; - else + } else { $realifip = get_interface_ipv6($gif['if']); + } $realifgw = get_interface_gateway_v6($gif['if']); } /* make sure the parent interface is up */ - if($realif) + if ($realif) { interfaces_bring_up($realif); - else + } else { log_error(gettext("could not bring realif up -- variable not defined -- interface_gif_configure()")); + } if (platform_booting() || !(empty($gif['gifif']))) { pfSense_interface_destroy($gif['gifif']); pfSense_interface_create($gif['gifif']); $gifif = $gif['gifif']; - } else + } else { $gifif = pfSense_interface_create("gif"); + } /* Do not change the order here for more see gif(4) NOTES section. */ mwexec("/sbin/ifconfig {$gifif} tunnel {$realifip} " . escapeshellarg($gif['remote-addr'])); - if((is_ipaddrv6($gif['tunnel-local-addr'])) || (is_ipaddrv6($gif['tunnel-remote-addr']))) { + if ((is_ipaddrv6($gif['tunnel-local-addr'])) || (is_ipaddrv6($gif['tunnel-remote-addr']))) { /* XXX: The prefixlen argument for tunnels of ipv6 is useless since it needs to be 128 as enforced by kernel */ //mwexec("/sbin/ifconfig {$gifif} inet6 " . escapeshellarg($gif['tunnel-local-addr']) . " " . escapeshellarg($gif['tunnel-remote-addr']) . " prefixlen /" . escapeshellarg($gif['tunnel-remote-net'])); mwexec("/sbin/ifconfig {$gifif} inet6 " . escapeshellarg($gif['tunnel-local-addr']) . " " . escapeshellarg($gif['tunnel-remote-addr']) . " prefixlen 128"); } else { mwexec("/sbin/ifconfig {$gifif} " . escapeshellarg($gif['tunnel-local-addr']) . " " . escapeshellarg($gif['tunnel-remote-addr']) . " netmask " . gen_subnet_mask($gif['tunnel-remote-net'])); } - if (isset($gif['link0'])) + if (isset($gif['link0'])) { pfSense_interface_flags($gifif, IFF_LINK0); - if (isset($gif['link1'])) + } + if (isset($gif['link1'])) { pfSense_interface_flags($gifif, IFF_LINK1); - if($gifif) + } + if ($gifif) { interfaces_bring_up($gifif); - else + } else { log_error(gettext("could not bring gifif up -- variable not defined")); + } if (!platform_booting()) { $iflist = get_configured_interface_list(); - foreach($iflist as $ifname) { - if($config['interfaces'][$ifname]['if'] == $gifif) { - if(get_interface_gateway($ifname)) { + foreach ($iflist as $ifname) { + if ($config['interfaces'][$ifname]['if'] == $gifif) { + if (get_interface_gateway($ifname)) { system_routing_configure($ifname); break; } - if(get_interface_gateway_v6($ifname)) { + if (get_interface_gateway_v6($ifname)) { system_routing_configure($ifname); break; } @@ -890,10 +980,12 @@ function interface_gif_configure(&$gif, $gifkey = "") { } - if(is_ipaddrv4($gif['tunnel-remote-addr'])) + if (is_ipaddrv4($gif['tunnel-remote-addr'])) { file_put_contents("{$g['tmp_path']}/{$gifif}_router", $gif['tunnel-remote-addr']); - if(is_ipaddrv6($gif['tunnel-remote-addr'])) + } + if (is_ipaddrv6($gif['tunnel-remote-addr'])) { file_put_contents("{$g['tmp_path']}/{$gifif}_routerv6", $gif['tunnel-remote-addr']); + } if (is_ipaddrv4($realifgw)) { mwexec("/sbin/route change -host " . escapeshellarg($gif['remote-addr']) . " {$realifgw}"); @@ -910,8 +1002,9 @@ function interface_gif_configure(&$gif, $gifkey = "") { function interfaces_configure() { global $config, $g; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; + } /* Set up our loopback interface */ interfaces_loopback_configure(); @@ -934,31 +1027,35 @@ function interfaces_configure() { /* This is needed to speedup interfaces on bootup. */ $reload = false; - if (!platform_booting()) + if (!platform_booting()) { $reload = true; + } - foreach($iflist as $if => $ifname) { + foreach ($iflist as $if => $ifname) { $realif = $config['interfaces'][$if]['if']; - if (strstr($realif, "bridge")) + if (strstr($realif, "bridge")) { $bridge_list[$if] = $ifname; - else if (strstr($realif, "gre")) + } else if (strstr($realif, "gre")) { $delayed_list[$if] = $ifname; - else if (strstr($realif, "gif")) + } else if (strstr($realif, "gif")) { $delayed_list[$if] = $ifname; - else if (strstr($realif, "ovpn")) { + } else if (strstr($realif, "ovpn")) { //echo "Delaying OpenVPN interface configuration...done.\n"; continue; } else if (!empty($config['interfaces'][$if]['ipaddrv6']) && $config['interfaces'][$if]['ipaddrv6'] == "track6") { $track6_list[$if] = $ifname; } else { - if (platform_booting()) + if (platform_booting()) { printf(gettext("Configuring %s interface..."), $ifname); + } - if($g['debug']) + if ($g['debug']) { log_error(sprintf(gettext("Configuring %s"), $ifname)); + } interface_configure($if, $reload); - if (platform_booting()) + if (platform_booting()) { echo gettext( "done.") . "\n"; + } } } @@ -978,15 +1075,18 @@ function interfaces_configure() { interfaces_bridge_configure(1); foreach ($track6_list as $if => $ifname) { - if (platform_booting()) + if (platform_booting()) { printf(gettext("Configuring %s interface..."), $ifname); - if ($g['debug']) + } + if ($g['debug']) { log_error(sprintf(gettext("Configuring %s"), $ifname)); + } interface_configure($if, $reload); - if (platform_booting()) + if (platform_booting()) { echo gettext("done.") . "\n"; + } } /* bring up vip interfaces */ @@ -999,30 +1099,36 @@ function interfaces_configure() { interfaces_gif_configure(2); foreach ($delayed_list as $if => $ifname) { - if (platform_booting()) + if (platform_booting()) { printf(gettext("Configuring %s interface..."), $ifname); - if ($g['debug']) + } + if ($g['debug']) { log_error(sprintf(gettext("Configuring %s"), $ifname)); + } interface_configure($if, $reload); - if (platform_booting()) + if (platform_booting()) { echo gettext("done.") . "\n"; + } } /* set up BRIDGe virtual interfaces */ interfaces_bridge_configure(2); foreach ($bridge_list as $if => $ifname) { - if (platform_booting()) + if (platform_booting()) { printf(gettext("Configuring %s interface..."), $ifname); - if($g['debug']) + } + if ($g['debug']) { log_error(sprintf(gettext("Configuring %s"), $ifname)); + } interface_configure($if, $reload); - if (platform_booting()) + if (platform_booting()) { echo gettext("done.") . "\n"; + } } /* configure interface groups */ @@ -1039,10 +1145,11 @@ function interfaces_configure() { services_dhcpd_configure(); /* restart dnsmasq or unbound */ - if (isset($config['dnsmasq']['enable'])) + if (isset($config['dnsmasq']['enable'])) { services_dnsmasq_configure(); - elseif (isset($config['unbound']['enable'])) + } elseif (isset($config['unbound']['enable'])) { services_unbound_configure(); + } } return 0; @@ -1057,50 +1164,57 @@ function interface_vip_bring_down($vip) { global $g; if (strpos($vip['interface'], '_vip')) { - if (is_ipaddrv6($vip['subnet'])) + if (is_ipaddrv6($vip['subnet'])) { $family = 'inet6'; - else + } else { $family = 'inet'; + } $carpvip = get_configured_carp_interface_list($vip['interface'], $family, 'vip'); $iface = $carpvip['interface']; - } else + } else { $iface = $vip['interface']; + } $vipif = get_real_interface($iface); switch ($vip['mode']) { - case "proxyarp": - if (file_exists("{$g['varrun_path']}/choparp_{$vipif}.pid")) - killbypid("{$g['varrun_path']}/choparp_{$vipif}.pid"); - break; - case "ipalias": - if (does_interface_exist($vipif)) { - if (is_ipaddrv6($vip['subnet'])) - mwexec("/sbin/ifconfig {$vipif} inet6 " . escapeshellarg($vip['subnet']) . " -alias"); - else - pfSense_interface_deladdress($vipif, $vip['subnet']); - } - break; - case "carp": - /* XXX: Is enough to delete ip address? */ - if (does_interface_exist($vipif)) { - if (is_ipaddrv6($vip['subnet'])) - mwexec("/sbin/ifconfig {$vipif} inet6 " . escapeshellarg($vip['subnet']) . " delete"); - else - pfSense_interface_deladdress($vipif, $vip['subnet']); - } - break; + case "proxyarp": + if (file_exists("{$g['varrun_path']}/choparp_{$vipif}.pid")) { + killbypid("{$g['varrun_path']}/choparp_{$vipif}.pid"); + } + break; + case "ipalias": + if (does_interface_exist($vipif)) { + if (is_ipaddrv6($vip['subnet'])) { + mwexec("/sbin/ifconfig {$vipif} inet6 " . escapeshellarg($vip['subnet']) . " -alias"); + } else { + pfSense_interface_deladdress($vipif, $vip['subnet']); + } + } + break; + case "carp": + /* XXX: Is enough to delete ip address? */ + if (does_interface_exist($vipif)) { + if (is_ipaddrv6($vip['subnet'])) { + mwexec("/sbin/ifconfig {$vipif} inet6 " . escapeshellarg($vip['subnet']) . " delete"); + } else { + pfSense_interface_deladdress($vipif, $vip['subnet']); + } + } + break; } } function interface_bring_down($interface = "wan", $destroy = false, $ifacecfg = false) { global $config, $g; - if (!isset($config['interfaces'][$interface])) + if (!isset($config['interfaces'][$interface])) { return; + } - if ($g['debug']) + if ($g['debug']) { log_error("Calling interface down for interface {$interface}, destroy is " . (($destroy) ? 'true' : 'false')); + } /* * NOTE: The $realifv6 is needed when WANv4 is type PPP and v6 is DHCP and the option v6 from v4 is used. @@ -1132,108 +1246,120 @@ function interface_bring_down($interface = "wan", $destroy = false, $ifacecfg = } switch ($ifcfg['ipaddr']) { - case "ppp": - case "pppoe": - case "pptp": - case "l2tp": - if (is_array($ppps) && count($ppps)) { - foreach ($ppps as $pppid => $ppp) { - if ($realif == $ppp['if']) { - if (isset($ppp['ondemand']) && !$destroy){ - send_event("interface reconfigure {$interface}"); + case "ppp": + case "pppoe": + case "pptp": + case "l2tp": + if (is_array($ppps) && count($ppps)) { + foreach ($ppps as $pppid => $ppp) { + if ($realif == $ppp['if']) { + if (isset($ppp['ondemand']) && !$destroy) { + send_event("interface reconfigure {$interface}"); + break; + } + if (file_exists("{$g['varrun_path']}/{$ppp['type']}_{$interface}.pid")) { + killbypid("{$g['varrun_path']}/{$ppp['type']}_{$interface}.pid"); + sleep(2); + } + unlink_if_exists("{$g['varetc_path']}/mpd_{$interface}.conf"); break; } - if (file_exists("{$g['varrun_path']}/{$ppp['type']}_{$interface}.pid")) { - killbypid("{$g['varrun_path']}/{$ppp['type']}_{$interface}.pid"); - sleep(2); - } - unlink_if_exists("{$g['varetc_path']}/mpd_{$interface}.conf"); - break; } } - } - break; - case "dhcp": - kill_dhclient_process($realif); - unlink_if_exists("{$g['varetc_path']}/dhclient_{$interface}.conf"); - if(does_interface_exist("$realif")) { - mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " delete", true); - interface_ipalias_cleanup($interface); - if ($destroy == true) - pfSense_interface_flags($realif, -IFF_UP); - mwexec("/usr/sbin/arp -d -i " . escapeshellarg($realif) . " -a"); - } - break; - default: - if(does_interface_exist("$realif")) { - mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " delete", true); - interface_ipalias_cleanup($interface); - if ($destroy == true) - pfSense_interface_flags($realif, -IFF_UP); - mwexec("/usr/sbin/arp -d -i " . escapeshellarg($realif) . " -a"); - } - break; + break; + case "dhcp": + kill_dhclient_process($realif); + unlink_if_exists("{$g['varetc_path']}/dhclient_{$interface}.conf"); + if (does_interface_exist("$realif")) { + mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " delete", true); + interface_ipalias_cleanup($interface); + if ($destroy == true) { + pfSense_interface_flags($realif, -IFF_UP); + } + mwexec("/usr/sbin/arp -d -i " . escapeshellarg($realif) . " -a"); + } + break; + default: + if (does_interface_exist("$realif")) { + mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " delete", true); + interface_ipalias_cleanup($interface); + if ($destroy == true) { + pfSense_interface_flags($realif, -IFF_UP); + } + mwexec("/usr/sbin/arp -d -i " . escapeshellarg($realif) . " -a"); + } + break; } $track6 = array(); switch ($ifcfg['ipaddrv6']) { - case "slaac": - case "dhcp6": - $pidv6 = find_dhcp6c_process($realif); - if($pidv6) - posix_kill($pidv6, SIGTERM); - sleep(3); - unlink_if_exists("{$g['varetc_path']}/dhcp6c_{$interface}.conf"); - if (does_interface_exist($realifv6)) { - $ip6 = find_interface_ipv6($realifv6); - if (is_ipaddrv6($ip6) && $ip6 != "::") - mwexec("/sbin/ifconfig " . escapeshellarg($realifv6) . " inet6 {$ip6} delete", true); - interface_ipalias_cleanup($interface, "inet6"); - if ($destroy == true) - pfSense_interface_flags($realif, -IFF_UP); - //mwexec("/usr/sbin/arp -d -i " . escapeshellarg($realif) . " -a"); - } - $track6 = link_interface_to_track6($interface); - break; - case "6rd": - case "6to4": - $realif = "{$interface}_stf"; - if(does_interface_exist("$realif")) { - $ip6 = get_interface_ipv6($interface); - if (is_ipaddrv6($ip6)) - mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 {$ip6} delete", true); - interface_ipalias_cleanup($interface, "inet6"); - if ($destroy == true) - pfSense_interface_flags($realif, -IFF_UP); - } - $track6 = link_interface_to_track6($interface); - break; - default: - if(does_interface_exist("$realif")) { - $ip6 = get_interface_ipv6($interface); - if (is_ipaddrv6($ip6)) - mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 {$ip6} delete", true); - if (!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) - mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 {$ifcfg['ipaddrv6']} delete", true); - interface_ipalias_cleanup($interface, "inet6"); - if ($destroy == true) - pfSense_interface_flags($realif, -IFF_UP); - //mwexec("/usr/sbin/arp -d -i " . escapeshellarg($realif) . " -a"); - } - $track6 = link_interface_to_track6($interface); - break; + case "slaac": + case "dhcp6": + $pidv6 = find_dhcp6c_process($realif); + if ($pidv6) { + posix_kill($pidv6, SIGTERM); + } + sleep(3); + unlink_if_exists("{$g['varetc_path']}/dhcp6c_{$interface}.conf"); + if (does_interface_exist($realifv6)) { + $ip6 = find_interface_ipv6($realifv6); + if (is_ipaddrv6($ip6) && $ip6 != "::") { + mwexec("/sbin/ifconfig " . escapeshellarg($realifv6) . " inet6 {$ip6} delete", true); + } + interface_ipalias_cleanup($interface, "inet6"); + if ($destroy == true) { + pfSense_interface_flags($realif, -IFF_UP); + } + //mwexec("/usr/sbin/arp -d -i " . escapeshellarg($realif) . " -a"); + } + $track6 = link_interface_to_track6($interface); + break; + case "6rd": + case "6to4": + $realif = "{$interface}_stf"; + if (does_interface_exist("$realif")) { + $ip6 = get_interface_ipv6($interface); + if (is_ipaddrv6($ip6)) { + mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 {$ip6} delete", true); + } + interface_ipalias_cleanup($interface, "inet6"); + if ($destroy == true) { + pfSense_interface_flags($realif, -IFF_UP); + } + } + $track6 = link_interface_to_track6($interface); + break; + default: + if (does_interface_exist("$realif")) { + $ip6 = get_interface_ipv6($interface); + if (is_ipaddrv6($ip6)) { + mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 {$ip6} delete", true); + } + if (!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) { + mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 {$ifcfg['ipaddrv6']} delete", true); + } + interface_ipalias_cleanup($interface, "inet6"); + if ($destroy == true) { + pfSense_interface_flags($realif, -IFF_UP); + } + //mwexec("/usr/sbin/arp -d -i " . escapeshellarg($realif) . " -a"); + } + $track6 = link_interface_to_track6($interface); + break; } if (!empty($track6) && is_array($track6)) { - if (!function_exists('services_dhcpd_configure')) + if (!function_exists('services_dhcpd_configure')) { require_once('services.inc'); + } /* Bring down radvd and dhcp6 on these interfaces */ services_dhcpd_configure('inet6', $track6); } $old_router = ''; - if (file_exists("{$g['tmp_path']}/{$realif}_router")) + if (file_exists("{$g['tmp_path']}/{$realif}_router")) { $old_router = trim(file_get_contents("{$g['tmp_path']}/{$realif}_router")); + } /* remove interface up file if it exists */ unlink_if_exists("{$g['tmp_path']}/{$realif}up"); @@ -1252,20 +1378,20 @@ function interface_bring_down($interface = "wan", $destroy = false, $ifacecfg = } if ($destroy == true) { - if (preg_match("/^[a-z0-9]+^tun|^ovpn|^gif|^gre|^lagg|^bridge|vlan|_stf$/i", $realif)) + if (preg_match("/^[a-z0-9]+^tun|^ovpn|^gif|^gre|^lagg|^bridge|vlan|_stf$/i", $realif)) { pfSense_interface_destroy($realif); + } } return; } -function interfaces_carp_set_maintenancemode($carp_maintenancemode){ +function interfaces_carp_set_maintenancemode($carp_maintenancemode) { global $config; if (isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == false) { unset($config["virtualip_carp_maintenancemode"]); write_config("Leave CARP maintenance mode"); - } else - if (!isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == true) { + } else if (!isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == true) { $config["virtualip_carp_maintenancemode"] = true; write_config("Enter CARP maintenance mode"); } @@ -1281,29 +1407,33 @@ function interfaces_carp_set_maintenancemode($carp_maintenancemode){ function interface_isppp_type($interface) { global $config; - if (!is_array($config['interfaces'][$interface])) + if (!is_array($config['interfaces'][$interface])) { return false; + } switch ($config['interfaces'][$interface]['ipaddr']) { - case 'pptp': - case 'l2tp': - case 'pppoe': - case 'ppp': - return true; - break; - default: - return false; - break; + case 'pptp': + case 'l2tp': + case 'pppoe': + case 'ppp': + return true; + break; + default: + return false; + break; } } function interfaces_ptpid_used($ptpid) { global $config; - if (is_array($config['ppps']['ppp'])) - foreach ($config['ppps']['ppp'] as & $settings) - if ($ptpid == $settings['ptpid']) + if (is_array($config['ppps']['ppp'])) { + foreach ($config['ppps']['ppp'] as & $settings) { + if ($ptpid == $settings['ptpid']) { return true; + } + } + } return false; } @@ -1311,8 +1441,9 @@ function interfaces_ptpid_used($ptpid) { function interfaces_ptpid_next() { $ptpid = 0; - while(interfaces_ptpid_used($ptpid)) + while (interfaces_ptpid_used($ptpid)) { $ptpid++; + } return $ptpid; } @@ -1323,8 +1454,9 @@ function getMPDCRONSettings($pppif) { $cron_cmd_file = "{$g['varetc_path']}/pppoe_restart_{$pppif}"; if (is_array($config['cron']['item'])) { foreach ($config['cron']['item'] as $i => $item) { - if (stripos($item['command'], $cron_cmd_file) !== false) + if (stripos($item['command'], $cron_cmd_file) !== false) { return array("ID" => $i, "ITEM" => $item); + } } } @@ -1337,21 +1469,24 @@ function handle_pppoe_reset($post_array) { $pppif = "{$post_array['type']}{$post_array['ptpid']}"; $cron_cmd_file = "{$g['varetc_path']}/pppoe_restart_{$pppif}"; - if (!is_array($config['cron']['item'])) + if (!is_array($config['cron']['item'])) { $config['cron']['item'] = array(); + } $itemhash = getMPDCRONSettings($pppif); // reset cron items if necessary and return if (empty($post_array['pppoe-reset-type'])) { - if (isset($itemhash)) + if (isset($itemhash)) { unset($config['cron']['item'][$itemhash['ID']]); + } sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP"); return; } - if (empty($itemhash)) + if (empty($itemhash)) { $itemhash = array(); + } $item = array(); if (isset($post_array['pppoe-reset-type']) && $post_array['pppoe-reset-type'] == "custom") { $item['minute'] = $post_array['pppoe_resetminute']; @@ -1369,44 +1504,46 @@ function handle_pppoe_reset($post_array) { $item['command'] = $cron_cmd_file; } else if (isset($post_array['pppoe-reset-type']) && $post_array['pppoe-reset-type'] == "preset") { switch ($post_array['pppoe_pr_preset_val']) { - case "monthly": - $item['minute'] = "0"; - $item['hour'] = "0"; - $item['mday'] = "1"; - $item['month'] = "*"; - $item['wday'] = "*"; - break; - case "weekly": - $item['minute'] = "0"; - $item['hour'] = "0"; - $item['mday'] = "*"; - $item['month'] = "*"; - $item['wday'] = "0"; - break; - case "daily": - $item['minute'] = "0"; - $item['hour'] = "0"; - $item['mday'] = "*"; - $item['month'] = "*"; - $item['wday'] = "*"; - break; - case "hourly": - $item['minute'] = "0"; - $item['hour'] = "*"; - $item['mday'] = "*"; - $item['month'] = "*"; - $item['wday'] = "*"; - break; + case "monthly": + $item['minute'] = "0"; + $item['hour'] = "0"; + $item['mday'] = "1"; + $item['month'] = "*"; + $item['wday'] = "*"; + break; + case "weekly": + $item['minute'] = "0"; + $item['hour'] = "0"; + $item['mday'] = "*"; + $item['month'] = "*"; + $item['wday'] = "0"; + break; + case "daily": + $item['minute'] = "0"; + $item['hour'] = "0"; + $item['mday'] = "*"; + $item['month'] = "*"; + $item['wday'] = "*"; + break; + case "hourly": + $item['minute'] = "0"; + $item['hour'] = "*"; + $item['mday'] = "*"; + $item['month'] = "*"; + $item['wday'] = "*"; + break; } // end switch $item['who'] = "root"; $item['command'] = $cron_cmd_file; } - if (empty($item)) + if (empty($item)) { return; - if (isset($itemhash['ID'])) + } + if (isset($itemhash['ID'])) { $config['cron']['item'][$itemhash['ID']] = $item; - else + } else { $config['cron']['item'][] = $item; + } } /* @@ -1417,35 +1554,40 @@ function interface_ppps_configure($interface) { global $config, $g; /* Return for unassigned interfaces. This is a minimum requirement. */ - if (empty($config['interfaces'][$interface])) + if (empty($config['interfaces'][$interface])) { return 0; + } $ifcfg = $config['interfaces'][$interface]; - if (!isset($ifcfg['enable'])) + if (!isset($ifcfg['enable'])) { return 0; + } // mpd5 requires a /var/spool/lock directory for PPP modem links. - if(!is_dir("/var/spool/lock")) { + if (!is_dir("/var/spool/lock")) { mkdir("/var/spool/lock", 0777, true); } // mpd5 modem chat script expected in the same directory as the mpd_xxx.conf files - if (!file_exists("{$g['varetc_path']}/mpd.script")) + if (!file_exists("{$g['varetc_path']}/mpd.script")) { @symlink("/usr/local/sbin/mpd.script", "{$g['varetc_path']}/mpd.script"); + } if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) { foreach ($config['ppps']['ppp'] as $pppid => $ppp) { - if ($ifcfg['if'] == $ppp['if']) + if ($ifcfg['if'] == $ppp['if']) { break; + } } } - if (!$ppp || $ifcfg['if'] != $ppp['if']){ + if (!$ppp || $ifcfg['if'] != $ppp['if']) { log_error(sprintf(gettext("Can't find PPP config for %s in interface_ppps_configure()."), $ifcfg['if'])); return 0; } $pppif = $ifcfg['if']; - if ($ppp['type'] == "ppp") + if ($ppp['type'] == "ppp") { $type = "modem"; - else + } else { $type = $ppp['type']; + } $upper_type = strtoupper($ppp['type']); /* XXX: This does not make sense and may create trouble @@ -1453,7 +1595,7 @@ function interface_ppps_configure($interface) { if (platform_booting()) { $descr = isset($ifcfg['descr']) ? $ifcfg['descr'] : strtoupper($interface); echo "starting {$pppif} link..."; - if(isvalidpid("{$g['varrun_path']}/{$ppp['type']}_{$interface}.pid")) + if (isvalidpid("{$g['varrun_path']}/{$ppp['type']}_{$interface}.pid")) return 0; } */ @@ -1462,8 +1604,9 @@ function interface_ppps_configure($interface) { if ($type != "modem") { foreach ($ports as $pid => $port) { $ports[$pid] = get_real_interface($port); - if (empty($ports[$pid])) + if (empty($ports[$pid])) { return 0; + } } } $localips = explode(',',$ppp['localip']); @@ -1473,7 +1616,7 @@ function interface_ppps_configure($interface) { /* We bring up the parent interface first because if DHCP is configured on the parent we need * to obtain an address first so we can write it in the mpd .conf file for PPTP and L2TP configs */ - foreach($ports as $pid => $port){ + foreach ($ports as $pid => $port) { switch ($ppp['type']) { case "pppoe": /* Bring the parent interface up */ @@ -1485,18 +1628,19 @@ function interface_ppps_configure($interface) { case "pptp": case "l2tp": /* configure interface */ - if(is_ipaddr($localips[$pid])){ + if (is_ipaddr($localips[$pid])) { // Manually configure interface IP/subnet pfSense_interface_setaddress($port, "{$localips[$pid]}/{$subnets[$pid]}"); interfaces_bring_up($port); - } else if (empty($localips[$pid])) + } else if (empty($localips[$pid])) { $localips[$pid] = get_interface_ip($port); // try to get the interface IP from the port + } - if(!is_ipaddr($localips[$pid])){ + if (!is_ipaddr($localips[$pid])) { log_error("Could not get a Local IP address for PPTP/L2TP link on {$port} in interfaces_ppps_configure. Using 0.0.0.0 ip!"); $localips[$pid] = "0.0.0.0"; } - if(!is_ipaddr($gateways[$pid])){ + if (!is_ipaddr($gateways[$pid])) { log_error(sprintf(gettext('Could not get a PPTP/L2TP Remote IP address from %1$s for %2$s in interfaces_ppps_configure.'), $dhcp_gateway, $gway)); return 0; } @@ -1514,53 +1658,63 @@ function interface_ppps_configure($interface) { } } - if (is_array($ports) && count($ports) > 1) + if (is_array($ports) && count($ports) > 1) { $multilink = "enable"; - else + } else { $multilink = "disable"; + } - if ($type == "modem"){ - if (is_ipaddr($ppp['localip'])) + if ($type == "modem") { + if (is_ipaddr($ppp['localip'])) { $localip = $ppp['localip']; - else + } else { $localip = '0.0.0.0'; + } - if (is_ipaddr($ppp['gateway'])) + if (is_ipaddr($ppp['gateway'])) { $gateway = $ppp['gateway']; - else + } else { $gateway = "10.64.64.{$pppid}"; + } $ranges = "{$localip}/0 {$gateway}/0"; - if (empty($ppp['apnum'])) + if (empty($ppp['apnum'])) { $ppp['apnum'] = 1; - } else + } + } else { $ranges = "0.0.0.0/0 0.0.0.0/0"; + } - if (isset($ppp['ondemand'])) + if (isset($ppp['ondemand'])) { $ondemand = "enable"; - else + } else { $ondemand = "disable"; - if (!isset($ppp['idletimeout'])) + } + if (!isset($ppp['idletimeout'])) { $ppp['idletimeout'] = 0; + } - if (empty($ppp['username']) && $type == "modem"){ + if (empty($ppp['username']) && $type == "modem") { $ppp['username'] = "user"; $ppp['password'] = "none"; } - if (empty($ppp['password']) && $type == "modem") + if (empty($ppp['password']) && $type == "modem") { $passwd = "none"; - else + } else { $passwd = base64_decode($ppp['password']); + } $bandwidths = explode(',',$ppp['bandwidth']); $defaultmtu = "1492"; - if (!empty($ifcfg['mtu'])) + if (!empty($ifcfg['mtu'])) { $defaultmtu = intval($ifcfg['mtu']); + } $mtus = explode(',',$ppp['mtu']); $mrus = explode(',',$ppp['mru']); - if (isset($ppp['mrru'])) + if (isset($ppp['mrru'])) { $mrrus = explode(',',$ppp['mrru']); + } // Construct the mpd.conf file $mpdconf = << $port){ + } + + foreach ($ports as $pid => $port) { $port = get_real_interface($port); $mpdconf .= << "1") ); - if (!empty($pfsyncinterface)) + if (!empty($pfsyncinterface)) { $carp_sync_int = get_real_interface($pfsyncinterface); - else + } else { unset($carp_sync_int); + } /* setup pfsync interface */ if (isset($carp_sync_int) and isset($pfsyncenabled)) { - if (is_ipaddr($pfsyncpeerip)) + if (is_ipaddr($pfsyncpeerip)) { $syncpeer = "syncpeer {$pfsyncpeerip}"; - else + } else { $syncpeer = "-syncpeer"; + } mwexec("/sbin/ifconfig pfsync0 syncdev {$carp_sync_int} {$syncpeer} up", false); @@ -1913,10 +2088,11 @@ function interfaces_sync_setup() { mwexec("/sbin/ifconfig pfsync0 -syncdev -syncpeer down", false); } - if($config['virtualip']['vip']) + if ($config['virtualip']['vip']) { set_single_sysctl("net.inet.carp.allow", "1"); - else + } else { set_single_sysctl("net.inet.carp.allow", "0"); + } if (platform_booting()) { unmute_kernel_msgs(); @@ -1926,18 +2102,19 @@ function interfaces_sync_setup() { function interface_proxyarp_configure($interface = "") { global $config, $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "interface_proxyarp_configure() being called $mt\n"; } /* kill any running choparp */ - if (empty($interface)) + if (empty($interface)) { killbyname("choparp"); - else { + } else { $vipif = get_real_interface($interface); - if (file_exists("{$g['varrun_path']}/choparp_{$vipif}.pid")) + if (file_exists("{$g['varrun_path']}/choparp_{$vipif}.pid")) { killbypid("{$g['varrun_path']}/choparp_{$vipif}.pid"); + } } $paa = array(); @@ -1946,16 +2123,19 @@ function interface_proxyarp_configure($interface = "") { /* group by interface */ foreach ($config['virtualip']['vip'] as $vipent) { if ($vipent['mode'] === "proxyarp") { - if ($vipent['interface']) + if ($vipent['interface']) { $proxyif = $vipent['interface']; - else + } else { $proxyif = "wan"; + } - if (!empty($interface) && $interface != $proxyif) + if (!empty($interface) && $interface != $proxyif) { continue; + } - if (!is_array($paa[$proxyif])) + if (!is_array($paa[$proxyif])) { $paa[$proxyif] = array(); + } $paa[$proxyif][] = $vipent; } @@ -1965,28 +2145,32 @@ function interface_proxyarp_configure($interface = "") { if (!empty($interface)) { if (is_array($paa[$interface])) { $paaifip = get_interface_ip($interface); - if (!is_ipaddr($paaifip)) + if (!is_ipaddr($paaifip)) { return; + } $args = get_real_interface($interface) . " auto"; foreach ($paa[$interface] as $paent) { - if (isset($paent['subnet'])) + if (isset($paent['subnet'])) { $args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}"); - else if (isset($paent['range'])) + } else if (isset($paent['range'])) { $args .= " " . escapeshellarg($paent['range']['from'] . "-" . $paent['range']['to']); + } } mwexec_bg("/usr/local/sbin/choparp " . $args); } } else if (count($paa) > 0) { foreach ($paa as $paif => $paents) { $paaifip = get_interface_ip($paif); - if (!is_ipaddr($paaifip)) + if (!is_ipaddr($paaifip)) { continue; + } $args = get_real_interface($paif) . " auto"; foreach ($paents as $paent) { - if (isset($paent['subnet'])) + if (isset($paent['subnet'])) { $args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}"); - else if (isset($paent['range'])) + } else if (isset($paent['range'])) { $args .= " " . escapeshellarg($paent['range']['from'] . "-" . $paent['range']['to']); + } } mwexec_bg("/usr/local/sbin/choparp " . $args); } @@ -1999,10 +2183,11 @@ function interface_ipalias_cleanup($interface, $inet = "inet4") { if (is_array($config['virtualip']['vip'])) { foreach ($config['virtualip']['vip'] as $vip) { if ($vip['mode'] == "ipalias" && $vip['interface'] == $interface) { - if ($inet == "inet6" && is_ipaddrv6($vip['subnet'])) + if ($inet == "inet6" && is_ipaddrv6($vip['subnet'])) { interface_vip_bring_down($vip); - else if ($inet == "inet4" && is_ipaddrv4($vip['subnet'])) + } else if ($inet == "inet4" && is_ipaddrv4($vip['subnet'])) { interface_vip_bring_down($vip); + } } } } @@ -2010,60 +2195,70 @@ function interface_ipalias_cleanup($interface, $inet = "inet4") { function interfaces_vips_configure($interface = "") { global $g, $config; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "interfaces_vips_configure() being called $mt\n"; } $paa = array(); - if(is_array($config['virtualip']['vip'])) { + if (is_array($config['virtualip']['vip'])) { $carp_setuped = false; $anyproxyarp = false; foreach ($config['virtualip']['vip'] as $vip) { switch ($vip['mode']) { - case "proxyarp": - /* nothing it is handled on interface_proxyarp_configure() */ - if ($interface <> "" && $vip['interface'] <> $interface) - continue; - $anyproxyarp = true; - break; - case "ipalias": - if ($interface <> "" && $vip['interface'] <> $interface) - continue; - interface_ipalias_configure($vip); - break; - case "carp": - if ($interface <> "" && $vip['interface'] <> $interface) - continue; - if ($carp_setuped == false) - $carp_setuped = true; - interface_carp_configure($vip); - break; + case "proxyarp": + /* nothing it is handled on interface_proxyarp_configure() */ + if ($interface <> "" && $vip['interface'] <> $interface) { + continue; + } + $anyproxyarp = true; + break; + case "ipalias": + if ($interface <> "" && $vip['interface'] <> $interface) { + continue; + } + interface_ipalias_configure($vip); + break; + case "carp": + if ($interface <> "" && $vip['interface'] <> $interface) { + continue; + } + if ($carp_setuped == false) { + $carp_setuped = true; + } + interface_carp_configure($vip); + break; } } - if ($carp_setuped == true) + if ($carp_setuped == true) { interfaces_sync_setup(); - if ($anyproxyarp == true) + } + if ($anyproxyarp == true) { interface_proxyarp_configure(); + } } } function interface_ipalias_configure(&$vip) { global $config; - if ($vip['mode'] != 'ipalias') + if ($vip['mode'] != 'ipalias') { return; + } if ($vip['interface'] != 'lo0' && stripos($vip['interface'], '_vip') === false) { - if (!isset($config['interfaces'][$vip['interface']])) + if (!isset($config['interfaces'][$vip['interface']])) { return; + } - if (!isset($config['interfaces'][$vip['interface']]['enable'])) + if (!isset($config['interfaces'][$vip['interface']]['enable'])) { return; + } } $af = 'inet'; - if(is_ipaddrv6($vip['subnet'])) + if (is_ipaddrv6($vip['subnet'])) { $af = 'inet6'; + } $iface = $vip['interface']; $vipadd = ''; if (strpos($vip['interface'], '_vip')) { @@ -2080,25 +2275,26 @@ function interface_reload_carps($cif) { global $config; $carpifs = link_ip_to_carp_interface(find_interface_ip($cif)); - if (empty($carpifs)) + if (empty($carpifs)) { return; + } $carps = explode(" ", $carpifs); - if(is_array($config['virtualip']['vip'])) { + if (is_array($config['virtualip']['vip'])) { $viparr = &$config['virtualip']['vip']; foreach ($viparr as $vip) { if (in_array($vip['carpif'], $carps)) { switch ($vip['mode']) { - case "carp": - interface_vip_bring_down($vip); - sleep(1); - interface_carp_configure($vip); - break; - case "ipalias": - interface_vip_bring_down($vip); - sleep(1); - interface_ipalias_configure($vip); - break; + case "carp": + interface_vip_bring_down($vip); + sleep(1); + interface_carp_configure($vip); + break; + case "ipalias": + interface_vip_bring_down($vip); + sleep(1); + interface_ipalias_configure($vip); + break; } } } @@ -2107,13 +2303,14 @@ function interface_reload_carps($cif) { function interface_carp_configure(&$vip) { global $config, $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "interface_carp_configure() being called $mt\n"; } - if ($vip['mode'] != "carp") + if ($vip['mode'] != "carp") { return; + } /* NOTE: Maybe its useless nowadays */ $realif = get_real_interface($vip['interface']); @@ -2124,25 +2321,29 @@ function interface_carp_configure(&$vip) { $vip_password = $vip['password']; $vip_password = escapeshellarg(addslashes(str_replace(" ", "", $vip_password))); - if ($vip['password'] != "") + if ($vip['password'] != "") { $password = " pass {$vip_password}"; + } $advbase = ""; - if (!empty($vip['advbase'])) + if (!empty($vip['advbase'])) { $advbase = "advbase " . escapeshellarg($vip['advbase']); + } $carp_maintenancemode = isset($config["virtualip_carp_maintenancemode"]); - if ($carp_maintenancemode) + if ($carp_maintenancemode) { $advskew = "advskew 254"; - else + } else { $advskew = "advskew " . escapeshellarg($vip['advskew']); - + } + mwexec("/sbin/ifconfig {$realif} vhid " . escapeshellarg($vip['vhid']) . " {$advskew} {$advbase} {$password}"); - if (is_ipaddrv4($vip['subnet'])) + if (is_ipaddrv4($vip['subnet'])) { mwexec("/sbin/ifconfig {$realif} " . escapeshellarg($vip['subnet']) . "/" . escapeshellarg($vip['subnet_bits']) . " alias vhid " . escapeshellarg($vip['vhid'])); - else if (is_ipaddrv6($vip['subnet'])) + } else if (is_ipaddrv6($vip['subnet'])) { mwexec("/sbin/ifconfig {$realif} inet6 " . escapeshellarg($vip['subnet']) . " prefixlen " . escapeshellarg($vip['subnet_bits']) . " alias vhid " . escapeshellarg($vip['vhid'])); + } return $realif; } @@ -2153,34 +2354,35 @@ function interface_wireless_clone($realif, $wlcfg) { * If it has not been cloned then go ahead and clone it. */ $needs_clone = false; - if(is_array($wlcfg['wireless'])) + if (is_array($wlcfg['wireless'])) { $wlcfg_mode = $wlcfg['wireless']['mode']; - else + } else { $wlcfg_mode = $wlcfg['mode']; + } switch($wlcfg_mode) { - case "hostap": - $mode = "wlanmode hostap"; - break; - case "adhoc": - $mode = "wlanmode adhoc"; - break; - default: - $mode = ""; - break; + case "hostap": + $mode = "wlanmode hostap"; + break; + case "adhoc": + $mode = "wlanmode adhoc"; + break; + default: + $mode = ""; + break; } $baseif = interface_get_wireless_base($wlcfg['if']); - if(does_interface_exist($realif)) { + if (does_interface_exist($realif)) { exec("/sbin/ifconfig " . escapeshellarg($realif), $output, $ret); $ifconfig_str = implode($output); - if(($wlcfg_mode == "hostap") && (! preg_match("/hostap/si", $ifconfig_str))) { + if (($wlcfg_mode == "hostap") && (! preg_match("/hostap/si", $ifconfig_str))) { log_error(sprintf(gettext("Interface %s changed to hostap mode"), $realif)); $needs_clone = true; } - if(($wlcfg_mode == "adhoc") && (! preg_match("/adhoc/si", $ifconfig_str))) { + if (($wlcfg_mode == "adhoc") && (! preg_match("/adhoc/si", $ifconfig_str))) { log_error(sprintf(gettext("Interface %s changed to adhoc mode"), $realif)); $needs_clone = true; } - if(($wlcfg_mode == "bss") && (preg_match("/hostap|adhoc/si", $ifconfig_str))) { + if (($wlcfg_mode == "bss") && (preg_match("/hostap|adhoc/si", $ifconfig_str))) { log_error(sprintf(gettext("Interface %s changed to infrastructure mode"), $realif)); $needs_clone = true; } @@ -2188,16 +2390,17 @@ function interface_wireless_clone($realif, $wlcfg) { $needs_clone = true; } - if($needs_clone == true) { + if ($needs_clone == true) { /* remove previous instance if it exists */ - if(does_interface_exist($realif)) + if (does_interface_exist($realif)) { pfSense_interface_destroy($realif); + } log_error(sprintf(gettext("Cloning new wireless interface %s"), $realif)); // Create the new wlan interface. FreeBSD returns the new interface name. // example: wlan2 exec("/sbin/ifconfig wlan create wlandev {$baseif} {$mode} bssid 2>&1", $out, $ret); - if($ret <> 0) { + if ($ret <> 0) { log_error(sprintf(gettext('Failed to clone interface %1$s with error code %2$s, output %3$s'), $baseif, $ret, $out[0])); return false; } @@ -2216,8 +2419,9 @@ function interface_sync_wireless_clones(&$ifcfg, $sync_changes = false) { 'diversity', 'txantenna', 'rxantenna', 'distance', 'regdomain', 'regcountry', 'reglocation'); - if(!is_interface_wireless($ifcfg['if'])) + if (!is_interface_wireless($ifcfg['if'])) { return; + } $baseif = interface_get_wireless_base($ifcfg['if']); @@ -2228,19 +2432,22 @@ function interface_sync_wireless_clones(&$ifcfg, $sync_changes = false) { if (isset($config['interfaces'][$if]['wireless']['standard']) || $sync_changes) { foreach ($shared_settings as $setting) { if ($sync_changes) { - if (isset($ifcfg['wireless'][$setting])) + if (isset($ifcfg['wireless'][$setting])) { $config['interfaces'][$if]['wireless'][$setting] = $ifcfg['wireless'][$setting]; - else if (isset($config['interfaces'][$if]['wireless'][$setting])) + } else if (isset($config['interfaces'][$if]['wireless'][$setting])) { unset($config['interfaces'][$if]['wireless'][$setting]); + } } else { - if (isset($config['interfaces'][$if]['wireless'][$setting])) + if (isset($config['interfaces'][$if]['wireless'][$setting])) { $ifcfg['wireless'][$setting] = $config['interfaces'][$if]['wireless'][$setting]; - else if (isset($ifcfg['wireless'][$setting])) + } else if (isset($ifcfg['wireless'][$setting])) { unset($ifcfg['wireless'][$setting]); + } } } - if (!$sync_changes) + if (!$sync_changes) { break; + } } } } @@ -2249,15 +2456,17 @@ function interface_sync_wireless_clones(&$ifcfg, $sync_changes = false) { if (isset($config['wireless']['interfaces'][$baseif]) && is_array($config['wireless']['interfaces'][$baseif])) { foreach ($shared_settings as $setting) { if ($sync_changes) { - if (isset($ifcfg['wireless'][$setting])) + if (isset($ifcfg['wireless'][$setting])) { $config['wireless']['interfaces'][$baseif][$setting] = $ifcfg['wireless'][$setting]; - else if (isset($config['wireless']['interfaces'][$baseif][$setting])) + } else if (isset($config['wireless']['interfaces'][$baseif][$setting])) { unset($config['wireless']['interfaces'][$baseif][$setting]); + } } else if (isset($config['wireless']['interfaces'][$baseif][$setting])) { - if (isset($config['wireless']['interfaces'][$baseif][$setting])) + if (isset($config['wireless']['interfaces'][$baseif][$setting])) { $ifcfg['wireless'][$setting] = $config['wireless']['interfaces'][$baseif][$setting]; - else if (isset($ifcfg['wireless'][$setting])) + } else if (isset($ifcfg['wireless'][$setting])) { unset($ifcfg['wireless'][$setting]); + } } } } @@ -2322,19 +2531,21 @@ function interface_wireless_configure($if, &$wl, &$wlcfg) { /* XXX: Disable ampdu for now on mwl when running in 11n mode * to prevent massive packet loss under certain conditions. */ - if(preg_match("/^mwl/i", $if) && ($standard == "11ng" || $standard == "11na")) + if (preg_match("/^mwl/i", $if) && ($standard == "11ng" || $standard == "11na")) { $wlcmd[] = "-ampdu"; + } /* Set ssid */ - if($wlcfg['ssid']) + if ($wlcfg['ssid']) { $wlcmd[] = "ssid " .escapeshellarg($wlcfg['ssid']); + } /* Set 802.11g protection mode */ $wlcmd[] = "protmode " . escapeshellarg($wlcfg['protmode']); /* set wireless channel value */ - if(isset($wlcfg['channel'])) { - if($wlcfg['channel'] == "0") { + if (isset($wlcfg['channel'])) { + if ($wlcfg['channel'] == "0") { $wlcmd[] = "channel any"; } else { $wlcmd[] = "channel " . escapeshellarg($wlcfg['channel']); @@ -2342,20 +2553,24 @@ function interface_wireless_configure($if, &$wl, &$wlcfg) { } /* Set antenna diversity value */ - if(isset($wlcfg['diversity'])) + if (isset($wlcfg['diversity'])) { $wl_sysctl[] = "diversity=" . escapeshellarg($wlcfg['diversity']); + } /* Set txantenna value */ - if(isset($wlcfg['txantenna'])) + if (isset($wlcfg['txantenna'])) { $wl_sysctl[] = "txantenna=" . escapeshellarg($wlcfg['txantenna']); + } /* Set rxantenna value */ - if(isset($wlcfg['rxantenna'])) + if (isset($wlcfg['rxantenna'])) { $wl_sysctl[] = "rxantenna=" . escapeshellarg($wlcfg['rxantenna']); + } /* set Distance value */ - if($wlcfg['distance']) + if ($wlcfg['distance']) { $distance = escapeshellarg($wlcfg['distance']); + } /* Set wireless hostap mode */ if ($wlcfg['mode'] == "hostap") { @@ -2374,46 +2589,46 @@ function interface_wireless_configure($if, &$wl, &$wlcfg) { /* Not necessary to set BSS mode as this is default if adhoc and/or hostap is NOT set */ /* handle hide ssid option */ - if(isset($wlcfg['hidessid']['enable'])) { + if (isset($wlcfg['hidessid']['enable'])) { $wlcmd[] = "hidessid"; } else { $wlcmd[] = "-hidessid"; } /* handle pureg (802.11g) only option */ - if(isset($wlcfg['pureg']['enable'])) { + if (isset($wlcfg['pureg']['enable'])) { $wlcmd[] = "mode 11g pureg"; } else { $wlcmd[] = "-pureg"; } /* handle puren (802.11n) only option */ - if(isset($wlcfg['puren']['enable'])) { + if (isset($wlcfg['puren']['enable'])) { $wlcmd[] = "puren"; } else { $wlcmd[] = "-puren"; } /* enable apbridge option */ - if(isset($wlcfg['apbridge']['enable'])) { + if (isset($wlcfg['apbridge']['enable'])) { $wlcmd[] = "apbridge"; } else { $wlcmd[] = "-apbridge"; } /* handle turbo option */ - if(isset($wlcfg['turbo']['enable'])) { + if (isset($wlcfg['turbo']['enable'])) { $wlcmd[] = "mediaopt turbo"; } else { $wlcmd[] = "-mediaopt turbo"; } /* handle txpower setting */ - /* if($wlcfg['txpower'] <> "") + /* if ($wlcfg['txpower'] <> "") $wlcmd[] = "txpower " . escapeshellarg($wlcfg['txpower']); */ /* handle wme option */ - if(isset($wlcfg['wme']['enable'])) { + if (isset($wlcfg['wme']['enable'])) { $wlcmd[] = "wme"; } else { $wlcmd[] = "-wme"; @@ -2452,9 +2667,9 @@ function interface_wireless_configure($if, &$wl, &$wlcfg) { conf_mount_rw(); switch ($wlcfg['mode']) { - case 'bss': - if (isset($wlcfg['wpa']['enable'])) { - $wpa .= << $mtu) + if (intval($config['interfaces'][$assignedport]['mtu']) > $mtu) { $mtu = $config['interfaces'][$assignedport]['mtu']; + } } } } @@ -2811,8 +3046,9 @@ function interface_vlan_mtu_configured($realhwif, $mtu) { function interface_vlan_adapt_mtu($vlanifs, $mtu) { global $config; - if (!is_array($vlanifs)) + if (!is_array($vlanifs)) { return; + } /* All vlans need to use the same mtu value as their parent. */ foreach ($vlanifs as $vlan) { @@ -2821,11 +3057,13 @@ function interface_vlan_adapt_mtu($vlanifs, $mtu) { if (!empty($config['interfaces'][$assignedport]['mtu'])) { pfSense_interface_mtu($vlan['vlanif'], $config['interfaces'][$assignedport]['mtu']); } else { - if (get_interface_mtu($vlan['vlanif']) != $mtu) + if (get_interface_mtu($vlan['vlanif']) != $mtu) { pfSense_interface_mtu($vlan['vlanif'], $mtu); + } } - } else if (get_interface_mtu($vlan['vlanif']) != $mtu) + } else if (get_interface_mtu($vlan['vlanif']) != $mtu) { pfSense_interface_mtu($vlan['vlanif'], $mtu); + } } } @@ -2836,8 +3074,9 @@ function interface_configure($interface = "wan", $reloadall = false, $linkupeven $wancfg = $config['interfaces'][$interface]; - if (!isset($wancfg['enable'])) + if (!isset($wancfg['enable'])) { return; + } $realif = get_real_interface($interface); $realhwif_array = get_parent_interface($interface); @@ -2850,40 +3089,47 @@ function interface_configure($interface = "wan", $reloadall = false, $linkupeven if (is_array($tmpifaces)) { foreach ($tmpifaces as $tmpiface) { if (is_ipaddrv6($tmpiface) || is_subnetv6($tmpiface)) { - if (!is_linklocal($tmpiface)) + if (!is_linklocal($tmpiface)) { mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 {$tmpiface} delete"); + } } else { if (is_subnetv4($tmpiface)) { $tmpip = explode('/', $tmpiface); $tmpip = $tmpip[0]; - } else + } else { $tmpip = $tmpiface; + } pfSense_interface_deladdress($realif, $tmpip); } } } /* only bring down the interface when both v4 and v6 are set to NONE */ - if (empty($wancfg['ipaddr']) && empty($wancfg['ipaddrv6'])) + if (empty($wancfg['ipaddr']) && empty($wancfg['ipaddrv6'])) { interface_bring_down($interface); + } } $interface_to_check = $realif; - if (interface_isppp_type($interface)) + if (interface_isppp_type($interface)) { $interface_to_check = $realhwif; + } /* Need to check that the interface exists or not in the case where its coming back from disabled state see #3270 */ - if (!platform_booting() && (in_array(substr($realif, 0, 3), array("gre", "gif")) || !does_interface_exist($interface_to_check))) + if (!platform_booting() && (in_array(substr($realif, 0, 3), array("gre", "gif")) || !does_interface_exist($interface_to_check))) { interface_virtual_create($interface_to_check); + } /* Disable Accepting router advertisements unless specifically requested */ - if ($g['debug']) + if ($g['debug']) { log_error("Deny router advertisements for interface {$interface}"); + } mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 -accept_rtadv", true); /* wireless configuration? */ - if (is_array($wancfg['wireless'])) + if (is_array($wancfg['wireless'])) { interface_wireless_configure($realif, $wancfg, $wancfg['wireless']); + } $mac = get_interface_mac($realhwif); /* @@ -2914,10 +3160,12 @@ function interface_configure($interface = "wan", $reloadall = false, $linkupeven /* media */ if ($wancfg['media'] || $wancfg['mediaopt']) { $cmd = "/sbin/ifconfig " . escapeshellarg($realhwif); - if ($wancfg['media']) + if ($wancfg['media']) { $cmd .= " media " . escapeshellarg($wancfg['media']); - if ($wancfg['mediaopt']) + } + if ($wancfg['mediaopt']) { $cmd .= " mediaopt " . escapeshellarg($wancfg['mediaopt']); + } mwexec($cmd); } @@ -2933,23 +3181,27 @@ function interface_configure($interface = "wan", $reloadall = false, $linkupeven $tunnelif = substr($realif, 0, 3); - if (does_interface_exist($wancfg['if'])) + if (does_interface_exist($wancfg['if'])) { interfaces_bring_up($wancfg['if']); + } if (!empty($wancfg['mtu'])) { if (stristr($realif, "_vlan")) { $assignedparent = convert_real_interface_to_friendly_interface_name($realhwif); if (!empty($assignedparent) && !empty($config['interfaces'][$assignedparent]['mtu'])) { $parentmtu = $config['interfaces'][$assignedparent]['mtu']; - if ($wancfg['mtu'] > $parentmtu) + if ($wancfg['mtu'] > $parentmtu) { log_error("There is a conflict on MTU between parent {$realhwif} and VLAN({$realif})"); - } else + } + } else { $parentmtu = 0; + } $parentmtu = interface_vlan_mtu_configured($realhwif, $parentmtu); - if (get_interface_mtu($realhwif) != $parentmtu) + if (get_interface_mtu($realhwif) != $parentmtu) { pfSense_interface_mtu($realhwif, $parentmtu); + } /* All vlans need to use the same mtu value as their parent. */ interface_vlan_adapt_mtu(link_interface_to_vlans($realhwif), $parentmtu); @@ -2966,61 +3218,64 @@ function interface_configure($interface = "wan", $reloadall = false, $linkupeven } } } else { - if ($wancfg['mtu'] != get_interface_mtu($realif)) + if ($wancfg['mtu'] != get_interface_mtu($realif)) { pfSense_interface_mtu($realif, $wancfg['mtu']); + } /* This case is needed when the parent of vlans is being configured */ $vlans = link_interface_to_vlans($realif); - if (is_array($vlans)) + if (is_array($vlans)) { interface_vlan_adapt_mtu($vlans, $wancfg['mtu']); + } unset($vlans); } /* XXX: What about gre/gif/.. ? */ } switch ($wancfg['ipaddr']) { - case 'dhcp': - interface_dhcp_configure($interface); - break; - case 'pppoe': - case 'l2tp': - case 'pptp': - case 'ppp': - interface_ppps_configure($interface); - break; - default: - /* XXX: Kludge for now related to #3280 */ - if (!in_array($tunnelif, array("gif", "gre", "ovp"))) { - if (is_ipaddrv4($wancfg['ipaddr']) && $wancfg['subnet'] <> "") - pfSense_interface_setaddress($realif, "{$wancfg['ipaddr']}/{$wancfg['subnet']}"); - } - break; + case 'dhcp': + interface_dhcp_configure($interface); + break; + case 'pppoe': + case 'l2tp': + case 'pptp': + case 'ppp': + interface_ppps_configure($interface); + break; + default: + /* XXX: Kludge for now related to #3280 */ + if (!in_array($tunnelif, array("gif", "gre", "ovp"))) { + if (is_ipaddrv4($wancfg['ipaddr']) && $wancfg['subnet'] <> "") { + pfSense_interface_setaddress($realif, "{$wancfg['ipaddr']}/{$wancfg['subnet']}"); + } + } + break; } switch ($wancfg['ipaddrv6']) { - case 'slaac': - case 'dhcp6': - interface_dhcpv6_configure($interface, $wancfg); - break; - case '6rd': - interface_6rd_configure($interface, $wancfg); - break; - case '6to4': - interface_6to4_configure($interface, $wancfg); - break; - case 'track6': - interface_track6_configure($interface, $wancfg, $linkupevent); - break; - default: - /* XXX: Kludge for now related to #3280 */ - if (!in_array($tunnelif, array("gif", "gre", "ovp"))) { - if (is_ipaddrv6($wancfg['ipaddrv6']) && $wancfg['subnetv6'] <> "") { - //pfSense_interface_setaddress($realif, "{$wancfg['ipaddrv6']}/{$wancfg['subnetv6']}"); - // FIXME: Add IPv6 Support to the pfSense module - mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 {$wancfg['ipaddrv6']} prefixlen " . escapeshellarg($wancfg['subnetv6'])); + case 'slaac': + case 'dhcp6': + interface_dhcpv6_configure($interface, $wancfg); + break; + case '6rd': + interface_6rd_configure($interface, $wancfg); + break; + case '6to4': + interface_6to4_configure($interface, $wancfg); + break; + case 'track6': + interface_track6_configure($interface, $wancfg, $linkupevent); + break; + default: + /* XXX: Kludge for now related to #3280 */ + if (!in_array($tunnelif, array("gif", "gre", "ovp"))) { + if (is_ipaddrv6($wancfg['ipaddrv6']) && $wancfg['subnetv6'] <> "") { + //pfSense_interface_setaddress($realif, "{$wancfg['ipaddrv6']}/{$wancfg['subnetv6']}"); + // FIXME: Add IPv6 Support to the pfSense module + mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 {$wancfg['ipaddrv6']} prefixlen " . escapeshellarg($wancfg['subnetv6'])); + } } - } - break; + break; } interface_netgraph_needed($interface); @@ -3031,31 +3286,36 @@ function interface_configure($interface = "wan", $reloadall = false, $linkupeven if ($tunnelif != 'gre') { unset($gre); $gre = link_interface_to_gre($interface); - if (!empty($gre)) + if (!empty($gre)) { array_walk($gre, 'interface_gre_configure'); + } } if ($tunnelif != 'gif') { unset($gif); - $gif = link_interface_to_gif($interface); - if (!empty($gif)) + $gif = link_interface_to_gif ($interface); + if (!empty($gif)) { array_walk($gif, 'interface_gif_configure'); + } } if ($linkupevent == false || substr($realif, 0, 4) == "ovpn") { unset($bridgetmp); $bridgetmp = link_interface_to_bridge($interface); - if (!empty($bridgetmp)) + if (!empty($bridgetmp)) { interface_bridge_add_member($bridgetmp, $realif); + } } $grouptmp = link_interface_to_group($interface); - if (!empty($grouptmp)) + if (!empty($grouptmp)) { array_walk($grouptmp, 'interface_group_add_member'); + } - if ($interface == "lan") + if ($interface == "lan") { /* make new hosts file */ system_hosts_generate(); + } if ($reloadall == true) { @@ -3066,17 +3326,19 @@ function interface_configure($interface = "wan", $reloadall = false, $linkupeven send_event("service reload ipsecdns"); /* restart dnsmasq or unbound */ - if (isset($config['dnsmasq']['enable'])) + if (isset($config['dnsmasq']['enable'])) { services_dnsmasq_configure(); - elseif (isset($config['unbound']['enable'])) + } elseif (isset($config['unbound']['enable'])) { services_unbound_configure(); + } /* update dyndns */ send_event("service reload dyndns {$interface}"); /* reload captive portal */ - if (!function_exists('captiveportal_init_rules_byinterface')) + if (!function_exists('captiveportal_init_rules_byinterface')) { require_once('captiveportal.inc'); + } captiveportal_init_rules_byinterface($interface); } } @@ -3088,21 +3350,25 @@ function interface_configure($interface = "wan", $reloadall = false, $linkupeven function interface_track6_configure($interface = "lan", $wancfg, $linkupevent = false) { global $config, $g; - if (!is_array($wancfg)) + if (!is_array($wancfg)) { return; + } - if (!isset($wancfg['enable'])) + if (!isset($wancfg['enable'])) { return; + } /* If the interface is not configured via another, exit */ - if (empty($wancfg['track6-interface'])) + if (empty($wancfg['track6-interface'])) { return; + } /* always configure a link-local of fe80::1:1 on the track6 interfaces */ $realif = get_real_interface($interface); $linklocal = find_interface_ipv6_ll($realif); - if (!empty($linklocal)) + if (!empty($linklocal)) { mwexec("/sbin/ifconfig {$realif} inet6 {$linklocal} delete"); + } /* XXX: This might break for good on a carp installation using link-local as network ips */ /* XXX: Probably should remove? */ mwexec("/sbin/ifconfig {$realif} inet6 fe80::1:1%{$realif}"); @@ -3114,38 +3380,43 @@ function interface_track6_configure($interface = "lan", $wancfg, $linkupevent = } switch($trackcfg['ipaddrv6']) { - case "6to4": - if ($g['debug']) - log_error("Interface {$interface} configured via {$wancfg['track6-interface']} type {$type}"); - interface_track6_6to4_configure($interface, $wancfg); - break; - case "6rd": - if ($g['debug']) - log_error("Interface {$interface} configured via {$wancfg['track6-interface']} type {$type}"); - interface_track6_6rd_configure($interface, $wancfg); - break; - case "dhcp6": - if ($linkupevent == true) { - /* - * NOTE: Usually come here from rc.linkup calling so just call directly instead of generating event - * Instead of disrupting all other v4 configuration just restart DHCPv6 client for now - * - * XXX: Probably DHCPv6 client should handle this automagically itself? - */ - $parentrealif = get_real_interface($wancfg['track6-interface']); - $pidv6 = find_dhcp6c_process($parentrealif); - if($pidv6) - posix_kill($pidv6, SIGHUP); - } - break; + case "6to4": + if ($g['debug']) { + log_error("Interface {$interface} configured via {$wancfg['track6-interface']} type {$type}"); + } + interface_track6_6to4_configure($interface, $wancfg); + break; + case "6rd": + if ($g['debug']) { + log_error("Interface {$interface} configured via {$wancfg['track6-interface']} type {$type}"); + } + interface_track6_6rd_configure($interface, $wancfg); + break; + case "dhcp6": + if ($linkupevent == true) { + /* + * NOTE: Usually come here from rc.linkup calling so just call directly instead of generating event + * Instead of disrupting all other v4 configuration just restart DHCPv6 client for now + * + * XXX: Probably DHCPv6 client should handle this automagically itself? + */ + $parentrealif = get_real_interface($wancfg['track6-interface']); + $pidv6 = find_dhcp6c_process($parentrealif); + if ($pidv6) { + posix_kill($pidv6, SIGHUP); + } + } + break; } if ($linkupevent == false) { - if (!function_exists('services_dhcpd_configure')) + if (!function_exists('services_dhcpd_configure')) { require_once("services.inc"); + } - if (isset($config['unbound']['enable'])) + if (isset($config['unbound']['enable'])) { services_unbound_configure(); + } services_dhcpd_configure("inet6"); } @@ -3158,12 +3429,14 @@ function interface_track6_6rd_configure($interface = "lan", $lancfg) { global $interface_ipv6_arr_cache; global $interface_snv6_arr_cache; - if (!is_array($lancfg)) + if (!is_array($lancfg)) { return; + } /* If the interface is not configured via another, exit */ - if (empty($lancfg['track6-interface'])) + if (empty($lancfg['track6-interface'])) { return; + } $wancfg = $config['interfaces'][$lancfg['track6-interface']]; if (empty($wancfg)) { @@ -3204,8 +3477,9 @@ function interface_track6_6rd_configure($interface = "lan", $lancfg) { $lanif = get_real_interface($interface); $oip = find_interface_ipv6($lanif); - if (is_ipaddrv6($oip)) + if (is_ipaddrv6($oip)) { mwexec("/sbin/ifconfig {$lanif} inet6 {$oip} delete"); + } unset($interface_ipv6_arr_cache[$lanif]); unset($interface_snv6_arr_cache[$lanif]); log_error("rd6 {$interface} with ipv6 address {$rd6lan} based on {$lancfg['track6-interface']} ipv4 {$ip4address}"); @@ -3219,12 +3493,14 @@ function interface_track6_6to4_configure($interface = "lan", $lancfg) { global $interface_ipv6_arr_cache; global $interface_snv6_arr_cache; - if (!is_array($lancfg)) + if (!is_array($lancfg)) { return; + } /* If the interface is not configured via another, exit */ - if (empty($lancfg['track6-interface'])) + if (empty($lancfg['track6-interface'])) { return; + } $wancfg = $config['interfaces'][$lancfg['track6-interface']]; if (empty($wancfg)) { @@ -3261,8 +3537,9 @@ function interface_track6_6to4_configure($interface = "lan", $lancfg) { $lanif = get_real_interface($interface); $oip = find_interface_ipv6($lanif); - if (is_ipaddrv6($oip)) + if (is_ipaddrv6($oip)) { mwexec("/sbin/ifconfig {$lanif} inet6 {$oip} delete"); + } unset($interface_ipv6_arr_cache[$lanif]); unset($interface_snv6_arr_cache[$lanif]); log_error("sixto4 {$interface} with ipv6 address {$sixto4lan} based on {$lancfg['track6-interface']} ipv4 {$ip4address}"); @@ -3277,11 +3554,13 @@ function interface_6rd_configure($interface = "wan", $wancfg) { /* because this is a tunnel interface we can only function * with a public IPv4 address on the interface */ - if (!is_array($wancfg)) + if (!is_array($wancfg)) { return; + } - if (!is_module_loaded('if_stf.ko')) + if (!is_module_loaded('if_stf.ko')) { mwexec('/sbin/kldload if_stf.ko'); + } $wanif = get_real_interface($interface); $ip4address = find_interface_ip($wanif); @@ -3291,8 +3570,9 @@ function interface_6rd_configure($interface = "wan", $wancfg) { } $hexwanv4 = return_hex_ipv4($ip4address); - if (!is_numeric($wancfg['prefix-6rd-v4plen'])) + if (!is_numeric($wancfg['prefix-6rd-v4plen'])) { $wancfg['prefix-6rd-v4plen'] = 0; + } /* create the long prefix notation for math, save the prefix length */ $rd6prefix = explode("/", $wancfg['prefix-6rd']); @@ -3300,8 +3580,9 @@ function interface_6rd_configure($interface = "wan", $wancfg) { $brgw = explode('.', $wancfg['gateway-6rd']); $rd6brgw = substr(Net_IPv6::_ip2Bin($rd6prefix[0]), 0, $rd6prefixlen); $rd6brgw .= str_pad(decbin($brgw[0]), 8, '0', STR_PAD_LEFT) . str_pad(decbin($brgw[1]), 8, '0', STR_PAD_LEFT) . str_pad(decbin($brgw[2]), 8, '0', STR_PAD_LEFT) . str_pad(decbin($brgw[3]), 8, '0', STR_PAD_LEFT); - if (strlen($rd6brgw) < 128) + if (strlen($rd6brgw) < 128) { $rd6brgw = str_pad($rd6brgw, 128, '0', STR_PAD_RIGHT); + } $rd6brgw = Net_IPv6::compress(Net_IPv6::_bin2Ip($rd6brgw)); unset($brgw); $rd6prefix = Net_IPv6::uncompress($rd6prefix[0]); @@ -3321,48 +3602,55 @@ function interface_6rd_configure($interface = "wan", $wancfg) { /* XXX: need to extend to support variable prefix size for v4 */ - if (!is_module_loaded("if_stf")) + if (!is_module_loaded("if_stf")) { mwexec("/sbin/kldload if_stf.ko"); + } $stfiface = "{$interface}_stf"; - if (does_interface_exist($stfiface)) + if (does_interface_exist($stfiface)) { pfSense_interface_destroy($stfiface); + } $tmpstfiface = pfSense_interface_create("stf"); pfSense_interface_rename($tmpstfiface, $stfiface); pfSense_interface_flags($stfiface, IFF_LINK2); mwexec("/sbin/ifconfig {$stfiface} inet6 {$rd6prefix}/{$rd6prefixlen}"); mwexec("/sbin/ifconfig {$stfiface} stfv4br " . escapeshellarg($wancfg['gateway-6rd'])); - if ($wancfg['prefix-6rd-v4plen'] >= 0 && $wancfg['prefix-6rd-v4plen'] <= 32) + if ($wancfg['prefix-6rd-v4plen'] >= 0 && $wancfg['prefix-6rd-v4plen'] <= 32) { mwexec("/sbin/ifconfig {$stfiface} stfv4net {$ip4address}/" . escapeshellarg($wancfg['prefix-6rd-v4plen'])); - if ($g['debug']) + } + if ($g['debug']) { log_error("Created 6rd interface {$stfiface} {$rd6prefix}/{$rd6prefixlen}"); + } /* write out a default router file */ file_put_contents("{$g['tmp_path']}/{$wanif}_routerv6", "{$rd6brgw}\n"); file_put_contents("{$g['tmp_path']}/{$wanif}_defaultgwv6", "{$rd6brgw}\n"); $ip4gateway = get_interface_gateway($interface); - if (is_ipaddrv4($ip4gateway)) + if (is_ipaddrv4($ip4gateway)) { mwexec("/sbin/route change -host " . escapeshellarg($wancfg['gateway-6rd']) . " {$ip4gateway}"); + } /* configure dependent interfaces */ - if (!platform_booting()) + if (!platform_booting()) { link_interface_to_track6($interface, "update"); + } return 0; } -function interface_6to4_configure($interface = "wan", $wancfg){ +function interface_6to4_configure($interface = "wan", $wancfg) { global $config, $g; /* because this is a tunnel interface we can only function * with a public IPv4 address on the interface */ - if (!is_array($wancfg)) + if (!is_array($wancfg)) { return; + } $wanif = get_real_interface($interface); $ip4address = find_interface_ip($wanif); - if((!is_ipaddrv4($ip4address)) || (is_private_ip($ip4address))) { + if ((!is_ipaddrv4($ip4address)) || (is_private_ip($ip4address))) { log_error("The interface IPv4 '{$ip4address}' address on interface '{$wanif}' is not public, not configuring 6RD tunnel"); return false; } @@ -3376,18 +3664,20 @@ function interface_6to4_configure($interface = "wan", $wancfg){ /* we need the hex form of the interface IPv4 address */ $ip4arr = explode(".", $ip4address); $hexwanv4 = ""; - foreach($ip4arr as $octet) + foreach ($ip4arr as $octet) { $hexwanv4 .= sprintf("%02x", $octet); + } /* we need the hex form of the broker IPv4 address */ $ip4arr = explode(".", "192.88.99.1"); $hexbrv4 = ""; - foreach($ip4arr as $octet) + foreach ($ip4arr as $octet) { $hexbrv4 .= sprintf("%02x", $octet); + } /* binary presentation of the prefix for all 128 bits. */ $stfprefixbin = ""; - foreach($stfarr as $element) { + foreach ($stfarr as $element) { $stfprefixbin .= sprintf("%016b", hexdec($element)); } /* just save the left prefix length bits */ @@ -3405,44 +3695,51 @@ function interface_6to4_configure($interface = "wan", $wancfg){ $stfbrarr = array(); $stfbrbinarr = array(); $stfbrbinarr = str_split($stfbrokerbin, 16); - foreach($stfbrbinarr as $bin) + foreach ($stfbrbinarr as $bin) { $stfbrarr[] = dechex(bindec($bin)); + } $stfbrgw = Net_IPv6::compress(implode(":", $stfbrarr)); /* convert the 128 bits for the broker address back into a valid IPv6 address */ $stflanarr = array(); $stflanbinarr = array(); $stflanbinarr = str_split($stflanbin, 16); - foreach($stflanbinarr as $bin) + foreach ($stflanbinarr as $bin) { $stflanarr[] = dechex(bindec($bin)); + } $stflanpr = Net_IPv6::compress(implode(":", $stflanarr)); $stflanarr[7] = 1; $stflan = Net_IPv6::compress(implode(":", $stflanarr)); /* setup the stf interface */ - if (!is_module_loaded("if_stf")) + if (!is_module_loaded("if_stf")) { mwexec("/sbin/kldload if_stf.ko"); + } $stfiface = "{$interface}_stf"; - if (does_interface_exist($stfiface)) + if (does_interface_exist($stfiface)) { pfSense_interface_destroy($stfiface); + } $tmpstfiface = pfSense_interface_create("stf"); pfSense_interface_rename($tmpstfiface, $stfiface); pfSense_interface_flags($stfiface, IFF_LINK2); mwexec("/sbin/ifconfig {$stfiface} inet6 {$stflanpr} prefixlen 16"); - if ($g['debug']) + if ($g['debug']) { log_error("Set IPv6 address inet6 {$stflanpr} prefixlen 16 for {$stfiface}, route {$stfbrgw}"); + } /* write out a default router file */ file_put_contents("{$g['tmp_path']}/{$wanif}_routerv6", "{$stfbrgw}"); file_put_contents("{$g['tmp_path']}/{$wanif}_defaultgwv6", "{$stfbrgw}"); $ip4gateway = get_interface_gateway($interface); - if (is_ipaddrv4($ip4gateway)) + if (is_ipaddrv4($ip4gateway)) { mwexec("/sbin/route change -host 192.88.99.1 {$ip4gateway}"); + } - if (!platform_booting()) + if (!platform_booting()) { link_interface_to_track6($interface, "update"); + } return 0; } @@ -3450,15 +3747,16 @@ function interface_6to4_configure($interface = "wan", $wancfg){ function interface_dhcpv6_configure($interface = "wan", $wancfg) { global $config, $g; - if (!is_array($wancfg)) + if (!is_array($wancfg)) { return; + } $wanif = get_real_interface($interface, "inet6"); $dhcp6cconf = ""; $dhcp6cconf .= "interface {$wanif} {\n"; /* for SLAAC interfaces we do fire off a dhcp6 client for just our name servers */ - if($wancfg['ipaddrv6'] == "slaac") { + if ($wancfg['ipaddrv6'] == "slaac") { $dhcp6cconf .= " information-only;\n"; $dhcp6cconf .= " request domain-name-servers;\n"; $dhcp6cconf .= " request domain-name;\n"; @@ -3468,15 +3766,18 @@ function interface_dhcpv6_configure($interface = "wan", $wancfg) { $trackiflist = array(); $iflist = link_interface_to_track6($interface); foreach ($iflist as $ifname => $ifcfg) { - if (is_numeric($ifcfg['track6-prefix-id'])) + if (is_numeric($ifcfg['track6-prefix-id'])) { $trackiflist[$ifname] = $ifcfg; + } } /* skip address request if this is set */ - if(!isset($wancfg['dhcp6prefixonly'])) + if (!isset($wancfg['dhcp6prefixonly'])) { $dhcp6cconf .= " send ia-na 0; # request stateful address\n"; - if(is_numeric($wancfg['dhcp6-ia-pd-len']) && !empty($trackiflist)) + } + if (is_numeric($wancfg['dhcp6-ia-pd-len']) && !empty($trackiflist)) { $dhcp6cconf .= " send ia-pd 0; # request prefix delegation\n"; + } $dhcp6cconf .= "\trequest domain-name-servers;\n"; $dhcp6cconf .= "\trequest domain-name;\n"; @@ -3484,18 +3785,21 @@ function interface_dhcpv6_configure($interface = "wan", $wancfg) { $dhcp6cconf .= "};\n"; - if(!isset($wancfg['dhcp6prefixonly'])) + if (!isset($wancfg['dhcp6prefixonly'])) { $dhcp6cconf .= "id-assoc na 0 { };\n"; + } - if(is_numeric($wancfg['dhcp6-ia-pd-len']) && !empty($trackiflist)) { + if (is_numeric($wancfg['dhcp6-ia-pd-len']) && !empty($trackiflist)) { /* Setup the prefix delegation */ $dhcp6cconf .= "id-assoc pd 0 {\n"; $preflen = 64 - $wancfg['dhcp6-ia-pd-len']; - if (isset($wancfg['dhcp6-ia-pd-send-hint'])) + if (isset($wancfg['dhcp6-ia-pd-send-hint'])) { $dhcp6cconf .= " prefix ::/{$preflen} infinity;\n"; + } foreach ($trackiflist as $friendly => $ifcfg) { - if ($g['debug']) + if ($g['debug']) { log_error("setting up $ifdescr - {$ifcfg['track6-prefix-id']}"); + } $realif = get_real_interface($friendly); $dhcp6cconf .= " prefix-interface {$realif} {\n"; $dhcp6cconf .= " sla-id {$ifcfg['track6-prefix-id']};\n"; @@ -3509,10 +3813,14 @@ function interface_dhcpv6_configure($interface = "wan", $wancfg) { } // DHCP6 Config File Advanced - if ($wancfg['adv_dhcp6_config_advanced']) { $dhcp6cconf = DHCP6_Config_File_Advanced($interface, $wancfg, $wanif); } + if ($wancfg['adv_dhcp6_config_advanced']) { + $dhcp6cconf = DHCP6_Config_File_Advanced($interface, $wancfg, $wanif); + } // DHCP6 Config File Override - if ($wancfg['adv_dhcp6_config_file_override']) { $dhcp6cconf = DHCP6_Config_File_Override($wancfg, $wanif); } + if ($wancfg['adv_dhcp6_config_file_override']) { + $dhcp6cconf = DHCP6_Config_File_Override($wancfg, $wanif); + } /* wide-dhcp6c works for now. */ if (!@file_put_contents("{$g['varetc_path']}/dhcp6c_{$interface}.conf", $dhcp6cconf)) { @@ -3595,12 +3903,14 @@ function DHCP6_Config_File_Advanced($interface, $wancfg, $wanif) { } $information_only = ""; - if ($wancfg['adv_dhcp6_interface_statement_information_only_enable'] != '') + if ($wancfg['adv_dhcp6_interface_statement_information_only_enable'] != '') { $information_only = "\tinformation-only;\n"; + } $script = "\tscript \"{$g['varetc_path']}/dhcp6c_{$interface}_script.sh\";\n"; - if ($wancfg['adv_dhcp6_interface_statement_script'] != '') + if ($wancfg['adv_dhcp6_interface_statement_script'] != '') { $script = "\tscript \"{$wancfg['adv_dhcp6_interface_statement_script']}\";\n"; + } $interface_statement = "interface"; $interface_statement .= " {$wanif}"; @@ -3615,19 +3925,21 @@ function DHCP6_Config_File_Advanced($interface, $wancfg, $wanif) { if ($wancfg['adv_dhcp6_id_assoc_statement_address_enable'] != '') { $id_assoc_statement_address .= "id-assoc"; $id_assoc_statement_address .= " na"; - if (is_numeric($wancfg['adv_dhcp6_id_assoc_statement_address_id'])) + if (is_numeric($wancfg['adv_dhcp6_id_assoc_statement_address_id'])) { $id_assoc_statement_address .= " {$wancfg['adv_dhcp6_id_assoc_statement_address_id']}"; + } $id_assoc_statement_address .= " { "; - if ( ($wancfg['adv_dhcp6_id_assoc_statement_address'] != '') && - (is_numeric($wancfg['adv_dhcp6_id_assoc_statement_address_pltime']) || - ($wancfg['adv_dhcp6_id_assoc_statement_address_pltime'] == 'infinity')) ) { + if (($wancfg['adv_dhcp6_id_assoc_statement_address'] != '') && + (is_numeric($wancfg['adv_dhcp6_id_assoc_statement_address_pltime']) || + ($wancfg['adv_dhcp6_id_assoc_statement_address_pltime'] == 'infinity'))) { $id_assoc_statement_address .= "\n\taddress"; $id_assoc_statement_address .= " {$wancfg['adv_dhcp6_id_assoc_statement_address']}"; $id_assoc_statement_address .= " {$wancfg['adv_dhcp6_id_assoc_statement_address_pltime']}"; - if ( (is_numeric($wancfg['adv_dhcp6_id_assoc_statement_address_vltime'])) || - ($wancfg['adv_dhcp6_id_assoc_statement_address_vltime'] == 'infinity') ) + if ((is_numeric($wancfg['adv_dhcp6_id_assoc_statement_address_vltime'])) || + ($wancfg['adv_dhcp6_id_assoc_statement_address_vltime'] == 'infinity')) { $id_assoc_statement_address .= " {$wancfg['adv_dhcp6_id_assoc_statement_address_vltime']}"; + } $id_assoc_statement_address .= ";\n"; } @@ -3638,19 +3950,21 @@ function DHCP6_Config_File_Advanced($interface, $wancfg, $wanif) { if ($wancfg['adv_dhcp6_id_assoc_statement_prefix_enable'] != '') { $id_assoc_statement_prefix .= "id-assoc"; $id_assoc_statement_prefix .= " pd"; - if (is_numeric($wancfg['adv_dhcp6_id_assoc_statement_prefix_id'])) + if (is_numeric($wancfg['adv_dhcp6_id_assoc_statement_prefix_id'])) { $id_assoc_statement_prefix .= " {$wancfg['adv_dhcp6_id_assoc_statement_prefix_id']}"; + } $id_assoc_statement_prefix .= " { "; - if ( ($wancfg['adv_dhcp6_id_assoc_statement_prefix'] != '') && - (is_numeric($wancfg['adv_dhcp6_id_assoc_statement_prefix_pltime']) || - ($wancfg['adv_dhcp6_id_assoc_statement_prefix_pltime'] == 'infinity')) ) { + if (($wancfg['adv_dhcp6_id_assoc_statement_prefix'] != '') && + (is_numeric($wancfg['adv_dhcp6_id_assoc_statement_prefix_pltime']) || + ($wancfg['adv_dhcp6_id_assoc_statement_prefix_pltime'] == 'infinity')) ) { $id_assoc_statement_prefix .= "\n\tprefix"; $id_assoc_statement_prefix .= " {$wancfg['adv_dhcp6_id_assoc_statement_prefix']}"; $id_assoc_statement_prefix .= " {$wancfg['adv_dhcp6_id_assoc_statement_prefix_pltime']}"; - if ( (is_numeric($wancfg['adv_dhcp6_id_assoc_statement_prefix_vltime'])) || - ($wancfg['adv_dhcp6_id_assoc_statement_prefix_vltime'] == 'infinity') ) + if ((is_numeric($wancfg['adv_dhcp6_id_assoc_statement_prefix_vltime'])) || + ($wancfg['adv_dhcp6_id_assoc_statement_prefix_vltime'] == 'infinity')) { $id_assoc_statement_prefix .= " {$wancfg['adv_dhcp6_id_assoc_statement_prefix_vltime']}"; + } $id_assoc_statement_prefix .= ";"; } @@ -3659,14 +3973,15 @@ function DHCP6_Config_File_Advanced($interface, $wancfg, $wanif) { $id_assoc_statement_prefix .= " {$wanif}"; $id_assoc_statement_prefix .= " {\n"; $id_assoc_statement_prefix .= "\t\tsla-id {$wancfg['adv_dhcp6_prefix_interface_statement_sla_id']};\n"; - if ( ($wancfg['adv_dhcp6_prefix_interface_statement_sla_len'] >= 0) && - ($wancfg['adv_dhcp6_prefix_interface_statement_sla_len'] <= 128) ) + if (($wancfg['adv_dhcp6_prefix_interface_statement_sla_len'] >= 0) && + ($wancfg['adv_dhcp6_prefix_interface_statement_sla_len'] <= 128)) { $id_assoc_statement_prefix .= "\t\tsla-len {$wancfg['adv_dhcp6_prefix_interface_statement_sla_len']};\n"; + } $id_assoc_statement_prefix .= "\t};"; } - if ( ($wancfg['adv_dhcp6_id_assoc_statement_prefix'] != '') || - (is_numeric($wancfg['adv_dhcp6_prefix_interface_statement_sla_id'])) ) { + if (($wancfg['adv_dhcp6_id_assoc_statement_prefix'] != '') || + (is_numeric($wancfg['adv_dhcp6_prefix_interface_statement_sla_id'])) ) { $id_assoc_statement_prefix .= "\n"; } @@ -3674,32 +3989,35 @@ function DHCP6_Config_File_Advanced($interface, $wancfg, $wanif) { } $authentication_statement = ""; - if ( ($wancfg['adv_dhcp6_authentication_statement_authname'] != '') && - ($wancfg['adv_dhcp6_authentication_statement_protocol'] == 'delayed') ) { + if (($wancfg['adv_dhcp6_authentication_statement_authname'] != '') && + ($wancfg['adv_dhcp6_authentication_statement_protocol'] == 'delayed')) { $authentication_statement .= "authentication"; $authentication_statement .= " {$wancfg['adv_dhcp6_authentication_statement_authname']}"; $authentication_statement .= " {\n"; $authentication_statement .= "\tprotocol {$wancfg['adv_dhcp6_authentication_statement_protocol']};\n"; - if (preg_match("/(hmac(-)?md5)||(HMAC(-)?MD5)/", $wancfg['adv_dhcp6_authentication_statement_algorithm'])) + if (preg_match("/(hmac(-)?md5)||(HMAC(-)?MD5)/", $wancfg['adv_dhcp6_authentication_statement_algorithm'])) { $authentication_statement .= "\talgorithm {$wancfg['adv_dhcp6_authentication_statement_algorithm']};\n"; - if ($wancfg['adv_dhcp6_authentication_statement_rdm'] == 'monocounter') + } + if ($wancfg['adv_dhcp6_authentication_statement_rdm'] == 'monocounter') { $authentication_statement .= "\trdm {$wancfg['adv_dhcp6_authentication_statement_rdm']};\n"; + } $authentication_statement .= "};\n"; } $key_info_statement = ""; - if ( ($wancfg['adv_dhcp6_key_info_statement_keyname'] != '') && - ($wancfg['adv_dhcp6_key_info_statement_realm'] != '') && - (is_numeric($wancfg['adv_dhcp6_key_info_statement_keyid'])) && - ($wancfg['adv_dhcp6_key_info_statement_secret'] != '') ) { + if (($wancfg['adv_dhcp6_key_info_statement_keyname'] != '') && + ($wancfg['adv_dhcp6_key_info_statement_realm'] != '') && + (is_numeric($wancfg['adv_dhcp6_key_info_statement_keyid'])) && + ($wancfg['adv_dhcp6_key_info_statement_secret'] != '')) { $key_info_statement .= "keyinfo"; $key_info_statement .= " {$wancfg['adv_dhcp6_key_info_statement_keyname']}"; $key_info_statement .= " {\n"; $key_info_statement .= "\trealm \"{$wancfg['adv_dhcp6_key_info_statement_realm']}\";\n"; $key_info_statement .= "\tkeyid {$wancfg['adv_dhcp6_key_info_statement_keyid']};\n"; $key_info_statement .= "\tsecret \"{$wancfg['adv_dhcp6_key_info_statement_secret']}\";\n"; - if (preg_match("/((([0-9]{4}-)?[0-9]{2}[0-9]{2} )?[0-9]{2}:[0-9]{2})||(foreever)/", $wancfg['adv_dhcp6_key_info_statement_expire'])) + if (preg_match("/((([0-9]{4}-)?[0-9]{2}[0-9]{2} )?[0-9]{2}:[0-9]{2})||(foreever)/", $wancfg['adv_dhcp6_key_info_statement_expire'])) { $key_info_statement .= "\texpire \"{$wancfg['adv_dhcp6_key_info_statement_expire']}\";\n"; + } $key_info_statement .= "};\n"; } @@ -3737,8 +4055,9 @@ function interface_dhcp_configure($interface = "wan") { $wancfg = $config['interfaces'][$interface]; $wanif = $wancfg['if']; - if (empty($wancfg)) + if (empty($wancfg)) { $wancfg = array(); + } /* generate dhclient_wan.conf */ $fd = fopen("{$g['varetc_path']}/dhclient_{$interface}.conf", "w"); @@ -3771,12 +4090,12 @@ initial-interval 1; script "/sbin/dhclient-script"; EOD; -if (is_ipaddrv4($wancfg['dhcprejectfrom'])) { - $dhclientconf .= << $vip) { if ($vip['mode'] == "carp") { - if ($interface == "{$vip['interface']}_vip{$vip['vhid']}") - return $vip['interface']; + if ($interface == "{$vip['interface']}_vip{$vip['vhid']}") { + return $vip['interface']; + } } } } @@ -4028,26 +4364,31 @@ function convert_real_interface_to_friendly_interface_name($interface = "wan", $ //$ifdescrs = get_configured_interface_list(false, true); foreach ($ifdescrs as $if => $ifname) { - if ($if == $interface || $ifname['if'] == $interface) + if ($if == $interface || $ifname['if'] == $interface) { return $if; + } - if (get_real_interface($if) == $interface) + if (get_real_interface($if) == $interface) { return $if; + } - if ($checkparent == false) + if ($checkparent == false) { continue; + } $int = get_parent_interface($if, true); if (is_array($int)) { foreach ($int as $iface) { - if ($iface == $interface) + if ($iface == $interface) { return $if; + } } } } - if ($interface == "enc0") + if ($interface == "enc0") { return 'IPsec'; + } } /* attempt to resolve interface to friendly descr */ @@ -4055,50 +4396,53 @@ function convert_friendly_interface_to_friendly_descr($interface) { global $config; switch ($interface) { - case "l2tp": - $ifdesc = "L2TP"; - break; - case "pptp": - $ifdesc = "PPTP"; - break; - case "pppoe": - $ifdesc = "PPPoE"; - break; - case "openvpn": - $ifdesc = "OpenVPN"; - break; - case "enc0": - case "ipsec": - case "IPsec": - $ifdesc = "IPsec"; - break; - default: - if (isset($config['interfaces'][$interface])) { - if (empty($config['interfaces'][$interface]['descr'])) - $ifdesc = strtoupper($interface); - else - $ifdesc = strtoupper($config['interfaces'][$interface]['descr']); + case "l2tp": + $ifdesc = "L2TP"; break; - } else if (substr($interface, 0, 4) == '_vip') { - if (is_array($config['virtualip']['vip'])) { - foreach ($config['virtualip']['vip'] as $counter => $vip) { - if ($vip['mode'] == "carp") { - if ($interface == "{$vip['interface']}_vip{$vip['vhid']}") - return "{$vip['subnet']} - {$vip['descr']}"; + case "pptp": + $ifdesc = "PPTP"; + break; + case "pppoe": + $ifdesc = "PPPoE"; + break; + case "openvpn": + $ifdesc = "OpenVPN"; + break; + case "enc0": + case "ipsec": + case "IPsec": + $ifdesc = "IPsec"; + break; + default: + if (isset($config['interfaces'][$interface])) { + if (empty($config['interfaces'][$interface]['descr'])) { + $ifdesc = strtoupper($interface); + } else { + $ifdesc = strtoupper($config['interfaces'][$interface]['descr']); + } + break; + } else if (substr($interface, 0, 4) == '_vip') { + if (is_array($config['virtualip']['vip'])) { + foreach ($config['virtualip']['vip'] as $counter => $vip) { + if ($vip['mode'] == "carp") { + if ($interface == "{$vip['interface']}_vip{$vip['vhid']}") { + return "{$vip['subnet']} - {$vip['descr']}"; + } + } + } + } + } else if (substr($interface, 0, 5) == '_lloc') { + return get_interface_linklocal($interface); + } else { + /* if list */ + $ifdescrs = get_configured_interface_with_descr(false, true); + foreach ($ifdescrs as $if => $ifname) { + if ($if == $interface || $ifname == $interface) { + return $ifname; } } } - } else if (substr($interface, 0, 5) == '_lloc') { - return get_interface_linklocal($interface); - } else { - /* if list */ - $ifdescrs = get_configured_interface_with_descr(false, true); - foreach ($ifdescrs as $if => $ifname) { - if ($if == $interface || $ifname == $interface) - return $ifname; - } - } - break; + break; } return $ifdesc; @@ -4108,8 +4452,9 @@ function convert_real_interface_to_friendly_descr($interface) { $ifdesc = convert_real_interface_to_friendly_interface_name("{$interface}"); - if (!empty($ifdesc)) + if (!empty($ifdesc)) { return convert_friendly_interface_to_friendly_descr($ifdesc); + } return $interface; } @@ -4129,12 +4474,14 @@ function get_parent_interface($interface, $avoidrecurse = false) { $parents = array(); //Check that we got a valid interface passed $realif = get_real_interface($interface); - if ($realif == NULL) + if ($realif == NULL) { return $parents; + } // If we got a real interface, find it's friendly assigned name - if ($interface == $realif && $avoidrecurse == false) + if ($interface == $realif && $avoidrecurse == false) { $interface = convert_real_interface_to_friendly_interface_name($interface); + } if (!empty($interface) && isset($config['interfaces'][$interface])) { $ifcfg = $config['interfaces'][$interface]; @@ -4143,16 +4490,19 @@ function get_parent_interface($interface, $avoidrecurse = false) { case "pppoe": case "pptp": case "l2tp": - if (empty($parents)) - if (is_array($config['ppps']['ppp'])) + if (empty($parents)) { + if (is_array($config['ppps']['ppp'])) { foreach ($config['ppps']['ppp'] as $pppidx => $ppp) { if ($ifcfg['if'] == $ppp['if']) { $ports = explode(',', $ppp['ports']); - foreach ($ports as $pid => $parent_if) + foreach ($ports as $pid => $parent_if) { $parents[$pid] = get_real_interface($parent_if); + } break; } } + } + } break; case "dhcp": case "static": @@ -4172,14 +4522,15 @@ function get_parent_interface($interface, $avoidrecurse = false) { } } - if (empty($parents)) + if (empty($parents)) { $parents[0] = $realif; + } return $parents; } function interface_is_wireless_clone($wlif) { - if(!stristr($wlif, "_wlan")) { + if (!stristr($wlif, "_wlan")) { return false; } else { return true; @@ -4187,7 +4538,7 @@ function interface_is_wireless_clone($wlif) { } function interface_get_wireless_base($wlif) { - if(!stristr($wlif, "_wlan")) { + if (!stristr($wlif, "_wlan")) { return $wlif; } else { return substr($wlif, 0, stripos($wlif, "_wlan")); @@ -4195,7 +4546,7 @@ function interface_get_wireless_base($wlif) { } function interface_get_wireless_clone($wlif) { - if(!stristr($wlif, "_wlan")) { + if (!stristr($wlif, "_wlan")) { return $wlif . "_wlan0"; } else { return $wlif; @@ -4208,99 +4559,105 @@ function get_real_interface($interface = "wan", $family = "all", $realv6iface = $wanif = NULL; switch ($interface) { - case "l2tp": - $wanif = "l2tp"; - break; - case "pptp": - $wanif = "pptp"; - break; - case "pppoe": - $wanif = "pppoe"; - break; - case "openvpn": - $wanif = "openvpn"; - break; - case "ipsec": - case "enc0": - $wanif = "enc0"; - break; - case "ppp": - $wanif = "ppp"; - break; - default: - if (substr($interface, 0, 4) == '_vip') { - $wanif = get_configured_carp_interface_list($interface, '', 'iface'); - if (!empty($wanif)) - $wanif = get_real_interface($wanif, $family); + case "l2tp": + $wanif = "l2tp"; break; - } else if (substr($interface, 0, 5) == '_lloc') { - $interface = substr($interface, 5); - } else if (does_interface_exist($interface, $flush)) { - /* - * If a real interface was already passed simply - * pass the real interface back. This encourages - * the usage of this function in more cases so that - * we can combine logic for more flexibility. - */ - $wanif = $interface; + case "pptp": + $wanif = "pptp"; break; - } - - if (empty($config['interfaces'][$interface])) + case "pppoe": + $wanif = "pppoe"; break; - - $cfg = &$config['interfaces'][$interface]; - - if ($family == "inet6") { - switch ($cfg['ipaddrv6']) { - case "6rd": - case "6to4": - $wanif = "{$interface}_stf"; - break; - case 'pppoe': - case 'ppp': - case 'l2tp': - case 'pptp': - if( is_array($cfg['wireless']) || preg_match($g['wireless_regex'], $cfg['if'])) - $wanif = interface_get_wireless_clone($cfg['if']); - else - $wanif = $cfg['if']; - break; - default: - switch ($cfg['ipaddr']) { - case 'pppoe': - case 'ppp': - case 'l2tp': - case 'pptp': - if (isset($cfg['dhcp6usev4iface']) && $realv6iface === false) - $wanif = $cfg['if']; - else { - $parents = get_parent_interface($interface); - if (!empty($parents[0])) - $wanif = $parents[0]; - else - $wanif = $cfg['if']; - } - break; - default: - if( is_array($cfg['wireless']) || preg_match($g['wireless_regex'], $cfg['if'])) - $wanif = interface_get_wireless_clone($cfg['if']); - else - $wanif = $cfg['if']; - break; + case "openvpn": + $wanif = "openvpn"; + break; + case "ipsec": + case "enc0": + $wanif = "enc0"; + break; + case "ppp": + $wanif = "ppp"; + break; + default: + if (substr($interface, 0, 4) == '_vip') { + $wanif = get_configured_carp_interface_list($interface, '', 'iface'); + if (!empty($wanif)) { + $wanif = get_real_interface($wanif, $family); } break; + } else if (substr($interface, 0, 5) == '_lloc') { + $interface = substr($interface, 5); + } else if (does_interface_exist($interface, $flush)) { + /* + * If a real interface was already passed simply + * pass the real interface back. This encourages + * the usage of this function in more cases so that + * we can combine logic for more flexibility. + */ + $wanif = $interface; + break; } - } else { - // Wireless cloned NIC support (FreeBSD 8+) - // interface name format: $parentnic_wlanparentnic# - // example: ath0_wlan0 - if( is_array($cfg['wireless']) || preg_match($g['wireless_regex'], $cfg['if'])) - $wanif = interface_get_wireless_clone($cfg['if']); - else - $wanif = $cfg['if']; - } - break; + + if (empty($config['interfaces'][$interface])) { + break; + } + + $cfg = &$config['interfaces'][$interface]; + + if ($family == "inet6") { + switch ($cfg['ipaddrv6']) { + case "6rd": + case "6to4": + $wanif = "{$interface}_stf"; + break; + case 'pppoe': + case 'ppp': + case 'l2tp': + case 'pptp': + if ( is_array($cfg['wireless']) || preg_match($g['wireless_regex'], $cfg['if'])) { + $wanif = interface_get_wireless_clone($cfg['if']); + } else { + $wanif = $cfg['if']; + } + break; + default: + switch ($cfg['ipaddr']) { + case 'pppoe': + case 'ppp': + case 'l2tp': + case 'pptp': + if (isset($cfg['dhcp6usev4iface']) && $realv6iface === false) { + $wanif = $cfg['if']; + } else { + $parents = get_parent_interface($interface); + if (!empty($parents[0])) { + $wanif = $parents[0]; + } else { + $wanif = $cfg['if']; + } + } + break; + default: + if (is_array($cfg['wireless']) || preg_match($g['wireless_regex'], $cfg['if'])) { + $wanif = interface_get_wireless_clone($cfg['if']); + } else { + $wanif = $cfg['if']; + } + break; + } + break; + } + } else { + // Wireless cloned NIC support (FreeBSD 8+) + // interface name format: $parentnic_wlanparentnic# + // example: ath0_wlan0 + if ( is_array($cfg['wireless']) || preg_match($g['wireless_regex'], $cfg['if'])) { + $wanif = interface_get_wireless_clone($cfg['if']); + } else { + $wanif = $cfg['if']; + } + } + break; } return $wanif; @@ -4310,20 +4667,24 @@ function get_real_interface($interface = "wan", $family = "all", $realv6iface = function guess_interface_from_ip($ipaddress) { $family = ''; - if(is_ipaddrv4($ipaddress)) + if (is_ipaddrv4($ipaddress)) { $family = 'inet'; - if (empty($family) && is_ipaddrv6($ipaddress)) + } + if (empty($family) && is_ipaddrv6($ipaddress)) { $family = 'inet6'; + } - if (empty($family)) + if (empty($family)) { return false; + } /* create a route table we can search */ $output = ''; $_gb = exec("/sbin/route -n get -{$family} " . escapeshellarg($ipaddress) . " | /usr/bin/awk '/interface/ { print \$2; };'", $output); $output[0] = trim($output[0], " \n"); - if (!empty($output[0])) + if (!empty($output[0])) { return $output[0]; + } return false; } @@ -4333,8 +4694,9 @@ function guess_interface_from_ip($ipaddress) { * (or if $bits is specified, where an IP within the subnet is defined) */ function find_ip_interface($ip, $bits = null) { - if (!is_ipaddr($ip)) + if (!is_ipaddr($ip)) { return false; + } $isv6ip = is_ipaddrv6($ip); @@ -4343,15 +4705,15 @@ function find_ip_interface($ip, $bits = null) { foreach ($ifdescrs as $ifdescr => $ifname) { $ifip = ($isv6ip) ? get_interface_ipv6($ifname) : get_interface_ip($ifname); - if (is_null($ifip)) + if (is_null($ifip)) { continue; + } if (is_null($bits)) { if ($ip == $ifip) { $int = get_real_interface($ifname); return $int; } - } - else { + } else { if (ip_in_subnet($ifip, $ip . "/" . $bits)) { $int = get_real_interface($ifname); return $int; @@ -4372,23 +4734,24 @@ function find_virtual_ip_alias($ip, $bits = null) { if (!is_array($config['virtualip']['vip'])) { return false; } - if (!is_ipaddr($ip)) + if (!is_ipaddr($ip)) { return false; + } $isv6ip = is_ipaddrv6($ip); foreach ($config['virtualip']['vip'] as $vip) { if ($vip['mode'] === "ipalias") { - if (is_ipaddrv6($vip['subnet']) != $isv6ip) + if (is_ipaddrv6($vip['subnet']) != $isv6ip) { continue; + } if (is_null($bits)) { if (ip_in_subnet($ip, $vip['subnet'] . "/" . $vip['subnet_bits'])) { return $vip; } - } - else { - if (($isv6ip && check_subnetsv6_overlap($ip, $bits, $vip['subnet'], $vip['subnet_bits'])) - || (!$isv6ip && check_subnets_overlap($ip, $bits, $vip['subnet'], $vip['subnet_bits']))) { + } else { + if (($isv6ip && check_subnetsv6_overlap($ip, $bits, $vip['subnet'], $vip['subnet_bits'])) || + (!$isv6ip && check_subnets_overlap($ip, $bits, $vip['subnet'], $vip['subnet_bits']))) { return $vip; } } @@ -4412,25 +4775,27 @@ function find_carp_interface($ip) { if (is_array($config['virtualip']['vip'])) { foreach ($config['virtualip']['vip'] as $vip) { if ($vip['mode'] == "carp") { - if(is_ipaddrv4($ip)) { + if (is_ipaddrv4($ip)) { $carp_ip = get_interface_ip($vip['interface']); } - if(is_ipaddrv6($ip)) { + if (is_ipaddrv6($ip)) { $carp_ip = get_interface_ipv6($vip['interface']); } exec("/sbin/ifconfig", $output, $return); - foreach($output as $line) { + foreach ($output as $line) { $elements = preg_split("/[ ]+/i", $line); - if(strstr($elements[0], "vip")) + if (strstr($elements[0], "vip")) { $curif = str_replace(":", "", $elements[0]); - if(stristr($line, $ip)) { + } + if (stristr($line, $ip)) { $if = $curif; continue; } } - if ($if) + if ($if) { return $if; + } } } } @@ -4439,32 +4804,36 @@ function find_carp_interface($ip) { function link_carp_interface_to_parent($interface) { global $config; - if (empty($interface)) + if (empty($interface)) { return; + } $carp_ip = get_interface_ip($interface); $carp_ipv6 = get_interface_ipv6($interface); - if((!is_ipaddrv4($carp_ip)) && (!is_ipaddrv6($carp_ipv6))) + if ((!is_ipaddrv4($carp_ip)) && (!is_ipaddrv6($carp_ipv6))) { return; + } /* if list */ $ifdescrs = get_configured_interface_list(); foreach ($ifdescrs as $ifdescr => $ifname) { /* check IPv4 */ - if(is_ipaddrv4($carp_ip)) { + if (is_ipaddrv4($carp_ip)) { $interfaceip = get_interface_ip($ifname); $subnet_bits = get_interface_subnet($ifname); $subnet_ip = gen_subnet("{$interfaceip}", "{$subnet_bits}"); - if(ip_in_subnet($carp_ip, "{$subnet_ip}/{$subnet_bits}")) + if (ip_in_subnet($carp_ip, "{$subnet_ip}/{$subnet_bits}")) { return $ifname; + } } /* Check IPv6 */ - if(is_ipaddrv6($carp_ipv6)) { + if (is_ipaddrv6($carp_ipv6)) { $interfaceipv6 = get_interface_ipv6($ifname); $prefixlen = get_interface_subnetv6($ifname); - if(ip_in_subnet($carp_ipv6, "{$interfaceipv6}/{$prefixlen}")) + if (ip_in_subnet($carp_ipv6, "{$interfaceipv6}/{$prefixlen}")) { return $ifname; + } } } return ""; @@ -4482,8 +4851,9 @@ function link_carp_interface_to_parent($interface) { function link_ip_to_carp_interface($ip) { global $config; - if (!is_ipaddr($ip)) + if (!is_ipaddr($ip)) { return; + } $carp_ints = ""; if (is_array($config['virtualip']['vip'])) { @@ -4499,8 +4869,9 @@ function link_ip_to_carp_interface($ip) { } } } - if (!empty($carp_int)) + if (!empty($carp_int)) { $carp_ints = implode(" ", array_unique($carp_int)); + } } return $carp_ints; @@ -4509,19 +4880,22 @@ function link_ip_to_carp_interface($ip) { function link_interface_to_track6($int, $action = "") { global $config; - if (empty($int)) + if (empty($int)) { return; + } if (is_array($config['interfaces'])) { $list = array(); foreach ($config['interfaces'] as $ifname => $ifcfg) { - if (!isset($ifcfg['enable'])) + if (!isset($ifcfg['enable'])) { continue; + } if (!empty($ifcfg['ipaddrv6']) && $ifcfg['track6-interface'] == $int) { - if ($action == "update") + if ($action == "update") { interface_track6_configure($ifname, $ifcfg); - else if ($action == "") + } else if ($action == "") { $list[$ifname] = $ifcfg; + } } } return $list; @@ -4546,40 +4920,47 @@ function interface_find_child_cfgmtu($realiface) { if (is_array($vlans)) { foreach ($vlans as $vlan) { $ifass = convert_real_interface_to_friendly_interface_name($vlan['vlanif']); - if (empty($ifass)) + if (empty($ifass)) { continue; + } if (!empty($config['interfaces'][$ifass]['mtu'])) { - if (intval($config['interfaces'][$ifass]['mtu']) > $mtu) + if (intval($config['interfaces'][$ifass]['mtu']) > $mtu) { $mtu = intval($config['interfaces'][$ifass]['mtu']); + } } } } if (is_array($gifs)) { foreach ($gifs as $vlan) { $ifass = convert_real_interface_to_friendly_interface_name($vlan['gifif']); - if (empty($ifass)) + if (empty($ifass)) { continue; + } if (!empty($config['interfaces'][$ifass]['mtu'])) { - if (intval($config['interfaces'][$ifass]['mtu']) > $mtu) + if (intval($config['interfaces'][$ifass]['mtu']) > $mtu) { $mtu = intval($config['interfaces'][$ifass]['mtu']); + } } } } if (is_array($gres)) { foreach ($gres as $vlan) { $ifass = convert_real_interface_to_friendly_interface_name($vlan['greif']); - if (empty($ifass)) + if (empty($ifass)) { continue; + } if (!empty($config['interfaces'][$ifass]['mtu'])) { - if (intval($config['interfaces'][$ifass]['mtu']) > $mtu) + if (intval($config['interfaces'][$ifass]['mtu']) > $mtu) { $mtu = intval($config['interfaces'][$ifass]['mtu']); + } } } } $ifass = convert_real_interface_to_friendly_interface_name($bridge); if (!empty($ifass) && !empty($config['interfaces'][$ifass]['mtu'])) { - if (intval($config['interfaces'][$ifass]['mtu']) > $mtu) + if (intval($config['interfaces'][$ifass]['mtu']) > $mtu) { $mtu = intval($config['interfaces'][$ifass]['mtu']); + } } unset($vlans, $bridge, $gifs, $gres, $ifass, $vlan); @@ -4589,8 +4970,9 @@ function interface_find_child_cfgmtu($realiface) { function link_interface_to_vlans($int, $action = "") { global $config; - if (empty($int)) + if (empty($int)) { return; + } if (is_array($config['vlans']['vlan'])) { $ifaces = array(); @@ -4598,12 +4980,14 @@ function link_interface_to_vlans($int, $action = "") { if ($int == $vlan['if']) { if ($action == "update") { interfaces_bring_up($int); - } else + } else { $ifaces[$vlan['tag']] = $vlan; + } } } - if (!empty($ifaces)) + if (!empty($ifaces)) { return $ifaces; + } } } @@ -4614,11 +4998,12 @@ function link_interface_to_vips($int, $action = "", $vhid = '') { $result = array(); foreach ($config['virtualip']['vip'] as $vip) { if ($int == $vip['interface']) { - if ($action == "update") + if ($action == "update") { interfaces_vips_configure($int); - else { - if (empty($vhid) || ($vhid == $vip['vhid'])) + } else { + if (empty($vhid) || ($vhid == $vip['vhid'])) { $result[] = $vip; + } } } } @@ -4639,8 +5024,9 @@ function link_interface_to_bridge($int) { if (is_array($config['bridges']['bridged'])) { foreach ($config['bridges']['bridged'] as $bridge) { - if (in_array($int, explode(',', $bridge['members']))) + if (in_array($int, explode(',', $bridge['members']))) { return "{$bridge['bridgeif']}"; + } } } } @@ -4652,8 +5038,9 @@ function link_interface_to_group($int) { if (is_array($config['ifgroups']['ifgroupentry'])) { foreach ($config['ifgroups']['ifgroupentry'] as $group) { - if (in_array($int, explode(" ", $group['members']))) + if (in_array($int, explode(" ", $group['members']))) { $result[$group['ifname']] = $int; + } } } @@ -4666,9 +5053,11 @@ function link_interface_to_gre($interface) { $result = array(); if (is_array($config['gres']['gre'])) { - foreach ($config['gres']['gre'] as $gre) - if($gre['if'] == $interface) + foreach ($config['gres']['gre'] as $gre) { + if ($gre['if'] == $interface) { $result[] = $gre; + } + } } return $result; @@ -4680,9 +5069,11 @@ function link_interface_to_gif($interface) { $result = array(); if (is_array($config['gifs']['gif'])) { - foreach ($config['gifs']['gif'] as $gif) - if($gif['if'] == $interface) + foreach ($config['gifs']['gif'] as $gif) { + if ($gif['if'] == $interface) { $result[] = $gif; + } + } } return $result; @@ -4697,8 +5088,9 @@ function find_interface_ip($interface, $flush = false) { $interface = str_replace("\n", "", $interface); - if (!does_interface_exist($interface)) + if (!does_interface_exist($interface)) { return; + } /* Setup IP cache */ if (!isset($interface_ip_arr_cache[$interface]) or $flush) { @@ -4721,8 +5113,9 @@ function find_interface_ipv6($interface, $flush = false) { $interface = trim($interface); $interface = get_real_interface($interface); - if (!does_interface_exist($interface)) + if (!does_interface_exist($interface)) { return; + } /* Setup IP cache */ if (!isset($interface_ipv6_arr_cache[$interface]) or $flush) { @@ -4743,16 +5136,17 @@ function find_interface_ipv6_ll($interface, $flush = false) { $interface = str_replace("\n", "", $interface); - if (!does_interface_exist($interface)) + if (!does_interface_exist($interface)) { return; + } /* Setup IP cache */ if (!isset($interface_llv6_arr_cache[$interface]) or $flush) { $ifinfo = pfSense_getall_interface_addresses($interface); - foreach($ifinfo as $line) { + foreach ($ifinfo as $line) { if (strstr($line, ":")) { $parts = explode("/", $line); - if(is_linklocal($parts[0])) { + if (is_linklocal($parts[0])) { $ifinfo['linklocal'] = $parts[0]; } } @@ -4767,8 +5161,9 @@ function find_interface_subnet($interface, $flush = false) { global $interface_ip_arr_cache; $interface = str_replace("\n", "", $interface); - if (does_interface_exist($interface) == false) + if (does_interface_exist($interface) == false) { return; + } if (!isset($interface_sn_arr_cache[$interface]) or $flush) { $ifinfo = pfSense_get_interface_addresses($interface); @@ -4784,8 +5179,9 @@ function find_interface_subnetv6($interface, $flush = false) { global $interface_ipv6_arr_cache; $interface = str_replace("\n", "", $interface); - if (does_interface_exist($interface) == false) + if (does_interface_exist($interface) == false) { return; + } if (!isset($interface_snv6_arr_cache[$interface]) or $flush) { $ifinfo = pfSense_get_interface_addresses($interface); @@ -4799,18 +5195,21 @@ function find_interface_subnetv6($interface, $flush = false) { function ip_in_interface_alias_subnet($interface, $ipalias) { global $config; - if (empty($interface) || !is_ipaddr($ipalias)) + if (empty($interface) || !is_ipaddr($ipalias)) { return false; + } if (is_array($config['virtualip']['vip'])) { foreach ($config['virtualip']['vip'] as $vip) { switch ($vip['mode']) { - case "ipalias": - if ($vip['interface'] <> $interface) + case "ipalias": + if ($vip['interface'] <> $interface) { + break; + } + $subnet = is_ipaddrv6($ipalias) ? gen_subnetv6($vip['subnet'], $vip['subnet_bits']) : gen_subnet($vip['subnet'], $vip['subnet_bits']); + if (ip_in_subnet($ipalias, $subnet . "/" . $vip['subnet_bits'])) { + return true; + } break; - $subnet = is_ipaddrv6($ipalias) ? gen_subnetv6($vip['subnet'], $vip['subnet_bits']) : gen_subnet($vip['subnet'], $vip['subnet_bits']); - if (ip_in_subnet($ipalias, $subnet . "/" . $vip['subnet_bits'])) - return true; - break; } } } @@ -4824,8 +5223,9 @@ function get_possible_listen_ips($include_ipv6_link_local=false) { foreach ($interfaces as $iface => $ifacename) { if ($include_ipv6_link_local) { /* This is to avoid going though added ll below */ - if (substr($iface, 0, 5) == '_lloc') + if (substr($iface, 0, 5) == '_lloc') { continue; + } $llip = find_interface_ipv6_ll(get_real_interface($iface)); if (!empty($llip)) { $interfaces["_lloc{$iface}"] = "{$ifacename} IPv6 Link-Local"; @@ -4834,17 +5234,19 @@ function get_possible_listen_ips($include_ipv6_link_local=false) { } /* XXX: Maybe use array_merge below? */ $carplist = get_configured_carp_interface_list(); - foreach ($carplist as $cif => $carpip) + foreach ($carplist as $cif => $carpip) { $interfaces[$cif] = $carpip . ' (' . get_vip_descr($carpip) . ')'; + } $aliaslist = get_configured_ip_aliases_list(); - foreach ($aliaslist as $aliasip => $aliasif) + foreach ($aliaslist as $aliasip => $aliasif) { $interfaces[$aliasip] = $aliasip . ' (' . get_vip_descr($aliasip) . ')'; + } $interfaces['lo0'] = 'Localhost'; return $interfaces; } - + function get_possible_traffic_source_addresses($include_ipv6_link_local=false) { global $config; @@ -4865,33 +5267,37 @@ function get_possible_traffic_source_addresses($include_ipv6_link_local=false) { } function get_interface_ip($interface = "wan") { - - $realif = get_failover_interface($interface); - if (!$realif) - return null; - if (substr($realif, 0, 4) == '_vip') + $realif = get_failover_interface($interface); + if (!$realif) { + return null; + } + + if (substr($realif, 0, 4) == '_vip') { return get_configured_carp_interface_list($realif, 'inet', 'ip'); + } $curip = find_interface_ip($realif); - if ($curip && is_ipaddr($curip) && ($curip != "0.0.0.0")) + if ($curip && is_ipaddr($curip) && ($curip != "0.0.0.0")) { return $curip; - else + } else { return null; + } } function get_interface_ipv6($interface = "wan", $flush = false) { global $config; $realif = get_failover_interface($interface, 'inet6'); - if (!$realif) + if (!$realif) { return null; + } - if (substr($realif, 0, 4) == '_vip') + if (substr($realif, 0, 4) == '_vip') { return get_configured_carp_interface_list($realif, 'inet6', 'ip'); - else if (substr($realif, 0, 5) == '_lloc') + } else if (substr($realif, 0, 5) == '_lloc') { return get_interface_linklocal($interface); - + } /* * NOTE: On the case when only the prefix is requested, @@ -4899,76 +5305,88 @@ function get_interface_ipv6($interface = "wan", $flush = false) { */ if (is_array($config['interfaces'][$interface])) { switch ($config['interfaces'][$interface]['ipaddr']) { - case 'pppoe': - case 'l2tp': - case 'pptp': - case 'ppp': - if ($config['interfaces'][$interface]['ipaddrv6'] == 'dhcp6') - $realif = get_real_interface($interface, 'inet6', true); - break; + case 'pppoe': + case 'l2tp': + case 'pptp': + case 'ppp': + if ($config['interfaces'][$interface]['ipaddrv6'] == 'dhcp6') { + $realif = get_real_interface($interface, 'inet6', true); + } + break; } if (isset($config['interfaces'][$interface]['dhcp6prefixonly'])) { $curip = find_interface_ipv6_ll($realif, $flush); - if ($curip && is_ipaddrv6($curip) && ($curip != "::")) + if ($curip && is_ipaddrv6($curip) && ($curip != "::")) { return $curip; + } } } $curip = find_interface_ipv6($realif, $flush); - if ($curip && is_ipaddrv6($curip) && ($curip != "::")) + if ($curip && is_ipaddrv6($curip) && ($curip != "::")) { return $curip; - else + } else { return null; + } } function get_interface_linklocal($interface = "wan") { $realif = get_failover_interface($interface, 'inet6'); - if (!$realif) + if (!$realif) { return null; + } - if (substr($interface, 0, 4) == '_vip') + if (substr($interface, 0, 4) == '_vip') { $realif = get_real_interface($interface); - else if (substr($interface, 0, 5) == '_lloc') + } else if (substr($interface, 0, 5) == '_lloc') { $realif = get_real_interface(substr($interface, 5)); + } $curip = find_interface_ipv6_ll($realif); - if ($curip && is_ipaddrv6($curip) && ($curip != "::")) + if ($curip && is_ipaddrv6($curip) && ($curip != "::")) { return $curip; - else + } else { return null; + } } function get_interface_subnet($interface = "wan") { - if (substr($interface, 0, 4) == '_vip') + if (substr($interface, 0, 4) == '_vip') { return get_configured_carp_interface_list($interface, 'inet', 'subnet'); + } $realif = get_real_interface($interface); - if (!$realif) + if (!$realif) { return null; + } $cursn = find_interface_subnet($realif); - if (!empty($cursn)) + if (!empty($cursn)) { return $cursn; + } return null; } function get_interface_subnetv6($interface = "wan") { - if (substr($interface, 0, 4) == '_vip') + if (substr($interface, 0, 4) == '_vip') { return get_configured_carp_interface_list($interface, 'inet6', 'subnet'); - else if (substr($interface, 0, 5) == '_lloc') + } else if (substr($interface, 0, 5) == '_lloc') { $interface = substr($interface, 5); + } $realif = get_real_interface($interface, 'inet6'); - if (!$realif) + if (!$realif) { return null; + } $cursn = find_interface_subnetv6($realif); - if (!empty($cursn)) + if (!empty($cursn)) { return $cursn; + } return null; } @@ -4980,7 +5398,7 @@ function get_interfaces_with_gateway() { $ints = array(); /* loop interfaces, check config for outbound */ - foreach($config['interfaces'] as $ifdescr => $ifname) { + foreach ($config['interfaces'] as $ifdescr => $ifname) { switch ($ifname['ipaddr']) { case "dhcp": case "ppp"; @@ -4989,12 +5407,13 @@ function get_interfaces_with_gateway() { case "l2tp": case "ppp"; $ints[$ifdescr] = $ifdescr; - break; + break; default: if (substr($ifname['if'], 0, 4) == "ovpn" || - !empty($ifname['gateway'])) + !empty($ifname['gateway'])) { $ints[$ifdescr] = $ifdescr; - break; + } + break; } } return $ints; @@ -5015,13 +5434,16 @@ function interface_has_gateway($friendly) { return true; break; default: - if (substr($ifname['if'], 0, 4) == "ovpn") + if (substr($ifname['if'], 0, 4) == "ovpn") { return true; + } $tunnelif = substr($ifname['if'], 0, 3); - if ($tunnelif == "gif" || $tunnelif == "gre") + if ($tunnelif == "gif" || $tunnelif == "gre") { return true; - if (!empty($ifname['gateway'])) + } + if (!empty($ifname['gateway'])) { return true; + } break; } } @@ -5043,13 +5465,16 @@ function interface_has_gatewayv6($friendly) { return true; break; default: - if (substr($ifname['if'], 0, 4) == "ovpn") + if (substr($ifname['if'], 0, 4) == "ovpn") { return true; + } $tunnelif = substr($ifname['if'], 0, 3); - if ($tunnelif == "gif" || $tunnelif == "gre") + if ($tunnelif == "gif" || $tunnelif == "gre") { return true; - if (!empty($ifname['gatewayv6'])) + } + if (!empty($ifname['gatewayv6'])) { return true; + } break; } } @@ -5081,16 +5506,17 @@ function is_altq_capable($int) { $int_family = remove_ifindex($int); - if (in_array($int_family, $capable)) + if (in_array($int_family, $capable)) { return true; - else if (stristr($int, "l2tp")) /* VLANs are name $parent_$vlan now */ + } else if (stristr($int, "l2tp")) { /* VLANs are named $parent_$vlan now */ return true; - else if (stristr($int, "_vlan")) /* VLANs are name $parent_$vlan now */ + } else if (stristr($int, "_vlan")) { /* VLANs are named $parent_$vlan now */ return true; - else if (stristr($int, "_wlan")) /* WLANs are name $parent_$wlan now */ + } else if (stristr($int, "_wlan")) { /* WLANs are named $parent_$wlan now */ return true; - else + } else { return false; + } } /****f* interfaces/is_interface_wireless @@ -5103,15 +5529,17 @@ function is_interface_wireless($interface) { global $config, $g; $friendly = convert_real_interface_to_friendly_interface_name($interface); - if(!isset($config['interfaces'][$friendly]['wireless'])) { + if (!isset($config['interfaces'][$friendly]['wireless'])) { if (preg_match($g['wireless_regex'], $interface)) { - if (isset($config['interfaces'][$friendly])) + if (isset($config['interfaces'][$friendly])) { $config['interfaces'][$friendly]['wireless'] = array(); + } return true; } return false; - } else + } else { return true; + } } function get_wireless_modes($interface) { @@ -5120,7 +5548,7 @@ function get_wireless_modes($interface) { $cloned_interface = get_real_interface($interface); - if($cloned_interface && is_interface_wireless($cloned_interface)) { + if ($cloned_interface && is_interface_wireless($cloned_interface)) { $chan_list = "/sbin/ifconfig {$cloned_interface} list chan"; $stack_list = "/usr/bin/awk -F\"Channel \" '{ gsub(/\\*/, \" \"); print \$2 \"\\\n\" \$3 }'"; $format_list = "/usr/bin/awk '{print \$5 \" \" \$6 \",\" \$1}'"; @@ -5134,20 +5562,24 @@ function get_wireless_modes($interface) { $channel_line = explode(",", $interface_channels["$c"]); $wireless_mode = trim($channel_line[0]); $wireless_channel = trim($channel_line[1]); - if(trim($wireless_mode) != "") { + if (trim($wireless_mode) != "") { /* if we only have 11g also set 11b channels */ - if($wireless_mode == "11g") { - if(!isset($wireless_modes["11b"])) + if ($wireless_mode == "11g") { + if (!isset($wireless_modes["11b"])) { $wireless_modes["11b"] = array(); - } else if($wireless_mode == "11g ht") { - if(!isset($wireless_modes["11b"])) + } + } else if ($wireless_mode == "11g ht") { + if (!isset($wireless_modes["11b"])) { $wireless_modes["11b"] = array(); - if(!isset($wireless_modes["11g"])) + } + if (!isset($wireless_modes["11g"])) { $wireless_modes["11g"] = array(); + } $wireless_mode = "11ng"; - } else if($wireless_mode == "11a ht") { - if(!isset($wireless_modes["11a"])) + } else if ($wireless_mode == "11a ht") { + if (!isset($wireless_modes["11a"])) { $wireless_modes["11a"] = array(); + } $wireless_mode = "11na"; } $wireless_modes["$wireless_mode"]["$c"] = $wireless_channel; @@ -5164,7 +5596,7 @@ function get_wireless_channel_info($interface) { $cloned_interface = get_real_interface($interface); - if($cloned_interface && is_interface_wireless($cloned_interface)) { + if ($cloned_interface && is_interface_wireless($cloned_interface)) { $chan_list = "/sbin/ifconfig {$cloned_interface} list txpower"; $stack_list = "/usr/bin/awk -F\"Channel \" '{ gsub(/\\*/, \" \"); print \$2 \"\\\n\" \$3 }'"; $format_list = "/usr/bin/awk '{print \$1 \",\" \$3 \" \" \$4 \",\" \$5 \",\" \$7}'"; @@ -5174,8 +5606,9 @@ function get_wireless_channel_info($interface) { foreach ($interface_channels as $channel_line) { $channel_line = explode(",", $channel_line); - if(!isset($wireless_channels[$channel_line[0]])) + if (!isset($wireless_channels[$channel_line[0]])) { $wireless_channels[$channel_line[0]] = $channel_line; + } } } return($wireless_channels); @@ -5208,8 +5641,9 @@ function get_interface_mac($interface) { ******/ function generate_random_mac_address() { $mac = "02"; - for($x=0; $x<5; $x++) + for ($x=0; $x<5; $x++) { $mac .= ":" . dechex(rand(16, 255)); + } return $mac; } @@ -5225,12 +5659,14 @@ function is_jumbo_capable($iface) { $iface = trim($iface); $capable = pfSense_get_interface_addresses($iface); - if (isset($capable['caps']['vlanmtu'])) + if (isset($capable['caps']['vlanmtu'])) { return true; + } // hack for some lagg modes missing vlanmtu, but work fine w/VLANs - if (substr($iface, 0, 4) == "lagg") + if (substr($iface, 0, 4) == "lagg") { return true; + } return false; } @@ -5240,7 +5676,7 @@ function interface_setup_pppoe_reset_file($pppif, $iface="") { $cron_file = "{$g['varetc_path']}/pppoe_restart_{$pppif}"; - if(!empty($iface) && !empty($pppif)){ + if (!empty($iface) && !empty($pppif)) { $cron_cmd = << /dev/null 2>&1 "); if (is_array($config['dhcpd'][$if]['staticmap'])) { - foreach ($config['dhcpd'][$if]['staticmap'] as $arpent) { mwexec("/usr/sbin/arp -s " . escapeshellarg($arpent['ipaddr']) . " " . escapeshellarg($arpent['mac'])); - } - } } else { mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " -staticarp " ); @@ -5338,10 +5773,11 @@ function get_failover_interface($interface, $family = "all") { $a_groups = return_gateway_groups_array(); if (is_array($a_groups[$interface])) { /* we found a gateway group, fetch the interface or vip */ - if (!empty($a_groups[$interface][0]['vip'])) + if (!empty($a_groups[$interface][0]['vip'])) { return $a_groups[$interface][0]['vip']; - else + } else { return $a_groups[$interface][0]['int']; + } } /* fall through to get_real_interface */ /* XXX: Really needed? */ From b37a2e8c90dd8d28c9a967750a9aee3898a6cdd5 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sat, 28 Feb 2015 14:25:49 +0545 Subject: [PATCH 142/257] Code style for etc inc i to p --- etc/inc/IPv6.inc | 82 +++++----- etc/inc/PEAR.inc | 8 +- etc/inc/ipsec.attributes.php | 72 +++++---- etc/inc/ipsec.auth-user.php | 39 +++-- etc/inc/ipsec.inc | 280 ++++++++++++++++++--------------- etc/inc/itemid.inc | 59 +++---- etc/inc/led.inc | 6 +- etc/inc/login_sasl_client.inc | 6 +- etc/inc/meta.inc | 51 +++--- etc/inc/notices.inc | 195 +++++++++++++---------- etc/inc/ntlm_sasl_client.inc | 24 +-- etc/inc/openvpn.attributes.php | 75 +++++---- etc/inc/openvpn.auth-user.php | 75 +++++---- etc/inc/openvpn.tls-verify.php | 10 +- etc/inc/plain_sasl_client.inc | 10 +- etc/inc/priv.inc | 141 +++++++++++------ 16 files changed, 648 insertions(+), 485 deletions(-) diff --git a/etc/inc/IPv6.inc b/etc/inc/IPv6.inc index 519cbcd09e..faacb8d2ce 100644 --- a/etc/inc/IPv6.inc +++ b/etc/inc/IPv6.inc @@ -12,7 +12,7 @@ * PHP versions 4 and 5 * * LICENSE: This source file is subject to the New BSD license, that is - * available through the world-wide-web at + * available through the world-wide-web at * http://www.opensource.org/licenses/bsd-license.php * If you did not receive a copy of the new BSDlicense and are unable * to obtain it through the world-wide-web, please send a note to @@ -66,7 +66,7 @@ define("NET_IPV6_RESERVED_NSAP", 12); define("NET_IPV6_RESERVED_IPX", 13); /** - * Address Type: Reserved for Geographic-Based Unicast Addresses + * Address Type: Reserved for Geographic-Based Unicast Addresses * (RFC 1884, Section 2.3) * @see getAddressType() */ @@ -148,11 +148,11 @@ class Net_IPv6 * @return Array the first element is the IP, the second the prefix length * @since 1.2.0 * @access public - * @static + * @static */ - static function separate($ip) + static function separate($ip) { - + $addr = $ip; $spec = ''; @@ -203,7 +203,7 @@ class Net_IPv6 * Tests for a prefix length specification in the address * and removes the prefix length, if exists * - * The method is technically identical to removeNetmaskSpec() and + * The method is technically identical to removeNetmaskSpec() and * will be dropped in a future release. * * @param String $ip a valid ipv6 address @@ -240,7 +240,7 @@ class Net_IPv6 * @access public * @static */ - static function getNetmaskSpec($ip) + static function getNetmaskSpec($ip) { $elements = Net_IPv6::separate($ip); @@ -256,7 +256,7 @@ class Net_IPv6 * Tests for a prefix length specification in the address * and returns the prefix length, if exists * - * The method is technically identical to getNetmaskSpec() and + * The method is technically identical to getNetmaskSpec() and * will be dropped in a future release. * * @param String $ip a valid ipv6 address @@ -266,9 +266,9 @@ class Net_IPv6 * @static * @deprecated */ - static function getPrefixLength($ip) + static function getPrefixLength($ip) { - if (preg_match("/^([0-9a-fA-F:]{2,39})\/(\d{1,3})*$/", + if (preg_match("/^([0-9a-fA-F:]{2,39})\/(\d{1,3})*$/", $ip, $matches)) { return $matches[2]; @@ -424,12 +424,12 @@ class Net_IPv6 * @see NET_IPV6_MULTICAST * @see NET_IPV6_LOCAL_LINK * @see NET_IPV6_LOCAL_SITE - * @see NET_IPV6_IPV4MAPPING - * @see NET_IPV6_UNSPECIFIED - * @see NET_IPV6_LOOPBACK + * @see NET_IPV6_IPV4MAPPING + * @see NET_IPV6_UNSPECIFIED + * @see NET_IPV6_LOOPBACK * @see NET_IPV6_UNKNOWN_TYPE */ - static function getAddressType($ip) + static function getAddressType($ip) { $ip = Net_IPv6::removeNetmaskSpec($ip); $binip = Net_IPv6::_ip2Bin($ip); @@ -444,7 +444,7 @@ class Net_IPv6 } else if (0 == strncmp(str_repeat('0', 80).str_repeat('1', 16), $binip, 96)) { // ::ffff/96 - return NET_IPV6_IPV4MAPPING; + return NET_IPV6_IPV4MAPPING; } else if (0 == strncmp('1111111010', $binip, 10)) { @@ -462,7 +462,7 @@ class Net_IPv6 return NET_IPV6_MULTICAST; - } else if (0 == strncmp('00000000', $binip, 8)) { + } else if (0 == strncmp('00000000', $binip, 8)) { return NET_IPV6_RESERVED; @@ -526,10 +526,10 @@ class Net_IPv6 * Example of calling with invalid input: 1::2:3:4:5:6:7:8:9 -> 1:0:2:3:4:5:6:7:8:9 * * @param String $ip a (possibly) valid IPv6-address (hex format) - * @param Boolean $leadingZeros if true, leading zeros are added to each - * block of the address - * (FF01::101 -> - * FF01:0000:0000:0000:0000:0000:0000:0101) + * @param Boolean $leadingZeros if true, leading zeros are added to each + * block of the address + * (FF01::101 -> + * FF01:0000:0000:0000:0000:0000:0000:0101) * * @return String the uncompressed IPv6-address (hex format) * @access public @@ -630,14 +630,14 @@ class Net_IPv6 } if(true == $leadingZeros) { - + $uipT = array(); $uiparts = explode(':', $uip); foreach($uiparts as $p) { $uipT[] = sprintf('%04s', $p); - + } $uip = implode(':', $uipT); @@ -665,14 +665,14 @@ class Net_IPv6 * Example: FF01:0:0:0:0:0:0:101 -> FF01::101 * 0:0:0:0:0:0:0:1 -> ::1 * - * When $ip is an already compressed address and $force is false, the method returns + * When $ip is an already compressed address and $force is false, the method returns * the value as is, even if the address can be compressed further. * * Example: FF01::0:1 -> FF01::0:1 * * To enforce maximum compression, you can set the second argument $force to true. * - * Example: FF01::0:1 -> FF01::1 + * Example: FF01::0:1 -> FF01::1 * * @param String $ip a valid IPv6-address (hex format) * @param boolean $force if true the address will be compressed as best as possible (since 1.2.0) @@ -683,14 +683,14 @@ class Net_IPv6 * @static * @author elfrink at introweb dot nl */ - static function compress($ip, $force = false) + static function compress($ip, $force = false) { - + if(false !== strpos($ip, '::')) { // its already compressed if(true == $force) { - $ip = Net_IPv6::uncompress($ip); + $ip = Net_IPv6::uncompress($ip); } else { @@ -798,20 +798,20 @@ class Net_IPv6 * Checks, if an IPv6 address can be compressed * * @param String $ip a valid IPv6 address - * + * * @return Boolean true, if address can be compressed - * + * * @access public * @since 1.2.0b * @static * @author Manuel Schmitt */ - static function isCompressible($ip) + static function isCompressible($ip) { return (bool)($ip != Net_IPv6::compress($address)); - } + } // }}} // {{{ SplitV64() @@ -826,7 +826,7 @@ class Net_IPv6 * 0:0:0:0:0:FFFF:129.144.52.38 * * @param String $ip a valid IPv6-address (hex format) - * @param Boolean $uncompress if true, the address will be uncompressed + * @param Boolean $uncompress if true, the address will be uncompressed * before processing * * @return Array [0] contains the IPv6 part, @@ -877,14 +877,14 @@ class Net_IPv6 { $elements = Net_IPv6::separate($ip); - + $ip = $elements[0]; if('' != $elements[1] && ( !is_numeric($elements[1]) || 0 > $elements[1] || 128 < $elements[1])) { return false; - } + } $ipPart = Net_IPv6::SplitV64($ip); $count = 0; @@ -901,14 +901,14 @@ class Net_IPv6 for ($i = 0; $i < count($ipv6); $i++) { if(4 < strlen($ipv6[$i])) { - + return false; } $dec = hexdec($ipv6[$i]); $hex = strtoupper(preg_replace("/^[0]{1,3}(.*[0-9a-fA-F])$/", - "\\1", + "\\1", $ipv6[$i])); if ($ipv6[$i] >= 0 && $dec <= 65535 @@ -967,8 +967,8 @@ class Net_IPv6 /** * Returns the lowest and highest IPv6 address * for a given IP and netmask specification - * - * The netmask may be a part of the $ip or + * + * The netmask may be a part of the $ip or * the number of netmask bits is provided via $bits * * The result is an indexed array. The key 'start' @@ -990,7 +990,7 @@ class Net_IPv6 $ip = null; $bitmask = null; - if ( null == $bits ) { + if ( null == $bits ) { $elements = explode('/', $ipToParse); @@ -1033,14 +1033,14 @@ class Net_IPv6 /** * Converts an IPv6 address from Hex into Binary representation. * - * @param String $ip the IP to convert (a:b:c:d:e:f:g:h), + * @param String $ip the IP to convert (a:b:c:d:e:f:g:h), * compressed IPs are allowed * * @return String the binary representation * @access private @ @since 1.1.0 */ - static function _ip2Bin($ip) + static function _ip2Bin($ip) { $binstr = ''; diff --git a/etc/inc/PEAR.inc b/etc/inc/PEAR.inc index 6fb91a3ef8..a28060267c 100644 --- a/etc/inc/PEAR.inc +++ b/etc/inc/PEAR.inc @@ -178,7 +178,7 @@ class PEAR * but is included for forward compatibility, so subclass * destructors should always call it. * - * See the note in the class desciption about output from + * See the note in the class description about output from * destructors. * * @access public @@ -403,7 +403,7 @@ class PEAR } /** - * This method deletes all occurences of the specified element from + * This method deletes all occurrences of the specified element from * the expected error codes stack. * * @param mixed $error_code error code that should be deleted @@ -698,7 +698,7 @@ class PEAR } /** - * OS independant PHP extension load. Remember to take care + * OS independent PHP extension load. Remember to take care * on the correct extension name for case sensitive OSes. * * @param string $ext The extension name @@ -819,7 +819,7 @@ function _PEAR_call_destructors() /** * Standard PEAR error class for PHP 4 * - * This class is supserseded by {@link PEAR_Exception} in PHP 5 + * This class is superseded by {@link PEAR_Exception} in PHP 5 * * @category pear * @package PEAR diff --git a/etc/inc/ipsec.attributes.php b/etc/inc/ipsec.attributes.php index b8d900ac3f..8a8ed5f3f7 100644 --- a/etc/inc/ipsec.attributes.php +++ b/etc/inc/ipsec.attributes.php @@ -1,7 +1,7 @@ diff --git a/etc/inc/ipsec.inc b/etc/inc/ipsec.inc index 53c60264c3..0780e2f1c4 100644 --- a/etc/inc/ipsec.inc +++ b/etc/inc/ipsec.inc @@ -167,9 +167,11 @@ $p2_pfskeygroups = array( function ipsec_ikeid_used($ikeid) { global $config; - foreach ($config['ipsec']['phase1'] as $ph1ent) - if( $ikeid == $ph1ent['ikeid'] ) + foreach ($config['ipsec']['phase1'] as $ph1ent) { + if ( $ikeid == $ph1ent['ikeid'] ) { return true; + } + } return false; } @@ -177,8 +179,9 @@ function ipsec_ikeid_used($ikeid) { function ipsec_ikeid_next() { $ikeid = 1; - while(ipsec_ikeid_used($ikeid)) + while (ipsec_ikeid_used($ikeid)) { $ikeid++; + } return $ikeid; } @@ -190,7 +193,7 @@ function ipsec_get_phase1_src(& $ph1ent) { if ($ph1ent['interface']) { if (!is_ipaddr($ph1ent['interface'])) { - if ($ph1ent['protocol'] == "inet6") { + if ($ph1ent['protocol'] == "inet6") { $interfaceip = get_interface_ipv6($ph1ent['interface']); } else { $interfaceip = get_interface_ip($ph1ent['interface']); @@ -200,10 +203,11 @@ function ipsec_get_phase1_src(& $ph1ent) { } } else { $if = "wan"; - if ($ph1ent['protocol'] == "inet6") + if ($ph1ent['protocol'] == "inet6") { $interfaceip = get_interface_ipv6($if); - else + } else { $interfaceip = get_interface_ip($if); + } } return $interfaceip; @@ -215,15 +219,18 @@ function ipsec_get_phase1_src(& $ph1ent) { function ipsec_get_phase1_dst(& $ph1ent) { global $g; - if (empty($ph1ent['remote-gateway'])) + if (empty($ph1ent['remote-gateway'])) { return false; + } $rg = $ph1ent['remote-gateway']; if (!is_ipaddr($rg)) { - if(! platform_booting()) + if (! platform_booting()) { return resolve_retry($rg); + } } - if(!is_ipaddr($rg)) + if (!is_ipaddr($rg)) { return false; + } return $rg; } @@ -237,10 +244,11 @@ function ipsec_idinfo_to_cidr(& $idinfo, $addrbits = false, $mode = "") { switch ($idinfo['type']) { case "address": if ($addrbits) { - if ($mode == "tunnel6") + if ($mode == "tunnel6") { return $idinfo['address']."/128"; - else + } else { return $idinfo['address']."/32"; + } } else return $idinfo['address']; break; /* NOTREACHED */ @@ -252,8 +260,9 @@ function ipsec_idinfo_to_cidr(& $idinfo, $addrbits = false, $mode = "") { return '0.0.0.0/0'; break; /* NOTREACHED */ default: - if (empty($mode) && !empty($idinfo['mode'])) + if (empty($mode) && !empty($idinfo['mode'])) { $mode = $idinfo['mode']; + } if ($mode == "tunnel6") { $address = get_interface_ipv6($idinfo['type']); @@ -279,10 +288,11 @@ function ipsec_idinfo_to_subnet(& $idinfo,$addrbits = false) { switch ($idinfo['type']) { case "address": if ($addrbits) { - if ($idinfo['mode'] == "tunnel6") + if ($idinfo['mode'] == "tunnel6") { return $idinfo['address']."/128"; - else + } else { return $idinfo['address']."/255.255.255.255"; + } } else return $idinfo['address']; break; /* NOTREACHED */ @@ -316,24 +326,25 @@ function ipsec_idinfo_to_text(& $idinfo) { global $config; switch ($idinfo['type']) { - case "address": - return $idinfo['address']; - break; /* NOTREACHED */ - case "network": - return $idinfo['address']."/".$idinfo['netbits']; - break; /* NOTREACHED */ - case "mobile": - return gettext("Mobile Client"); - break; /* NOTREACHED */ - case "none": - return gettext("None"); - break; /* NOTREACHED */ - default: - if (!empty($config['interfaces'][$idinfo['type']])) - return convert_friendly_interface_to_friendly_descr($idinfo['type']); - else - return strtoupper($idinfo['type']); - break; /* NOTREACHED */ + case "address": + return $idinfo['address']; + break; /* NOTREACHED */ + case "network": + return $idinfo['address']."/".$idinfo['netbits']; + break; /* NOTREACHED */ + case "mobile": + return gettext("Mobile Client"); + break; /* NOTREACHED */ + case "none": + return gettext("None"); + break; /* NOTREACHED */ + default: + if (!empty($config['interfaces'][$idinfo['type']])) { + return convert_friendly_interface_to_friendly_descr($idinfo['type']); + } else { + return strtoupper($idinfo['type']); + } + break; /* NOTREACHED */ } } @@ -343,18 +354,21 @@ function ipsec_idinfo_to_text(& $idinfo) { function ipsec_lookup_phase1(& $ph2ent,& $ph1ent) { global $config; - if (!is_array($config['ipsec'])) + if (!is_array($config['ipsec'])) { return false; - if (!is_array($config['ipsec']['phase1'])) + } + if (!is_array($config['ipsec']['phase1'])) { return false; - if (empty($config['ipsec']['phase1'])) + } + if (empty($config['ipsec']['phase1'])) { return false; + } foreach ($config['ipsec']['phase1'] as $ph1tmp) { - if ($ph1tmp['ikeid'] == $ph2ent['ikeid']) { - $ph1ent = $ph1tmp; - return $ph1ent; - } + if ($ph1tmp['ikeid'] == $ph2ent['ikeid']) { + $ph1ent = $ph1tmp; + return $ph1ent; + } } return false; @@ -367,8 +381,9 @@ function ipsec_phase1_status(&$ipsec_status, $ikeid) { foreach ($ipsec_status as $ike) { if ($ike['id'] == $ikeid) { - if ($ike['status'] == 'established') + if ($ike['status'] == 'established') { return true; + } } } @@ -380,8 +395,9 @@ function ipsec_phase1_status(&$ipsec_status, $ikeid) { */ function ipsec_phase2_status(&$ipsec_status, &$phase2) { - if (ipsec_lookup_phase1($ph2ent,$ph1ent)) + if (ipsec_lookup_phase1($ph2ent,$ph1ent)) { return ipsec_phase1_status($ipsec_status, $ph1ent['ikeid']); + } return false; } @@ -406,8 +422,9 @@ function ipsec_smp_dump_status() { $response = ""; while (!strstr($sread, "")) { $sread = fgets($fd); - if ($sread === false) + if ($sread === false) { break; + } $response .= $sread; } fclose($fd); @@ -438,13 +455,16 @@ function ipsec_dump_spd() if ($fd) { while (!feof($fd)) { $line = chop(fgets($fd)); - if (!$line) + if (!$line) { continue; - if ($line == "No SPD entries.") + } + if ($line == "No SPD entries.") { break; + } if ($line[0] != "\t") { - if (is_array($cursp)) + if (is_array($cursp)) { $spd[] = $cursp; + } $cursp = array(); $linea = explode(" ", $line); $cursp['srcid'] = substr($linea[0], 0, strpos($linea[0], "[")); @@ -453,13 +473,13 @@ function ipsec_dump_spd() } else if (is_array($cursp)) { $line = trim($line, "\t\r\n "); $linea = explode(" ", $line); - switch($i) - { + switch ($i) { case 1: - if ($linea[1] == "none") /* don't show default anti-lockout rule */ + if ($linea[1] == "none") /* don't show default anti-lockout rule */ { unset($cursp); - else + } else { $cursp['dir'] = $linea[0]; + } break; case 2: $upperspec = explode("/", $linea[0]); @@ -471,8 +491,9 @@ function ipsec_dump_spd() } $i++; } - if (is_array($cursp) && count($cursp)) + if (is_array($cursp) && count($cursp)) { $spd[] = $cursp; + } pclose($fd); } @@ -489,29 +510,29 @@ function ipsec_dump_sad() if ($fd) { while (!feof($fd)) { $line = chop(fgets($fd)); - if (!$line || $line[0] == " ") + if (!$line || $line[0] == " ") { continue; - if ($line == "No SAD entries.") + } + if ($line == "No SAD entries.") { break; - if ($line[0] != "\t") - { - if (is_array($cursa)) + } + if ($line[0] != "\t") { + if (is_array($cursa)) { $sad[] = $cursa; + } $cursa = array(); list($cursa['src'],$cursa['dst']) = explode(" ", $line); - } - else - { + } else { $line = trim($line, "\t\n\r "); $linea = explode(" ", $line); foreach ($linea as $idx => $linee) { - if ($linee == 'esp' || $linee == 'ah' || $linee[0] == '#') + if ($linee == 'esp' || $linee == 'ah' || $linee[0] == '#') { $cursa['proto'] = $linee; - else if (substr($linee, 0, 3) == 'spi') + } else if (substr($linee, 0, 3) == 'spi') { $cursa['spi'] = substr($linee, strpos($linee, 'x') + 1, -1); - else if (substr($linee, 0, 5) == 'reqid') + } else if (substr($linee, 0, 5) == 'reqid') { $cursa['reqid'] = substr($linee, strpos($linee, 'x') + 1, -1); - else if (substr($linee, 0, 2) == 'E:') { + } else if (substr($linee, 0, 2) == 'E:') { $cursa['ealgo'] = $linea[$idx + 1]; break; } else if (substr($linee, 0, 2) == 'A:') { @@ -521,12 +542,12 @@ function ipsec_dump_sad() $cursa['data'] = substr($linea[$idx + 1], 0, strpos($linea[$idx + 1], 'bytes') - 1) . ' B'; break; } - } } } - if (is_array($cursa) && count($cursa)) + if (is_array($cursa) && count($cursa)) { $sad[] = $cursa; + } pclose($fd); } @@ -547,8 +568,9 @@ function ipsec_dump_mobile() { } /* This is needed for fixing #4130 */ - if (filesize("{$g['tmp_path']}/strongswan_leases.xml") < 200) + if (filesize("{$g['tmp_path']}/strongswan_leases.xml") < 200) { return array(); + } $custom_listtags = array('lease', 'pool'); $response = parse_xml_config("{$g['tmp_path']}/strongswan_leases.xml", "leases"); @@ -570,13 +592,13 @@ function ipsec_mobilekey_sort() { function ipsec_get_number_of_phase2($ikeid) { global $config; - $a_phase2 = $config['ipsec']['phase2']; + $a_phase2 = $config['ipsec']['phase2']; $nbph2=0; - if (is_array($a_phase2) && count($a_phase2)) { - foreach ($a_phase2 as $ph2tmp) { - if ($ph2tmp['ikeid'] == $ikeid) { + if (is_array($a_phase2) && count($a_phase2)) { + foreach ($a_phase2 as $ph2tmp) { + if ($ph2tmp['ikeid'] == $ikeid) { $nbph2++; } } @@ -589,8 +611,9 @@ function ipsec_get_descr($ikeid) { global $config; if (!isset($config['ipsec']['phase1']) || - !is_array($config['ipsec']['phase1'])) + !is_array($config['ipsec']['phase1'])) { return ''; + } foreach ($config['ipsec']['phase1'] as $p1) { if ($p1['ikeid'] == $ikeid) { @@ -602,26 +625,28 @@ function ipsec_get_descr($ikeid) { } function ipsec_get_phase1($ikeid) { - global $config; + global $config; - if (!isset($config['ipsec']['phase1']) || - !is_array($config['ipsec']['phase1'])) - return ''; + if (!isset($config['ipsec']['phase1']) || + !is_array($config['ipsec']['phase1'])) { + return ''; + } - $a_phase1 = $config['ipsec']['phase1']; - foreach ($a_phase1 as $p1) { - if ($p1['ikeid'] == $ikeid) { - return $p1; - } - } - unset($a_phase1); + $a_phase1 = $config['ipsec']['phase1']; + foreach ($a_phase1 as $p1) { + if ($p1['ikeid'] == $ikeid) { + return $p1; + } + } + unset($a_phase1); } function ipsec_fixup_ip($ipaddr) { - if (is_ipaddrv6($ipaddr) || is_subnetv6($ipaddr)) + if (is_ipaddrv6($ipaddr) || is_subnetv6($ipaddr)) { return Net_IPv6::compress(Net_IPv6::uncompress($ipaddr)); - else + } else { return $ipaddr; + } } function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array()) { @@ -630,66 +655,71 @@ function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array()) { $id_data = $ph1ent['myid_data']; $addr = ipsec_get_phase1_src($ph1ent); - if (!$addr) + if (!$addr) { return array(); + } } elseif ($side = "peer") { $id_type = $ph1ent['peerid_type']; $id_data = $ph1ent['peerid_data']; - if (isset($ph1ent['mobile'])) + if (isset($ph1ent['mobile'])) { $addr = "%any"; - else + } else { $addr = $ph1ent['remote-gateway']; - } else + } + } else { return array(); + } $thisid_type = $id_type; switch ($thisid_type) { - case 'myaddress': - $thisid_type = 'address'; - $thisid_data = $addr; - break; - case 'dyn_dns': - $thisid_type = 'dns'; - $thisid_data = $id_data; - break; - case 'peeraddress': - $thisid_type = 'address'; - $thisid_data = $rgmap[$ph1ent['remote-gateway']]; - break; - case 'address': - $thisid_data = $id_data; - break; - case 'fqdn': - $thisid_data = "{$id_data}"; - break; - case 'keyid tag': - $thisid_type = 'keyid'; - $thisid_data = "{$thisid_data}"; - break; - case 'user_fqdn': - $thisid_type = 'userfqdn'; - $thisid_data = "{$id_data}"; - break; - case 'asn1dn': - $thisid_data = $id_data; - if ($thisid_data && $thisid_data[0] != '"') - $thisid_data = "\"{$id_data}\""; - break; + case 'myaddress': + $thisid_type = 'address'; + $thisid_data = $addr; + break; + case 'dyn_dns': + $thisid_type = 'dns'; + $thisid_data = $id_data; + break; + case 'peeraddress': + $thisid_type = 'address'; + $thisid_data = $rgmap[$ph1ent['remote-gateway']]; + break; + case 'address': + $thisid_data = $id_data; + break; + case 'fqdn': + $thisid_data = "{$id_data}"; + break; + case 'keyid tag': + $thisid_type = 'keyid'; + $thisid_data = "{$thisid_data}"; + break; + case 'user_fqdn': + $thisid_type = 'userfqdn'; + $thisid_data = "{$id_data}"; + break; + case 'asn1dn': + $thisid_data = $id_data; + if ($thisid_data && $thisid_data[0] != '"') { + $thisid_data = "\"{$id_data}\""; + } + break; } return array($thisid_type, $thisid_data); } function ipsec_fixup_network($network) { - if (substr($network, -3) == '|/0') + if (substr($network, -3) == '|/0') { $result = substr($network, 0, -3); - else { + } else { $tmp = explode('|', $network); - if (isset($tmp[1])) + if (isset($tmp[1])) { $result = $tmp[1]; - else + } else { $result = $tmp[0]; + } unset($tmp); } @@ -699,14 +729,16 @@ function ipsec_fixup_network($network) { function ipsec_new_reqid() { global $config; - if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) + if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) { return; + } $ipsecreqid = lock('ipsecreqids', LOCK_EX); $keyids = array(); $keyid = 1; - foreach ($config['ipsec']['phase2'] as $ph2) + foreach ($config['ipsec']['phase2'] as $ph2) { $keyids[$ph2['reqid']] = $ph2['reqid']; + } for ($i = 1; $i < 16000; $i++) { if (!isset($keyids[$i])) { diff --git a/etc/inc/itemid.inc b/etc/inc/itemid.inc index 2e228c35ce..dff4a8bc29 100644 --- a/etc/inc/itemid.inc +++ b/etc/inc/itemid.inc @@ -5,29 +5,29 @@ */ /* - Copyright (C) 2009 Janne Enberg - All rights reserved. + Copyright (C) 2009 Janne Enberg + All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. */ @@ -40,24 +40,25 @@ * RESULT * boolean - true if item was found and deleted ******/ -function delete_id($id, &$array){ +function delete_id($id, &$array) { // Index to delete $delete_index = NULL; - if (!is_array($array)) + if (!is_array($array)) { return false; + } // Search for the item in the array - foreach ($array as $key => $item){ + foreach ($array as $key => $item) { // If this item is the one we want to delete - if(isset($item['associated-rule-id']) && $item['associated-rule-id']==$id ){ + if (isset($item['associated-rule-id']) && $item['associated-rule-id']==$id ) { $delete_index = $key; break; } } // If we found the item, unset it - if( $delete_index!==NULL ){ + if ($delete_index!==NULL) { unset($array[$delete_index]); return true; } else { @@ -78,14 +79,16 @@ function delete_id($id, &$array){ function get_id($id, &$array) { // Use $foo = &get_id('id', array('id'=>'value')); - if (!is_array($array)) + if (!is_array($array)) { return false; + } // Search for the item in the array - foreach ($array as $key => $item){ + foreach ($array as $key => $item) { // If this item is the one we want to delete - if (isset($item['associated-rule-id']) && $item['associated-rule-id']==$id) + if (isset($item['associated-rule-id']) && $item['associated-rule-id']==$id) { return $key; + } } return false; @@ -97,7 +100,7 @@ function get_id($id, &$array) { * RESULT * string - unique id ******/ -function get_unique_id(){ +function get_unique_id() { return uniqid("nat_", true); } diff --git a/etc/inc/led.inc b/etc/inc/led.inc index 9d060597cd..1661950e09 100644 --- a/etc/inc/led.inc +++ b/etc/inc/led.inc @@ -84,8 +84,9 @@ function led_digit($led, $digitstring) { $dstring = "d"; while ($i < strlen($digitstring)) { $thisdigit = substr($digitstring, $i++, 1); - if (is_numeric($thisdigit)) + if (is_numeric($thisdigit)) { $dstring .= $thisdigit; + } } led_ctl($led, $dstring); } @@ -123,8 +124,9 @@ function led_count() { */ function led_exists($led) { global $led_root; - if (!is_numeric($led)) + if (!is_numeric($led)) { return false; + } return file_exists("{$led_root}{$led}"); } diff --git a/etc/inc/login_sasl_client.inc b/etc/inc/login_sasl_client.inc index 923d16efab..f5cc0500e2 100644 --- a/etc/inc/login_sasl_client.inc +++ b/etc/inc/login_sasl_client.inc @@ -23,7 +23,7 @@ class login_sasl_client_class Function Start(&$client, &$message, &$interactions) { - if($this->state!=SASL_LOGIN_STATE_START) + if ($this->state!=SASL_LOGIN_STATE_START) { $client->error="LOGIN authentication state is not at the start"; return(SASL_FAIL); @@ -37,7 +37,7 @@ class login_sasl_client_class "realm"=>"" ); $status=$client->GetCredentials($this->credentials,$defaults,$interactions); - if($status==SASL_CONTINUE) + if ($status==SASL_CONTINUE) $this->state=SASL_LOGIN_STATE_IDENTIFY_USER; Unset($message); return($status); @@ -45,7 +45,7 @@ class login_sasl_client_class Function Step(&$client, $response, &$message, &$interactions) { - switch($this->state) + switch ($this->state) { case SASL_LOGIN_STATE_IDENTIFY_USER: $message=$this->credentials["user"].(strlen($this->credentials["realm"]) ? "@".$this->credentials["realm"] : ""); diff --git a/etc/inc/meta.inc b/etc/inc/meta.inc index 11295f532e..520e6227bb 100644 --- a/etc/inc/meta.inc +++ b/etc/inc/meta.inc @@ -33,7 +33,7 @@ * followed by the appropriate value or value pair. All markers * are prefixed with a ##| sequence. The + suffix is used to * denote the beginning of a tag block followed by the tag name. - * A - suffix is used to denote the end of a tag blaock. Values + * A - suffix is used to denote the end of a tag block. Values * are denoted using the * suffix and can optionally be expressed * as a key value pair. An example of a metadata tag block ... * @@ -48,7 +48,7 @@ * metadata['']['INFO']['BLAH'][0] == true * metadata['']['INFO']['TEXT'][0] == "SOME TEXT" * - * NOTE: All statements must be at the begining of a line and + * NOTE: All statements must be at the beginning of a line and * contiguous for a tag. The example shown above would not be * processed due to the extra ' * ' comment chars. * @@ -60,8 +60,9 @@ function list_phpfiles($path, & $found) { - if (!is_array($found)) + if (!is_array($found)) { $found = array(); + } $dir = opendir($path); if (!$dir) { @@ -69,11 +70,13 @@ function list_phpfiles($path, & $found) { return; } - while($fname = readdir($dir)) { - if($fname == "." || $fname == ".." || $fname[0] == '.') + while ($fname = readdir($dir)) { + if ($fname == "." || $fname == ".." || $fname[0] == '.') { continue; - if (fnmatch('*.php', $fname)) + } + if (fnmatch('*.php', $fname)) { $found[] = $fname; + } } } @@ -83,16 +86,19 @@ function list_phpfiles($path, & $found) { function read_file_metadata($fpath, & $metadata, $taglist = false) { - if (!is_array($metadata)) + if (!is_array($metadata)) { $metadata = array(); + } - if ($taglist) + if ($taglist) { $taglist = explode(",", $taglist); + } $fname = $fpath; $slash = strrpos($fname,"/"); - if ($slash) + if ($slash) { $fname = substr($fname,$slash + 1); + } $fdata = @file_get_contents($fpath); if (!$fdata) { @@ -107,20 +113,24 @@ function read_file_metadata($fpath, & $metadata, $taglist = false) { while (true) { $tagbeg_off = stripos($fdata, "##|+", $offset); - if ($tagbeg_off === false) + if ($tagbeg_off === false) { break; + } $tagbeg_trm = stripos($fdata, "\n", $tagbeg_off); - if ($tagbeg_trm === false) + if ($tagbeg_trm === false) { break; + } $tagend_off = stripos($fdata, "##|-", $tagbeg_trm); - if ($tagend_off === false) + if ($tagend_off === false) { break; + } $tagend_trm = stripos($fdata, "\n", $tagend_off); - if ($tagend_trm === false) + if ($tagend_trm === false) { break; + } $tagbeg_len = $tagbeg_trm - $tagbeg_off; $tagend_len = $tagend_trm - $tagend_off; @@ -146,17 +156,20 @@ function read_file_metadata($fpath, & $metadata, $taglist = false) { $offset = $tagend_trm + 1; - if (is_array($taglist)) - if (!in_array($tagbeg,$taglist)) + if (is_array($taglist)) { + if (!in_array($tagbeg,$taglist)) { continue; + } + } $vals = array(); $lines = explode("\n",$mdata); foreach ($lines as $line) { - if (!strlen($line)) + if (!strlen($line)) { continue; + } $valtag = stripos($line, "##|*"); if ($valtag === false || $valtag) { @@ -189,12 +202,14 @@ function read_file_metadata($fpath, & $metadata, $taglist = false) { $vals[$vname][] = $vdata; } - if (count($vals)) + if (count($vals)) { $tags[$tagbeg] = $vals; + } } - if (count($tags)) + if (count($tags)) { $metadata[$fname] = $tags; + } } ?> diff --git a/etc/inc/notices.inc b/etc/inc/notices.inc index bad3a32600..4b9655b96a 100644 --- a/etc/inc/notices.inc +++ b/etc/inc/notices.inc @@ -1,37 +1,35 @@ $id, @@ -82,7 +82,7 @@ function file_notice($id, $notice, $category = "General", $url = "", $priority = ); $queue[$queuekey] = $toqueue; $queueout = fopen($notice_path, "w"); - if(!$queueout) { + if (!$queueout) { log_error(printf(gettext("Could not open %s for writing"), $notice_path)); return; } @@ -90,8 +90,9 @@ function file_notice($id, $notice, $category = "General", $url = "", $priority = fclose($queueout); log_error("New alert found: $notice"); /* soekris */ - if(file_exists("/dev/led/error")) + if (file_exists("/dev/led/error")) { exec("/bin/echo 1 > /dev/led/error"); + } /* wrap & alix */ led_normalize(); led_morse(1, 'sos'); @@ -111,13 +112,16 @@ function file_notice($id, $notice, $category = "General", $url = "", $priority = function get_notices($category = "all") { global $g; - if(file_exists("{$g['tmp_path']}/notices")) { + if (file_exists("{$g['tmp_path']}/notices")) { $queue = unserialize(file_get_contents("{$g['tmp_path']}/notices")); - if(!$queue) return false; - if($category != 'all') { - foreach($queue as $time => $notice) { - if(strtolower($notice['category']) == strtolower($category)) + if (!$queue) { + return false; + } + if ($category != 'all') { + foreach ($queue as $time => $notice) { + if (strtolower($notice['category']) == strtolower($category)) { $toreturn[$time] = $notice; + } } return $toreturn; } else { @@ -140,35 +144,38 @@ function close_notice($id) { global $notice_path; require_once("util.inc"); /* soekris */ - if(file_exists("/dev/led/error")) + if (file_exists("/dev/led/error")) { exec("/bin/echo 0 > /dev/led/error"); + } /* wrap & alix */ led_normalize(); $ids = array(); - if(!$notices = get_notices()) return; - if($id == "all") { + if (!$notices = get_notices()) { + return; + } + if ($id == "all") { unlink_if_exists($notice_path); return; } - foreach(array_keys($notices) as $time) { - if($id == $time) { + foreach (array_keys($notices) as $time) { + if ($id == $time) { unset($notices[$id]); break; } } - foreach($notices as $key => $notice) { + foreach ($notices as $key => $notice) { $ids[$key] = $notice['id']; } - foreach($ids as $time => $tocheck) { - if($id == $tocheck) { + foreach ($ids as $time => $tocheck) { + if ($id == $tocheck) { unset($notices[$time]); break; } } - if(count($notices) != 0) { + if (count($notices) != 0) { $queueout = fopen($notice_path, "w"); - fwrite($queueout, serialize($notices)); - fclose($queueout); + fwrite($queueout, serialize($notices)); + fclose($queueout); } else { unlink_if_exists($notice_path); } @@ -185,14 +192,17 @@ function close_notice($id) { * Outputs notices in XML formatted text ******/ function dump_xml_notices() { - if(file_exists("/cf/conf/use_xmlreader")) + if (file_exists("/cf/conf/use_xmlreader")) { require_once("xmlreader.inc"); - else + } else { require_once("xmlparse.inc"); + } global $notice_path, $listtags; $listtags[] = 'notice'; - if(!$notices = get_notices()) return; - foreach($notices as $time => $notice) { + if (!$notices = get_notices()) { + return; + } + foreach ($notices as $time => $notice) { $notice['time'] = $time; $toput['notice'][] = $notice; } @@ -209,21 +219,23 @@ function dump_xml_notices() { * prints notices to the GUI ******/ function print_notices($notices, $category = "all") { - foreach($notices as $notice) { - if($category != "all") { - if(in_array($notice['category'], $category)) $categories[] = $notice['category']; + foreach ($notices as $notice) { + if ($category != "all") { + if (in_array($notice['category'], $category)) { + $categories[] = $notice['category']; + } } else { $categories[] = $notice['category']; } } $categories = array_unique($categories); sort($categories); - foreach($categories as $category) { + foreach ($categories as $category) { $toreturn .= "
  • {$category}
      "; - foreach($notices as $notice) { - if(strtolower($notice['category']) == strtolower($category)) { - if($notice['id'] != "") { - if($notice['url'] != "") { + foreach ($notices as $notice) { + if (strtolower($notice['category']) == strtolower($category)) { + if ($notice['id'] != "") { + if ($notice['url'] != "") { $toreturn .= "
    • {$notice['id']} - {$notice['notice']}
    • "; } else { $toreturn .= "
    • {$notice['id']} - {$notice['notice']}
    • "; @@ -246,7 +258,9 @@ function print_notices($notices, $category = "all") { ******/ function print_notice_box($category = "all") { $notices = get_notices(); - if(!$notices) return; + if (!$notices) { + return; + } print_info_box_np(print_notices($notices, $category)); return; } @@ -261,7 +275,7 @@ function print_notice_box($category = "all") { ******/ function are_notices_pending($category = "all") { global $notice_path; - if(file_exists($notice_path)) { + if (file_exists($notice_path)) { return true; } return false; @@ -277,17 +291,20 @@ function are_notices_pending($category = "all") { ******/ function notify_via_smtp($message, $force = false) { global $config, $g; - if(platform_booting()) + if (platform_booting()) { return; + } - if(isset($config['notifications']['smtp']['disable']) && !$force) + if (isset($config['notifications']['smtp']['disable']) && !$force) { return; + } /* Do NOT send the same message twice */ - if(file_exists("/var/db/notices_lastmsg.txt")) { + if (file_exists("/var/db/notices_lastmsg.txt")) { $lastmsg = trim(file_get_contents("/var/db/notices_lastmsg.txt")); - if($lastmsg == $message) + if ($lastmsg == $message) { return; + } } /* Store last message sent to avoid spamming */ @@ -304,14 +321,17 @@ function send_smtp_message($message, $subject = "(no subject)", $force = false) require_once("sasl.inc"); require_once("smtp.inc"); - if(isset($config['notifications']['smtp']['disable']) && !$force) + if (isset($config['notifications']['smtp']['disable']) && !$force) { return; + } - if(!$config['notifications']['smtp']['ipaddress']) + if (!$config['notifications']['smtp']['ipaddress']) { return; + } - if(!$config['notifications']['smtp']['notifyemailaddress']) + if (!$config['notifications']['smtp']['notifyemailaddress']) { return; + } $smtp = new smtp_class; @@ -327,13 +347,14 @@ function send_smtp_message($message, $subject = "(no subject)", $force = false) $smtp->debug = 0; $smtp->html_debug = 0; $smtp->localhost=$config['system']['hostname'].".".$config['system']['domain']; - - if($config['notifications']['smtp']['fromaddress']) + + if ($config['notifications']['smtp']['fromaddress']) { $from = $config['notifications']['smtp']['fromaddress']; - + } + // Use SMTP Auth if fields are filled out - if($config['notifications']['smtp']['username'] && - $config['notifications']['smtp']['password']) { + if ($config['notifications']['smtp']['username'] && + $config['notifications']['smtp']['password']) { if (isset($config['notifications']['smtp']['authentication_mechanism'])) { $smtp->authentication_mechanism = $config['notifications']['smtp']['authentication_mechanism']; } else { @@ -350,7 +371,7 @@ function send_smtp_message($message, $subject = "(no subject)", $force = false) "Date: ".date("r") ); - if($smtp->SendMessage($from, preg_split('/\s*,\s*/', trim($to)), $headers, $message)) { + if ($smtp->SendMessage($from, preg_split('/\s*,\s*/', trim($to)), $headers, $message)) { log_error(sprintf(gettext("Message sent to %s OK"), $to)); return; } else { @@ -371,14 +392,16 @@ function notify_via_growl($message, $force=false) { require_once("growl.class"); global $config,$g; - if (isset($config['notifications']['growl']['disable']) && !$force) + if (isset($config['notifications']['growl']['disable']) && !$force) { return; + } /* Do NOT send the same message twice */ - if(file_exists("/var/db/growlnotices_lastmsg.txt")) { + if (file_exists("/var/db/growlnotices_lastmsg.txt")) { $lastmsg = trim(file_get_contents("/var/db/growlnotices_lastmsg.txt")); - if($lastmsg == $message) + if ($lastmsg == $message) { return; + } } $hostname = $config['system']['hostname'] . "." . $config['system']['domain']; @@ -386,8 +409,8 @@ function notify_via_growl($message, $force=false) { $growl_password = $config['notifications']['growl']['password']; $growl_name = $config['notifications']['growl']['name']; $growl_notification = $config['notifications']['growl']['notification_name']; - - if(!empty($growl_ip)) { + + if (!empty($growl_ip)) { $growl = new Growl($growl_ip, $growl_password, $growl_name); $growl->notify("{$growl_notification}", gettext(sprintf("%s (%s) - Notification", $g['product_name'], $hostname)), "{$message}"); } @@ -413,9 +436,9 @@ function register_via_growl() { $growl_password = $config['notifications']['growl']['password']; $growl_name = $config['notifications']['growl']['name']; $growl_notification = $config['notifications']['growl']['notification_name']; - - if($growl_ip) { - $growl = new Growl($growl_ip, $growl_password, $growl_name); + + if ($growl_ip) { + $growl = new Growl($growl_ip, $growl_password, $growl_name); $growl->addNotification($growl_notification); $growl->register(); } diff --git a/etc/inc/ntlm_sasl_client.inc b/etc/inc/ntlm_sasl_client.inc index f21fcb55cd..18e56588c3 100644 --- a/etc/inc/ntlm_sasl_client.inc +++ b/etc/inc/ntlm_sasl_client.inc @@ -18,12 +18,12 @@ class ntlm_sasl_client_class Function Initialize(&$client) { - if(!function_exists($function="mcrypt_encrypt") - || !function_exists($function="hash")) + if (!function_exists($function="mcrypt_encrypt") || + !function_exists($function="hash")) { $extensions=array( "mcrypt_encrypt"=>"mcrypt", - "hash"=>"hash" + "hash"=>"hash" ); $client->error="the extension ".$extensions[$function]." required by the NTLM SASL client class is not available in this PHP configuration"; return(0); @@ -33,7 +33,7 @@ class ntlm_sasl_client_class Function ASCIIToUnicode($ascii) { - for($unicode="",$a=0;$aASCIIToUnicode($password); - $md4=hash("md4", $unicode); + $md4=hash("md4", $unicode); $padded=$md4.str_repeat(chr(0),21-strlen($md4)); $iv_size=mcrypt_get_iv_size(MCRYPT_DES,MCRYPT_MODE_ECB); $iv=mcrypt_create_iv($iv_size,MCRYPT_RAND); - for($response="",$third=0;$third<21;$third+=7) + for ($response="",$third=0;$third<21;$third+=7) { - for($packed="",$p=$third;$p<$third+7;$p++) - $packed.=str_pad(decbin(ord(substr($padded,$p,1))),8,"0",STR_PAD_LEFT); - for($key="",$p=0;$pstate!=SASL_NTLM_STATE_START) + if ($this->state!=SASL_NTLM_STATE_START) { $client->error="NTLM authentication state is not at the start"; return(SASL_FAIL); @@ -147,7 +147,7 @@ class ntlm_sasl_client_class ); $defaults=array(); $status=$client->GetCredentials($this->credentials,$defaults,$interactions); - if($status==SASL_CONTINUE) + if ($status==SASL_CONTINUE) $this->state=SASL_NTLM_STATE_IDENTIFY_DOMAIN; Unset($message); return($status); @@ -155,7 +155,7 @@ class ntlm_sasl_client_class Function Step(&$client, $response, &$message, &$interactions) { - switch($this->state) + switch ($this->state) { case SASL_NTLM_STATE_IDENTIFY_DOMAIN: $message=$this->TypeMsg1($this->credentials["realm"],$this->credentials["workstation"]); diff --git a/etc/inc/openvpn.attributes.php b/etc/inc/openvpn.attributes.php index 8a04ca41c7..467d69130d 100644 --- a/etc/inc/openvpn.attributes.php +++ b/etc/inc/openvpn.attributes.php @@ -1,7 +1,7 @@ if (file_exists("{$g['varetc_path']}/openvpn/{$modeid}.ca")) { @@ -145,12 +147,14 @@ if (!is_array($authmodes)) { $attributes = array(); foreach ($authmodes as $authmode) { $authcfg = auth_get_authserver($authmode); - if (!$authcfg && $authmode != "local") + if (!$authcfg && $authmode != "local") { continue; + } $authenticated = authenticate_user($username, $password, $authcfg, $attributes); - if ($authenticated == true) + if ($authenticated == true) { break; + } } if ($authenticated == false) { @@ -165,42 +169,47 @@ if ($authenticated == false) { } } -if (file_exists("/etc/inc/openvpn.attributes.php")) - include_once("/etc/inc/openvpn.attributes.php"); - +if (file_exists("/etc/inc/openvpn.attributes.php")) { + include_once("/etc/inc/openvpn.attributes.php"); +} + $content = ""; if (is_array($attributes['dns-servers'])) { - foreach ($attributes['dns-servers'] as $dnssrv) { - if (is_ipaddr($dnssrv)) - $content .= "push \"dhcp-option DNS {$dnssrv}\"\n"; - } + foreach ($attributes['dns-servers'] as $dnssrv) { + if (is_ipaddr($dnssrv)) { + $content .= "push \"dhcp-option DNS {$dnssrv}\"\n"; + } + } } if (is_array($attributes['routes'])) { - foreach ($attributes['routes'] as $route) + foreach ($attributes['routes'] as $route) { $content .= "push \"route {$route} vpn_gateway\"\n"; + } } if (isset($attributes['framed_ip'])) { /* XXX: only use when TAP windows driver >= 8.2.x */ -/* if (isset($attributes['framed_mask'])) { - $content .= "topology subnet\n"; - $content .= "ifconfig-push {$attributes['framed_ip']} {$attributes['framed_mask']}"; - } else { +/* if (isset($attributes['framed_mask'])) { + $content .= "topology subnet\n"; + $content .= "ifconfig-push {$attributes['framed_ip']} {$attributes['framed_mask']}"; + } else { */ - $content .= "topology net30\n"; - $content .= "ifconfig-push {$attributes['framed_ip']} ". long2ip((ip2long($attributes['framed_ip']) + 1)); -// } + $content .= "topology net30\n"; + $content .= "ifconfig-push {$attributes['framed_ip']} ". long2ip((ip2long($attributes['framed_ip']) + 1)); +// } +} + +if (!empty($content)) { + @file_put_contents("{$g['tmp_path']}/{$username}", $content); } - -if (!empty($content)) - @file_put_contents("{$g['tmp_path']}/{$username}", $content); syslog(LOG_NOTICE, "user '{$username}' authenticated\n"); closelog(); -if (isset($_GET['username'])) +if (isset($_GET['username'])) { echo "OK"; -else +} else { return (0); +} ?> diff --git a/etc/inc/openvpn.tls-verify.php b/etc/inc/openvpn.tls-verify.php index 9fd896b29a..023ec19d2c 100644 --- a/etc/inc/openvpn.tls-verify.php +++ b/etc/inc/openvpn.tls-verify.php @@ -31,7 +31,7 @@ */ /* - pfSense_BUILDER_BINARIES: + pfSense_BUILDER_BINARIES: pfSense_MODULE: openvpn */ /* @@ -63,8 +63,9 @@ if (isset($_GET['certdepth'])) { $subj = explode("/", $cert_subject); foreach ($subj at $s) { list($n, $v) = explode("=", $s); - if ($n == "CN") + if ($n == "CN") { $common_name = $v; + } } */ @@ -87,9 +88,10 @@ if (isset($allowed_depth) && ($cert_depth > $allowed_depth)) { //syslog(LOG_WARNING, "Found certificate {$argv[2]} with depth {$cert_depth}\n"); closelog(); -if (isset($_GET['certdepth'])) +if (isset($_GET['certdepth'])) { echo "OK"; -else +} else { exit(0); +} ?> diff --git a/etc/inc/plain_sasl_client.inc b/etc/inc/plain_sasl_client.inc index c7feed029b..691580ce9b 100644 --- a/etc/inc/plain_sasl_client.inc +++ b/etc/inc/plain_sasl_client.inc @@ -26,7 +26,7 @@ class plain_sasl_client_class Function Start(&$client, &$message, &$interactions) { - if($this->state!=SASL_PLAIN_STATE_START) + if ($this->state!=SASL_PLAIN_STATE_START) { $client->error="PLAIN authentication state is not at the start"; return(SASL_FAIL); @@ -42,9 +42,9 @@ class plain_sasl_client_class "mode"=>"" ); $status=$client->GetCredentials($this->credentials,$defaults,$interactions); - if($status==SASL_CONTINUE) + if ($status==SASL_CONTINUE) { - switch($this->credentials["mode"]) + switch ($this->credentials["mode"]) { case SASL_PLAIN_EXIM_MODE: $message=$this->credentials["user"]."\0".$this->credentials["password"]."\0"; @@ -65,11 +65,11 @@ class plain_sasl_client_class Function Step(&$client, $response, &$message, &$interactions) { - switch($this->state) + switch ($this->state) { /* case SASL_PLAIN_STATE_IDENTIFY: - switch($this->credentials["mode"]) + switch ($this->credentials["mode"]) { case SASL_PLAIN_EXIM_MODE: $message=$this->credentials["user"]."\0".$this->credentials["password"]."\0"; diff --git a/etc/inc/priv.inc b/etc/inc/priv.inc index 8d1a736223..ee6e8766c4 100644 --- a/etc/inc/priv.inc +++ b/etc/inc/priv.inc @@ -49,46 +49,57 @@ require_once("priv.defs.inc"); /* Load and process custom privs. */ function get_priv_files($directory) { $dir_array = array(); - if(!is_dir($directory)) + if (!is_dir($directory)) { return; + } if ($dh = opendir($directory)) { while (($file = readdir($dh)) !== false) { $canadd = 0; - if($file == ".") + if ($file == ".") { $canadd = 1; - if($file == "..") + } + if ($file == "..") { $canadd = 1; - if($canadd == 0) + } + if ($canadd == 0) { array_push($dir_array, $file); + } } closedir($dh); } - if(!is_array($dir_array)) + if (!is_array($dir_array)) { return; + } return $dir_array; } // Load and sort privs $dir_array = get_priv_files("/etc/inc/priv"); -foreach ($dir_array as $file) - if (!is_dir("/etc/inc/priv/{$file}") && stristr($file,".inc")) +foreach ($dir_array as $file) { + if (!is_dir("/etc/inc/priv/{$file}") && stristr($file,".inc")) { include("/etc/inc/priv/{$file}"); -if(is_dir("/usr/local/pkg/priv")) { + } +} +if (is_dir("/usr/local/pkg/priv")) { $dir_array = get_priv_files("/usr/local/pkg/priv"); - foreach ($dir_array as $file) - if (!is_dir("/usr/local/pkg/priv/{$file}") && stristr($file,".inc")) + foreach ($dir_array as $file) { + if (!is_dir("/usr/local/pkg/priv/{$file}") && stristr($file,".inc")) { include("/usr/local/pkg/priv/{$file}"); + } + } } -if(is_array($priv_list)) +if (is_array($priv_list)) { sort_privs($priv_list); +} function cmp_privkeys($a, $b) { /* user privs at the top */ $auser = strncmp("user-", $a, 5); $buser = strncmp("user-", $b, 5); - if($auser != $buser) + if ($auser != $buser) { return $auser - $buser; + } /* name compare others */ return strcasecmp($a, $b); @@ -103,27 +114,31 @@ function cmp_page_matches($page, & $matches, $fullwc = true) { // $dbg_matches = implode(",", $matches); // log_error("debug: checking page {$page} match with {$dbg_matches}"); - if (!is_array($matches)) + if (!is_array($matches)) { return false; + } /* skip any leading fwdslash */ $test = strpos($page, "/"); - if ($test !== false && $test == 0) + if ($test !== false && $test == 0) { $page = substr($page, 1); + } /* look for a match */ foreach ($matches as $match) { /* possibly ignore full wildcard match */ - if (!$fullwc && !strcmp($match ,"*")) + if (!$fullwc && !strcmp($match ,"*")) { continue; + } /* compare exact or wildcard match */ $match = str_replace(array(".", "*","?"), array("\.", ".*","\?"), $match); $result = preg_match("@^/{$match}$@", "/{$page}"); - - if ($result) + + if ($result) { return true; + } } return false; @@ -133,13 +148,16 @@ function map_page_privname($page) { global $priv_list; foreach ($priv_list as $pname => $pdata) { - if (strncmp($pname, "page-", 5)) + if (strncmp($pname, "page-", 5)) { continue; + } $fullwc = false; - if (!strcasecmp($page,"any")||!strcmp($page,"*")) + if (!strcasecmp($page,"any")||!strcmp($page,"*")) { $fullwc = true; - if (cmp_page_matches($page, $pdata['match'], $fullwc)) + } + if (cmp_page_matches($page, $pdata['match'], $fullwc)) { return $pname; + } } return false; @@ -151,30 +169,36 @@ function get_user_privdesc(& $user) { $privs = array(); $user_privs = $user['priv']; - if (!is_array($user_privs)) + if (!is_array($user_privs)) { $user_privs = array(); + } $names = local_user_get_groups($user, true); foreach ($names as $name) { $group = getGroupEntry($name); $group_privs = $group['priv']; - if (!is_array($group_privs)) + if (!is_array($group_privs)) { continue; + } foreach ($group_privs as $pname) { - if (in_array($pname,$user_privs)) + if (in_array($pname,$user_privs)) { continue; - if (!$priv_list[$pname]) + } + if (!$priv_list[$pname]) { continue; + } $priv = $priv_list[$pname]; $priv['group'] = $group['name']; $privs[] = $priv; } } - foreach ($user_privs as $pname) - if($priv_list[$pname]) + foreach ($user_privs as $pname) { + if ($priv_list[$pname]) { $privs[] = $priv_list[$pname]; + } + } return $privs; } @@ -182,19 +206,24 @@ function get_user_privdesc(& $user) { function isAllowed($username, $page) { global $_SESSION; - if (!isset($username)) + if (!isset($username)) { return false; + } /* admin/root access check */ $user = getUserEntry($username); - if (isset($user)) - if (isset($user['uid'])) - if ($user['uid']==0) + if (isset($user)) { + if (isset($user['uid'])) { + if ($user['uid']==0) { return true; + } + } + } /* user privilege access check */ - if (cmp_page_matches($page, $_SESSION['page-match'])) + if (cmp_page_matches($page, $_SESSION['page-match'])) { return true; + } return false; } @@ -206,15 +235,19 @@ function isAllowedPage($page) { $username = $_SESSION['Username']; - if (!isset($username)) + if (!isset($username)) { return false; + } /* admin/root access check */ $user = getUserEntry($username); - if (isset($user)) - if (isset($user['uid'])) - if ($user['uid']==0) + if (isset($user)) { + if (isset($user['uid'])) { + if ($user['uid']==0) { return true; + } + } + } /* user privilege access check */ return cmp_page_matches($page, $_SESSION['page-match']); @@ -223,51 +256,61 @@ function isAllowedPage($page) { function getPrivPages(& $entry, & $allowed_pages) { global $priv_list; - if (!is_array($entry['priv'])) + if (!is_array($entry['priv'])) { return; + } foreach ($entry['priv'] as $pname) { - if (strncmp($pname, "page-", 5)) + if (strncmp($pname, "page-", 5)) { continue; + } $priv = &$priv_list[$pname]; - if (!is_array($priv)) + if (!is_array($priv)) { continue; + } $matches = &$priv['match']; - if (!is_array($matches)) + if (!is_array($matches)) { continue; - foreach ($matches as $match) + } + foreach ($matches as $match) { $allowed_pages[] = $match; + } } } function getAllowedPages($username) { global $config, $_SESSION; - if (!function_exists("ldap_connect")) + if (!function_exists("ldap_connect")) { return; - + } + $allowed_pages = array(); $allowed_groups = array(); - + $authcfg = auth_get_authserver($config['system']['webgui']['authmode']); // obtain ldap groups if we are in ldap mode - if ($authcfg['type'] == "ldap") + if ($authcfg['type'] == "ldap") { $allowed_groups = @ldap_get_groups($username, $authcfg); - else { + } else { // search for a local user by name $local_user = getUserEntry($username); getPrivPages($local_user, $allowed_pages); // obtain local groups if we have a local user - if ($local_user) + if ($local_user) { $allowed_groups = local_user_get_groups($local_user); + } } // build a list of allowed pages - if (is_array($config['system']['group']) && is_array($allowed_groups)) - foreach ($config['system']['group'] as $group) - if (in_array($group['name'], $allowed_groups)) + if (is_array($config['system']['group']) && is_array($allowed_groups)) { + foreach ($config['system']['group'] as $group) { + if (in_array($group['name'], $allowed_groups)) { getPrivPages($group, $allowed_pages); + } + } + } // $dbg_pages = implode(",", $allowed_pages); // $dbg_groups = implode(",", $allowed_groups); From ef00af3c3a7d205a028404c863484d89b26169cf Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sat, 28 Feb 2015 14:46:21 +0545 Subject: [PATCH 143/257] Code style openvpn.inc --- etc/inc/openvpn.inc | 461 ++++++++++++++++++++++++++++---------------- 1 file changed, 291 insertions(+), 170 deletions(-) diff --git a/etc/inc/openvpn.inc b/etc/inc/openvpn.inc index 3bdb5a609e..99b039f4d1 100644 --- a/etc/inc/openvpn.inc +++ b/etc/inc/openvpn.inc @@ -85,7 +85,7 @@ $openvpn_verbosity_level = array( global $openvpn_dh_lengths; $openvpn_dh_lengths = array( - 1024, 2048, 4096 ); + 1024, 2048, 4096); global $openvpn_cert_depths; $openvpn_cert_depths = array( @@ -107,20 +107,21 @@ $openvpn_server_modes = array( global $openvpn_client_modes; $openvpn_client_modes = array( 'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"), - 'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )") ); + 'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )")); global $openvpn_compression_modes; $openvpn_compression_modes = array( - '' => gettext("No Preference"), - 'no' => gettext("Disabled - No Compression"), - 'adaptive' => gettext("Enabled with Adaptive Compression"), - 'yes' => gettext("Enabled without Adaptive Compression")); + '' => gettext("No Preference"), + 'no' => gettext("Disabled - No Compression"), + 'adaptive' => gettext("Enabled with Adaptive Compression"), + 'yes' => gettext("Enabled without Adaptive Compression")); function openvpn_create_key() { $fp = popen("/usr/local/sbin/openvpn --genkey --secret /dev/stdout 2>/dev/null", "r"); - if (!$fp) + if (!$fp) { return false; + } $rslt = stream_get_contents($fp); pclose($fp); @@ -131,8 +132,9 @@ function openvpn_create_key() { function openvpn_create_dhparams($bits) { $fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r"); - if (!$fp) + if (!$fp) { return false; + } $rslt = stream_get_contents($fp); pclose($fp); @@ -143,15 +145,21 @@ function openvpn_create_dhparams($bits) { function openvpn_vpnid_used($vpnid) { global $config; - if (is_array($config['openvpn']['openvpn-server'])) - foreach ($config['openvpn']['openvpn-server'] as & $settings) - if ($vpnid == $settings['vpnid']) + if (is_array($config['openvpn']['openvpn-server'])) { + foreach ($config['openvpn']['openvpn-server'] as & $settings) { + if ($vpnid == $settings['vpnid']) { return true; + } + } + } - if (is_array($config['openvpn']['openvpn-client'])) - foreach ($config['openvpn']['openvpn-client'] as & $settings) - if ($vpnid == $settings['vpnid']) + if (is_array($config['openvpn']['openvpn-client'])) { + foreach ($config['openvpn']['openvpn-client'] as & $settings) { + if ($vpnid == $settings['vpnid']) { return true; + } + } + } return false; } @@ -159,8 +167,9 @@ function openvpn_vpnid_used($vpnid) { function openvpn_vpnid_next() { $vpnid = 1; - while(openvpn_vpnid_used($vpnid)) + while (openvpn_vpnid_used($vpnid)) { $vpnid++; + } return $vpnid; } @@ -170,29 +179,35 @@ function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) { if (is_array($config['openvpn']['openvpn-server'])) { foreach ($config['openvpn']['openvpn-server'] as & $settings) { - if (isset($settings['disable'])) + if (isset($settings['disable'])) { continue; + } - if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) + if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) { continue; + } if ($port == $settings['local_port'] && $prot == $settings['protocol'] && - ($interface == $settings['interface'] || $interface == "any" || $settings['interface'] == "any")) + ($interface == $settings['interface'] || $interface == "any" || $settings['interface'] == "any")) { return $settings['vpnid']; + } } } if (is_array($config['openvpn']['openvpn-client'])) { foreach ($config['openvpn']['openvpn-client'] as & $settings) { - if (isset($settings['disable'])) + if (isset($settings['disable'])) { continue; + } - if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) + if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) { continue; + } if ($port == $settings['local_port'] && $prot == $settings['protocol'] && - ($interface == $settings['interface'] || $interface == "any" || $settings['interface'] == "any")) + ($interface == $settings['interface'] || $interface == "any" || $settings['interface'] == "any")) { return $settings['vpnid']; + } } } @@ -202,10 +217,12 @@ function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) { function openvpn_port_next($prot, $interface = "wan") { $port = 1194; - while(openvpn_port_used($prot, $interface, $port)) + while (openvpn_port_used($prot, $interface, $port)) { $port++; - while(openvpn_port_used($prot, "any", $port)) + } + while (openvpn_port_used($prot, "any", $port)) { $port++; + } return $port; } @@ -252,19 +269,25 @@ function openvpn_get_engines() { $linematch = array(); preg_match("/\((.*)\)\s(.*)/", $engine, $linematch); foreach ($details as $dt) { - if (strpos($dt, "unavailable") !== FALSE) + if (strpos($dt, "unavailable") !== FALSE) { $keep = false; - if (strpos($dt, "available") !== FALSE) + } + if (strpos($dt, "available") !== FALSE) { continue; - if (strpos($dt, "[") !== FALSE) + } + if (strpos($dt, "[") !== FALSE) { $ciphers = trim($dt, "[]"); + } } - if (!empty($ciphers)) + if (!empty($ciphers)) { $ciphers = " - " . $ciphers; - if (strlen($ciphers) > 60) + } + if (strlen($ciphers) > 60) { $ciphers = substr($ciphers, 0, 60) . " ... "; - if ($keep) + } + if ($keep) { $openssl_engines[$linematch[1]] = $linematch[2] . $ciphers; + } } return $openssl_engines; } @@ -276,49 +299,57 @@ function openvpn_validate_engine($engine) { function openvpn_validate_host($value, $name) { $value = trim($value); - if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) + if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) { return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name); + } return false; } function openvpn_validate_port($value, $name) { $value = trim($value); - if (empty($value) || !is_numeric($value) || $value < 0 || ($value > 65535)) + if (empty($value) || !is_numeric($value) || $value < 0 || ($value > 65535)) { return sprintf(gettext("The field '%s' must contain a valid port, ranging from 0 to 65535."), $name); + } return false; } function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") { $value = trim($value); $error = false; - if (empty($value)) + if (empty($value)) { return false; + } $networks = explode(',', $value); - if (!$multiple && (count($networks) > 1)) + if (!$multiple && (count($networks) > 1)) { return sprintf(gettext("The field '%s' must contain a single valid %s CIDR range."), $name, $ipproto); - - foreach ($networks as $network) { - if ($ipproto == "ipv4") - $error = !openvpn_validate_cidr_ipv4($network); - else - $error = !openvpn_validate_cidr_ipv6($network); - if ($error) - break; } - if ($error) + foreach ($networks as $network) { + if ($ipproto == "ipv4") { + $error = !openvpn_validate_cidr_ipv4($network); + } else { + $error = !openvpn_validate_cidr_ipv6($network); + } + if ($error) { + break; + } + } + + if ($error) { return sprintf(gettext("The field '%s' must contain only valid %s CIDR range(s) separated by commas."), $name, $ipproto); - else + } else { return false; + } } function openvpn_validate_cidr_ipv4($value) { $value = trim($value); if (!empty($value)) { list($ip, $mask) = explode('/', $value); - if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) + if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) { return false; + } } return true; } @@ -327,54 +358,70 @@ function openvpn_validate_cidr_ipv6($value) { $value = trim($value); if (!empty($value)) { list($ipv6, $prefix) = explode('/', $value); - if (empty($prefix)) + if (empty($prefix)) { $prefix = "128"; - if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) + } + if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) { return false; + } } return true; } function openvpn_add_dhcpopts(& $settings, & $conf) { - if (!empty($settings['dns_domain'])) + if (!empty($settings['dns_domain'])) { $conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n"; + } - if (!empty($settings['dns_server1'])) + if (!empty($settings['dns_server1'])) { $conf .= "push \"dhcp-option DNS {$settings['dns_server1']}\"\n"; - if (!empty($settings['dns_server2'])) + } + if (!empty($settings['dns_server2'])) { $conf .= "push \"dhcp-option DNS {$settings['dns_server2']}\"\n"; - if (!empty($settings['dns_server3'])) + } + if (!empty($settings['dns_server3'])) { $conf .= "push \"dhcp-option DNS {$settings['dns_server3']}\"\n"; - if (!empty($settings['dns_server4'])) + } + if (!empty($settings['dns_server4'])) { $conf .= "push \"dhcp-option DNS {$settings['dns_server4']}\"\n"; + } - if (!empty($settings['push_register_dns'])) + if (!empty($settings['push_register_dns'])) { $conf .= "push \"register-dns\"\n"; + } - if (!empty($settings['ntp_server1'])) + if (!empty($settings['ntp_server1'])) { $conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n"; - if (!empty($settings['ntp_server2'])) + } + if (!empty($settings['ntp_server2'])) { $conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n"; + } if ($settings['netbios_enable']) { - if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) + if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) { $conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n"; - if (!empty($settings['dhcp_nbtscope'])) + } + if (!empty($settings['dhcp_nbtscope'])) { $conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n"; + } - if (!empty($settings['wins_server1'])) + if (!empty($settings['wins_server1'])) { $conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n"; - if (!empty($settings['wins_server2'])) + } + if (!empty($settings['wins_server2'])) { $conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n"; + } - if (!empty($settings['nbdd_server1'])) + if (!empty($settings['nbdd_server1'])) { $conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n"; + } } - if ($settings['gwredir']) + if ($settings['gwredir']) { $conf .= "push \"redirect-gateway def1\"\n"; + } } function openvpn_add_custom(& $settings, & $conf) { @@ -384,10 +431,12 @@ function openvpn_add_custom(& $settings, & $conf) { $options = explode(';', $settings['custom_options']); if (is_array($options)) { - foreach ($options as $option) + foreach ($options as $option) { $conf .= "$option\n"; - } else + } + } else { $conf .= "{$settings['custom_options']}\n"; + } } } @@ -407,10 +456,12 @@ function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") function openvpn_reconfigure($mode, $settings) { global $g, $config; - if (empty($settings)) + if (empty($settings)) { return; - if (isset($settings['disable'])) + } + if (isset($settings['disable'])) { return; + } openvpn_create_dirs(); /* * NOTE: Deleting tap devices causes spontaneous reboots. Instead, @@ -421,24 +472,27 @@ function openvpn_reconfigure($mode, $settings) { $vpnid = $settings['vpnid']; $mode_id = $mode.$vpnid; - if (isset($settings['dev_mode'])) + if (isset($settings['dev_mode'])) { $tunname = "{$settings['dev_mode']}{$vpnid}"; - else { /* defaults to tun */ + } else { + /* defaults to tun */ $tunname = "tun{$vpnid}"; $settings['dev_mode'] = "tun"; } - if ($mode == "server") + if ($mode == "server") { $devname = "ovpns{$vpnid}"; - else + } else { $devname = "ovpnc{$vpnid}"; + } /* is our device already configured */ if (!does_interface_exist($devname)) { /* create the tap device if required */ - if (!file_exists("/dev/{$tunname}")) + if (!file_exists("/dev/{$tunname}")) { exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create"); + } /* rename the device */ mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname)); @@ -448,15 +502,17 @@ function openvpn_reconfigure($mode, $settings) { $ifname = convert_real_interface_to_friendly_interface_name($devname); $grouptmp = link_interface_to_group($ifname); - if (!empty($grouptmp)) + if (!empty($grouptmp)) { array_walk($grouptmp, 'interface_group_add_member'); + } unset($grouptmp, $ifname); } $pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid"; $proto = strtolower($settings['protocol']); - if (substr($settings['protocol'], 0, 3) == "TCP") + if (substr($settings['protocol'], 0, 3) == "TCP") { $proto = "{$proto}-{$mode}"; + } $dev_mode = $settings['dev_mode']; $cipher = $settings['crypto']; // OpenVPN defaults to SHA1, so use it when unset to maintain compatibility. @@ -468,7 +524,7 @@ function openvpn_reconfigure($mode, $settings) { // If a specific ip address (VIP) is requested, use it. // Otherwise, if a specific interface is requested, use it - // If "any" interface was selected, local directive will be ommited. + // If "any" interface was selected, local directive will be omitted. if (is_ipaddrv4($ipaddr)) { $iface_ip=$ipaddr; } else { @@ -491,7 +547,7 @@ function openvpn_reconfigure($mode, $settings) { } $conf .= "dev-type {$settings['dev_mode']}\n"; - switch($settings['dev_mode']) { + switch ($settings['dev_mode']) { case "tun": if (!$settings['no_tun_ipv6']) { $conf .= "tun-ipv6\n"; @@ -514,7 +570,7 @@ function openvpn_reconfigure($mode, $settings) { $conf .= "up /usr/local/sbin/ovpn-linkup\n"; $conf .= "down /usr/local/sbin/ovpn-linkdown\n"; if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) { - switch($settings['mode']) { + switch ($settings['mode']) { case 'server_user': case 'server_tls_user': $conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n"; @@ -530,8 +586,9 @@ function openvpn_reconfigure($mode, $settings) { $conf .= "local {$iface_ipv6}\n"; } - if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) + if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) { $conf .= "engine {$settings['engine']}\n"; + } // server specific settings if ($mode == 'server') { @@ -541,7 +598,7 @@ function openvpn_reconfigure($mode, $settings) { $mask = gen_subnet_mask($cidr); // configure tls modes - switch($settings['mode']) { + switch ($settings['mode']) { case 'p2p_tls': case 'server_tls': case 'server_user': @@ -551,7 +608,7 @@ function openvpn_reconfigure($mode, $settings) { } // configure p2p/server modes - switch($settings['mode']) { + switch ($settings['mode']) { case 'p2p_tls': // If the CIDR is less than a /30, OpenVPN will complain if you try to // use the server directive. It works for a single client without it. @@ -559,23 +616,26 @@ function openvpn_reconfigure($mode, $settings) { if (!empty($ip) && !empty($mask) && ($cidr < 30)) { $conf .= "server {$ip} {$mask}\n"; $conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc\n"; - if(is_ipaddr($ipv6)) + if (is_ipaddr($ipv6)) { $conf .= "server-ipv6 {$ipv6}/{$prefix}\n"; + } } case 'p2p_shared_key': if (!empty($ip) && !empty($mask)) { list($ip1, $ip2) = openvpn_get_interface_ip($ip, $mask); - if ($settings['dev_mode'] == 'tun') + if ($settings['dev_mode'] == 'tun') { $conf .= "ifconfig {$ip1} {$ip2}\n"; - else + } else { $conf .= "ifconfig {$ip1} {$mask}\n"; + } } if (!empty($ipv6) && !empty($prefix)) { list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix); - if ($settings['dev_mode'] == 'tun') + if ($settings['dev_mode'] == 'tun') { $conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n"; - else + } else { $conf .= "ifconfig-ipv6 {$ipv6_1} {$prefix}\n"; + } } break; case 'server_tls': @@ -583,8 +643,9 @@ function openvpn_reconfigure($mode, $settings) { case 'server_tls_user': if (!empty($ip) && !empty($mask)) { $conf .= "server {$ip} {$mask}\n"; - if(is_ipaddr($ipv6)) + if (is_ipaddr($ipv6)) { $conf .= "server-ipv6 {$ipv6}/{$prefix}\n"; + } $conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc\n"; } else { if ($settings['serverbridge_dhcp']) { @@ -606,27 +667,30 @@ function openvpn_reconfigure($mode, $settings) { } // configure user auth modes - switch($settings['mode']) { + switch ($settings['mode']) { case 'server_user': $conf .= "client-cert-not-required\n"; case 'server_tls_user': /* username-as-common-name is not compatible with server-bridge */ - if (stristr($conf, "server-bridge") === false) + if (stristr($conf, "server-bridge") === false) { $conf .= "username-as-common-name\n"; + } if (!empty($settings['authmode'])) { $strictusercn = "false"; - if ($settings['strictusercn']) + if ($settings['strictusercn']) { $strictusercn = "true"; + } $conf .= "auth-user-pass-verify \"/usr/local/sbin/ovpn_auth_verify user '{$settings['authmode']}' {$strictusercn} {$mode_id}\" via-env\n"; } break; } - if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) + if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) { $settings['cert_depth'] = 1; + } if (is_numeric($settings['cert_depth'])) { - if (($mode == 'client') && empty($settings['certref'])) + if (($mode == 'client') && empty($settings['certref'])) { $cert = ""; - else { + } else { $cert = lookup_cert($settings['certref']); /* XXX: Seems not used at all! */ $servercn = urlencode(cert_get_cn($cert['crt'])); @@ -642,8 +706,9 @@ function openvpn_reconfigure($mode, $settings) { $conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n"; //$conf .= "management 127.0.0.1 {$settings['local_port']}\n"; - if ($settings['maxclients']) + if ($settings['maxclients']) { $conf .= "max-clients {$settings['maxclients']}\n"; + } // Can we push routes if ($settings['local_network']) { @@ -653,18 +718,20 @@ function openvpn_reconfigure($mode, $settings) { $conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true); } - switch($settings['mode']) { + switch ($settings['mode']) { case 'server_tls': case 'server_user': case 'server_tls_user': // Configure client dhcp options openvpn_add_dhcpopts($settings, $conf); - if ($settings['client2client']) + if ($settings['client2client']) { $conf .= "client-to-client\n"; + } break; } - if (isset($settings['duplicate_cn'])) + if (isset($settings['duplicate_cn'])) { $conf .= "duplicate-cn\n"; + } } // client specific settings @@ -672,7 +739,7 @@ function openvpn_reconfigure($mode, $settings) { if ($mode == 'client') { // configure p2p mode - switch($settings['mode']) { + switch ($settings['mode']) { case 'p2p_tls': $conf .= "tls-client\n"; case 'shared_key': @@ -683,12 +750,13 @@ function openvpn_reconfigure($mode, $settings) { // If there is no bind option at all (ip and/or port), add "nobind" directive // Otherwise, use the local port if defined, failing that, use lport 0 to // ensure a random source port. - if ((empty($iface_ip)) && (!$settings['local_port'])) + if ((empty($iface_ip)) && (!$settings['local_port'])) { $conf .= "nobind\n"; - elseif ($settings['local_port']) + } elseif ($settings['local_port']) { $conf .= "lport {$settings['local_port']}\n"; - else + } else { $conf .= "lport 0\n"; + } // Use unix socket to overcome the problem on any type of server $conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n"; @@ -696,26 +764,29 @@ function openvpn_reconfigure($mode, $settings) { // The remote server $conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n"; - if (!empty($settings['use_shaper'])) + if (!empty($settings['use_shaper'])) { $conf .= "shaper {$settings['use_shaper']}\n"; + } if (!empty($settings['tunnel_network'])) { list($ip, $mask) = explode('/', $settings['tunnel_network']); $mask = gen_subnet_mask($mask); list($ip1, $ip2) = openvpn_get_interface_ip($ip, $mask); - if ($settings['dev_mode'] == 'tun') + if ($settings['dev_mode'] == 'tun') { $conf .= "ifconfig {$ip2} {$ip1}\n"; - else + } else { $conf .= "ifconfig {$ip2} {$mask}\n"; + } } if (!empty($settings['tunnel_networkv6'])) { list($ipv6, $prefix) = explode('/', $settings['tunnel_networkv6']); list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix); - if ($settings['dev_mode'] == 'tun') + if ($settings['dev_mode'] == 'tun') { $conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n"; - else + } else { $conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n"; + } } if ($settings['auth_user'] && $settings['auth_pass']) { @@ -748,7 +819,7 @@ function openvpn_reconfigure($mode, $settings) { } // Write the settings for the keys - switch($settings['mode']) { + switch ($settings['mode']) { case 'p2p_shared_key': openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret"); break; @@ -764,33 +835,38 @@ function openvpn_reconfigure($mode, $settings) { openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert"); openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key"); } - if ($mode == 'server') + if ($mode == 'server') { $conf .= "dh {$g['etc_path']}/dh-parameters.{$settings['dh_length']}\n"; + } if (!empty($settings['crlref'])) { $crl = lookup_crl($settings['crlref']); crl_update($crl); openvpn_add_keyfile($crl['text'], $conf, $mode_id, "crl-verify"); } if ($settings['tls']) { - if ($mode == "server") + if ($mode == "server") { $tlsopt = 0; - else + } else { $tlsopt = 1; + } openvpn_add_keyfile($settings['tls'], $conf, $mode_id, "tls-auth", $tlsopt); } break; } - if (!empty($settings['compression'])) + if (!empty($settings['compression'])) { $conf .= "comp-lzo {$settings['compression']}\n"; + } - if ($settings['passtos']) + if ($settings['passtos']) { $conf .= "passtos\n"; + } - if ($settings['resolve_retry']) + if ($settings['resolve_retry']) { $conf .= "resolv-retry infinite\n"; - else if ($mode == 'client') + } else if ($mode == 'clie} nt') { $conf .= "resolv-retry infinite\n"; + } if ($settings['dynamic_ip']) { $conf .= "persist-remote-ip\n"; @@ -850,7 +926,7 @@ function openvpn_restart($mode, $settings) { /* wait until the process exits, or timeout and kill it */ $i = 0; - while(posix_kill($pid, 0)) { + while (posix_kill($pid, 0)) { usleep(250000); if ($i > 10) { log_error("OpenVPN ID $mode_id PID $pid still running, killing."); @@ -861,19 +937,22 @@ function openvpn_restart($mode, $settings) { } } - if (isset($settings['disable'])) + if (isset($settings['disable'])) { return; + } /* Do not start a client if we are a CARP backup on this vip! */ - if (($mode == "client") && (strstr($settings['interface'], "_vip") && get_carp_interface_status($settings['interface']) != "MASTER")) + if (($mode == "client") && (strstr($settings['interface'], "_vip") && get_carp_interface_status($settings['interface']) != "MASTER")) { return; + } /* Check if client is bound to a gateway group */ $a_groups = return_gateway_groups_array(); if (is_array($a_groups[$settings['interface']])) { - /* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */ - if (($a_groups[$settings['interface']][0]['vip'] <> "") && (get_carp_interface_status($a_groups[$settings['interface']][0]['vip']) != "MASTER")) + /* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */ + if (($a_groups[$settings['interface']][0]['vip'] <> "") && (get_carp_interface_status($a_groups[$settings['interface']][0]['vip']) != "MASTER")) { return; + } } /* start the new process */ @@ -881,8 +960,9 @@ function openvpn_restart($mode, $settings) { openvpn_clear_route($mode, $settings); mwexec_bg("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath)); - if (!platform_booting()) + if (!platform_booting()) { send_event("filter reload"); + } } function openvpn_delete($mode, & $settings) { @@ -891,16 +971,18 @@ function openvpn_delete($mode, & $settings) { $vpnid = $settings['vpnid']; $mode_id = $mode.$vpnid; - if (isset($settings['dev_mode'])) + if (isset($settings['dev_mode'])) { $tunname = "{$settings['dev_mode']}{$vpnid}"; - else { /* defaults to tun */ + } else { + /* defaults to tun */ $tunname = "tun{$vpnid}"; } - if ($mode == "server") + if ($mode == "server") { $devname = "ovpns{$vpnid}"; - else + } else { $devname = "ovpnc{$vpnid}"; + } /* kill the process if running */ $pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid"; @@ -926,11 +1008,13 @@ function openvpn_delete($mode, & $settings) { function openvpn_cleanup_csc($common_name) { global $g, $config; - if (empty($common_name)) + if (empty($common_name)) { return; + } $fpath = "{$g['varetc_path']}/openvpn-csc/" . basename($common_name); - if (is_file($fpath)) + if (is_file($fpath)) { unlink_if_exists($fpath); + } return; } @@ -946,11 +1030,13 @@ function openvpn_resync_csc(& $settings) { openvpn_create_dirs(); $conf = ''; - if ($settings['block']) + if ($settings['block']) { $conf .= "disable\n"; + } - if ($settings['push_reset']) + if ($settings['push_reset']) { $conf .= "push-reset\n"; + } if (!empty($settings['tunnel_network'])) { list($ip, $mask) = explode('/', $settings['tunnel_network']); @@ -958,10 +1044,11 @@ function openvpn_resync_csc(& $settings) { $serverip = long2ip32($baselong + 1); $clientip = long2ip32($baselong + 2); /* Because this is being pushed, the order from the client's point of view. */ - if ($settings['dev_mode'] != 'tap') + if ($settings['dev_mode'] != 'tap') { $conf .= "ifconfig-push {$clientip} {$serverip}\n"; - else + } else { $conf .= "ifconfig-push {$clientip} {$mask}\n"; + } } if ($settings['local_network']) { @@ -982,8 +1069,9 @@ function openvpn_resync_csc(& $settings) { openvpn_add_dhcpopts($settings, $conf); - if ($settings['gwredir']) + if ($settings['gwredir']) { $conf .= "push \"redirect-gateway def1\"\n"; + } openvpn_add_custom($settings, $conf); @@ -1009,12 +1097,14 @@ function openvpn_resync($mode, $settings) { function openvpn_resync_all($interface = "") { global $g, $config; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; + } openvpn_create_dirs(); - if (!is_array($config['openvpn'])) + if (!is_array($config['openvpn'])) { $config['openvpn'] = array(); + } /* if (!$config['openvpn']['dh-parameters']) { @@ -1032,30 +1122,35 @@ function openvpn_resync_all($interface = "") { file_put_contents($path_ovdh, $dh_parameters); } */ - if ($interface <> "") + if ($interface <> "") { log_error("Resyncing OpenVPN instances for interface " . convert_friendly_interface_to_friendly_descr($interface) . "."); - else + } else { log_error("Resyncing OpenVPN instances."); + } if (is_array($config['openvpn']['openvpn-server'])) { foreach ($config['openvpn']['openvpn-server'] as & $settings) { - if ($interface <> "" && $interface != $settings['interface']) + if ($interface <> "" && $interface != $settings['interface']) { continue; + } openvpn_resync('server', $settings); } } if (is_array($config['openvpn']['openvpn-client'])) { foreach ($config['openvpn']['openvpn-client'] as & $settings) { - if ($interface <> "" && $interface != $settings['interface']) + if ($interface <> "" && $interface != $settings['interface']) { continue; + } openvpn_resync('client', $settings); } } - if (is_array($config['openvpn']['openvpn-csc'])) - foreach ($config['openvpn']['openvpn-csc'] as & $settings) + if (is_array($config['openvpn']['openvpn-csc'])) { + foreach ($config['openvpn']['openvpn-csc'] as & $settings) { openvpn_resync_csc($settings); + } + } } @@ -1084,8 +1179,9 @@ function openvpn_resync_gwgroup($gwgroupname = "") { // Note: no need to resysnc Client Specific (csc) here, as changes to the OpenVPN real interface do not effect these. - } else + } else { log_error("openvpn_resync_gwgroup called with null gwgroup parameter."); + } } function openvpn_get_active_servers($type="multipoint") { @@ -1094,8 +1190,9 @@ function openvpn_get_active_servers($type="multipoint") { $servers = array(); if (is_array($config['openvpn']['openvpn-server'])) { foreach ($config['openvpn']['openvpn-server'] as & $settings) { - if (empty($settings) || isset($settings['disable'])) + if (empty($settings) || isset($settings['disable'])) { continue; + } $prot = $settings['protocol']; $port = $settings['local_port']; @@ -1103,21 +1200,22 @@ function openvpn_get_active_servers($type="multipoint") { $server = array(); $server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194; $server['mode'] = $settings['mode']; - if ($settings['description']) + if ($settings['description']) { $server['name'] = "{$settings['description']} {$prot}:{$port}"; - else + } else { $server['name'] = "Server {$prot}:{$port}"; + } $server['conns'] = array(); $server['vpnid'] = $settings['vpnid']; $server['mgmt'] = "server{$server['vpnid']}"; $socket = "unix://{$g['varetc_path']}/openvpn/{$server['mgmt']}.sock"; list($tn, $sm) = explode('/', $settings['tunnel_network']); - if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30) ) && ($type == "p2p")) + if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) { $servers[] = openvpn_get_client_status($server, $socket); - elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) + } elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) { $servers[] = openvpn_get_server_status($server, $socket); - + } } } return $servers; @@ -1140,16 +1238,19 @@ function openvpn_get_server_status($server, $socket) { $line = fgets($fp, 1024); $info = stream_get_meta_data($fp); - if ($info['timed_out']) + if ($info['timed_out']) { break; + } /* parse header list line */ - if (strstr($line, "HEADER")) + if (strstr($line, "HEADER")) { continue; + } /* parse end of output line */ - if (strstr($line, "END") || strstr($line, "ERROR")) + if (strstr($line, "END") || strstr($line, "ERROR")) { break; + } /* parse client list line */ if (strstr($line, "CLIENT_LIST")) { @@ -1197,18 +1298,20 @@ function openvpn_get_active_clients() { if (is_array($config['openvpn']['openvpn-client'])) { foreach ($config['openvpn']['openvpn-client'] as & $settings) { - if (empty($settings) || isset($settings['disable'])) + if (empty($settings) || isset($settings['disable'])) { continue; + } $prot = $settings['protocol']; $port = ($settings['local_port']) ? ":{$settings['local_port']}" : ""; $client = array(); $client['port'] = $settings['local_port']; - if ($settings['description']) + if ($settings['description']) { $client['name'] = "{$settings['description']} {$prot}{$port}"; - else + } else { $client['name'] = "Client {$prot}{$port}"; + } $client['vpnid'] = $settings['vpnid']; $client['mgmt'] = "client{$client['vpnid']}"; @@ -1236,8 +1339,9 @@ function openvpn_get_client_status($client, $socket) { $line = fgets($fp, 1024); $info = stream_get_meta_data($fp); - if ($info['timed_out']) + if ($info['timed_out']) { break; + } /* Get the client state */ if (strstr($line,"CONNECTED")) { @@ -1266,8 +1370,9 @@ function openvpn_get_client_status($client, $socket) { $client['status'] .= "; " . $list[2]; } /* parse end of output line */ - if (strstr($line, "END") || strstr($line, "ERROR")) + if (strstr($line, "END") || strstr($line, "ERROR")) { break; + } } /* If up, get read/write stats */ @@ -1279,8 +1384,9 @@ function openvpn_get_client_status($client, $socket) { $line = fgets($fp, 1024); $info = stream_get_meta_data($fp); - if ($info['timed_out']) + if ($info['timed_out']) { break; + } if (strstr($line,"TCP/UDP read bytes")) { $list = explode(",", $line); @@ -1293,8 +1399,9 @@ function openvpn_get_client_status($client, $socket) { } /* parse end of output line */ - if (strstr($line, "END")) + if (strstr($line, "END")) { break; + } } } @@ -1318,12 +1425,14 @@ function openvpn_refresh_crls() { if (is_array($config['openvpn']['openvpn-server'])) { foreach ($config['openvpn']['openvpn-server'] as $settings) { - if (empty($settings)) + if (empty($settings)) { continue; - if (isset($settings['disable'])) + } + if (isset($settings['disable'])) { continue; + } // Write the settings for the keys - switch($settings['mode']) { + switch ($settings['mode']) { case 'p2p_tls': case 'server_tls': case 'server_tls_user': @@ -1343,10 +1452,12 @@ function openvpn_refresh_crls() { function openvpn_create_dirs() { global $g; - if (!is_dir("{$g['varetc_path']}/openvpn")) + if (!is_dir("{$g['varetc_path']}/openvpn")) { safe_mkdir("{$g['varetc_path']}/openvpn", 0750); - if (!is_dir("{$g['varetc_path']}/openvpn-csc")) + } + if (!is_dir("{$g['varetc_path']}/openvpn-csc")) { safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750); + } } function openvpn_get_interface_ip($ip, $mask) { @@ -1367,20 +1478,22 @@ function openvpn_get_interface_ipv6($ipv6, $prefix) { } function openvpn_clear_route($mode, $settings) { - if (empty($settings['tunnel_network'])) + if (empty($settings['tunnel_network'])) { return; + } list($ip, $cidr) = explode('/', $settings['tunnel_network']); $mask = gen_subnet_mask($cidr); $clear_route = false; - switch($settings['mode']) { + switch ($settings['mode']) { case 'shared_key': $clear_route = true; break; case 'p2p_tls': case 'p2p_shared_key': - if ($cidr == 30) + if ($cidr == 30) { $clear_route = true; + } break; } @@ -1394,20 +1507,23 @@ function openvpn_clear_route($mode, $settings) { function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) { $routes = ""; - if (empty($value)) + if (empty($value)) { return ""; + } $networks = explode(',', $value); foreach ($networks as $network) { - if ($ipproto == "ipv4") + if ($ipproto == "ipv4") { $route = openvpn_gen_route_ipv4($network, $iroute); - else + } else { $route = openvpn_gen_route_ipv6($network, $iroute); + } - if ($push) + if ($push) { $routes .= "push \"{$route}\"\n"; - else + } else { $routes .= "{$route}\n"; + } } return $routes; } @@ -1422,8 +1538,9 @@ function openvpn_gen_route_ipv4($network, $iroute = false) { function openvpn_gen_route_ipv6($network, $iroute = false) { $i = ($iroute) ? "i" : ""; list($ipv6, $prefix) = explode('/', trim($network)); - if (empty($prefix)) + if (empty($prefix)) { $prefix = "128"; + } return "{$i}route-ipv6 ${ipv6}/${prefix}"; } @@ -1432,21 +1549,25 @@ function openvpn_get_settings($mode, $vpnid) { if (is_array($config['openvpn']['openvpn-server'])) { foreach ($config['openvpn']['openvpn-server'] as $settings) { - if (isset($settings['disable'])) + if (isset($settings['disable'])) { continue; + } - if ($vpnid != 0 && $vpnid == $settings['vpnid']) + if ($vpnid != 0 && $vpnid == $settings['vpnid']) { return $settings; + } } } if (is_array($config['openvpn']['openvpn-client'])) { foreach ($config['openvpn']['openvpn-client'] as $settings) { - if (isset($settings['disable'])) + if (isset($settings['disable'])) { continue; + } - if ($vpnid != 0 && $vpnid == $settings['vpnid']) + if ($vpnid != 0 && $vpnid == $settings['vpnid']) { return $settings; + } } } From 472da675cc6f3899de35b03f9bfabeba39d8e6ca Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sat, 28 Feb 2015 18:41:39 +0545 Subject: [PATCH 144/257] Semi-colon went AWOL in dyndns.class after putting it back the code runs much better :) --- etc/inc/dyndns.class | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/dyndns.class b/etc/inc/dyndns.class index 50114aa436..686d8f22e4 100644 --- a/etc/inc/dyndns.class +++ b/etc/inc/dyndns.class @@ -355,7 +355,7 @@ $server = "https://dynupdate.no-ip.com/ducupdate.php"; $port = ""; if ($this->_dnsServer) { - $server = $this->_dnsServer + $server = $this->_dnsServer; } if ($this->_dnsPort) { $port = ":" . $this->_dnsPort; From 23a193dabc5f3c0f2c7db5dc173a4790938bc804 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sat, 28 Feb 2015 20:25:02 +0545 Subject: [PATCH 145/257] Code style for pfsense-utils --- etc/inc/pfsense-utils.inc | 1111 +++++++++++++++++++++---------------- 1 file changed, 633 insertions(+), 478 deletions(-) diff --git a/etc/inc/pfsense-utils.inc b/etc/inc/pfsense-utils.inc index 7fcb000ea8..88a156445b 100644 --- a/etc/inc/pfsense-utils.inc +++ b/etc/inc/pfsense-utils.inc @@ -1,37 +1,35 @@ real interface if needed */ $int_family = preg_split("/[0-9]+/", $int); $supported_ints = array('fxp'); if (in_array($int_family, $supported_ints)) { - if(does_interface_exist($int)) + if (does_interface_exist($int)) { pfSense_interface_flags($int, IFF_LINK0); + } } } /* This is mostly for vlans and ppp types */ $realhwif = get_parent_interface($interface); - if ($realhwif[0] == $int) + if ($realhwif[0] == $int) { hardware_offloading_applyflags($int); - else { + } else { hardware_offloading_applyflags($realhwif[0]); hardware_offloading_applyflags($int); } @@ -231,8 +242,9 @@ function enable_hardware_offloading($interface) { ******/ function interface_supports_polling($iface) { $opts = pfSense_get_interface_addresses($iface); - if (is_array($opts) && isset($opts['caps']['polling'])) + if (is_array($opts) && isset($opts['caps']['polling'])) { return true; + } return false; } @@ -250,27 +262,38 @@ function interface_supports_polling($iface) { function is_alias_inuse($alias) { global $g, $config; - if($alias == "") return false; + if ($alias == "") { + return false; + } /* loop through firewall rules looking for alias in use */ - if(is_array($config['filter']['rule'])) - foreach($config['filter']['rule'] as $rule) { - if($rule['source']['address']) - if($rule['source']['address'] == $alias) + if (is_array($config['filter']['rule'])) { + foreach ($config['filter']['rule'] as $rule) { + if ($rule['source']['address']) { + if ($rule['source']['address'] == $alias) { return true; - if($rule['destination']['address']) - if($rule['destination']['address'] == $alias) + } + } + if ($rule['destination']['address']) { + if ($rule['destination']['address'] == $alias) { return true; + } + } } + } /* loop through nat rules looking for alias in use */ - if(is_array($config['nat']['rule'])) - foreach($config['nat']['rule'] as $rule) { - if($rule['target'] && $rule['target'] == $alias) + if (is_array($config['nat']['rule'])) { + foreach ($config['nat']['rule'] as $rule) { + if ($rule['target'] && $rule['target'] == $alias) { return true; - if($rule['source']['address'] && $rule['source']['address'] == $alias) + } + if ($rule['source']['address'] && $rule['source']['address'] == $alias) { return true; - if($rule['destination']['address'] && $rule['destination']['address'] == $alias) + } + if ($rule['destination']['address'] && $rule['destination']['address'] == $alias) { return true; + } } + } return false; } @@ -287,13 +310,17 @@ function is_alias_inuse($alias) { function is_schedule_inuse($schedule) { global $g, $config; - if($schedule == "") return false; + if ($schedule == "") { + return false; + } /* loop through firewall rules looking for schedule in use */ - if(is_array($config['filter']['rule'])) - foreach($config['filter']['rule'] as $rule) { - if($rule['sched'] == $schedule) + if (is_array($config['filter']['rule'])) { + foreach ($config['filter']['rule'] as $rule) { + if ($rule['sched'] == $schedule) { return true; + } } + } return false; } @@ -310,17 +337,21 @@ function is_schedule_inuse($schedule) { function setup_polling() { global $g, $config; - if (isset($config['system']['polling'])) + if (isset($config['system']['polling'])) { set_single_sysctl("kern.polling.idle_poll", "1"); - else + } else { set_single_sysctl("kern.polling.idle_poll", "0"); + } - if($config['system']['polling_each_burst']) + if ($config['system']['polling_each_burst']) { set_single_sysctl("kern.polling.each_burst", $config['system']['polling_each_burst']); - if($config['system']['polling_burst_max']) + } + if ($config['system']['polling_burst_max']) { set_single_sysctl("kern.polling.burst_max", $config['system']['polling_burst_max']); - if($config['system']['polling_user_frac']) + } + if ($config['system']['polling_user_frac']) { set_single_sysctl("kern.polling.user_frac", $config['system']['polling_user_frac']); + } } /****f* pfsense-utils/setup_microcode @@ -338,8 +369,9 @@ function setup_microcode() { /* if list */ $iflist = get_configured_interface_list(false, true); - foreach($iflist as $if => $ifdescr) + foreach ($iflist as $if => $ifdescr) { enable_hardware_offloading($if); + } unset($iflist); } @@ -373,13 +405,16 @@ function get_carp_interface_status($carpinterface) { $interface = get_real_interface($interface); $carp_query = ''; $_gb = exec("/sbin/ifconfig $interface | /usr/bin/grep -v grep | /usr/bin/grep carp: | /usr/bin/head -n 1", $carp_query); - foreach($carp_query as $int) { - if (stripos($int, "MASTER")) + foreach ($carp_query as $int) { + if (stripos($int, "MASTER")) { return "MASTER"; - if (stripos($int, "BACKUP")) + } + if (stripos($int, "BACKUP")) { return "BACKUP"; - if (stripos($int, "INIT")) + } + if (stripos($int, "INIT")) { return "INIT"; + } } return; } @@ -388,8 +423,9 @@ function get_carp_interface_status($carpinterface) { * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync */ function get_pfsync_interface_status($pfsyncinterface) { - if (!does_interface_exist($pfsyncinterface)) + if (!does_interface_exist($pfsyncinterface)) { return; + } return exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'"); } @@ -406,8 +442,9 @@ function add_rule_to_anchor($anchor, $rule, $label) { * remove $text from file $file */ function remove_text_from_file($file, $text) { - if(!file_exists($file) && !is_writable($file)) + if (!file_exists($file) && !is_writable($file)) { return; + } $filecontents = file_get_contents($file); $text = str_replace($text, "", $filecontents); @file_put_contents($file, $text); @@ -418,12 +455,13 @@ function remove_text_from_file($file, $text) { * replaces the text if it already exists. */ function add_text_to_file($file, $text, $replace = false) { - if(file_exists($file) and is_writable($file)) { + if (file_exists($file) and is_writable($file)) { $filecontents = file($file); $filecontents = array_map('rtrim', $filecontents); array_push($filecontents, $text); - if ($replace) + if ($replace) { $filecontents = array_unique($filecontents); + } $file_text = implode("\n", $filecontents); @@ -441,13 +479,14 @@ function after_sync_bump_adv_skew() { $processed_skew = 1; $a_vip = &$config['virtualip']['vip']; foreach ($a_vip as $vipent) { - if($vipent['advskew'] <> "") { + if ($vipent['advskew'] <> "") { $processed_skew = 1; $vipent['advskew'] = $vipent['advskew']+1; } } - if($processed_skew == 1) + if ($processed_skew == 1) { write_config(gettext("After synch increase advertising skew")); + } } /* @@ -481,13 +520,15 @@ function WakeOnLan($addr, $mac) $addr_byte = explode(':', $mac); $hw_addr = ''; - for ($a=0; $a < 6; $a++) + for ($a=0; $a < 6; $a++) { $hw_addr .= chr(hexdec($addr_byte[$a])); + } $msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255); - for ($a = 1; $a <= 16; $a++) + for ($a = 1; $a <= 16; $a++) { $msg .= $hw_addr; + } // send it to the broadcast address using UDP $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); @@ -497,8 +538,9 @@ function WakeOnLan($addr, $mac) } else { // setting a broadcast option to socket: $opt_ret = socket_set_option($s, 1, 6, TRUE); - if($opt_ret < 0) + if ($opt_ret < 0) { log_error(sprintf(gettext("setsockopt() failed, error: %s"), strerror($opt_ret))); + } $e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050); socket_close($s); log_error(sprintf(gettext('Magic Packet sent (%1$s) to {%2$s} MAC=%3$s'), $e, $addr, $mac)); @@ -513,9 +555,10 @@ function WakeOnLan($addr, $mac) * Useful for finding paths and stripping file extensions. */ function reverse_strrchr($haystack, $needle) { - if (!is_string($haystack)) + if (!is_string($haystack)) { return; - return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false; + } + return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1) : false; } /* @@ -561,8 +604,9 @@ function restore_config_section($section_name, $new_contents) { return false; } $config[$section_name] = &$section_xml; - if(file_exists("{$g['tmp_path']}/config.cache")) + if (file_exists("{$g['tmp_path']}/config.cache")) { unlink("{$g['tmp_path']}/config.cache"); + } write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name)); disable_security_checks(); conf_mount_ro(); @@ -599,8 +643,9 @@ function merge_config_section($section_name, $new_contents) { function http_post($server, $port, $url, $vars) { $user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)"; $urlencoded = ""; - while (list($key,$value) = each($vars)) + while (list($key,$value) = each($vars)) { $urlencoded.= urlencode($key) . "=" . urlencode($value) . "&"; + } $urlencoded = substr($urlencoded,0,-1); $content_length = strlen($urlencoded); $headers = "POST $url HTTP/1.1 @@ -626,8 +671,9 @@ Content-Length: $content_length fputs($fp, $urlencoded); $ret = ""; - while (!feof($fp)) + while (!feof($fp)) { $ret.= fgets($fp, 1024); + } fclose($fp); return $ret; @@ -636,9 +682,9 @@ Content-Length: $content_length /* * php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors */ -if (!function_exists('php_check_syntax')){ +if (!function_exists('php_check_syntax')) { global $g; - function php_check_syntax($code_to_check, &$errormessage){ + function php_check_syntax($code_to_check, &$errormessage) { return false; $fout = fopen("{$g['tmp_path']}/codetocheck.php","w"); $code = $_POST['content']; @@ -664,8 +710,8 @@ if (!function_exists('php_check_syntax')){ /* * php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors */ -if (!function_exists('php_check_syntax')){ - function php_check_syntax($code_to_check, &$errormessage){ +if (!function_exists('php_check_syntax')) { + function php_check_syntax($code_to_check, &$errormessage) { return false; $command = "/usr/local/bin/php -l " . escapeshellarg($code_to_check); $output = exec_command($command); @@ -687,16 +733,19 @@ if (!function_exists('php_check_syntax')){ */ function rmdir_recursive($path,$follow_links=false) { $to_do = glob($path); - if(!is_array($to_do)) $to_do = array($to_do); - foreach($to_do as $workingdir) { // Handle wildcards by foreaching. - if(file_exists($workingdir)) { - if(is_dir($workingdir)) { + if (!is_array($to_do)) { + $to_do = array($to_do); + } + foreach ($to_do as $workingdir) { // Handle wildcards by foreaching. + if (file_exists($workingdir)) { + if (is_dir($workingdir)) { $dir = opendir($workingdir); while ($entry = readdir($dir)) { - if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry"))) + if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry"))) { unlink("$workingdir/$entry"); - elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..') + } elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..') { rmdir_recursive("$workingdir/$entry"); + } } closedir($dir); rmdir($workingdir); @@ -716,11 +765,12 @@ function call_pfsense_method($method, $params, $timeout = 0) { $xmlrpc_base_url = get_active_xml_rpc_base_url(); $xmlrpc_path = $g['xmlrpcpath']; - + $xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url); $ip = gethostbyname($xmlrpcfqdn); - if($ip == $xmlrpcfqdn) + if ($ip == $xmlrpcfqdn) { return false; + } $msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params))); $port = 0; @@ -728,27 +778,31 @@ function call_pfsense_method($method, $params, $timeout = 0) { $proxyport = 0; $proxyuser = ""; $proxypass = ""; - if (!empty($config['system']['proxyurl'])) + if (!empty($config['system']['proxyurl'])) { $proxyurl = $config['system']['proxyurl']; - if (!empty($config['system']['proxyport']) && is_numeric($config['system']['proxyport'])) + } + if (!empty($config['system']['proxyport']) && is_numeric($config['system']['proxyport'])) { $proxyport = $config['system']['proxyport']; - if (!empty($config['system']['proxyuser'])) + } + if (!empty($config['system']['proxyuser'])) { $proxyuser = $config['system']['proxyuser']; - if (!empty($config['system']['proxypass'])) + } + if (!empty($config['system']['proxypass'])) { $proxypass = $config['system']['proxypass']; + } $cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url, $port, $proxyurl, $proxyport, $proxyuser, $proxypass); // If the ALT PKG Repo has a username/password set, use it. - if($config['system']['altpkgrepo']['username'] && - $config['system']['altpkgrepo']['password']) { + if ($config['system']['altpkgrepo']['username'] && + $config['system']['altpkgrepo']['password']) { $username = $config['system']['altpkgrepo']['username']; $password = $config['system']['altpkgrepo']['password']; $cli->setCredentials($username, $password); } $resp = $cli->send($msg, $timeout); - if(!is_object($resp)) { + if (!is_object($resp)) { log_error(sprintf(gettext("XMLRPC communication error: %s"), $cli->errstr)); return false; - } elseif($resp->faultCode()) { + } elseif ($resp->faultCode()) { log_error(sprintf(gettext('XMLRPC request failed with error %1$s: %2$s'), $resp->faultCode(), $resp->faultString())); return false; } else { @@ -761,12 +815,13 @@ function call_pfsense_method($method, $params, $timeout = 0) { */ function check_firmware_version($tocheck = "all", $return_php = true) { global $g, $config; - + $xmlrpc_base_url = get_active_xml_rpc_base_url(); $xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url); $ip = gethostbyname($xmlrpcfqdn); - if($ip == $xmlrpcfqdn) + if ($ip == $xmlrpcfqdn) { return false; + } $version = php_uname('r'); $version = explode('-', $version); $rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))), @@ -777,19 +832,20 @@ function check_firmware_version($tocheck = "all", $return_php = true) { ); unset($version); - if($tocheck == "all") { + if ($tocheck == "all") { $params = $rawparams; } else { - foreach($tocheck as $check) { + foreach ($tocheck as $check) { $params['check'] = $rawparams['check']; $params['platform'] = $rawparams['platform']; } } - if($config['system']['firmware']['branch']) + if ($config['system']['firmware']['branch']) { $params['branch'] = $config['system']['firmware']['branch']; + } /* XXX: What is this method? */ - if(!($versions = call_pfsense_method('pfsense.get_firmware_version', $params))) { + if (!($versions = call_pfsense_method('pfsense.get_firmware_version', $params))) { return false; } else { $versions["current"] = $params; @@ -848,19 +904,22 @@ function strncpy(&$dst, $src, $length) { function reload_interfaces_sync() { global $config, $g; - if($g['debug']) + if ($g['debug']) { log_error(gettext("reload_interfaces_sync() is starting.")); + } /* parse config.xml again */ $config = parse_config(true); /* enable routing */ system_routing_enable(); - if($g['debug']) + if ($g['debug']) { log_error(gettext("Enabling system routing")); + } - if($g['debug']) + if ($g['debug']) { log_error(gettext("Cleaning up Interfaces")); + } /* set up interfaces */ interfaces_configure(); @@ -951,47 +1010,53 @@ function setup_serial_port($when="save", $path="") { $boot_config_file = "{$path}/boot.config"; $loader_conf_file = "{$path}/boot/loader.conf"; /* serial console - write out /boot.config */ - if(file_exists($boot_config_file)) + if (file_exists($boot_config_file)) { $boot_config = file_get_contents($boot_config_file); - else + } else { $boot_config = ""; + } $serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "115200"; if ($g['platform'] != "cdrom") { $boot_config_split = explode("\n", $boot_config); $fd = fopen($boot_config_file,"w"); - if($fd) { - foreach($boot_config_split as $bcs) { - if(stristr($bcs, "-D") || stristr($bcs, "-h")) { + if ($fd) { + foreach ($boot_config_split as $bcs) { + if (stristr($bcs, "-D") || stristr($bcs, "-h")) { /* DONT WRITE OUT, WE'LL DO IT LATER */ } else { - if($bcs <> "") + if ($bcs <> "") { fwrite($fd, "{$bcs}\n"); + } } } - if (($g['platform'] == "nanobsd") && !file_exists("/etc/nano_use_vga.txt")) + if (($g['platform'] == "nanobsd") && !file_exists("/etc/nano_use_vga.txt")) { fwrite($fd, "-S{$serialspeed} -h"); - else if (is_serial_enabled()) + } else if (is_serial_enabled()) { fwrite($fd, "-S{$serialspeed} -D"); + } fclose($fd); } /* serial console - write out /boot/loader.conf */ - if ($when == "upgrade") + if ($when == "upgrade") { system("echo \"Reading {$loader_conf_file}...\" >> /conf/upgrade_log.txt"); + } $boot_config = file_get_contents($loader_conf_file); $boot_config_split = explode("\n", $boot_config); - if(count($boot_config_split) > 0) { + if (count($boot_config_split) > 0) { $new_boot_config = array(); // Loop through and only add lines that are not empty, and which // do not contain a console directive. - foreach($boot_config_split as $bcs) - if(!empty($bcs) - && (stripos($bcs, "console") === false) - && (stripos($bcs, "boot_multicons") === false) - && (stripos($bcs, "boot_serial") === false) - && (stripos($bcs, "hw.usb.no_pf") === false)) + foreach ($boot_config_split as $bcs) { + if (!empty($bcs) && + (stripos($bcs, "console") === false) && + (stripos($bcs, "boot_multicons") === false) && + (stripos($bcs, "boot_serial") === false) && + (stripos($bcs, "hw.usb.no_pf") === false)) { $new_boot_config[] = $bcs; + } + } if (($g['platform'] == "nanobsd") && !file_exists("/etc/nano_use_vga.txt")) { $new_boot_config[] = 'boot_serial="YES"'; @@ -1028,19 +1093,21 @@ function setup_serial_port($when="save", $path="") { $console_type = 'al.Pc'; $serial_type = 'al.' . $serialspeed; } - foreach($ttys_split as $tty) { - if (stristr($tty, "ttyv0")) + foreach ($ttys_split as $tty) { + if (stristr($tty, "ttyv0")) { fwrite($fd, "ttyv0 \"/usr/libexec/getty {$console_type}\" cons25 on secure\n"); - else if (stristr($tty, "ttyu")) { + } else if (stristr($tty, "ttyu")) { $ttyn = substr($tty, 0, 5); fwrite($fd, "{$ttyn} \"/usr/libexec/getty {$serial_type}\" cons25 {$on_off} secure\n"); - } else + } else { fwrite($fd, $tty . "\n"); + } } unset($on_off, $console_type, $serial_type); fclose($fd); - if ($when != "upgrade") + if ($when != "upgrade") { reload_ttys(); + } conf_mount_ro(); return; @@ -1051,8 +1118,9 @@ function is_serial_enabled() { if (!isset($g['enableserial_force']) && !isset($config['system']['enableserial']) && - ($g['platform'] == "pfSense" || $g['platform'] == "cdrom" || file_exists("/etc/nano_use_vga.txt"))) + ($g['platform'] == "pfSense" || $g['platform'] == "cdrom" || file_exists("/etc/nano_use_vga.txt"))) { return false; + } return true; } @@ -1064,7 +1132,7 @@ function reload_ttys() { function print_value_list($list, $count = 10, $separator = ",") { $list = implode($separator, array_slice($list, 0, $count)); - if(count($list) < $count) { + if (count($list) < $count) { $list .= "."; } else { $list .= "..."; @@ -1076,12 +1144,14 @@ function print_value_list($list, $count = 10, $separator = ",") { function is_dhcp_server_enabled() { global $config; - if (!is_array($config['dhcpd'])) + if (!is_array($config['dhcpd'])) { return false; + } foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) { - if (isset($dhcpifconf['enable']) && !empty($config['interfaces'][$dhcpif])) + if (isset($dhcpifconf['enable']) && !empty($config['interfaces'][$dhcpif])) { return true; + } } return false; @@ -1093,17 +1163,20 @@ function is_dhcpv6_server_enabled() { if (is_array($config['interfaces'])) { foreach ($config['interfaces'] as $ifcfg) { - if (isset($ifcfg['enable']) && !empty($ifcfg['track6-interface'])) + if (isset($ifcfg['enable']) && !empty($ifcfg['track6-interface'])) { return true; + } } } - if (!is_array($config['dhcpdv6'])) + if (!is_array($config['dhcpdv6'])) { return false; + } foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) { - if (isset($dhcpv6ifconf['enable']) && !empty($config['interfaces'][$dhcpv6if])) + if (isset($dhcpv6ifconf['enable']) && !empty($config['interfaces'][$dhcpv6if])) { return true; + } } return false; @@ -1113,46 +1186,55 @@ function is_dhcpv6_server_enabled() { function is_radvd_enabled() { global $config; - if (!is_array($config['dhcpdv6'])) + if (!is_array($config['dhcpdv6'])) { $config['dhcpdv6'] = array(); + } $dhcpdv6cfg = $config['dhcpdv6']; $Iflist = get_configured_interface_list(); /* handle manually configured DHCP6 server settings first */ foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) { - if(!isset($config['interfaces'][$dhcpv6if]['enable'])) + if (!isset($config['interfaces'][$dhcpv6if]['enable'])) { continue; + } - if(!isset($dhcpv6ifconf['ramode'])) + if (!isset($dhcpv6ifconf['ramode'])) { $dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode']; + } - if($dhcpv6ifconf['ramode'] == "disabled") + if ($dhcpv6ifconf['ramode'] == "disabled") { continue; + } $ifcfgipv6 = get_interface_ipv6($dhcpv6if); - if(!is_ipaddrv6($ifcfgipv6)) + if (!is_ipaddrv6($ifcfgipv6)) { continue; + } return true; } /* handle DHCP-PD prefixes and 6RD dynamic interfaces */ foreach ($Iflist as $if => $ifdescr) { - if(!isset($config['interfaces'][$if]['track6-interface'])) + if (!isset($config['interfaces'][$if]['track6-interface'])) { continue; - if(!isset($config['interfaces'][$if]['enable'])) + } + if (!isset($config['interfaces'][$if]['enable'])) { continue; + } $ifcfgipv6 = get_interface_ipv6($if); - if(!is_ipaddrv6($ifcfgipv6)) + if (!is_ipaddrv6($ifcfgipv6)) { continue; + } $ifcfgsnv6 = get_interface_subnetv6($if); $subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6); - if(!is_ipaddrv6($subnetv6)) + if (!is_ipaddrv6($subnetv6)) { continue; + } return true; } @@ -1166,44 +1248,50 @@ function is_pppoe_server_enabled() { $pppoeenable = false; - if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe'])) + if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe'])) { return false; + } - foreach ($config['pppoes']['pppoe'] as $pppoes) - if ($pppoes['mode'] == 'server') + foreach ($config['pppoes']['pppoe'] as $pppoes) { + if ($pppoes['mode'] == 'server') { $pppoeenable = true; + } + } return $pppoeenable; } -function convert_seconds_to_hms($sec){ +function convert_seconds_to_hms($sec) { $min=$hrs=0; - if ($sec != 0){ + if ($sec != 0) { $min = floor($sec/60); $sec %= 60; } - if ($min != 0){ + if ($min != 0) { $hrs = floor($min/60); $min %= 60; } - if ($sec < 10) + if ($sec < 10) { $sec = "0".$sec; - if ($min < 10) + } + if ($min < 10) { $min = "0".$min; - if ($hrs < 10) + } + if ($hrs < 10) { $hrs = "0".$hrs; + } $result = $hrs.":".$min.":".$sec; return $result; } /* Compute the total uptime from the ppp uptime log file in the conf directory */ -function get_ppp_uptime($port){ - if (file_exists("/conf/{$port}.log")){ +function get_ppp_uptime($port) { + if (file_exists("/conf/{$port}.log")) { $saved_time = file_get_contents("/conf/{$port}.log"); $uptime_data = explode("\n",$saved_time); $sec=0; - foreach($uptime_data as $upt) { + foreach ($uptime_data as $upt) { $sec += substr($upt, 1 + strpos($upt, " ")); } return convert_seconds_to_hms($sec); @@ -1218,16 +1306,18 @@ function get_interface_info($ifdescr) { global $config, $g; $ifinfo = array(); - if (empty($config['interfaces'][$ifdescr])) + if (empty($config['interfaces'][$ifdescr])) { return; + } $ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if']; $ifinfo['if'] = get_real_interface($ifdescr); $chkif = $ifinfo['if']; $ifinfotmp = pfSense_get_interface_addresses($chkif); $ifinfo['status'] = $ifinfotmp['status']; - if (empty($ifinfo['status'])) + if (empty($ifinfo['status'])) { $ifinfo['status'] = "down"; + } $ifinfo['macaddr'] = $ifinfotmp['macaddr']; $ifinfo['mtu'] = $ifinfotmp['mtu']; $ifinfo['ipaddr'] = $ifinfotmp['ipaddr']; @@ -1235,8 +1325,9 @@ function get_interface_info($ifdescr) { $ifinfo['linklocal'] = get_interface_linklocal($ifdescr); $ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr); $ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr); - if (isset($ifinfotmp['link0'])) + if (isset($ifinfotmp['link0'])) { $link0 = "down"; + } $ifinfotmp = pfSense_get_interface_stats($chkif); // $ifinfo['inpkts'] = $ifinfotmp['inpkts']; // $ifinfo['outpkts'] = $ifinfotmp['outpkts']; @@ -1290,82 +1381,89 @@ function get_interface_info($ifdescr) { $ifconfiginfo = ""; $link_type = $config['interfaces'][$ifdescr]['ipaddr']; switch ($link_type) { - /* DHCP? -> see if dhclient is up */ - case "dhcp": - /* see if dhclient is up */ - if (find_dhclient_process($ifinfo['if']) != 0) - $ifinfo['dhcplink'] = "up"; - else - $ifinfo['dhcplink'] = "down"; - - break; - /* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */ - case "pppoe": - case "pptp": - case "l2tp": - if ($ifinfo['status'] == "up" && !isset($link0)) - /* get PPPoE link status for dial on demand */ - $ifinfo["{$link_type}link"] = "up"; - else - $ifinfo["{$link_type}link"] = "down"; - - break; - /* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */ - case "ppp": - if ($ifinfo['status'] == "up") - $ifinfo['ppplink'] = "up"; - else - $ifinfo['ppplink'] = "down" ; - - if (empty($ifinfo['status'])) - $ifinfo['status'] = "down"; - - if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) { - foreach ($config['ppps']['ppp'] as $pppid => $ppp) { - if ($config['interfaces'][$ifdescr]['if'] == $ppp['if']) - break; + /* DHCP? -> see if dhclient is up */ + case "dhcp": + /* see if dhclient is up */ + if (find_dhclient_process($ifinfo['if']) != 0) { + $ifinfo['dhcplink'] = "up"; + } else { + $ifinfo['dhcplink'] = "down"; } - } - $dev = $ppp['ports']; - if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev)) + break; - if (!file_exists($dev)) { - $ifinfo['nodevice'] = 1; - $ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?"); - } + /* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */ + case "pppoe": + case "pptp": + case "l2tp": + if ($ifinfo['status'] == "up" && !isset($link0)) { + /* get PPPoE link status for dial on demand */ + $ifinfo["{$link_type}link"] = "up"; + } else { + $ifinfo["{$link_type}link"] = "down"; + } - $usbmodemoutput = array(); - exec("usbconfig", $usbmodemoutput); - $mondev = "{$g['tmp_path']}/3gstats.{$ifdescr}"; - if(file_exists($mondev)) { - $cellstats = file($mondev); - /* skip header */ - $a_cellstats = explode(",", $cellstats[1]); - if(preg_match("/huawei/i", implode("\n", $usbmodemoutput))) { - $ifinfo['cell_rssi'] = huawei_rssi_to_string($a_cellstats[1]); - $ifinfo['cell_mode'] = huawei_mode_to_string($a_cellstats[2], $a_cellstats[3]); - $ifinfo['cell_simstate'] = huawei_simstate_to_string($a_cellstats[10]); - $ifinfo['cell_service'] = huawei_service_to_string(trim($a_cellstats[11])); + break; + /* PPP interface? -> get uptime for this session and cumulative uptime from the persistent log file in conf */ + case "ppp": + if ($ifinfo['status'] == "up") { + $ifinfo['ppplink'] = "up"; + } else { + $ifinfo['ppplink'] = "down" ; } - if(preg_match("/zte/i", implode("\n", $usbmodemoutput))) { - $ifinfo['cell_rssi'] = zte_rssi_to_string($a_cellstats[1]); - $ifinfo['cell_mode'] = zte_mode_to_string($a_cellstats[2], $a_cellstats[3]); - $ifinfo['cell_simstate'] = zte_simstate_to_string($a_cellstats[10]); - $ifinfo['cell_service'] = zte_service_to_string(trim($a_cellstats[11])); + + if (empty($ifinfo['status'])) { + $ifinfo['status'] = "down"; } - $ifinfo['cell_upstream'] = $a_cellstats[4]; - $ifinfo['cell_downstream'] = trim($a_cellstats[5]); - $ifinfo['cell_sent'] = $a_cellstats[6]; - $ifinfo['cell_received'] = trim($a_cellstats[7]); - $ifinfo['cell_bwupstream'] = $a_cellstats[8]; - $ifinfo['cell_bwdownstream'] = trim($a_cellstats[9]); - } - // Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over! - if (isset($ppp['uptime'])) - $ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")"; - break; - default: - break; + + if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) { + foreach ($config['ppps']['ppp'] as $pppid => $ppp) { + if ($config['interfaces'][$ifdescr]['if'] == $ppp['if']) { + break; + } + } + } + $dev = $ppp['ports']; + if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev)) { + break; + } + if (!file_exists($dev)) { + $ifinfo['nodevice'] = 1; + $ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?"); + } + + $usbmodemoutput = array(); + exec("usbconfig", $usbmodemoutput); + $mondev = "{$g['tmp_path']}/3gstats.{$ifdescr}"; + if (file_exists($mondev)) { + $cellstats = file($mondev); + /* skip header */ + $a_cellstats = explode(",", $cellstats[1]); + if (preg_match("/huawei/i", implode("\n", $usbmodemoutput))) { + $ifinfo['cell_rssi'] = huawei_rssi_to_string($a_cellstats[1]); + $ifinfo['cell_mode'] = huawei_mode_to_string($a_cellstats[2], $a_cellstats[3]); + $ifinfo['cell_simstate'] = huawei_simstate_to_string($a_cellstats[10]); + $ifinfo['cell_service'] = huawei_service_to_string(trim($a_cellstats[11])); + } + if (preg_match("/zte/i", implode("\n", $usbmodemoutput))) { + $ifinfo['cell_rssi'] = zte_rssi_to_string($a_cellstats[1]); + $ifinfo['cell_mode'] = zte_mode_to_string($a_cellstats[2], $a_cellstats[3]); + $ifinfo['cell_simstate'] = zte_simstate_to_string($a_cellstats[10]); + $ifinfo['cell_service'] = zte_service_to_string(trim($a_cellstats[11])); + } + $ifinfo['cell_upstream'] = $a_cellstats[4]; + $ifinfo['cell_downstream'] = trim($a_cellstats[5]); + $ifinfo['cell_sent'] = $a_cellstats[6]; + $ifinfo['cell_received'] = trim($a_cellstats[7]); + $ifinfo['cell_bwupstream'] = $a_cellstats[8]; + $ifinfo['cell_bwdownstream'] = trim($a_cellstats[9]); + } + // Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over! + if (isset($ppp['uptime'])) { + $ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")"; + } + break; + default: + break; } if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) { @@ -1378,7 +1476,7 @@ function get_interface_info($ifdescr) { unset($ifconfiginfo); exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo); $wifconfiginfo = array(); - if(is_interface_wireless($ifdescr)) { + if (is_interface_wireless($ifdescr)) { exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo); array_shift($wifconfiginfo); } @@ -1396,19 +1494,23 @@ function get_interface_info($ifdescr) { } if (preg_match("/status: (.*)$/", $ici, $matches)) { - if ($matches[1] != "active") + if ($matches[1] != "active") { $ifinfo['status'] = $matches[1]; - if($ifinfo['status'] == gettext("running")) + } + if ($ifinfo['status'] == gettext("running")) { $ifinfo['status'] = gettext("up"); + } } if (preg_match("/channel (\S*)/", $ici, $matches)) { $ifinfo['channel'] = $matches[1]; } if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) { - if ($matches[1][0] == '"') + if ($matches[1][0] == '"') { $ifinfo['ssid'] = substr($matches[1], 1, -1); - else + } + else { $ifinfo['ssid'] = $matches[1]; + } } if (preg_match("/laggproto (.*)$/", $ici, $matches)) { $ifinfo['laggproto'] = $matches[1]; @@ -1417,7 +1519,7 @@ function get_interface_info($ifdescr) { $ifinfo['laggport'][] = $matches[1]; } } - foreach($wifconfiginfo as $ici) { + foreach ($wifconfiginfo as $ici) { $elements = preg_split("/[ ]+/i", $ici); if ($elements[0] != "") { $ifinfo['bssid'] = $elements[0]; @@ -1428,7 +1530,6 @@ function get_interface_info($ifdescr) { if ($elements[4] != "") { $ifinfo['rssi'] = $elements[4]; } - } /* lookup the gateway */ if (interface_has_gateway($ifdescr)) { @@ -1439,15 +1540,15 @@ function get_interface_info($ifdescr) { $bridge = ""; $bridge = link_interface_to_bridge($ifdescr); - if($bridge) { + if ($bridge) { $bridge_text = `/sbin/ifconfig {$bridge}`; - if(stristr($bridge_text, "blocking") <> false) { + if (stristr($bridge_text, "blocking") <> false) { $ifinfo['bridge'] = "" . gettext("blocking") . " - " . gettext("check for ethernet loops"); $ifinfo['bridgeint'] = $bridge; - } else if(stristr($bridge_text, "learning") <> false) { + } else if (stristr($bridge_text, "learning") <> false) { $ifinfo['bridge'] = gettext("learning"); $ifinfo['bridgeint'] = $bridge; - } else if(stristr($bridge_text, "forwarding") <> false) { + } else if (stristr($bridge_text, "forwarding") <> false) { $ifinfo['bridge'] = gettext("forwarding"); $ifinfo['bridgeint'] = $bridge; } @@ -1467,36 +1568,37 @@ function get_uptime_sec() { $boottime = get_single_sysctl("kern.boottime"); preg_match("/sec = (\d+)/", $boottime, $matches); $boottime = $matches[1]; - if(intval($boottime) == 0) + if (intval($boottime) == 0) { return 0; + } $uptime = time() - $boottime; return $uptime; } function add_hostname_to_watch($hostname) { - if(!is_dir("/var/db/dnscache")) { + if (!is_dir("/var/db/dnscache")) { mkdir("/var/db/dnscache"); } $result = array(); - if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) { + if ((is_fqdn($hostname)) && (!is_ipaddr($hostname))) { $domrecords = array(); $domips = array(); exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost); - if($rethost == 0) { - foreach($domrecords as $domr) { + if ($rethost == 0) { + foreach ($domrecords as $domr) { $doml = explode(" ", $domr); $domip = $doml[3]; /* fill array with domain ip addresses */ - if(is_ipaddr($domip)) { + if (is_ipaddr($domip)) { $domips[] = $domip; } } } sort($domips); $contents = ""; - if(! empty($domips)) { - foreach($domips as $ip) { + if (!empty($domips)) { + foreach ($domips as $ip) { $contents .= "$ip\n"; } } @@ -1509,16 +1611,16 @@ function add_hostname_to_watch($hostname) { function is_fqdn($fqdn) { $hostname = false; - if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) { + if (preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) { $hostname = true; } - if(preg_match("/\.\./", $fqdn)) { + if (preg_match("/\.\./", $fqdn)) { $hostname = false; } - if(preg_match("/^\./i", $fqdn)) { + if (preg_match("/^\./i", $fqdn)) { $hostname = false; } - if(preg_match("/\//i", $fqdn)) { + if (preg_match("/\//i", $fqdn)) { $hostname = false; } return($hostname); @@ -1547,40 +1649,40 @@ function pfsense_default_table_entries_size() { * if it has changed we return the old records * if no change we return false */ function compare_hostname_to_dnscache($hostname) { - if(!is_dir("/var/db/dnscache")) { + if (!is_dir("/var/db/dnscache")) { mkdir("/var/db/dnscache"); } $hostname = trim($hostname); - if(is_readable("/var/db/dnscache/{$hostname}")) { + if (is_readable("/var/db/dnscache/{$hostname}")) { $oldcontents = file_get_contents("/var/db/dnscache/{$hostname}"); } else { $oldcontents = ""; } - if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) { + if ((is_fqdn($hostname)) && (!is_ipaddr($hostname))) { $domrecords = array(); $domips = array(); exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost); - if($rethost == 0) { - foreach($domrecords as $domr) { + if ($rethost == 0) { + foreach ($domrecords as $domr) { $doml = explode(" ", $domr); $domip = $doml[3]; /* fill array with domain ip addresses */ - if(is_ipaddr($domip)) { + if (is_ipaddr($domip)) { $domips[] = $domip; } } } sort($domips); $contents = ""; - if(! empty($domips)) { - foreach($domips as $ip) { + if (!empty($domips)) { + foreach ($domips as $ip) { $contents .= "$ip\n"; } } } - if(trim($oldcontents) != trim($contents)) { - if($g['debug']) { + if (trim($oldcontents) != trim($contents)) { + if ($g['debug']) { log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents)); } return ($oldcontents); @@ -1596,8 +1698,9 @@ function load_crypto() { global $config, $g; $crypto_modules = array('glxsb', 'aesni'); - if (!in_array($config['system']['crypto_hardware'], $crypto_modules)) + if (!in_array($config['system']['crypto_hardware'], $crypto_modules)) { return false; + } if (!empty($config['system']['crypto_hardware']) && !is_module_loaded($config['system']['crypto_hardware'])) { log_error("Loading {$config['system']['crypto_hardware']} cryptographic accelerator module."); @@ -1612,8 +1715,9 @@ function load_thermal_hardware() { global $config, $g; $thermal_hardware_modules = array('coretemp', 'amdtemp'); - if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules)) + if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules)) { return false; + } if (!empty($config['system']['thermal_hardware']) && !is_module_loaded($config['system']['thermal_hardware'])) { log_error("Loading {$config['system']['thermal_hardware']} thermal monitor module."); @@ -1633,12 +1737,15 @@ function isvm() { $virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86", "VirtualBox"); $_gb = exec('/bin/kenv smbios.system.product 2>/dev/null', $output, $rc); - if ($rc != 0 || !isset($output[0])) + if ($rc != 0 || !isset($output[0])) { return false; + } - foreach ($virtualenvs as $virtualenv) - if (stripos($output[0], $virtualenv) !== false) + foreach ($virtualenvs as $virtualenv) { + if (stripos($output[0], $virtualenv) !== false) { return true; + } + } return false; } @@ -1653,8 +1760,9 @@ function download_file($url, $destination, $verify_ssl = false, $connect_timeout $fp = fopen($destination, "wb"); - if (!$fp) + if (!$fp) { return false; + } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); @@ -1668,8 +1776,9 @@ function download_file($url, $destination, $verify_ssl = false, $connect_timeout if (!empty($config['system']['proxyurl'])) { curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']); - if (!empty($config['system']['proxyport'])) + if (!empty($config['system']['proxyport'])) { curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']); + } if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) { @curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE); curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}"); @@ -1710,8 +1819,9 @@ function download_file_with_progress_bar($url_file, $destination_file, $readbody if (!empty($config['system']['proxyurl'])) { curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']); - if (!empty($config['system']['proxyport'])) + if (!empty($config['system']['proxyport'])) { curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']); + } if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) { @curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE); curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}"); @@ -1720,8 +1830,9 @@ function download_file_with_progress_bar($url_file, $destination_file, $readbody @curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - if($fout) + if ($fout) { fclose($fout); + } curl_close($ch); return ($http_code == 200) ? true : $http_code; } @@ -1731,7 +1842,7 @@ function read_header($ch, $string) { $length = strlen($string); $regs = ""; preg_match("/(Content-Length:) (.*)/", $string, $regs); - if($regs[2] <> "") { + if ($regs[2] <> "") { $file_size = intval($regs[2]); } ob_flush(); @@ -1743,15 +1854,16 @@ function read_body($ch, $string) { global $pkg_interface; $length = strlen($string); $downloaded += intval($length); - if($file_size > 0) { + if ($file_size > 0) { $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0); $downloadProgress = 100 - $downloadProgress; - } else + } else { $downloadProgress = 0; - if($lastseen <> $downloadProgress and $downloadProgress < 101) { - if($sendto == "status") { - if($pkg_interface == "console") { - if(($downloadProgress % 10) == 0 || $downloadProgress < 10) { + } + if ($lastseen <> $downloadProgress and $downloadProgress < 101) { + if ($sendto == "status") { + if ($pkg_interface == "console") { + if (($downloadProgress % 10) == 0 || $downloadProgress < 10) { $tostatus = $static_status . $downloadProgress . "%"; if ($downloadProgress == 100) { $tostatus = $tostatus . "\r"; @@ -1763,8 +1875,8 @@ function read_body($ch, $string) { update_status($tostatus); } } else { - if($pkg_interface == "console") { - if(($downloadProgress % 10) == 0 || $downloadProgress < 10) { + if ($pkg_interface == "console") { + if (($downloadProgress % 10) == 0 || $downloadProgress < 10) { $tooutput = $static_output . $downloadProgress . "%"; if ($downloadProgress == 100) { $tooutput = $tooutput . "\r"; @@ -1776,14 +1888,15 @@ function read_body($ch, $string) { update_output_window($tooutput); } } - if(($pkg_interface != "console") || (($downloadProgress % 10) == 0) || ($downloadProgress < 10)) { - update_progress_bar($downloadProgress, $first_progress_update); - $first_progress_update = FALSE; - } + if (($pkg_interface != "console") || (($downloadProgress % 10) == 0) || ($downloadProgress < 10)) { + update_progress_bar($downloadProgress, $first_progress_update); + $first_progress_update = FALSE; + } $lastseen = $downloadProgress; } - if($fout) + if ($fout) { fwrite($fout, $string); + } ob_flush(); return $length; } @@ -1794,7 +1907,7 @@ function read_body($ch, $string) { function update_output_window($text) { global $pkg_interface; $log = preg_replace("/\n/", "\\n", $text); - if($pkg_interface != "console") { + if ($pkg_interface != "console") { echo "\n"; } else { - if(!($first_time)) + if (!($first_time)) { echo "\x08\x08\x08\x08\x08"; + } echo sprintf("%4d%%", $percent); } } /* Split() is being DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged. */ -if(!function_exists("split")) { +if (!function_exists("split")) { function split($separator, $haystack, $limit = null) { log_error("deprecated split() call with separator '{$separator}'"); return preg_split($separator, $haystack, $limit); @@ -1853,42 +1969,52 @@ if(!function_exists("split")) { function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) { global $g, $config, $pconfig, $debug; - if(!$origname) + if (!$origname) { return; - - $sectionref = &$config; - foreach($section as $sectionname) { - if(is_array($sectionref) && isset($sectionref[$sectionname])) - $sectionref = &$sectionref[$sectionname]; - else - return; } - if($debug) $fd = fopen("{$g['tmp_path']}/print_r", "a"); - if($debug) fwrite($fd, print_r($pconfig, true)); + $sectionref = &$config; + foreach ($section as $sectionname) { + if (is_array($sectionref) && isset($sectionref[$sectionname])) { + $sectionref = &$sectionref[$sectionname]; + } else { + return; + } + } - if(is_array($sectionref)) { - foreach($sectionref as $itemkey => $item) { - if($debug) fwrite($fd, "$itemkey\n"); + if ($debug) { + $fd = fopen("{$g['tmp_path']}/print_r", "a"); + fwrite($fd, print_r($pconfig, true)); + } + + if (is_array($sectionref)) { + foreach ($sectionref as $itemkey => $item) { + if ($debug) { + fwrite($fd, "$itemkey\n"); + } $fieldfound = true; $fieldref = &$sectionref[$itemkey]; - foreach($field as $fieldname) { - if(is_array($fieldref) && isset($fieldref[$fieldname])) + foreach ($field as $fieldname) { + if (is_array($fieldref) && isset($fieldref[$fieldname])) { $fieldref = &$fieldref[$fieldname]; - else { + } else { $fieldfound = false; break; } } - if($fieldfound && $fieldref == $origname) { - if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n"); + if ($fieldfound && $fieldref == $origname) { + if ($debug) { + fwrite($fd, "Setting old alias value $origname to $new_alias_name\n"); + } $fieldref = $new_alias_name; } } } - if($debug) fclose($fd); + if ($debug) { + fclose($fd); + } } @@ -1911,20 +2037,24 @@ function parse_aliases_file($filename, $type = "url", $max_items = -1) { /* NOTE: fgetss() is not a typo RTFM before being smart */ while (($fc = fgetss($fd)) !== FALSE) { $tmp = trim($fc, " \t\n\r"); - if (empty($tmp)) + if (empty($tmp)) { continue; + } $tmp_str = strstr($tmp, '#', true); - if (!empty($tmp_str)) + if (!empty($tmp_str)) { $tmp = $tmp_str; + } $tmp_str = strstr($tmp, ' ', true); - if (!empty($tmp_str)) + if (!empty($tmp_str)) { $tmp = $tmp_str; + } $valid = ($type == "url" && (is_ipaddr($tmp) || is_subnet($tmp))) || - ($type == "url_ports" && (is_port($tmp) || is_portrange($tmp))); + ($type == "url_ports" && (is_port($tmp) || is_portrange($tmp))); if ($valid) { $items[] = $tmp; - if (count($items) == $max_items) + if (count($items) == $max_items) { break; + } } } fclose($fd); @@ -1940,8 +2070,9 @@ function update_alias_url_data() { $lockkey = lock('aliasurl'); if (is_array($config['aliases']['alias'])) { foreach ($config['aliases']['alias'] as $x => $alias) { - if (empty($alias['aliasurl'])) + if (empty($alias['aliasurl'])) { continue; + } $address = null; foreach ($alias['aliasurl'] as $alias_url) { @@ -1954,11 +2085,13 @@ function update_alias_url_data() { /* if the item is tar gzipped then extract */ if (stripos($alias_url, '.tgz')) { - if (!process_alias_tgz($temp_filename)) + if (!process_alias_tgz($temp_filename)) { continue; + } } else if (stripos($alias_url, '.zip')) { - if (!process_alias_unzip($temp_filename)) + if (!process_alias_unzip($temp_filename)) { continue; + } } if (file_exists("{$temp_filename}/aliases")) { $address = parse_aliases_file("{$temp_filename}/aliases", $alias['type'], 3000); @@ -1978,7 +2111,7 @@ function update_alias_url_data() { } function process_alias_unzip($temp_filename) { - if(!file_exists("/usr/local/bin/unzip")) { + if (!file_exists("/usr/local/bin/unzip")) { log_error(gettext("Alias archive is a .zip file which cannot be decompressed because utility is missing!")); return false; } @@ -1992,14 +2125,15 @@ function process_alias_unzip($temp_filename) { log_error(gettext("Could not open {$temp_filename}/aliases for writing!")); return false; } - foreach($files_to_process as $f2p) { + foreach ($files_to_process as $f2p) { $tmpfd = @fopen($f2p, 'r'); if (!$tmpfd) { log_error(gettext("The following file could not be read {$f2p} from {$temp_filename}")); continue; } - while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE) + while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE) { fwrite($fd, $tmpbuf); + } fclose($tmpfd); unlink($f2p); } @@ -2010,7 +2144,7 @@ function process_alias_unzip($temp_filename) { } function process_alias_tgz($temp_filename) { - if(!file_exists('/usr/bin/tar')) { + if (!file_exists('/usr/bin/tar')) { log_error(gettext("Alias archive is a .tar/tgz file which cannot be decompressed because utility is missing!")); return false; } @@ -2024,14 +2158,15 @@ function process_alias_tgz($temp_filename) { log_error(gettext("Could not open {$temp_filename}/aliases for writing!")); return false; } - foreach($files_to_process as $f2p) { + foreach ($files_to_process as $f2p) { $tmpfd = @fopen($f2p, 'r'); if (!$tmpfd) { log_error(gettext("The following file could not be read {$f2p} from {$temp_filename}")); continue; } - while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE) + while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE) { fwrite($fd, $tmpbuf); + } fclose($tmpfd); unlink($f2p); } @@ -2048,12 +2183,13 @@ function version_compare_dates($a, $b) { if ((!$a_time) || (!$b_time)) { return FALSE; } else { - if ($a_time < $b_time) + if ($a_time < $b_time) { return -1; - elseif ($a_time == $b_time) + } elseif ($a_time == $b_time) { return 0; - else + } else { return 1; + } } } function version_get_string_value($a) { @@ -2074,8 +2210,9 @@ function version_get_string_value($a) { if (substr($a, 0, strlen($str)) == $str) { $major = $num; $n = substr($a, strlen($str)); - if (is_numeric($n)) + if (is_numeric($n)) { $minor = $n; + } break; } } @@ -2084,10 +2221,11 @@ function version_get_string_value($a) { function version_compare_string($a, $b) { // Only compare string parts if both versions give a specific release // (If either version lacks a string part, assume intended to match all release levels) - if (isset($a) && isset($b)) + if (isset($a) && isset($b)) { return version_compare_numeric(version_get_string_value($a), version_get_string_value($b)); - else + } else { return 0; + } } function version_compare_numeric($a, $b) { $a_arr = explode('.', rtrim($a, '.0')); @@ -2096,10 +2234,11 @@ function version_compare_numeric($a, $b) { foreach ($a_arr as $n => $val) { if (array_key_exists($n, $b_arr)) { // So far so good, both have values at this minor version level. Compare. - if ($val > $b_arr[$n]) + if ($val > $b_arr[$n]) { return 1; - elseif ($val < $b_arr[$n]) + } elseif ($val < $b_arr[$n]) { return -1; + } } else { // a is greater, since b doesn't have any minor version here. return 1; @@ -2119,8 +2258,9 @@ function pfs_version_compare($cur_time, $cur_text, $remote) { if ($v === FALSE) { // If that fails, try to compare by string // Before anything else, simply test if the strings are equal - if (($cur_text == $remote) || ($cur_time == $remote)) + if (($cur_text == $remote) || ($cur_time == $remote)) { return 0; + } list($cur_num, $cur_str) = explode('-', $cur_text); list($rem_num, $rem_str) = explode('-', $remote); @@ -2128,8 +2268,9 @@ function pfs_version_compare($cur_time, $cur_text, $remote) { $v = version_compare_numeric($cur_num, $rem_num); // If the numeric parts are the same, compare the string parts. - if ($v == 0) + if ($v == 0) { return version_compare_string($cur_str, $rem_str); + } } return $v; } @@ -2148,9 +2289,9 @@ function process_alias_urltable($name, $url, $freq, $forceupdate=false) { } // If the file doesn't exist or is older than update_freq days, fetch a new copy. - if (!file_exists($urltable_filename) - || ((time() - filemtime($urltable_filename)) > ($freq * 86400 - 90)) - || $forceupdate) { + if (!file_exists($urltable_filename) || + ((time() - filemtime($urltable_filename)) > ($freq * 86400 - 90)) || + $forceupdate) { // Try to fetch the URL supplied conf_mount_rw(); @@ -2164,12 +2305,13 @@ function process_alias_urltable($name, $url, $freq, $forceupdate=false) { file_put_contents($urltable_filename, implode("\n", $ports)); } unlink_if_exists($urltable_filename . ".tmp"); - } else + } else { touch($urltable_filename); + } conf_mount_ro(); return true; } else { - // File exists, and it doesn't need updated. + // File exists, and it doesn't need to be updated. return -1; } } @@ -2204,9 +2346,11 @@ function nanobsd_switch_boot_slice() { $slice = $BOOTFLASH; } - for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); } + for ($i = 0; $i < ob_get_level(); $i++) { + ob_end_flush(); + } ob_implicit_flush(1); - if(strstr($slice, "s2")) { + if (strstr($slice, "s2")) { $ASLICE="2"; $AOLDSLICE="1"; $AGLABEL_SLICE="pfsense1"; @@ -2240,7 +2384,9 @@ function nanobsd_clone_slice() { global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE; nanobsd_detect_slice_info(); - for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); } + for ($i = 0; $i < ob_get_level(); $i++) { + ob_end_flush(); + } ob_implicit_flush(1); set_single_sysctl("kern.geom.debugflags", "16"); exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1"); @@ -2248,7 +2394,7 @@ function nanobsd_clone_slice() { exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}"); $status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID); set_single_sysctl("kern.geom.debugflags", "0"); - if($status) { + if ($status) { return false; } else { return true; @@ -2268,10 +2414,11 @@ function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) { /dev/ufs/{$gslice} / ufs ro,noatime 1 1 /dev/ufs/cf /cf ufs ro,noatime 1 1 EOF; - if (file_put_contents($fstabpath, $fstab)) + if (file_put_contents($fstabpath, $fstab)) { $status = true; - else + } else { $status = false; + } } else { $status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}"); } @@ -2291,7 +2438,7 @@ function nanobsd_detect_slice_info() { $ACTIVE_SLICE=nanobsd_get_active_slice(); // Detect which slice is active and set information. - if(strstr($REAL_BOOT_DEVICE, "s1")) { + if (strstr($REAL_BOOT_DEVICE, "s1")) { $SLICE="2"; $OLDSLICE="1"; $GLABEL_SLICE="pfsense1"; @@ -2335,8 +2482,7 @@ function get_include_contents($filename) { */ function xml2array($contents, $get_attributes = 1, $priority = 'tag') { - if (!function_exists('xml_parser_create')) - { + if (!function_exists('xml_parser_create')) { return array (); } $parser = xml_parser_create(''); @@ -2345,64 +2491,56 @@ function xml2array($contents, $get_attributes = 1, $priority = 'tag') xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); xml_parse_into_struct($parser, trim($contents), $xml_values); xml_parser_free($parser); - if (!$xml_values) + if (!$xml_values) { return; //Hmm... + } $xml_array = array (); $parents = array (); $opened_tags = array (); $arr = array (); $current = & $xml_array; $repeated_tag_index = array (); - foreach ($xml_values as $data) - { + foreach ($xml_values as $data) { unset ($attributes, $value); extract($data); $result = array (); $attributes_data = array (); - if (isset ($value)) - { - if ($priority == 'tag') + if (isset ($value)) { + if ($priority == 'tag') { $result = $value; - else + } else { $result['value'] = $value; - } - if (isset ($attributes) and $get_attributes) - { - foreach ($attributes as $attr => $val) - { - if ($priority == 'tag') - $attributes_data[$attr] = $val; - else - $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' } } - if ($type == "open") - { + if (isset ($attributes) and $get_attributes) { + foreach ($attributes as $attr => $val) { + if ($priority == 'tag') { + $attributes_data[$attr] = $val; + } else { + $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' + } + } + } + if ($type == "open") { $parent[$level -1] = & $current; - if (!is_array($current) or (!in_array($tag, array_keys($current)))) - { + if (!is_array($current) or (!in_array($tag, array_keys($current)))) { $current[$tag] = $result; - if ($attributes_data) + if ($attributes_data) { $current[$tag . '_attr'] = $attributes_data; + } $repeated_tag_index[$tag . '_' . $level] = 1; $current = & $current[$tag]; - } - else - { - if (isset ($current[$tag][0])) - { + } else { + if (isset ($current[$tag][0])) { $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result; $repeated_tag_index[$tag . '_' . $level]++; - } - else - { + } else { $current[$tag] = array ( $current[$tag], $result ); $repeated_tag_index[$tag . '_' . $level] = 2; - if (isset ($current[$tag . '_attr'])) - { + if (isset ($current[$tag . '_attr'])) { $current[$tag]['0_attr'] = $current[$tag . '_attr']; unset ($current[$tag . '_attr']); } @@ -2410,52 +2548,39 @@ function xml2array($contents, $get_attributes = 1, $priority = 'tag') $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1; $current = & $current[$tag][$last_item_index]; } - } - elseif ($type == "complete") - { - if (!isset ($current[$tag])) - { + } elseif ($type == "complete") { + if (!isset ($current[$tag])) { $current[$tag] = $result; $repeated_tag_index[$tag . '_' . $level] = 1; - if ($priority == 'tag' and $attributes_data) + if ($priority == 'tag' and $attributes_data) { $current[$tag . '_attr'] = $attributes_data; - } - else - { - if (isset ($current[$tag][0]) and is_array($current[$tag])) - { + } + } else { + if (isset ($current[$tag][0]) and is_array($current[$tag])) { $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result; - if ($priority == 'tag' and $get_attributes and $attributes_data) - { + if ($priority == 'tag' and $get_attributes and $attributes_data) { $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data; } $repeated_tag_index[$tag . '_' . $level]++; - } - else - { + } else { $current[$tag] = array ( $current[$tag], $result ); $repeated_tag_index[$tag . '_' . $level] = 1; - if ($priority == 'tag' and $get_attributes) - { - if (isset ($current[$tag . '_attr'])) - { + if ($priority == 'tag' and $get_attributes) { + if (isset ($current[$tag . '_attr'])) { $current[$tag]['0_attr'] = $current[$tag . '_attr']; unset ($current[$tag . '_attr']); } - if ($attributes_data) - { + if ($attributes_data) { $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data; } } $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken } } - } - elseif ($type == 'close') - { + } elseif ($type == 'close') { $current = & $parent[$level -1]; } } @@ -2463,18 +2588,20 @@ function xml2array($contents, $get_attributes = 1, $priority = 'tag') } function get_country_name($country_code) { - if ($country_code != "ALL" && strlen($country_code) != 2) + if ($country_code != "ALL" && strlen($country_code) != 2) { return ""; + } $country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml"; $country_names_contents = file_get_contents($country_names_xml); $country_names = xml2array($country_names_contents); - if($country_code == "ALL") { + if ($country_code == "ALL") { $country_list = array(); - foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) { - $country_list[] = array("code" => $country['ISO_3166-1_Alpha-2_Code_element'], - "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) ); + foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) { + $country_list[] = array( + "code" => $country['ISO_3166-1_Alpha-2_Code_element'], + "name" => ucwords(strtolower($country['ISO_3166-1_Country_name']))); } return $country_list; } @@ -2493,37 +2620,41 @@ function filter_rules_sort() { global $config; /* mark each rule with the sequence number (to retain the order while sorting) */ - for ($i = 0; isset($config['filter']['rule'][$i]); $i++) + for ($i = 0; isset($config['filter']['rule'][$i]); $i++) { $config['filter']['rule'][$i]['seq'] = $i; + } usort($config['filter']['rule'], "filter_rules_compare"); /* strip the sequence numbers again */ - for ($i = 0; isset($config['filter']['rule'][$i]); $i++) + for ($i = 0; isset($config['filter']['rule'][$i]); $i++) { unset($config['filter']['rule'][$i]['seq']); + } } function filter_rules_compare($a, $b) { - if (isset($a['floating']) && isset($b['floating'])) + if (isset($a['floating']) && isset($b['floating'])) { return $a['seq'] - $b['seq']; - else if (isset($a['floating'])) + } else if (isset($a['floating'])) { return -1; - else if (isset($b['floating'])) + } else if (isset($b['floating'])) { return 1; - else if ($a['interface'] == $b['interface']) + } else if ($a['interface'] == $b['interface']) { return $a['seq'] - $b['seq']; - else + } else { return compare_interface_friendly_names($a['interface'], $b['interface']); + } } function generate_ipv6_from_mac($mac) { $elements = explode(":", $mac); - if(count($elements) <> 6) + if (count($elements) <> 6) { return false; + } $i = 0; $ipv6 = "fe80::"; - foreach($elements as $byte) { - if($i == 0) { + foreach ($elements as $byte) { + if ($i == 0) { $hexadecimal = substr($byte, 1, 2); $bitmap = base_convert($hexadecimal, 16, 2); $bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT); @@ -2531,13 +2662,13 @@ function generate_ipv6_from_mac($mac) { $byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16); } $ipv6 .= $byte; - if($i == 1) { + if ($i == 1) { $ipv6 .= ":"; } - if($i == 3) { + if ($i == 3) { $ipv6 .= ":"; } - if($i == 2) { + if ($i == 2) { $ipv6 .= "ff:fe"; } @@ -2557,18 +2688,20 @@ function generate_ipv6_from_mac($mac) { function load_mac_manufacturer_table() { /* load MAC-Manufacture data from the file */ $macs = false; - if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes")) + if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes")) { $macs=file("/usr/local/share/nmap/nmap-mac-prefixes"); - if ($macs){ - foreach ($macs as $line){ - if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){ + } + if ($macs) { + foreach ($macs as $line) { + if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)) { /* store values like this $mac_man['000C29']='VMware' */ $mac_man["$matches[1]"]=$matches[2]; } } return $mac_man; - } else + } else { return -1; + } } @@ -2599,8 +2732,9 @@ function is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, if ($check_subnets) { $iflist = get_configured_interface_list(); foreach ($iflist as $if => $ifname) { - if ($ignore_if == $if) + if ($ignore_if == $if) { continue; + } if ($isipv6 === true) { $bitmask = get_interface_subnetv6($if); @@ -2610,38 +2744,46 @@ function is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, $subnet = gen_subnet(get_interface_ip($if), $bitmask); } - if (ip_in_subnet($ipaddr, $subnet . '/' . $bitmask)) + if (ip_in_subnet($ipaddr, $subnet . '/' . $bitmask)) { return true; + } } } else { - if ($isipv6 === true) + if ($isipv6 === true) { $interface_list_ips = get_configured_ipv6_addresses(); - else + } else { $interface_list_ips = get_configured_ip_addresses(); + } - foreach($interface_list_ips as $if => $ilips) { - if ($ignore_if == $if) + foreach ($interface_list_ips as $if => $ilips) { + if ($ignore_if == $if) { continue; - if (strcasecmp($ipaddr, $ilips) == 0) + } + if (strcasecmp($ipaddr, $ilips) == 0) { return true; + } } } $interface_list_vips = get_configured_vips_list(true); foreach ($interface_list_vips as $id => $vip) { /* Skip CARP interfaces here since they were already checked above */ - if ($id == $ignore_vip_id || (substr($ignore_if, 0, 4) == '_vip') && substr($ignore_vip_if, 5) == $vip['uniqdid']) + if ($id == $ignore_vip_id || (substr($ignore_if, 0, 4) == '_vip') && substr($ignore_vip_if, 5) == $vip['uniqdid']) { continue; - if (strcasecmp($ipaddr, $vip['ipaddr']) == 0) + } + if (strcasecmp($ipaddr, $vip['ipaddr']) == 0) { return true; + } } if ($check_localip) { - if (is_array($config['pptpd']) && !empty($config['pptpd']['localip']) && (strcasecmp($ipaddr, $config['pptpd']['localip']) == 0)) + if (is_array($config['pptpd']) && !empty($config['pptpd']['localip']) && (strcasecmp($ipaddr, $config['pptpd']['localip']) == 0)) { return true; + } - if (!is_array($config['l2tp']) && !empty($config['l2tp']['localip']) && (strcasecmp($ipaddr, $config['l2tp']['localip']) == 0)) + if (!is_array($config['l2tp']) && !empty($config['l2tp']['localip']) && (strcasecmp($ipaddr, $config['l2tp']['localip']) == 0)) { return true; + } } return false; @@ -2657,11 +2799,12 @@ function is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, */ function pfSense_handle_custom_code($src_dir) { // Allow extending of the nat edit page and include custom input validation - if(is_dir("$src_dir")) { + if (is_dir("$src_dir")) { $cf = glob($src_dir . "/*.inc"); - foreach($cf as $nf) { - if($nf == "." || $nf == "..") + foreach ($cf as $nf) { + if ($nf == "." || $nf == "..") { continue; + } // Include the extra handler include("$nf"); } @@ -2694,8 +2837,9 @@ function system_get_language_code() { //$code = $g_languages[$language]['code']; $code = str_replace("_", "-", $language); - if (empty($code)) + if (empty($code)) { $code = "en-US"; // Set default code. + } return $code; } @@ -2706,8 +2850,9 @@ function system_get_language_codeset() { $language = $config['system']['language']; $codeset = $g_languages[$language]['codeset']; - if (empty($codeset)) + if (empty($codeset)) { $codeset = "UTF-8"; // Set default codeset. + } return $codeset; } @@ -2745,8 +2890,9 @@ $g_languages = array ( ); function return_hex_ipv4($ipv4) { - if(!is_ipaddrv4($ipv4)) + if (!is_ipaddrv4($ipv4)) { return(false); + } /* we need the hex form of the interface IPv4 address */ $ip4arr = explode(".", $ipv4); @@ -2754,29 +2900,32 @@ function return_hex_ipv4($ipv4) { } function convert_ipv6_to_128bit($ipv6) { - if(!is_ipaddrv6($ipv6)) + if (!is_ipaddrv6($ipv6)) { return(false); + } $ip6arr = array(); $ip6prefix = Net_IPv6::uncompress($ipv6); $ip6arr = explode(":", $ip6prefix); /* binary presentation of the prefix for all 128 bits. */ $ip6prefixbin = ""; - foreach($ip6arr as $element) { + foreach ($ip6arr as $element) { $ip6prefixbin .= sprintf("%016b", hexdec($element)); } return($ip6prefixbin); } function convert_128bit_to_ipv6($ip6bin) { - if(strlen($ip6bin) <> 128) + if (strlen($ip6bin) <> 128) { return(false); + } $ip6arr = array(); $ip6binarr = array(); $ip6binarr = str_split($ip6bin, 16); - foreach($ip6binarr as $binpart) + foreach ($ip6binarr as $binpart) { $ip6arr[] = dechex(bindec($binpart)); + } $ip6addr = Net_IPv6::compress(implode(":", $ip6arr)); return($ip6addr); @@ -2790,10 +2939,11 @@ function convert_128bit_to_ipv6($ip6bin) { function calculate_ipv6_delegation_length($if) { global $config; - if(!is_array($config['interfaces'][$if])) + if (!is_array($config['interfaces'][$if])) { return false; + } - switch($config['interfaces'][$if]['ipaddrv6']) { + switch ($config['interfaces'][$if]['ipaddrv6']) { case "6to4": $pdlen = 16; break; @@ -2817,7 +2967,7 @@ function huawei_rssi_to_string($rssi) { $dbm = array(); $i = 0; $dbstart = -113; - while($i < 32) { + while ($i < 32) { $dbm[$i] = $dbstart + ($i * 2); $i++; } @@ -2913,7 +3063,7 @@ function get_configured_pppoe_server_interfaces() { global $config; $iflist = array(); if (is_array($config['pppoes']['pppoe'])) { - foreach($config['pppoes']['pppoe'] as $pppoe) { + foreach ($config['pppoes']['pppoe'] as $pppoe) { if ($pppoe['mode'] == "server") { $int = "poes". $pppoe['pppoeid']; $iflist[$int] = strtoupper($int); @@ -2925,12 +3075,13 @@ function get_configured_pppoe_server_interfaces() { function get_pppoes_child_interfaces($ifpattern) { $if_arr = array(); - if($ifpattern == "") + if ($ifpattern == "") { return; + } exec("ifconfig", $out, $ret); - foreach($out as $line) { - if(preg_match("/^({$ifpattern}[0-9]+):/i", $line, $match)) { + foreach ($out as $line) { + if (preg_match("/^({$ifpattern}[0-9]+):/i", $line, $match)) { $if_arr[] = $match[1]; } } @@ -2952,24 +3103,28 @@ function get_pppoes_child_interfaces($ifpattern) { function pkg_call_plugins($plugin_type, $plugin_params) { global $g, $config; $results = array(); - if (!is_array($config['installedpackages']['package'])) + if (!is_array($config['installedpackages']['package'])) { return $results; + } foreach ($config['installedpackages']['package'] as $package) { - if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) + if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) { continue; + } $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], 'packagegui'); $pkgname = substr(reverse_strrchr($package['configurationfile'], "."),0,-1); - if (is_array($pkg_config['plugins']['item'])) + if (is_array($pkg_config['plugins']['item'])) { foreach ($pkg_config['plugins']['item'] as $plugin) { if ($plugin['type'] == $plugin_type) { - if (file_exists($pkg_config['include_file'])) + if (file_exists($pkg_config['include_file'])) { require_once($pkg_config['include_file']); - else + } else { continue; + } $plugin_function = $pkgname . '_'. $plugin_type; $results[$pkgname] = @eval($plugin_function($plugin_params)); } } + } } return $results; } From 49aec489d8f7c16f745a5b70a7dc9bb47571077b Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sat, 28 Feb 2015 23:09:31 +0545 Subject: [PATCH 146/257] Code style for pkg-utils --- etc/inc/pkg-utils.inc | 723 ++++++++++++++++++++++++------------------ 1 file changed, 415 insertions(+), 308 deletions(-) diff --git a/etc/inc/pkg-utils.inc b/etc/inc/pkg-utils.inc index 690d2f6e76..f0ff2d2bb5 100644 --- a/etc/inc/pkg-utils.inc +++ b/etc/inc/pkg-utils.inc @@ -1,37 +1,36 @@ >/tmp/pbi_delete_errors.txt"); } @@ -120,8 +124,9 @@ function remove_freebsd_package($packagestring) { ******/ function is_package_installed($packagename) { $pkg = get_pkg_id($packagename); - if($pkg == -1) + if ($pkg == -1) { return false; + } return true; } @@ -137,9 +142,10 @@ function get_pkg_id($pkg_name) { global $config; if (is_array($config['installedpackages']['package'])) { - foreach($config['installedpackages']['package'] as $idx => $pkg) { - if($pkg['name'] == $pkg_name) + foreach ($config['installedpackages']['package'] as $idx => $pkg) { + if ($pkg['name'] == $pkg_name) { return $idx; + } } } return -1; @@ -177,8 +183,8 @@ function get_pkg_info($pkgs = 'all', $info = 'all') { $freebsd_machine = php_uname("m"); $params = array( - "pkg" => $pkgs, - "info" => $info, + "pkg" => $pkgs, + "info" => $info, "freebsd_version" => get_freebsd_version(), "freebsd_machine" => $freebsd_machine ); @@ -191,7 +197,7 @@ function get_pkg_sizes($pkgs = 'all') { $freebsd_machine = php_uname("m"); $params = array( - "pkg" => $pkgs, + "pkg" => $pkgs, "freebsd_version" => get_freebsd_version(), "freebsd_machine" => $freebsd_machine ); @@ -199,9 +205,9 @@ function get_pkg_sizes($pkgs = 'all') { $xmlrpc_base_url = get_active_xml_rpc_base_url(); $cli = new XML_RPC_Client($g['xmlrpcpath'], $xmlrpc_base_url); $resp = $cli->send($msg, 10); - if(!is_object($resp)) + if (!is_object($resp)) { log_error("Could not get response from XMLRPC server!"); - else if (!$resp->faultCode()) { + } else if (!$resp->faultCode()) { $raw_versions = $resp->value(); return xmlrpc_value_to_php($raw_versions); } @@ -218,29 +224,36 @@ function resync_all_package_configs($show_message = false) { log_error(gettext("Resyncing configuration for all packages.")); - if (!is_array($config['installedpackages']['package'])) + if (!is_array($config['installedpackages']['package'])) { return; + } - if($show_message == true) + if ($show_message == true) { echo "Syncing packages:"; + } conf_mount_rw(); - foreach($config['installedpackages']['package'] as $idx => $package) { - if (empty($package['name'])) + foreach ($config['installedpackages']['package'] as $idx => $package) { + if (empty($package['name'])) { continue; - if($show_message == true) + } + if ($show_message == true) { echo " " . $package['name']; + } get_pkg_depends($package['name'], "all"); - if(platform_booting() != true) + if (platform_booting() != true) { stop_service(get_pkg_internal_name($package)); + } sync_package($idx, true, true); - if($pkg_interface == "console") + if ($pkg_interface == "console") { echo "\n" . gettext("Syncing packages:"); + } } - if($show_message == true) + if ($show_message == true) { echo " done.\n"; + } @unlink("/conf/needs_package_sync"); conf_mount_ro(); @@ -251,8 +264,9 @@ function resync_all_package_configs($show_message = false) { * package is installed. */ function is_freebsd_pkg_installed($pkg) { - if(!$pkg) + if (!$pkg) { return; + } $output = ""; $_gb = exec("/usr/local/sbin/pbi_info " . escapeshellarg($pkg) . ' 2>/dev/null', $output, $retval); @@ -271,13 +285,14 @@ function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $retu global $config; $pkg_id = get_pkg_id($pkg_name); - if($pkg_id == -1) + if ($pkg_id == -1) { return -1; // This package doesn't really exist - exit the function. - else if (!isset($config['installedpackages']['package'][$pkg_id])) + } else if (!isset($config['installedpackages']['package'][$pkg_id])) { return; // No package belongs to the pkg_id passed to this function. + } $package =& $config['installedpackages']['package'][$pkg_id]; - if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) { + if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) { log_error(sprintf(gettext('The %1$s package is missing required dependencies and must be reinstalled. %2$s'), $package['name'], $package['configurationfile'])); uninstall_package($package['name']); if (install_package($package['name']) < 0) { @@ -287,47 +302,56 @@ function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $retu } $pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui"); if (!empty($pkg_xml['additional_files_needed'])) { - foreach($pkg_xml['additional_files_needed'] as $item) { - if ($return_nosync == 0 && isset($item['nosync'])) + foreach ($pkg_xml['additional_files_needed'] as $item) { + if ($return_nosync == 0 && isset($item['nosync'])) { continue; // Do not return depends with nosync set if not required. + } $depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames. $depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name. - if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file))) - if (($filetype != "all") && (strtolower(substr($depend_file, -strlen($filetype))) != strtolower($filetype))) + if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file))) { + if (($filetype != "all") && (strtolower(substr($depend_file, -strlen($filetype))) != strtolower($filetype))) { continue; - if ($item['prefix'] != "") - $prefix = $item['prefix']; - else - $prefix = "/usr/local/pkg/"; - // Ensure that the prefix exists to avoid installation errors. - if(!is_dir($prefix)) - exec("/bin/mkdir -p {$prefix}"); - if(!file_exists($prefix . $depend_file)) - log_error(sprintf(gettext("The %s package is missing required dependencies and must be reinstalled."), $package['name'])); - switch ($format) { - case "files": - $depends[] = $prefix . $depend_file; - break; - case "names": - switch ($filetype) { - case "all": - if(preg_match("/\.xml/i", $depend_file)) { - $depend_xml = parse_xml_config_pkg("/usr/local/pkg/{$depend_file}", "packagegui"); - if (!empty($depend_xml)) - $depends[] = $depend_xml['name']; - } else - $depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename. - break; - case ".xml": - $depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui"); - if (!empty($depend_xml)) - $depends[] = $depend_xml['name']; - break; - default: - $depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have). - break; } } + if ($item['prefix'] != "") { + $prefix = $item['prefix']; + } else { + $prefix = "/usr/local/pkg/"; + } + // Ensure that the prefix exists to avoid installation errors. + if (!is_dir($prefix)) { + exec("/bin/mkdir -p {$prefix}"); + } + if (!file_exists($prefix . $depend_file)) { + log_error(sprintf(gettext("The %s package is missing required dependencies and must be reinstalled."), $package['name'])); + } + switch ($format) { + case "files": + $depends[] = $prefix . $depend_file; + break; + case "names": + switch ($filetype) { + case "all": + if (preg_match("/\.xml/i", $depend_file)) { + $depend_xml = parse_xml_config_pkg("/usr/local/pkg/{$depend_file}", "packagegui"); + if (!empty($depend_xml)) { + $depends[] = $depend_xml['name']; + } + } else { + $depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename. + } + break; + case ".xml": + $depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui"); + if (!empty($depend_xml)) { + $depends[] = $depend_xml['name']; + } + break; + default: + $depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have). + break; + } + } } return $depends; } @@ -344,8 +368,9 @@ function uninstall_package($pkg_name) { $static_output .= "Removing package...\n"; update_output_window($static_output); if (is_array($pkg_depends)) { - foreach ($pkg_depends as $pkg_depend) + foreach ($pkg_depends as $pkg_depend) { delete_package($pkg_depend); + } } else { // The packages (1 or more) are all in one long string. // We need to pass them 1 at a time to delete_package. @@ -376,39 +401,45 @@ function force_remove_package($pkg_name) { function sync_package($pkg_name, $sync_depends = true, $show_message = false) { global $config, $config_parsed; global $builder_package_install; - - // If this code is being called by pfspkg_installer - // which the builder system uses then return (ignore). - if($builder_package_install) - return; - - if(empty($config['installedpackages']['package'])) - return; - if(!is_numeric($pkg_name)) { - $pkg_id = get_pkg_id($pkg_name); - if($pkg_id == -1) - return -1; // This package doesn't really exist - exit the function. - } else - $pkg_id = $pkg_name; - if(!is_array($config['installedpackages']['package'][$pkg_id])) + // If this code is being called by pfspkg_installer + // which the builder system uses then return (ignore). + if ($builder_package_install) { + return; + } + + if (empty($config['installedpackages']['package'])) { + return; + } + if (!is_numeric($pkg_name)) { + $pkg_id = get_pkg_id($pkg_name); + if ($pkg_id == -1) { + return -1; // This package doesn't really exist - exit the function. + } + } else { + $pkg_id = $pkg_name; + } + + if (!is_array($config['installedpackages']['package'][$pkg_id])) { return; // No package belongs to the pkg_id passed to this function. + } $package =& $config['installedpackages']['package'][$pkg_id]; - if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) { + if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) { log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name'])); force_remove_package($package['name']); return -1; } $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui"); - if(isset($pkg_config['nosync'])) + if (isset($pkg_config['nosync'])) { return; + } /* Bring in package include files */ if (!empty($pkg_config['include_file'])) { $include_file = $pkg_config['include_file']; - if (file_exists($include_file)) + if (file_exists($include_file)) { require_once($include_file); - else { + } else { /* XXX: What the heck is this?! */ log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!"); uninstall_package($package['name']); @@ -419,15 +450,17 @@ function sync_package($pkg_name, $sync_depends = true, $show_message = false) { } } - if(!empty($pkg_config['custom_php_global_functions'])) + if (!empty($pkg_config['custom_php_global_functions'])) { eval($pkg_config['custom_php_global_functions']); - if(!empty($pkg_config['custom_php_resync_config_command'])) + } + if (!empty($pkg_config['custom_php_resync_config_command'])) { eval($pkg_config['custom_php_resync_config_command']); - if($sync_depends == true) { + } + if ($sync_depends == true) { $depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking. - if(is_array($depends)) { - foreach($depends as $item) { - if(!file_exists($item)) { + if (is_array($depends)) { + foreach ($depends as $item) { + if (!file_exists($item)) { require_once("notices.inc"); file_notice($package['name'], sprintf(gettext("The %s package is missing required dependencies and must be reinstalled."), $package['name']), "Packages", "/pkg_mgr_install.php?mode=reinstallpkg&pkg={$package['name']}", 1); log_error("Could not find {$item}. Reinstalling package."); @@ -438,24 +471,29 @@ function sync_package($pkg_name, $sync_depends = true, $show_message = false) { } } else { $item_config = parse_xml_config_pkg($item, "packagegui"); - if (empty($item_config)) + if (empty($item_config)) { continue; - if(isset($item_config['nosync'])) + } + if (isset($item_config['nosync'])) { continue; + } if (!empty($item_config['include_file'])) { - if (file_exists($item_config['include_file'])) + if (file_exists($item_config['include_file'])) { require_once($item_config['include_file']); - else { + } else { log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing."); continue; } } - if($item_config['custom_php_global_functions'] <> "") + if ($item_config['custom_php_global_functions'] <> "") { eval($item_config['custom_php_global_functions']); - if($item_config['custom_php_resync_config_command'] <> "") + } + if ($item_config['custom_php_resync_config_command'] <> "") { eval($item_config['custom_php_resync_config_command']); - if($show_message == true) + } + if ($show_message == true) { print " " . $item_config['name']; + } } } } @@ -475,13 +513,14 @@ function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = $filename = str_replace(" ", " ", $filename); $pkgs = explode(" ", $filename); - foreach($pkgs as $filename) { + foreach ($pkgs as $filename) { $filename = trim($filename); if ($g['platform'] == "nanobsd") { $pkgtmpdir = "/usr/bin/env PKG_TMPDIR=/root/ "; $pkgstagingdir = "/root/tmp"; - if (!is_dir($pkgstagingdir)) + if (!is_dir($pkgstagingdir)) { mkdir($pkgstagingdir); + } $pkgstaging = "-o {$pkgstagingdir}/instmp.XXXXXX"; $fetchdir = $pkgstagingdir; } else { @@ -491,10 +530,12 @@ function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = /* FreeBSD has no PBI's hosted, so fall back to our own URL for now. (Maybe fail to PC-BSD?) */ $rel = get_freebsd_version(); $priv_url = "https://files.pfsense.org/packages/{$rel}/All/"; - if (empty($base_url)) + if (empty($base_url)) { $base_url = $priv_url; - if (substr($base_url, -1) == "/") + } + if (substr($base_url, -1) == "/") { $base_url = substr($base_url, 0, -1); + } $fetchto = "{$fetchdir}/apkg_{$filename}"; $static_output .= "\n" . str_repeat(" ", $dependlevel * 2 + 1) . "Downloading {$base_url}/{$filename} ... "; if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto) !== true) { @@ -517,8 +558,9 @@ function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = $pkgaddout = ""; $no_checksig = ""; - if (isset($config['system']['pkg_nochecksig'])) + if (isset($config['system']['pkg_nochecksig'])) { $no_checksig = "--no-checksig"; + } $result = exec("/usr/local/sbin/pbi_add " . $pkgstaging . " -f -v {$no_checksig} " . escapeshellarg($fetchto) . " 2>&1", $pkgaddout, $rc); pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\n"); @@ -529,7 +571,7 @@ function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = $pbi_prefix = $pbi_prefix[0]; $links = get_pbi_binaries(escapeshellarg($pbi_name)); - foreach($links as $link) { + foreach ($links as $link) { @unlink("/usr/local/{$link['link_name']}"); @symlink("{$link['target']}","/usr/local/{$link['link_name']}"); } @@ -544,17 +586,20 @@ function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = ); foreach ($extra_links as $link) { - if (!file_exists($pbi_prefix . "/" . $link['target'])) + if (!file_exists($pbi_prefix . "/" . $link['target'])) { continue; + } @rmdir("{$pbi_prefix}/{$link['link_name']}"); unlink_if_exists("{$pbi_prefix}/{$link['link_name']}"); @symlink("{$pbi_prefix}/{$link['target']}", "{$pbi_prefix}/{$link['link_name']}"); } pkg_debug("pbi_add successfully completed.\n"); } else { - if (is_array($pkgaddout)) - foreach ($pkgaddout as $line) + if (is_array($pkgaddout)) { + foreach ($pkgaddout as $line) { $static_output .= " " . $line .= "\n"; + } + } update_output_window($static_output); pkg_debug("pbi_add failed.\n"); @@ -567,25 +612,29 @@ function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = function get_pbi_binaries($pbi) { $result = array(); - if (empty($pbi)) + if (empty($pbi)) { return $result; + } $gb = exec("/usr/local/sbin/pbi_info {$pbi} | /usr/bin/awk '/Prefix/ {print $2}'", $pbi_prefix); $pbi_prefix = $pbi_prefix[0]; - if (empty($pbi_prefix)) + if (empty($pbi_prefix)) { return $result; + } - foreach(array('bin', 'sbin') as $dir) { - if(!is_dir("{$pbi_prefix}/{$dir}")) + foreach (array('bin', 'sbin') as $dir) { + if (!is_dir("{$pbi_prefix}/{$dir}")) { continue; + } $files = glob("{$pbi_prefix}/{$dir}/*.pbiopt"); - foreach($files as $f) { + foreach ($files as $f) { $pbiopts = file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - foreach($pbiopts as $pbiopt) { - if (!preg_match('/^TARGET:\s+(.*)$/', $pbiopt, $matches)) + foreach ($pbiopts as $pbiopt) { + if (!preg_match('/^TARGET:\s+(.*)$/', $pbiopt, $matches)) { continue; + } $result[] = array( 'target' => preg_replace('/\.pbiopt$/', '', $f), @@ -604,10 +653,11 @@ function install_package($package, $pkg_info = "", $force_install = false) { /* safe side. Write config below will send to ro again. */ conf_mount_rw(); - if($pkg_interface == "console") + if ($pkg_interface == "console") { echo "\n"; + } /* fetch package information if needed */ - if(empty($pkg_info) or !is_array($pkg_info[$package])) { + if (empty($pkg_info) or !is_array($pkg_info[$package])) { $pkg_info = get_pkg_info(array($package)); $pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array. if (empty($pkg_info)) { @@ -618,17 +668,19 @@ function install_package($package, $pkg_info = "", $force_install = false) { if (!$force_install) { $compatible = true; $version = rtrim(file_get_contents("/etc/version")); - - if (isset($pkg_info['required_version'])) + + if (isset($pkg_info['required_version'])) { $compatible = (pfs_version_compare("", $version, $pkg_info['required_version']) >= 0); - if (isset($pkg_info['maximum_version'])) + } + if (isset($pkg_info['maximum_version'])) { $compatible = $compatible && (pfs_version_compare("", $version, $pkg_info['maximum_version']) <= 0); - + } + if (!$compatible) { log_error(sprintf(gettext('Package %s is not supported on this version.'), $pkg_info['name'])); $static_output .= sprintf(gettext("Package %s is not supported on this version."), $pkg_info['name']); update_status($static_output); - + conf_mount_ro(); return -1; } @@ -645,7 +697,7 @@ function install_package($package, $pkg_info = "", $force_install = false) { $pkgid = get_pkg_id($pkg_info['name']); $static_output .= gettext("Saving updated package information...") . " "; update_output_window($static_output); - if($pkgid == -1) { + if ($pkgid == -1) { $config['installedpackages']['package'][] = $pkg_info; $changedesc = sprintf(gettext("Installed %s package."),$pkg_info['name']); $to_output = gettext("done.") . "\n"; @@ -654,8 +706,9 @@ function install_package($package, $pkg_info = "", $force_install = false) { $changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']); $to_output = gettext("overwrite!") . "\n"; } - if(file_exists('/conf/needs_package_sync')) + if (file_exists('/conf/needs_package_sync')) { @unlink('/conf/needs_package_sync'); + } conf_mount_ro(); write_config("Intermediate config write during package install for {$pkg_info['name']}."); $static_output .= $to_output; @@ -675,27 +728,31 @@ function install_package($package, $pkg_info = "", $force_install = false) { log_error(sprintf(gettext("Successfully installed package: %s."), $pkg_info['name'])); $static_output .= gettext("done.") . "\n"; update_output_window($static_output); - if($pkg_info['after_install_info']) - update_output_window($pkg_info['after_install_info']); + if ($pkg_info['after_install_info']) { + update_output_window($pkg_info['after_install_info']); + } } } function get_after_install_info($package) { global $pkg_info; /* fetch package information if needed */ - if(!$pkg_info or !is_array($pkg_info[$package])) { + if (!$pkg_info or !is_array($pkg_info[$package])) { $pkg_info = get_pkg_info(array($package)); $pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array. } - if($pkg_info['after_install_info']) + if ($pkg_info['after_install_info']) { return $pkg_info['after_install_info']; + } } function eval_once($toeval) { global $evaled; - if(!$evaled) $evaled = array(); + if (!$evaled) { + $evaled = array(); + } $evalmd5 = md5($toeval); - if(!in_array($evalmd5, $evaled)) { + if (!in_array($evalmd5, $evaled)) { @eval($toeval); $evaled[] = $evalmd5; } @@ -705,28 +762,30 @@ function eval_once($toeval) { function install_package_xml($pkg) { global $g, $config, $static_output, $pkg_interface, $config_parsed; - if(($pkgid = get_pkg_id($pkg)) == -1) { + if (($pkgid = get_pkg_id($pkg)) == -1) { $static_output .= sprintf(gettext("The %s package is not installed.%sInstallation aborted."), $pkg, "\n\n"); update_output_window($static_output); - if($pkg_interface <> "console") { + if ($pkg_interface <> "console") { echo "\n"; echo "\n"; } sleep(1); return false; - } else + } else { $pkg_info = $config['installedpackages']['package'][$pkgid]; + } /* pkg_add the package and its dependencies */ - if($pkg_info['depends_on_package_base_url'] != "") { - if($pkg_interface == "console") + if ($pkg_info['depends_on_package_base_url'] != "") { + if ($pkg_interface == "console") { echo "\n"; + } update_status(gettext("Installing") . " " . $pkg_info['name'] . " " . gettext("and its dependencies.")); $static_output .= gettext("Downloading") . " " . $pkg_info['name'] . " " . gettext("and its dependencies... "); $static_orig = $static_output; $static_output .= "\n"; update_output_window($static_output); - foreach((array) $pkg_info['depends_on_package_pbi'] as $pkgdep) { + foreach ((array) $pkg_info['depends_on_package_pbi'] as $pkgdep) { $pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1); $static_output = $static_orig . "\nChecking for package installation... "; update_output_window($static_output); @@ -735,7 +794,7 @@ function install_package_xml($pkg) { $static_output .= "of {$pkg_name} failed!\n\nInstallation aborted."; update_output_window($static_output); pkg_debug(gettext("Package WAS NOT installed properly.") . "\n"); - if($pkg_interface <> "console") { + if ($pkg_interface <> "console") { echo "\n"; echo "\n"; } @@ -747,22 +806,23 @@ function install_package_xml($pkg) { } $configfile = substr(strrchr($pkg_info['config_file'], '/'), 1); - if(file_exists("/usr/local/pkg/" . $configfile)) { + if (file_exists("/usr/local/pkg/" . $configfile)) { $static_output .= gettext("Loading package configuration... "); update_output_window($static_output); $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui"); $static_output .= gettext("done.") . "\n"; update_output_window($static_output); $static_output .= gettext("Configuring package components...\n"); - if (!empty($pkg_config['filter_rules_needed'])) + if (!empty($pkg_config['filter_rules_needed'])) { $config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed']; + } update_output_window($static_output); /* modify system files */ - if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) { + if (is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) { $static_output .= gettext("System files... "); update_output_window($static_output); - foreach($pkg_config['modify_system']['item'] as $ms) { - if($ms['textneeded']) { + foreach ($pkg_config['modify_system']['item'] as $ms) { + if ($ms['textneeded']) { add_text_to_file($ms['modifyfilename'], $ms['textneeded']); } } @@ -777,13 +837,13 @@ function install_package_xml($pkg) { * instead of making us blindly guess */ $missing_include = false; - if($pkg_config['include_file'] <> "") { + if ($pkg_config['include_file'] <> "") { $static_output .= gettext("Loading package instructions...") . "\n"; update_output_window($static_output); pkg_debug("require_once('{$pkg_config['include_file']}')\n"); - if (file_exists($pkg_config['include_file'])) + if (file_exists($pkg_config['include_file'])) { require_once($pkg_config['include_file']); - else { + } else { $missing_include = true; $static_output .= "Include " . basename($pkg_config['include_file']) . " is missing!\n"; update_output_window($static_output); @@ -796,14 +856,14 @@ function install_package_xml($pkg) { $static_output .= gettext("Custom commands...") . "\n"; update_output_window($static_output); if ($missing_include == false) { - if($pkg_config['custom_php_global_functions'] <> "") { + if ($pkg_config['custom_php_global_functions'] <> "") { $static_output .= gettext("Executing custom_php_global_functions()..."); update_output_window($static_output); eval_once($pkg_config['custom_php_global_functions']); $static_output .= gettext("done.") . "\n"; update_output_window($static_output); } - if($pkg_config['custom_php_install_command']) { + if ($pkg_config['custom_php_install_command']) { $static_output .= gettext("Executing custom_php_install_command()..."); update_output_window($static_output); /* XXX: create symlinks for conf files into the PBI directories. @@ -817,12 +877,12 @@ function install_package_xml($pkg) { exec("/usr/local/sbin/pbi_info | grep '^{$pkg_name_for_pbi_match}' | xargs /usr/local/sbin/pbi_info | awk '/Prefix/ {print $2}'",$pbidirarray); $pbidir0 = $pbidirarray[0]; exec("find /usr/local/etc/ -name *.conf | grep " . escapeshellarg($pkg),$files); - foreach($files as $f) { + foreach ($files as $f) { $pbiconf = str_replace('/usr/local',$pbidir0,$f); - if(is_file($pbiconf) || is_link($pbiconf)) { + if (is_file($pbiconf) || is_link($pbiconf)) { unlink($pbiconf); } - if(is_dir(dirname($pbiconf))) { + if (is_dir(dirname($pbiconf))) { symlink($f,$pbiconf); } else { log_error("The dir for {$pbiconf} does not exist. Cannot add symlink to {$f}."); @@ -832,7 +892,7 @@ function install_package_xml($pkg) { $static_output .= gettext("done.") . "\n"; update_output_window($static_output); } - if($pkg_config['custom_php_resync_config_command'] <> "") { + if ($pkg_config['custom_php_resync_config_command'] <> "") { $static_output .= gettext("Executing custom_php_resync_config_command()..."); update_output_window($static_output); eval_once($pkg_config['custom_php_resync_config_command']); @@ -841,48 +901,57 @@ function install_package_xml($pkg) { } } /* sidebar items */ - if(is_array($pkg_config['menu'])) { + if (is_array($pkg_config['menu'])) { $static_output .= gettext("Menu items... "); update_output_window($static_output); - foreach($pkg_config['menu'] as $menu) { - if(is_array($config['installedpackages']['menu'])) { - foreach($config['installedpackages']['menu'] as $amenu) - if($amenu['name'] == $menu['name']) + foreach ($pkg_config['menu'] as $menu) { + if (is_array($config['installedpackages']['menu'])) { + foreach ($config['installedpackages']['menu'] as $amenu) { + if ($amenu['name'] == $menu['name']) { continue 2; - } else + } + } + } else { $config['installedpackages']['menu'] = array(); + } $config['installedpackages']['menu'][] = $menu; } $static_output .= gettext("done.") . "\n"; update_output_window($static_output); } /* integrated tab items */ - if(is_array($pkg_config['tabs']['tab'])) { + if (is_array($pkg_config['tabs']['tab'])) { $static_output .= gettext("Integrated Tab items... "); update_output_window($static_output); - foreach($pkg_config['tabs']['tab'] as $tab) { - if(is_array($config['installedpackages']['tab'])) { - foreach($config['installedpackages']['tab'] as $atab) - if($atab['name'] == $tab['name']) + foreach ($pkg_config['tabs']['tab'] as $tab) { + if (is_array($config['installedpackages']['tab'])) { + foreach ($config['installedpackages']['tab'] as $atab) { + if ($atab['name'] == $tab['name']) { continue 2; - } else + } + } + } else { $config['installedpackages']['tab'] = array(); + } $config['installedpackages']['tab'][] = $tab; } $static_output .= gettext("done.") . "\n"; update_output_window($static_output); } /* services */ - if(is_array($pkg_config['service'])) { + if (is_array($pkg_config['service'])) { $static_output .= gettext("Services... "); update_output_window($static_output); - foreach($pkg_config['service'] as $service) { - if(is_array($config['installedpackages']['service'])) { - foreach($config['installedpackages']['service'] as $aservice) - if($aservice['name'] == $service['name']) + foreach ($pkg_config['service'] as $service) { + if (is_array($config['installedpackages']['service'])) { + foreach ($config['installedpackages']['service'] as $aservice) { + if ($aservice['name'] == $service['name']) { continue 2; - } else + } + } + } else { $config['installedpackages']['service'] = array(); + } $config['installedpackages']['service'][] = $service; } $static_output .= gettext("done.") . "\n"; @@ -892,7 +961,7 @@ function install_package_xml($pkg) { $static_output .= gettext("Loading package configuration... failed!") . "\n\n" . gettext("Installation aborted."); update_output_window($static_output); pkg_debug(gettext("Unable to load package configuration. Installation aborted.") ."\n"); - if($pkg_interface <> "console") { + if ($pkg_interface <> "console") { echo "\n"; echo "\n"; } @@ -901,7 +970,7 @@ function install_package_xml($pkg) { } /* set up package logging streams */ - if($pkg_info['logging']) { + if ($pkg_info['logging']) { mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}"); @chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600); add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']); @@ -914,14 +983,16 @@ function install_package_xml($pkg) { function does_package_depend($pkg) { // Should not happen, but just in case. - if(!$pkg) + if (!$pkg) { return; + } $pkg_var_db_dir = glob("/var/db/pkg/{$pkg}*"); // If this package has dependency then return true - foreach($pkg_var_db_dir as $pvdd) { - if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) + foreach ($pkg_var_db_dir as $pvdd) { + if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) { return true; - } + } + } // Did not find a record of dependencies, so return false. return false; } @@ -929,14 +1000,16 @@ function does_package_depend($pkg) { function delete_package($pkg) { global $config, $g, $static_output, $vardb; - if(!$pkg) + if (!$pkg) { return; + } // Note: $pkg has the full PBI package name followed by ".pbi". Strip off ".pbi". $pkg = substr(reverse_strrchr($pkg, "."), 0, -1); - if($pkg) + if ($pkg) { $static_output .= sprintf(gettext("Starting package deletion for %s..."),$pkg); + } update_output_window($static_output); remove_freebsd_package($pkg); @@ -958,7 +1031,7 @@ function delete_package_xml($pkg) { if ($pkgid == -1) { $static_output .= sprintf(gettext("The %s package is not installed.%sDeletion aborted."), $pkg, "\n\n"); update_output_window($static_output); - if($pkg_interface <> "console") { + if ($pkg_interface <> "console") { echo "\n"; echo "\n"; } @@ -976,16 +1049,16 @@ function delete_package_xml($pkg) { $menus =& $config['installedpackages']['menu']; $services = &$config['installedpackages']['service']; $pkg_info =& $packages[$pkgid]; - if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) { + if (file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) { $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui"); /* remove tab items */ - if(is_array($pkg_config['tabs'])) { + if (is_array($pkg_config['tabs'])) { $static_output .= gettext("Tabs items... "); update_output_window($static_output); - if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) { - foreach($pkg_config['tabs']['tab'] as $tab) { - foreach($tabs as $key => $insttab) { - if($insttab['name'] == $tab['name']) { + if (is_array($pkg_config['tabs']['tab']) && is_array($tabs)) { + foreach ($pkg_config['tabs']['tab'] as $tab) { + foreach ($tabs as $key => $insttab) { + if ($insttab['name'] == $tab['name']) { unset($tabs[$key]); break; } @@ -996,13 +1069,13 @@ function delete_package_xml($pkg) { update_output_window($static_output); } /* remove menu items */ - if(is_array($pkg_config['menu'])) { + if (is_array($pkg_config['menu'])) { $static_output .= gettext("Menu items... "); update_output_window($static_output); if (is_array($pkg_config['menu']) && is_array($menus)) { - foreach($pkg_config['menu'] as $menu) { - foreach($menus as $key => $instmenu) { - if($instmenu['name'] == $menu['name']) { + foreach ($pkg_config['menu'] as $menu) { + foreach ($menus as $key => $instmenu) { + if ($instmenu['name'] == $menu['name']) { unset($menus[$key]); break; } @@ -1013,21 +1086,24 @@ function delete_package_xml($pkg) { update_output_window($static_output); } /* remove services */ - if(is_array($pkg_config['service'])) { + if (is_array($pkg_config['service'])) { $static_output .= gettext("Services... "); update_output_window($static_output); if (is_array($pkg_config['service']) && is_array($services)) { - foreach($pkg_config['service'] as $service) { - foreach($services as $key => $instservice) { - if($instservice['name'] == $service['name']) { - if(platform_booting() != true) + foreach ($pkg_config['service'] as $service) { + foreach ($services as $key => $instservice) { + if ($instservice['name'] == $service['name']) { + if (platform_booting() != true) { stop_service($service['name']); - if($service['rcfile']) { + } + if ($service['rcfile']) { $prefix = RCFILEPREFIX; - if (!empty($service['prefix'])) + if (!empty($service['prefix'])) { $prefix = $service['prefix']; - if (file_exists("{$prefix}{$service['rcfile']}")) + } + if (file_exists("{$prefix}{$service['rcfile']}")) { @unlink("{$prefix}{$service['rcfile']}"); + } } unset($services[$key]); } @@ -1049,13 +1125,13 @@ function delete_package_xml($pkg) { * instead of making us blindly guess */ $missing_include = false; - if($pkg_config['include_file'] <> "") { + if ($pkg_config['include_file'] <> "") { $static_output .= gettext("Loading package instructions...") . "\n"; update_output_window($static_output); pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n"); - if (file_exists($pkg_config['include_file'])) + if (file_exists($pkg_config['include_file'])) { require_once($pkg_config['include_file']); - else { + } else { $missing_include = true; update_output_window($static_output); $static_output .= "Include file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n"; @@ -1066,34 +1142,40 @@ function delete_package_xml($pkg) { * So we prevent it from being run at all to not interrupt all the other code. */ if ($missing_include == false) { - /* evalate this package's global functions and pre deinstall commands */ - if($pkg_config['custom_php_global_functions'] <> "") + /* evaluate this package's global functions and pre deinstall commands */ + if ($pkg_config['custom_php_global_functions'] <> "") { eval_once($pkg_config['custom_php_global_functions']); - if($pkg_config['custom_php_pre_deinstall_command'] <> "") + } + if ($pkg_config['custom_php_pre_deinstall_command'] <> "") { eval_once($pkg_config['custom_php_pre_deinstall_command']); + } } /* system files */ - if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) { + if (is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) { $static_output .= gettext("System files... "); update_output_window($static_output); - foreach($pkg_config['modify_system']['item'] as $ms) - if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']); + foreach ($pkg_config['modify_system']['item'] as $ms) { + if ($ms['textneeded']) { + remove_text_from_file($ms['modifyfilename'], $ms['textneeded']); + } + } $static_output .= gettext("done.") . "\n"; update_output_window($static_output); } /* deinstall commands */ - if($pkg_config['custom_php_deinstall_command'] <> "") { + if ($pkg_config['custom_php_deinstall_command'] <> "") { $static_output .= gettext("Deinstall commands... "); update_output_window($static_output); if ($missing_include == false) { eval_once($pkg_config['custom_php_deinstall_command']); $static_output .= gettext("done.") . "\n"; - } else + } else { $static_output .= "\nNot executing custom deinstall hook because an include is missing.\n"; + } update_output_window($static_output); } - if($pkg_config['include_file'] <> "") { + if ($pkg_config['include_file'] <> "") { $static_output .= gettext("Removing package instructions..."); update_output_window($static_output); pkg_debug(sprintf(gettext("Remove '%s'"), $pkg_config['include_file']) . "\n"); @@ -1102,15 +1184,16 @@ function delete_package_xml($pkg) { update_output_window($static_output); } /* remove all additional files */ - if(is_array($pkg_config['additional_files_needed'])) { + if (is_array($pkg_config['additional_files_needed'])) { $static_output .= gettext("Auxiliary files... "); update_output_window($static_output); - foreach($pkg_config['additional_files_needed'] as $afn) { + foreach ($pkg_config['additional_files_needed'] as $afn) { $filename = get_filename_from_url($afn['item'][0]); - if($afn['prefix'] <> "") + if ($afn['prefix'] <> "") { $prefix = $afn['prefix']; - else + } else { $prefix = "/usr/local/pkg/"; + } unlink_if_exists($prefix . $filename); } $static_output .= gettext("done.") . "\n"; @@ -1124,7 +1207,7 @@ function delete_package_xml($pkg) { update_output_window($static_output); } /* syslog */ - if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") { + if (is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") { $static_output .= "Syslog entries... "; update_output_window($static_output); remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']); @@ -1133,7 +1216,7 @@ function delete_package_xml($pkg) { $static_output .= "done.\n"; update_output_window($static_output); } - + conf_mount_ro(); /* remove config.xml entries */ $static_output .= gettext("Configuration... "); @@ -1152,9 +1235,11 @@ function expand_to_bytes($size) { "B" => "0" ); $suffix = substr($size, -1); - if(!in_array($suffix, array_keys($conv))) return $size; + if (!in_array($suffix, array_keys($conv))) { + return $size; + } $size = substr($size, 0, -1); - for($i = 0; $i < $conv[$suffix]; $i++) { + for ($i = 0; $i < $conv[$suffix]; $i++) { $size *= 1024; } return $size; @@ -1166,20 +1251,25 @@ function get_pkg_db() { } function walk_depend($depend, $pkgdb = "", $alreadyseen = "") { - if(!$pkgdb) + if (!$pkgdb) { $pkgdb = get_pkg_db(); - if(!is_array($alreadyseen)) + } + if (!is_array($alreadyseen)) { $alreadyseen = array(); - if (!is_array($depend)) + } + if (!is_array($depend)) { $depend = array(); - foreach($depend as $adepend) { + } + foreach ($depend as $adepend) { $pkgname = reverse_strrchr($adepend['name'], '.'); - if(in_array($pkgname, $alreadyseen)) { + if (in_array($pkgname, $alreadyseen)) { continue; - } elseif(!in_array($pkgname, $pkgdb)) { + } elseif (!in_array($pkgname, $pkgdb)) { $size += expand_to_bytes($adepend['size']); $alreadyseen[] = $pkgname; - if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen); + if (is_array($adepend['depend'])) { + $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen); + } } } return $size; @@ -1187,14 +1277,17 @@ function walk_depend($depend, $pkgdb = "", $alreadyseen = "") { function get_package_install_size($pkg = 'all', $pkg_info = "") { global $config, $g; - if((!is_array($pkg)) and ($pkg != 'all')) + if ((!is_array($pkg)) and ($pkg != 'all')) { $pkg = array($pkg); + } $pkgdb = get_pkg_db(); - if(!$pkg_info) + if (!$pkg_info) { $pkg_info = get_pkg_sizes($pkg); - foreach($pkg as $apkg) { - if(!$pkg_info[$apkg]) + } + foreach ($pkg as $apkg) { + if (!$pkg_info[$apkg]) { continue; + } $toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb)); } return $toreturn; @@ -1202,10 +1295,10 @@ function get_package_install_size($pkg = 'all', $pkg_info = "") { function squash_from_bytes($size, $round = "") { $conv = array(1 => "B", "K", "M", "G"); - foreach($conv as $div => $suffix) { + foreach ($conv as $div => $suffix) { $sizeorig = $size; - if(($size /= 1024) < 1) { - if($round) { + if (($size /= 1024) < 1) { + if ($round) { $sizeorig = round($sizeorig, $round); } return $sizeorig . $suffix; @@ -1234,7 +1327,7 @@ function pkg_reinstall_all() { } $todo = array(); $all_names = array(); - foreach($config['installedpackages']['package'] as $package) { + foreach ($config['installedpackages']['package'] as $package) { $todo[] = array('name' => $package['name'], 'version' => $package['version']); $all_names[] = $package['name']; } @@ -1242,9 +1335,9 @@ function pkg_reinstall_all() { echo " >>> {$package_name_list}\n"; log_error($package_name_list); - foreach($todo as $pkgtodo) { + foreach ($todo as $pkgtodo) { $static_output = ""; - if($pkgtodo['name']) { + if ($pkgtodo['name']) { log_error(gettext("Uninstalling package") . " {$pkgtodo['name']}"); uninstall_package($pkgtodo['name']); log_error(gettext("Finished uninstalling package") . " {$pkgtodo['name']}"); @@ -1254,8 +1347,9 @@ function pkg_reinstall_all() { } } log_error(gettext("Finished reinstalling all packages.")); - } else + } else { echo "No packages are installed."; + } } function stop_packages() { @@ -1273,16 +1367,17 @@ function stop_packages() { log_error("Stopping all packages."); $rcfiles = glob(RCFILEPREFIX . "*.sh"); - if (!$rcfiles) + if (!$rcfiles) { $rcfiles = array(); - else { + } else { $rcfiles = array_flip($rcfiles); - if (!$rcfiles) + if (!$rcfiles) { $rcfiles = array(); + } } if (is_array($config['installedpackages']['package'])) { - foreach($config['installedpackages']['package'] as $package) { + foreach ($config['installedpackages']['package'] as $package) { echo " Stopping package {$package['name']}..."; $internal_name = get_pkg_internal_name($package); stop_service($internal_name); @@ -1296,8 +1391,9 @@ function stop_packages() { if ($shell) { echo " Stopping {$rcfile}..."; if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) { - if ($shell) + if ($shell) { pclose($shell); + } $shell = @popen("/bin/sh", "w"); } echo "done.\n"; @@ -1306,37 +1402,44 @@ function stop_packages() { } } -function package_skip_tests($index,$requested_version){ +function package_skip_tests($index,$requested_version) { global $config, $g; /* Get pfsense version*/ $version = rtrim(file_get_contents("/etc/version")); - - if($g['platform'] == "nanobsd") - if($index['noembedded']) + + if ($g['platform'] == "nanobsd") { + if ($index['noembedded']) { return true; - + } + } + /* If we are on not on HEAD, and the package wants it, skip */ - if ($version <> "HEAD" && $index['required_version'] == "HEAD" && $requested_version <> "other") + if ($version <> "HEAD" && $index['required_version'] == "HEAD" && $requested_version <> "other") { return true; - + } + /* If there is no required version, and the requested package version is not 'none', then skip */ - if (empty($index['required_version']) && $requested_version <> "none") + if (empty($index['required_version']) && $requested_version <> "none") { return true; - + } + /* If the requested version is not 'other', and the required version is newer than what we have, skip. */ - if($requested_version <> "other" && (pfs_version_compare("", $version, $index['required_version']) < 0)) + if ($requested_version <> "other" && (pfs_version_compare("", $version, $index['required_version']) < 0)) { return true; - - /* If the requestion version is 'other' and we are on the version requested, skip. */ - if($requested_version == "other" && (pfs_version_compare("", $version, $index['required_version']) == 0)) + } + + /* If the requested version is 'other' and we are on the version requested, skip. */ + if ($requested_version == "other" && (pfs_version_compare("", $version, $index['required_version']) == 0)) { return true; - + } + /* Package is only for an older version, lets skip */ - if($index['maximum_version'] && (pfs_version_compare("", $version, $index['maximum_version']) > 0)) + if ($index['maximum_version'] && (pfs_version_compare("", $version, $index['maximum_version']) > 0)) { return true; - - /* Do not skip package list */ + } + + /* Do not skip package list */ return false; } @@ -1401,10 +1504,11 @@ function check_package_server_ssl() { curl_close($ch); /* The result from curl is 1 on failure, 0 on success. */ - if ($verifyfail == 0) + if ($verifyfail == 0) { return true; - else + } else { return false; + } } /* Keep this message centrally since it will be used several times on pages @@ -1437,7 +1541,7 @@ function pkg_fetch_config_file($package, $pkg_info = "") { global $g, $config, $static_output, $pkg_interface; conf_mount_rw(); - if(empty($pkg_info) or !is_array($pkg_info[$package])) { + if (empty($pkg_info) or !is_array($pkg_info[$package])) { $pkg_info = get_pkg_info(array($package)); $pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array. if (empty($pkg_info)) { @@ -1447,17 +1551,17 @@ function pkg_fetch_config_file($package, $pkg_info = "") { } /* fetch the package's configuration file */ - if($pkg_info['config_file'] != "") { + if ($pkg_info['config_file'] != "") { $static_output .= "\n" . gettext("Downloading package configuration file... "); update_output_window($static_output); pkg_debug(gettext("Downloading package configuration file...") . "\n"); $fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1); download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto); - if(!file_exists('/usr/local/pkg/' . $fetchto)) { + if (!file_exists('/usr/local/pkg/' . $fetchto)) { pkg_debug(gettext("ERROR! Unable to fetch package configuration file. Aborting installation.") . "\n"); - if($pkg_interface == "console") + if ($pkg_interface == "console") { print "\n" . gettext("ERROR! Unable to fetch package configuration file. Aborting package installation.") . "\n"; - else { + } else { $static_output .= gettext("failed!\n\nInstallation aborted.\n"); update_output_window($static_output); echo "
      Show install log"; @@ -1477,7 +1581,7 @@ function pkg_fetch_additional_files($package, $pkg_info = "") { global $g, $config, $static_output, $pkg_interface; conf_mount_rw(); - if(empty($pkg_info) or !is_array($pkg_info[$package])) { + if (empty($pkg_info) or !is_array($pkg_info[$package])) { $pkg_info = get_pkg_info(array($package)); $pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array. if (empty($pkg_info)) { @@ -1487,31 +1591,34 @@ function pkg_fetch_additional_files($package, $pkg_info = "") { } $configfile = substr(strrchr($pkg_info['config_file'], '/'), 1); - if(file_exists("/usr/local/pkg/" . $configfile)) { + if (file_exists("/usr/local/pkg/" . $configfile)) { $static_output .= gettext("Loading package configuration... "); update_output_window($static_output); $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui"); $static_output .= gettext("done.") . "\n"; update_output_window($static_output); /* download additional files */ - if(is_array($pkg_config['additional_files_needed'])) { + if (is_array($pkg_config['additional_files_needed'])) { $static_output .= gettext("Additional files... "); $static_orig = $static_output; update_output_window($static_output); - foreach($pkg_config['additional_files_needed'] as $afn) { + foreach ($pkg_config['additional_files_needed'] as $afn) { $filename = get_filename_from_url($afn['item'][0]); - if($afn['chmod'] <> "") + if ($afn['chmod'] <> "") { $pkg_chmod = $afn['chmod']; - else + } else { $pkg_chmod = ""; + } - if($afn['prefix'] <> "") + if ($afn['prefix'] <> "") { $prefix = $afn['prefix']; - else + } else { $prefix = "/usr/local/pkg/"; + } - if(!is_dir($prefix)) + if (!is_dir($prefix)) { safe_mkdir($prefix); + } $static_output .= $filename . " "; update_output_window($static_output); if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename) !== true) { @@ -1520,13 +1627,13 @@ function pkg_fetch_additional_files($package, $pkg_info = "") { update_output_window($static_output); return false; } - if(stristr($filename, ".tgz") <> "") { + if (stristr($filename, ".tgz") <> "") { pkg_debug(gettext("Extracting tarball to -C for ") . $filename . "...\n"); $tarout = ""; exec("/usr/bin/tar xvzf " . escapeshellarg($prefix . $filename) . " -C / 2>&1", $tarout); pkg_debug(print_r($tarout, true) . "\n"); } - if($pkg_chmod <> "") { + if ($pkg_chmod <> "") { pkg_debug(sprintf(gettext('Changing file mode to %1$s for %2$s%3$s%4$s'), $pkg_chmod, $prefix, $filename, "\n")); @chmod($prefix . $filename, $pkg_chmod); system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}"); From 839966e3968c9d6355fe859b8788563403dc09fc Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sun, 1 Mar 2015 21:31:48 +0545 Subject: [PATCH 147/257] Ancient bug on upgrade_014_to_015 This code looked silly the way it was, with the construct: $var = $var; unset($var); Seems it was accidentally changed to this way many years ago by https://github.com/pfsense/pfsense/commit/588a183b0e58f09932ffef35cc0003cca2313aba IMHO we want to do the conversion to $config['system']['gateway'] here so that later config conversion will then process it as expected. Note that in a current (2.2) config there is not $config['system']['gateway'] but that is switched over later in upgrade_021_to_022 - which switches back to $config['interfaces']['wan']['gateway'] and then later config conversions do their thing with that. I guess this will only effect people who upgrade from some really old config (or monowall?) --- etc/inc/upgrade_config.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/upgrade_config.inc b/etc/inc/upgrade_config.inc index 71b97c8396..be70d73927 100644 --- a/etc/inc/upgrade_config.inc +++ b/etc/inc/upgrade_config.inc @@ -254,7 +254,7 @@ function upgrade_014_to_015() { /* Default route moved */ if (isset($config['interfaces']['wan']['gateway'])) if ($config['interfaces']['wan']['gateway'] <> "") - $config['interfaces']['wan']['gateway'] = $config['interfaces']['wan']['gateway']; + $config['system']['gateway'] = $config['interfaces']['wan']['gateway']; unset($config['interfaces']['wan']['gateway']); /* Queues are no longer interface specific */ From 860842334c922e719b7fb137e6348098eb8f937e Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Mon, 2 Mar 2015 22:48:59 +0545 Subject: [PATCH 148/257] Be safe use require_once in zeromq I was testing code and just doing stuff like: require_once("zeromq.inc"); in Diagnostics->Command Prompt, PHP Execute That brings an error because underneath that PHP Execute code it has already included auth.inc I guess zeromq.inc is used quite separately to the rest of the system, and must be OK just having a "require" here. But it seems safer to always use require_once, just in case it gets called in a new way/sequence. Comments welcome. --- etc/inc/zeromq.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/zeromq.inc b/etc/inc/zeromq.inc index 65589d0896..a8503fccdd 100644 --- a/etc/inc/zeromq.inc +++ b/etc/inc/zeromq.inc @@ -32,7 +32,7 @@ define('ZEROMQ_TRUE', 'true'); define('ZEROMQ_FASLE', 'false'); $do_not_include_config_gui_inc = true; -require("auth.inc"); +require_once("auth.inc"); //$debug = true; From 61e047a50339da4a0b6a9202f163950573e8a578 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Tue, 3 Mar 2015 00:11:10 +0545 Subject: [PATCH 149/257] Code style etc in r s --- etc/inc/radius.inc | 136 +-- etc/inc/rrd.inc | 112 +-- etc/inc/sasl.inc | 4 +- etc/inc/service-utils.inc | 210 +++-- etc/inc/services.inc | 933 ++++++++++++-------- etc/inc/shaper.inc | 1734 +++++++++++++++++++++++-------------- etc/inc/smtp.inc | 2 +- etc/inc/system.inc | 752 +++++++++------- 8 files changed, 2342 insertions(+), 1541 deletions(-) diff --git a/etc/inc/radius.inc b/etc/inc/radius.inc index bb8bf6cf80..709607f9a8 100644 --- a/etc/inc/radius.inc +++ b/etc/inc/radius.inc @@ -6,30 +6,30 @@ Copyright (c) 2003, Michael Bretterklieber All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. The names of the authors may not be used to endorse or promote products + 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - This code cannot simply be copied and put under the GNU Public License or + This code cannot simply be copied and put under the GNU Public License or any other GPL-like (LGPL, GPL2) License. This version of RADIUS.php has been modified by @@ -73,7 +73,7 @@ PEAR::loadExtension('radius'); * * Abstract base class for RADIUS * - * @package Auth_RADIUS + * @package Auth_RADIUS */ class Auth_RADIUS extends PEAR { @@ -138,7 +138,7 @@ class Auth_RADIUS extends PEAR { * * @return void */ - function Auth_RADIUS() + function Auth_RADIUS() { $this->PEAR(); } @@ -146,8 +146,8 @@ class Auth_RADIUS extends PEAR { /** * Adds a RADIUS server to the list of servers for requests. * - * At most 10 servers may be specified. When multiple servers - * are given, they are tried in round-robin fashion until a + * At most 10 servers may be specified. When multiple servers + * are given, they are tried in round-robin fashion until a * valid response is received * * @access public @@ -158,7 +158,7 @@ class Auth_RADIUS extends PEAR { * @param integer $maxtries Max. retries for each request * @return void */ - function addServer($servername = 'localhost', $port = 0, $sharedSecret = 'testing123', $timeout = 3, $maxtries = 2) + function addServer($servername = 'localhost', $port = 0, $sharedSecret = 'testing123', $timeout = 3, $maxtries = 2) { $this->_servers[] = array($servername, $port, $sharedSecret, $timeout, $maxtries); } @@ -169,7 +169,7 @@ class Auth_RADIUS extends PEAR { * @access public * @return string */ - function getError() + function getError() { return radius_strerror($this->res); } @@ -181,7 +181,7 @@ class Auth_RADIUS extends PEAR { * @param string $file Path to the configuration file * @return void */ - function setConfigfile($file) + function setConfigfile($file) { $this->_configfile = $file; } @@ -195,7 +195,7 @@ class Auth_RADIUS extends PEAR { * @param type $type Attribute-type * @return bool true on success, false on error */ - function putAttribute($attrib, $value, $type = null) + function putAttribute($attrib, $value, $type = null) { if ($type == null) { $type = gettype($value); @@ -225,8 +225,8 @@ class Auth_RADIUS extends PEAR { * @param mixed $port Attribute-value * @param type $type Attribute-type * @return bool true on success, false on error - */ - function putVendorAttribute($vendor, $attrib, $value, $type = null) + */ + function putVendorAttribute($vendor, $attrib, $value, $type = null) { if ($type == null) { @@ -270,11 +270,11 @@ class Auth_RADIUS extends PEAR { } /** - * Overwrite this. + * Overwrite this. * * @access public */ - function open() + function open() { } @@ -339,7 +339,7 @@ class Auth_RADIUS extends PEAR { * @return bool true on success, false on error * @see addServer() */ - function putServer($servername, $port = 0, $sharedsecret = 'testing123', $timeout = 3, $maxtries = 3) + function putServer($servername, $port = 0, $sharedsecret = 'testing123', $timeout = 3, $maxtries = 3) { if (!radius_add_server($this->res, $servername, $port, $sharedsecret, $timeout, $maxtries)) { return false; @@ -354,7 +354,7 @@ class Auth_RADIUS extends PEAR { * @param string $servername Servername or IP-Address * @return bool true on success, false on error */ - function putConfigfile($file) + function putConfigfile($file) { if (!radius_config($this->res, $file)) { return false; @@ -363,11 +363,11 @@ class Auth_RADIUS extends PEAR { } /** - * Initiates a RADIUS request. + * Initiates a RADIUS request. * * @access public - * @return bool true on success, false on errors - */ + * @return bool true on success, false on errors + */ function start() { if (!$this->open()) { @@ -447,7 +447,7 @@ class Auth_RADIUS extends PEAR { if (!is_array($attrib)) { return false; - } + } $attr = $attrib['attr']; $data = $attrib['data']; @@ -592,7 +592,7 @@ class Auth_RADIUS extends PEAR { $this->attributes['url_logoff'] = radius_cvt_string($datav); break; } - } + } elseif ($vendor == 14122) { /* RADIUS_VENDOR_WISPr Wi-Fi Alliance */ @@ -719,9 +719,9 @@ class Auth_RADIUS extends PEAR { * * Class for authenticating using PAP (Plaintext) * - * @package Auth_RADIUS + * @package Auth_RADIUS */ -class Auth_RADIUS_PAP extends Auth_RADIUS +class Auth_RADIUS_PAP extends Auth_RADIUS { /** @@ -746,7 +746,7 @@ class Auth_RADIUS_PAP extends Auth_RADIUS * * @return bool true on success, false on error */ - function open() + function open() { $this->res = radius_auth_open(); if (!$this->res) { @@ -756,7 +756,7 @@ class Auth_RADIUS_PAP extends Auth_RADIUS } /** - * Creates an authentication request + * Creates an authentication request * * Creates an authentication request. * You MUST call this method before you can put any attribute @@ -772,7 +772,7 @@ class Auth_RADIUS_PAP extends Auth_RADIUS } /** - * Put authentication specific attributes + * Put authentication specific attributes * * @return void */ @@ -792,10 +792,10 @@ class Auth_RADIUS_PAP extends Auth_RADIUS * class Auth_RADIUS_CHAP_MD5 * * Class for authenticating using CHAP-MD5 see RFC1994. - * Instead og the plaintext password the challenge and + * Instead og the plaintext password the challenge and * the response are needed. * - * @package Auth_RADIUS + * @package Auth_RADIUS */ class Auth_RADIUS_CHAP_MD5 extends Auth_RADIUS_PAP { @@ -836,7 +836,7 @@ class Auth_RADIUS_CHAP_MD5 extends Auth_RADIUS_PAP /** * Put CHAP-MD5 specific attributes * - * For authenticating using CHAP-MD5 via RADIUS you have to put the challenge + * For authenticating using CHAP-MD5 via RADIUS you have to put the challenge * and the response. The chapid is inserted in the first byte of the response. * * @return void @@ -844,7 +844,7 @@ class Auth_RADIUS_CHAP_MD5 extends Auth_RADIUS_PAP function putAuthAttributes() { if (isset($this->username)) { - $this->putAttribute(RADIUS_USER_NAME, $this->username); + $this->putAttribute(RADIUS_USER_NAME, $this->username); } if (isset($this->response)) { $response = pack('C', $this->chapid) . $this->response; @@ -877,9 +877,9 @@ class Auth_RADIUS_CHAP_MD5 extends Auth_RADIUS_PAP * * Class for authenticating using MS-CHAPv1 see RFC2433 * - * @package Auth_RADIUS + * @package Auth_RADIUS */ -class Auth_RADIUS_MSCHAPv1 extends Auth_RADIUS_CHAP_MD5 +class Auth_RADIUS_MSCHAPv1 extends Auth_RADIUS_CHAP_MD5 { /** * LAN-Manager-Response @@ -895,9 +895,9 @@ class Auth_RADIUS_MSCHAPv1 extends Auth_RADIUS_CHAP_MD5 var $flags = 1; /** - * Put MS-CHAPv1 specific attributes + * Put MS-CHAPv1 specific attributes * - * For authenticating using MS-CHAPv1 via RADIUS you have to put the challenge + * For authenticating using MS-CHAPv1 via RADIUS you have to put the challenge * and the response. The response has this structure: * struct rad_mschapvalue { * u_char ident; @@ -930,9 +930,9 @@ class Auth_RADIUS_MSCHAPv1 extends Auth_RADIUS_CHAP_MD5 * * Class for authenticating using MS-CHAPv2 see RFC2759 * - * @package Auth_RADIUS + * @package Auth_RADIUS */ -class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1 +class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1 { /** * 16 Bytes binary challenge @@ -947,9 +947,9 @@ class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1 var $peerChallenge = null; /** - * Put MS-CHAPv2 specific attributes + * Put MS-CHAPv2 specific attributes * - * For authenticating using MS-CHAPv1 via RADIUS you have to put the challenge + * For authenticating using MS-CHAPv1 via RADIUS you have to put the challenge * and the response. The response has this structure: * struct rad_mschapv2value { * u_char ident; @@ -964,11 +964,11 @@ class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1 function putAuthAttributes() { if (isset($this->username)) { - $this->putAttribute(RADIUS_USER_NAME, $this->username); + $this->putAttribute(RADIUS_USER_NAME, $this->username); } if (isset($this->response) && isset($this->peerChallenge)) { - // Response: chapid, flags (1 = use NT Response), Peer challenge, reserved, Response - $resp = pack('CCa16a8a24',$this->chapid , 1, $this->peerChallenge, str_repeat("\0", 8), $this->response); + // Response: chapid, flags (1 = use NT Response), Peer challenge, reserved, Response + $resp = pack('CCa16a8a24',$this->chapid , 1, $this->peerChallenge, str_repeat("\0", 8), $this->response); $this->putVendorAttribute(RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP2_RESPONSE, $resp); } if (isset($this->challenge)) { @@ -983,7 +983,7 @@ class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1 * attributes are filled with Nullbytes to leave nothing in the mem. * * @access public - */ + */ function close() { Auth_RADIUS_MSCHAPv1::close(); @@ -995,10 +995,10 @@ class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1 * class Auth_RADIUS_Acct * * Class for RADIUS accounting - * - * @package Auth_RADIUS + * + * @package Auth_RADIUS */ -class Auth_RADIUS_Acct extends Auth_RADIUS +class Auth_RADIUS_Acct extends Auth_RADIUS { /** * Defines where the Authentication was made, possible values are: @@ -1011,19 +1011,19 @@ class Auth_RADIUS_Acct extends Auth_RADIUS * Defines the type of the accounting request, on of: * RADIUS_START, RADIUS_STOP, RADIUS_ACCOUNTING_ON, RADIUS_ACCOUNTING_OFF * @var integer - */ + */ var $status_type = null; /** * The time the user was logged in in seconds * @var integer - */ + */ var $session_time = null; /** * A uniq identifier for the session of the user, maybe the PHP-Session-Id * @var string - */ + */ var $session_id = null; /** @@ -1066,7 +1066,7 @@ class Auth_RADIUS_Acct extends Auth_RADIUS * * @return bool true on success, false on error */ - function open() + function open() { $this->res = radius_acct_open(); if (!$this->res) { @@ -1076,7 +1076,7 @@ class Auth_RADIUS_Acct extends Auth_RADIUS } /** - * Creates an accounting request + * Creates an accounting request * * Creates an accounting request. * You MUST call this method before you can put any attribute. @@ -1094,10 +1094,10 @@ class Auth_RADIUS_Acct extends Auth_RADIUS /** * Put attributes for accounting. * - * Here we put some accounting values. There many more attributes for accounting, + * Here we put some accounting values. There many more attributes for accounting, * but for web-applications only certain attributes make sense. * @return void - */ + */ function putAuthAttributes() { if (isset($this->username)) { @@ -1121,10 +1121,10 @@ class Auth_RADIUS_Acct extends Auth_RADIUS * class Auth_RADIUS_Acct_Start * * Class for RADIUS accounting. Its usualy used, after the user has logged in. - * + * * @package Auth_RADIUS */ -class Auth_RADIUS_Acct_Start extends Auth_RADIUS_Acct +class Auth_RADIUS_Acct_Start extends Auth_RADIUS_Acct { /** * Defines the type of the accounting request. diff --git a/etc/inc/rrd.inc b/etc/inc/rrd.inc index c620419f28..5aaff68636 100644 --- a/etc/inc/rrd.inc +++ b/etc/inc/rrd.inc @@ -61,14 +61,15 @@ function restore_rrd() { } unset($rrdrestore); $_gb = exec("cd /;LANG=C /usr/bin/tar -tf {$g['cf_conf_path']}/rrd.tgz", $rrdrestore, $rrdreturn); - if($rrdreturn != 0) { + if ($rrdreturn != 0) { log_error("RRD restore failed exited with $rrdreturn, the error is: $rrdrestore\n"); return; } foreach ($rrdrestore as $xml_file) { $rrd_file = '/' . substr($xml_file, 0, -4) . '.rrd'; - if (file_exists("{$rrd_file}")) + if (file_exists("{$rrd_file}")) { @unlink($rrd_file); + } file_put_contents("{$g['tmp_path']}/rrd_restore", $xml_file); $_gb = exec("cd /;LANG=C /usr/bin/tar -xf {$g['cf_conf_path']}/rrd.tgz -T {$g['tmp_path']}/rrd_restore"); if (!file_exists("/{$xml_file}")) { @@ -107,7 +108,7 @@ function create_new_rrd($rrdcreatecmd) { } function migrate_rrd_format($rrdoldxml, $rrdnewxml) { - if(!file_exists("/tmp/rrd_notice_sent.txt")) { + if (!file_exists("/tmp/rrd_notice_sent.txt")) { $_gb = exec("echo 'Converting RRD configuration to new format. This might take a bit...' | wall"); @touch("/tmp/rrd_notice_sent.txt"); } @@ -119,8 +120,8 @@ function migrate_rrd_format($rrdoldxml, $rrdnewxml) { /* add data sources not found in the old array from the new array */ $i = 0; - foreach($rrdnewxml['ds'] as $ds) { - if(!is_array($rrdoldxml['ds'][$i])) { + foreach ($rrdnewxml['ds'] as $ds) { + if (!is_array($rrdoldxml['ds'][$i])) { $rrdoldxml['ds'][$i] = $rrdnewxml['ds'][$i]; /* set unknown values to 0 */ $rrdoldxml['ds'][$i]['last_ds'] = " 0.0000000000e+00 "; @@ -134,16 +135,16 @@ function migrate_rrd_format($rrdoldxml, $rrdnewxml) { $rracountold = count($rrdoldxml['rra']); $rracountnew = count($rrdnewxml['rra']); /* process each RRA, which contain a database */ - foreach($rrdnewxml['rra'] as $rra) { - if(!is_array($rrdoldxml['rra'][$i])) { + foreach ($rrdnewxml['rra'] as $rra) { + if (!is_array($rrdoldxml['rra'][$i])) { $rrdoldxml['rra'][$i] = $rrdnewxml['rra'][$i]; } $d = 0; /* process cdp_prep */ $cdp_prep = $rra['cdp_prep']; - foreach($cdp_prep['ds'] as $ds) { - if(!is_array($rrdoldxml['rra'][$i]['cdp_prep']['ds'][$d])) { + foreach ($cdp_prep['ds'] as $ds) { + if (!is_array($rrdoldxml['rra'][$i]['cdp_prep']['ds'][$d])) { $rrdoldxml['rra'][$i]['cdp_prep']['ds'][$d] = $rrdnewxml['rra'][$i]['cdp_prep']['ds'][$d]; $rrdoldxml['rra'][$i]['cdp_prep']['ds'][$d]['primary_value'] = " 0.0000000000e+00 "; $rrdoldxml['rra'][$i]['cdp_prep']['ds'][$d]['secondary_value'] = " 0.0000000000e+00 "; @@ -163,28 +164,28 @@ function migrate_rrd_format($rrdoldxml, $rrdnewxml) { $rowsdata = $rows; $rowsempty = array(); $r = 0; - while($r < $rowcountdiff) { + while ($r < $rowcountdiff) { $rowsempty[] = $rrdnewxml['rra'][$i]['database']['row'][$r]; $r++; } $rows = $rowsempty + $rowsdata; /* now foreach the rows in the database */ - foreach($rows['row'] as $row) { - if(!is_array($rrdoldxml['rra'][$i]['database']['row'][$k])) { + foreach ($rows['row'] as $row) { + if (!is_array($rrdoldxml['rra'][$i]['database']['row'][$k])) { $rrdoldxml['rra'][$i]['database']['row'][$k] = $rrdnewxml['rra'][$i]['database']['row'][$k]; } $m = 0; $vcountold = count($rrdoldxml['rra'][$i]['database']['row'][$k]['v']); $vcountnew = count($rrdnewxml['rra'][$i]['database']['row'][$k]['v']); - foreach($row['v'] as $value) { - if(empty($rrdoldxml['rra'][$i]['database']['row'][$k]['v'][$m])) { - if(isset($valid)) { + foreach ($row['v'] as $value) { + if (empty($rrdoldxml['rra'][$i]['database']['row'][$k]['v'][$m])) { + if (isset($valid)) { $rrdoldxml['rra'][$i]['database']['row'][$k]['v'][$m] = "0.0000000000e+00 "; } else { $rrdoldxml['rra'][$i]['database']['row'][$k]['v'][$m] = $rrdnewxml['rra'][$i]['database']['row'][$k]['v'][$m]; } } else { - if($value <> " NaN ") { + if ($value <> " NaN ") { $valid = true; } else { $valid = false; @@ -206,8 +207,9 @@ function migrate_rrd_format($rrdoldxml, $rrdnewxml) { function enable_rrd_graphing() { global $config, $g, $altq_list_queues; - if(platform_booting()) + if (platform_booting()) { echo gettext("Generating RRD graphs..."); + } $rrddbpath = "/var/db/rrd/"; $rrdgraphpath = "/usr/local/www/rrd"; @@ -309,16 +311,17 @@ function enable_rrd_graphing() { /* IPsec counters */ $ifdescrs['ipsec'] = "IPsec"; /* OpenVPN server counters */ - if(is_array($config['openvpn']['openvpn-server'])) { - foreach($config['openvpn']['openvpn-server'] as $server) { + if (is_array($config['openvpn']['openvpn-server'])) { + foreach ($config['openvpn']['openvpn-server'] as $server) { $serverid = "ovpns" . $server['vpnid']; $ifdescrs[$serverid] = "{$server['description']}"; } } if (platform_booting()) { - if (!is_dir("{$g['vardb_path']}/rrd")) + if (!is_dir("{$g['vardb_path']}/rrd")) { mkdir("{$g['vardb_path']}/rrd", 0775); + } @chown("{$g['vardb_path']}/rrd", "nobody"); } @@ -326,7 +329,7 @@ function enable_rrd_graphing() { /* process all real and pseudo interfaces */ foreach ($ifdescrs as $ifname => $ifdescr) { $temp = get_real_interface($ifname); - if($temp <> "") { + if ($temp <> "") { $realif = $temp; } @@ -351,7 +354,7 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { + if (platform_booting()) { mwexec("$rrdtool update $rrddbpath$ifname$traffic N:U:U:U:U:U:U:U:U"); } @@ -384,7 +387,7 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { + if (platform_booting()) { mwexec("$rrdtool update $rrddbpath$ifname$packets N:U:U:U:U:U:U:U:U"); } @@ -397,7 +400,7 @@ function enable_rrd_graphing() { $rrdupdatesh .= "END {print b4pi \":\" b4po \":\" b4bi \":\" b4bo \":\" b6pi \":\" b6po \":\" b6bi \":\" b6bo};'`\n"; /* WIRELESS, set up the rrd file */ - if($config['interfaces'][$ifname]['wireless']['mode'] == "bss") { + if ($config['interfaces'][$ifname]['wireless']['mode'] == "bss") { if (!file_exists("$rrddbpath$ifname$wireless")) { $rrdcreate = "$rrdtool create $rrddbpath$ifname$wireless --step $rrdwirelessinterval "; $rrdcreate .= "DS:snr:GAUGE:$wirelessvalid:0:1000 "; @@ -413,7 +416,7 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { + if (platform_booting()) { mwexec("$rrdtool update $rrddbpath$ifname$wireless N:U:U:U"); } @@ -424,7 +427,7 @@ function enable_rrd_graphing() { } /* OpenVPN, set up the rrd file */ - if(stristr($ifname, "ovpns")) { + if (stristr($ifname, "ovpns")) { if (!file_exists("$rrddbpath$ifname$vpnusers")) { $rrdcreate = "$rrdtool create $rrddbpath$ifname$vpnusers --step $rrdvpninterval "; $rrdcreate .= "DS:users:GAUGE:$vpnvalid:0:10000 "; @@ -438,13 +441,13 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { + if (platform_booting()) { mwexec("$rrdtool update $rrddbpath$ifname$vpnusers N:U"); } - if(is_array($config['openvpn']['openvpn-server'])) { - foreach($config['openvpn']['openvpn-server'] as $server) { - if("ovpns{$server['vpnid']}" == $ifname) { + if (is_array($config['openvpn']['openvpn-server'])) { + foreach ($config['openvpn']['openvpn-server'] as $server) { + if ("ovpns{$server['vpnid']}" == $ifname) { $port = $server['local_port']; $vpnid = $server['vpnid']; } @@ -520,12 +523,12 @@ function enable_rrd_graphing() { unset($rrdcreate); } - if(platform_booting()) { + if (platform_booting()) { $rrdqcommand = "-t "; $rrducommand = "N"; $qi = 0; foreach ($qlist as $qname => $q) { - if($qi == 0) { + if ($qi == 0) { $rrdqcommand .= "{$qname}"; } else { $rrdqcommand .= ":{$qname}"; @@ -573,7 +576,7 @@ function enable_rrd_graphing() { } /* 3G interfaces */ - if(preg_match("/ppp[0-9]+/i", $realif)) { + if (preg_match("/ppp[0-9]+/i", $realif)) { if (!file_exists("$rrddbpath$ifname$cellular")) { $rrdcreate = "$rrdtool create $rrddbpath$ifname$cellular --step $rrdcellularinterval "; $rrdcreate .= "DS:rssi:GAUGE:$cellularvalid:0:100 "; @@ -588,7 +591,7 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { + if (platform_booting()) { mwexec("$rrdtool update $rrddbpath$ifname$cellular N:U:U:U"); } @@ -605,7 +608,7 @@ function enable_rrd_graphing() { $ifname = "system"; /* STATES, create pf states database */ - if(! file_exists("$rrddbpath$ifname$states")) { + if (!file_exists("$rrddbpath$ifname$states")) { $rrdcreate = "$rrdtool create $rrddbpath$ifname$states --step $rrdstatesinterval "; $rrdcreate .= "DS:pfrate:GAUGE:$statesvalid:0:10000000 "; $rrdcreate .= "DS:pfstates:GAUGE:$statesvalid:0:10000000 "; @@ -622,7 +625,7 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { + if (platform_booting()) { mwexec("$rrdtool update $rrddbpath$ifname$states N:U:U:U:U:U"); } @@ -640,7 +643,7 @@ function enable_rrd_graphing() { /* End pf states statistics */ /* CPU, create CPU statistics database */ - if(! file_exists("$rrddbpath$ifname$proc")) { + if (!file_exists("$rrddbpath$ifname$proc")) { $rrdcreate = "$rrdtool create $rrddbpath$ifname$proc --step $rrdprocinterval "; $rrdcreate .= "DS:user:GAUGE:$procvalid:0:10000000 "; $rrdcreate .= "DS:nice:GAUGE:$procvalid:0:10000000 "; @@ -657,7 +660,7 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { + if (platform_booting()) { mwexec("$rrdtool update $rrddbpath$ifname$proc N:U:U:U:U:U"); } @@ -670,7 +673,7 @@ function enable_rrd_graphing() { /* End CPU statistics */ /* Memory, create Memory statistics database */ - if(! file_exists("$rrddbpath$ifname$mem")) { + if (!file_exists("$rrddbpath$ifname$mem")) { $rrdcreate = "$rrdtool create $rrddbpath$ifname$mem --step $rrdmeminterval "; $rrdcreate .= "DS:active:GAUGE:$memvalid:0:10000000 "; $rrdcreate .= "DS:inactive:GAUGE:$memvalid:0:10000000 "; @@ -695,7 +698,7 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { + if (platform_booting()) { mwexec("$rrdtool update $rrddbpath$ifname$mem N:U:U:U:U:U"); } @@ -708,7 +711,7 @@ function enable_rrd_graphing() { /* End Memory statistics */ /* mbuf, create mbuf statistics database */ - if(! file_exists("$rrddbpath$ifname$mbuf")) { + if (!file_exists("$rrddbpath$ifname$mbuf")) { $rrdcreate = "$rrdtool create $rrddbpath$ifname$mbuf --step $rrdmbufinterval "; $rrdcreate .= "DS:current:GAUGE:$mbufvalid:0:10000000 "; $rrdcreate .= "DS:cache:GAUGE:$mbufvalid:0:10000000 "; @@ -732,7 +735,7 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { + if (platform_booting()) { mwexec("$rrdtool update $rrddbpath$ifname$mbuf N:U:U:U:U"); } @@ -745,7 +748,7 @@ function enable_rrd_graphing() { /* SPAMD, set up the spamd rrd file */ if (isset($config['installedpackages']['spamdsettings']) && - $config['installedpackages']['spamdsettings']['config'][0]['enablerrd']) { + $config['installedpackages']['spamdsettings']['config'][0]['enablerrd']) { /* set up the spamd rrd file */ if (!file_exists("$rrddbpath$ifname$spamd")) { $rrdcreate = "$rrdtool create $rrddbpath$ifname$spamd --step $rrdspamdinterval "; @@ -777,10 +780,11 @@ function enable_rrd_graphing() { /* End System statistics */ /* Captive Portal statistics, set up the rrd file */ - if(is_array($config['captiveportal'])) { + if (is_array($config['captiveportal'])) { foreach ($config['captiveportal'] as $cpkey => $cp) { - if (!isset($cp['enable'])) + if (!isset($cp['enable'])) { continue; + } $ifname= "captiveportal"; $concurrent_filename = $rrddbpath . $ifname . '-' . $cpkey . $captiveportalconcurrent; @@ -809,7 +813,7 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { + if (platform_booting()) { mwexec("$rrdtool update $concurrent_filename N:U"); } @@ -845,7 +849,7 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { + if (platform_booting()) { mwexec("$rrdtool update $loggedin_filename N:U"); } @@ -888,8 +892,8 @@ function enable_rrd_graphing() { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { - mwexec("$rrdtool update $rrddbpath$ntpd N:U:U:U:U:U:U"); + if (platform_booting()) { + mwexec("$rrdtool update $rrddbpath$ntpd N:U:U:U:U:U:U"); } /* the ntp stats gathering function. */ @@ -931,12 +935,13 @@ function enable_rrd_graphing() { } $databases = glob("{$rrddbpath}/*.rrd"); - foreach($databases as $database) { + foreach ($databases as $database) { chown($database, "nobody"); } - if(platform_booting()) + if (platform_booting()) { echo gettext("done.") . "\n"; + } } @@ -963,9 +968,10 @@ function create_gateway_quality_rrd($rrd_file) { } /* enter UNKNOWN values in the RRD so it knows we rebooted. */ - if(platform_booting()) { - if (!is_dir("{$g['vardb_path']}/rrd")) + if (platform_booting()) { + if (!is_dir("{$g['vardb_path']}/rrd")) { mkdir("{$g['vardb_path']}/rrd", 0775); + } @chown("{$g['vardb_path']}/rrd", "nobody"); diff --git a/etc/inc/sasl.inc b/etc/inc/sasl.inc index f6a8d0b26b..a9582dacec 100644 --- a/etc/inc/sasl.inc +++ b/etc/inc/sasl.inc @@ -178,7 +178,7 @@ class sasl_client_class Retrieve the values of one or more credentials to be used by the authentication mechanism classes. This is meant to be used by authentication mechanism driver - classes to retrieve the credentials that may be neede. + classes to retrieve the credentials that may be needed. The function may return SASL_CONTINUE if it succeeded, or SASL_NOMECH if it was not possible to retrieve one of the requested credentials. @@ -359,7 +359,7 @@ class sasl_client_class INTEGER Process the authentication steps after the initial step, - until the authetication iteration dialog is complete. + until the authentication iteration dialog is complete. Call this function iteratively after a successful initial step calling the Start function. The function returns SASL_CONTINUE if step was diff --git a/etc/inc/service-utils.inc b/etc/inc/service-utils.inc index a78446e219..8323924025 100644 --- a/etc/inc/service-utils.inc +++ b/etc/inc/service-utils.inc @@ -1,36 +1,35 @@ "") { eval("\$rc={$aservice['custom_php_service_status_command']};"); return $rc; } - if(empty($aservice['executable'])) + if (empty($aservice['executable'])) { return false; - if (is_process_running($aservice['executable'])) + } + if (is_process_running($aservice['executable'])) { return true; + } return false; } } } - if (is_process_running($service)) + if (is_process_running($service)) { return true; + } return false; } function get_services() { global $config; - if (is_array($config['installedpackages']['service'])) + if (is_array($config['installedpackages']['service'])) { $services = $config['installedpackages']['service']; - else + } else { $services = array(); + } - /* Add services that are in the base. - * + /* + * Add services that are in the base. */ if (is_radvd_enabled()) { $pconfig = array(); @@ -275,8 +289,9 @@ function get_services() { $ifdescrs = get_configured_interface_list(); foreach ($ifdescrs as $if) { $oc = $config['interfaces'][$if]; - if ($oc['if'] && (!link_interface_to_bridge($if))) + if ($oc['if'] && (!link_interface_to_bridge($if))) { $iflist[$if] = $if; + } } if (isset($config['dhcrelay']['enable'])) { @@ -377,40 +392,48 @@ function get_services() { function find_service_by_name($name) { $services = get_services(); - foreach ($services as $service) - if ($service["name"] == $name) + foreach ($services as $service) { + if ($service["name"] == $name) { return $service; + } + } return array(); } function find_service_by_openvpn_vpnid($vpnid) { $services = get_services(); - foreach ($services as $service) - if (($service["name"] == "openvpn") && isset($service["vpnid"]) && ($service["vpnid"] == $vpnid)) + foreach ($services as $service) { + if (($service["name"] == "openvpn") && isset($service["vpnid"]) && ($service["vpnid"] == $vpnid)) { return $service; + } + } return array(); } function find_service_by_cp_zone($zone) { $services = get_services(); - foreach ($services as $service) - if (($service["name"] == "captiveportal") && isset($service["zone"]) && ($service["zone"] == $zone)) + foreach ($services as $service) { + if (($service["name"] == "captiveportal") && isset($service["zone"]) && ($service["zone"] == $zone)) { return $service; + } + } return array(); } function service_name_compare($a, $b) { - if (strtolower($a['name']) == strtolower($b['name'])) + if (strtolower($a['name']) == strtolower($b['name'])) { return 0; + } return (strtolower($a['name']) < strtolower($b['name'])) ? -1 : 1; } function get_pkg_descr($package_name) { global $config; if (is_array($config['installedpackages']['package'])) { - foreach($config['installedpackages']['package'] as $pkg) { - if($pkg['name'] == $package_name) + foreach ($config['installedpackages']['package'] as $pkg) { + if ($pkg['name'] == $package_name) { return $pkg['descr']; + } } } return gettext("Not available."); @@ -424,8 +447,9 @@ function get_service_status($service) { break; case "captiveportal": $running = is_pid_running("{$g['varrun_path']}/lighty-{$service['zone']}-CaptivePortal.pid"); - if (isset($config['captiveportal'][$service['zone']]['httpslogin'])) + if (isset($config['captiveportal'][$service['zone']]['httpslogin'])) { $running = $running && is_pid_running("{$g['varrun_path']}/lighty-{$service['zone']}-CaptivePortal-SSL.pid"); + } break; case "vhosts-http": $running = is_pid_running("{$g['varrun_path']}/vhosts-http.pid"); @@ -445,21 +469,23 @@ function get_service_status($service) { function get_service_status_icon($service, $withtext = true, $smallicon = false) { global $g; $output = ""; - if(get_service_status($service)) { + if (get_service_status($service)) { $statustext = gettext("Running"); $output .= "\"status\" "; - if ($withtext) + if ($withtext) { $output .= " " . $statustext; + } } else { $service_enabled = is_service_enabled($service['name']); $statustext = ($service_enabled) ? gettext("Stopped") : gettext("Disabled"); $output .= "\"status\" "; - if ($withtext) + if ($withtext) { $output .= " {$statustext}"; + } } return $output; } @@ -468,7 +494,7 @@ function get_service_control_links($service, $addname = false) { global $g; $output = ""; $stitle = ($addname) ? $service['name'] . " " : ""; - if(get_service_status($service)) { + if (get_service_status($service)) { switch ($service['name']) { case "openvpn": $output .= ""; @@ -502,18 +528,20 @@ function get_service_control_links($service, $addname = false) { $output .= ""; break; default: - if ($service_enabled) + if ($service_enabled) { $output .= ""; + } } - if ($service_enabled) + if ($service_enabled) { $output .= "start\n"; + } } return $output; } function service_control_start($name, $extras) { global $g; - switch($name) { + switch ($name) { case 'radvd': services_radvd_configure(); break; @@ -563,8 +591,9 @@ function service_control_start($name, $extras) { if (($vpnmode == "server") || ($vpnmode == "client")) { $id = isset($extras['vpnid']) ? htmlspecialchars($extras['vpnid']) : htmlspecialchars($extras['id']); $configfile = "{$g['varetc_path']}/openvpn/{$vpnmode}{$id}.conf"; - if (file_exists($configfile)) + if (file_exists($configfile)) { openvpn_restart_by_vpnid($vpnmode, $id); + } } break; case 'relayd': @@ -578,7 +607,7 @@ function service_control_start($name, $extras) { } function service_control_stop($name, $extras) { global $g; - switch($name) { + switch ($name) { case 'radvd': killbypid("{$g['varrun_path']}/radvd.pid"); break; @@ -649,7 +678,7 @@ function service_control_stop($name, $extras) { function service_control_restart($name, $extras) { global $g; - switch($name) { + switch ($name) { case 'radvd': services_radvd_configure(); break; @@ -702,8 +731,9 @@ function service_control_restart($name, $extras) { if ($vpnmode == "server" || $vpnmode == "client") { $id = htmlspecialchars($extras['id']); $configfile = "{$g['varetc_path']}/openvpn/{$vpnmode}{$id}.conf"; - if (file_exists($configfile)) + if (file_exists($configfile)) { openvpn_restart_by_vpnid($vpnmode, $id); + } } break; case 'relayd': diff --git a/etc/inc/services.inc b/etc/inc/services.inc index 1f5283abae..7fee002f02 100644 --- a/etc/inc/services.inc +++ b/etc/inc/services.inc @@ -44,17 +44,19 @@ define('DYNDNS_PROVIDER_DESCRIPTIONS', 'City Network,CloudFlare,Custom,Custom (v /* implement ipv6 route advertising daemon */ function services_radvd_configure($blacklist = array()) { global $config, $g; - - if ($g['platform'] == 'jail') - return; - if(isset($config['system']['developerspew'])) { + if ($g['platform'] == 'jail') { + return; + } + + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "services_radvd_configure() being called $mt\n"; } - if (!is_array($config['dhcpdv6'])) + if (!is_array($config['dhcpdv6'])) { $config['dhcpdv6'] = array(); + } $Iflist = get_configured_interface_list(); $Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces()); @@ -67,23 +69,29 @@ function services_radvd_configure($blacklist = array()) { /* handle manually configured DHCP6 server settings first */ foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) { - if (!is_array($config['interfaces'][$dhcpv6if])) + if (!is_array($config['interfaces'][$dhcpv6if])) { continue; - if (!isset($config['interfaces'][$dhcpv6if]['enable'])) + } + if (!isset($config['interfaces'][$dhcpv6if]['enable'])) { continue; + } /* Do not put in the config an interface which is down */ - if (isset($blacklist[$dhcpv6if])) + if (isset($blacklist[$dhcpv6if])) { continue; - if (!isset($dhcpv6ifconf['ramode'])) + } + if (!isset($dhcpv6ifconf['ramode'])) { $dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode']; + } /* are router advertisements enabled? */ - if ($dhcpv6ifconf['ramode'] == "disabled") + if ($dhcpv6ifconf['ramode'] == "disabled") { continue; + } - if (!isset($dhcpv6ifconf['rapriority'])) + if (!isset($dhcpv6ifconf['rapriority'])) { $dhcpv6ifconf['rapriority'] = "medium"; + } /* always start with the real parent, we override with the carp if later */ $carpif = false; @@ -97,20 +105,23 @@ function services_radvd_configure($blacklist = array()) { if (strstr($dhcpv6if, "_vip")) { // CARP IP, check if it's enabled and find parent - if (!get_carp_status() || get_carp_interface_status($dhcpv6if) != "MASTER") + if (!get_carp_status() || get_carp_interface_status($dhcpv6if) != "MASTER") { continue; + } $ifparent = link_carp_interface_to_parent($dhcpv6if); $realif = convert_friendly_interface_to_real_interface_name($ifparent); } else { $realif = get_real_interface($dhcpv6if, "inet6"); } - - if (isset($radvdifs[$realif])) + + if (isset($radvdifs[$realif])) { continue; + } $ifcfgipv6 = get_interface_ipv6($dhcpv6if); - if (!is_ipaddrv6($ifcfgipv6)) + if (!is_ipaddrv6($ifcfgipv6)) { continue; + } $ifcfgsnv6 = get_interface_subnetv6($dhcpv6if); $subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6); @@ -122,12 +133,13 @@ function services_radvd_configure($blacklist = array()) { $radvdconf .= "\tMinRtrAdvInterval 5;\n"; $radvdconf .= "\tMaxRtrAdvInterval 20;\n"; $mtu = get_interface_mtu($realif); - if (is_numeric($mtu)) + if (is_numeric($mtu)) { $radvdconf .= "\tAdvLinkMTU {$mtu};\n"; - else + } else { $radvdconf .= "\tAdvLinkMTU 1280;\n"; + } // $radvdconf .= "\tDeprecatePrefix on;\n"; - switch($dhcpv6ifconf['rapriority']) { + switch ($dhcpv6ifconf['rapriority']) { case "low": $radvdconf .= "\tAdvDefaultPreference low;\n"; break; @@ -138,7 +150,7 @@ function services_radvd_configure($blacklist = array()) { $radvdconf .= "\tAdvDefaultPreference medium;\n"; break; } - switch($dhcpv6ifconf['ramode']) { + switch ($dhcpv6ifconf['ramode']) { case "managed": case "assist": $radvdconf .= "\tAdvManagedFlag on;\n"; @@ -146,12 +158,12 @@ function services_radvd_configure($blacklist = array()) { break; } $radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n"; - if($carpif == true) { + if ($carpif == true) { $radvdconf .= "\t\tDeprecatePrefix off;\n"; } else { $radvdconf .= "\t\tDeprecatePrefix on;\n"; } - switch($dhcpv6ifconf['ramode']) { + switch ($dhcpv6ifconf['ramode']) { case "managed": $radvdconf .= "\t\tAdvOnLink on;\n"; $radvdconf .= "\t\tAdvAutonomous off;\n"; @@ -171,11 +183,11 @@ function services_radvd_configure($blacklist = array()) { $radvdconf .= "\t\tAdvOnLink on;\n"; $radvdconf .= "\t\tAdvAutonomous on;\n"; $radvdconf .= "\t\tAdvRouterAddr on;\n"; - break; + break; } $radvdconf .= "\t};\n"; - if($carpif === true) { + if ($carpif === true) { $radvdconf .= "\troute ::/0 {\n"; $radvdconf .= "\t\tRemoveRoute off;\n"; $radvdconf .= "\t};\n"; @@ -188,25 +200,31 @@ function services_radvd_configure($blacklist = array()) { /* add DNS servers */ $dnslist = array(); if (isset($dhcpv6ifconf['rasamednsasdhcp6']) && is_array($dhcpv6ifconf['dnsserver']) && !empty($dhcpv6ifconf['dnsserver'])) { - foreach($dhcpv6ifconf['dnsserver'] as $server) - if (is_ipaddrv6($server)) + foreach ($dhcpv6ifconf['dnsserver'] as $server) { + if (is_ipaddrv6($server)) { $dnslist[] = $server; + } + } } elseif (!isset($dhcpv6ifconf['rasamednsasdhcp6']) && isset($dhcpv6ifconf['radnsserver']) && is_array($dhcpv6ifconf['radnsserver'])) { - foreach($dhcpv6ifconf['radnsserver'] as $server) - if (is_ipaddrv6($server)) + foreach ($dhcpv6ifconf['radnsserver'] as $server) { + if (is_ipaddrv6($server)) { $dnslist[] = $server; + } + } } elseif (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) { $dnslist[] = get_interface_ipv6($realif); } elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) { - foreach($config['system']['dnsserver'] as $server) { - if (is_ipaddrv6($server)) + foreach ($config['system']['dnsserver'] as $server) { + if (is_ipaddrv6($server)) { $dnslist[] = $server; + } } } if (count($dnslist) > 0) { $dnsstring = implode(" ", $dnslist); - if ($dnsstring <> "") + if ($dnsstring <> "") { $radvdconf .= "\tRDNSS {$dnsstring} { };\n"; + } } if (!empty($dhcpv6ifconf['domain'])) { $radvdconf .= "\tDNSSL {$dhcpv6ifconf['domain']} { };\n"; @@ -218,16 +236,20 @@ function services_radvd_configure($blacklist = array()) { /* handle DHCP-PD prefixes and 6RD dynamic interfaces */ foreach ($Iflist as $if => $ifdescr) { - if(!isset($config['interfaces'][$if]['track6-interface'])) + if (!isset($config['interfaces'][$if]['track6-interface'])) { continue; - if(!isset($config['interfaces'][$if]['enable'])) + } + if (!isset($config['interfaces'][$if]['enable'])) { continue; + } /* Do not put in the config an interface which is down */ - if (isset($blacklist[$if])) + if (isset($blacklist[$if])) { continue; + } $trackif = $config['interfaces'][$if]['track6-interface']; - if (empty($config['interfaces'][$trackif])) + if (empty($config['interfaces'][$trackif])) { continue; + } if (strstr($if, "_vip")) { // CARP IP, find parent @@ -236,13 +258,14 @@ function services_radvd_configure($blacklist = array()) { } else { $realif = get_real_interface($if, "inet6"); } - + /* prevent duplicate entries, manual overrides */ - if (isset($radvdifs[$realif])) + if (isset($radvdifs[$realif])) { continue; + } $ifcfgipv6 = get_interface_ipv6($if); - if(!is_ipaddrv6($ifcfgipv6)) { + if (!is_ipaddrv6($ifcfgipv6)) { $subnetv6 = "::"; $ifcfgsnv6 = "64"; } else { @@ -252,9 +275,10 @@ function services_radvd_configure($blacklist = array()) { $radvdifs[$realif] = $realif; $autotype = $config['interfaces'][$trackif]['ipaddrv6']; - - if ($g['debug']) + + if ($g['debug']) { log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}"); + } $radvdconf .= "# Generated config for {$autotype} delegation from {$trackif} on {$if}\n"; $radvdconf .= "interface {$realif} {\n"; @@ -262,10 +286,11 @@ function services_radvd_configure($blacklist = array()) { $radvdconf .= "\tMinRtrAdvInterval 3;\n"; $radvdconf .= "\tMaxRtrAdvInterval 10;\n"; $mtu = get_interface_mtu($realif); - if (is_numeric($mtu)) + if (is_numeric($mtu)) { $radvdconf .= "\tAdvLinkMTU {$mtu};\n"; - else + } else { $radvdconf .= "\tAdvLinkMTU 1280;\n"; + } $radvdconf .= "\tAdvOtherConfigFlag on;\n"; $radvdconf .= "\t\tprefix {$subnetv6}/{$ifcfgsnv6} {\n"; $radvdconf .= "\t\tAdvOnLink on;\n"; @@ -278,15 +303,17 @@ function services_radvd_configure($blacklist = array()) { if (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) { $dnslist[] = $ifcfgipv6; } elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) { - foreach($config['system']['dnsserver'] as $server) { - if(is_ipaddrv6($server)) + foreach ($config['system']['dnsserver'] as $server) { + if (is_ipaddrv6($server)) { $dnslist[] = $server; + } } } if (count($dnslist) > 0) { $dnsstring = implode(" ", $dnslist); - if (!empty($dnsstring)) + if (!empty($dnsstring)) { $radvdconf .= "\tRDNSS {$dnsstring} { };\n"; + } } if (!empty($config['system']['domain'])) { $radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n"; @@ -297,16 +324,18 @@ function services_radvd_configure($blacklist = array()) { /* write radvd.conf */ if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) { log_error("Error: cannot open radvd.conf in services_radvd_configure().\n"); - if (platform_booting()) + if (platform_booting()) { printf("Error: cannot open radvd.conf in services_radvd_configure().\n"); + } } unset($radvdconf); if (count($radvdifs) > 0) { - if (isvalidpid("{$g['varrun_path']}/radvd.pid")) + if (isvalidpid("{$g['varrun_path']}/radvd.pid")) { sigkillbypid("{$g['varrun_path']}/radvd.pid", "HUP"); - else + } else { mwexec("/usr/local/sbin/radvd -p {$g['varrun_path']}/radvd.pid -C {$g['varetc_path']}/radvd.conf -m syslog"); + } } else { /* we need to shut down the radvd cleanly, it will send out the prefix * information with a lifetime of 0 to notify clients of a (possible) new prefix */ @@ -339,13 +368,15 @@ function services_dhcpd_configure($family = "all", $blacklist = array()) { fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n"); $status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`; - if (!trim($status)) + if (!trim($status)) { fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n"); + } fclose($fd); mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh"); - if ($family == "all" || $family == "inet") + if ($family == "all" || $family == "inet") { services_dhcpdv4_configure(); + } if ($family == "all" || $family == "inet6") { services_dhcpdv6_configure($blacklist); services_radvd_configure($blacklist); @@ -357,31 +388,37 @@ function services_dhcpdv4_configure() { $need_ddns_updates = false; $ddns_zones = array(); - if($g['services_dhcp_server_enable'] == false) + if ($g['services_dhcp_server_enable'] == false) { return; + } - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "services_dhcpdv4_configure($if) being called $mt\n"; } /* kill any running dhcpd */ - if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) + if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) { killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid"); + } /* DHCP enabled on any interfaces? */ - if (!is_dhcp_server_enabled()) + if (!is_dhcp_server_enabled()) { return 0; + } /* if OLSRD is enabled, allow WAN to house DHCP. */ - if (!function_exists('is_package_installed')) + if (!function_exists('is_package_installed')) { require_once('pkg-utils.inc'); - if (is_package_installed('olsrd') && isset($config['installedpackages']['olsrd'])) - foreach($config['installedpackages']['olsrd']['config'] as $olsrd) + } + if (is_package_installed('olsrd') && isset($config['installedpackages']['olsrd'])) { + foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) { if (isset($olsrd['enable']) && $olsrd['enable'] == "on") { $is_olsr_enabled = true; break; } + } + } if (platform_booting()) { /* restore the leases, if we have them */ @@ -390,7 +427,7 @@ function services_dhcpdv4_configure() { $dhcpreturn = ""; exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/dhcpleases.tgz 2>&1", $dhcprestore, $dhcpreturn); $dhcprestore = implode(" ", $dhcprestore); - if($dhcpreturn <> 0) { + if ($dhcpreturn <> 0) { log_error(sprintf(gettext('DHCP leases restore failed exited with %1$s, the error is: %2$s%3$s'), $dhcpreturn, $dhcprestore, "\n")); } } @@ -401,34 +438,37 @@ function services_dhcpdv4_configure() { } $syscfg = $config['system']; - if (!is_array($config['dhcpd'])) + if (!is_array($config['dhcpd'])) { $config['dhcpd'] = array(); + } $dhcpdcfg = $config['dhcpd']; $Iflist = get_configured_interface_list(); /* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */ $dns_arrv4 = array(); if (is_array($syscfg['dnsserver'])) { - foreach($syscfg['dnsserver'] as $dnsserver) { + foreach ($syscfg['dnsserver'] as $dnsserver) { if (is_ipaddrv4($dnsserver)) { $dns_arrv4[] = $dnsserver; } } } - if (platform_booting()) + if (platform_booting()) { echo gettext("Starting DHCP service..."); - else + } else { sleep(1); + } $custoptions = ""; foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) { - if(is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) { - foreach($dhcpifconf['numberoptions']['item'] as $itemidx => $item) { - if(!empty($item['type'])) + if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) { + foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) { + if (!empty($item['type'])) { $itemtype = $item['type']; - else + } else { $itemtype = "text"; + } $custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n"; } } @@ -451,19 +491,21 @@ update-conflict-detection false; EOD; - if(!isset($dhcpifconf['disableauthoritative'])) + if (!isset($dhcpifconf['disableauthoritative'])) { $dhcpdconf .= "authoritative;\n"; + } - if(isset($dhcpifconf['alwaysbroadcast'])) + if (isset($dhcpifconf['alwaysbroadcast'])) { $dhcpdconf .= "always-broadcast on\n"; + } $dhcpdifs = array(); $enable_add_routers = false; $gateways_arr = return_gateways_array(); /* only add a routers line if the system has any IPv4 gateway at all */ /* a static route has a gateway, manually overriding this field always works */ - foreach($gateways_arr as $gwitem) { - if($gwitem['ipprotocol'] == "inet") { + foreach ($gateways_arr as $gwitem) { + if ($gwitem['ipprotocol'] == "inet") { $enable_add_routers = true; break; } @@ -474,28 +516,30 @@ EOD; */ foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) { - if (!isset($config['interfaces'][$dhcpif]['enable'])) + if (!isset($config['interfaces'][$dhcpif]['enable'])) { continue; + } interfaces_staticarp_configure($dhcpif); - if (!isset($dhcpifconf['enable'])) + if (!isset($dhcpifconf['enable'])) { continue; + } - if($dhcpifconf['failover_peerip'] <> "") { + if ($dhcpifconf['failover_peerip'] <> "") { $intip = get_interface_ip($dhcpif); /* * yep, failover peer is defined. * does it match up to a defined vip? */ $skew = 110; - if(is_array($config['virtualip']['vip'])) { + if (is_array($config['virtualip']['vip'])) { foreach ($config['virtualip']['vip'] as $vipent) { - if($vipent['interface'] == $dhcpif) { + if ($vipent['interface'] == $dhcpif) { $carp_nw = gen_subnet($vipent['subnet'], $vipent['subnet_bits']); if (ip_in_subnet($dhcpifconf['failover_peerip'], "{$carp_nw}/{$vipent['subnet_bits']}")) { /* this is the interface! */ - if(is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) { + if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) { $skew = 0; break; } @@ -505,7 +549,7 @@ EOD; } else { log_error(gettext("Warning! DHCP Failover setup and no CARP virtual IPs defined!")); } - if($skew > 10) { + if ($skew > 10) { $type = "secondary"; $my_port = "520"; $peer_port = "519"; @@ -518,7 +562,7 @@ EOD; } if (is_ipaddrv4($intip)) { - $dhcpdconf .= << "") { + if ($dhcpifconf['domainsearchlist'] <> "") { $dnscfg .= " option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n"; } if (isset($dhcpifconf['ddnsupdate'])) { $need_ddns_updates = true; $newzone = array(); - if($dhcpifconf['ddnsdomain'] <> "") { + if ($dhcpifconf['ddnsdomain'] <> "") { $newzone['domain-name'] = $dhcpifconf['ddnsdomain']; $dnscfg .= " ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n"; } else { @@ -583,8 +631,9 @@ EOPP; $revsubnet = explode(".", $subnet); $revsubnet = array_reverse($revsubnet); foreach ($revsubnet as $octet) { - if ($octet != "0") + if ($octet != "0") { break; + } array_shift($revsubnet); } $newzone['ptr-domain'] = implode(".", $revsubnet) . ".in-addr.arpa"; @@ -592,25 +641,28 @@ EOPP; if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) { $dnscfg .= " option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";"; - if ($newzone['domain-name']) + if ($newzone['domain-name']) { $newzone['dns-servers'] = $dhcpifconf['dnsserver']; + } } else if (isset($config['dnsmasq']['enable'])) { $dnscfg .= " option domain-name-servers {$ifcfgip};"; - if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) + if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) { $newzone['dns-servers'] = $syscfg['dnsserver']; + } } else if (isset($config['unbound']['enable'])) { $dnscfg .= " option domain-name-servers {$ifcfgip};"; } else if (!empty($dns_arrv4)) { $dnscfg .= " option domain-name-servers " . join(",", $dns_arrv4) . ";"; - if ($newzone['domain-name']) + if ($newzone['domain-name']) { $newzone['dns-servers'] = $dns_arrv4; + } } - /* Create classes - These all contain comma separated lists. Join them into one + /* Create classes - These all contain comma separated lists. Join them into one big comma separated string then split them all up. */ $all_mac_strings = array(); if (is_array($dhcpifconf['pool'])) { - foreach($all_pools as $poolconf) { + foreach ($all_pools as $poolconf) { $all_mac_strings[] = $poolconf['mac_allow']; $all_mac_strings[] = $poolconf['mac_deny']; } @@ -619,8 +671,9 @@ EOPP; $all_mac_strings[] = $dhcpifconf['mac_deny']; $all_mac_list = array_unique(explode(',', implode(',', $all_mac_strings))); foreach ($all_mac_list as $mac) { - if (empty($mac)) + if (empty($mac)) { continue; + } $dhcpdconf .= 'class "' . str_replace(':', '', $mac) . '" {' . "\n"; // Skip the first octet of the MAC address - for media type, typically Ethernet ("01") and match the rest. $dhcpdconf .= ' match if substring (hardware, 1, ' . (substr_count($mac, ':') + 1) . ') = ' . $mac . ';' . "\n"; @@ -629,45 +682,53 @@ EOPP; $dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n"; -// Setup pool options - foreach($all_pools as $poolconf) { + // Setup pool options + foreach ($all_pools as $poolconf) { $dhcpdconf .= " pool {\n"; /* is failover dns setup? */ if (is_array($poolconf['dnsserver']) && $poolconf['dnsserver'][0] <> "") { $dhcpdconf .= " option domain-name-servers {$poolconf['dnsserver'][0]}"; - if($poolconf['dnsserver'][1] <> "") + if ($poolconf['dnsserver'][1] <> "") { $dhcpdconf .= ",{$poolconf['dnsserver'][1]}"; - if($poolconf['dnsserver'][2] <> "") + } + if ($poolconf['dnsserver'][2] <> "") { $dhcpdconf .= ",{$poolconf['dnsserver'][2]}"; - if($poolconf['dnsserver'][3] <> "") + } + if ($poolconf['dnsserver'][3] <> "") { $dhcpdconf .= ",{$poolconf['dnsserver'][3]}"; + } $dhcpdconf .= ";\n"; } /* allow/deny MACs */ $mac_allow_list = array_unique(explode(',', $poolconf['mac_allow'])); foreach ($mac_allow_list as $mac) { - if (empty($mac)) + if (empty($mac)) { continue; + } $dhcpdconf .= " allow members of \"" . str_replace(':', '', $mac) . "\";\n"; } $mac_deny_list = array_unique(explode(',', $poolconf['mac_deny'])); foreach ($mac_deny_list as $mac) { - if (empty($mac)) + if (empty($mac)) { continue; + } $dhcpdconf .= " deny members of \"" . str_replace(':', '', $mac) . "\";\n"; } - if($poolconf['failover_peerip'] <> "") + if ($poolconf['failover_peerip'] <> "") { $dhcpdconf .= " deny dynamic bootp clients;\n"; + } - if (isset($poolconf['denyunknown'])) + if (isset($poolconf['denyunknown'])) { $dhcpdconf .= " deny unknown-clients;\n"; + } - if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) + if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) { $dhcpdconf .= " option routers {$poolconf['gateway']};\n"; + } - if($dhcpifconf['failover_peerip'] <> "") { + if ($dhcpifconf['failover_peerip'] <> "") { $dhcpdconf .= " failover peer \"dhcp_{$dhcpif}\";\n"; } @@ -677,13 +738,14 @@ EOPP; $pdnscfg .= " option domain-name \"{$poolconf['domain']}\";\n"; } - if(!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) { + if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) { $pdnscfg .= " option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n"; } if (isset($poolconf['ddnsupdate'])) { - if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) + if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) { $pdnscfg .= " ddns-domainname \"{$poolconf['ddnsdomain']}\";\n"; + } $pdnscfg .= " ddns-update-style interim;\n"; } @@ -693,12 +755,14 @@ EOPP; $dhcpdconf .= "{$pdnscfg}"; // default-lease-time - if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) + if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) { $dhcpdconf .= " default-lease-time {$poolconf['defaultleasetime']};\n"; + } // max-lease-time - if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) + if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) { $dhcpdconf .= " max-lease-time {$poolconf['maxleasetime']};\n"; + } // netbios-name* if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) { @@ -707,19 +771,22 @@ EOPP; } // ntp-servers - if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) + if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) { $dhcpdconf .= " option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n"; + } // tftp-server-name - if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) + if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) { $dhcpdconf .= " option tftp-server-name \"{$poolconf['tftp']}\";\n"; + } // ldap-server - if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) + if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) { $dhcpdconf .= " option ldap-server \"{$poolconf['ldap']}\";\n"; + } // net boot information - if(isset($poolconf['netboot'])) { + if (isset($poolconf['netboot'])) { if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) { $dhcpdconf .= " next-server {$poolconf['nextserver']};\n"; } @@ -744,20 +811,23 @@ EOPP; $add_routers = $enable_add_routers; $routers = $ifcfgip; } - if($add_routers) + if ($add_routers) { $dhcpdconf .= " option routers {$routers};\n"; + } $dhcpdconf .= << "") + if ($dhcpifconf['tftp'] <> "") { $dhcpdconf .= " option tftp-server-name \"{$dhcpifconf['tftp']}\";\n"; + } // Handle option, number rowhelper values $dhcpdconf .= "\n"; - if($dhcpifconf['numberoptions']['item']) { - foreach($dhcpifconf['numberoptions']['item'] as $itemidx => $item) { - if(empty($item['type']) || $item['type'] == "text") + if ($dhcpifconf['numberoptions']['item']) { + foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) { + if (empty($item['type']) || $item['type'] == "text") { $dhcpdconf .= " option custom-{$dhcpif}-{$itemidx} \"{$item['value']}\";\n"; - else + } else { $dhcpdconf .= " option custom-{$dhcpif}-{$itemidx} {$item['value']};\n"; + } } } // ldap-server - if ($dhcpifconf['ldap'] <> "") + if ($dhcpifconf['ldap'] <> "") { $dhcpdconf .= " option ldap-server \"{$dhcpifconf['ldap']}\";\n"; + } // net boot information - if(isset($dhcpifconf['netboot'])) { + if (isset($dhcpifconf['netboot'])) { if ($dhcpifconf['nextserver'] <> "") { $dhcpdconf .= " next-server {$dhcpifconf['nextserver']};\n"; } @@ -821,28 +895,34 @@ EOD; foreach ($dhcpifconf['staticmap'] as $sm) { $dhcpdconf .= "host s_{$dhcpif}_{$i} {\n"; - if ($sm['mac']) - $dhcpdconf .= " hardware ethernet {$sm['mac']};\n"; + if ($sm['mac']) { + $dhcpdconf .= " hardware ethernet {$sm['mac']};\n"; + } - if ($sm['cid']) - $dhcpdconf .= " option dhcp-client-identifier \"{$sm['cid']}\";\n"; + if ($sm['cid']) { + $dhcpdconf .= " option dhcp-client-identifier \"{$sm['cid']}\";\n"; + } - if ($sm['ipaddr']) + if ($sm['ipaddr']) { $dhcpdconf .= " fixed-address {$sm['ipaddr']};\n"; + } if ($sm['hostname']) { $dhhostname = str_replace(" ", "_", $sm['hostname']); $dhhostname = str_replace(".", "_", $dhhostname); $dhcpdconf .= " option host-name \"{$dhhostname}\";\n"; } - if ($sm['filename']) + if ($sm['filename']) { $dhcpdconf .= " filename \"{$sm['filename']}\";\n"; + } - if ($sm['rootpath']) + if ($sm['rootpath']) { $dhcpdconf .= " option root-path \"{$sm['rootpath']}\";\n"; + } - if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) + if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) { $dhcpdconf .= " option routers {$sm['gateway']};\n"; + } $smdnscfg = ""; @@ -850,13 +930,14 @@ EOD; $smdnscfg .= " option domain-name \"{$sm['domain']}\";\n"; } - if(!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) { + if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) { $smdnscfg .= " option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n"; } if (isset($sm['ddnsupdate'])) { - if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) + if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) { $pdnscfg .= " ddns-domainname \"{$sm['ddnsdomain']}\";\n"; + } $pdnscfg .= " ddns-update-style interim;\n"; } @@ -866,12 +947,14 @@ EOD; $dhcpdconf .= "{$smdnscfg}"; // default-lease-time - if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) + if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) { $dhcpdconf .= " default-lease-time {$sm['defaultleasetime']};\n"; + } // max-lease-time - if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) + if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) { $dhcpdconf .= " max-lease-time {$sm['maxleasetime']};\n"; + } // netbios-name* if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) { @@ -880,12 +963,14 @@ EOD; } // ntp-servers - if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) + if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) { $dhcpdconf .= " option ntp-servers " . join(",", $sm['ntpserver']) . ";\n"; + } // tftp-server-name - if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) + if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) { $dhcpdconf .= " option tftp-server-name \"{$sm['tftp']}\";\n"; + } $dhcpdconf .= "}\n"; $i++; @@ -893,10 +978,8 @@ EOD; } $dhcpdifs[] = get_real_interface($dhcpif); - if ($newzone['domain-name']) - { - if ($need_ddns_updates) - { + if ($newzone['domain-name']) { + if ($need_ddns_updates) { $newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']); } $ddns_zones[] = $newzone; @@ -920,11 +1003,12 @@ EOD; unset($dhcpdconf); /* create an empty leases database */ - if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) + if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) { @touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"); + } /* make sure there isn't a stale dhcpd.pid file, which can make dhcpd fail to start. */ - /* if we get here, dhcpd has been killed and is not started yet */ + /* if we get here, dhcpd has been killed and is not started yet */ unlink_if_exists("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid"); /* fire up dhcpd in a chroot */ @@ -933,8 +1017,9 @@ EOD; join(" ", $dhcpdifs)); } - if (platform_booting()) + if (platform_booting()) { print "done.\n"; + } return 0; } @@ -942,8 +1027,7 @@ EOD; function dhcpdkey($dhcpifconf) { $dhcpdconf = ""; - if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") - { + if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") { $dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n"; $dhcpdconf .= " algorithm hmac-md5;\n"; $dhcpdconf .= " secret {$dhcpifconf['ddnsdomainkey']};\n"; @@ -960,8 +1044,9 @@ function dhcpdzones($ddns_zones, $dhcpifconf) if (is_array($ddns_zones)) { $added_zones = array(); foreach ($ddns_zones as $zone) { - if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) + if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) { continue; + } $primary = $zone['dns-servers'][0]; $secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1]; @@ -979,20 +1064,24 @@ function dhcpdzones($ddns_zones, $dhcpifconf) if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) { $dhcpdconf .= "zone {$zone['domain-name']}. {\n"; $dhcpdconf .= " primary {$primary};\n"; - if (is_ipaddrv4($secondary)) + if (is_ipaddrv4($secondary)) { $dhcpdconf .= " secondary {$secondary};\n"; - if($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") - $dhcpdconf .= " key {$dhcpifconf['ddnsdomainkeyname']};\n"; + } + if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") { + $dhcpdconf .= " key {$dhcpifconf['ddnsdomainkeyname']};\n"; + } $dhcpdconf .= "}\n"; $added_zones[] = $zone['domain-name']; } if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) { $dhcpdconf .= "zone {$zone['ptr-domain']} {\n"; $dhcpdconf .= " primary {$primary};\n"; - if (is_ipaddrv4($secondary)) + if (is_ipaddrv4($secondary)) { $dhcpdconf .= " secondary {$secondary};\n"; - if($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") - $dhcpdconf .= " key {$dhcpifconf['ddnsdomainkeyname']};\n"; + } + if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") { + $dhcpdconf .= " key {$dhcpifconf['ddnsdomainkeyname']};\n"; + } $dhcpdconf .= "}\n"; $added_zones[] = $zone['ptr-domain']; } @@ -1005,23 +1094,27 @@ function dhcpdzones($ddns_zones, $dhcpifconf) function services_dhcpdv6_configure($blacklist = array()) { global $config, $g; - if($g['services_dhcp_server_enable'] == false) + if ($g['services_dhcp_server_enable'] == false) { return; + } - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "services_dhcpd_configure($if) being called $mt\n"; } /* kill any running dhcpd */ - if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) + if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) { killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid"); - if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) + } + if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) { killbypid("{$g['varrun_path']}/dhcpleases6.pid"); + } /* DHCP enabled on any interfaces? */ - if (!is_dhcpv6_server_enabled()) + if (!is_dhcpv6_server_enabled()) { return 0; + } if (platform_booting()) { if ($g['platform'] != "pfSense") { @@ -1031,7 +1124,7 @@ function services_dhcpdv6_configure($blacklist = array()) { $dhcpreturn = ""; exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/dhcp6leases.tgz 2>&1", $dhcprestore, $dhcpreturn); $dhcprestore = implode(" ", $dhcprestore); - if($dhcpreturn <> 0) { + if ($dhcpreturn <> 0) { log_error("DHCP leases v6 restore failed exited with $dhcpreturn, the error is: $dhcprestore\n"); } } @@ -1039,28 +1132,32 @@ function services_dhcpdv6_configure($blacklist = array()) { } $syscfg = $config['system']; - if (!is_array($config['dhcpdv6'])) + if (!is_array($config['dhcpdv6'])) { $config['dhcpdv6'] = array(); + } $dhcpdv6cfg = $config['dhcpdv6']; $Iflist = get_configured_interface_list(); $Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces()); - if (platform_booting()) + if (platform_booting()) { echo "Starting DHCPv6 service..."; - else + } else { sleep(1); + } /* we add a fake entry for interfaces that are set to track6 another WAN */ foreach ($Iflist as $ifname) { /* Do not put in the config an interface which is down */ - if (isset($blacklist[$ifname])) + if (isset($blacklist[$ifname])) { continue; + } if (!empty($config['interfaces'][$ifname]['track6-interface'])) { $realif = get_real_interface($ifname, "inet6"); $ifcfgipv6 = get_interface_ipv6($ifname); - if(!is_ipaddrv6($ifcfgipv6)) + if (!is_ipaddrv6($ifcfgipv6)) { continue; + } $ifcfgipv6 = Net_IPv6::getNetmask($ifcfgipv6, 64); $trackifname = $config['interfaces'][$ifname]['track6-interface']; $trackcfg = $config['interfaces'][$trackifname]; @@ -1075,7 +1172,7 @@ function services_dhcpdv6_configure($blacklist = array()) { $ifcfgipv6arr[7] = "2000"; $dhcpdv6cfg[$ifname]['range']['to'] = Net_IPv6::compress(implode(":", $ifcfgipv6arr)); /* prefix length > 0? We can add dhcp6 prefix delegation server */ - if($pdlen > 2) { + if ($pdlen > 2) { $pdlenmax = $pdlen; $pdlenhalf = $pdlenmax -1; $pdlenmin = (64 - ceil($pdlenhalf / 4)); @@ -1099,15 +1196,16 @@ function services_dhcpdv6_configure($blacklist = array()) { $custoptionsv6 = ""; foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) { - if(is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) { - foreach($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) { + if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) { + foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) { $custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n"; } } } - if(isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) + if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) { $custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n"; + } $dhcpdv6conf = << "") { + if ($dhcpv6ifconf['domainsearchlist'] <> "") { $dnscfgv6 .= " option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n"; - } + } if (isset($dhcpv6ifconf['ddnsupdate'])) { - if($dhcpv6ifconf['ddnsdomain'] <> "") { + if ($dhcpv6ifconf['ddnsdomain'] <> "") { $dnscfgv6 .= " ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n"; } $dnscfgv6 .= " ddns-update-style interim;\n"; @@ -1177,18 +1279,19 @@ EOD; $dnscfgv6 .= " option dhcp6.name-servers {$ifcfgipv6};"; } else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) { $dns_arrv6 = array(); - foreach($syscfg['dnsserver'] as $dnsserver) { + foreach ($syscfg['dnsserver'] as $dnsserver) { if (is_ipaddrv6($dnsserver)) { $dns_arrv6[] = $dnsserver; } } - if(!empty($dns_arrv6)) + if (!empty($dns_arrv6)) { $dnscfgv6 .= " option dhcp6.name-servers " . join(",", $dns_arrv6) . ";"; + } } if ($dhcpv6ifconf['domain']) { $newzone = array(); - $newzone['domain-name'] = $dhcpv6ifconf['domain']; + $newzone['domain-name'] = $dhcpv6ifconf['domain']; $newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary']; $ddns_zones[] = $newzone; } @@ -1213,44 +1316,50 @@ EOD; if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) { $dhcpdv6conf .= " option dhcp6.name-servers {$dhcpv6ifconf['dns6ip']};\n"; } - // default-lease-time - if ($dhcpv6ifconf['defaultleasetime']) + // default-lease-time + if ($dhcpv6ifconf['defaultleasetime']) { $dhcpdv6conf .= " default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n"; + } // max-lease-time - if ($dhcpv6ifconf['maxleasetime']) + if ($dhcpv6ifconf['maxleasetime']) { $dhcpdv6conf .= " max-lease-time {$dhcpv6ifconf['maxleasetime']};\n"; + } // ntp-servers if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) { $ntpservers = array(); - foreach($dhcpv6ifconf['ntpserver'] as $ntpserver) { - if(is_ipaddrv6($ntpserver)) + foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) { + if (is_ipaddrv6($ntpserver)) { $ntpservers[] = $ntpserver; + } } - if(count($ntpservers) > 0 ) + if (count($ntpservers) > 0) { $dhcpdv6conf .= " option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n"; + } } // tftp-server-name /* Needs ISC DHCPD support - if ($dhcpv6ifconf['tftp'] <> "") + if ($dhcpv6ifconf['tftp'] <> "") { $dhcpdv6conf .= " option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n"; + } */ // Handle option, number rowhelper values $dhcpdv6conf .= "\n"; if ($dhcpv6ifconf['numberoptions']['item']) { - foreach($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) { + foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) { $dhcpdv6conf .= " option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6['value']}\";\n"; } } // ldap-server - if ($dhcpv6ifconf['ldap'] <> "") + if ($dhcpv6ifconf['ldap'] <> "") { $dhcpdv6conf .= " option ldap-server \"{$dhcpv6ifconf['ldap']}\";\n"; + } // net boot information - if(isset($dhcpv6ifconf['netboot'])) { + if (isset($dhcpv6ifconf['netboot'])) { if (!empty($dhcpv6ifconf['bootfile_url'])) { $dhcpdv6conf .= " option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n"; } @@ -1268,33 +1377,35 @@ host s_{$dhcpv6if}_{$i} { host-identifier option dhcp6.client-id {$sm['duid']}; EOD; - if ($sm['ipaddrv6']) + if ($sm['ipaddrv6']) { $dhcpdv6conf .= " fixed-address6 {$sm['ipaddrv6']};\n"; + } if ($sm['hostname']) { $dhhostname = str_replace(" ", "_", $sm['hostname']); $dhhostname = str_replace(".", "_", $dhhostname); $dhcpdv6conf .= " option host-name {$dhhostname};\n"; } - if ($sm['filename']) + if ($sm['filename']) { $dhcpdv6conf .= " filename \"{$sm['filename']}\";\n"; + } - if ($sm['rootpath']) + if ($sm['rootpath']) { $dhcpdv6conf .= " option root-path \"{$sm['rootpath']}\";\n"; + } $dhcpdv6conf .= "}\n"; $i++; } } - if ($dhcpv6ifconf['domain']) - { + if ($dhcpv6ifconf['domain']) { $dhcpdv6conf .= dhcpdkey($dhcpv6ifconf); $dhcpdv6conf .= dhcpdzones($ddns_zones, $dhcpv6ifconf); } if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) { - if(preg_match("/poes/si", $dhcpv6if)) { + if (preg_match("/poes/si", $dhcpv6if)) { /* magic here */ $dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if)); } else { @@ -1311,32 +1422,31 @@ EOD; } } - if ($nsupdate) - { + if ($nsupdate) { $dhcpdv6conf .= "ddns-update-style interim;\n"; - } - else - { + } else { $dhcpdv6conf .= "ddns-update-style none;\n"; } /* write dhcpdv6.conf */ if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) { log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n"); - if (platform_booting()) + if (platform_booting()) { printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n"); + } unset($dhcpdv6conf); return 1; } unset($dhcpdv6conf); /* create an empty leases v6 database */ - if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) + if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) { @touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases"); + } - /* make sure there isn't a stale dhcpdv6.pid file, which may make dhcpdv6 fail to start. */ - /* if we get here, dhcpdv6 has been killed and is not started yet */ - unlink_if_exists("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid"); + /* make sure there isn't a stale dhcpdv6.pid file, which may make dhcpdv6 fail to start. */ + /* if we get here, dhcpdv6 has been killed and is not started yet */ + unlink_if_exists("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid"); /* fire up dhcpd in a chroot */ if (count($dhcpdv6ifs) > 0) { @@ -1344,24 +1454,26 @@ EOD; join(" ", $dhcpdv6ifs)); mwexec("/usr/local/sbin/dhcpleases6 -c \"/usr/local/bin/php -f /usr/local/sbin/prefixes.php|/bin/sh\" -l {$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases"); } - if (platform_booting()) + if (platform_booting()) { print gettext("done.") . "\n"; + } return 0; } function services_igmpproxy_configure() { - global $config, $g; + global $config, $g; - /* kill any running igmpproxy */ - killbyname("igmpproxy"); + /* kill any running igmpproxy */ + killbyname("igmpproxy"); - if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) + if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) { return 1; + } - $iflist = get_configured_interface_list(); + $iflist = get_configured_interface_list(); - $igmpconf = << "") { - $item = explode(" ", $igmpcf['address']); - foreach($item as $iww) - $igmpconf .= "altnet {$iww}\n"; - } - $igmpconf .= "\n"; - } - foreach ($iflist as $ifn) { - $realif = get_real_interface($ifn); - $igmpconf .= "phyint {$realif} disabled\n"; - } + if ($igmpcf['address'] <> "") { + $item = explode(" ", $igmpcf['address']); + foreach ($item as $iww) { + $igmpconf .= "altnet {$iww}\n"; + } + } + $igmpconf .= "\n"; + } + foreach ($iflist as $ifn) { + $realif = get_real_interface($ifn); + $igmpconf .= "phyint {$realif} disabled\n"; + } $igmpconf .= "\n"; - $igmpfl = fopen($g['tmp_path'] . "/igmpproxy.conf", "w"); - if (!$igmpfl) { - log_error(gettext("Could not write Igmpproxy configuration file!")); - return; - } - fwrite($igmpfl, $igmpconf); - fclose($igmpfl); + $igmpfl = fopen($g['tmp_path'] . "/igmpproxy.conf", "w"); + if (!$igmpfl) { + log_error(gettext("Could not write Igmpproxy configuration file!")); + return; + } + fwrite($igmpfl, $igmpconf); + fclose($igmpfl); unset($igmpconf); /* NOTE: -d4 means everything LOG_WARNING and smaller */ - mwexec("/usr/local/sbin/igmpproxy -d4 -c {$g['tmp_path']}/igmpproxy.conf"); - log_error(gettext("Started IGMP proxy service.")); + mwexec("/usr/local/sbin/igmpproxy -d4 -c {$g['tmp_path']}/igmpproxy.conf"); + log_error(gettext("Started IGMP proxy service.")); - return 0; + return 0; } function services_dhcrelay_configure() { global $config, $g; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; - if(isset($config['system']['developerspew'])) { + } + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "services_dhcrelay_configure() being called $mt\n"; } @@ -1423,24 +1538,28 @@ function services_dhcrelay_configure() { $dhcrelaycfg =& $config['dhcrelay']; /* DHCPRelay enabled on any interfaces? */ - if (!isset($dhcrelaycfg['enable'])) + if (!isset($dhcrelaycfg['enable'])) { return 0; + } - if (platform_booting()) + if (platform_booting()) { echo gettext("Starting DHCP relay service..."); - else + } else { sleep(1); + } $iflist = get_configured_interface_list(); $dhcifaces = explode(",", $dhcrelaycfg['interface']); foreach ($dhcifaces as $dhcrelayif) { if (!isset($iflist[$dhcrelayif]) || - link_interface_to_bridge($dhcrelayif)) + link_interface_to_bridge($dhcrelayif)) { continue; + } - if (is_ipaddr(get_interface_ip($dhcrelayif))) + if (is_ipaddr(get_interface_ip($dhcrelayif))) { $dhcrelayifs[] = get_real_interface($dhcrelayif); + } } /* @@ -1452,8 +1571,9 @@ function services_dhcrelay_configure() { unset($destif); foreach ($iflist as $ifname) { $subnet = get_interface_ip($ifname); - if (!is_ipaddr($subnet)) + if (!is_ipaddr($subnet)) { continue; + } $subnet .= "/" . get_interface_subnet($ifname); if (ip_in_subnet($srvip, $subnet)) { $destif = get_real_interface($ifname); @@ -1472,13 +1592,13 @@ function services_dhcrelay_configure() { if (!isset($destif)) { /* Create a array from the existing route table */ - exec("/usr/bin/netstat -rnWf inet", $route_str); - array_shift($route_str); - array_shift($route_str); - array_shift($route_str); - array_shift($route_str); - $route_arr = array(); - foreach($route_str as $routeline) { + exec("/usr/bin/netstat -rnWf inet", $route_str); + array_shift($route_str); + array_shift($route_str); + array_shift($route_str); + array_shift($route_str); + $route_arr = array(); + foreach ($route_str as $routeline) { $items = preg_split("/[ ]+/i", $routeline); if (is_subnetv4($items[0])) { $subnet = $items[0]; @@ -1503,12 +1623,14 @@ function services_dhcrelay_configure() { break; } } - } else + } else { $destif = get_real_interface("wan"); + } } - if (!empty($destif)) + if (!empty($destif)) { $dhcrelayifs[] = $destif; + } } $dhcrelayifs = array_unique($dhcrelayifs); @@ -1520,8 +1642,9 @@ function services_dhcrelay_configure() { $cmd = "/usr/local/sbin/dhcrelay -i " . implode(" -i ", $dhcrelayifs); - if (isset($dhcrelaycfg['agentoption'])) + if (isset($dhcrelaycfg['agentoption'])) { $cmd .= " -a -m replace"; + } $cmd .= " " . implode(" ", $srvips); mwexec($cmd); @@ -1532,9 +1655,10 @@ function services_dhcrelay_configure() { function services_dhcrelay6_configure() { global $config, $g; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; - if(isset($config['system']['developerspew'])) { + } + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "services_dhcrelay6_configure() being called $mt\n"; } @@ -1545,24 +1669,27 @@ function services_dhcrelay6_configure() { $dhcrelaycfg =& $config['dhcrelay6']; /* DHCPv6 Relay enabled on any interfaces? */ - if (!isset($dhcrelaycfg['enable'])) + if (!isset($dhcrelaycfg['enable'])) { return 0; + } - if (platform_booting()) + if (platform_booting()) { echo gettext("Starting DHCPv6 relay service..."); - else + } else { sleep(1); + } $iflist = get_configured_interface_list(); $dhcifaces = explode(",", $dhcrelaycfg['interface']); foreach ($dhcifaces as $dhcrelayif) { if (!isset($iflist[$dhcrelayif]) || - link_interface_to_bridge($dhcrelayif)) + link_interface_to_bridge($dhcrelayif)) continue; - if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) + if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) { $dhcrelayifs[] = get_real_interface($dhcrelayif); + } } $dhcrelayifs = array_unique($dhcrelayifs); @@ -1571,13 +1698,14 @@ function services_dhcrelay6_configure() { * on the interface in which the destination server sits. */ $srvips = explode(",", $dhcrelaycfg['server']); - $srvifaces = array(); + $srvifaces = array(); foreach ($srvips as $srcidx => $srvip) { unset($destif); foreach ($iflist as $ifname) { $subnet = get_interface_ipv6($ifname); - if (!is_ipaddrv6($subnet)) + if (!is_ipaddrv6($subnet)) { continue; + } $subnet .= "/" . get_interface_subnetv6($ifname); if (ip_in_subnet($srvip, $subnet)) { $destif = get_real_interface($ifname); @@ -1598,19 +1726,19 @@ function services_dhcrelay6_configure() { if (!isset($destif)) { /* Create a array from the existing route table */ - exec("/usr/bin/netstat -rnWf inet6", $route_str); - array_shift($route_str); - array_shift($route_str); - array_shift($route_str); - array_shift($route_str); - $route_arr = array(); - foreach($route_str as $routeline) { - $items = preg_split("/[ ]+/i", $routeline); + exec("/usr/bin/netstat -rnWf inet6", $route_str); + array_shift($route_str); + array_shift($route_str); + array_shift($route_str); + array_shift($route_str); + $route_arr = array(); + foreach ($route_str as $routeline) { + $items = preg_split("/[ ]+/i", $routeline); if (ip_in_subnet($srvip, $items[0])) { $destif = trim($items[6]); break; } - } + } } if (!isset($destif)) { @@ -1621,8 +1749,9 @@ function services_dhcrelay6_configure() { break; } } - } else + } else { $destif = get_real_interface("wan"); + } } if (!empty($destif)) { @@ -1631,7 +1760,7 @@ function services_dhcrelay6_configure() { } /* fire up dhcrelay */ - if (empty($dhcrelayifs) || empty($srvifaces) ) { + if (empty($dhcrelayifs) || empty($srvifaces)) { log_error("No suitable interface found for running dhcrelay -6!"); return; /* XXX */ } @@ -1651,8 +1780,9 @@ function services_dhcrelay6_configure() { function services_dyndns_configure_client($conf) { - if (!isset($conf['enable'])) + if (!isset($conf['enable'])) { return; + } /* load up the dyndns.class */ require_once("dyndns.class"); @@ -1681,7 +1811,7 @@ function services_dyndns_configure_client($conf) { function services_dyndns_configure($int = "") { global $config, $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "services_dyndns_configure() being called $mt\n"; } @@ -1689,8 +1819,9 @@ function services_dyndns_configure($int = "") { $dyndnscfg = $config['dyndnses']['dyndns']; $gwgroups = return_gateway_groups_array(); if (is_array($dyndnscfg)) { - if (platform_booting()) + if (platform_booting()) { echo gettext("Starting DynDNS clients..."); + } foreach ($dyndnscfg as $dyndns) { if ((empty($int)) || ($int == $dyndns['interface']) || (is_array($gwgroups[$dyndns['interface']]))) { @@ -1702,8 +1833,9 @@ function services_dyndns_configure($int = "") { } } - if (platform_booting()) + if (platform_booting()) { echo gettext("done.") . "\n"; + } } return 0; @@ -1716,8 +1848,9 @@ function dyndnsCheckIP($int) { $gateways_status = return_gateways_status(true); // If the gateway for this interface is down, then the external check cannot work. // Avoid the long wait for the external check to timeout. - if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'],"down")) + if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) { return "down"; + } $hosttocheck = "http://checkip.dyndns.org"; $ip_ch = curl_init($hosttocheck); curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1); @@ -1747,25 +1880,28 @@ function services_dnsmasq_configure() { ); - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "services_dnsmasq_configure() being called $mt\n"; } /* kill any running dnsmasq */ - if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) + if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) { sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM"); + } if (isset($config['dnsmasq']['enable'])) { - if (platform_booting()) + if (platform_booting()) { echo gettext("Starting DNS forwarder..."); - else + } else { sleep(1); + } - /* generate hosts file */ - if(system_hosts_generate()!=0) - $return = 1; + /* generate hosts file */ + if (system_hosts_generate()!=0) { + $return = 1; + } $args = ""; @@ -1774,11 +1910,12 @@ function services_dnsmasq_configure() { } /* Setup listen port, if non-default */ - if (is_port($config['dnsmasq']['port'])) + if (is_port($config['dnsmasq']['port'])) { $args .= " --port={$config['dnsmasq']['port']} "; + } $listen_addresses = ""; - if(isset($config['dnsmasq']['interface'])) { + if (isset($config['dnsmasq']['interface'])) { $interfaces = explode(",", $config['dnsmasq']['interface']); foreach ($interfaces as $interface) { if (is_ipaddrv4($interface)) { @@ -1791,18 +1928,21 @@ function services_dnsmasq_configure() { if (is_linklocal($interface) && strstr($interface, "%")) { $tmpaddrll6 = explode("%", $interface); $listen_addresses .= " --listen-address={$tmpaddrll6[0]} "; - } else + } else { $listen_addresses .= " --listen-address={$interface} "; + } } else if (strstr($interface, "_vip")) { $laddr = get_configured_carp_interface_list($interface); - if (is_ipaddr($laddr)) + if (is_ipaddr($laddr)) { $listen_addresses .= " --listen-address={$laddr} "; + } } else { $if = get_real_interface($interface); if (does_interface_exist($if)) { $laddr = get_interface_ip($interface); - if (is_ipaddrv4($laddr)) + if (is_ipaddrv4($laddr)) { $listen_addresses .= " --listen-address={$laddr} "; + } $laddr6 = get_interface_ipv6($interface); if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) { /* @@ -1812,16 +1952,18 @@ function services_dnsmasq_configure() { if (is_linklocal($laddr6) && strstr($laddr6, "%")) { $tmpaddrll6 = explode("%", $laddr6); $listen_addresses .= " --listen-address={$tmpaddrll6[0]} "; - } else + } else { $listen_addresses .= " --listen-address={$laddr6} "; + } } } } } if (!empty($listen_addresses)) { $args .= " {$listen_addresses} "; - if (isset($config['dnsmasq']['strictbind'])) + if (isset($config['dnsmasq']['strictbind'])) { $args .= " --bind-interfaces "; + } } } @@ -1843,14 +1985,15 @@ function services_dnsmasq_configure() { // Build an array of the private reverse lookup domain names $reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa"); // Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme. - for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) { + for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) { $reverse_domain_a[] = "$subnet_num.172.in-addr.arpa"; } // Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override. - foreach ($reverse_domain_a as $reverse_domain) { - if (!isset($override_a[$reverse_domain])) + foreach ($reverse_domain_a as $reverse_domain) { + if (!isset($override_a[$reverse_domain])) { $args .= " --server=/$reverse_domain/ "; + } } unset($override_a); unset($reverse_domain_a); @@ -1858,24 +2001,26 @@ function services_dnsmasq_configure() { /* Setup forwarded domains */ if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) { - foreach($config['dnsmasq']['domainoverrides'] as $override) { - if ($override['ip'] == "!") + foreach ($config['dnsmasq']['domainoverrides'] as $override) { + if ($override['ip'] == "!") { $override[ip] = ""; + } $args .= ' --server=/' . $override['domain'] . '/' . $override['ip']; } } /* Allow DNS Rebind for forwarded domains */ if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) { - if(!isset($config['system']['webgui']['nodnsrebindcheck'])) { - foreach($config['dnsmasq']['domainoverrides'] as $override) { + if (!isset($config['system']['webgui']['nodnsrebindcheck'])) { + foreach ($config['dnsmasq']['domainoverrides'] as $override) { $args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ '; } } } - if(!isset($config['system']['webgui']['nodnsrebindcheck'])) + if (!isset($config['system']['webgui']['nodnsrebindcheck'])) { $dns_rebind = "--rebind-localhost-ok --stop-dns-rebind"; + } if (isset($config['dnsmasq']['strict_order'])) { $args .= " --strict-order "; @@ -1885,13 +2030,15 @@ function services_dnsmasq_configure() { $args .= " --domain-needed "; } - if ($config['dnsmasq']['custom_options']) + if ($config['dnsmasq']['custom_options']) { foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) { $args .= " " . escapeshellarg("--{$c}"); $p = explode('=', $c); - if (array_key_exists($p[0], $standard_args)) + if (array_key_exists($p[0], $standard_args)) { unset($standard_args[$p[0]]); + } } + } $args .= ' ' . implode(' ', array_values($standard_args)); /* run dnsmasq */ @@ -1900,15 +2047,17 @@ function services_dnsmasq_configure() { mwexec_bg($cmd); unset($args); - system_dhcpleases_configure(); + system_dhcpleases_configure(); - if (platform_booting()) + if (platform_booting()) { echo gettext("done.") . "\n"; + } } if (!platform_booting()) { - if(services_dhcpd_configure()!=0) + if (services_dhcpd_configure()!=0) { $return = 1; + } } return $return; @@ -1924,30 +2073,35 @@ function services_unbound_configure() { } // kill any running Unbound instance - if (file_exists("{$g['varrun_path']}/unbound.pid")) + if (file_exists("{$g['varrun_path']}/unbound.pid")) { sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM"); + } if (isset($config['unbound']['enable'])) { - if (platform_booting()) + if (platform_booting()) { echo gettext("Starting DNS Resolver..."); - else + } else { sleep(1); + } /* generate hosts file */ - if(system_hosts_generate()!=0) + if (system_hosts_generate()!=0) { $return = 1; + } require_once('/etc/inc/unbound.inc'); sync_unbound_service(); - if (platform_booting()) + if (platform_booting()) { echo gettext("done.") . "\n"; + } - system_dhcpleases_configure(); + system_dhcpleases_configure(); } if (!platform_booting()) { - if (services_dhcpd_configure()!=0) + if (services_dhcpd_configure()!=0) { $return = 1; + } } return $return; @@ -1955,7 +2109,7 @@ function services_unbound_configure() { function services_snmpd_configure() { global $config, $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "services_snmpd_configure() being called $mt\n"; } @@ -1963,13 +2117,15 @@ function services_snmpd_configure() { /* kill any running snmpd */ sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM"); sleep(2); - if(is_process_running("bsnmpd")) + if (is_process_running("bsnmpd")) { mwexec("/usr/bin/killall bsnmpd", true); + } if (isset($config['snmpd']['enable'])) { - if (platform_booting()) + if (platform_booting()) { echo gettext("Starting SNMP daemon... "); + } /* generate snmpd.conf */ $fd = fopen("{$g['varetc_path']}/snmpd.conf", "w"); @@ -1987,8 +2143,8 @@ read := "{$config['snmpd']['rocommunity']}" EOD; /* No docs on what write strings do there for disable for now. - if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){ - $snmpdconf .= << $dnsupdate) { - if (!isset($dnsupdate['enable'])) + if (!isset($dnsupdate['enable'])) { continue; - if (!empty($int) && $int != $dnsupdate['interface']) + } + if (!empty($int) && $int != $dnsupdate['interface']) { continue; - if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) + } + if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) { continue; + } /* determine interface name */ $if = get_real_interface($dnsupdate['interface']); - - if (isset($dnsupdate['usepublicip'])) - $wanip = dyndnsCheckIP($dnsupdate['interface']); - else - $wanip = get_interface_ip($dnsupdate['interface']); - + + if (isset($dnsupdate['usepublicip'])) { + $wanip = dyndnsCheckIP($dnsupdate['interface']); + } else { + $wanip = get_interface_ip($dnsupdate['interface']); + } + $wanipv6 = get_interface_ipv6($dnsupdate['interface']); $cacheFile = "{$g['conf_path']}/dyndns_{$dnsupdate['interface']}_rfc2136_" . escapeshellarg($dnsupdate['host']) . "_{$dnsupdate['server']}.cache"; $currentTime = time(); @@ -2190,13 +2353,15 @@ function services_dnsupdate_process($int = "", $updatehost = "", $forced = false if ($wanip || $wanipv6) { $keyname = $dnsupdate['keyname']; /* trailing dot */ - if (substr($keyname, -1) != ".") + if (substr($keyname, -1) != ".") { $keyname .= "."; + } $hostname = $dnsupdate['host']; /* trailing dot */ - if (substr($hostname, -1) != ".") + if (substr($hostname, -1) != ".") { $hostname .= "."; + } /* write private key file this is dumb - public and private keys are the same for HMAC-MD5, @@ -2229,8 +2394,9 @@ EOD; /* generate update instructions */ $upinst = ""; - if (!empty($dnsupdate['server'])) + if (!empty($dnsupdate['server'])) { $upinst .= "server {$dnsupdate['server']}\n"; + } if (file_exists($cacheFile)) { list($cachedipv4, $cacheTimev4) = explode("|", file_get_contents($cacheFile)); @@ -2256,8 +2422,9 @@ EOD; } else { log_error("phpDynDNS: Not updating {$dnsupdate['host']} A record because the IP address has not changed."); } - } else + } else { @unlink($cacheFile); + } /* Update IPv6 if we have it. */ if (is_ipaddrv6($wanipv6)) { @@ -2271,8 +2438,9 @@ EOD; } else { log_error("phpDynDNS: Not updating {$dnsupdate['host']} AAAA record because the IPv6 address has not changed."); } - } else + } else { @unlink("{$cacheFile}.ipv6"); + } conf_mount_ro(); $upinst .= "\n"; /* mind that trailing newline! */ @@ -2282,8 +2450,9 @@ EOD; unset($upinst); /* invoke nsupdate */ $cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key"; - if (isset($dnsupdate['usetcp'])) + if (isset($dnsupdate['usetcp'])) { $cmd .= " -v"; + } $cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}"; mwexec_bg($cmd); unset($cmd); @@ -2319,13 +2488,14 @@ function configure_cron() { if (is_array($config['cron']['item'])) { $crontab_contents .= "#\n"; $crontab_contents .= "# " . gettext("pfSense specific crontab entries") . "\n"; - $crontab_contents .= "# " .gettext( "Created:") . " " . date("F j, Y, g:i a") . "\n"; + $crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n"; $crontab_contents .= "#\n"; if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) { $http_proxy = $config['system']['proxyurl']; - if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) + if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) { $http_proxy .= ':' . $config['system']['proxyport']; + } $crontab_contents .= "HTTP_PROXY={$http_proxy}"; } @@ -2357,7 +2527,7 @@ function configure_cron() { function upnp_action ($action) { global $g, $config; - switch($action) { + switch ($action) { case "start": if (file_exists('/var/etc/miniupnpd.conf')) { @unlink("{$g['varrun_path']}/miniupnpd.pid"); @@ -2366,8 +2536,9 @@ function upnp_action ($action) { break; case "stop": killbypid("{$g['varrun_path']}/miniupnpd.pid"); - while((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) + while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) { mwexec('killall miniupnpd 2>/dev/null', true); + } mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null'); mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null'); break; @@ -2381,10 +2552,11 @@ function upnp_action ($action) { function upnp_start() { global $config; - if(!isset($config['installedpackages']['miniupnpd']['config'])) + if (!isset($config['installedpackages']['miniupnpd']['config'])) { return; + } - if($config['installedpackages']['miniupnpd']['config'][0]['enable']) { + if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) { echo gettext("Starting UPnP service... "); require_once('/usr/local/pkg/miniupnpd.inc'); sync_package_miniupnpd(); @@ -2398,21 +2570,23 @@ function install_cron_job($command, $active=false, $minute="0", $hour="*", $mont $is_installed = false; $cron_changed = true; - if (!is_array($config['cron'])) + if (!is_array($config['cron'])) { $config['cron'] = array(); - if (!is_array($config['cron']['item'])) + } + if (!is_array($config['cron']['item'])) { $config['cron']['item'] = array(); + } $x=0; - foreach($config['cron']['item'] as $item) { - if(strstr($item['command'], $command)) { + foreach ($config['cron']['item'] as $item) { + if (strstr($item['command'], $command)) { $is_installed = true; break; } $x++; } - if($active) { + if ($active) { $cron_item = array(); $cron_item['minute'] = $minute; $cron_item['hour'] = $hour; @@ -2421,7 +2595,7 @@ function install_cron_job($command, $active=false, $minute="0", $hour="*", $mont $cron_item['wday'] = $weekday; $cron_item['who'] = $who; $cron_item['command'] = $command; - if(!$is_installed) { + if (!$is_installed) { $config['cron']['item'][] = $cron_item; write_config(sprintf(gettext("Installed cron job for %s"), $command)); } else { @@ -2434,14 +2608,15 @@ function install_cron_job($command, $active=false, $minute="0", $hour="*", $mont } } } else { - if($is_installed == true) { + if ($is_installed == true) { unset($config['cron']['item'][$x]); write_config(sprintf(gettext("Removed cron job for %s"), $command)); } } - if ($cron_changed) + if ($cron_changed) { configure_cron(); + } } ?> diff --git a/etc/inc/shaper.inc b/etc/inc/shaper.inc index d2f7bfc886..92384e1289 100644 --- a/etc/inc/shaper.inc +++ b/etc/inc/shaper.inc @@ -37,10 +37,9 @@ require_once("util.inc"); require_once("notices.inc"); /* - * I admit :) this is derived from xmplparse.inc StartElement() + * I admit :) this is derived from xmlparse.inc StartElement() */ -function &get_reference_to_me_in_config(&$mypath) -{ +function &get_reference_to_me_in_config(&$mypath) { global $config; $ptr =& $config['shaper']; @@ -51,8 +50,7 @@ function &get_reference_to_me_in_config(&$mypath) return $ptr; } -function unset_object_by_reference(&$mypath) -{ +function unset_object_by_reference(&$mypath) { global $config; $ptr =& $config['shaper']; @@ -62,8 +60,7 @@ function unset_object_by_reference(&$mypath) unset($ptr['queue'][$mypath[$i]]); } -function &get_dn_reference_to_me_in_config(&$mypath) -{ +function &get_dn_reference_to_me_in_config(&$mypath) { global $config; $ptr =& $config['dnshaper']; @@ -74,8 +71,7 @@ function &get_dn_reference_to_me_in_config(&$mypath) return $ptr; } -function unset_dn_object_by_reference(&$mypath) -{ +function unset_dn_object_by_reference(&$mypath) { global $config; $ptr =& $config['dnshaper']; @@ -85,87 +81,127 @@ function unset_dn_object_by_reference(&$mypath) unset($ptr['queue'][$mypath[$i]]); } -function clean_child_queues($type, $mypath) -{ +function clean_child_queues($type, $mypath) { $ref = &get_reference_to_me_in_config($mypath); switch ($type) { - case 'HFSC': - if (isset($ref['borrow'])) unset($ref['borrow']); - if (isset($ref['hogs'])) unset($ref['hogs']); - if (isset($ref['buckets'])) unset($ref['buckets']); - break; - case 'PRIQ': - if (isset($ref['borrow'])) unset($ref['borrow']); - if (isset($ref['bandwidth'])) unset($ref['bandwidth']); - if (isset($ref['bandwidthtype'])) unset($ref['bandwidthtype']); - /* fall through */ - case 'FAIRQ': - if (isset($ref['borrow'])) unset($ref['borrow']); - /* fall through */ - case 'CBQ': - if (isset($ref['realtime'])) unset($ref['realtime']); - if (isset($ref['realtime1'])) unset($ref['realtime1']); - if (isset($ref['realtime2'])) unset($ref['realtime2']); - if (isset($ref['realtime3'])) unset($ref['realtime3']); - if (isset($ref['upperlimit'])) unset($ref['upperlimit']); - if (isset($ref['upperlimit1'])) unset($ref['upperlimit1']); - if (isset($ref['upperlimit2'])) unset($ref['upperlimit2']); - if (isset($ref['upperlimit3'])) unset($ref['upperlimit3']); - if (isset($ref['linkshare'])) unset($ref['linkshare']); - if (isset($ref['linkshare1'])) unset($ref['linkshare1']); - if (isset($ref['linkshare2'])) unset($ref['linkshare2']); - if (isset($ref['linkshare3'])) unset($ref['linkshare3']); - if (isset($ref['hogs'])) unset($ref['hogs']); - if (isset($ref['buckets'])) unset($ref['buckets']); - break; + case 'HFSC': + if (isset($ref['borrow'])) { + unset($ref['borrow']); + } + if (isset($ref['hogs'])) { + unset($ref['hogs']); + } + if (isset($ref['buckets'])) { + unset($ref['buckets']); + } + break; + case 'PRIQ': + if (isset($ref['borrow'])) { + unset($ref['borrow']); + } + if (isset($ref['bandwidth'])) { + unset($ref['bandwidth']); + } + if (isset($ref['bandwidthtype'])) { + unset($ref['bandwidthtype']); + } + /* fall through */ + case 'FAIRQ': + if (isset($ref['borrow'])) { + unset($ref['borrow']); + } + /* fall through */ + case 'CBQ': + if (isset($ref['realtime'])) { + unset($ref['realtime']); + } + if (isset($ref['realtime1'])) { + unset($ref['realtime1']); + } + if (isset($ref['realtime2'])) { + unset($ref['realtime2']); + } + if (isset($ref['realtime3'])) { + unset($ref['realtime3']); + } + if (isset($ref['upperlimit'])) { + unset($ref['upperlimit']); + } + if (isset($ref['upperlimit1'])) { + unset($ref['upperlimit1']); + } + if (isset($ref['upperlimit2'])) { + unset($ref['upperlimit2']); + } + if (isset($ref['upperlimit3'])) { + unset($ref['upperlimit3']); + } + if (isset($ref['linkshare'])) { + unset($ref['linkshare']); + } + if (isset($ref['linkshare1'])) { + unset($ref['linkshare1']); + } + if (isset($ref['linkshare2'])) { + unset($ref['linkshare2']); + } + if (isset($ref['linkshare3'])) { + unset($ref['linkshare3']); + } + if (isset($ref['hogs'])) { + unset($ref['hogs']); + } + if (isset($ref['buckets'])) { + unset($ref['buckets']); + } + break; } } -function get_bandwidthtype_scale($type) -{ +function get_bandwidthtype_scale($type) { switch ($type) { - case "Gb": - $factor = 1024 * 1024 * 1024; - break; - case "Mb": - $factor = 1024 * 1024; - break; - case "Kb": - $factor = 1024; - break; - case "b": - default: - $factor = 1; - break; + case "Gb": + $factor = 1024 * 1024 * 1024; + break; + case "Mb": + $factor = 1024 * 1024; + break; + case "Kb": + $factor = 1024; + break; + case "b": + default: + $factor = 1; + break; } return intval($factor); } -function get_hfsc_bandwidth($object, $bw) -{ +function get_hfsc_bandwidth($object, $bw) { $pattern= "/[0-9]+/"; - if (preg_match($pattern, $bw, $match)) + if (preg_match($pattern, $bw, $match)) { $bw_1 = $match[1]; - else + } else { return 0; + } $pattern= "/(b|Kb|Mb|Gb|%)/"; if (preg_match($pattern, $bw, $match)) { switch ($match[1]) { - case '%': - $bw_1 = $bw_1 / 100 * get_interface_bandwidth($object); - break; - default: - $bw_1 = $bw_1 * get_bandwidthtype_scale($match[0]); - break; + case '%': + $bw_1 = $bw_1 / 100 * get_interface_bandwidth($object); + break; + default: + $bw_1 = $bw_1 * get_bandwidthtype_scale($match[0]); + break; } return floatval($bw_1); - } else + } else { return 0; + } } -function get_interface_bandwidth($object) -{ +function get_interface_bandwidth($object) { global $altq_list_queues; $int = $object->GetInterface(); @@ -174,16 +210,16 @@ function get_interface_bandwidth($object) $bw_3 = $altq->GetBandwidth(); $bw_3 = $bw_3 * get_bandwidthtype_scale($altq->GetBwscale()); return floatval($bw_3); - } else + } else { return 0; + } } /* * This is duplicated here since we cannot include guiconfig.inc. * Including it makes all stuff break. */ -function shaper_do_input_validation($postdata, $reqdfields, $reqdfieldsn, $input_errors) -{ +function shaper_do_input_validation($postdata, $reqdfields, $reqdfieldsn, $input_errors) { /* check for bad control characters */ foreach ($postdata as $pn => $pd) { @@ -199,27 +235,29 @@ function shaper_do_input_validation($postdata, $reqdfields, $reqdfieldsn, $input } } -function cleanup_queue_from_rules($queue) -{ +function cleanup_queue_from_rules($queue) { global $config; foreach ($config['filter']['rule'] as $rule) { - if ($rule['defaultqueue'] == $queue) + if ($rule['defaultqueue'] == $queue) { unset($rule['defaultqueue']); - if ($rule['ackqueue'] == $queue) + } + if ($rule['ackqueue'] == $queue) { unset($rule['ackqueue']); + } } } -function cleanup_dnqueue_from_rules($queue) -{ +function cleanup_dnqueue_from_rules($queue) { global $config; foreach ($config['filter']['rule'] as $rule) { - if ($rule['dnpipe'] == $queue) + if ($rule['dnpipe'] == $queue) { unset($rule['dnpipe']); - if ($rule['pdnpipe'] == $queue) + } + if ($rule['pdnpipe'] == $queue) { unset($rule['pdnpipe']); + } } } @@ -245,8 +283,9 @@ class altq_root_queue { function GetDefaultQueuePresent() { if (!empty($this->queues)) { foreach ($this->queues as $q) { - if ($q->GetDefault()) + if ($q->GetDefault()) { return true; + } } } @@ -265,10 +304,11 @@ class altq_root_queue { $this->qenabled = $value; } function CanHaveChildren() { - if ($this->GetScheduler() == "CODELQ") + if ($this->GetScheduler() == "CODELQ") { return false; - else + } else { return true; + } } function CanBeDeleted() { return false; @@ -325,29 +365,37 @@ class altq_root_queue { shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - if ($data['bandwidth'] && (!is_numeric($data['bandwidth']))) + if ($data['bandwidth'] && (!is_numeric($data['bandwidth']))) { $input_errors[] = gettext("Bandwidth must be an integer."); - if ($data['bandwidth'] < 0) + } + if ($data['bandwidth'] < 0) { $input_errors[] = gettext("Bandwidth cannot be negative."); - if ($data['qlimit'] && (!is_numeric($data['qlimit']))) + } + if ($data['qlimit'] && (!is_numeric($data['qlimit']))) { $input_errors[] = gettext("Qlimit must be an integer."); - if ($data['qlimit'] < 0) + } + if ($data['qlimit'] < 0) { $input_errors[] = gettext("Qlimit must be positive."); - if ($data['tbrconfig'] && (!is_numeric($data['tbrconfig']))) + } + if ($data['tbrconfig'] && (!is_numeric($data['tbrconfig']))) { $input_errors[] = gettext("Tbrsize must be an integer."); - if ($data['tbrconfig'] < 0) + } + if ($data['tbrconfig'] < 0) { $input_errors[] = gettext("Tbrsize must be positive."); + } } /* Implement this to shorten some code on the frontend page */ function ReadConfig(&$conf) { - if (isset($conf['tbrconfig'])) + if (isset($conf['tbrconfig'])) { $this->SetTbrConfig($conf['tbrconfig']); - else + } else { $this->SetTbrConfig($conf['tbrconfig']); + } $this->SetBandwidth($conf['bandwidth']); - if ($conf['bandwidthtype'] <> "") + if ($conf['bandwidthtype'] <> "") { $this->SetBwscale($conf['bandwidthtype']); + } if (isset($conf['scheduler'])) { if ($this->GetScheduler() != $conf['scheduler']) { foreach ($this->queues as $q) { @@ -357,16 +405,19 @@ class altq_root_queue { } $this->SetScheduler($conf['scheduler']); } - if (isset($conf['qlimit']) && $conf['qlimit'] <> "") + if (isset($conf['qlimit']) && $conf['qlimit'] <> "") { $this->SetQlimit($conf['qlimit']); - else + } else { $this->SetQlimit(""); - if (isset($conf['name'])) + } + if (isset($conf['name'])) { $this->SetQname($conf['name']); - if (!empty($conf['enabled'])) + } + if (!empty($conf['enabled'])) { $this->SetEnabled($conf['enabled']); - else + } else { $this->SetEnabled(""); + } } function copy_queue($interface, &$cflink) { @@ -392,34 +443,36 @@ class altq_root_queue { //$qlist[$this->GetQname()] = & $this; if (is_array($this->queues)) { - foreach ($this->queues as $queue) + foreach ($this->queues as $queue) { $queue->get_queue_list($qlist); + } } return $qlist; } function &add_queue($interface, &$queue, &$path, &$input_errors) { - if (!is_array($this->queues)) + if (!is_array($this->queues)) { $this->queues = array(); + } switch ($this->GetScheduler()) { - case "PRIQ": - $q =& new priq_queue(); - break; - case "HFSC": - $q =& new hfsc_queue(); - break; - case "CBQ": - $q =& new cbq_queue(); - break; - case "FAIRQ": - $q =& new fairq_queue(); - break; - default: - /* XXX: but should not happen anyway */ - return; - break; + case "PRIQ": + $q =& new priq_queue(); + break; + case "HFSC": + $q =& new hfsc_queue(); + break; + case "CBQ": + $q =& new cbq_queue(); + break; + case "FAIRQ": + $q =& new fairq_queue(); + break; + default: + /* XXX: but should not happen anyway */ + return; + break; } $q->SetLink($path); $q->SetInterface($this->GetInterface()); @@ -434,12 +487,12 @@ class altq_root_queue { if (isset($queue['bandwidth'])) { switch ($queue['bandwidthtype']) { - case "%": - $myBw = $this->GetAvailableBandwidth() * $queue['bandwidth'] / 100; - break; - default: - $myBw = $queue['bandwidth'] * get_bandwidthtype_scale($queue['bandwdithtype']); - break; + case "%": + $myBw = $this->GetAvailableBandwidth() * $queue['bandwidth'] / 100; + break; + default: + $myBw = $queue['bandwidth'] * get_bandwidthtype_scale($queue['bandwdithtype']); + break; } } $q->SetAvailableBandwidth($myBw); @@ -464,8 +517,9 @@ class altq_root_queue { } foreach ($this->queues as $q) { $result =& $q->find_queue("", $qname); - if ($result) + if ($result) { return $result; + } } } @@ -477,8 +531,9 @@ class altq_root_queue { } else if ($this->GetScheduler() <> "PRIQ") { foreach ($this->queues as $q) { $result = $q->find_parentqueue("", $qname); - if ($result) + if ($result) { return $result; + } } } } @@ -493,7 +548,7 @@ class altq_root_queue { foreach ($this->queues as $q) { $tree .= $q->build_tree(); } - $tree .= "
    "; + $tree .= "
"; } $tree .= ""; return $tree; @@ -501,7 +556,7 @@ class altq_root_queue { function delete_queue() { foreach ($this->queues as $q) { - $this->SetAvailableBandwidth($this->GetAvailableBandwidth() + $q->GetAvailableBandwidth()); + $this->SetAvailableBandwidth($this->GetAvailableBandwidth() + $q->GetAvailableBandwidth()); $q->delete_queue(); } unset_object_by_reference($this->GetLink()); @@ -522,24 +577,29 @@ class altq_root_queue { * First it spits: * altq on $interface .............. * then it goes like - * foreach ($queues as $qkey => $queue) + * foreach ($queues as $qkey => $queue) { * this->queues[$qkey]->build_rule(); + * } */ function build_rules(&$default = false) { if (count($this->queues) > 0 && $this->GetEnabled() == "on") { $default = false; $rules = " altq on " . get_real_interface($this->GetInterface()); - if ($this->GetScheduler()) + if ($this->GetScheduler()) { $rules .= " ".strtolower($this->GetScheduler()); - if ($this->GetQlimit() > 0) + } + if ($this->GetQlimit() > 0) { $rules .= " qlimit " . $this->GetQlimit() . " "; + } if ($this->GetBandwidth()) { $rules .= " bandwidth ".trim($this->GetBandwidth()); - if ($this->GetBwscale()) + if ($this->GetBwscale()) { $rules .= $this->GetBwscale(); + } } - if ($this->GetTbrConfig()) + if ($this->GetTbrConfig()) { $rules .= " tbrsize ".$this->GetTbrConfig(); + } if (count($this->queues)) { $i = count($this->queues); $rules .= " queue { "; @@ -547,8 +607,9 @@ class altq_root_queue { if ($i > 1) { $i--; $rules .= " {$qkey}, "; - } else + } else { $rules .= " {$qkey} "; + } } $rules .= " } \n"; foreach ($this->queues as $q) { @@ -565,17 +626,21 @@ class altq_root_queue { $frule .= $rules; } else if ($this->GetEnabled() == "on" && $this->GetScheduler() == "CODELQ") { $rules = " altq on " . get_real_interface($this->GetInterface()); - if ($this->GetScheduler()) + if ($this->GetScheduler()) { $rules .= " ".strtolower($this->GetScheduler()); - if ($this->GetQlimit() > 0) + } + if ($this->GetQlimit() > 0) { $rules .= " ( qlimit " . $this->GetQlimit() . " ) "; + } if ($this->GetBandwidth()) { $rules .= " bandwidth ".trim($this->GetBandwidth()); - if ($this->GetBwscale()) + if ($this->GetBwscale()) { $rules .= $this->GetBwscale(); + } } - if ($this->GetTbrConfig()) + if ($this->GetTbrConfig()) { $rules .= " tbrsize ".$this->GetTbrConfig(); + } $rules .= " queue"; } @@ -610,8 +675,9 @@ class altq_root_queue { global $g; $altq =& $this; - if ($altq) + if ($altq) { $scheduler = ": " . $altq->GetScheduler(); + } $form = ""; $form .= "GetInterface() . "&queue=". $this->GetInterface()."&action=show\">". $shaperIFlist[$this->GetInterface()] .": ".$scheduler.""; $form .= ""; @@ -640,8 +706,9 @@ class altq_root_queue { $form .= gettext("Enable/Disable"); $form .= "
"; $form .= " GetEnabled() == "on") + if ($this->GetEnabled() == "on") { $form .= " checked=\"checked\""; + } $form .= " /> " . gettext("Enable/disable discipline and its children") . ""; $form .= ""; $form .= "
" . gettext("Name") . ""; @@ -653,24 +720,29 @@ class altq_root_queue { $form .= ""; $form .= ""; $form .= "
"; @@ -684,20 +756,24 @@ class altq_root_queue { $form .= $this->GetBandwidth() . "\" />"; $form .= ""; $form .= ""; @@ -714,14 +790,13 @@ class altq_root_queue { $form .= "\" />"; $form .= "
"; $form .= gettext("Adjusts the size, in bytes, of the token bucket regulator. " - . "If not specified, heuristics based on the interface " - . "bandwidth are used to determine the size."); + . "If not specified, heuristics based on the interface " + . "bandwidth are used to determine the size."); $form .= ""; $form .= "GetInterface() . "\" />"; $form .= "GetQname()."\" />"; - return $form; } @@ -735,22 +810,26 @@ class altq_root_queue { */ function wconfig() { $cflink = &get_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) + if (!is_array($cflink)) { $cflink = array(); + } $cflink['interface'] = $this->GetInterface(); $cflink['name'] = $this->GetQname(); $cflink['scheduler'] = $this->GetScheduler(); $cflink['bandwidth'] = $this->GetBandwidth(); $cflink['bandwidthtype'] = $this->GetBwscale(); $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) + if (empty($cflink['qlimit'])) { unset($cflink['qlimit']); + } $cflink['tbrconfig'] = trim($this->GetTbrConfig()); - if (empty($cflink['tbrconfig'])) + if (empty($cflink['tbrconfig'])) { unset($cflink['tbrconfig']); + } $cflink['enabled'] = $this->GetEnabled(); - if (empty($cflink['enabled'])) + if (empty($cflink['enabled'])) { unset($cflink['enabled']); + } } } @@ -858,12 +937,14 @@ class priq_queue { $this->qbandwidthtype = $scale; } function GetDefaultQueuePresent() { - if ($this->GetDefault()) + if ($this->GetDefault()) { return true; + } if (!empty($this->subqueues)) { foreach ($this->subqueues as $q) { - if ($q->GetDefault()) + if ($q->GetDefault()) { return true; + } } } @@ -955,14 +1036,14 @@ class priq_queue { $q->copy_queue($interface, $cflink['queue'][$q->GetQname()]); } } - } function clean_queue($sched) { clean_child_queues($sched, $this->GetLink()); if (is_array($this->subqueues)) { - foreach ($this->subqueues as $q) + foreach ($this->subqueues as $q) { $q->clean_queue($sched); + } } } @@ -970,8 +1051,9 @@ class priq_queue { $qlist[$this->GetQname()] = & $this; if (is_array($this->subqueues)) { - foreach ($this->subqueues as $queue) + foreach ($this->subqueues as $queue) { $queue->get_queue_list($qlist); + } } } @@ -993,8 +1075,9 @@ class priq_queue { } function &find_queue($interface, $qname) { - if ($qname == $this->GetQname()) + if ($qname == $this->GetQname()) { return $this; + } } function find_parentqueue($interface, $qname) { return; } @@ -1005,25 +1088,32 @@ class priq_queue { $reqdfieldsn[] = gettext("Name"); shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - if ($data['bandwidth'] && (!is_numeric($data['bandwidth']))) + if ($data['bandwidth'] && (!is_numeric($data['bandwidth']))) { $input_errors[] = "Bandwidth must be an integer."; - if ($data['bandwidth'] < 0) + } + if ($data['bandwidth'] < 0) { $input_errors[] = "Bandwidth cannot be negative."; - if ($data['priority'] && (!is_numeric($data['priority']) - || ($data['priority'] < 1) || ($data['priority'] > 15))) { + } + if ($data['priority'] && (!is_numeric($data['priority']) || + ($data['priority'] < 1) || ($data['priority'] > 15))) { $input_errors[] = gettext("The priority must be an integer between 1 and 15."); } - if ($data['qlimit'] && (!is_numeric($data['qlimit']))) + if ($data['qlimit'] && (!is_numeric($data['qlimit']))) { $input_errors[] = gettext("Queue limit must be an integer"); - if ($data['qlimit'] < 0) + } + if ($data['qlimit'] < 0) { $input_errors[] = gettext("Queue limit must be positive"); - if (!empty($data['newname']) && !preg_match("/^[a-zA-Z0-9_-]*$/", $data['newname'])) + } + if (!empty($data['newname']) && !preg_match("/^[a-zA-Z0-9_-]*$/", $data['newname'])) { $input_errors[] = gettext("Queue names must be alphanumeric and _ or - only."); - if (!empty($data['name']) && !preg_match("/^[a-zA-Z0-9_-]*$/", $data['name'])) + } + if (!empty($data['name']) && !preg_match("/^[a-zA-Z0-9_-]*$/", $data['name'])) { $input_errors[] = gettext("Queue names must be alphanumeric and _ or - only."); + } $default = $this->GetDefault(); - if (!empty($data['default']) && altq_get_default_queue($data['interface']) && empty($default)) + if (!empty($data['default']) && altq_get_default_queue($data['interface']) && empty($default)) { $input_errors[] = gettext("Only one default queue per interface is allowed."); + } } function ReadConfig(&$q) { @@ -1031,58 +1121,70 @@ class priq_queue { $this->SetQname($q['newname']); } else if (!empty($q['newname'])) { $this->SetQname($q['newname']); - } else if (isset($q['name'])) + } else if (isset($q['name'])) { $this->SetQname($q['name']); - if (isset($q['interface'])) + } + if (isset($q['interface'])) { $this->SetInterface($q['interface']); + } $this->SetBandwidth($q['bandwidth']); - if ($q['bandwidthtype'] <> "") + if ($q['bandwidthtype'] <> "") { $this->SetBwscale($q['bandwidthtype']); - if (!empty($q['qlimit'])) + } + if (!empty($q['qlimit'])) { $this->SetQlimit($q['qlimit']); - else + } else { $this->SetQlimit(""); // Default - if (!empty($q['priority'])) + } + if (!empty($q['priority'])) { $this->SetQPriority($q['priority']); - else + } else { $this->SetQpriority(""); - if (!empty($q['description'])) + } + if (!empty($q['description'])) { $this->SetDescription($q['description']); - else + } else { $this->SetDescription(""); - if (!empty($q['red'])) + } + if (!empty($q['red'])) { $this->SetRed($q['red']); - else + } else { $this->SetRed(); - if (!empty($q['codel'])) + } + if (!empty($q['codel'])) { $this->SetCodel($q['codel']); - else + } else { $this->SetCodel(); - if (!empty($q['rio'])) + } + if (!empty($q['rio'])) { $this->SetRio($q['rio']); - else + } else { $this->SetRio(); - if (!empty($q['ecn'])) + } + if (!empty($q['ecn'])) { $this->SetEcn($q['ecn']); - else + } else { $this->SetEcn(); - if (!empty($q['default'])) + } + if (!empty($q['default'])) { $this->SetDefault($q['default']); - else + } else { $this->SetDefault(); - if (!empty($q['enabled'])) + } + if (!empty($q['enabled'])) { $this->SetEnabled($q['enabled']); - else + } else { $this->SetEnabled(""); - + } } function build_tree() { $tree = "
  • GetInterface()."&queue=". $this->GetQname()."&action=show"; $tree .= "\" "; $tmpvalue = $this->GetDefault(); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $tree .= " class=\"navlnk\""; + } $tree .= " >" . $this->GetQname() . ""; /* * Not needed here! @@ -1105,14 +1207,17 @@ class priq_queue { */ function build_rules(&$default = false) { $pfq_rule = " queue ". $this->qname; - if ($this->GetInterface()) + if ($this->GetInterface()) { $pfq_rule .= " on ".get_real_interface($this->GetInterface()); + } $tmpvalue = $this->GetQpriority(); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $pfq_rule .= " priority ".$this->GetQpriority(); + } $tmpvalue = $this->GetQlimit(); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $pfq_rule .= " qlimit " . $this->GetQlimit(); + } if ($this->GetRed() || $this->GetRio() || $this->GetEcn() || $this->GetDefault() || $this->GetCodel()) { $pfq_rule .= " priq ( "; $tmpvalue = $this->GetRed(); @@ -1122,29 +1227,33 @@ class priq_queue { } $tmpvalue = $this->GetRio(); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " rio "; } $tmpvalue = $this->GetEcn(); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " ecn "; } $tmpvalue = $this->GetCodel(); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " codel "; } $tmpvalue = $this->GetDefault(); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $pfq_rule .= " default "; $default = true; } @@ -1168,8 +1277,9 @@ class priq_queue { $form .= gettext("Enable/Disable"); $form .= "
    "; $form .= " GetEnabled() == "on") + if ($this->GetEnabled() == "on") { $form .= " checked=\"checked\""; + } $form .= " /> " . gettext("Enable/Disable queue and its children") . ""; $form .= ""; $form .= ""; @@ -1211,23 +1321,27 @@ class priq_queue { } $form .= "GetRed(); - if(!empty($tmpvalue)) + if (!empty($tmpvalue)) { $form .= " checked=\"checked\""; + } $form .= " /> " . gettext("Random Early Detection") . "
    "; $form .= "GetRio(); - if(!empty($tmpvalue)) + if (!empty($tmpvalue)) { $form .= " checked=\"checked\""; + } $form .= " /> " . gettext("Random Early Detection In and Out") . "
    "; $form .= "GetEcn(); - if(!empty($tmpvalue)) + if (!empty($tmpvalue)) { $form .= " checked=\"checked\""; + } $form .= " /> " . gettext("Explicit Congestion Notification") . "
    "; $form .= "GetCodel(); - if(!empty($tmpvalue)) + if (!empty($tmpvalue)) { $form .= " checked=\"checked\""; + } $form .= " /> " . gettext("Codel Active Queue") . "
    "; $form .= "
    " . gettext("Select options for this queue"); $form .= "
    "; @@ -1242,13 +1356,14 @@ class priq_queue { } function build_shortform() { - /* XXX: Hacks in site. Mostly layer violations! */ + /* XXX: Hacks in sight. Mostly layer violations! */ global $g, $altq_list_queues; global $shaperIFlist; $altq =& $altq_list_queues[$this->GetInterface()]; - if ($altq) + if ($altq) { $scheduler = ": " . $altq->GetScheduler(); + } $form = ""; $form .= "GetInterface() . "&queue=" . $this->GetQname()."&action=show\">". $shaperIFlist[$this->GetInterface()] .$scheduler.""; $form .= ""; @@ -1261,11 +1376,13 @@ class priq_queue { $form .= gettext("Bandwidth:") . " " . $this->GetBandwidth().$this->GetBwscale(); $form .= ""; $tmpvalue = $this->GetQpriority(); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $form .= "" .gettext("Priority: on") . " "; + } $tmpvalue = $this->GetDefault(); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $form .= "" . gettext("Default: on") . " "; + } $form .= ""; $form .= "GetInterface() . "&queue="; @@ -1279,43 +1396,53 @@ class priq_queue { } - function update_altq_queue_data(&$q) { + function update_altq_queue_data(&$q) { $this->ReadConfig($q); } function wconfig() { $cflink =& get_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) + if (!is_array($cflink)) { $cflink = array(); + } $cflink['name'] = $this->GetQname(); $cflink['interface'] = $this->GetInterface(); $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) + if (empty($cflink['qlimit'])) { unset($cflink['qlimit']); + } $cflink['priority'] = trim($this->GetQpriority()); - if (empty($cflink['priority'])) + if (empty($cflink['priority'])) { unset($cflink['priority']); + } $cflink['description'] = trim($this->GetDescription()); - if (empty($cflink['description'])) + if (empty($cflink['description'])) { unset($cflink['description']); + } $cflink['enabled'] = trim($this->GetEnabled()); - if (empty($cflink['enabled'])) + if (empty($cflink['enabled'])) { unset($cflink['enabled']); + } $cflink['default'] = trim($this->GetDefault()); - if (empty($cflink['default'])) + if (empty($cflink['default'])) { unset($cflink['default']); + } $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) + if (empty($cflink['red'])) { unset($cflink['red']); + } $cflink['codel'] = trim($this->GetCodel()); - if (empty($cflink['codel'])) + if (empty($cflink['codel'])) { unset($cflink['codel']); + } $cflink['rio'] = trim($this->GetRio()); - if (empty($cflink['rio'])) + if (empty($cflink['rio'])) { unset($cflink['rio']); + } $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) + if (empty($cflink['ecn'])) { unset($cflink['ecn']); + } } } @@ -1426,8 +1553,9 @@ class hfsc_queue extends priq_queue { function &add_queue($interface, &$qname, &$path, &$input_errors) { - if (!is_array($this->subqueues)) + if (!is_array($this->subqueues)) { $this->subqueues = array(); + } $q =& new hfsc_queue(); $q->SetInterface($this->GetInterface()); $q->SetParent($this); @@ -1441,12 +1569,12 @@ class hfsc_queue extends priq_queue { $q->SetEnabled("on"); $q->SetLink($path); switch ($q->GetBwscale()) { - case "%": - $myBw = $this->GetAvailableBandwidth() * $qname['bandwidth'] / 100; - break; - default: - $myBw = $qname['bandwidth'] * get_bandwidthtype_scale($q->GetBwscale()); - break; + case "%": + $myBw = $this->GetAvailableBandwidth() * $qname['bandwidth'] / 100; + break; + default: + $myBw = $qname['bandwidth'] * get_bandwidthtype_scale($q->GetBwscale()); + break; } $q->SetAvailableBandwidth($myBw); $this->SetAvailableBandwidth($this->GetAvailableBandwidth() - $myBw); @@ -1469,31 +1597,39 @@ class hfsc_queue extends priq_queue { $cflink['name'] = $this->GetQname(); $cflink['interface'] = $interface; $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) + if (empty($cflink['qlimit'])) { unset($cflink['qlimit']); + } $cflink['priority'] = trim($this->GetQpriority()); - if (empty($cflink['priority'])) + if (empty($cflink['priority'])) { unset($cflink['priority']); + } $cflink['description'] = trim($this->GetDescription()); - if (empty($cflink['description'])) + if (empty($cflink['description'])) { unset($cflink['description']); + } $cflink['bandwidth'] = $this->GetBandwidth(); $cflink['bandwidthtype'] = $this->GetBwscale(); $cflink['enabled'] = trim($this->GetEnabled()); - if (empty($cflink['enabled'])) + if (empty($cflink['enabled'])) { unset($cflink['enabled']); + } $cflink['default'] = trim($this->GetDefault()); - if (empty($cflink['default'])) + if (empty($cflink['default'])) { unset($cflink['default']); + } $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) + if (empty($cflink['red'])) { unset($cflink['red']); + } $cflink['rio'] = trim($this->GetRio()); - if (empty($cflink['rio'])) + if (empty($cflink['rio'])) { unset($cflink['rio']); + } $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) + if (empty($cflink['ecn'])) { unset($cflink['ecn']); + } if ($this->GetLinkshare() <> "") { if ($this->GetL_m1() <> "") { $cflink['linkshare1'] = $this->GetL_m1(); @@ -1563,8 +1699,8 @@ class hfsc_queue extends priq_queue { cleanup_queue_from_rules($this->GetQname()); $parent =& $this->GetParent(); foreach ($this->subqueues as $q) { - $this->SetAvailableBandwidth($this->GetAvailableBandwidth() + $q->GetAvailableBandwidth()); - $q->delete_queue(); + $this->SetAvailableBandwidth($this->GetAvailableBandwidth() + $q->GetAvailableBandwidth()); + $q->delete_queue(); } unset_object_by_reference($this->GetLink()); } @@ -1573,23 +1709,27 @@ class hfsc_queue extends priq_queue { * Should search even its children */ function &find_queue($interface, $qname) { - if ($qname == $this->GetQname()) + if ($qname == $this->GetQname()) { return $this; + } foreach ($this->subqueues as $q) { $result =& $q->find_queue("", $qname); - if ($result) + if ($result) { return $result; + } } } function &find_parentqueue($interface, $qname) { - if ($this->subqueues[$qname]) + if ($this->subqueues[$qname]) { return $this; + } foreach ($this->subqueues as $q) { $result = $q->find_parentqueue("", $qname); - if ($result) + if ($result) { return $result; + } } } @@ -1604,15 +1744,18 @@ class hfsc_queue extends priq_queue { shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); if (isset($data['linkshare3']) && $data['linkshare3'] <> "") { - if ($data['bandwidth'] && (!is_numeric($data['bandwidth']))) + if ($data['bandwidth'] && (!is_numeric($data['bandwidth']))) { $input_errors[] = gettext("Bandwidth must be an integer."); + } - if ($data['bandwidth'] < 0) + if ($data['bandwidth'] < 0) { $input_errors[] = gettext("Bandwidth cannot be negative."); + } if ($data['bandwidthtype'] == "%") { - if ($data['bandwidth'] > 100 || $data['bandwidth'] < 0) + if ($data['bandwidth'] > 100 || $data['bandwidth'] < 0) { $input_errors[] = gettext("Bandwidth in percentage should be between 1 and 100 bounds."); + } } /* $parent =& $this->GetParent(); @@ -1623,76 +1766,98 @@ class hfsc_queue extends priq_queue { $mybw = floatval($data['bandwidth']) * get_bandwidthtype_scale($data['bandwidthtype']); break; } - if ($parent->GetAvailableBandwidth() < $myBw) + if ($parent->GetAvailableBandwidth() < $myBw) { $input_errors[] = "The sum of children bandwidth exceeds that of the parent."; + } */ } - if ($data['upperlimit1'] <> "" && $data['upperlimit2'] == "") + if ($data['upperlimit1'] <> "" && $data['upperlimit2'] == "") { $input_errors[] = gettext("upperlimit service curve defined but missing (d) value"); - if ($data['upperlimit2'] <> "" && $data['upperlimit1'] == "") + } + if ($data['upperlimit2'] <> "" && $data['upperlimit1'] == "") { $input_errors[] = gettext("upperlimit service curve defined but missing initial bandwidth (m1) value"); - if ($data['upperlimit1'] <> "" && !is_valid_shaperbw($data['upperlimit1'])) + } + if ($data['upperlimit1'] <> "" && !is_valid_shaperbw($data['upperlimit1'])) { $input_errors[] = gettext("upperlimit m1 value needs to be Kb, Mb, Gb, or %"); - if ($data['upperlimit2'] <> "" && !is_numeric($data['upperlimit2'])) + } + if ($data['upperlimit2'] <> "" && !is_numeric($data['upperlimit2'])) { $input_errors[] = gettext("upperlimit d value needs to be numeric"); - if ($data['upperlimit3'] <> "" && !is_valid_shaperbw($data['upperlimit3'])) + } + if ($data['upperlimit3'] <> "" && !is_valid_shaperbw($data['upperlimit3'])) { $input_errors[] = gettext("upperlimit m2 value needs to be Kb, Mb, Gb, or %"); + } /* if (isset($data['upperlimit']) && $data['upperlimit3'] <> "" && $data['upperlimit1'] <> "") { $bw_1 = get_hfsc_bandwidth($this, $data['upperlimit1']); $bw_2 = get_hfsc_bandwidth($this, $data['upperlimit3']); - if (floatval($bw_1) < floatval($bw_2)) + if (floatval($bw_1) < floatval($bw_2)) { $input_errors[] = ("upperlimit m1 cannot be smaller than m2"); + } - if (get_interface_bandwidth($this) < (0.8 * (floatval($bw_1) + floatval($bw_2)))) + if (get_interface_bandwidth($this) < (0.8 * (floatval($bw_1) + floatval($bw_2)))) { $input_errors[] = ("upperlimit specification exceeds 80% of allowable allocation."); + } } */ - if ($data['linkshare1'] <> "" && $data['linkshare2'] == "") + if ($data['linkshare1'] <> "" && $data['linkshare2'] == "") { $input_errors[] = gettext("linkshare service curve defined but missing (d) value"); - if ($data['linkshare2'] <> "" && $data['linkshare1'] == "") + } + if ($data['linkshare2'] <> "" && $data['linkshare1'] == "") { $input_errors[] = gettext("linkshare service curve defined but missing initial bandwidth (m1) value"); - if ($data['linkshare1'] <> "" && !is_valid_shaperbw($data['linkshare1'])) + } + if ($data['linkshare1'] <> "" && !is_valid_shaperbw($data['linkshare1'])) { $input_errors[] = gettext("linkshare m1 value needs to be Kb, Mb, Gb, or %"); - if ($data['linkshare2'] <> "" && !is_numeric($data['linkshare2'])) + } + if ($data['linkshare2'] <> "" && !is_numeric($data['linkshare2'])) { $input_errors[] = gettext("linkshare d value needs to be numeric"); - if ($data['linkshare3'] <> "" && !is_valid_shaperbw($data['linkshare3'])) + } + if ($data['linkshare3'] <> "" && !is_valid_shaperbw($data['linkshare3'])) { $input_errors[] = gettext("linkshare m2 value needs to be Kb, Mb, Gb, or %"); - if ($data['realtime1'] <> "" && $data['realtime2'] == "") + } + if ($data['realtime1'] <> "" && $data['realtime2'] == "") { $input_errors[] = gettext("realtime service curve defined but missing (d) value"); - if ($data['realtime2'] <> "" && $data['realtime1'] == "") + } + if ($data['realtime2'] <> "" && $data['realtime1'] == "") { $input_errors[] = gettext("realtime service curve defined but missing initial bandwidth (m1) value"); + } /* if (isset($data['linkshare']) && $data['linkshare3'] <> "" && $data['linkshare1'] <> "" && 0) { $bw_1 = get_hfsc_bandwidth($this, $data['linkshare1']); $bw_2 = get_hfsc_bandwidth($this, $data['linkshare3']); - if (floatval($bw_1) < floatval($bw_2)) + if (floatval($bw_1) < floatval($bw_2)) { $input_errors[] = ("linkshare m1 cannot be smaller than m2"); + } - if (get_interface_bandwidth($this) < (0.8 * (floatval($bw_1) + floatval($bw_2)))) + if (get_interface_bandwidth($this) < (0.8 * (floatval($bw_1) + floatval($bw_2)))) { $input_errors[] = ("linkshare specification exceeds 80% of allowable allocation."); + } } */ - if ($data['realtime1'] <> "" && !is_valid_shaperbw($data['realtime1'])) + if ($data['realtime1'] <> "" && !is_valid_shaperbw($data['realtime1'])) { $input_errors[] = gettext("realtime m1 value needs to be Kb, Mb, Gb, or %"); - if ($data['realtime2'] <> "" && !is_numeric($data['realtime2'])) + } + if ($data['realtime2'] <> "" && !is_numeric($data['realtime2'])) { $input_errors[] = gettext("realtime d value needs to be numeric"); - if ($data['realtime3'] <> "" && !is_valid_shaperbw($data['realtime3'])) + } + if ($data['realtime3'] <> "" && !is_valid_shaperbw($data['realtime3'])) { $input_errors[] = gettext("realtime m2 value needs to be Kb, Mb, Gb, or %"); + } /* if (isset($data['realtime']) && $data['realtime3'] <> "" && $data['realtime1'] <> "" && 0) { $bw_1 = get_hfsc_bandwidth($this, $data['realtime1']); $bw_2 = get_hfsc_bandwidth($this, $data['realtime3']); - if (floatval($bw_1) < floatval($bw_2)) + if (floatval($bw_1) < floatval($bw_2)) { $input_errors[] = ("realtime m1 cannot be smaller than m2"); + } - if (get_interface_bandwidth($this) < (0.8 * (floatval($bw_1) + floatval($bw_2)))) + if (get_interface_bandwidth($this) < (0.8 * (floatval($bw_1) + floatval($bw_2)))) { $input_errors[] = ("realtime specification exceeds 80% of allowable allocation."); + } } */ } @@ -1712,8 +1877,9 @@ class hfsc_queue extends priq_queue { $this->SetL_m2($cflink['linkshare3']); $this->SetLinkshare(); } - } else + } else { $this->DisableLinkshare(); + } if (!empty($cflink['realtime'])) { if (!empty($cflink['realtime1'])) { $this->SetR_m1($cflink['realtime1']); @@ -1728,8 +1894,9 @@ class hfsc_queue extends priq_queue { $this->SetR_m2($cflink['realtime3']); $this->SetRealtime(); } - } else + } else { $this->DisableRealtime(); + } if (!empty($cflink['upperlimit'])) { if (!empty($cflink['upperlimit1'])) { $this->SetU_m1($cflink['upperlimit1']); @@ -1744,8 +1911,9 @@ class hfsc_queue extends priq_queue { $this->SetU_m2($cflink['upperlimit3']); $this->SetUpperlimit(); } - } else + } else { $this->DisableUpperlimit(); + } parent::ReadConfig($cflink); } @@ -1753,8 +1921,9 @@ class hfsc_queue extends priq_queue { $tree = "
  • GetInterface() ."&queue=" . $this->GetQname()."&action=show"; $tree .= "\" "; $tmpvalue = $this->GetDefault(); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $tree .= " class=\"navlnk\""; + } $tree .= " >" . $this->GetQname() . ""; if (is_array($this->subqueues)) { $tree .= "
      "; @@ -1771,14 +1940,17 @@ class hfsc_queue extends priq_queue { function build_rules(&$default = false) { $pfq_rule = " queue ". $this->qname; - if ($this->GetInterface()) + if ($this->GetInterface()) { $pfq_rule .= " on ".get_real_interface($this->GetInterface()); - if ($this->GetBandwidth() && $this->GetBwscale()) + } + if ($this->GetBandwidth() && $this->GetBwscale()) { $pfq_rule .= " bandwidth ".trim($this->GetBandwidth()).$this->GetBwscale(); + } $tmpvalue = $this->GetQlimit(); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $pfq_rule .= " qlimit " . $this->GetQlimit(); + } if ($this->GetDefault() || $this->GetRed() || $this->GetRio() || $this->GetEcn() || $this->GetCodel() || $this->GetRealtime() <> "" || $this->GetLinkshare() <> "" || $this->GetUpperlimit() <> "") { $pfq_rule .= " hfsc ( "; $tmpvalue = $this->GetRed(); @@ -1789,59 +1961,69 @@ class hfsc_queue extends priq_queue { $tmpvalue = $this->GetRio(); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " rio "; } $tmpvalue = $this->GetEcn(); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " ecn "; } $tmpvalue = $this->GetCodel(); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " codel "; } $tmpvalue = $this->GetDefault(); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " default "; $default = true; } if ($this->GetRealtime() <> "") { - if ($comma) + if ($comma) { $pfq_rule .= " , "; - if ($this->GetR_m1() <> "" && $this->GetR_d() <> "" && $this->GetR_m2() <> "") + } + if ($this->GetR_m1() <> "" && $this->GetR_d() <> "" && $this->GetR_m2() <> "") { $pfq_rule .= " realtime (".$this->GetR_m1() . ", " . $this->GetR_d().", ". $this->GetR_m2() .") "; - else if ($this->GetR_m2() <> "") + } else if ($this->GetR_m2() <> "") { $pfq_rule .= " realtime " . $this->GetR_m2(); + } $comma = 1; } if ($this->GetLinkshare() <> "") { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; - if ($this->GetL_m1() <> "" && $this->GetL_d() <> "" && $this->GetL_m2() <> "") + } + if ($this->GetL_m1() <> "" && $this->GetL_d() <> "" && $this->GetL_m2() <> "") { $pfq_rule .= " linkshare (".$this->GetL_m1(). ", ". $this->GetL_d(). ", ". $this->GetL_m2(). ") "; - else if ($this->GetL_m2() <> "") + } else if ($this->GetL_m2() <> "") { $pfq_rule .= " linkshare " . $this->GetL_m2() . " "; + } $comma = 1; } if ($this->GetUpperlimit() <> "") { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; - if ($this->GetU_m1() <> "" && $this->GetU_d() <> "" && $this->GetU_m2() <> "") + } + if ($this->GetU_m1() <> "" && $this->GetU_d() <> "" && $this->GetU_m2() <> "") { $pfq_rule .= " upperlimit (".$this->GetU_m1().", ". $this->GetU_d().", ". $this->GetU_m2(). ") "; - else if ($this->GetU_m2() <> "") + } else if ($this->GetU_m2() <> "") { $pfq_rule .= " upperlimit " . $this->GetU_m2() . " "; + } } $pfq_rule .= " ) "; } @@ -1852,12 +2034,14 @@ class hfsc_queue extends priq_queue { if ($i > 1) { $i--; $pfq_rule .= " {$qkey}, "; - } else + } else { $pfq_rule .= " {$qkey} "; + } } $pfq_rule .= " } \n"; - foreach ($this->subqueues as $q) + foreach ($this->subqueues as $q) { $pfq_rule .= $q->build_rules($default); + } } $pfq_rule .= " \n"; @@ -1918,24 +2102,29 @@ class hfsc_queue extends priq_queue { $form .= "\" />"; $form .= "
      "; $form .= "" . gettext("Choose the amount of bandwidth for this queue"); @@ -1946,67 +2135,79 @@ class hfsc_queue extends priq_queue { $form .= ""; $form .= ""; $form .= ""; $form .= ""; $form .= ""; $form .= "
       
      m1
      d
      m2
      GetUpperlimit()<> "") + if ($this->GetUpperlimit()<> "") { $form .= " checked=\"checked\" "; + } $form .= "onchange=\"enable_upperlimit()\" /> " . gettext("Upperlimit:") . "GetU_m1()); $form .= "\" id=\"upperlimit1\" name=\"upperlimit1\" "; - if ($this->GetUpperlimit() == "") + if ($this->GetUpperlimit() == "") { $form .= " disabled=\"disabled\""; + } $form .= " />GetU_d()); $form .= "\" id=\"upperlimi2\" name=\"upperlimit2\" "; - if ($this->GetUpperlimit() == "") + if ($this->GetUpperlimit() == "") { $form .= " disabled=\"disabled\""; + } $form .= " />GetU_m2()); $form .= "\" id=\"upperlimit3\" name=\"upperlimit3\" "; - if ($this->GetUpperlimit() == "") + if ($this->GetUpperlimit() == "") { $form .= " disabled=\"disabled\""; + } $form .= " />" . gettext("The maximum allowed bandwidth for the queue.") . "
      GetRealtime() <> "") + if ($this->GetRealtime() <> "") { $form .= " checked=\"checked\" "; + } $form .= "onchange=\"enable_realtime()\" /> " . gettext("Real time:") . "GetR_m1()); $form .= "\" id=\"realtime1\" name=\"realtime1\" "; - if ($this->GetRealtime() == "") + if ($this->GetRealtime() == "") { $form .= " disabled=\"disabled\""; + } $form .= " />GetR_d()); $form .= "\" id=\"realtime2\" name=\"realtime2\" "; - if ($this->GetRealtime() == "") + if ($this->GetRealtime() == "") { $form .= " disabled=\"disabled\""; + } $form .= " />GetR_m2()); $form .= "\" id=\"realtime3\" name=\"realtime3\" "; - if ($this->GetRealtime() == "") + if ($this->GetRealtime() == "") { $form .= " disabled=\"disabled\""; + } $form .= " />" . gettext("The minimum required bandwidth for the queue.") . "
      GetLinkshare() <> "") + if ($this->GetLinkshare() <> "") { $form .= " checked=\"checked\" "; + } $form .= "onchange=\"enable_linkshare()\" /> " . gettext("Link share:") . "GetL_m1()); $form .= "\" id=\"linkshare1\" name=\"linkshare1\" "; - if ($this->GetLinkshare() == "") + if ($this->GetLinkshare() == "") { $form .= " disabled=\"disabled\""; + } $form .= " />GetL_d()); $form .= "\" id=\"linkshare2\" name=\"linkshare2\" "; - if ($this->GetLinkshare() == "") + if ($this->GetLinkshare() == "") { $form .= " disabled=\"disabled\""; + } $form .= " />GetL_m2()); $form .= "\" id=\"linkshare3\" name=\"linkshare3\" "; - if ($this->GetLinkshare() == "") + if ($this->GetLinkshare() == "") { $form .= " disabled=\"disabled\""; + } $form .= " />" . gettext("The bandwidth share of a backlogged queue - this overrides priority.") . "

      "; $form .= gettext("The format for service curve specifications is (m1, d, m2). m2 controls " - . "the bandwidth assigned to the queue. m1 and d are optional and can be " - . "used to control the initial bandwidth assignment. For the first d milliseconds the queue gets the bandwidth given as m1, afterwards the value " - . "given in m2."); + . "the bandwidth assigned to the queue. m1 and d are optional and can be " + . "used to control the initial bandwidth assignment. For the first d milliseconds the queue gets the bandwidth given as m1, afterwards the value " + . "given in m2."); $form .= ""; $form .= ""; @@ -2019,39 +2220,49 @@ class hfsc_queue extends priq_queue { function wconfig() { $cflink =& get_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) + if (!is_array($cflink)) { $cflink = array(); + } $cflink['name'] = $this->GetQname(); $cflink['interface'] = $this->GetInterface(); $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) + if (empty($cflink['qlimit'])) { unset($cflink['qlimit']); + } $cflink['priority'] = $this->GetQpriority(); - if (empty($cflink['priority'])) + if (empty($cflink['priority'])) { unset($cflink['priority']); + } $cflink['description'] = $this->GetDescription(); - if (empty($cflink['description'])) + if (empty($cflink['description'])) { unset($cflink['description']); + } $cflink['bandwidth'] = $this->GetBandwidth(); $cflink['bandwidthtype'] = $this->GetBwscale(); $cflink['enabled'] = $this->GetEnabled(); - if (empty($cflink['enabled'])) + if (empty($cflink['enabled'])) { unset($cflink['enabled']); + } $cflink['default'] = $this->GetDefault(); - if (empty($cflink['default'])) + if (empty($cflink['default'])) { unset($cflink['default']); + } $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) + if (empty($cflink['red'])) { unset($cflink['red']); + } $cflink['rio'] = $this->GetRio(); - if (empty($cflink['rio'])) + if (empty($cflink['rio'])) { unset($cflink['rio']); + } $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) + if (empty($cflink['ecn'])) { unset($cflink['ecn']); + } $cflink['codel'] = trim($this->GetCodel()); - if (empty($cflink['codel'])) + if (empty($cflink['codel'])) { unset($cflink['codel']); + } if ($this->GetLinkshare() <> "") { if ($this->GetL_m1() <> "") { $cflink['linkshare1'] = $this->GetL_m1(); @@ -2139,8 +2350,9 @@ class cbq_queue extends priq_queue { function &add_queue($interface, &$qname, &$path, &$input_errors) { - if (!is_array($this->subqueues)) + if (!is_array($this->subqueues)) { $this->subqueues = array(); + } $q =& new cbq_queue(); $q->SetInterface($this->GetInterface()); $q->SetParent($this); @@ -2151,12 +2363,12 @@ class cbq_queue extends priq_queue { return $q; } switch ($q->GetBwscale()) { - case "%": - $myBw = $this->GetAvailableBandwidth() * $qname['bandwidth'] / 100; - break; - default: - $myBw = $qname['bandwidth'] * get_bandwidthtype_scale($q->GetBwscale()); - break; + case "%": + $myBw = $this->GetAvailableBandwidth() * $qname['bandwidth'] / 100; + break; + default: + $myBw = $qname['bandwidth'] * get_bandwidthtype_scale($q->GetBwscale()); + break; } $q->SetAvailableBandwidth($myBw); $this->SetAvailableBandwidth($this->GetAvailableBandwidth() - $myBw); @@ -2180,35 +2392,44 @@ class cbq_queue extends priq_queue { $cflink['interface'] = $interface; $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($clink['qlimit'])) + if (empty($clink['qlimit'])) { unset($cflink['qlimit']); + } $cflink['priority'] = trim($this->GetQpriority()); - if (empty($cflink['priority'])) + if (empty($cflink['priority'])) { unset($cflink['priority']); + } $cflink['name'] = $this->GetQname(); $cflink['description'] = trim($this->GetDescription()); - if (empty($cflink['description'])) + if (empty($cflink['description'])) { unset($cflink['description']); + } $cflink['bandwidth'] = $this->GetBandwidth(); $cflink['bandwidthtype'] = $this->GetBwscale(); $cflink['enabled'] = trim($this->GetEnabled()); - if (empty($cflink['enabled'])) + if (empty($cflink['enabled'])) { unset($cflink['enabled']); + } $cflink['default'] = trim($this->GetDefault()); - if (empty($cflink['default'])) + if (empty($cflink['default'])) { unset($cflink['default']); + } $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) + if (empty($cflink['red'])) { unset($cflink['red']); + } $cflink['rio'] = trim($this->GetRio()); - if (empty($cflink['rio'])) + if (empty($cflink['rio'])) { unset($cflink['rio']); + } $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) + if (empty($cflink['ecn'])) { unset($cflink['ecn']); + } $cflink['borrow'] = trim($this->GetBorrow()); - if (empty($cflink['borrow'])) + if (empty($cflink['borrow'])) { unset($cflink['borrow']); + } if (is_array($this->queues)) { $cflinkp['queue'] = array(); foreach ($this->subqueues as $q) { @@ -2222,22 +2443,26 @@ class cbq_queue extends priq_queue { * Should search even its children */ function &find_queue($interface, $qname) { - if ($qname == $this->GetQname()) + if ($qname == $this->GetQname()) { return $this; + } foreach ($this->subqueues as $q) { $result =& $q->find_queue("", $qname); - if ($result) + if ($result) { return $result; + } } } function &find_parentqueue($interface, $qname) { - if ($this->subqueues[$qname]) + if ($this->subqueues[$qname]) { return $this; + } foreach ($this->subqueues as $q) { $result = $q->find_parentqueue("", $qname); - if ($result) + if ($result) { return $result; + } } } @@ -2245,8 +2470,8 @@ class cbq_queue extends priq_queue { unref_on_altq_queue_list($this->GetQname()); cleanup_queue_from_rules($this->GetQname()); foreach ($this->subqueues as $q) { - $this->SetAvailableBandwidth($this->GetAvailableBandwidth() + $q->GetAvailableBandwidth()); - $q->delete_queue(); + $this->SetAvailableBandwidth($this->GetAvailableBandwidth() + $q->GetAvailableBandwidth()); + $q->delete_queue(); } unset_object_by_reference($this->GetLink()); } @@ -2254,8 +2479,9 @@ class cbq_queue extends priq_queue { function validate_input($data, &$input_errors) { parent::validate_input($data, $input_errors); - if ($data['priority'] > 7) + if ($data['priority'] > 7) { $input_errors[] = gettext("Priority must be an integer between 1 and 7."); + } $reqdfields[] = "bandwidth"; $reqdfieldsn[] = gettext("Bandwidth"); $reqdfields[] = "bandwidthtype"; @@ -2263,16 +2489,19 @@ class cbq_queue extends priq_queue { shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - if ($data['bandwidth'] && !is_numeric($data['bandwidth'])) + if ($data['bandwidth'] && !is_numeric($data['bandwidth'])) { $input_errors[] = gettext("Bandwidth must be an integer."); + } - if ($data['bandwidth'] < 0) + if ($data['bandwidth'] < 0) { $input_errors[] = gettext("Bandwidth cannot be negative."); + } if ($data['bandwidthtype'] == "%") { - if ($data['bandwidth'] > 100 || $data['bandwidth'] < 0) + if ($data['bandwidth'] > 100 || $data['bandwidth'] < 0) { $input_errors[] = gettext("Bandwidth in percentage should be between 1 and 100 bounds."); + } } /* @@ -2285,17 +2514,19 @@ class cbq_queue extends priq_queue { $mybw = floatval($data['bandwidth']) * get_bandwidthtype_scale($data['bandwidthtype']); break; } - if ($parent->GetAvailableBandwidth() < floatval($myBw)) + if ($parent->GetAvailableBandwidth() < floatval($myBw)) { $input_errors[] = "The sum of the children bandwidth exceeds that of the parent."; + } */ } function ReadConfig(&$q) { parent::ReadConfig($q); - if (!empty($q['borrow'])) + if (!empty($q['borrow'])) { $this->SetBorrow("on"); - else + } else { $this->SetBorrow(""); + } } function build_javascript() { @@ -2306,8 +2537,9 @@ class cbq_queue extends priq_queue { $tree = "
    • GetInterface()."&queue=" . $this->GetQname()."&action=show"; $tree .= "\" "; $tmpvalue = trim($this->GetDefault()); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $tree .= " class=\"navlnk\""; + } $tree .= " >" . $this->GetQname() . ""; if (is_array($this->subqueues)) { $tree .= "
        "; @@ -2323,16 +2555,20 @@ class cbq_queue extends priq_queue { /* Even this should take children into consideration */ function build_rules(&$default = false) { $pfq_rule = "queue ". $this->qname; - if ($this->GetInterface()) + if ($this->GetInterface()) { $pfq_rule .= " on ".get_real_interface($this->GetInterface()); - if ($this->GetBandwidth() && $this->GetBwscale()) + } + if ($this->GetBandwidth() && $this->GetBwscale()) { $pfq_rule .= " bandwidth ".trim($this->GetBandwidth()).$this->GetBwscale(); + } $tmpvalue = $this->GetQpriority(); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $pfq_rule .= " priority " . $this->GetQpriority(); + } $tmpvalue = trim($this->GetQlimit()); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $pfq_rule .= " qlimit " . $this->GetQlimit(); + } if ($this->GetDefault() || $this->GetRed() || $this->GetRio() || $this->GetEcn() || $this->GetBorrow() || $this->GetCodel()) { $pfq_rule .= " cbq ( "; $tmpvalue = trim($this->GetRed()); @@ -2347,30 +2583,34 @@ class cbq_queue extends priq_queue { } $tmpvalue = trim($this->GetRio()); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " rio "; } $tmpvalue = trim($this->GetEcn()); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " ecn "; } $tmpvalue = trim($this->GetDefault()); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " default "; $default = true; } $tmpvalue = trim($this->GetBorrow()); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= ", "; + } $pfq_rule .= " borrow "; } $pfq_rule .= " ) "; @@ -2382,12 +2622,14 @@ class cbq_queue extends priq_queue { if ($i > 1) { $i--; $pfq_rule .= " {$qkey}, "; - } else + } else { $pfq_rule .= " {$qkey} "; + } } $pfq_rule .= " } \n"; - foreach ($this->subqueues as $q) + foreach ($this->subqueues as $q) { $pfq_rule .= $q->build_rules($default); + } } $pfq_rule .= " \n"; @@ -2399,37 +2641,44 @@ class cbq_queue extends priq_queue { $form .= ""; $form .= "" . gettext("Bandwidth") . ""; $form .= " GetBandwidth() > 0) + if ($this->GetBandwidth() > 0) { $form .= htmlspecialchars($this->GetBandwidth()); + } $form .= "\" />"; $form .= "
        "; $form .= "" . gettext("Choose the amount of bandwidth for this queue"); $form .= ""; $form .= "" . gettext("Scheduler specific options") . ""; $form .= "GetBorrow() == "on") + if ($this->GetBorrow() == "on") { $form .= " checked=\"checked\" "; + } $form .= " /> " . gettext("Borrow from other queues when available") . "
        "; return $form; @@ -2441,42 +2690,53 @@ class cbq_queue extends priq_queue { function wconfig() { $cflink =& get_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) + if (!is_array($cflink)) { $cflink = array(); + } $cflink['interface'] = $this->GetInterface(); $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) + if (empty($cflink['qlimit'])) { unset($cflink['qlimit']); + } $cflink['priority'] = $this->GetQpriority(); - if (empty($cflink['priority'])) + if (empty($cflink['priority'])) { unset($cflink['priority']); + } $cflink['name'] = $this->GetQname(); $cflink['description'] = $this->GetDescription(); - if (empty($cflink['description'])) + if (empty($cflink['description'])) { unset($cflink['description']); + } $cflink['bandwidth'] = $this->GetBandwidth(); $cflink['bandwidthtype'] = $this->GetBwscale(); $cflink['enabled'] = trim($this->GetEnabled()); - if (empty($cflink['enabled'])) + if (empty($cflink['enabled'])) { unset($cflink['enabled']); + } $cflink['default'] = trim($this->GetDefault()); - if (empty($cflink['default'])) + if (empty($cflink['default'])) { unset($cflink['default']); + } $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) + if (empty($cflink['red'])) { unset($cflink['red']); + } $cflink['rio'] = trim($this->GetRio()); - if (empty($cflink['rio'])) + if (empty($cflink['rio'])) { unset($cflink['rio']); + } $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) + if (empty($cflink['ecn'])) { unset($cflink['ecn']); + } $cflink['codel'] = trim($this->GetCodel()); - if (empty($cflink['codel'])) + if (empty($cflink['codel'])) { unset($cflink['codel']); + } $cflink['borrow'] = trim($this->GetBorrow()); - if (empty($cflink['borrow'])) + if (empty($cflink['borrow'])) { unset($cflink['borrow']); + } } } @@ -2522,8 +2782,9 @@ class fairq_queue extends priq_queue { * Should search even its children */ function &find_queue($interface, $qname) { - if ($qname == $this->GetQname()) + if ($qname == $this->GetQname()) { return $this; + } } function find_parentqueue($interface, $qname) { return; } @@ -2537,8 +2798,9 @@ class fairq_queue extends priq_queue { function validate_input($data, &$input_errors) { parent::validate_input($data, $input_errors); - if ($data['priority'] > 255) + if ($data['priority'] > 255) { $input_errors[] = gettext("Priority must be an integer between 1 and 255."); + } $reqdfields[] = "bandwidth"; $reqdfieldsn[] = gettext("Bandwidth"); $reqdfields[] = "bandwidthtype"; @@ -2546,17 +2808,20 @@ class fairq_queue extends priq_queue { shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - if ($data['bandwidth'] && !is_numeric($data['bandwidth'])) + if ($data['bandwidth'] && !is_numeric($data['bandwidth'])) { $input_errors[] = gettext("Bandwidth must be an integer."); + } - if ($data['bandwidth'] < 0) + if ($data['bandwidth'] < 0) { $input_errors[] = gettext("Bandwidth cannot be negative."); + } if ($data['bandwidthtype'] == "%") { - if ($data['bandwidth'] > 100 || $data['bandwidth'] < 0) + if ($data['bandwidth'] > 100 || $data['bandwidth'] < 0) { $input_errors[] = gettext("Bandwidth in percentage should be between 1 and 100 bounds."); + } } /* @@ -2568,21 +2833,24 @@ class fairq_queue extends priq_queue { $mybw = floatval($data['bandwidth']) * get_bandwidthtype_scale($data['bandwidthtype']); break; } - if ($parent->GetAvailableBandwidth() < floatval($myBw)) + if ($parent->GetAvailableBandwidth() < floatval($myBw)) { $input_errors[] = "The sum of children bandwidth exceeds that of the parent."; + } */ } function ReadConfig(&$q) { parent::ReadConfig($q); - if (!empty($q['buckets'])) + if (!empty($q['buckets'])) { $this->SetBuckets($q['buckets']); - else + } else { $this->SetBuckets(""); - if (!empty($q['hogs']) && is_valid_shaperbw($q['hogs'])) + } + if (!empty($q['hogs']) && is_valid_shaperbw($q['hogs'])) { $this->SetHogs($q['hogs']); - else + } else { $this->SetHogs(""); + } } function build_javascript() { @@ -2594,8 +2862,9 @@ class fairq_queue extends priq_queue { $this->GetInterface()."&queue=" . $this->GetQname()."&action=show"; $tree .= "\" "; $tmpvalue = trim($this->GetDefault()); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $tree .= " class=\"navlnk\""; + } $tree .= " >" . $this->GetQname() . ""; $tree .= ""; return $tree; @@ -2604,18 +2873,22 @@ class fairq_queue extends priq_queue { /* Even this should take children into consideration */ function build_rules(&$default = false) { $pfq_rule = "queue ". $this->qname; - if ($this->GetInterface()) + if ($this->GetInterface()) { $pfq_rule .= " on ".get_real_interface($this->GetInterface()); - if ($this->GetBandwidth() && $this->GetBwscale()) + } + if ($this->GetBandwidth() && $this->GetBwscale()) { $pfq_rule .= " bandwidth ".trim($this->GetBandwidth()).$this->GetBwscale(); + } $tmpvalue = trim($this->GetQpriority()); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $pfq_rule .= " priority " . $this->GetQpriority(); + } $tmpvalue = trim($this->GetQlimit()); - if (!empty($tmpvalue)) + if (!empty($tmpvalue)) { $pfq_rule .= " qlimit " . $this->GetQlimit(); - if ($this->GetDefault() || $this->GetRed() || $this->GetRio() - || $this->GetEcn() || $this->GetBuckets() || $this->GetHogs() || $this->GetCodel()) { + } + if ($this->GetDefault() || $this->GetRed() || $this->GetRio() || + $this->GetEcn() || $this->GetBuckets() || $this->GetHogs() || $this->GetCodel()) { $pfq_rule .= " fairq ( "; $tmpvalue = trim($this->GetRed()); if (!empty($tmpvalue)) { @@ -2629,39 +2902,44 @@ class fairq_queue extends priq_queue { } $tmpvalue = trim($this->GetRio()); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " rio "; } $tmpvalue = trim($this->GetEcn()); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " ecn "; } $tmpvalue = trim($this->GetDefault()); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= " ,"; + } $comma = 1; $pfq_rule .= " default "; $default = true; } $tmpvalue = trim($this->GetBuckets()); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= ", "; + } $pfq_rule .= " buckets " . $this->GetBuckets() . " "; } $tmpvalue = trim($this->GetHogs()); if (!empty($tmpvalue)) { - if ($comma) + if ($comma) { $pfq_rule .= ", "; + } $pfq_rule .= " hogs " . $this->GetHogs() . " "; } - $pfq_rule .= " ) "; + $pfq_rule .= " ) "; } $pfq_rule .= " \n"; @@ -2673,29 +2951,35 @@ class fairq_queue extends priq_queue { $form .= ""; $form .= "" . gettext("Bandwidth") . ""; $form .= " GetBandwidth() > 0) + if ($this->GetBandwidth() > 0) { $form .= htmlspecialchars($this->GetBandwidth()); + } $form .= "\" />"; $form .= "
        "; $form .= "" . gettext("Choose the amount of bandwidth for this queue"); @@ -2704,13 +2988,15 @@ class fairq_queue extends priq_queue { $form .= ""; $form .= ""; $form .= "
        "; $form .= "GetBuckets()); - if(!empty($tmpvalue)) + if (!empty($tmpvalue)) { $form .= $this->GetBuckets(); + } $form .= "\" /> " . gettext("Number of buckets available.") . "
        GetHogs()); - if(!empty($tmpvalue)) + if (!empty($tmpvalue)) { $form .= $this->GetHogs(); + } $form .= "\" /> " . gettext("Bandwidth limit for hosts to not saturate link.") . "
        "; return $form; @@ -2722,45 +3008,57 @@ class fairq_queue extends priq_queue { function wconfig() { $cflink =& get_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) + if (!is_array($cflink)) { $cflink = array(); + } $cflink['interface'] = $this->GetInterface(); $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) + if (empty($cflink['qlimit'])) { unset($cflink['qlimit']); + } $cflink['priority'] = trim($this->GetQpriority()); - if (empty($cflink['priority'])) + if (empty($cflink['priority'])) { unset($cflink['priority']); + } $cflink['name'] = $this->GetQname(); $cflink['description'] = trim($this->GetDescription()); - if (empty($cflink['description'])) + if (empty($cflink['description'])) { unset($cflink['description']); + } $cflink['bandwidth'] = $this->GetBandwidth(); $cflink['bandwidthtype'] = $this->GetBwscale(); $cflink['enabled'] = $this->GetEnabled(); - if (empty($cflink['enabled'])) + if (empty($cflink['enabled'])) { unset($cflink['enabled']); + } $cflink['default'] = trim($this->GetDefault()); - if (empty($cflink['default'])) + if (empty($cflink['default'])) { unset($cflink['default']); + } $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) + if (empty($cflink['red'])) { unset($cflink['red']); + } $cflink['rio'] = trim($this->GetRio()); - if (empty($cflink['rio'])) + if (empty($cflink['rio'])) { unset($cflink['rio']); + } $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) + if (empty($cflink['ecn'])) { unset($cflink['ecn']); + } $cflink['codel'] = trim($this->GetCodel()); - if (empty($cflink['codel'])) + if (empty($cflink['codel'])) { unset($cflink['codel']); + } $cflink['buckets'] = trim($this->GetBuckets()); - if (empty($cflink['buckets'])) + if (empty($cflink['buckets'])) { unset($cflink['buckets']); + } $cflink['hogs'] = trim($this->GetHogs()); - if (empty($cflink['hogs'])) + if (empty($cflink['hogs'])) { unset($cflink['hogs']); + } } } @@ -2798,8 +3096,9 @@ class dummynet_class { return $this->link; } function GetMask() { - if (!isset($this->mask["type"])) + if (!isset($this->mask["type"])) { $this->mask["type"] = "none"; + } return $this->mask; } function SetMask($mask) { @@ -2898,53 +3197,67 @@ class dummynet_class { shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); if ($data['plr'] && (!is_numeric($data['plr']) || - ($data['plr'] < 0) || ($data['plr'] > 1))) + ($data['plr'] < 0) || ($data['plr'] > 1))) { $input_errors[] = gettext("Plr must be a value between 0 and 1."); + } if ($data['buckets'] && (!is_numeric($data['buckets']) || - ($data['buckets'] < 16) || ($data['buckets'] > 65535))) + ($data['buckets'] < 16) || ($data['buckets'] > 65535))) { $input_errors[] = gettext("Buckets must be an integer between 16 and 65535."); - if ($data['qlimit'] && (!is_numeric($data['qlimit']))) + } + if ($data['qlimit'] && (!is_numeric($data['qlimit']))) { $input_errors[] = gettext("Queue limit must be an integer"); - if (!empty($data['newname']) && !preg_match("/^[a-zA-Z0-9_-]+$/", $data['newname'])) + } + if (!empty($data['newname']) && !preg_match("/^[a-zA-Z0-9_-]+$/", $data['newname'])) { $input_errors[] = gettext("Queue names must be alphanumeric and _ or - only."); - if (!empty($data['name']) && !preg_match("/^[a-zA-Z0-9_-]+$/", $data['name'])) + } + if (!empty($data['name']) && !preg_match("/^[a-zA-Z0-9_-]+$/", $data['name'])) { $input_errors[] = gettext("Queue names must be alphanumeric and _ or - only."); - if (isset($data['maskbits']) && ($data['maskbits'] <> "")) - if ((!is_numeric($data['maskbits'])) || ($data['maskbits'] <= 0) || ($data['maskbits'] > 32)) + } + if (isset($data['maskbits']) && ($data['maskbits'] <> "")) { + if ((!is_numeric($data['maskbits'])) || ($data['maskbits'] <= 0) || ($data['maskbits'] > 32)) { $input_errors[] = gettext("IPV4 bit mask must be blank or numeric value between 1 and 32."); - if (isset($data['maskbitsv6']) && ($data['maskbitsv6'] <> "")) - if ((!is_numeric($data['maskbitsv6'])) || ($data['maskbitsv6'] <= 0) || ($data['maskbitsv6'] > 128)) + } + } + if (isset($data['maskbitsv6']) && ($data['maskbitsv6'] <> "")) { + if ((!is_numeric($data['maskbitsv6'])) || ($data['maskbitsv6'] <= 0) || ($data['maskbitsv6'] > 128)) { $input_errors[] = gettext("IPV6 bit mask must be blank or numeric value between 1 and 128."); + } + } } function build_mask_rules(&$pfq_rule) { $mask = $this->GetMask(); if (!empty($mask['type'])) { - if ($mask['type'] <> 'none') + if ($mask['type'] <> 'none') { $pfq_rule .= " mask"; + } switch ($mask['type']) { - case 'srcaddress': - if (!empty($mask['bitsv6']) && ($mask['bitsv6'] <> "")) - $pfq_rule .= " src-ip6 /" . $mask['bitsv6']; - else - $pfq_rule .= " src-ip6 /128"; - if (!empty($mask['bits']) && ($mask['bits'] <> "")) - $pfq_rule .= sprintf(" src-ip 0x%x", gen_subnet_mask_long($mask['bits'])); - else - $pfq_rule .= " src-ip 0xffffffff"; - break; - case 'dstaddress': - if (!empty($mask['bitsv6']) && ($mask['bitsv6'] <> "")) - $pfq_rule .= " dst-ip6 /" . $mask['bitsv6']; - else - $pfq_rule .= " dst-ip6 /128"; - if (!empty($mask['bits']) && ($mask['bits'] <> "")) - $pfq_rule .= sprintf(" dst-ip 0x%x", gen_subnet_mask_long($mask['bits'])); - else - $pfq_rule .= " dst-ip 0xffffffff"; - break; - default: - break; + case 'srcaddress': + if (!empty($mask['bitsv6']) && ($mask['bitsv6'] <> "")) { + $pfq_rule .= " src-ip6 /" . $mask['bitsv6']; + } else { + $pfq_rule .= " src-ip6 /128"; + } + if (!empty($mask['bits']) && ($mask['bits'] <> "")) { + $pfq_rule .= sprintf(" src-ip 0x%x", gen_subnet_mask_long($mask['bits'])); + } else { + $pfq_rule .= " src-ip 0xffffffff"; + } + break; + case 'dstaddress': + if (!empty($mask['bitsv6']) && ($mask['bitsv6'] <> "")) { + $pfq_rule .= " dst-ip6 /" . $mask['bitsv6']; + } else { + $pfq_rule .= " dst-ip6 /128"; + } + if (!empty($mask['bits']) && ($mask['bits'] <> "")) { + $pfq_rule .= sprintf(" dst-ip 0x%x", gen_subnet_mask_long($mask['bits'])); + } else { + $pfq_rule .= " dst-ip 0xffffffff"; + } + break; + default: + break; } } } @@ -2970,8 +3283,9 @@ class dnpipe_class extends dummynet_class { } function delete_queue() { cleanup_dnqueue_from_rules($this->GetQname()); - foreach ($this->subqueues as $q) + foreach ($this->subqueues as $q) { $q->delete_queue(); + } unset_dn_object_by_reference($this->GetLink()); @pfSense_pipe_action("pipe delete " . $this->GetNumber()); } @@ -2981,17 +3295,18 @@ class dnpipe_class extends dummynet_class { function SetBandwidth($bandwidth) { $this->qbandwidth = $bandwidth; } - function GetBurst() { - return $this->qburst; - } - function SetBurst($burst) { - $this->qburst = $burst; - } + function GetBurst() { + return $this->qburst; + } + function SetBurst($burst) { + $this->qburst = $burst; + } function &add_queue($interface, &$queue, &$path, &$input_errors) { - if (!is_array($this->subqueues)) + if (!is_array($this->subqueues)) { $this->subqueues = array(); + } $q =& new dnqueue_class(); $q->SetLink($path); @@ -3016,8 +3331,9 @@ class dnpipe_class extends dummynet_class { $qlist[$this->GetQname()] = $this->GetNumber(); if (is_array($this->subqueues)) { - foreach ($this->subqueues as $queue) + foreach ($this->subqueues as $queue) { $queue->get_queue_list($qlist); + } } return $qlist; } @@ -3026,12 +3342,14 @@ class dnpipe_class extends dummynet_class { * Should search even its children */ function &find_queue($pipe, $qname) { - if ($qname == $this->GetQname()) + if ($qname == $this->GetQname()) { return $this; + } foreach ($this->subqueues as $q) { $result =& $q->find_queue("", $qname); - if ($result) + if ($result) { return $result; + } } } @@ -3048,28 +3366,34 @@ class dnpipe_class extends dummynet_class { /* XXX: Really no better way? */ for ($i = 0; $i < 2900; $i++) { if (!empty($data["bwsched{$i}"])) { - if ($data["bwsched{$i}"] != "none") + if ($data["bwsched{$i}"] != "none") { $schedule++; - else + } else { $schedulenone++; + } } if (!empty($data["bandwidth{$i}"])) { - if (!is_numeric($data["bandwidth{$i}"])) + if (!is_numeric($data["bandwidth{$i}"])) { $input_errors[] = sprintf(gettext("Bandwidth for schedule %s must be an integer."), $data["bwsched{$i}"]); - else if (($data["burst{$i}"] != "") && (!is_numeric($data["burst{$i}"]))) + } else if (($data["burst{$i}"] != "") && (!is_numeric($data["burst{$i}"]))) { $input_errors[] = sprintf(gettext("Burst for schedule %s must be an integer."), $data["bwsched{$i}"]); - else + } else { $entries++; + } } } - if ($schedule == 0 && $entries > 1) + if ($schedule == 0 && $entries > 1) { $input_errors[] = gettext("You need to specify a schedule for every additional entry"); - if ($schedulenone > 0 && $entries > 1) + } + if ($schedulenone > 0 && $entries > 1) { $input_errors[] = gettext("If more than one bandwidth configured all schedules need to be selected"); - if ($entries == 0) + } + if ($entries == 0) { $input_errors[] = gettext("At least one bw specification is necessary"); - if ($data['delay'] && (!is_numeric($data['delay']))) + } + if ($data['delay'] && (!is_numeric($data['delay']))) { $input_errors[] = gettext("Delay must be an integer."); + } } function ReadConfig(&$q) { @@ -3090,10 +3414,12 @@ class dnpipe_class extends dummynet_class { $bw = array(); $bw['bw'] = $q["bandwidth{$i}"]; $bw['burst'] = $q["burst{$i}"]; - if (isset($q["bwtype{$i}"]) && $q["bwtype{$i}"]) + if (isset($q["bwtype{$i}"]) && $q["bwtype{$i}"]) { $bw['bwscale'] = $q["bwtype{$i}"]; - if (isset($q["bwsched{$i}"]) && $q["bwsched{$i}"]) + } + if (isset($q["bwsched{$i}"]) && $q["bwsched{$i}"]) { $bw['bwsched'] = $q["bwsched{$i}"]; + } $bandwidth[] = $bw; } } @@ -3105,39 +3431,47 @@ class dnpipe_class extends dummynet_class { $this->SetBurst($q['burst']['item']); } - if (isset($q['qlimit']) && $q['qlimit'] <> "") + if (isset($q['qlimit']) && $q['qlimit'] <> "") { $this->SetQlimit($q['qlimit']); - else + } else { $this->SetQlimit(""); - if (isset($q['mask']) && $q['mask'] <> "") + } + if (isset($q['mask']) && $q['mask'] <> "") { $masktype = $q['mask']; - else + } else { $masktype = ""; - if (isset($q['maskbits']) && $q['maskbits'] <> "") + } + if (isset($q['maskbits']) && $q['maskbits'] <> "") { $maskbits = $q['maskbits']; - else + } else { $maskbits = ""; - if (isset($q['maskbitsv6']) && $q['maskbitsv6'] <> "") + } + if (isset($q['maskbitsv6']) && $q['maskbitsv6'] <> "") { $maskbitsv6 = $q['maskbitsv6']; - else + } else { $maskbitsv6 = ""; + } $this->SetMask(array("type" => $masktype, "bits" => $maskbits, "bitsv6" => $maskbitsv6)); - if (isset($q['buckets']) && $q['buckets'] <> "") + if (isset($q['buckets']) && $q['buckets'] <> "") { $this->SetBuckets($q['buckets']); - else + } else { $this->SetBuckets(""); - if (isset($q['plr']) && $q['plr'] <> "") + } + if (isset($q['plr']) && $q['plr'] <> "") { $this->SetPlr($q['plr']); - else + } else { $this->SetPlr(""); - if (isset($q['delay']) && $q['delay'] <> "") + } + if (isset($q['delay']) && $q['delay'] <> "") { $this->SetDelay($q['delay']); - else + } else { $this->SetDelay(0); - if (isset($q['description']) && $q['description'] <> "") + } + if (isset($q['description']) && $q['description'] <> "") { $this->SetDescription($q['description']); - else + } else { $this->SetDescription(""); + } $this->SetEnabled($q['enabled']); } @@ -3160,8 +3494,9 @@ class dnpipe_class extends dummynet_class { function build_rules() { global $config, $time_based_rules; - if ($this->GetEnabled() == "") + if ($this->GetEnabled() == "") { return; + } $pfq_rule = "\npipe ". $this->GetNumber() . " config "; $found = false; @@ -3175,8 +3510,9 @@ class dnpipe_class extends dummynet_class { if ($bw['bwsched'] == $schedule['name']) { if (filter_get_time_based_rule_status($schedule)) { $pfq_rule .= " bw ".trim($bw['bw']).$bw['bwscale']; - if (is_numeric($bw['burst']) && ($bw['burst'] > 0)) + if (is_numeric($bw['burst']) && ($bw['burst'] > 0)) { $pfq_rule .= " burst ".trim($bw['burst']); + } $found = true; break; } @@ -3189,32 +3525,40 @@ class dnpipe_class extends dummynet_class { } } else { $pfq_rule .= " bw ".trim($bw['bw']).$bw['bwscale']; - if (is_numeric($bw['burst']) && ($bw['burst'] > 0)) + if (is_numeric($bw['burst']) && ($bw['burst'] > 0)) { $pfq_rule .= " burst ".trim($bw['burst']); + } $found = true; break; } } - if ($found == false) + if ($found == false) { $pfq_rule .= " bw 0"; - } else + } + } else { $pfq_rule .= " bw 0"; + } - if ($this->GetQlimit()) + if ($this->GetQlimit()) { $pfq_rule .= " queue " . $this->GetQlimit(); - if ($this->GetPlr()) + } + if ($this->GetPlr()) { $pfq_rule .= " plr " . $this->GetPlr(); - if ($this->GetBuckets()) + } + if ($this->GetBuckets()) { $pfq_rule .= " buckets " . $this->GetBuckets(); - if ($this->GetDelay()) + } + if ($this->GetDelay()) { $pfq_rule .= " delay " . $this->GetDelay(); + } $this->build_mask_rules($pfq_rule); $pfq_rule .= "\n"; if (!empty($this->subqueues) && count($this->subqueues) > 0) { - foreach ($this->subqueues as $q) - $pfq_rule .= $q->build_rules(); + foreach ($this->subqueues as $q) { + $pfq_rule .= $q->build_rules(); + } } $pfq_rule .= " \n"; @@ -3234,13 +3578,15 @@ class dnpipe_class extends dummynet_class { $schedules = ""; if (is_array($config['schedules']) && is_array($config['schedules']['schedule'])) { foreach ($config['schedules']['schedule'] as $schedule) { - if ($schedule['name'] <> "") + if ($schedule['name'] <> "") { $schedules .= ""; + } } } $bwopt = ""; - foreach (array("Kb" => "Kbit/s", "Mb" => "Mbit/s", "Gb" => "Gbit/s", "b" => "Bit/s") as $bwidx => $bw) + foreach (array("Kb" => "Kbit/s", "Mb" => "Mbit/s", "Gb" => "Gbit/s", "b" => "Bit/s") as $bwidx => $bw) { $bwopt .= ""; + } $javasr .= << @@ -3274,12 +3620,13 @@ var addBwRowTo = (function() { function removeBwRow(el) { var cel; - while (el && el.nodeName.toLowerCase() != "tr") + while (el && el.nodeName.toLowerCase() != "tr") { el = el.parentNode; if (el && el.parentNode) { cel = el.getElementsByTagName("td").item(0); el.parentNode.removeChild(el); } + } } //]]> @@ -3297,8 +3644,9 @@ EOD; $schedules[] = "none";//leave none to leave rule enabled all the time if (is_array($config['schedules']) && is_array($config['schedules']['schedule'])) { foreach ($config['schedules']['schedule'] as $schedule) { - if ($schedule['name'] <> "") + if ($schedule['name'] <> "") { $schedules[] = $schedule['name']; + } } } @@ -3306,8 +3654,9 @@ EOD; $form .= gettext("Enable"); $form .= ""; $form .= " GetEnabled() == "on") + if ($this->GetEnabled() == "on") { $form .= " checked=\"checked\""; + } $form .= " /> " . gettext("Enable limiter and its children") . ""; $form .= ""; $form .= "
        " . gettext("Name") . ""; @@ -3342,8 +3691,9 @@ EOD; $form .= ""; @@ -3372,44 +3723,51 @@ EOD; $form .= ""; $form .= " 
        "; $form .= "" . gettext("If 'source' or 'destination' slots is chosen, \n" - . "a dynamic pipe with the bandwidth, delay, packet loss and queue size given above will \n" - . "be created for each source/destination IP address encountered, \n" - . "respectively. This makes it possible to easily specify bandwidth \n" - . "limits per host.") . "
        "; + . "a dynamic pipe with the bandwidth, delay, packet loss and queue size given above will \n" + . "be created for each source/destination IP address encountered, \n" + . "respectively. This makes it possible to easily specify bandwidth \n" + . "limits per host.") . "

        "; $form .= "255.255.255.255/  "none") - $form .= $mask['bits']; + if ($mask['type'] <> "none") { + $form .= $mask['bits']; + } $form .= "\""; - if ($mask['type'] == "none") + if ($mask['type'] == "none") { $form .= " disabled"; + } $form .= " />"; $form .= "  IPV4 mask bits (1-32)
        "; $form .= "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/  "none") - $form .= $mask['bitsv6']; + if ($mask['type'] <> "none") { + $form .= $mask['bitsv6']; + } $form .= "\""; - if ($mask['type'] == "none") + if ($mask['type'] == "none") { $form .= " disabled"; + } $form .= " />"; $form .= "  IPV6 mask bits (1-128)
        "; $form .= "" . gettext("If 'source' or 'destination' slots is chosen, \n" - . "leaving the mask bits blank will create one pipe per host. Otherwise specify \n" - . "the number of 'one' bits in the subnet mask used to group multiple hosts \n" - . "per pipe.") . ""; + . "leaving the mask bits blank will create one pipe per host. Otherwise specify \n" + . "the number of 'one' bits in the subnet mask used to group multiple hosts \n" + . "per pipe.") . ""; $form .= ""; $form .= "" . gettext("Description") . ""; $form .= ""; @@ -3432,7 +3790,7 @@ EOD; $form .= "GetDelay() . "\" />"; $form .= " ms
        " . gettext("Hint: in most cases, you " - . "should specify 0 here (or leave the field empty)") . "
        "; + . "should specify 0 here (or leave the field empty)") . "
        "; $form .= ""; $form .= ""; $form .= "" . gettext("Packet loss rate") . ""; @@ -3440,8 +3798,8 @@ EOD; $form .= "GetPlr() . "\" />"; $form .= " 
        " . gettext("Hint: in most cases, you " - . "should specify 0 here (or leave the field empty). " - . "A value of 0.001 means one packet in 1000 gets dropped") . ""; + . "should specify 0 here (or leave the field empty). " + . "A value of 0.001 means one packet in 1000 gets dropped") . ""; $form .= ""; $form .= ""; $form .= "" . gettext("Queue Size") . ""; @@ -3450,9 +3808,9 @@ EOD; $form .= $this->GetQlimit() . "\" />"; $form .= " slots
        "; $form .= "" . gettext("Hint: in most cases, you " - . "should leave the field empty. All packets in this pipe are placed into a fixed-size queue first, " - . "then they are delayed by value specified in the Delay field, and then they " - . "are delivered to their destination.") . ""; + . "should leave the field empty. All packets in this pipe are placed into a fixed-size queue first, " + . "then they are delayed by value specified in the Delay field, and then they " + . "are delivered to their destination.") . ""; $form .= ""; $form .= ""; $form .= "" . gettext("Bucket Size") . ""; @@ -3470,8 +3828,9 @@ EOD; function wconfig() { $cflink =& get_dn_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) + if (!is_array($cflink)) { $cflink = array(); + } $cflink['name'] = $this->GetQname(); $cflink['number'] = $this->GetNumber(); $cflink['qlimit'] = $this->GetQlimit(); @@ -3482,8 +3841,9 @@ EOD; if (is_array($bandwidth)) { $cflink['bandwidth'] = array(); $cflink['bandwidth']['item'] = array(); - foreach ($bandwidth as $bwidx => $bw) + foreach ($bandwidth as $bwidx => $bw) { $cflink['bandwidth']['item'][] = $bw; + } } $cflink['enabled'] = $this->GetEnabled(); @@ -3515,7 +3875,9 @@ class dnqueue_class extends dummynet_class { } /* Just a stub in case we ever try to call this from the frontend. */ - function &add_queue($interface, &$queue, &$path, &$input_errors) { return; } + function &add_queue($interface, &$queue, &$path, &$input_errors) { + return; + } function delete_queue() { cleanup_dnqueue_from_rules($this->GetQname()); @@ -3527,18 +3889,20 @@ class dnqueue_class extends dummynet_class { parent::validate_input($data, $input_errors); if ($data['weight'] && ((!is_numeric($data['weight'])) || - ($data['weight'] < 1 && $data['weight'] > 100))) + ($data['weight'] < 1 && $data['weight'] > 100))) { $input_errors[] = gettext("Weight must be an integer between 1 and 100."); + } } /* * Should search even its children */ function &find_queue($pipe, $qname) { - if ($qname == $this->GetQname()) + if ($qname == $this->GetQname()) { return $this; - else + } else { return NULL; + } } function &find_parentqueue($pipe, $qname) { @@ -3546,8 +3910,9 @@ class dnqueue_class extends dummynet_class { } function &get_queue_list(&$qlist) { - if ($this->GetEnabled() == "") + if ($this->GetEnabled() == "") { return; + } $qlist[$this->GetQname()] = "?" .$this->GetNumber(); } @@ -3560,39 +3925,47 @@ class dnqueue_class extends dummynet_class { $this->SetQname($q['name']); } $this->SetNumber($q['number']); - if (isset($q['qlimit']) && $q['qlimit'] <> "") + if (isset($q['qlimit']) && $q['qlimit'] <> "") { $this->SetQlimit($q['qlimit']); - else + } else { $this->SetQlimit(""); - if (isset($q['mask']) && $q['mask'] <> "") + } + if (isset($q['mask']) && $q['mask'] <> "") { $masktype = $q['mask']; - else + } else { $masktype = ""; - if (isset($q['maskbits']) && $q['maskbits'] <> "") + } + if (isset($q['maskbits']) && $q['maskbits'] <> "") { $maskbits = $q['maskbits']; - else + } else { $maskbits = ""; - if (isset($q['maskbitsv6']) && $q['maskbitsv6'] <> "") + } + if (isset($q['maskbitsv6']) && $q['maskbitsv6'] <> "") { $maskbitsv6 = $q['maskbitsv6']; - else + } else { $maskbitsv6 = ""; + } $this->SetMask(array("type" => $masktype, "bits" => $maskbits, "bitsv6" => $maskbitsv6)); - if (isset($q['buckets']) && $q['buckets'] <> "") + if (isset($q['buckets']) && $q['buckets'] <> "") { $this->SetBuckets($q['buckets']); - else + } else { $this->SetBuckets(""); - if (isset($q['plr']) && $q['plr'] <> "") + } + if (isset($q['plr']) && $q['plr'] <> "") { $this->SetPlr($q['plr']); - else + } else { $this->SetPlr(""); - if (isset($q['weight']) && $q['weight'] <> "") + } + if (isset($q['weight']) && $q['weight'] <> "") { $this->SetWeight($q['weight']); - else + } else { $this->SetWeight(""); - if (isset($q['description']) && $q['description'] <> "") + } + if (isset($q['description']) && $q['description'] <> "") { $this->SetDescription($q['description']); - else + } else { $this->SetDescription(""); + } $this->SetEnabled($q['enabled']); } @@ -3606,17 +3979,21 @@ class dnqueue_class extends dummynet_class { } function build_rules() { - if ($this->GetEnabled() == "") + if ($this->GetEnabled() == "") { return; + } $parent =& $this->GetParent(); $pfq_rule = "queue ". $this->GetNumber() . " config pipe " . $parent->GetNumber(); - if ($this->GetQlimit()) + if ($this->GetQlimit()) { $pfq_rule .= " queue " . $this->GetQlimit(); - if ($this->GetWeight()) + } + if ($this->GetWeight()) { $pfq_rule .= " weight " . $this->GetWeight(); - if ($this->GetBuckets()) + } + if ($this->GetBuckets()) { $pfq_rule .= " buckets " . $this->GetBuckets(); + } $this->build_mask_rules($pfq_rule); $pfq_rule .= "\n"; @@ -3633,8 +4010,9 @@ class dnqueue_class extends dummynet_class { $form .= gettext("Enable/Disable"); $form .= ""; $form .= " GetEnabled() == "on") + if ($this->GetEnabled() == "on") { $form .= " checked=\"checked\""; + } $form .= " /> " . gettext("Enable/Disable queue") . ""; $form .= ""; $form .= "
        " . gettext("Name") . ""; @@ -3653,16 +4031,19 @@ class dnqueue_class extends dummynet_class { $form .= ""; $form .= " slots
        "; @@ -3672,19 +4053,23 @@ class dnqueue_class extends dummynet_class { . "respectively. This makes it possible to easily specify bandwidth \n" . "limits per host.") . "
        "; $form .= "255.255.255.255/  "none") + if ($mask['type'] <> "none") { $form .= $mask['bits']; + } $form .= "\""; - if ($mask['type'] == "none") + if ($mask['type'] == "none") { $form .= " disabled"; + } $form .= " />"; $form .= "  IPV4 mask bits (1-32)
        "; $form .= "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/  "none") + if ($mask['type'] <> "none") { $form .= $mask['bitsv6']; + } $form .= "\""; - if ($mask['type'] == "none") + if ($mask['type'] == "none") { $form .= " disabled"; + } $form .= " />"; $form .= "  IPV6 mask bits (1-128)
        "; $form .= "" . gettext("If 'source' or 'destination' slots is chosen, \n" @@ -3757,8 +4142,9 @@ class dnqueue_class extends dummynet_class { function wconfig() { $cflink =& get_dn_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) + if (!is_array($cflink)) { $cflink = array(); + } $cflink['name'] = $this->GetQname(); $cflink['number'] = $this->GetNumber(); $cflink['qlimit'] = $this->GetQlimit(); @@ -3817,7 +4203,7 @@ class layer7 { $this->rsets = $rsets; } - //Add a tuple (rule,sctructure,element) to the $rsets + //Add a tuple (rule,structure,element) to the $rsets function add_rule($l7set) { $this->rsets[] = $l7set; @@ -3825,7 +4211,7 @@ class layer7 { // Build the layer7 rules function build_l7_rules() { - if($this->GetREnabled() == "") { + if ($this->GetREnabled() == "") { return; } //$l7rules = "#" . $this->rdescription . "\n"; @@ -3840,13 +4226,14 @@ class layer7 { $this->SetRName($qname); $this->SetREnabled($q['enabled']); $this->SetRPort($q['divert_port']); - if(isset($q['description']) && $q['description'] <> "") + if (isset($q['description']) && $q['description'] <> "") { $this->SetRDescription($q['description']); + } $rsets = $q['l7rules']; //Put individual rules in the array - if(is_array($rsets)) { + if (is_array($rsets)) { $this->rsets = array(); // XXX: ugly hack - foreach($rsets as $l7r) { + foreach ($rsets as $l7r) { $l7obj = new l7rule(); $l7obj->SetRProtocol($l7r['protocol']); $l7obj->SetRStructure($l7r['structure']); @@ -3906,13 +4293,13 @@ class layer7 { function wconfig() { global $config; - if(!is_array($config['l7shaper']['container'])) { + if (!is_array($config['l7shaper']['container'])) { $config['l7shaper']['container'] = array(); } // $cflink =& get_l7c_reference_to_me_in_config($this->GetRName()); - // Test if this rule does exists already - if(!$cflink) { + // Test if this rule exists already + if (!$cflink) { $cflink =& $config['l7shaper']['container'][]; } $cflink['name'] = $this->GetRName(); @@ -3920,15 +4307,15 @@ class layer7 { $cflink['description'] = $this->GetRDescription(); $cflink['divert_port'] = $this->GetRPort(); - //Destroy previously existent rules - if(is_array($cflink['rules'])) { + // Destroy previously existent rules + if (is_array($cflink['rules'])) { unset($cflink['l7rules']); } $cflink['l7rules'] = array(); $i = 0; - foreach($this->rsets as $rulel7) { + foreach ($this->rsets as $rulel7) { $cflink['l7rules'][$i]['protocol'] = $rulel7->GetRProtocol(); $cflink['l7rules'][$i]['structure'] = $rulel7->GetRStructure(); $cflink['l7rules'][$i]['behaviour'] = $rulel7->GetRBehaviour(); @@ -3940,18 +4327,21 @@ class layer7 { function get_unique_structures() { $unique_structures = array("action" => false, "dummynet" => false, "altq" => false); - foreach($this->rsets as $l7rule) { - if($l7rule->GetRStructure() == "action") + foreach ($this->rsets as $l7rule) { + if ($l7rule->GetRStructure() == "action") { $unique_structures['action'] = true; - else if($l7rule->GetRStructure() == "limiter") + } else if ($l7rule->GetRStructure() == "limiter") { $unique_structures['dummynet'] = true; - else + } else { $unique_structures['altq'] = true; + } } //Delete non used structures so we don't have to check this in filter.inc - foreach($unique_structures as $key => $value) - if(!$value) + foreach ($unique_structures as $key => $value) { + if (!$value) { unset($unique_structures[$key]); + } + } return $unique_structures; } @@ -3961,8 +4351,9 @@ class layer7 { shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - if (!preg_match("/^[a-zA-Z0-9_-]+$/", $data['container'])) + if (!preg_match("/^[a-zA-Z0-9_-]+$/", $data['container'])) { $input_errors[] = gettext("Queue names must be alphanumeric and _ or - only."); + } } function delete_l7c() { @@ -4007,17 +4398,19 @@ class l7rule { read_dummynet_config(); $dn_list =& get_unique_dnqueue_list(); $found = false; - if(is_array($dn_list)) { - foreach($dn_list as $key => $value) { - if($key == $this->GetRBehaviour()) { - if($value[0] == "?") + if (is_array($dn_list)) { + foreach ($dn_list as $key => $value) { + if ($key == $this->GetRBehaviour()) { + if ($value[0] == "?") { $l7rule = $this->GetRProtocol() . " = dnqueue " . substr($value, 1) . "\n"; - else + } else { $l7rule = $this->GetRProtocol() . " = dnpipe " . $value . "\n"; + } $found = true; } - if($found) + if ($found) { break; + } } } break; @@ -4036,8 +4429,9 @@ function get_divert_ports() { global $layer7_rules_list; $dports = array(); - foreach($layer7_rules_list as $l7r) + foreach ($layer7_rules_list as $l7r) { $dports[] = $l7r->GetRPort(); + } return $dports; } @@ -4047,10 +4441,11 @@ function &get_l7c_reference_to_me_in_config(&$name) { $ptr = NULL; - if(is_array($config['l7shaper']['container'])) { - foreach($config['l7shaper']['container'] as $key => $value) { - if($value['name'] == $name) + if (is_array($config['l7shaper']['container'])) { + foreach ($config['l7shaper']['container'] as $key => $value) { + if ($value['name'] == $name) { $ptr =& $config['l7shaper']['container'][$key]; + } } } return $ptr; @@ -4060,9 +4455,9 @@ function &get_l7c_reference_to_me_in_config(&$name) { function unset_l7_object_by_reference(&$name) { global $config; - if(is_array($config['l7shaper']['container'])) { - foreach($config['l7shaper']['container'] as $key => $value) { - if($value['name'] == $name) { + if (is_array($config['l7shaper']['container'])) { + foreach ($config['l7shaper']['container'] as $key => $value) { + if ($value['name'] == $name) { unset($config['l7shaper']['container'][$key]['l7rules']); unset($config['l7shaper']['container'][$key]); break; @@ -4084,8 +4479,9 @@ function read_layer7_config() { $layer7_rules_list = array(); foreach ($l7cs as $conf) { - if (empty($conf['name'])) + if (empty($conf['name'])) { continue; /* XXX: grrrrrr at php */ + } $root =& new layer7(); $root->ReadConfig($conf['name'],$conf); $layer7_rules_list[$root->GetRName()] = &$root; @@ -4095,12 +4491,15 @@ function read_layer7_config() { function update_layer7_custom_patterns() { global $config; - if (!is_array($config['l7shaper']['custom_pat'])) + if (!is_array($config['l7shaper']['custom_pat'])) { return; + } - foreach ($config['l7shaper']['custom_pat'] as $filename => $filecontent) - if (!file_exists("/usr/local/share/protocols/" . $filename)) + foreach ($config['l7shaper']['custom_pat'] as $filename => $filecontent) { + if (!file_exists("/usr/local/share/protocols/" . $filename)) { @file_put_contents("/usr/local/share/protocols/" . $filename, base64_decode($filecontent)); + } + } } function generate_layer7_files() { @@ -4109,16 +4508,17 @@ function generate_layer7_files() { read_layer7_config(); if (!empty($layer7_rules_list)) { - if (!is_module_loaded("ipdivert.ko")) + if (!is_module_loaded("ipdivert.ko")) { mwexec("/sbin/kldload ipdivert.ko"); + } array_map('unlink', glob("{$g['tmp_path']}/*.l7")); } update_layer7_custom_patterns(); - foreach($layer7_rules_list as $l7rules) { - if($l7rules->GetREnabled()) { + foreach ($layer7_rules_list as $l7rules) { + if ($l7rules->GetREnabled()) { $filename = $l7rules->GetRName() . ".l7"; $path = "{$g['tmp_path']}/" . $filename; @@ -4139,8 +4539,8 @@ function layer7_start_l7daemon() { * read_layer7_config(); */ - foreach($layer7_rules_list as $l7rules) { - if($l7rules->GetREnabled()) { + foreach ($layer7_rules_list as $l7rules) { + if ($l7rules->GetREnabled()) { $filename = $l7rules->GetRName() . ".l7"; $path = "{$g['tmp_path']}/" . $filename; @@ -4151,7 +4551,7 @@ function layer7_start_l7daemon() { log_error(sprintf(gettext("Sending HUP signal to %s"), $l7pid[0])); mwexec("/bin/kill -HUP {$l7pid[0]}"); } else { - // XXX: Hardcoded number of packets to garbage collect and queue length.. + // XXX: Hardcoded number of packets to garbage collect and queue length. $ipfw_classifyd_init = "/usr/local/sbin/ipfw-classifyd -n 8 -q 700 -c {$path} -p " . $l7rules->GetRPort() . " -P /usr/local/share/protocols"; mwexec_bg($ipfw_classifyd_init); } @@ -4166,10 +4566,11 @@ function generate_protocols_array() { $protocols = return_dir_as_array("/usr/local/share/protocols"); $protocols_new = array(); - if(is_array($protocols)) { - foreach($protocols as $key => $proto) { - if (strstr($proto, ".pat")) + if (is_array($protocols)) { + foreach ($protocols as $key => $proto) { + if (strstr($proto, ".pat")) { $protocols_new[$key] =& str_replace(".pat", "", $proto); + } } sort($protocols_new); } @@ -4180,10 +4581,13 @@ function get_l7_unique_list() { global $layer7_rules_list; $l7list = array(); - if(is_array($layer7_rules_list)) - foreach($layer7_rules_list as $l7c) - if($l7c->GetREnabled()) + if (is_array($layer7_rules_list)) { + foreach ($layer7_rules_list as $l7c) { + if ($l7c->GetREnabled()) { $l7list[] = $l7c->GetRName(); + } + } + } return $l7list; } @@ -4192,20 +4596,24 @@ function get_l7_unique_list() { function cleanup_l7_from_rules(&$name) { global $config; - if(is_array($config['filter']['rule'])) + if (is_array($config['filter']['rule'])) { foreach ($config['filter']['rule'] as $key => $rule) { - if ($rule['l7container'] == $name) + if ($rule['l7container'] == $name) { unset($config['filter']['rule'][$key]['l7container']); + } } + } } function get_dummynet_name_list() { $dn_name_list =& get_unique_dnqueue_list(); $dn_name = array(); - if(is_array($dn_name_list)) - foreach($dn_name_list as $key => $value) + if (is_array($dn_name_list)) { + foreach ($dn_name_list as $key => $value) { $dn_name[] = $key; + } + } return $dn_name; @@ -4214,30 +4622,33 @@ function get_dummynet_name_list() { function get_altq_name_list() { $altq_name_list =& get_unique_queue_list(); $altq_name = array(); - if(is_array($altq_name_list)) - foreach($altq_name_list as $key => $aqobj) + if (is_array($altq_name_list)) { + foreach ($altq_name_list as $key => $aqobj) { $altq_name[] = $key; + } + } return $altq_name; } /* - * XXX: TODO Make a class shaper to hide all these function + * XXX: TODO Make a class shaper to hide all these functions * from the global namespace. */ /* * This is a layer violation but for now there is no way - * i can find to properly do this with PHP. + * I can find to properly do this with PHP. */ function altq_get_default_queue($interface) { global $altq_list_queues; $altq_tmp = $altq_list_queues[$interface]; - if ($altq_tmp) + if ($altq_tmp) { return $altq_tmp->GetDefaultQueuePresent(); - else + } else { return false; + } } function altq_check_default_queues() { @@ -4245,12 +4656,15 @@ function altq_check_default_queues() { $count = 0; if (is_array($altq_list_queues)) { - foreach($altq_list_queues as $altq) { - if ($altq->GetDefaultQueuePresent()) + foreach ($altq_list_queues as $altq) { + if ($altq->GetDefaultQueuePresent()) { $count++; + } } } - else $count++; + else { + $count++; + } return 0; } @@ -4261,12 +4675,14 @@ function &get_unique_queue_list() { $qlist = array(); if (is_array($altq_list_queues)) { foreach ($altq_list_queues as $altq) { - if ($altq->GetEnabled() == "") + if ($altq->GetEnabled() == "") { continue; + } $tmplist =& $altq->get_queue_list(); foreach ($tmplist as $qname => $link) { - if ($link->GetEnabled() <> "") + if ($link->GetEnabled() <> "") { $qlist[$qname] = $link; + } } } } @@ -4279,8 +4695,9 @@ function &get_unique_dnqueue_list() { $qlist = array(); if (is_array($dummynet_pipe_list)) { foreach ($dummynet_pipe_list as $dn) { - if ($dn->GetEnabled() == "") + if ($dn->GetEnabled() == "") { continue; + } $tmplist =& $dn->get_queue_list(); foreach ($tmplist as $qname => $link) { $qlist[$qname] = $link; @@ -4291,34 +4708,39 @@ function &get_unique_dnqueue_list() { } function ref_on_altq_queue_list($parent, $qname) { - if (isset($GLOBALS['queue_list'][$qname])) + if (isset($GLOBALS['queue_list'][$qname])) { $GLOBALS['queue_list'][$qname]++; - else + } else { $GLOBALS['queue_list'][$qname] = 1; + } unref_on_altq_queue_list($parent); } function unref_on_altq_queue_list($qname) { $GLOBALS['queue_list'][$qname]--; - if ($GLOBALS['queue_list'][$qname] <= 1) + if ($GLOBALS['queue_list'][$qname] <= 1) { unset($GLOBALS['queue_list'][$qname]); + } } function read_altq_config() { global $altq_list_queues, $config; $path = array(); - if (!is_array($config['shaper'])) + if (!is_array($config['shaper'])) { $config['shaper'] = array(); - if (!is_array($config['shaper']['queue'])) + } + if (!is_array($config['shaper']['queue'])) { $config['shaper']['queue'] = array(); + } $a_int = &$config['shaper']['queue']; $altq_list_queues = array(); - if (!is_array($config['shaper']['queue'])) + if (!is_array($config['shaper']['queue'])) { return; + } foreach ($a_int as $key => $conf) { $int = $conf['interface']; @@ -4347,21 +4769,25 @@ function read_dummynet_config() { global $dummynet_pipe_list, $config; $path = array(); - if (!is_array($config['dnshaper'])) + if (!is_array($config['dnshaper'])) { $config['dnshaper'] = array(); - if (!is_array($config['dnshaper']['queue'])) + } + if (!is_array($config['dnshaper']['queue'])) { $config['dnshaper']['queue'] = array(); + } $a_int = &$config['dnshaper']['queue']; $dummynet_pipe_list = array(); - if (!is_array($config['dnshaper']['queue']) - || !count($config['dnshaper']['queue'])) + if (!is_array($config['dnshaper']['queue']) || + !count($config['dnshaper']['queue'])) { return; + } foreach ($a_int as $key => $conf) { - if (empty($conf['name'])) + if (empty($conf['name'])) { continue; /* XXX: grrrrrr at php */ + } $root =& new dnpipe_class(); $root->ReadConfig($conf); $dummynet_pipe_list[$root->GetQname()] = &$root; @@ -4391,8 +4817,9 @@ function get_interface_list_to_show() { if ($altq_list_queues[$shif]) { continue; } else { - if (!is_altq_capable(get_real_interface($shif))) + if (!is_altq_capable(get_real_interface($shif))) { continue; + } $tree .= "
      • ".$shDescr."
      • "; } } @@ -4406,8 +4833,9 @@ function filter_generate_altq_queues() { read_altq_config(); $altq_rules = ""; - foreach ($altq_list_queues as $altq) + foreach ($altq_list_queues as $altq) { $altq_rules .= $altq->build_rules(); + } return $altq_rules; } @@ -4420,8 +4848,9 @@ function dnqueue_find_nextnumber() { foreach ($dummynet_pipe_list as $dn) { $tmplist =& $dn->get_queue_list(); foreach ($tmplist as $qname => $link) { - if ($link[0] == "?") + if ($link[0] == "?") { $dnused[$qname] = substr($link, 1); + } } } } @@ -4434,12 +4863,14 @@ function dnqueue_find_nextnumber() { $dnnumber = $dnnum - 1; $found = true; break; - } else + } else { $dnnumber = $dnnum; + } } - if ($found == false) + if ($found == false) { $dnnumber++; + } unset($dnused, $dnnum, $found); return $dnnumber; @@ -4449,8 +4880,9 @@ function dnpipe_find_nextnumber() { global $dummynet_pipe_list; $dnused = array(); - foreach ($dummynet_pipe_list as $dn) + foreach ($dummynet_pipe_list as $dn) { $dnused[] = $dn->GetNumber(); + } sort($dnused, SORT_NUMERIC); $dnnumber = 0; @@ -4460,12 +4892,14 @@ function dnpipe_find_nextnumber() { $dnnumber = $dnnum - 1; $found = true; break; - } else + } else { $dnnumber = $dnnum; + } } - if ($found == false) + if ($found == false) { $dnnumber++; + } unset($dnused, $dnnum, $found); return $dnnumber; @@ -4477,8 +4911,9 @@ function filter_generate_dummynet_rules() { read_dummynet_config(); $dn_rules = ""; - foreach ($dummynet_pipe_list as $dn) + foreach ($dummynet_pipe_list as $dn) { $dn_rules .= $dn->build_rules(); + } if (!empty($dn_rules)) { if (!is_module_loaded("dummynet.ko")) { @@ -4498,8 +4933,9 @@ function build_iface_without_this_queue($iface, $qname) { global $shaperIFlist; $altq =& $altq_list_queues[$iface]; - if ($altq) + if ($altq) { $scheduler = ": " . $altq->GetScheduler(); + } $form = ""; $form .= "". $shaperIFlist[$iface] . $scheduler.""; $form .= ""; @@ -4519,14 +4955,14 @@ function build_iface_without_this_queue($iface, $qname) { $default_shaper_msg = ""; $default_shaper_msg .= "" . sprintf(gettext("Welcome to the %s Traffic Shaper."), $g['product_name']) . "
        "; $default_shaper_msg .= gettext("The tree on the left helps you navigate through the queues
        " - . "buttons at the bottom represent queue actions and are activated accordingly."); + . "buttons at the bottom represent queue actions and are activated accordingly."); $default_shaper_msg .= "
        "; $default_shaper_msg .= ""; $dn_default_shaper_msg = ""; $dn_default_shaper_msg .= "" . sprintf(gettext("Welcome to the %s Traffic Shaper."), $g['product_name']) . "
        "; $dn_default_shaper_msg .= gettext("The tree on the left helps you navigate through the queues
        " - . "buttons at the bottom represent queue actions and are activated accordingly."); + . "buttons at the bottom represent queue actions and are activated accordingly."); $dn_default_shaper_msg .= "
        "; $dn_default_shaper_msg .= ""; diff --git a/etc/inc/smtp.inc b/etc/inc/smtp.inc index 525bb3364a..035a30a07e 100644 --- a/etc/inc/smtp.inc +++ b/etc/inc/smtp.inc @@ -105,7 +105,7 @@ class smtp_class { if(feof($this->connection)) { - $this->error=gettext("reached the end of data while reading from the SMTP server conection"); + $this->error=gettext("reached the end of data while reading from the SMTP server connection"); return(""); } if(GetType($data=@fgets($this->connection,100))!="string" diff --git a/etc/inc/system.inc b/etc/inc/system.inc index f95e9f31d8..112c2183c3 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -31,7 +31,7 @@ /* pfSense_BUILDER_BINARIES: /usr/sbin/powerd /usr/bin/killall /sbin/route - pfSense_BUILDER_BINARIES: /bin/hostname /bin/ls /usr/sbin/syslogd + pfSense_BUILDER_BINARIES: /bin/hostname /bin/ls /usr/sbin/syslogd pfSense_BUILDER_BINARIES: /usr/sbin/pccardd /usr/local/sbin/lighttpd /bin/chmod /bin/mkdir pfSense_BUILDER_BINARIES: /usr/bin/tar /usr/local/sbin/ntpd /usr/local/sbin/ntpdate pfSense_BUILDER_BINARIES: /usr/bin/nohup /sbin/dmesg /usr/local/sbin/atareinit /sbin/kldload @@ -41,25 +41,31 @@ function activate_powerd() { global $config, $g; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; - if(is_process_running("powerd")) + } + if (is_process_running("powerd")) { exec("/usr/bin/killall powerd"); - if(isset($config['system']['powerd_enable'])) { - if ($g["platform"] == "nanobsd") + } + if (isset($config['system']['powerd_enable'])) { + if ($g["platform"] == "nanobsd") { exec("/sbin/kldload cpufreq"); + } $ac_mode = "hadp"; - if (!empty($config['system']['powerd_ac_mode'])) + if (!empty($config['system']['powerd_ac_mode'])) { $ac_mode = $config['system']['powerd_ac_mode']; + } $battery_mode = "hadp"; - if (!empty($config['system']['powerd_battery_mode'])) + if (!empty($config['system']['powerd_battery_mode'])) { $battery_mode = $config['system']['powerd_battery_mode']; + } $normal_mode = "hadp"; - if (!empty($config['system']['powerd_normal_mode'])) + if (!empty($config['system']['powerd_normal_mode'])) { $normal_mode = $config['system']['powerd_normal_mode']; + } mwexec("/usr/sbin/powerd -b $battery_mode -a $ac_mode -n $normal_mode"); } @@ -68,8 +74,9 @@ function activate_powerd() { function get_default_sysctl_value($id) { global $sysctls; - if (isset($sysctls[$id])) + if (isset($sysctls[$id])) { return $sysctls[$id]; + } } function get_sysctl_descr($sysctl) { @@ -85,11 +92,12 @@ function system_get_sysctls() { $disp_sysctl = array(); $disp_cache = array(); if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) { - foreach($config['sysctl']['item'] as $id => $tunable) { - if ($tunable['value'] == "default") + foreach ($config['sysctl']['item'] as $id => $tunable) { + if ($tunable['value'] == "default") { $value = get_default_sysctl_value($tunable['tunable']); - else + } else { $value = $tunable['value']; + } $disp_sysctl[$id] = $tunable; $disp_sysctl[$id]['modified'] = true; @@ -98,8 +106,9 @@ function system_get_sysctls() { } foreach ($sysctls as $sysctl => $value) { - if (isset($disp_cache[$sysctl])) + if (isset($disp_cache[$sysctl])) { continue; + } $disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl)); } @@ -110,15 +119,17 @@ function system_get_sysctls() { function activate_sysctls() { global $config, $g, $sysctls; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; + } if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) { - foreach($config['sysctl']['item'] as $tunable) { - if($tunable['value'] == "default") + foreach ($config['sysctl']['item'] as $tunable) { + if ($tunable['value'] == "default") { $value = get_default_sysctl_value($tunable['tunable']); - else + } else { $value = $tunable['value']; + } $sysctls[$tunable['tunable']] = $value; } @@ -130,45 +141,58 @@ function activate_sysctls() { function system_resolvconf_generate($dynupdate = false) { global $config, $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_resolvconf_generate() being called $mt\n"; } $syscfg = $config['system']; - if (((isset($config['dnsmasq']['enable']) && (!isset($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") && (empty($config['dnsmasq']['interface']) || in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) - || (isset($config['unbound']['enable'])) && (!isset($config['unbound']['port']) || $config['unbound']['port'] == "53") && (empty($config['unbound']['active_interface']) || in_array("lo0", explode(",", $config['unbound']['active_interface'])) || in_array("all", explode(",", $config['unbound']['active_interface']), true))) - && !isset($config['system']['dnslocalhost'])) + if ((((isset($config['dnsmasq']['enable'])) && + (!isset($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") && + (empty($config['dnsmasq']['interface']) || + in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) || + ((isset($config['unbound']['enable'])) && + (!isset($config['unbound']['port']) || $config['unbound']['port'] == "53") && + (empty($config['unbound']['active_interface']) || + in_array("lo0", explode(",", $config['unbound']['active_interface'])) || + in_array("all", explode(",", $config['unbound']['active_interface']), true)))) && + (!isset($config['system']['dnslocalhost']))) { $resolvconf .= "nameserver 127.0.0.1\n"; + } if (isset($syscfg['dnsallowoverride'])) { /* get dynamically assigned DNS servers (if any) */ $ns = array_unique(get_searchdomains()); - foreach($ns as $searchserver) { - if($searchserver) + foreach ($ns as $searchserver) { + if ($searchserver) { $resolvconf .= "search {$searchserver}\n"; + } } $ns = array_unique(get_nameservers()); - foreach($ns as $nameserver) { - if($nameserver) + foreach ($ns as $nameserver) { + if ($nameserver) { $resolvconf .= "nameserver $nameserver\n"; + } } } else { // Do not create blank search/domain lines, it can break tools like dig. - if($syscfg['domain']) + if ($syscfg['domain']) { $resolvconf .= "search {$syscfg['domain']}\n"; + } } if (is_array($syscfg['dnsserver'])) { foreach ($syscfg['dnsserver'] as $ns) { - if ($ns) + if ($ns) { $resolvconf .= "nameserver $ns\n"; + } } } // Add EDNS support - if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) + if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) { $resolvconf .= "options edns0\n"; + } $dnslock = lock('resolvconf', LOCK_EX); @@ -193,8 +217,9 @@ function system_resolvconf_generate($dynupdate = false) { if (!platform_booting()) { /* restart dhcpd (nameservers may have changed) */ - if (!$dynupdate) + if (!$dynupdate) { services_dhcpd_configure(); + } } /* setup static routes for DNS servers. */ @@ -221,7 +246,7 @@ function system_resolvconf_generate($dynupdate = false) { if (isset($config['system']['route-debug'])) { $mt = microtime(); log_error("ROUTING debug: $mt - route change -host -inet6 {$syscfg['dnsserver'][$dnscountermo]} $gatewayip "); - } + } } } } @@ -236,17 +261,19 @@ function get_searchdomains() { global $config, $g; $master_list = array(); - + // Read in dhclient nameservers $search_list = glob("/var/etc/searchdomain_*"); if (is_array($search_list)) { - foreach($search_list as $fdns) { + foreach ($search_list as $fdns) { $contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - if (!is_array($contents)) + if (!is_array($contents)) { continue; + } foreach ($contents as $dns) { - if(is_hostname($dns)) + if (is_hostname($dns)) { $master_list[] = $dns; + } } } } @@ -257,28 +284,32 @@ function get_searchdomains() { function get_nameservers() { global $config, $g; $master_list = array(); - + // Read in dhclient nameservers $dns_lists = glob("/var/etc/nameserver_*"); if (is_array($dns_lists)) { - foreach($dns_lists as $fdns) { + foreach ($dns_lists as $fdns) { $contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - if (!is_array($contents)) + if (!is_array($contents)) { continue; + } foreach ($contents as $dns) { - if(is_ipaddr($dns)) + if (is_ipaddr($dns)) { $master_list[] = $dns; + } } } } // Read in any extra nameservers - if(file_exists("/var/etc/nameservers.conf")) { + if (file_exists("/var/etc/nameservers.conf")) { $dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - if(is_array($dns_s)) { - foreach($dns_s as $dns) - if (is_ipaddr($dns)) + if (is_array($dns_s)) { + foreach ($dns_s as $dns) { + if (is_ipaddr($dns)) { $master_list[] = $dns; + } + } } } @@ -293,10 +324,11 @@ function system_hosts_generate() { } $syscfg = $config['system']; - if (isset($config['unbound']) && isset($config['unbound']['enable'])) + if (isset($config['unbound']) && isset($config['unbound']['enable'])) { $dnsmasqcfg = $config['unbound']; - else + } else { $dnsmasqcfg = $config['dnsmasq']; + } $hosts = "127.0.0.1 localhost localhost.{$syscfg['domain']}\n"; $hosts .= "::1 localhost localhost.{$syscfg['domain']}\n"; @@ -305,11 +337,13 @@ function system_hosts_generate() { if ($config['interfaces']['lan']) { $cfgip = get_interface_ip("lan"); - if (is_ipaddr($cfgip)) + if (is_ipaddr($cfgip)) { $hosts .= "{$cfgip} {$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n"; + } $cfgipv6 = get_interface_ipv6("lan"); - if (is_ipaddrv6($cfgipv6)) + if (is_ipaddrv6($cfgipv6)) { $hosts .= "{$cfgipv6} {$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n"; + } } else { $sysiflist = get_configured_interface_list(); $hosts_if_found = false; @@ -325,61 +359,75 @@ function system_hosts_generate() { $hosts .= "{$cfgipv6} {$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n"; $hosts_if_found = true; } - if ($hosts_if_found == true) + if ($hosts_if_found == true) { break; + } } } } if (isset($dnsmasqcfg['enable'])) { - if (!is_array($dnsmasqcfg['hosts'])) + if (!is_array($dnsmasqcfg['hosts'])) { $dnsmasqcfg['hosts'] = array(); + } foreach ($dnsmasqcfg['hosts'] as $host) { - if ($host['host']) + if ($host['host']) { $lhosts .= "{$host['ip']} {$host['host']}.{$host['domain']} {$host['host']}\n"; - else + } else { $lhosts .= "{$host['ip']} {$host['domain']}\n"; - if (!is_array($host['aliases']) || !is_array($host['aliases']['item'])) + } + if (!is_array($host['aliases']) || !is_array($host['aliases']['item'])) { continue; + } foreach ($host['aliases']['item'] as $alias) { - if ($alias['host']) + if ($alias['host']) { $lhosts .= "{$host['ip']} {$alias['host']}.{$alias['domain']} {$alias['host']}\n"; - else + } else { $lhosts .= "{$host['ip']} {$alias['domain']}\n"; + } } } if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) { - foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) - if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable'])) - foreach ($dhcpifconf['staticmap'] as $host) - if ($host['ipaddr'] && $host['hostname'] && $host['domain']) - $dhosts .= "{$host['ipaddr']} {$host['hostname']}.{$host['domain']} {$host['hostname']}\n"; - else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain']) - $dhosts .= "{$host['ipaddr']} {$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n"; - else if ($host['ipaddr'] && $host['hostname']) - $dhosts .= "{$host['ipaddr']} {$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n"; + foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) { + if (is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable'])) { + foreach ($dhcpifconf['staticmap'] as $host) { + if ($host['ipaddr'] && $host['hostname'] && $host['domain']) { + $dhosts .= "{$host['ipaddr']} {$host['hostname']}.{$host['domain']} {$host['hostname']}\n"; + } else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain']) { + $dhosts .= "{$host['ipaddr']} {$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n"; + } else if ($host['ipaddr'] && $host['hostname']) { + $dhosts .= "{$host['ipaddr']} {$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n"; + } + } + } + } } if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) { - foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf) - if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable'])) - foreach ($dhcpifconf['staticmap'] as $host) - if ($host['ipaddrv6'] && $host['hostname'] && $host['domain']) - $dhosts .= "{$host['ipaddrv6']} {$host['hostname']}.{$host['domain']} {$host['hostname']}\n"; - else if ($host['ipaddrv6'] && $host['hostname'] && $dhcpifconf['domain']) - $dhosts .= "{$host['ipaddrv6']} {$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n"; - else if ($host['ipaddrv6'] && $host['hostname']) - $dhosts .= "{$host['ipaddrv6']} {$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n"; + foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf) { + if (is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable'])) { + foreach ($dhcpifconf['staticmap'] as $host) { + if ($host['ipaddrv6'] && $host['hostname'] && $host['domain']) { + $dhosts .= "{$host['ipaddrv6']} {$host['hostname']}.{$host['domain']} {$host['hostname']}\n"; + } else if ($host['ipaddrv6'] && $host['hostname'] && $dhcpifconf['domain']) { + $dhosts .= "{$host['ipaddrv6']} {$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n"; + } else if ($host['ipaddrv6'] && $host['hostname']) { + $dhosts .= "{$host['ipaddrv6']} {$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n"; + } + } + } + } } - if (isset($dnsmasqcfg['dhcpfirst'])) + if (isset($dnsmasqcfg['dhcpfirst'])) { $hosts .= $dhosts . $lhosts; - else + } else { $hosts .= $lhosts . $dhosts; + } } /* - * Do not remove this because dhcpleases monitors with kqueue it needs to be + * Do not remove this because dhcpleases monitors with kqueue it needs to be * killed before writing to hosts files. */ if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) { @@ -404,16 +452,18 @@ function system_hosts_generate() { function system_dhcpleases_configure() { global $config, $g; - - if ($g['platform'] == 'jail') + + if ($g['platform'] == 'jail') { return; + } /* Start the monitoring process for dynamic dhcpclients. */ - if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) - || (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) { + if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) || + (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) { /* Make sure we do not error out */ mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db"); - if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) + if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) { @touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"); + } if (isset($config['unbound']['enable'])) { $dns_pid = "unbound.pid"; @@ -430,13 +480,15 @@ function system_dhcpleases_configure() { if (intval($retval) == 0) { sigkillbypid($pidfile, "HUP"); return; - } else + } else { sigkillbypid($pidfile, "TERM"); + } } /* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */ - if (is_process_running("dhcpleases")) + if (is_process_running("dhcpleases")) { sigkillbyname('dhcpleases', "TERM"); + } @unlink($pidfile); mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/{$dns_pid} {$unbound_conf} -h {$g['varetc_path']}/hosts"); } else { @@ -447,7 +499,7 @@ function system_dhcpleases_configure() { function system_hostname_configure() { global $config, $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_hostname_configure() being called $mt\n"; } @@ -458,7 +510,7 @@ function system_hostname_configure() { $status = mwexec("/bin/hostname " . escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}")); - /* Setup host GUID ID. This is used by ZFS. */ + /* Setup host GUID ID. This is used by ZFS. */ mwexec("/etc/rc.d/hostid start"); return $status; @@ -466,9 +518,10 @@ function system_hostname_configure() { function system_routing_configure($interface = "") { global $config, $g; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; - if(isset($config['system']['developerspew'])) { + } + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_routing_configure() being called $mt\n"; } @@ -485,33 +538,39 @@ function system_routing_configure($interface = "") { foreach ($config['gateways']['gateway_item'] as $gateway) { if (isset($gateway['defaultgw'])) { if ($foundgw == false && ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) { - if(strpos($gateway['gateway'], ":")) + if (strpos($gateway['gateway'], ":")) { continue; - if ($gateway['gateway'] == "dynamic") + } + if ($gateway['gateway'] == "dynamic") { $gateway['gateway'] = get_interface_gateway($gateway['interface']); + } $gatewayip = $gateway['gateway']; $interfacegw = $gateway['interface']; if (!empty($gateway['interface'])) { $defaultif = get_real_interface($gateway['interface']); - if ($defaultif) + if ($defaultif) { @file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']); + } } $foundgw = true; } else if ($foundgwv6 == false && ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) { - if ($gateway['gateway'] == "dynamic") + if ($gateway['gateway'] == "dynamic") { $gateway['gateway'] = get_interface_gateway_v6($gateway['interface']); + } $gatewayipv6 = $gateway['gateway']; $interfacegwv6 = $gateway['interface']; if (!empty($gateway['interface'])) { $defaultifv6 = get_real_interface($gateway['interface']); - if ($defaultifv6) + if ($defaultifv6) { @file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']); + } } $foundgwv6 = true; } } - if ($foundgw === true && $foundgwv6 === true) + if ($foundgw === true && $foundgwv6 === true) { break; + } } } if ($foundgw == false) { @@ -519,7 +578,7 @@ function system_routing_configure($interface = "") { $interfacegw = "wan"; $gatewayip = get_interface_gateway("wan"); @file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip); - } + } if ($foundgwv6 == false) { $defaultifv6 = get_real_interface("wan"); $interfacegwv6 = "wan"; @@ -529,8 +588,8 @@ function system_routing_configure($interface = "") { $dont_add_route = false; /* if OLSRD is enabled, allow WAN to house DHCP. */ if (is_array($config['installedpackages']['olsrd'])) { - foreach($config['installedpackages']['olsrd']['config'] as $olsrd) { - if(($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) { + foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) { + if (($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) { $dont_add_route = true; log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled."))); break; @@ -538,20 +597,21 @@ function system_routing_configure($interface = "") { } } - if ($dont_add_route == false ) { - if (!empty($interface) && $interface != $interfacegw) + if ($dont_add_route == false) { + if (!empty($interface) && $interface != $interfacegw) { ; - else if (is_ipaddrv4($gatewayip)) { + } else if (is_ipaddrv4($gatewayip)) { log_error("ROUTING: setting default route to $gatewayip"); mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip)); } - if (!empty($interface) && $interface != $interfacegwv6) + if (!empty($interface) && $interface != $interfacegwv6) { ; - else if (is_ipaddrv6($gatewayipv6)) { + } else if (is_ipaddrv6($gatewayipv6)) { $ifscope = ""; - if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%')) + if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%')) { $ifscope = "%{$defaultifv6}"; + } log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}"); mwexec("/sbin/route change -inet6 default " . escapeshellarg("{$gatewayipv6}{$ifscope}")); } @@ -577,39 +637,46 @@ function system_staticroutes_configure($interface = "", $update_dns = false) { continue; } $gateway = $gateways_arr[$rtent['gateway']]; - if (!empty($interface) && $interface != $gateway['friendlyiface']) + if (!empty($interface) && $interface != $gateway['friendlyiface']) { continue; + } $gatewayip = $gateway['gateway']; $interfacegw = $gateway['interface']; $blackhole = ""; - if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3))) + if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3))) { $blackhole = "-blackhole"; + } - if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) + if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) { continue; + } $dnscache = array(); if ($update_dns === true) { - if (is_subnet($rtent['network'])) + if (is_subnet($rtent['network'])) { continue; + } $dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network']))); - if (empty($dnscache)) + if (empty($dnscache)) { continue; + } } - if (is_subnet($rtent['network'])) + if (is_subnet($rtent['network'])) { $ips = array($rtent['network']); - else { - if (!isset($rtent['disabled'])) + } else { + if (!isset($rtent['disabled'])) { $filterdns_list[] = $rtent['network']; + } $ips = add_hostname_to_watch($rtent['network']); } foreach ($dnscache as $ip) { - if (in_array($ip, $ips)) + if (in_array($ip, $ips)) { continue; + } mwexec("/sbin/route delete " . escapeshellarg($ip), true); if (isset($config['system']['route-debug'])) { $mt = microtime(); @@ -630,15 +697,16 @@ function system_staticroutes_configure($interface = "", $update_dns = false) { } foreach ($ips as $ip) { - if (is_ipaddrv4($ip)) + if (is_ipaddrv4($ip)) { $ip .= "/32"; + } // do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes - + $inet = (is_subnetv6($ip) ? "-inet6" : "-inet"); $cmd = "/sbin/route change {$inet} {$blackhole} " . escapeshellarg($ip) . " "; - if (is_subnet($ip)) + if (is_subnet($ip)) { if (is_ipaddr($gatewayip)) { mwexec($cmd . escapeshellarg($gatewayip)); if (isset($config['system']['route-debug'])) { @@ -652,6 +720,7 @@ function system_staticroutes_configure($interface = "", $update_dns = false) { log_error("ROUTING debug: $mt - $cmd -iface $interfacegw "); } } + } } } unset($gateways_arr); @@ -663,15 +732,17 @@ function system_staticroutes_configure($interface = "", $update_dns = false) { $interval = 60; $hostnames = ""; array_unique($filterdns_list); - foreach ($filterdns_list as $hostname) + foreach ($filterdns_list as $hostname) { $hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n"; + } file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames); unset($hostnames); - if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) + if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) { sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP"); - else + } else { mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1"); + } } else { killbypid("{$g['varrun_path']}/filterdns-route.pid"); @unlink("{$g['varrun_path']}/filterdns-route.pid"); @@ -684,7 +755,7 @@ function system_staticroutes_configure($interface = "", $update_dns = false) { function system_routing_enable() { global $config, $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_routing_enable() being called $mt\n"; } @@ -699,10 +770,11 @@ function system_routing_enable() { function system_syslogd_fixup_server($server) { /* If it's an IPv6 IP alone, encase it in brackets */ - if (is_ipaddrv6($server)) + if (is_ipaddrv6($server)) { return "[$server]"; - else + } else { return $server; + } } function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") { @@ -711,18 +783,21 @@ function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") { $remote_servers = ""; $pad_to = 56; $padding = ceil(($pad_to - strlen($facility))/8)+1; - if($syslogcfg['remoteserver']) + if ($syslogcfg['remoteserver']) { $remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n"; - if($syslogcfg['remoteserver2']) + } + if ($syslogcfg['remoteserver2']) { $remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n"; - if($syslogcfg['remoteserver3']) + } + if ($syslogcfg['remoteserver3']) { $remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n"; + } return $remote_servers; } function system_syslogd_start() { global $config, $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_syslogd_start() being called $mt\n"; } @@ -731,11 +806,13 @@ function system_syslogd_start() { $syslogcfg = $config['syslog']; - if (platform_booting()) + if (platform_booting()) { echo gettext("Starting syslog..."); + } - if (is_process_running("fifolog_writer")) + if (is_process_running("fifolog_writer")) { mwexec('/bin/pkill fifolog_writer'); + } // Which logging type are we using this week?? if (isset($config['system']['disablesyslogclog'])) { @@ -756,9 +833,9 @@ function system_syslogd_start() { if (isset($syslogcfg)) { $separatelogfacilities = array('ntp','ntpd','ntpdate','charon','ipsec_starter','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','dhcp6c','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd','filterlog'); $syslogconf = ""; - if($config['installedpackages']['package']) { - foreach($config['installedpackages']['package'] as $package) { - if($package['logging']) { + if ($config['installedpackages']['package']) { + foreach ($config['installedpackages']['package'] as $package) { + if ($package['logging']) { array_push($separatelogfacilities, $package['logging']['facilityname']); mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}"); $syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n"; @@ -767,76 +844,96 @@ function system_syslogd_start() { } $facilitylist = implode(',', array_unique($separatelogfacilities)); $syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/routing.log\n"; + } $syslogconf .= "!ntp,ntpd,ntpdate\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/ntpd.log\n"; + } $syslogconf .= "!ppp\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/ppp.log\n"; + } $syslogconf .= "!pptps\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/pptps.log\n"; + } $syslogconf .= "!poes\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/poes.log\n"; + } $syslogconf .= "!l2tps\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/l2tps.log\n"; + } $syslogconf .= "!charon,ipsec_starter\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/ipsec.log\n"; - if (isset($syslogcfg['vpn'])) + } + if (isset($syslogcfg['vpn'])) { $syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*"); + } $syslogconf .= "!openvpn\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/openvpn.log\n"; - if (isset($syslogcfg['vpn'])) + } + if (isset($syslogcfg['vpn'])) { $syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*"); + } $syslogconf .= "!apinger\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/gateways.log\n"; - if (isset($syslogcfg['apinger'])) + } + if (isset($syslogcfg['apinger'])) { $syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*"); + } $syslogconf .= "!dnsmasq,filterdns,unbound\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/resolver.log\n"; + } $syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/dhcpd.log\n"; - if (isset($syslogcfg['dhcp'])) + } + if (isset($syslogcfg['dhcp'])) { $syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*"); + } $syslogconf .= "!relayd\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/relayd.log\n"; - if (isset($syslogcfg['relayd'])) + } + if (isset($syslogcfg['relayd'])) { $syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*"); + } $syslogconf .= "!hostapd\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/wireless.log\n"; - if (isset($syslogcfg['hostapd'])) + } + if (isset($syslogcfg['hostapd'])) { $syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*"); + } $syslogconf .= "!filterlog\n"; $syslogconf .= "*.* {$log_directive}{$g['varlog_path']}/filter.log\n"; - if (isset($syslogcfg['filter'])) + if (isset($syslogcfg['filter'])) { $syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*"); + } $syslogconf .= "!-{$facilitylist}\n"; - if (!isset($syslogcfg['disablelocallogging'])) + if (!isset($syslogcfg['disablelocallogging'])) { $syslogconf .= << "admin@{$config['system']['hostname']}.{$config['system']['domain']}", 'commonName' => "{$config['system']['hostname']}-{$cert['refid']}"); $old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */ - if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")){ - while($ssl_err = openssl_error_string()){ + if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) { + while ($ssl_err = openssl_error_string()) { log_error("Error creating WebGUI Certificate: openssl library returns: " . $ssl_err); } error_reporting($old_err_level); @@ -967,8 +1074,9 @@ function system_webgui_create_certificate() { function system_webgui_start() { global $config, $g; - if (platform_booting()) + if (platform_booting()) { echo gettext("Starting webConfigurator..."); + } chdir($g['www_path']); @@ -979,19 +1087,22 @@ function system_webgui_start() { $ca = ""; /* non-standard port? */ - if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") + if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") { $portarg = "{$config['system']['webgui']['port']}"; + } if ($config['system']['webgui']['protocol'] == "https") { // Ensure that we have a webConfigurator CERT $cert =& lookup_cert($config['system']['webgui']['ssl-certref']); - if(!is_array($cert) || !$cert['crt'] || !$cert['prv']) + if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) { $cert = system_webgui_create_certificate(); + } $crt = base64_decode($cert['crt']); $key = base64_decode($cert['prv']); - if(!$config['system']['webgui']['port']) + if (!$config['system']['webgui']['port']) { $portarg = "443"; + } $ca = ca_chain($cert); } @@ -1011,10 +1122,11 @@ function system_webgui_start() { $res = mwexec("/usr/local/sbin/lighttpd -f {$g['varetc_path']}/lighty-webConfigurator.conf"); if (platform_booting()) { - if ($res == 0) + if ($res == 0) { echo gettext("done.") . "\n"; - else + } else { echo gettext("failed!") . "\n"; + } } return $res; @@ -1033,10 +1145,11 @@ function system_generate_lighty_config($filename, global $config, $g; - if(!is_dir("{$g['tmp_path']}/lighttpdcompress")) + if (!is_dir("{$g['tmp_path']}/lighttpdcompress")) { mkdir("{$g['tmp_path']}/lighttpdcompress"); + } - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_generate_lighty_config() being called $mt\n"; } @@ -1046,13 +1159,15 @@ function system_generate_lighty_config($filename, $captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n"; $maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip']; - if (empty($maxprocperip)) + if (empty($maxprocperip)) { $maxprocperip = 10; + } $captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}"; $server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n"; - if(!is_dir("{$g['tmp_path']}/captiveportal")) + if (!is_dir("{$g['tmp_path']}/captiveportal")) { @mkdir("{$g['tmp_path']}/captiveportal", 0555); + } $server_max_request_size = "server.max-request-size = 384"; $cgi_config = ""; } else { @@ -1063,22 +1178,24 @@ function system_generate_lighty_config($filename, $server_max_request_size = "server.max-request-size = 2097152"; $cgi_config = "cgi.assign = ( \".cgi\" => \"\" )"; } - - if (empty($port)) + + if (empty($port)) { $lighty_port = "80"; - else + } else { $lighty_port = $port; + } $memory = get_memory(); $realmem = $memory[1]; // Determine web GUI process settings and take into account low memory systems - if ($realmem < 255) + if ($realmem < 255) { $max_procs = 1; - else + } else { $max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2; + } - // Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM + // Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM if ($captive_portal !== false) { if ($realmem > 135 and $realmem < 256) { $max_procs += 1; // 2 worker processes @@ -1087,19 +1204,21 @@ function system_generate_lighty_config($filename, } else if ($realmem > 512) { $max_procs += 4; // 6 worker processes } - if ($max_procs > 1) + if ($max_procs > 1) { $max_php_children = intval($max_procs/2); - else + } else { $max_php_children = 1; + } } else { - if ($realmem < 78) + if ($realmem < 78) { $max_php_children = 0; - else + } else { $max_php_children = 1; + } } - if(!isset($config['syslog']['nologlighttpd'])) { + if (!isset($config['syslog']['nologlighttpd'])) { $lighty_use_syslog = << "" and $key <> "") { + if ($cert <> "" and $key <> "") { $lighty_config .= "\n"; $lighty_config .= "## ssl configuration\n"; $lighty_config .= "ssl.engine = \"enable\"\n"; $lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n"; - if($ca <> "") + if ($ca <> "") { $lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n"; + } } $lighty_config .= " }\n"; @@ -1298,8 +1418,8 @@ compress.filetype = ("text/plain","text/css", "text/xml", "text/javascript" ) {$captive_portal_mod_evasive} expire.url = ( - "" => "access 50 hours", - ) + "" => "access 50 hours", + ) EOD; @@ -1311,7 +1431,7 @@ EOD; $key = str_replace("\n\n", "\n", $key); $ca = str_replace("\n\n", "\n", $ca); - if($cert <> "" and $key <> "") { + if ($cert <> "" and $key <> "") { $fd = fopen("{$g['varetc_path']}/{$cert_location}", "w"); if (!$fd) { printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n"); @@ -1322,7 +1442,7 @@ EOD; fwrite($fd, "\n"); fwrite($fd, $key); fclose($fd); - if(!(empty($ca) || (strlen(trim($ca)) == 0))) { + if (!(empty($ca) || (strlen(trim($ca)) == 0))) { $fd = fopen("{$g['varetc_path']}/{$ca_location}", "w"); if (!$fd) { printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n"); @@ -1347,8 +1467,8 @@ EOD; while (!feof($fd)) { $dmesgl = fgets($fd); if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) { - unset($config['system']['webgui']['beast_protection']); - log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")"); + unset($config['system']['webgui']['beast_protection']); + log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")"); break; } } @@ -1362,14 +1482,16 @@ EOD; $lighty_config .= "ssl.cipher-list = \"DHE-RSA-CAMELLIA256-SHA:DHE-DSS-CAMELLIA256-SHA:CAMELLIA256-SHA:DHE-DSS-AES256-SHA:AES256-SHA:DHE-RSA-CAMELLIA128-SHA:DHE-DSS-CAMELLIA128-SHA:CAMELLIA128-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:!aNULL:!eNULL:!3DES:@STRENGTH\"\n"; } - if(!(empty($ca) || (strlen(trim($ca)) == 0))) + if (!(empty($ca) || (strlen(trim($ca)) == 0))) { $lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n"; + } } - // Add HTTP to HTTPS redirect + // Add HTTP to HTTPS redirect if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) { - if($lighty_port != "443") + if ($lighty_port != "443") { $redirectport = ":{$lighty_port}"; + } $lighty_config .= << "") { + } elseif ($config['system'][$cmdn] <> "") { /* execute single item */ exec($config['system'][$cmdn]); @@ -1869,7 +2011,7 @@ function system_do_shell_commands($early = 0) { function system_console_configure() { global $config, $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_console_configure() being called $mt\n"; } @@ -1883,7 +2025,7 @@ function system_console_configure() { function system_dmesg_save() { global $g; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_dmesg_save() being called $mt\n"; } @@ -1895,8 +2037,9 @@ function system_dmesg_save() { $lastcpline = 0; for ($i = 0; $i < count($dmesg); $i++) { - if (strstr($dmesg[$i], "Copyright (c) 1992-")) + if (strstr($dmesg[$i], "Copyright (c) 1992-")) { $lastcpline = $i; + } } $fd = fopen("{$g['varlog_path']}/dmesg.boot", "w"); @@ -1905,8 +2048,9 @@ function system_dmesg_save() { return 1; } - for ($i = $lastcpline; $i < count($dmesg); $i++) + for ($i = $lastcpline; $i < count($dmesg); $i++) { fwrite($fd, $dmesg[$i] . "\n"); + } fclose($fd); unset($dmesg); @@ -1916,7 +2060,7 @@ function system_dmesg_save() { function system_set_harddisk_standby() { global $g, $config; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_set_harddisk_standby() being called $mt\n"; } @@ -1948,12 +2092,12 @@ function system_set_harddisk_standby() { function system_setup_sysctl() { global $config; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_setup_sysctl() being called $mt\n"; } - activate_sysctls(); + activate_sysctls(); if (isset($config['system']['sharednet'])) { system_disable_arp_wrong_if(); @@ -1962,7 +2106,7 @@ function system_setup_sysctl() { function system_disable_arp_wrong_if() { global $config; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_disable_arp_wrong_if() being called $mt\n"; } @@ -1974,7 +2118,7 @@ function system_disable_arp_wrong_if() { function system_enable_arp_wrong_if() { global $config; - if(isset($config['system']['developerspew'])) { + if (isset($config['system']['developerspew'])) { $mt = microtime(); echo "system_enable_arp_wrong_if() being called $mt\n"; } @@ -1990,14 +2134,15 @@ function enable_watchdog() { $install_watchdog = false; $supported_watchdogs = array("Geode"); $file = file_get_contents("/var/log/dmesg.boot"); - foreach($supported_watchdogs as $sd) { - if(stristr($file, "Geode")) { + foreach ($supported_watchdogs as $sd) { + if (stristr($file, "Geode")) { $install_watchdog = true; } } - if($install_watchdog == true) { - if(is_process_running("watchdogd")) + if ($install_watchdog == true) { + if (is_process_running("watchdogd")) { mwexec("/usr/bin/killall watchdogd", true); + } exec("/usr/sbin/watchdogd"); } } @@ -2008,20 +2153,20 @@ function system_check_reset_button() { $specplatform = system_identify_specific_platform(); switch ($specplatform['name']) { - case 'alix': - case 'wrap': - case 'FW7541': - case 'APU': - case 'C2358': - break; - default: - return 0; + case 'alix': + case 'wrap': + case 'FW7541': + case 'APU': + case 'C2358': + break; + default: + return 0; } $retval = mwexec("/usr/local/sbin/" . $specplatform['name'] . "resetbtn"); if ($retval == 99) { - /* user has pressed reset button for 2 seconds - + /* user has pressed reset button for 2 seconds - reset to factory defaults */ echo << 'generic-pc', 'descr' => gettext("Generic PC")); - - if ($g['platform'] == 'generic-pc-cdrom') + } + + if ($g['platform'] == 'generic-pc-cdrom') { return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)")); - + } + /* Try to guess from smbios strings */ unset($output); $_gb = exec('/bin/kenv smbios.system.product 2>/dev/null', $output); switch ($output[0]) { - case 'FW7541': - return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541')); - break; - case 'APU': - return (array('name' => 'APU', 'descr' => 'Netgate APU')); - break; - case 'RCC-VE': - return (array('name' => 'C2358', 'descr' => 'Netgate C2358')); - break; + case 'FW7541': + return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541')); + break; + case 'APU': + return (array('name' => 'APU', 'descr' => 'Netgate APU')); + break; + case 'RCC-VE': + return (array('name' => 'C2358', 'descr' => 'Netgate C2358')); + break; } /* the rest of the code only deals with 'embedded' platforms */ - if ($g['platform'] != 'nanobsd') + if ($g['platform'] != 'nanobsd') { return array('name' => $g['platform'], 'descr' => $g['platform']); + } $dmesg = get_single_sysctl('hw.model'); - if (strpos($dmesg, "PC Engines WRAP") !== false) + if (strpos($dmesg, "PC Engines WRAP") !== false) { return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP')); - - if (strpos($dmesg, "PC Engines ALIX") !== false) - return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX')); + } - if (preg_match("/Soekris net45../", $dmesg, $matches)) + if (strpos($dmesg, "PC Engines ALIX") !== false) { + return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX')); + } + + if (preg_match("/Soekris net45../", $dmesg, $matches)) { return array('name' => 'net45xx', 'descr' => $matches[0]); - - if (preg_match("/Soekris net48../", $dmesg, $matches)) + } + + if (preg_match("/Soekris net48../", $dmesg, $matches)) { return array('name' => 'net48xx', 'descr' => $matches[0]); - - if (preg_match("/Soekris net55../", $dmesg, $matches)) + } + + if (preg_match("/Soekris net55../", $dmesg, $matches)) { return array('name' => 'net55xx', 'descr' => $matches[0]); + } unset($dmesg); $dmesg_boot = system_get_dmesg_boot(); - if (strpos($dmesg_boot, "PC Engines ALIX") !== false) + if (strpos($dmesg_boot, "PC Engines ALIX") !== false) { return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX')); + } unset($dmesg_boot); /* unknown embedded platform */ @@ -2104,7 +2258,7 @@ function system_identify_specific_platform() { function system_get_dmesg_boot() { global $g; - + return file_get_contents("{$g['varlog_path']}/dmesg.boot"); } From 751533a2c8ee81b8db7a8435da1c321135b427f9 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Tue, 3 Mar 2015 00:39:50 +0545 Subject: [PATCH 150/257] Code style etc inc u --- etc/inc/unbound.inc | 189 ++++--- etc/inc/upgrade_config.inc | 992 ++++++++++++++++++++++--------------- etc/inc/util.inc | 709 +++++++++++++++----------- etc/inc/uuid.php | 8 +- 4 files changed, 1126 insertions(+), 772 deletions(-) diff --git a/etc/inc/unbound.inc b/etc/inc/unbound.inc index bbe802771c..bef0f4a794 100644 --- a/etc/inc/unbound.inc +++ b/etc/inc/unbound.inc @@ -55,7 +55,7 @@ function unbound_optimization() { $optimization_settings = array(); - /* + /* * Set the number of threads equal to number of CPUs. * Use 1 to disable threading, if for some reason this sysctl fails. */ @@ -95,8 +95,9 @@ function unbound_optimization() { } } // Safety check in case kern.ipc.maxsockbuf is not available. - if (!isset($optimization['so_rcvbuf'])) + if (!isset($optimization['so_rcvbuf'])) { $optimization['so_rcvbuf'] = "#so-rcvbuf: 4m"; + } return $optimization; @@ -112,8 +113,9 @@ function unbound_generate_config() { if (isset($config['unbound']['dnssec'])) { $module_config = "validator iterator"; $anchor_file = "auto-trust-anchor-file: {$g['unbound_chroot_path']}/root.key"; - } else + } else { $module_config = "iterator"; + } // Setup DNS Rebinding if (!isset($config['system']['webgui']['nodnsrebindcheck'])) { @@ -138,19 +140,22 @@ EOF; $bindints .= "interface: ::0\n"; $bindints .= "interface-automatic: yes\n"; } else { - foreach($active_interfaces as $ubif) { + foreach ($active_interfaces as $ubif) { if (is_ipaddr($ubif)) { - //$bindints .= "interface: $ubif\n"; -- until redmine #4062 is fixed, then uncomment this. + //$bindints .= "interface: $ubif\n"; -- until redmine #4062 is fixed, then uncomment this. } else { $intip = get_interface_ip($ubif); - if (is_ipaddrv4($intip)) + if (is_ipaddrv4($intip)) { $bindints .= "interface: $intip\n"; + } $intip = get_interface_ipv6($ubif); - if (is_ipaddrv6($intip)) - if (!is_linklocal($intip)) // skipping link local for the moment to not break people's configs: https://redmine.pfsense.org/issues/4062 + if (is_ipaddrv6($intip)) { + if (!is_linklocal($intip)) { // skipping link local for the moment to not break people's configs: https://redmine.pfsense.org/issues/4062 $bindints .= "interface: $intip\n"; + } + } } - } + } } } else { $bindints .= "interface: 0.0.0.0\n"; @@ -162,13 +167,15 @@ EOF; if (!empty($config['unbound']['outgoing_interface'])) { $outgoingints = "# Outgoing interfaces to be used\n"; $outgoing_interfaces = explode(",", $config['unbound']['outgoing_interface']); - foreach($outgoing_interfaces as $outif) { + foreach ($outgoing_interfaces as $outif) { $outip = get_interface_ip($outif); - if (!is_null($outip)) + if (!is_null($outip)) { $outgoingints .= "outgoing-interface: $outip\n"; + } $outip = get_interface_ipv6($outif); - if (!is_null($outip)) + if (!is_null($outip)) { $outgoingints .= "outgoing-interface: $outip\n"; + } } } @@ -197,8 +204,9 @@ EOF; if ($config['unbound']['custom_options']) { $custom_options_source = explode("\n", base64_decode($config['unbound']['custom_options'])); $custom_options = "# Unbound custom options\n"; - foreach ($custom_options_source as $ent) + foreach ($custom_options_source as $ent) { $custom_options .= $ent."\n"; + } } // Server configuration variables @@ -219,8 +227,9 @@ EOF; $infra_host_ttl = (!empty($config['unbound']['infra_host_ttl'])) ? $config['unbound']['infra_host_ttl'] : "900"; $infra_cache_numhosts = (!empty($config['unbound']['infra_cache_numhosts'])) ? $config['unbound']['infra_cache_numhosts'] : "10000"; $unwanted_reply_threshold = (!empty($config['unbound']['unwanted_reply_threshold'])) ? $config['unbound']['unwanted_reply_threshold'] : "0"; - if ($unwanted_reply_threshold == "disabled") + if ($unwanted_reply_threshold == "disabled") { $unwanted_reply_threshold = "0"; + } $msg_cache_size = (!empty($config['unbound']['msgcachesize'])) ? $config['unbound']['msgcachesize'] : "4"; $verbosity = isset($config['unbound']['log_verbosity']) ? $config['unbound']['log_verbosity'] : 1; $use_caps = isset($config['unbound']['use_caps']) ? "yes" : "no"; @@ -230,15 +239,17 @@ EOF; $dnsservers = array(); if (isset($config['system']['dnsallowoverride'])) { $ns = array_unique(get_nameservers()); - foreach($ns as $nameserver) { - if ($nameserver) + foreach ($ns as $nameserver) { + if ($nameserver) { $dnsservers[] = $nameserver; + } } } else { $ns = array_unique(get_dns_servers()); - foreach($ns as $nameserver) { - if ($nameserver) + foreach ($ns as $nameserver) { + if ($nameserver) { $dnsservers[] = $nameserver; + } } } @@ -249,11 +260,13 @@ forward-zone: name: "." EOD; - foreach($dnsservers as $dnsserver) + foreach ($dnsservers as $dnsserver) { $forward_conf .= "\tforward-addr: $dnsserver\n"; + } } - } else + } else { $forward_conf = ""; + } // Size of the RRset cache == 2 * msg-cache-size per Unbound's recommendations $rrset_cache_size = $msg_cache_size * 2; @@ -380,19 +393,22 @@ function read_hosts() { */ $etc_hosts = array(); foreach (file('/etc/hosts') as $line) { - if (strpos($line, "dhcpleases automatically entered")) + if (strpos($line, "dhcpleases automatically entered")) { break; + } $d = preg_split('/\s+/', $line, -1, PREG_SPLIT_NO_EMPTY); - if (empty($d) || substr(reset($d), 0, 1) == "#") + if (empty($d) || substr(reset($d), 0, 1) == "#") { continue; + } $ip = array_shift($d); $fqdn = array_shift($d); $name = array_shift($d); if (!empty($fqdn) && $fqdn != "empty") { - if (!empty($name) && $name != "empty") + if (!empty($name) && $name != "empty") { array_push($etc_hosts, array(ipaddr => "$ip", fqdn => "$fqdn", name => "$name")); - else + } else { array_push($etc_hosts, array(ipaddr => "$ip", fqdn => "$fqdn")); + } } } return $etc_hosts; @@ -409,26 +425,31 @@ function sync_unbound_service() { unbound_generate_config(); do_as_unbound_user("start"); require_once("service-utils.inc"); - if (is_service_running("unbound")) + if (is_service_running("unbound")) { do_as_unbound_user("restore_cache"); + } } function unbound_acl_id_used($id) { global $config; - if (is_array($config['unbound']['acls'])) - foreach($config['unbound']['acls'] as & $acls) - if ($id == $acls['aclid']) + if (is_array($config['unbound']['acls'])) { + foreach ($config['unbound']['acls'] as & $acls) { + if ($id == $acls['aclid']) { return true; + } + } + } return false; } function unbound_get_next_id() { $aclid = 0; - while(unbound_acl_id_used($aclid)) + while (unbound_acl_id_used($aclid)) { $aclid++; + } return $aclid; } @@ -437,23 +458,23 @@ function do_as_unbound_user($cmd) { global $g; switch ($cmd) { - case "start": - mwexec("/usr/local/sbin/unbound -c {$g['unbound_chroot_path']}/unbound.conf"); - break; - case "stop": - mwexec("echo '/usr/local/sbin/unbound-control stop' | /usr/bin/su -m unbound", true); - break; - case "reload": - mwexec("echo '/usr/local/sbin/unbound-control reload' | /usr/bin/su -m unbound", true); - break; - case "unbound-anchor": - mwexec("echo '/usr/local/sbin/unbound-anchor -a {$g['unbound_chroot_path']}/root.key' | /usr/bin/su -m unbound", true); - break; - case "unbound-control-setup": - mwexec("echo '/usr/local/sbin/unbound-control-setup -d {$g['unbound_chroot_path']}' | /usr/bin/su -m unbound", true); - break; - default: - break; + case "start": + mwexec("/usr/local/sbin/unbound -c {$g['unbound_chroot_path']}/unbound.conf"); + break; + case "stop": + mwexec("echo '/usr/local/sbin/unbound-control stop' | /usr/bin/su -m unbound", true); + break; + case "reload": + mwexec("echo '/usr/local/sbin/unbound-control reload' | /usr/bin/su -m unbound", true); + break; + case "unbound-anchor": + mwexec("echo '/usr/local/sbin/unbound-anchor -a {$g['unbound_chroot_path']}/root.key' | /usr/bin/su -m unbound", true); + break; + case "unbound-control-setup": + mwexec("echo '/usr/local/sbin/unbound-control-setup -d {$g['unbound_chroot_path']}' | /usr/bin/su -m unbound", true); + break; + default: + break; } } @@ -464,16 +485,17 @@ function unbound_add_domain_overrides($pvt_rev="") { $sorted_domains = msort($domains, "domain"); $result = array(); - foreach($sorted_domains as $domain) { + foreach ($sorted_domains as $domain) { $domain_key = current($domain); - if (!isset($result[$domain_key])) + if (!isset($result[$domain_key])) { $result[$domain_key] = array(); + } $result[$domain_key][] = $domain['ip']; } // Domain overrides that have multiple entries need multiple stub-addr: added $domain_entries = ""; - foreach($result as $domain=>$ips) { + foreach ($result as $domain=>$ips) { if ($pvt_rev == "private") { $domain_entries .= "private-domain: \"$domain\"\n"; $domain_entries .= "domain-insecure: \"$domain\"\n"; @@ -484,15 +506,16 @@ function unbound_add_domain_overrides($pvt_rev="") { } else { $domain_entries .= "stub-zone:\n"; $domain_entries .= "\tname: \"$domain\"\n"; - foreach($ips as $ip) + foreach ($ips as $ip) { $domain_entries .= "\tstub-addr: $ip\n"; + } $domain_entries .= "\tstub-prime: no\n"; } } - if ($pvt_rev != "") + if ($pvt_rev != "") { return $domain_entries; - else { + } else { create_unbound_chroot_path(); file_put_contents("{$g['unbound_chroot_path']}/domainoverrides.conf", $domain_entries); } @@ -506,20 +529,22 @@ function unbound_add_host_entries() { $hosts = read_hosts(); $added_ptr = array(); foreach ($hosts as $host) { - if (is_ipaddrv4($host['ipaddr'])) + if (is_ipaddrv4($host['ipaddr'])) { $type = 'A'; - else if (is_ipaddrv6($host['ipaddr'])) + } else if (is_ipaddrv6($host['ipaddr'])) { $type = 'AAAA'; - else + } else { continue; + } - if(!$added_ptr[$host['ipaddr']]) { + if (!$added_ptr[$host['ipaddr']]) { $unbound_entries .= "local-data-ptr: \"{$host['ipaddr']} {$host['fqdn']}\"\n"; $added_ptr[$host['ipaddr']] = true; } $unbound_entries .= "local-data: \"{$host['fqdn']} {$type} {$host['ipaddr']}\"\n"; - if (isset($host['name'])) + if (isset($host['name'])) { $unbound_entries .= "local-data: \"{$host['name']} {$type} {$host['ipaddr']}\"\n"; + } } // Write out entries @@ -539,28 +564,33 @@ function unbound_control($action) { case "start": // Start Unbound if ($config['unbound']['enable'] == "on") { - if (!is_service_running("unbound")) + if (!is_service_running("unbound")) { do_as_unbound_user("start"); + } } break; case "stop": - if ($config['unbound']['enable'] == "on") + if ($config['unbound']['enable'] == "on") { do_as_unbound_user("stop"); + } break; case "reload": - if ($config['unbound']['enable'] == "on") + if ($config['unbound']['enable'] == "on") { do_as_unbound_user("reload"); + } break; case "dump_cache": // Dump Unbound's Cache - if ($config['unbound']['dumpcache'] == "on") + if ($config['unbound']['dumpcache'] == "on") { do_as_unbound_user("dump_cache"); + } break; case "restore_cache": // Restore Unbound's Cache if ((is_service_running("unbound")) && ($config['unbound']['dumpcache'] == "on")) { - if (file_exists($cache_dumpfile) && filesize($cache_dumpfile) > 0) + if (file_exists($cache_dumpfile) && filesize($cache_dumpfile) > 0) { do_as_unbound_user("load_cache < /var/tmp/unbound_cache"); + } } break; default: @@ -576,10 +606,11 @@ function unbound_statistics() { if ($config['stats'] == "on") { $stats_interval = $config['unbound']['stats_interval']; $cumulative_stats = $config['cumulative_stats']; - if ($config['extended_stats'] == "on") + if ($config['extended_stats'] == "on") { $extended_stats = "yes"; - else + } else { $extended_stats = "no"; + } } else { $stats_interval = "0"; $cumulative_stats = "no"; @@ -607,13 +638,15 @@ function unbound_acls_config() { // Add our networks for active interfaces including localhost if (!empty($config['unbound']['active_interface'])) { $active_interfaces = array_flip(explode(",", $config['unbound']['active_interface'])); - if (in_array("all", $active_interfaces)) + if (in_array("all", $active_interfaces)) { $active_interfaces = get_configured_interface_with_descr(); - } else + } + } else { $active_interfaces = get_configured_interface_with_descr(); - + } + $bindints = ""; - foreach($active_interfaces as $ubif => $ifdesc) { + foreach ($active_interfaces as $ubif => $ifdesc) { $ifip = get_interface_ip($ubif); if (is_ipaddrv4($ifip)) { // IPv4 is handled via NAT networks below @@ -623,13 +656,14 @@ function unbound_acls_config() { if (!is_linklocal($ifip)) { $subnet_bits = get_interface_subnetv6($ubif); $subnet_ip = gen_subnetv6($ifip, $subnet_bits); - // only add LAN-type interfaces - if (!interface_has_gateway($ubif)) + // only add LAN-type interfaces + if (!interface_has_gateway($ubif)) { $aclcfg .= "access-control: {$subnet_ip}/{$subnet_bits} allow\n"; + } } // add for IPv6 static routes to local networks // for safety, we include only routes reachable on an interface with no - // gateway specified - read: not an Internet connection. + // gateway specified - read: not an Internet connection. $static_routes = get_staticroutes(); foreach ($static_routes as $route) { if ((lookup_gateway_interface_by_name($route['gateway']) == $ubif) && !interface_has_gateway($ubif)) { @@ -639,7 +673,7 @@ function unbound_acls_config() { } } } - + // Generate IPv4 access-control entries using the same logic as automatic outbound NAT if (empty($FilterIflist)) { filter_generate_optcfg_array(); @@ -647,17 +681,18 @@ function unbound_acls_config() { $natnetworks_array = array(); $natnetworks_array = filter_nat_rules_automatic_tonathosts(); foreach ($natnetworks_array as $allowednet) { - $aclcfg .= "access-control: $allowednet allow \n"; - } + $aclcfg .= "access-control: $allowednet allow \n"; + } } // Configure the custom ACLs if (is_array($config['unbound']['acls'])) { - foreach($config['unbound']['acls'] as $unbound_acl) { + foreach ($config['unbound']['acls'] as $unbound_acl) { $aclcfg .= "#{$unbound_acl['aclname']}\n"; - foreach($unbound_acl['row'] as $network) { - if ($unbound_acl['aclaction'] == "allow snoop") + foreach ($unbound_acl['row'] as $network) { + if ($unbound_acl['aclaction'] == "allow snoop") { $unbound_acl['aclaction'] = "allow_snoop"; + } $aclcfg .= "access-control: {$network['acl_network']}/{$network['mask']} {$unbound_acl['aclaction']}\n"; } } diff --git a/etc/inc/upgrade_config.inc b/etc/inc/upgrade_config.inc index be70d73927..89bef330a9 100644 --- a/etc/inc/upgrade_config.inc +++ b/etc/inc/upgrade_config.inc @@ -35,8 +35,9 @@ pfSense_MODULE: config */ -if(!function_exists("dump_rrd_to_xml")) +if (!function_exists("dump_rrd_to_xml")) { require("rrd.inc"); +} /* Upgrade functions must be named: * upgrade_XXX_to_YYY @@ -107,9 +108,9 @@ function upgrade_010_to_011() { $fr = &$config['filter']['rule'][$i]; /* remap interface */ - if (array_key_exists($fr['interface'], $ifmap)) + if (array_key_exists($fr['interface'], $ifmap)) { $fr['interface'] = $ifmap[$fr['interface']]; - else { + } else { /* remove the rule */ printf(gettext("%sWarning: filter rule removed " . "(interface '%s' does not exist anymore)."), "\n", $fr['interface']); @@ -119,9 +120,9 @@ function upgrade_010_to_011() { /* remap source network */ if (isset($fr['source']['network'])) { - if (array_key_exists($fr['source']['network'], $ifmap)) + if (array_key_exists($fr['source']['network'], $ifmap)) { $fr['source']['network'] = $ifmap[$fr['source']['network']]; - else { + } else { /* remove the rule */ printf(gettext("%sWarning: filter rule removed " . "(source network '%s' does not exist anymore)."), "\n", $fr['source']['network']); @@ -132,9 +133,9 @@ function upgrade_010_to_011() { /* remap destination network */ if (isset($fr['destination']['network'])) { - if (array_key_exists($fr['destination']['network'], $ifmap)) + if (array_key_exists($fr['destination']['network'], $ifmap)) { $fr['destination']['network'] = $ifmap[$fr['destination']['network']]; - else { + } else { /* remove the rule */ printf(gettext("%sWarning: filter rule removed " . "(destination network '%s' does not exist anymore)."), "\n", $fr['destination']['network']); @@ -146,45 +147,46 @@ function upgrade_010_to_011() { /* convert shaper rules */ $n = count($config['pfqueueing']['rule']); - if (is_array($config['pfqueueing']['rule'])) - for ($i = 0; $i < $n; $i++) { + if (is_array($config['pfqueueing']['rule'])) { + for ($i = 0; $i < $n; $i++) { - $fr = &$config['pfqueueing']['rule'][$i]; + $fr = &$config['pfqueueing']['rule'][$i]; - /* remap interface */ - if (array_key_exists($fr['interface'], $ifmap)) - $fr['interface'] = $ifmap[$fr['interface']]; - else { - /* remove the rule */ - printf(gettext("%sWarning: traffic shaper rule removed " . - "(interface '%s' does not exist anymore)."), "\n", $fr['interface']); - unset($config['pfqueueing']['rule'][$i]); - continue; - } - - /* remap source network */ - if (isset($fr['source']['network'])) { - if (array_key_exists($fr['source']['network'], $ifmap)) - $fr['source']['network'] = $ifmap[$fr['source']['network']]; - else { + /* remap interface */ + if (array_key_exists($fr['interface'], $ifmap)) { + $fr['interface'] = $ifmap[$fr['interface']]; + } else { /* remove the rule */ printf(gettext("%sWarning: traffic shaper rule removed " . - "(source network '%s' does not exist anymore)."), "\n", $fr['source']['network']); + "(interface '%s' does not exist anymore)."), "\n", $fr['interface']); unset($config['pfqueueing']['rule'][$i]); continue; } - } - /* remap destination network */ - if (isset($fr['destination']['network'])) { - if (array_key_exists($fr['destination']['network'], $ifmap)) - $fr['destination']['network'] = $ifmap[$fr['destination']['network']]; - else { - /* remove the rule */ - printf(gettext("%sWarning: traffic shaper rule removed " . - "(destination network '%s' does not exist anymore)."), "\n", $fr['destination']['network']); - unset($config['pfqueueing']['rule'][$i]); - continue; + /* remap source network */ + if (isset($fr['source']['network'])) { + if (array_key_exists($fr['source']['network'], $ifmap)) { + $fr['source']['network'] = $ifmap[$fr['source']['network']]; + } else { + /* remove the rule */ + printf(gettext("%sWarning: traffic shaper rule removed " . + "(source network '%s' does not exist anymore)."), "\n", $fr['source']['network']); + unset($config['pfqueueing']['rule'][$i]); + continue; + } + } + + /* remap destination network */ + if (isset($fr['destination']['network'])) { + if (array_key_exists($fr['destination']['network'], $ifmap)) { + $fr['destination']['network'] = $ifmap[$fr['destination']['network']]; + } else { + /* remove the rule */ + printf(gettext("%sWarning: traffic shaper rule removed " . + "(destination network '%s' does not exist anymore)."), "\n", $fr['destination']['network']); + unset($config['pfqueueing']['rule'][$i]); + continue; + } } } } @@ -252,20 +254,25 @@ function upgrade_013_to_014() { function upgrade_014_to_015() { global $config; /* Default route moved */ - if (isset($config['interfaces']['wan']['gateway'])) - if ($config['interfaces']['wan']['gateway'] <> "") + if (isset($config['interfaces']['wan']['gateway'])) { + if ($config['interfaces']['wan']['gateway'] <> "") { $config['system']['gateway'] = $config['interfaces']['wan']['gateway']; + } + } unset($config['interfaces']['wan']['gateway']); /* Queues are no longer interface specific */ - if (isset($config['interfaces']['lan']['schedulertype'])) + if (isset($config['interfaces']['lan']['schedulertype'])) { unset($config['interfaces']['lan']['schedulertype']); - if (isset($config['interfaces']['wan']['schedulertype'])) + } + if (isset($config['interfaces']['wan']['schedulertype'])) { unset($config['interfaces']['wan']['schedulertype']); + } for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) { - if(isset($config['interfaces']['opt' . $i]['schedulertype'])) + if (isset($config['interfaces']['opt' . $i]['schedulertype'])) { unset($config['interfaces']['opt' . $i]['schedulertype']); + } } } @@ -300,9 +307,9 @@ function upgrade_016_to_017() { function upgrade_017_to_018() { global $config; - if(isset($config['proxyarp']) && is_array($config['proxyarp']['proxyarpnet'])) { + if (isset($config['proxyarp']) && is_array($config['proxyarp']['proxyarpnet'])) { $proxyarp = &$config['proxyarp']['proxyarpnet']; - foreach($proxyarp as $arpent){ + foreach ($proxyarp as $arpent) { $vip = array(); $vip['mode'] = "proxyarp"; $vip['interface'] = $arpent['interface']; @@ -325,9 +332,9 @@ function upgrade_017_to_018() { } unset($config['proxyarp']); } - if(isset($config['installedpackages']) && isset($config['installedpackages']['carp']) && is_array($config['installedpackages']['carp']['config'])) { + if (isset($config['installedpackages']) && isset($config['installedpackages']['carp']) && is_array($config['installedpackages']['carp']['config'])) { $carp = &$config['installedpackages']['carp']['config']; - foreach($carp as $carpent){ + foreach ($carp as $carpent) { $vip = array(); $vip['mode'] = "carp"; $vip['interface'] = "AUTO"; @@ -360,7 +367,7 @@ function upgrade_018_to_019() { function upgrade_019_to_020() { global $config; - if(is_array($config['ipsec']['tunnel'])) { + if (is_array($config['ipsec']['tunnel'])) { reset($config['ipsec']['tunnel']); while (list($index, $tunnel) = each($config['ipsec']['tunnel'])) { /* Sanity check on required variables */ @@ -375,7 +382,7 @@ function upgrade_019_to_020() { function upgrade_020_to_021() { global $config; /* shaper scheduler moved */ - if(isset($config['system']['schedulertype'])) { + if (isset($config['system']['schedulertype'])) { $config['shaper']['schedulertype'] = $config['system']['schedulertype']; unset($config['system']['schedulertype']); } @@ -390,7 +397,7 @@ function upgrade_021_to_022() { function upgrade_022_to_023() { global $config; - if(isset($config['shaper'])) { + if (isset($config['shaper'])) { /* wipe previous shaper configuration */ unset($config['shaper']); } @@ -627,7 +634,7 @@ function upgrade_039_to_040() { function upgrade_040_to_041() { global $config; - if(!$config['sysctl']) { + if (!$config['sysctl']) { $config['sysctl']['item'] = array(); $config['sysctl']['item'][0]['tunable'] = "net.inet.tcp.blackhole"; @@ -720,10 +727,12 @@ function upgrade_040_to_041() { function upgrade_041_to_042() { global $config; - if (isset($config['shaper'])) + if (isset($config['shaper'])) { unset($config['shaper']); - if (isset($config['ezshaper'])) + } + if (isset($config['ezshaper'])) { unset($config['ezshaper']); + } } @@ -733,12 +742,12 @@ function upgrade_042_to_043() { $iflist = get_configured_interface_list(false, true); $gateways = array(); $i = 0; - foreach($iflist as $ifname => $interface) { - if(! interface_has_gateway($ifname)) { + foreach ($iflist as $ifname => $interface) { + if (! interface_has_gateway($ifname)) { continue; } $config['gateways']['gateway_item'][$i] = array(); - if(is_ipaddr($config['interfaces'][$ifname]['gateway'])) { + if (is_ipaddr($config['interfaces'][$ifname]['gateway'])) { $config['gateways']['gateway_item'][$i]['gateway'] = $config['interfaces'][$ifname]['gateway']; $config['gateways']['gateway_item'][$i]['descr'] = sprintf(gettext("Interface %s Static Gateway"), $ifname); } else { @@ -748,10 +757,10 @@ function upgrade_042_to_043() { $config['gateways']['gateway_item'][$i]['interface'] = $ifname; $config['gateways']['gateway_item'][$i]['name'] = "GW_" . strtoupper($ifname); /* add default gateway bit for wan on upgrade */ - if($ifname == "wan") { + if ($ifname == "wan") { $config['gateways']['gateway_item'][$i]['defaultgw'] = true; } - if(is_ipaddr($config['interfaces'][$ifname]['use_rrd_gateway'])) { + if (is_ipaddr($config['interfaces'][$ifname]['use_rrd_gateway'])) { $config['gateways']['gateway_item'][$i]['monitor'] = $config['interfaces'][$ifname]['use_rrd_gateway']; unset($config['interfaces'][$ifname]['use_rrd_gateway']); } @@ -759,12 +768,13 @@ function upgrade_042_to_043() { /* Update all filter rules which might reference this gateway */ $j = 0; - foreach($config['filter']['rule'] as $rule) { - if(is_ipaddr($rule['gateway'])) { - if ($rule['gateway'] == $config['gateways']['gateway_item'][$i]['gateway']) + foreach ($config['filter']['rule'] as $rule) { + if (is_ipaddr($rule['gateway'])) { + if ($rule['gateway'] == $config['gateways']['gateway_item'][$i]['gateway']) { $config['filter']['rule'][$j]['gateway'] = $config['gateways']['gateway_item'][$i]['name']; - else if ($rule['gateway'] == $ifname) + } else if ($rule['gateway'] == $ifname) { $config['filter']['rule'][$j]['gateway'] = $config['gateways']['gateway_item'][$i]['name']; + } } $j++; } @@ -772,7 +782,7 @@ function upgrade_042_to_043() { /* rename old Quality RRD files in the process */ $rrddbpath = "/var/db/rrd"; $gwname = "GW_" . strtoupper($ifname); - if(is_readable("{$rrddbpath}/{$ifname}-quality.rrd")) { + if (is_readable("{$rrddbpath}/{$ifname}-quality.rrd")) { rename("{$rrddbpath}/{$ifname}-quality.rrd", "{$rrddbpath}/{$gwname}-quality.rrd"); } $i++; @@ -797,7 +807,7 @@ function upgrade_043_to_044() { break; } } - if($gwmap[$sroute['gateway']]) { + if ($gwmap[$sroute['gateway']]) { /* We already added a gateway name for this IP */ $config['staticroutes']['route'][$idx]['gateway'] = "{$gwmap[$sroute['gateway']]}"; $found = true; @@ -810,8 +820,9 @@ function upgrade_043_to_044() { $gateway['gateway'] = $sroute['gateway']; $gateway['interface'] = $sroute['interface']; $gateway['descr'] = sprintf(gettext("Upgraded static route for %s"), $sroute['network']); - if (!is_array($config['gateways']['gateway_item'])) + if (!is_array($config['gateways']['gateway_item'])) { $config['gateways']['gateway_item'] = array(); + } $config['gateways']['gateway_item'][] = $gateway; $config['staticroutes']['route'][$idx]['gateway'] = $gateway['name']; $i++; @@ -829,8 +840,8 @@ function upgrade_044_to_045() { foreach ($config['vlans']['vlan'] as $id => $vlan) { /* Make sure to update the interfaces section with the right name */ $vlan_name = "{$vlan['if']}_vlan{$vlan['tag']}"; - foreach($iflist as $ifname) { - if($config['interfaces'][$ifname]['if'] == "vlan{$i}") { + foreach ($iflist as $ifname) { + if ($config['interfaces'][$ifname]['if'] == "vlan{$i}") { $config['interfaces'][$ifname]['if'] = $vlan_name; continue; } @@ -847,39 +858,39 @@ function upgrade_045_to_046() { /* Load up monitors that are in the default config for 2.0 but not in 1.2.3 thus wouldn't be in an upgraded config. */ $config['load_balancer']['monitor_type'] = array ( - array ( 'name' => 'ICMP', + array ('name' => 'ICMP', 'type' => 'icmp', 'descr' => 'ICMP', 'options' => '', ), - array ( 'name' => 'TCP', + array ('name' => 'TCP', 'type' => 'tcp', 'descr' => 'Generic TCP', 'options' => '', ), - array ( 'name' => 'HTTP', + array ('name' => 'HTTP', 'type' => 'http', 'descr' => 'Generic HTTP', 'options' => - array ( 'path' => '/', + array ('path' => '/', 'host' => '', 'code' => '200', ), ), - array ( 'name' => 'HTTPS', + array ('name' => 'HTTPS', 'type' => 'https', 'descr' => 'Generic HTTPS', 'options' => - array ( 'path' => '/', + array ('path' => '/', 'host' => '', 'code' => '200', ), ), - array ( 'name' => 'SMTP', + array ('name' => 'SMTP', 'type' => 'send', 'descr' => 'Generic SMTP', 'options' => - array ( 'send' => '', + array ('send' => '', 'expect' => '220 *', ), ), @@ -890,9 +901,9 @@ function upgrade_045_to_046() { $pool_a = &$config['load_balancer']['lbpool']; $pools = array(); /* Index pools by name */ - if(is_array($pool_a)) { + if (is_array($pool_a)) { for ($i = 0; isset($pool_a[$i]); $i++) { - if($pool_a[$i]['type'] == "server") { + if ($pool_a[$i]['type'] == "server") { $pools[$pool_a[$i]['name']] = $pool_a[$i]; } } @@ -907,8 +918,9 @@ function upgrade_045_to_046() { $pool['behaviour'] = 'balance'; $pool['name'] = "{$vs_a[$i]['name']}-sitedown"; $pool['descr'] = sprintf(gettext("Sitedown pool for VS: %s"), $vs_a[$i]['name']); - if (is_array($vs_a[$i]['pool'])) + if (is_array($vs_a[$i]['pool'])) { $vs_a[$i]['pool'] = $vs_a[$i]['pool'][0]; + } $pool['port'] = $pools[$vs_a[$i]['pool']]['port']; $pool['servers'] = array(); $pool['servers'][] = $vs_a[$i]['sitedown']; @@ -918,7 +930,7 @@ function upgrade_045_to_046() { } } } - if(count($config['load_balancer']) == 0) { + if (count($config['load_balancer']) == 0) { unset($config['load_balancer']); } mwexec('/usr/sbin/pw groupadd -n _relayd -g 913'); @@ -930,7 +942,7 @@ function upgrade_046_to_047() { global $config; /* Upgrade IPsec from tunnel to phase1/phase2 */ - if(is_array($config['ipsec']['tunnel'])) { + if (is_array($config['ipsec']['tunnel'])) { $a_phase1 = array(); $a_phase2 = array(); @@ -960,7 +972,7 @@ function upgrade_046_to_047() { /* none found, create a new one */ - if (!isset( $ph1ent )) { + if (!isset($ph1ent)) { /* build new phase1 entry */ @@ -968,11 +980,12 @@ function upgrade_046_to_047() { $ph1ent['ikeid'] = ++$ikeid; - if (isset($tunnel['disabled'])) + if (isset($tunnel['disabled'])) { $ph1ent['disabled'] = $tunnel['disabled']; + } /* convert to the new vip[$vhid] name */ - if(preg_match("/^carp/", $tunnel['interface'])) { + if (preg_match("/^carp/", $tunnel['interface'])) { $carpid = str_replace("carp", "", $tunnel['interface']); $tunnel['interface'] = "vip" . $config['virtualip']['vip'][$carpid]['vhid']; } @@ -982,8 +995,9 @@ function upgrade_046_to_047() { $ph1ent['mode'] = $tunnel['p1']['mode']; - if (isset($tunnel['p1']['myident']['myaddress'])) + if (isset($tunnel['p1']['myident']['myaddress'])) { $ph1ent['myid_type'] = "myaddress"; + } if (isset($tunnel['p1']['myident']['address'])) { $ph1ent['myid_type'] = "address"; $ph1ent['myid_data'] = $tunnel['p1']['myident']['address']; @@ -1009,24 +1023,24 @@ function upgrade_046_to_047() { switch ($tunnel['p1']['encryption-algorithm']) { case "des": - $ph1alg = array( 'name' => 'des' ); - break; + $ph1alg = array('name' => 'des'); + break; case "3des": - $ph1alg = array( 'name' => '3des' ); - break; + $ph1alg = array('name' => '3des'); + break; case "blowfish": - $ph1alg = array( 'name' => 'blowfish', 'keylen' => '128' ); - break; + $ph1alg = array('name' => 'blowfish', 'keylen' => '128'); + break; case "cast128": - $ph1alg = array( 'name' => 'cast128' ); - break; + $ph1alg = array('name' => 'cast128'); + break; case "rijndael": - $ph1alg = array( 'name' => 'aes', 'keylen' => '128' ); - break; + $ph1alg = array('name' => 'aes', 'keylen' => '128'); + break; case "rijndael 256": case "aes 256": - $ph1alg = array( 'name' => 'aes', 'keylen' => '256' ); - break; + $ph1alg = array('name' => 'aes', 'keylen' => '256'); + break; } $ph1ent['encryption-algorithm'] = $ph1alg; @@ -1035,14 +1049,18 @@ function upgrade_046_to_047() { $ph1ent['lifetime'] = $tunnel['p1']['lifetime']; $ph1ent['authentication_method'] = $tunnel['p1']['authentication_method']; - if (isset($tunnel['p1']['pre-shared-key'])) + if (isset($tunnel['p1']['pre-shared-key'])) { $ph1ent['pre-shared-key'] = $tunnel['p1']['pre-shared-key']; - if (isset($tunnel['p1']['cert'])) + } + if (isset($tunnel['p1']['cert'])) { $ph1ent['cert'] = $tunnel['p1']['cert']; - if (isset($tunnel['p1']['peercert'])) + } + if (isset($tunnel['p1']['peercert'])) { $ph1ent['peercert'] = $tunnel['p1']['peercert']; - if (isset($tunnel['p1']['private-key'])) + } + if (isset($tunnel['p1']['private-key'])) { $ph1ent['private-key'] = $tunnel['p1']['private-key']; + } $ph1ent['nat_traversal'] = "on"; $ph1ent['dpd_enable'] = 1; @@ -1058,32 +1076,35 @@ function upgrade_046_to_047() { $ph2ent['ikeid'] = $ph1ent['ikeid']; - if (isset($tunnel['disabled'])) + if (isset($tunnel['disabled'])) { $ph1ent['disabled'] = $tunnel['disabled']; + } $ph2ent['descr'] = sprintf(gettext("phase2 for %s"), $tunnel['descr']); $type = "lan"; - if ($tunnel['local-subnet']['network']) + if ($tunnel['local-subnet']['network']) { $type = $tunnel['local-subnet']['network']; + } if ($tunnel['local-subnet']['address']) { list($address,$netbits) = explode("/",$tunnel['local-subnet']['address']); - if (is_null($netbits)) + if (is_null($netbits)) { $type = "address"; - else + } else { $type = "network"; + } } switch ($type) { case "address": - $ph2ent['localid'] = array('type' => $type,'address' => $address); - break; + $ph2ent['localid'] = array('type' => $type,'address' => $address); + break; case "network": - $ph2ent['localid'] = array('type' => $type,'address' => $address,'netbits' => $netbits); - break; + $ph2ent['localid'] = array('type' => $type,'address' => $address,'netbits' => $netbits); + break; default: - $ph2ent['localid'] = array('type' => $type); - break; + $ph2ent['localid'] = array('type' => $type); + break; } list($address,$netbits) = explode("/",$tunnel['remote-subnet']); @@ -1092,40 +1113,42 @@ function upgrade_046_to_047() { $ph2ent['protocol'] = $tunnel['p2']['protocol']; $aes_count = 0; - foreach( $tunnel['p2']['encryption-algorithm-option'] as $tunalg ) { + foreach ($tunnel['p2']['encryption-algorithm-option'] as $tunalg) { $aes_found = false; switch ($tunalg) { case "des": - $ph2alg = array( 'name' => 'des' ); - break; + $ph2alg = array('name' => 'des'); + break; case "3des": - $ph2alg = array( 'name' => '3des' ); - break; + $ph2alg = array('name' => '3des'); + break; case "blowfish": - $ph2alg = array( 'name' => 'blowfish', 'keylen' => 'auto' ); - break; + $ph2alg = array('name' => 'blowfish', 'keylen' => 'auto'); + break; case "cast128": - $ph2alg = array( 'name' => 'cast128' ); - break; + $ph2alg = array('name' => 'cast128'); + break; case "rijndael": case "rijndael 256": case "aes 256": - $ph2alg = array( 'name' => 'aes', 'keylen' => 'auto' ); - $aes_found = true; - $aes_count++; - break; + $ph2alg = array('name' => 'aes', 'keylen' => 'auto'); + $aes_found = true; + $aes_count++; + break; } - if( !$aes_found || ($aes_count < 2)) + if (!$aes_found || ($aes_count < 2)) { $ph2ent['encryption-algorithm-option'][] = $ph2alg; + } } $ph2ent['hash-algorithm-option'] = $tunnel['p2']['hash-algorithm-option']; $ph2ent['pfsgroup'] = $tunnel['p2']['pfsgroup']; $ph2ent['lifetime'] = $tunnel['p2']['lifetime']; - if (isset($tunnel['pinghost']['pinghost'])) + if (isset($tunnel['pinghost']['pinghost'])) { $ph2ent['pinghost'] = $tunnel['pinghost']; + } $a_phase2[] = $ph2ent; } @@ -1136,10 +1159,10 @@ function upgrade_046_to_047() { } /* Upgrade Mobile IPsec */ - if (isset($config['ipsec']['mobileclients']) - && is_array($config['ipsec']['mobileclients']) - && is_array($config['ipsec']['mobileclients']['p1']) - && is_array($config['ipsec']['mobileclients']['p2'])) { + if (isset($config['ipsec']['mobileclients']) && + is_array($config['ipsec']['mobileclients']) && + is_array($config['ipsec']['mobileclients']['p1']) && + is_array($config['ipsec']['mobileclients']['p2'])) { if (isset($config['ipsec']['mobileclients']['enable'])) { $config['ipsec']['client']['enable'] = true; @@ -1152,16 +1175,18 @@ function upgrade_046_to_047() { $ph1ent = array(); $ph1ent['ikeid'] = ++$ikeid; - if (!isset($mobilecfg['enable'])) + if (!isset($mobilecfg['enable'])) { $ph1ent['disabled'] = true; + } /* Assume WAN since mobile tunnels couldn't be on a separate interface on 1.2.x */ $ph1ent['interface'] = 'wan'; $ph1ent['descr'] = "Mobile Clients (upgraded)"; $ph1ent['mode'] = $mobilecfg['p1']['mode']; - if (isset($mobilecfg['p1']['myident']['myaddress'])) + if (isset($mobilecfg['p1']['myident']['myaddress'])) { $ph1ent['myid_type'] = "myaddress"; + } if (isset($mobilecfg['p1']['myident']['address'])) { $ph1ent['myid_type'] = "address"; $ph1ent['myid_data'] = $mobilecfg['p1']['myident']['address']; @@ -1187,24 +1212,24 @@ function upgrade_046_to_047() { switch ($mobilecfg['p1']['encryption-algorithm']) { case "des": - $ph1alg = array( 'name' => 'des' ); - break; + $ph1alg = array('name' => 'des'); + break; case "3des": - $ph1alg = array( 'name' => '3des' ); - break; + $ph1alg = array('name' => '3des'); + break; case "blowfish": - $ph1alg = array( 'name' => 'blowfish', 'keylen' => '128' ); - break; + $ph1alg = array('name' => 'blowfish', 'keylen' => '128'); + break; case "cast128": - $ph1alg = array( 'name' => 'cast128' ); - break; + $ph1alg = array('name' => 'cast128'); + break; case "rijndael": - $ph1alg = array( 'name' => 'aes', 'keylen' => '128' ); - break; + $ph1alg = array('name' => 'aes', 'keylen' => '128'); + break; case "rijndael 256": case "aes 256": - $ph1alg = array( 'name' => 'aes', 'keylen' => '256' ); - break; + $ph1alg = array('name' => 'aes', 'keylen' => '256'); + break; } $ph1ent['encryption-algorithm'] = $ph1alg; @@ -1213,12 +1238,15 @@ function upgrade_046_to_047() { $ph1ent['lifetime'] = $mobilecfg['p1']['lifetime']; $ph1ent['authentication_method'] = $mobilecfg['p1']['authentication_method']; - if (isset($mobilecfg['p1']['cert'])) + if (isset($mobilecfg['p1']['cert'])) { $ph1ent['cert'] = $mobilecfg['p1']['cert']; - if (isset($mobilecfg['p1']['peercert'])) + } + if (isset($mobilecfg['p1']['peercert'])) { $ph1ent['peercert'] = $mobilecfg['p1']['peercert']; - if (isset($mobilecfg['p1']['private-key'])) + } + if (isset($mobilecfg['p1']['private-key'])) { $ph1ent['private-key'] = $mobilecfg['p1']['private-key']; + } $ph1ent['nat_traversal'] = "on"; $ph1ent['dpd_enable'] = 1; @@ -1234,32 +1262,33 @@ function upgrade_046_to_047() { $ph2ent['protocol'] = $mobilecfg['p2']['protocol']; $aes_count = 0; - foreach( $mobilecfg['p2']['encryption-algorithm-option'] as $tunalg ) { + foreach ($mobilecfg['p2']['encryption-algorithm-option'] as $tunalg) { $aes_found = false; switch ($tunalg) { case "des": - $ph2alg = array( 'name' => 'des' ); - break; + $ph2alg = array('name' => 'des'); + break; case "3des": - $ph2alg = array( 'name' => '3des' ); - break; + $ph2alg = array('name' => '3des'); + break; case "blowfish": - $ph2alg = array( 'name' => 'blowfish', 'keylen' => 'auto' ); - break; + $ph2alg = array('name' => 'blowfish', 'keylen' => 'auto'); + break; case "cast128": - $ph2alg = array( 'name' => 'cast128' ); - break; + $ph2alg = array('name' => 'cast128'); + break; case "rijndael": case "rijndael 256": case "aes 256": - $ph2alg = array( 'name' => 'aes', 'keylen' => 'auto' ); - $aes_found = true; - $aes_count++; - break; + $ph2alg = array('name' => 'aes', 'keylen' => 'auto'); + $aes_found = true; + $aes_count++; + break; } - if( !$aes_found || ($aes_count < 2)) + if (!$aes_found || ($aes_count < 2)) { $ph2ent['encryption-algorithm-option'][] = $ph2alg; + } } $ph2ent['hash-algorithm-option'] = $mobilecfg['p2']['hash-algorithm-option']; $ph2ent['pfsgroup'] = $mobilecfg['p2']['pfsgroup']; @@ -1278,7 +1307,7 @@ function upgrade_047_to_048() { if (!empty($config['dyndns'])) { $config['dyndnses'] = array(); $config['dyndnses']['dyndns'] = array(); - if(isset($config['dyndns'][0]['host'])) { + if (isset($config['dyndns'][0]['host'])) { $tempdyn = array(); $tempdyn['enable'] = isset($config['dyndns'][0]['enable']); $tempdyn['type'] = $config['dyndns'][0]['type']; @@ -1295,10 +1324,12 @@ function upgrade_047_to_048() { } if (!empty($config['dnsupdate'])) { $pconfig = $config['dnsupdate'][0]; - if (!$pconfig['ttl']) + if (!$pconfig['ttl']) { $pconfig['ttl'] = 60; - if (!$pconfig['keytype']) + } + if (!$pconfig['keytype']) { $pconfig['keytype'] = "zone"; + } $pconfig['interface'] = "wan"; $config['dnsupdates']['dnsupdate'][] = $pconfig; unset($config['dnsupdate']); @@ -1329,7 +1360,7 @@ function upgrade_047_to_048() { $config['interfaces']['wan']['pptp_username'] = $pconfig['username']; $config['interfaces']['wan']['pptp_password'] = $pconfig['password']; $config['interfaces']['wan']['provider'] = $pconfig['provider']; - $config['interfaces']['wan']['ondemand'] = isset($pconfig['ondemand'] ); + $config['interfaces']['wan']['ondemand'] = isset($pconfig['ondemand']); $config['interfaces']['wan']['timeout'] = $pconfig['timeout']; } } @@ -1345,26 +1376,30 @@ function upgrade_048_to_049() { $all['gid'] = 1998; $all['member'] = array(); - if (!is_array($config['system']['user'])) + if (!is_array($config['system']['user'])) { $config['system']['user'] = array(); - if (!is_array($config['system']['group'])) + } + if (!is_array($config['system']['group'])) { $config['system']['group'] = array(); + } /* work around broken uid assignments */ $config['system']['nextuid'] = 2000; foreach ($config['system']['user'] as & $user) { - if (isset($user['uid']) && !$user['uid']) + if (isset($user['uid']) && !$user['uid']) { continue; + } $user['uid'] = $config['system']['nextuid']++; } /* work around broken gid assignments */ $config['system']['nextgid'] = 2000; foreach ($config['system']['group'] as & $group) { - if ($group['name'] == $g['admin_group']) + if ($group['name'] == $g['admin_group']) { $group['gid'] = 1999; - else + } else { $group['gid'] = $config['system']['nextgid']++; + } } /* build group membership information */ @@ -1372,8 +1407,9 @@ function upgrade_048_to_049() { $group['member'] = array(); foreach ($config['system']['user'] as & $user) { $groupnames = explode(",", $user['groupname']); - if (in_array($group['name'],$groupnames)) + if (in_array($group['name'],$groupnames)) { $group['member'][] = $user['uid']; + } } } @@ -1384,9 +1420,11 @@ function upgrade_048_to_049() { } /* reset group scope information */ - foreach ($config['system']['group'] as & $group) - if ($group['name'] != $g['admin_group']) - $group['scope'] = "user"; + foreach ($config['system']['group'] as & $group) { + if ($group['name'] != $g['admin_group']) { + $group['scope'] = "user"; + } + } /* insert new all group */ $groups = Array(); @@ -1399,8 +1437,9 @@ function upgrade_048_to_049() { function upgrade_049_to_050() { global $config; - if (!is_array($config['system']['user'])) + if (!is_array($config['system']['user'])) { $config['system']['user'] = array(); + } /* update user privileges */ foreach ($config['system']['user'] as & $user) { $privs = array(); @@ -1409,13 +1448,13 @@ function upgrade_049_to_050() { continue; } foreach ($user['priv'] as $priv) { - switch($priv['id']) { + switch ($priv['id']) { case "hasshell": - $privs[] = "user-shell-access"; - break; + $privs[] = "user-shell-access"; + break; case "copyfiles": - $privs[] = "user-copy-files"; - break; + $privs[] = "user-copy-files"; + break; } } $user['priv'] = $privs; @@ -1430,8 +1469,9 @@ function upgrade_049_to_050() { } foreach ($group['pages'] as $page) { $priv = map_page_privname($page); - if ($priv) + if ($priv) { $privs[] = $priv; + } } unset($group['pages']); $group['priv'] = $privs; @@ -1458,7 +1498,7 @@ function upgrade_050_to_051() { unset($config['bridge']); $convert_bridges = false; - foreach($config['interfaces'] as $intf) { + foreach ($config['interfaces'] as $intf) { if (isset($intf['bridge']) && $intf['bridge'] <> "") { $config['bridges'] = array(); $config['bridges']['bridged'] = array(); @@ -1486,10 +1526,12 @@ function upgrade_050_to_051() { function upgrade_051_to_052() { global $config; $config['openvpn'] = array(); - if (!is_array($config['ca'])) + if (!is_array($config['ca'])) { $config['ca'] = array(); - if (!is_array($config['cert'])) + } + if (!is_array($config['cert'])) { $config['cert'] = array(); + } $vpnid = 1; @@ -1498,10 +1540,11 @@ function upgrade_051_to_052() { $config['openvpn']['openvpn-server'] = array(); $index = 1; - foreach($config['installedpackages']['openvpnserver']['config'] as $server) { + foreach ($config['installedpackages']['openvpnserver']['config'] as $server) { - if (!is_array($server)) + if (!is_array($server)) { continue; + } if ($server['auth_method'] == "pki") { @@ -1523,8 +1566,9 @@ function upgrade_051_to_052() { $crl['descr'] = "Imported OpenVPN CRL #{$index}"; $crl['caref'] = $ca['refid']; $crl['text'] = $server['crl'][0]; - if(!is_array($config['crl'])) + if (!is_array($config['crl'])) { $config['crl'] = array(); + } $config['crl'][] = $crl; $server['crlref'] = $crl['refid']; } @@ -1548,7 +1592,7 @@ function upgrade_051_to_052() { /* determine operational mode */ if ($server['auth_method'] == 'pki') { - if($server['nopool']) { + if ($server['nopool']) { $server['mode'] = "p2p_tls"; } else { $server['mode'] = "server_tls"; @@ -1561,18 +1605,20 @@ function upgrade_051_to_052() { /* modify configuration values */ $server['dh_length'] = 1024; unset($server['dh_params']); - if (!$server['interface']) + if (!$server['interface']) { $server['interface'] = 'any'; + } $server['tunnel_network'] = $server['addresspool']; unset($server['addresspool']); if (isset($server['use_lzo']) && ($server['use_lzo'] == "on")) { $server['compression'] = "on"; unset($server['use_lzo']); } - if ($server['nopool']) + if ($server['nopool']) { $server['pool_enable'] = false; - else + } else { $server['pool_enable'] = "yes"; + } unset($server['nopool']); $server['dns_domain'] = $server['dhcp_domainname']; unset($server['dhcp_domainname']); @@ -1593,10 +1639,11 @@ function upgrade_051_to_052() { } unset($server['dhcp_ntp']); - if ($server['dhcp_nbtdisable']) + if ($server['dhcp_nbtdisable']) { $server['netbios_enable'] = false; - else + } else { $server['netbios_enable'] = "yes"; + } unset($server['dhcp_nbtdisable']); $server['netbios_ntype'] = $server['dhcp_nbttype']; unset($server['dhcp_nbttype']); @@ -1619,10 +1666,11 @@ function upgrade_051_to_052() { } unset($server['dhcp_wins']); - if (!empty($server['disable'])) + if (!empty($server['disable'])) { $server['disable'] = true; - else + } else { unset($server['disable']); + } /* allocate vpnid */ $server['vpnid'] = $vpnid++; @@ -1640,8 +1688,9 @@ function upgrade_051_to_052() { } else if (substr($tmpstr, 0, 5) == "local") { $localip = substr($tmpstr, 5); $server['ipaddr'] = str_replace("\n", "", $localip); - } else + } else { $cstmopts[] = $tmpcstmopt; + } } $server['custom_options'] = implode(";", $cstmopts); if (!empty($assigned_if)) { @@ -1664,10 +1713,11 @@ function upgrade_051_to_052() { $config['openvpn']['openvpn-client'] = array(); $index = 1; - foreach($config['installedpackages']['openvpnclient']['config'] as $client) { + foreach ($config['installedpackages']['openvpnclient']['config'] as $client) { - if (!is_array($client)) + if (!is_array($client)) { continue; + } if ($client['auth_method'] == "pki") { @@ -1701,15 +1751,17 @@ function upgrade_051_to_052() { } /* determine operational mode */ - if ($client['auth_method'] == 'pki') + if ($client['auth_method'] == 'pki') { $client['mode'] = "p2p_tls"; - else + } else { $client['mode'] = "p2p_shared_key"; + } unset($client['auth_method']); /* modify configuration values */ - if (!$client['interface']) + if (!$client['interface']) { $client['interface'] = 'wan'; + } $client['tunnel_network'] = $client['interface_ip']; unset($client['interface_ip']); $client['server_addr'] = $client['serveraddr']; @@ -1741,8 +1793,9 @@ function upgrade_051_to_052() { } else if (substr($tmpstr, 0, 5) == "local") { $localip = substr($tmpstr, 5); $client['ipaddr'] = str_replace("\n", "", $localip); - } else + } else { $cstmopts[] = $tmpcstmopt; + } } $client['custom_options'] = implode(";", $cstmopts); if (!empty($assigned_if)) { @@ -1755,10 +1808,11 @@ function upgrade_051_to_052() { } } - if (!empty($client['disable'])) + if (!empty($client['disable'])) { $client['disable'] = true; - else + } else { unset($client['disable']); + } $config['openvpn']['openvpn-client'][] = $client; } @@ -1770,10 +1824,11 @@ function upgrade_051_to_052() { if (is_array($config['installedpackages']['openvpncsc'])) { $config['openvpn']['openvpn-csc'] = array(); - foreach($config['installedpackages']['openvpncsc']['config'] as $csc) { + foreach ($config['installedpackages']['openvpncsc']['config'] as $csc) { - if (!is_array($csc)) + if (!is_array($csc)) { continue; + } /* modify configuration values */ $csc['common_name'] = $csc['commonname']; @@ -1799,10 +1854,11 @@ function upgrade_051_to_052() { } unset($csc['dhcp_ntp']); - if ($csc['dhcp_nbtdisable']) + if ($csc['dhcp_nbtdisable']) { $csc['netbios_enable'] = false; - else + } else { $csc['netbios_enable'] = "yes"; + } unset($csc['dhcp_nbtdisable']); $csc['netbios_ntype'] = $csc['dhcp_nbttype']; unset($csc['dhcp_nbttype']); @@ -1825,10 +1881,11 @@ function upgrade_051_to_052() { } unset($csc['dhcp_wins']); - if (!empty($csc['disable'])) + if (!empty($csc['disable'])) { $csc['disable'] = true; - else + } else { unset($csc['disable']); + } $config['openvpn']['openvpn-csc'][] = $csc; } @@ -1837,7 +1894,7 @@ function upgrade_051_to_052() { } if (count($config['openvpn']['openvpn-server']) > 0 || - count($config['openvpn']['openvpn-client']) > 0) { + count($config['openvpn']['openvpn-client']) > 0) { $ovpnrule = array(); $ovpnrule['type'] = "pass"; $ovpnrule['interface'] = "openvpn"; @@ -1854,24 +1911,28 @@ function upgrade_051_to_052() { * FIXME: hack to keep things working with no installedpackages * or carp array in the configuration data. */ - if (!is_array($config['installedpackages'])) + if (!is_array($config['installedpackages'])) { $config['installedpackages'] = array(); - if (!is_array($config['installedpackages']['carp'])) + } + if (!is_array($config['installedpackages']['carp'])) { $config['installedpackages']['carp'] = array(); + } } function upgrade_052_to_053() { global $config; - if (!is_array($config['ca'])) + if (!is_array($config['ca'])) { $config['ca'] = array(); - if (!is_array($config['cert'])) + } + if (!is_array($config['cert'])) { $config['cert'] = array(); + } /* migrate advanced admin page webui ssl to certificate manager */ if ($config['system']['webgui']['certificate'] && - $config['system']['webgui']['private-key']) { + $config['system']['webgui']['private-key']) { /* create cert entry */ $cert = array(); @@ -1898,27 +1959,29 @@ function upgrade_052_to_053() { function upgrade_053_to_054() { global $config; - if(is_array($config['load_balancer']['lbpool'])) { + if (is_array($config['load_balancer']['lbpool'])) { $lbpool_arr = $config['load_balancer']['lbpool']; $lbpool_srv_arr = array(); $gateway_group_arr = array(); $gateways = return_gateways_array(); $group_name_changes = array(); - if (! is_array($config['gateways']['gateway_item'])) + if (! is_array($config['gateways']['gateway_item'])) { $config['gateways']['gateway_item'] = array(); + } $a_gateways =& $config['gateways']['gateway_item']; - foreach($lbpool_arr as $lbpool) { - if($lbpool['type'] == "gateway") { + foreach ($lbpool_arr as $lbpool) { + if ($lbpool['type'] == "gateway") { // Gateway Groups have to have valid names in pf, old lb pools did not. Clean them up. - $group_name = preg_replace("/[^A-Za-z0-9]/", "", $lbpool['name'] ); + $group_name = preg_replace("/[^A-Za-z0-9]/", "", $lbpool['name']); // If we made and changes, check for collisions and note the change. if ($group_name != $lbpool['name']) { // Make sure the name isn't already in use. foreach ($gateway_group_arr as $gwg) { // If the name is in use, add some random bits to avoid collision. - if ($gwg['name'] == $group_name) + if ($gwg['name'] == $group_name) { $group_name .= uniqid(); + } } $group_name_changes[$lbpool['name']] = $group_name; } @@ -1927,19 +1990,22 @@ function upgrade_053_to_054() { $gateway_group['trigger'] = "down"; $gateway_group['item'] = array(); $i = 0; - foreach($lbpool['servers'] as $member) { + foreach ($lbpool['servers'] as $member) { $split = explode("|", $member); $interface = $split[0]; $monitor = $split[1]; /* on static upgraded configuration we automatically prepend GW_ */ $static_name = "GW_" . strtoupper($interface); - if(is_ipaddr($monitor)) - foreach ($a_gateways as & $gw) - if ($gw['name'] == $static_name) + if (is_ipaddr($monitor)) { + foreach ($a_gateways as & $gw) { + if ($gw['name'] == $static_name) { $gw['monitor'] = $monitor; + } + } + } /* on failover increment tier. Else always assign 1 */ - if($lbpool['behaviour'] == "failover") { + if ($lbpool['behaviour'] == "failover") { $i++; } else { $i = 1; @@ -1956,7 +2022,7 @@ function upgrade_053_to_054() { } // Unset lbpool if we no longer have any server pools if (count($lbpool_srv_arr) == 0) { - if(empty($config['load_balancer'])) { + if (empty($config['load_balancer'])) { unset($config['load_balancer']); } else { unset($config['load_balancer']['lbpool']); @@ -1968,10 +2034,13 @@ function upgrade_053_to_054() { if (count($gateway_group_arr) != 0) { $config['gateways']['gateway_group'] = $gateway_group_arr; // Update any rules that had a gateway change, if any. - if (count($group_name_changes) > 0) - foreach ($config['filter']['rule'] as & $rule) - if (!empty($rule["gateway"]) && array_key_exists($rule["gateway"], $group_name_changes)) + if (count($group_name_changes) > 0) { + foreach ($config['filter']['rule'] as & $rule) { + if (!empty($rule["gateway"]) && array_key_exists($rule["gateway"], $group_name_changes)) { $rule["gateway"] = $group_name_changes[$rule["gateway"]]; + } + } + } } } @@ -2013,17 +2082,19 @@ function upgrade_054_to_055() { } /* the roundtrip times need to be divided by 1000 to get seconds, really */ $databases = array(); - if (!file_exists($rrddbpath)) + if (!file_exists($rrddbpath)) { @mkdir($rrddbpath); + } chdir($rrddbpath); $databases = glob("*-quality.rrd"); rsort($databases); - foreach($databases as $database) { + foreach ($databases as $database) { $xmldump = "{$database}.old.xml"; $xmldumpnew = "{$database}.new.xml"; - if (platform_booting()) + if (platform_booting()) { echo "Migrate RRD database {$database} to new format for IPv6 \n"; + } mwexec("$rrdtool tune {$rrddbpath}{$database} -r roundtrip:delay 2>&1"); dump_rrd_to_xml("{$rrddbpath}/{$database}", "{$g['tmp_path']}/{$xmldump}"); @@ -2031,9 +2102,9 @@ function upgrade_054_to_055() { $rrdold = $rrdold['rrd']; $i = 0; - foreach($rrdold['rra'] as $rra) { + foreach ($rrdold['rra'] as $rra) { $l = 0; - foreach($rra['database']['row'] as $row) { + foreach ($rra['database']['row'] as $row) { $vnew = divide_delay($row['v'][1]); $rrdold['rra'][$i]['database']['row'][$l]['v'][1] = $vnew; $l++; @@ -2049,20 +2120,22 @@ function upgrade_054_to_055() { @unlink("{$g['tmp_path']}/{$xmldumpnew}"); } /* let apinger recreate required files */ - if (!platform_booting()) + if (!platform_booting()) { setup_gateways_monitor(); + } /* build a list of traffic and packets databases */ $databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/'); rsort($databases); - foreach($databases as $database) { + foreach ($databases as $database) { $databasetmp = "{$database}.tmp"; $xmldump = "{$database}.old.xml"; $xmldumptmp = "{$database}.tmp.xml"; $xmldumpnew = "{$database}.new.xml"; - if (platform_booting()) + if (platform_booting()) { echo "Migrate RRD database {$database} to new format \n"; + } /* rename DS source */ mwexec("$rrdtool tune {$rrddbpath}/{$database} -r in:inpass 2>&1"); mwexec("$rrdtool tune {$rrddbpath}/{$database} -r out:outpass 2>71"); @@ -2094,7 +2167,7 @@ function upgrade_054_to_055() { /* remove any MAX RRA's. Not needed for traffic. */ $i = 0; foreach ($rrdold['rra'] as $rra) { - if(trim($rra['cf']) == "MAX") { + if (trim($rra['cf']) == "MAX") { unset($rrdold['rra'][$i]); } $i++; @@ -2112,34 +2185,39 @@ function upgrade_054_to_055() { @unlink("{$g['tmp_path']}/{$xmldump}"); @unlink("{$g['tmp_path']}/{$xmldumpnew}"); } - if (!platform_booting()) + if (!platform_booting()) { enable_rrd_graphing(); + } /* Let's save the RRD graphs after we run enable RRD graphing */ /* The function will restore the rrd.tgz so we will save it after */ exec("cd /; LANG=C NO_REMOUNT=1 RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh"); unlink_if_exists("{$g['vardb_path']}/rrd/*.xml"); - if (platform_booting()) + if (platform_booting()) { echo "Updating configuration..."; + } } function upgrade_055_to_056() { global $config; - if (!is_array($config['ca'])) + if (!is_array($config['ca'])) { $config['ca'] = array(); - if (!is_array($config['cert'])) + } + if (!is_array($config['cert'])) { $config['cert'] = array(); + } /* migrate ipsec ca's to cert manager */ if (is_array($config['ipsec']['cacert'])) { - foreach($config['ipsec']['cacert'] as & $cacert) { + foreach ($config['ipsec']['cacert'] as & $cacert) { $ca = array(); $ca['refid'] = uniqid(); - if (is_array($cacert['cert'])) + if (is_array($cacert['cert'])) { $ca['crt'] = $cacert['cert'][0]; - else + } else { $ca['crt'] = $cacert['cert']; + } $ca['descr'] = $cacert['ident']; $config['ca'][] = $ca; } @@ -2148,23 +2226,27 @@ function upgrade_055_to_056() { /* migrate phase1 certificates to cert manager */ if (is_array($config['ipsec']['phase1'])) { - foreach($config['ipsec']['phase1'] as & $ph1ent) { + foreach ($config['ipsec']['phase1'] as & $ph1ent) { $cert = array(); $cert['refid'] = uniqid(); $cert['descr'] = "IPsec Peer {$ph1ent['remote-gateway']} Certificate"; - if (is_array($ph1ent['cert'])) + if (is_array($ph1ent['cert'])) { $cert['crt'] = $ph1ent['cert'][0]; - else + } else { $cert['crt'] = $ph1ent['cert']; + } $cert['prv'] = $ph1ent['private-key']; $config['cert'][] = $cert; $ph1ent['certref'] = $cert['refid']; - if ($ph1ent['cert']) + if ($ph1ent['cert']) { unset($ph1ent['cert']); - if ($ph1ent['private-key']) + } + if ($ph1ent['private-key']) { unset($ph1ent['private-key']); - if ($ph1ent['peercert']) + } + if ($ph1ent['peercert']) { unset($ph1ent['peercert']); + } } } } @@ -2173,11 +2255,12 @@ function upgrade_055_to_056() { function upgrade_056_to_057() { global $config; - if (!is_array($config['system']['user'])) + if (!is_array($config['system']['user'])) { $config['system']['user'] = array(); + } /* migrate captivate portal to user manager */ if (is_array($config['captiveportal']['user'])) { - foreach($config['captiveportal']['user'] as $user) { + foreach ($config['captiveportal']['user'] as $user) { // avoid user conflicts $found = false; foreach ($config['system']['user'] as $userent) { @@ -2186,8 +2269,9 @@ function upgrade_056_to_057() { break; } } - if ($found) + if ($found) { continue; + } $user['scope'] = "user"; if (isset($user['expirationdate'])) { $user['expires'] = $user['expirationdate']; @@ -2207,17 +2291,20 @@ function upgrade_056_to_057() { function upgrade_057_to_058() { global $config; /* set all phase2 entries to tunnel mode */ - if (is_array($config['ipsec']['phase2'])) - foreach($config['ipsec']['phase2'] as & $ph2ent) + if (is_array($config['ipsec']['phase2'])) { + foreach ($config['ipsec']['phase2'] as & $ph2ent) { $ph2ent['mode'] = 'tunnel'; + } + } } function upgrade_058_to_059() { global $config; if (is_array($config['schedules']['schedule'])) { - foreach ($config['schedules']['schedule'] as & $schedl) + foreach ($config['schedules']['schedule'] as & $schedl) { $schedl['schedlabel'] = uniqid(); + } } } @@ -2229,10 +2316,11 @@ function upgrade_059_to_060() { foreach ($config['ca'] as & $ca) { $subject = cert_get_subject($ca['crt']); $issuer = cert_get_issuer($ca['crt']); - if($issuer <> $subject) { + if ($issuer <> $subject) { $issuer_crt =& lookup_ca_by_subject($issuer); - if($issuer_crt) + if ($issuer_crt) { $ca['caref'] = $issuer_crt['refid']; + } } } @@ -2241,10 +2329,11 @@ function upgrade_059_to_060() { foreach ($config['cert'] as & $cert) { $subject = cert_get_subject($cert['crt']); $issuer = cert_get_issuer($cert['crt']); - if($issuer <> $subject) { + if ($issuer <> $subject) { $issuer_crt =& lookup_ca_by_subject($issuer); - if($issuer_crt) + if ($issuer_crt) { $cert['caref'] = $issuer_crt['refid']; + } } } } @@ -2254,10 +2343,12 @@ function upgrade_059_to_060() { function upgrade_060_to_061() { global $config; - if (is_array($config['interfaces']['wan'])) + if (is_array($config['interfaces']['wan'])) { $config['interfaces']['wan']['enable'] = true; - if (is_array($config['interfaces']['lan'])) + } + if (is_array($config['interfaces']['lan'])) { $config['interfaces']['lan']['enable'] = true; + } /* On 1.2.3 the "mtu" field adjusted MSS. On 2.x the "mtu" field is actually the MTU. Rename accordingly. @@ -2314,7 +2405,7 @@ function upgrade_062_to_063() { /* Upgrade legacy Themes to the new pfsense_ng */ global $config; - switch($config['theme']) { + switch ($config['theme']) { case "nervecenter": $config['theme'] = "pfsense_ng"; break; @@ -2332,63 +2423,73 @@ function upgrade_063_to_064() { $config['ppps']['ppp'][$pppid]['if'] = "ppp".$j; $config['ppps']['ppp'][$pppid]['ptpid'] = $j; $j++; - if (isset($ppp['port'])){ + if (isset($ppp['port'])) { $config['ppps']['ppp'][$pppid]['ports'] = $ppp['port']; unset($config['ppps']['ppp'][$pppid]['port']); } - if (!isset($ppp['type'])){ + if (!isset($ppp['type'])) { $config['ppps']['ppp'][$pppid]['type'] = "ppp"; } - if (isset($ppp['defaultgw'])) + if (isset($ppp['defaultgw'])) { unset($config['ppps']['ppp'][$pppid]['defaultgw']); + } } } - if (!is_array($config['ppps']['ppp'])) + if (!is_array($config['ppps']['ppp'])) { $config['ppps']['ppp'] = array(); + } $a_ppps = &$config['ppps']['ppp']; foreach ($ifcfg as $ifname => $ifinfo) { $ppp = array(); // For pppoe conversion - if ($ifinfo['ipaddr'] == "pppoe" || $ifinfo['ipaddr'] == "pptp"){ - if (isset($ifinfo['ptpid'])) + if ($ifinfo['ipaddr'] == "pppoe" || $ifinfo['ipaddr'] == "pptp") { + if (isset($ifinfo['ptpid'])) { continue; + } $ppp['ptpid'] = $j; $ppp['type'] = $ifinfo['ipaddr']; $ppp['if'] = $ifinfo['ipaddr'].$j; $ppp['ports'] = $ifinfo['if']; - if ($ifinfo['ipaddr'] == "pppoe"){ + if ($ifinfo['ipaddr'] == "pppoe") { $ppp['username'] = $ifinfo['pppoe_username']; $ppp['password'] = base64_encode($ifinfo['pppoe_password']); } - if ($ifinfo['ipaddr'] == "pptp"){ + if ($ifinfo['ipaddr'] == "pptp") { $ppp['username'] = $ifinfo['pptp_username']; $ppp['password'] = base64_encode($ifinfo['pptp_password']); } - if (isset($ifinfo['provider'])) + if (isset($ifinfo['provider'])) { $ppp['provider'] = $ifinfo['provider']; - if (isset($ifinfo['ondemand'])) + } + if (isset($ifinfo['ondemand'])) { $ppp['ondemand'] = true; - if (isset($ifinfo['timeout'])) + } + if (isset($ifinfo['timeout'])) { $ppp['idletimeout'] = $ifinfo['timeout']; - if (isset($ifinfo['pppoe']['pppoe-reset-type'])){ + } + if (isset($ifinfo['pppoe']['pppoe-reset-type'])) { $ppp['pppoe-reset-type'] = $ifinfo['pppoe']['pppoe-reset-type']; if (is_array($config['cron']['item'])) { for ($i = 0; $i < count($config['cron']['item']); $i++) { $item = $config['cron']['item'][$i]; - if (strpos($item['command'], "/conf/pppoe{$ifname}restart") !== false) + if (strpos($item['command'], "/conf/pppoe{$ifname}restart") !== false) { $config['cron']['item'][$i]['command'] = "/var/etc/pppoe_restart_" . $ppp['if']; + } } } } - if (isset($ifinfo['local'])) + if (isset($ifinfo['local'])) { $ppp['localip'] = $ifinfo['local']; - if (isset($ifinfo['subnet'])) + } + if (isset($ifinfo['subnet'])) { $ppp['subnet'] = $ifinfo['subnet']; - if (isset($ifinfo['remote'])) + } + if (isset($ifinfo['remote'])) { $ppp['gateway'] = $ifinfo['remote']; + } $ifcfg[$ifname]['if'] = $ifinfo['ipaddr'].$j; $j++; @@ -2436,8 +2537,9 @@ function upgrade_065_to_066() { $foundifs = true; } } - if ($foundifs == true) + if ($foundifs == true) { $dhcrelaycfg['interface'] = implode(",", $dhcrelayifs); + } } } @@ -2463,8 +2565,9 @@ function upgrade_067_to_068() { $username = array(); foreach ($config['pppoe']['user'] as $user) { $usr = $user['name'] . ":" . base64_encode($user['password']); - if ($user['ip']) + if ($user['ip']) { $usr .= ":{$user['ip']}"; + } $username[] = $usr; } $config['pppoes']['pppoe'][0]['username'] = implode(" ", $username); @@ -2475,26 +2578,31 @@ function upgrade_067_to_068() { function upgrade_068_to_069() { global $config; - if (!is_array($config['system']['user'])) + if (!is_array($config['system']['user'])) { return; + } foreach ($config['system']['user'] as & $user) { - if (!is_array($user['cert'])) + if (!is_array($user['cert'])) { continue; + } $rids = array(); foreach ($user['cert'] as $id => $cert) { - if (!isset($cert['descr'])) + if (!isset($cert['descr'])) { continue; + } $tcert = $cert; // Make sure each cert gets a refid - if (!isset($tcert['refid'])) + if (!isset($tcert['refid'])) { $tcert['refid'] = uniqid(); + } // Keep the cert references for this user $rids[] = $tcert['refid']; $config['cert'][] = $tcert; } // Replace user certs with cert references instead. - if (count($rids) > 0) + if (count($rids) > 0) { $user['cert'] = $rids; + } } } @@ -2504,10 +2612,11 @@ function upgrade_069_to_070() { /* Convert NAT 1:1 rules */ if (is_array($config['nat']['onetoone'])) { foreach ($config['nat']['onetoone'] as $nidx => $natent) { - if ($natent['subnet'] == 32) + if ($natent['subnet'] == 32) { $config['nat']['onetoone'][$nidx]['source'] = array("address" => $natent['internal']); - else + } else { $config['nat']['onetoone'][$nidx]['source'] = array("address" => $natent['internal'] . "/" . $natent['subnet']); + } $config['nat']['onetoone'][$nidx]['destination'] = array("any" => true); @@ -2523,8 +2632,8 @@ function upgrade_070_to_071() { global $config; if (is_array($config['cron']['item'])) { - foreach($config['cron']['item'] as $idx => $cronitem) { - if(stristr($cronitem['command'], "checkreload.sh")) { + foreach ($config['cron']['item'] as $idx => $cronitem) { + if (stristr($cronitem['command'], "checkreload.sh")) { unset($config['cron']['item'][$idx]); break; } @@ -2534,35 +2643,44 @@ function upgrade_070_to_071() { function rename_field(& $section, $oldname, $newname) { if (is_array($section)) { - foreach($section as & $item) { - if (is_array($item) && !empty($item[$oldname])) + foreach ($section as & $item) { + if (is_array($item) && !empty($item[$oldname])) { $item[$newname] = $item[$oldname]; - if (is_array($item) && isset($item[$oldname])) + } + if (is_array($item) && isset($item[$oldname])) { unset($item[$oldname]); + } } } } function upgrade_071_to_072() { global $config; - if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) + if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) { rename_field($config['sysctl']['item'], 'desc', 'descr'); + } } function upgrade_072_to_073() { global $config; - if (!is_array($config['load_balancer'])) + if (!is_array($config['load_balancer'])) { return; - if (is_array($config['load_balancer']['monitor_type'])) + } + if (is_array($config['load_balancer']['monitor_type'])) { rename_field($config['load_balancer']['monitor_type'], 'desc', 'descr'); - if (is_array($config['load_balancer']['lbpool'])) + } + if (is_array($config['load_balancer']['lbpool'])) { rename_field($config['load_balancer']['lbpool'], 'desc', 'descr'); - if (is_array($config['load_balancer']['lbaction'])) + } + if (is_array($config['load_balancer']['lbaction'])) { rename_field($config['load_balancer']['lbaction'], 'desc', 'descr'); - if (is_array($config['load_balancer']['lbprotocol'])) + } + if (is_array($config['load_balancer']['lbprotocol'])) { rename_field($config['load_balancer']['lbprotocol'], 'desc', 'descr'); - if (is_array($config['load_balancer']['virtual_server'])) + } + if (is_array($config['load_balancer']['virtual_server'])) { rename_field($config['load_balancer']['virtual_server'], 'desc', 'descr'); + } } function upgrade_073_to_074() { @@ -2572,12 +2690,15 @@ function upgrade_073_to_074() { function upgrade_074_to_075() { global $config; - if (is_array($config['ca'])) + if (is_array($config['ca'])) { rename_field($config['ca'], 'name', 'descr'); - if (is_array($config['cert'])) + } + if (is_array($config['cert'])) { rename_field($config['cert'], 'name', 'descr'); - if (is_array($config['crl'])) + } + if (is_array($config['crl'])) { rename_field($config['crl'], 'name', 'descr'); + } } function upgrade_075_to_076() { @@ -2595,16 +2716,17 @@ function upgrade_075_to_076() { function upgrade_076_to_077() { global $config; - foreach($config['filter']['rule'] as & $rule) { - if (isset($rule['protocol']) && !empty($rule['protocol'])) - $rule['protocol'] = strtolower($rule['protocol']); + foreach ($config['filter']['rule'] as & $rule) { + if (isset($rule['protocol']) && !empty($rule['protocol'])) { + $rule['protocol'] = strtolower($rule['protocol']); + } } } function upgrade_077_to_078() { global $config; - if (is_array($config['pptpd']) && is_array($config['pptpd']['radius']) - && !is_array($config['pptpd']['radius']['server'])) { + if (is_array($config['pptpd']) && is_array($config['pptpd']['radius']) && + !is_array($config['pptpd']['radius']['server'])) { $radarr = array(); $radsvr = array(); $radsvr['ip'] = $config['pptpd']['radius']['server']; @@ -2613,8 +2735,9 @@ function upgrade_077_to_078() { $radsvr['acctport'] = 1813; $radsvr['enable'] = isset($config['pptpd']['radius']['enable']); $radarr['accounting'] = isset($config['pptpd']['radius']['accounting']); - if ($radarr['accounting']) + if ($radarr['accounting']) { $radarr['acct_update'] = $radsvr['ip']; + } $radarr['server'] = $radsvr; $config['pptpd']['radius'] = $radarr; } @@ -2633,7 +2756,7 @@ function upgrade_079_to_080() { /* Upgrade config in 1.2.3 specifying a username other than admin for syncing. */ if (!empty($config['system']['username']) && is_array($config['installedpackages']['carpsettings']) && - is_array($config['installedpackages']['carpsettings']['config'])) { + is_array($config['installedpackages']['carpsettings']['config'])) { $config['installedpackages']['carpsettings']['config'][0]['username'] = $config['system']['username']; unset($config['system']['username']); } @@ -2646,8 +2769,8 @@ function upgrade_080_to_081() { /* tag all the existing gateways as being IPv4 */ $i = 0; - if(is_array($config['gateways']['gateway_item'])) { - foreach($config['gateways']['gateway_item'] as $gw) { + if (is_array($config['gateways']['gateway_item'])) { + foreach ($config['gateways']['gateway_item'] as $gw) { $config['gateways']['gateway_item'][$i]['ipprotocol'] = "inet"; $i++; } @@ -2679,12 +2802,13 @@ function upgrade_080_to_081() { /* build a list of traffic and packets databases */ $databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/'); rsort($databases); - foreach($databases as $database) { + foreach ($databases as $database) { $xmldump = "{$database}.old.xml"; $xmldumpnew = "{$database}.new.xml"; - if (platform_booting()) + if (platform_booting()) { echo "Migrate RRD database {$database} to new format for IPv6.\n"; + } /* dump contents to xml and move database out of the way */ dump_rrd_to_xml("{$rrddbpath}/{$database}", "{$g['tmp_path']}/{$xmldump}"); @@ -2782,16 +2906,16 @@ function upgrade_080_to_081() { $value = " NaN "; $xml = file_get_contents("{$g['tmp_path']}/{$xmldump}"); - foreach($ds_arr as $ds) { + foreach ($ds_arr as $ds) { $xml = preg_replace("/$ds_search/s", "$ds{$ds_search}", $xml); } - foreach($cdp_arr as $cdp) { + foreach ($cdp_arr as $cdp) { $xml = preg_replace("/$cdp_search/s", "$cdp{$cdp_replace}", $xml); } - foreach($ds_arr as $ds) { + foreach ($ds_arr as $ds) { $xml = preg_replace("/$value_search/s", "$value{$value_replace}", $xml); } - + file_put_contents("{$g['tmp_path']}/{$xmldumpnew}", $xml); mwexec("$rrdtool restore -f {$g['tmp_path']}/{$xmldumpnew} {$rrddbpath}/{$database} 2>&1"); unset($xml); @@ -2799,16 +2923,19 @@ function upgrade_080_to_081() { unlink_if_exists("{$g['tmp_path']}/{$xmldump}"); unlink_if_exists("{$g['tmp_path']}/{$xmldumpnew}"); } - if (!platform_booting()) + if (!platform_booting()) { enable_rrd_graphing(); + } /* Let's save the RRD graphs after we run enable RRD graphing */ /* The function will restore the rrd.tgz so we will save it after */ exec("cd /; LANG=C NO_REMOUNT=1 RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh"); - if (platform_booting()) + if (platform_booting()) { echo "Updating configuration..."; - foreach($config['filter']['rule'] as & $rule) { - if (isset($rule['protocol']) && !empty($rule['protocol'])) + } + foreach ($config['filter']['rule'] as & $rule) { + if (isset($rule['protocol']) && !empty($rule['protocol'])) { $rule['protocol'] = strtolower($rule['protocol']); + } } unset($rule); } @@ -2828,8 +2955,9 @@ function upgrade_082_to_083() { $config['captiveportal']['cpzone'] = $tmpcp; $config['captiveportal']['cpzone']['zoneid'] = 8000; $config['captiveportal']['cpzone']['zone'] = "cpzone"; - if ($config['captiveportal']['cpzone']['auth_method'] == "radius") + if ($config['captiveportal']['cpzone']['auth_method'] == "radius") { $config['captiveportal']['cpzone']['radius_protocol'] = "PAP"; + } } if (!empty($config['voucher'])) { $tmpcp = $config['voucher']; @@ -2864,8 +2992,8 @@ function upgrade_084_to_085() { $gateways = return_gateways_array(); $oldnames = array(); /* setup translation array */ - foreach($gateways as $name => $gw) { - if(isset($gw['dynamic'])){ + foreach ($gateways as $name => $gw) { + if (isset($gw['dynamic'])) { $oldname = strtoupper($config['interfaces'][$gw['friendlyiface']]['descr']); $oldnames[$oldname] = $name; } else { @@ -2874,14 +3002,14 @@ function upgrade_084_to_085() { } /* process the old array */ - if(is_array($config['gateways']['gateway_group'])) { + if (is_array($config['gateways']['gateway_group'])) { $group_array_new = array(); - foreach($config['gateways']['gateway_group'] as $name => $group) { - if(is_array($group['item'])) { + foreach ($config['gateways']['gateway_group'] as $name => $group) { + if (is_array($group['item'])) { $newlist = array(); - foreach($group['item'] as $entry) { + foreach ($group['item'] as $entry) { $elements = explode("|", $entry); - if($oldnames[$elements[0]] <> "") { + if ($oldnames[$elements[0]] <> "") { $newlist[] = "{$oldnames[$elements[0]]}|{$elements[1]}"; } else { $newlist[] = "{$elements[0]}|{$elements[1]}"; @@ -2895,8 +3023,8 @@ function upgrade_084_to_085() { } /* rename old Quality RRD files in the process */ $rrddbpath = "/var/db/rrd"; - foreach($oldnames as $old => $new) { - if(is_readable("{$rrddbpath}/{$old}-quality.rrd")) { + foreach ($oldnames as $old => $new) { + if (is_readable("{$rrddbpath}/{$old}-quality.rrd")) { @rename("{$rrddbpath}/{$old}-quality.rrd", "{$rrddbpath}/{$new}-quality.rrd"); } } @@ -2910,8 +3038,9 @@ function upgrade_085_to_086() { if (is_array($config['virtualip']['vip'])) { $vipchg = array(); foreach ($config['virtualip']['vip'] as $vip) { - if ($vip['mode'] != "carp") + if ($vip['mode'] != "carp") { continue; + } $config = array_replace_values_recursive( $config, '^vip' . $vip['vhid'] . '$', @@ -2924,10 +3053,12 @@ function upgrade_085_to_086() { function upgrade_086_to_087() { global $config, $dummynet_pipe_list; - if (!is_array($config['filter']) || !is_array($config['filter']['rule'])) + if (!is_array($config['filter']) || !is_array($config['filter']['rule'])) { return; - if (!is_array($config['dnshaper']) || !is_array($config['dnshaper']['queue'])) + } + if (!is_array($config['dnshaper']) || !is_array($config['dnshaper']['queue'])) { return; + } $dnqueue_number = 1; $dnpipe_number = 1; @@ -2961,12 +3092,14 @@ function upgrade_086_to_087() { foreach ($config['filter']['rule'] as $idx => $rule) { if (!empty($rule['dnpipe'])) { - if (!empty($dn_list[$rule['dnpipe']])) + if (!empty($dn_list[$rule['dnpipe']])) { $config['filter']['rule'][$idx]['dnpipe'] = $dn_list[$rule['dnpipe']]; + } } if (!empty($rule['pdnpipe'])) { - if (!empty($dn_list[$rule['pdnpipe']])) + if (!empty($dn_list[$rule['pdnpipe']])) { $config['filter']['rule'][$idx]['pdnpipe'] = $dn_list[$rule['pdnpipe']]; + } } } } @@ -2980,10 +3113,12 @@ function upgrade_087_to_088() { function upgrade_088_to_089() { global $config; - if (!is_array($config['ca'])) + if (!is_array($config['ca'])) { $config['ca'] = array(); - if (!is_array($config['cert'])) + } + if (!is_array($config['cert'])) { $config['cert'] = array(); + } /* migrate captive portal ssl to certificate manager */ if (is_array($config['captiveportal'])) { @@ -3074,13 +3209,16 @@ function upgrade_092_to_093() { $suffixes = array("concurrent", "loggedin"); - foreach ($suffixes as $suffix) - if (file_exists("{$g['vardb_path']}/rrd/captiveportal-{$suffix}.rrd")) + foreach ($suffixes as $suffix) { + if (file_exists("{$g['vardb_path']}/rrd/captiveportal-{$suffix}.rrd")) { rename("{$g['vardb_path']}/rrd/captiveportal-{$suffix}.rrd", "{$g['vardb_path']}/rrd/captiveportal-cpZone-{$suffix}.rrd"); + } + } - if (!platform_booting()) + if (!platform_booting()) { enable_rrd_graphing(); + } } function upgrade_093_to_094() { @@ -3096,13 +3234,17 @@ function upgrade_093_to_094() { function upgrade_094_to_095() { global $config; - if (!isset($config['interfaces']) || !is_array($config['interfaces'])) + if (!isset($config['interfaces']) || !is_array($config['interfaces'])) { return; + } - foreach ($config['interfaces'] as $iface => $cfg) - if (isset($cfg['ipaddrv6']) && ($cfg['ipaddrv6'] == "track6")) - if (!isset($cfg['track6-prefix-id']) || ($cfg['track6-prefix-id'] == "")) + foreach ($config['interfaces'] as $iface => $cfg) { + if (isset($cfg['ipaddrv6']) && ($cfg['ipaddrv6'] == "track6")) { + if (!isset($cfg['track6-prefix-id']) || ($cfg['track6-prefix-id'] == "")) { $config['interfaces'][$iface]['track6-prefix-id'] = 0; + } + } + } } function upgrade_095_to_096() { @@ -3127,18 +3269,21 @@ function upgrade_095_to_096() { /* build a list of traffic and packets databases */ $databases = return_dir_as_array($rrddbpath, '/-(traffic|packets)\.rrd$/'); rsort($databases); - foreach($databases as $database) { - if (platform_booting()) + foreach ($databases as $database) { + if (platform_booting()) { echo "Update RRD database {$database}.\n"; + } $cmd = "{$rrdtool} tune {$rrddbpath}/{$database}"; - foreach ($names as $name) + foreach ($names as $name) { $cmd .= " -a {$name}:{$stream}"; + } mwexec("{$cmd} 2>&1"); } - if (!platform_booting()) + if (!platform_booting()) { enable_rrd_graphing(); + } /* Let's save the RRD graphs after we run enable RRD graphing */ /* The function will restore the rrd.tgz so we will save it after */ exec("cd /; LANG=C NO_REMOUNT=1 RRDDBPATH='{$rrddbpath}' CF_CONF_PATH='{$g['cf_conf_path']}' /etc/rc.backup_rrd.sh"); @@ -3162,8 +3307,9 @@ function upgrade_097_to_098() { function upgrade_098_to_099() { global $config; - if (empty($config['dhcpd']) || !is_array($config['dhcpd'])) + if (empty($config['dhcpd']) || !is_array($config['dhcpd'])) { return; + } foreach ($config['dhcpd'] as & $dhcpifconf) { if (isset($dhcpifconf['next-server'])) { @@ -3181,15 +3327,18 @@ function upgrade_099_to_100() { function upgrade_100_to_101() { global $config, $g; - if (!is_array($config['voucher'])) + if (!is_array($config['voucher'])) { return; + } foreach ($config['voucher'] as $cpzone => $cp) { - if (!is_array($cp['roll'])) + if (!is_array($cp['roll'])) { continue; + } foreach ($cp['roll'] as $ridx => $rcfg) { - if (!empty($rcfg['comment'])) + if (!empty($rcfg['comment'])) { $config['voucher'][$cpzone]['roll'][$ridx]['descr'] = $rcfg['comment']; + } } } } @@ -3199,11 +3348,13 @@ function upgrade_101_to_102() { if (is_array($config['captiveportal'])) { foreach ($config['captiveportal'] as $cpzone => $cp) { - if (!is_array($cp['passthrumac'])) + if (!is_array($cp['passthrumac'])) { continue; + } - foreach ($cp['passthrumac'] as $idx => $passthrumac) + foreach ($cp['passthrumac'] as $idx => $passthrumac) { $config['captiveportal'][$cpzone]['passthrumac'][$idx]['action'] = 'pass'; + } } } @@ -3212,14 +3363,16 @@ function upgrade_101_to_102() { if (isset($config['openvpn']) && is_array($config['openvpn'])) { if (is_array($config['openvpn']['openvpn-server'])) { foreach ($config['openvpn']['openvpn-server'] as &$vpn) { - if (!empty($vpn['compression'])) + if (!empty($vpn['compression'])) { $vpn['compression'] = "adaptive"; + } } } if (is_array($config['openvpn']['openvpn-client'])) { foreach ($config['openvpn']['openvpn-client'] as &$vpn) { - if (!empty($vpn['compression'])) + if (!empty($vpn['compression'])) { $vpn['compression'] = "adaptive"; + } } } } @@ -3231,8 +3384,9 @@ function upgrade_102_to_103() { if (isset($config['nat']['advancedoutbound']['enable'])) { $config['nat']['advancedoutbound']['mode'] = "advanced"; unset($config['nat']['advancedoutbound']['enable']); - } else + } else { $config['nat']['advancedoutbound']['mode'] = "automatic"; + } $config['nat']['outbound'] = $config['nat']['advancedoutbound']; @@ -3252,21 +3406,25 @@ function upgrade_103_to_104() { /* update user privileges */ foreach ($config['system']['user'] as & $user) { - if (!is_array($user['priv'])) + if (!is_array($user['priv'])) { continue; + } foreach ($user['priv'] as & $priv) { - if (array_key_exists($priv, $changed_privs)) + if (array_key_exists($priv, $changed_privs)) { $priv = $changed_privs[$priv]; + } } } /* update group privileges */ foreach ($config['system']['group'] as & $group) { - if (!is_array($group['priv'])) + if (!is_array($group['priv'])) { continue; + } foreach ($group['priv'] as & $priv) { - if (array_key_exists($priv, $changed_privs)) + if (array_key_exists($priv, $changed_privs)) { $priv = $changed_privs[$priv]; + } } } @@ -3316,7 +3474,6 @@ function upgrade_106_to_107() { $config['nat']['rule'][$ridx]['tracker'] = $tracker; $tracker++; } - } unset($tracker, $ridx); } @@ -3325,25 +3482,29 @@ function upgrade_106_to_107() { function upgrade_107_to_108() { global $config; - if (isset($config['system']['webgui']['noautocomplete'])) + if (isset($config['system']['webgui']['noautocomplete'])) { unset($config['system']['webgui']['noautocomplete']); - else + } else { $config['system']['webgui']['loginautocomplete'] = true; + } } function upgrade_108_to_109() { global $config; - if (!isset($config['filter']['rule']) || !is_array($config['filter']['rule'])) + if (!isset($config['filter']['rule']) || !is_array($config['filter']['rule'])) { return; + } foreach ($config['filter']['rule'] as &$rule) { - if (!isset($rule['dscp']) || empty($rule['dscp'])) + if (!isset($rule['dscp']) || empty($rule['dscp'])) { continue; + } $pos = strpos($rule['dscp'], ' '); - if ($pos !== false) + if ($pos !== false) { $rule['dscp'] = substr($rule['dscp'], 0, $pos); + } unset($pos); } } @@ -3351,12 +3512,14 @@ function upgrade_108_to_109() { function upgrade_109_to_110() { global $config; - if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) + if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) { return; + } foreach ($config['ipsec']['phase2'] as &$rule) { - if (!empty($rule['uniqid'])) + if (!empty($rule['uniqid'])) { continue; + } $rule['uniqid'] = uniqid(); } @@ -3381,8 +3544,9 @@ function upgrade_110_to_111() { /* Remove old menu and service entries */ if (isset($config['installedpackages']['menu']) && is_array($config['installedpackages']['menu'])) { foreach ($config['installedpackages']['menu'] as $idx => $menu) { - if ($menu['name'] != 'Unbound DNS') + if ($menu['name'] != 'Unbound DNS') { continue; + } unset($config['installedpackages']['menu'][$idx]); break; @@ -3391,20 +3555,23 @@ function upgrade_110_to_111() { if (isset($config['installedpackages']['service']) && is_array($config['installedpackages']['service'])) { foreach ($config['installedpackages']['service'] as $idx => $service) { - if ($service['name'] != 'unbound') + if ($service['name'] != 'unbound') { continue; + } unset($config['installedpackages']['service'][$idx]); break; } } - if (!isset($config['installedpackages']['unbound']['config'][0])) + if (!isset($config['installedpackages']['unbound']['config'][0])) { return; + } $pkg = $config['installedpackages']['unbound']['config'][0]; - if (isset($config['installedpackages']['unboundadvanced']['config'][0])) + if (isset($config['installedpackages']['unboundadvanced']['config'][0])) { $pkg = array_merge($pkg, $config['installedpackages']['unboundadvanced']['config'][0]); + } $new = array(); @@ -3425,8 +3592,9 @@ function upgrade_110_to_111() { foreach ($fields as $oldk => $newk) { if (isset($pkg[$oldk])) { - if ($pkg[$oldk] == 'on') + if ($pkg[$oldk] == 'on') { $new[$newk] = true; + } unset($pkg[$oldk]); } } @@ -3456,36 +3624,44 @@ function upgrade_110_to_111() { } } - if (isset($new['custom_options']) && !empty($new['custom_options'])) + if (isset($new['custom_options']) && !empty($new['custom_options'])) { $new['custom_options'] = str_replace("\r\n", "\n", $new['custom_options']); + } /* Following options were removed, bring them as custom_options */ if (isset($pkg['stats']) && $pkg['stats'] == "on") { - if (isset($pkg['stats_interval'])) + if (isset($pkg['stats_interval'])) { $new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "statistics-interval: {$pkg['stats_interval']}"; - if (isset($pkg['cumulative_stats'])) + } + if (isset($pkg['cumulative_stats'])) { $new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "statistics-cumulative: {$pkg['cumulative_stats']}"; - if (isset($pkg['extended_stats']) && $pkg['extended_stats'] == "on") + } + if (isset($pkg['extended_stats']) && $pkg['extended_stats'] == "on") { $new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "extended-statistics: yes"; - else + } else { $new['custom_options'] .= (empty($new['custom_options']) ? "" : "\n") . "extended-statistics: no"; + } } $new['acls'] = array(); if (isset($config['installedpackages']['unboundacls']['config']) && is_array($config['installedpackages']['unboundacls']['config'])) { - foreach ($config['installedpackages']['unboundacls']['config'] as $acl) + foreach ($config['installedpackages']['unboundacls']['config'] as $acl) { $new['acls'][] = $acl; + } } $config['unbound'] = $new; - if(isset($config['installedpackages']['unbound'])) + if (isset($config['installedpackages']['unbound'])) { unset($config['installedpackages']['unbound']); - if(isset($config['installedpackages']['unboundadvanced'])) + } + if (isset($config['installedpackages']['unboundadvanced'])) { unset($config['installedpackages']['unboundadvanced']); - if(isset($config['installedpackages']['unboundacls'])) + } + if (isset($config['installedpackages']['unboundacls'])) { unset($config['installedpackages']['unboundacls']); + } unset($pkg, $new); } @@ -3508,64 +3684,74 @@ function upgrade_112_to_113() { global $config; if (isset($config['notifications']['smtp']['ssl']) && - $config['notifications']['smtp']['ssl'] == "checked") + $config['notifications']['smtp']['ssl'] == "checked") { $config['notifications']['smtp']['ssl'] = true; - else + } else { unset($config['notifications']['smtp']['ssl']); + } if (isset($config['notifications']['smtp']['tls']) && - $config['notifications']['smtp']['tls'] == "checked") + $config['notifications']['smtp']['tls'] == "checked") { $config['notifications']['smtp']['tls'] = true; - else + } else { unset($config['notifications']['smtp']['tls']); + } } function upgrade_113_to_114() { global $config; if (!isset($config['ipsec']['phase1']) || - !is_array($config['ipsec']['phase1'])) + !is_array($config['ipsec']['phase1'])) { return; + } - foreach($config['ipsec']['phase1'] as &$ph1ent) - if (!isset($ph1ent['iketype'])) + foreach ($config['ipsec']['phase1'] as &$ph1ent) { + if (!isset($ph1ent['iketype'])) { $ph1ent['iketype'] = 'ikev1'; + } + } } function upgrade_114_to_115() { global $config; - if (isset($config['unbound']['custom_options'])) + if (isset($config['unbound']['custom_options'])) { $config['unbound']['custom_options'] = base64_encode($config['unbound']['custom_options']); + } } function upgrade_115_to_116() { global $config; - if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) - return; + if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) { + return; + } - $keyid = 1; - foreach ($config['ipsec']['phase2'] as $idx => $ph2) { - $config['ipsec']['phase2'][$idx]['reqid'] = $keyid; + $keyid = 1; + foreach ($config['ipsec']['phase2'] as $idx => $ph2) { + $config['ipsec']['phase2'][$idx]['reqid'] = $keyid; $keyid++; } } function upgrade_116_to_117() { - global $config; + global $config; - if (!isset($config['installedpackages']['miniupnpd']['config'][0])) + if (!isset($config['installedpackages']['miniupnpd']['config'][0])) { return; + } $miniupnpd =& $config['installedpackages']['miniupnpd']['config'][0]; $miniupnpd['row'] = array(); for ($i = 1; $i <= 4; $i++) { - if (isset($miniupnpd["permuser{$i}"]) && !empty($miniupnpd["permuser{$i}"])) + if (isset($miniupnpd["permuser{$i}"]) && !empty($miniupnpd["permuser{$i}"])) { $miniupnpd['row'][] = array('permuser' => $miniupnpd["permuser{$i}"]); + } unset($miniupnpd["permuser{$i}"]); } } ?> + diff --git a/etc/inc/util.inc b/etc/inc/util.inc index 993c4df774..05b33edacf 100644 --- a/etc/inc/util.inc +++ b/etc/inc/util.inc @@ -64,32 +64,37 @@ function isvalidproc($proc) { /* sigkill a process by pid file */ /* return 1 for success and 0 for a failure */ function sigkillbypid($pidfile, $sig) { - if (file_exists($pidfile)) + if (file_exists($pidfile)) { return mwexec("/bin/pkill " . escapeshellarg("-{$sig}") . " -F {$pidfile}", true); + } return 0; } /* kill a process by name */ function sigkillbyname($procname, $sig) { - if(isvalidproc($procname)) + if (isvalidproc($procname)) { return mwexec("/usr/bin/killall " . escapeshellarg("-{$sig}") . " " . escapeshellarg($procname), true); + } } /* kill a process by name */ function killbyname($procname) { - if(isvalidproc($procname)) + if (isvalidproc($procname)) { mwexec("/usr/bin/killall " . escapeshellarg($procname)); + } } function is_subsystem_dirty($subsystem = "") { global $g; - if ($subsystem == "") + if ($subsystem == "") { return false; + } - if (file_exists("{$g['varrun_path']}/{$subsystem}.dirty")) + if (file_exists("{$g['varrun_path']}/{$subsystem}.dirty")) { return true; + } return false; } @@ -97,8 +102,9 @@ function is_subsystem_dirty($subsystem = "") { function mark_subsystem_dirty($subsystem = "") { global $g; - if (!file_put_contents("{$g['varrun_path']}/{$subsystem}.dirty", "DIRTY")) + if (!file_put_contents("{$g['varrun_path']}/{$subsystem}.dirty", "DIRTY")) { log_error(sprintf(gettext("WARNING: Could not mark subsystem: %s dirty"), $subsystem)); + } } function clear_subsystem_dirty($subsystem = "") { @@ -117,25 +123,28 @@ function config_unlock() { /* lock configuration file */ function lock($lock, $op = LOCK_SH) { global $g, $cfglckkeyconsumers; - if (!$lock) + if (!$lock) { die(gettext("WARNING: You must give a name as parameter to lock() function.")); + } if (!file_exists("{$g['tmp_path']}/{$lock}.lock")) { @touch("{$g['tmp_path']}/{$lock}.lock"); @chmod("{$g['tmp_path']}/{$lock}.lock", 0666); } $cfglckkeyconsumers++; if ($fp = fopen("{$g['tmp_path']}/{$lock}.lock", "w")) { - if (flock($fp, $op)) + if (flock($fp, $op)) { return $fp; - else + } else { fclose($fp); + } } } function try_lock($lock, $timeout = 5) { global $g, $cfglckkeyconsumers; - if (!$lock) + if (!$lock) { die(gettext("WARNING: You must give a name as parameter to try_lock() function.")); + } if (!file_exists("{$g['tmp_path']}/{$lock}.lock")) { @touch("{$g['tmp_path']}/{$lock}.lock"); @chmod("{$g['tmp_path']}/{$lock}.lock", 0666); @@ -143,7 +152,7 @@ function try_lock($lock, $timeout = 5) { $cfglckkeyconsumers++; if ($fp = fopen("{$g['tmp_path']}/{$lock}.lock", "w")) { $trycounter = 0; - while(!flock($fp, LOCK_EX | LOCK_NB)) { + while (!flock($fp, LOCK_EX | LOCK_NB)) { if ($trycounter >= $timeout) { fclose($fp); return NULL; @@ -176,8 +185,9 @@ function unlock_force($lock) { function send_event($cmd) { global $g; - if(!isset($g['event_address'])) + if (!isset($g['event_address'])) { $g['event_address'] = "unix:///var/run/check_reload_status"; + } $try = 0; while ($try < 3) { @@ -185,12 +195,14 @@ function send_event($cmd) { if ($fd) { fwrite($fd, $cmd); $resp = fread($fd, 4096); - if ($resp != "OK\n") + if ($resp != "OK\n") { log_error("send_event: sent {$cmd} got {$resp}"); + } fclose($fd); $try = 3; - } else if (!is_process_running("check_reload_status")) + } else if (!is_process_running("check_reload_status")) { mwexec_bg("/usr/bin/nice -n20 /usr/local/sbin/check_reload_status"); + } $try++; } } @@ -198,11 +210,13 @@ function send_event($cmd) { function send_multiple_events($cmds) { global $g; - if(!isset($g['event_address'])) + if (!isset($g['event_address'])) { $g['event_address'] = "unix:///var/run/check_reload_status"; + } - if (!is_array($cmds)) + if (!is_array($cmds)) { return; + } while ($try < 3) { $fd = @fsockopen($g['event_address']); @@ -210,13 +224,15 @@ function send_multiple_events($cmds) { foreach ($cmds as $cmd) { fwrite($fd, $cmd); $resp = fread($fd, 4096); - if ($resp != "OK\n") + if ($resp != "OK\n") { log_error("send_event: sent {$cmd} got {$resp}"); + } } fclose($fd); $try = 3; - } else if (!is_process_running("check_reload_status")) + } else if (!is_process_running("check_reload_status")) { mwexec_bg("/usr/bin/nice -n20 /usr/local/sbin/check_reload_status"); + } $try++; } } @@ -271,8 +287,9 @@ function refcount_unreference($reference) { if ($shm_data < 0) { //debug_backtrace(); log_error(sprintf(gettext("Reference %s is going negative, not doing unreference."), $reference)); - } else + } else { @shmop_write($shmid, str_pad($shm_data, 10, "\x0", STR_PAD_RIGHT), 0); + } @shmop_close($shmid); unlock($shm_lck); } catch (Exception $e) { @@ -300,30 +317,33 @@ function is_module_loaded($module_name) { $module_name = str_replace(".ko", "", $module_name); $running = 0; $_gb = exec("/sbin/kldstat -qn {$module_name} 2>&1", $_gb, $running); - if (intval($running) == 0) + if (intval($running) == 0) { return true; - else + } else { return false; + } } /* validate non-negative numeric string, or equivalent numeric variable */ function is_numericint($arg) { - return (((is_int($arg) && $arg >= 0) || (is_string($arg) && strlen($arg) > 0 && ctype_digit($arg))) ? true : false); + return (((is_int($arg) && $arg >= 0) || (is_string($arg) && strlen($arg) > 0 && ctype_digit($arg))) ? true : false); } -/* Generate the (human readable) ipv4 or ipv6 subnet address (i.e., netmask, or subnet start IP) +/* Generate the (human readable) ipv4 or ipv6 subnet address (i.e., netmask, or subnet start IP) given an (human readable) ipv4 or ipv6 host address and subnet bit count */ function gen_subnet($ipaddr, $bits) { - if (($sn = gen_subnetv6($ipaddr, $bits)) == '') + if (($sn = gen_subnetv6($ipaddr, $bits)) == '') { $sn = gen_subnetv4($ipaddr, $bits); // try to avoid rechecking IPv4/v6 + } return $sn; } /* same as gen_subnet() but accepts IPv4 only */ function gen_subnetv4($ipaddr, $bits) { if (is_ipaddrv4($ipaddr) && is_numericint($bits) && $bits <= 32) { - if ($bits == 0) + if ($bits == 0) { return '0.0.0.0'; // avoids <<32 + } return long2ip(ip2long($ipaddr) & ((0xFFFFFFFF << (32 - $bits)) & 0xFFFFFFFF)); } return ""; @@ -331,24 +351,27 @@ function gen_subnetv4($ipaddr, $bits) { /* same as gen_subnet() but accepts IPv6 only */ function gen_subnetv6($ipaddr, $bits) { - if (is_ipaddrv6($ipaddr) && is_numericint($bits) && $bits <= 128) + if (is_ipaddrv6($ipaddr) && is_numericint($bits) && $bits <= 128) { return Net_IPv6::compress(Net_IPv6::getNetmask($ipaddr, $bits)); + } return ""; } /* Generate the (human readable) ipv4 or ipv6 subnet end address (i.e., highest address, end IP, or IPv4 broadcast address) given an (human readable) ipv4 or ipv6 host address and subnet bit count. */ function gen_subnet_max($ipaddr, $bits) { - if (($sn = gen_subnetv6_max($ipaddr, $bits)) == '') + if (($sn = gen_subnetv6_max($ipaddr, $bits)) == '') { $sn = gen_subnetv4_max($ipaddr, $bits); // try to avoid rechecking IPv4/v6 + } return $sn; } /* same as gen_subnet_max() but validates IPv4 only */ function gen_subnetv4_max($ipaddr, $bits) { if (is_ipaddrv4($ipaddr) && is_numericint($bits) && $bits <= 32) { - if ($bits == 32) + if ($bits == 32) { return $ipaddr; + } return long2ip32(ip2long($ipaddr) | ~gen_subnet_mask_long($bits)); } return ""; @@ -385,7 +408,7 @@ function long2ip32($ip) { /* Convert IP address to long int, truncated to 32-bits to avoid sign extension on 64-bit platforms. */ function ip2long32($ip) { - return ( ip2long($ip) & 0xFFFFFFFF ); + return (ip2long($ip) & 0xFFFFFFFF); } /* Convert IP address to unsigned long int. */ @@ -442,12 +465,13 @@ function ip_greater_than($ip1, $ip2) { /* compare two IP addresses */ function ipcmp($a, $b) { - if (ip_less_than($a, $b)) + if (ip_less_than($a, $b)) { return -1; - else if (ip_greater_than($a, $b)) + } else if (ip_greater_than($a, $b)) { return 1; - else + } else { return 0; + } } /* Convert a range of IPv4 addresses to an array of individual addresses. */ @@ -464,9 +488,10 @@ function ip_range_to_address_array($startip, $endip, $max_size = 5000) { $endip = $temp; } - if (ip_range_size_v4($startip, $endip) > $max_size) + if (ip_range_size_v4($startip, $endip) > $max_size) { return false; - + } + // Container for IP addresses within this range. $rangeaddresses = array(); $end_int = ip2ulong($endip); @@ -547,28 +572,30 @@ function ip_range_to_subnet_array($startip, $endip) { } /* returns true if $range is a valid pair of IPv4 or IPv6 addresses separated by a "-" - false - if not a valid pair - true (numeric 4 or 6) - if valid, gives type of addresses */ + false - if not a valid pair + true (numeric 4 or 6) - if valid, gives type of addresses */ function is_iprange($range) { if (substr_count($range, '-') != 1) { return false; } list($ip1, $ip2) = explode ('-', $range); - if (is_ipaddrv4($ip1) && is_ipaddrv4($ip2)) + if (is_ipaddrv4($ip1) && is_ipaddrv4($ip2)) { return 4; - if (is_ipaddrv6($ip1) && is_ipaddrv6($ip2)) + } + if (is_ipaddrv6($ip1) && is_ipaddrv6($ip2)) { return 6; + } return false; } /* returns true if $ipaddr is a valid dotted IPv4 address or a IPv6 - false - not valid - true (numeric 4 or 6) - if valid, gives type of address */ + false - not valid + true (numeric 4 or 6) - if valid, gives type of address */ function is_ipaddr($ipaddr) { - if(is_ipaddrv4($ipaddr)) { + if (is_ipaddrv4($ipaddr)) { return 4; } - if(is_ipaddrv6($ipaddr)) { + if (is_ipaddrv6($ipaddr)) { return 6; } return false; @@ -576,8 +603,9 @@ function is_ipaddr($ipaddr) { /* returns true if $ipaddr is a valid IPv6 address */ function is_ipaddrv6($ipaddr) { - if (!is_string($ipaddr) || empty($ipaddr)) + if (!is_string($ipaddr) || empty($ipaddr)) { return false; + } if (strstr($ipaddr, "%") && is_linklocal($ipaddr)) { $tmpip = explode("%", $ipaddr); $ipaddr = $tmpip[0]; @@ -587,16 +615,18 @@ function is_ipaddrv6($ipaddr) { /* returns true if $ipaddr is a valid dotted IPv4 address */ function is_ipaddrv4($ipaddr) { - if (!is_string($ipaddr) || empty($ipaddr)) + if (!is_string($ipaddr) || empty($ipaddr)) { return false; + } $ip_long = ip2long($ipaddr); $ip_reverse = long2ip32($ip_long); - if ($ipaddr == $ip_reverse) + if ($ipaddr == $ip_reverse) { return true; - else + } else { return false; + } } /* returns true if $ipaddr is a valid IPv6 linklocal address */ @@ -606,40 +636,45 @@ function is_linklocal($ipaddr) { /* returns scope of a linklocal address */ function get_ll_scope($addr) { - if (!is_linklocal($addr) || !strstr($addr, "%")) + if (!is_linklocal($addr) || !strstr($addr, "%")) { return ""; + } list ($ll, $scope) = explode("%", $addr); return $scope; } /* returns true if $ipaddr is a valid literal IPv6 address */ function is_literalipaddrv6($ipaddr) { - if(preg_match("/\[([0-9a-f:]+)\]/i", $ipaddr, $match)) + if (preg_match("/\[([0-9a-f:]+)\]/i", $ipaddr, $match)) { $ipaddr = $match[1]; - else + } else { return false; + } return is_ipaddrv6($ipaddr); } /* returns true if $iport is a valid IPv4/IPv6 address + port - false - not valid - true (numeric 4 or 6) - if valid, gives type of address */ + false - not valid + true (numeric 4 or 6) - if valid, gives type of address */ function is_ipaddrwithport($ipport) { $c = strrpos($ipport, ":"); - if ($c === false) + if ($c === false) { return false; // can't split at final colon if no colon exists - - if (!is_port(substr($ipport, $c + 1))) + } + + if (!is_port(substr($ipport, $c + 1))) { return false; // no valid port after last colon + } $ip = substr($ipport, 0, $c); // else is text before last colon a valid IP - if (is_literalipaddrv6($ip)) + if (is_literalipaddrv6($ip)) { return 6; - elseif (is_ipaddrv4($ip)) + } elseif (is_ipaddrv4($ip)) { return 4; - else + } else { return false; + } } function is_hostnamewithport($hostport) { @@ -659,25 +694,29 @@ function is_ipaddroralias($ipaddr) { if (is_alias($ipaddr)) { if (is_array($config['aliases']['alias'])) { foreach ($config['aliases']['alias'] as $alias) { - if ($alias['name'] == $ipaddr && !preg_match("/port/i", $alias['type'])) + if ($alias['name'] == $ipaddr && !preg_match("/port/i", $alias['type'])) { return true; + } } } return false; - } else + } else { return is_ipaddr($ipaddr); + } } /* returns true if $subnet is a valid IPv4 or IPv6 subnet in CIDR format - false - if not a valid subnet - true (numeric 4 or 6) - if valid, gives type of subnet */ + false - if not a valid subnet + true (numeric 4 or 6) - if valid, gives type of subnet */ function is_subnet($subnet) { if (is_string($subnet) && preg_match('/^(?:([0-9.]{7,15})|([0-9a-f:]{2,39}))\/(\d{1,3})$/i', $subnet, $parts)) { - if (is_ipaddrv4($parts[1]) && $parts[3] <= 32) + if (is_ipaddrv4($parts[1]) && $parts[3] <= 32) { return 4; - if (is_ipaddrv6($parts[2]) && $parts[3] <= 128) + } + if (is_ipaddrv6($parts[2]) && $parts[3] <= 128) { return 6; + } } return false; } @@ -696,10 +735,11 @@ function is_subnetv6($subnet) { function is_subnetoralias($subnet) { global $aliastable; - if (isset($aliastable[$subnet]) && is_subnet($aliastable[$subnet])) + if (isset($aliastable[$subnet]) && is_subnet($aliastable[$subnet])) { return true; - else + } else { return is_subnet($subnet); + } } function subnet_size($subnet) { @@ -743,15 +783,18 @@ function subnetv4_expand($subnet) { /* find out whether two subnets overlap */ function check_subnets_overlap($subnet1, $bits1, $subnet2, $bits2) { - if (!is_numeric($bits1)) + if (!is_numeric($bits1)) { $bits1 = 32; - if (!is_numeric($bits2)) + } + if (!is_numeric($bits2)) { $bits2 = 32; + } - if ($bits1 < $bits2) + if ($bits1 < $bits2) { $relbits = $bits1; - else + } else { $relbits = $bits2; + } $sn1 = gen_subnet_mask_long($relbits) & ip2long($subnet1); $sn2 = gen_subnet_mask_long($relbits) & ip2long($subnet2); @@ -771,7 +814,7 @@ function check_subnetsv6_overlap($subnet1, $bits1, $subnet2, $bits2) { /* return true if $addr is in $subnet, false if not */ function ip_in_subnet($addr,$subnet) { - if(is_ipaddrv6($addr) && is_subnetv6($subnet)) { + if (is_ipaddrv6($addr) && is_subnetv6($subnet)) { return (Net_IPv6::isInNetmask($addr, $subnet)); } else if (is_ipaddrv4($addr) && is_subnetv4($subnet)) { list($ip, $mask) = explode('/', $subnet); @@ -783,40 +826,46 @@ function ip_in_subnet($addr,$subnet) { /* returns true if $hostname is just a valid hostname (top part without any of the domain part) */ function is_unqualified_hostname($hostname) { - if (!is_string($hostname)) + if (!is_string($hostname)) { return false; + } - if (preg_match('/^(?:[a-z0-9_]|[a-z0-9_][a-z0-9_\-]*[a-z0-9_])$/i', $hostname)) + if (preg_match('/^(?:[a-z0-9_]|[a-z0-9_][a-z0-9_\-]*[a-z0-9_])$/i', $hostname)) { return true; - else + } else { return false; + } } /* returns true if $hostname is a valid hostname, with or without being a fully-qualified domain name. */ function is_hostname($hostname) { - if (!is_string($hostname)) + if (!is_string($hostname)) { return false; + } - if (is_domain($hostname)) + if (is_domain($hostname)) { if ((substr_count($hostname, ".") == 1) && ($hostname[strlen($hostname)-1] == ".")) { /* Only a single dot at the end like "test." - hosts cannot be directly in the root domain. */ return false; } else { return true; } - else + } else { return false; + } } /* returns true if $domain is a valid domain name */ function is_domain($domain) { - if (!is_string($domain)) + if (!is_string($domain)) { return false; + } - if (preg_match('/^(?:(?:[a-z_0-9]|[a-z_0-9][a-z_0-9\-]*[a-z_0-9])\.)*(?:[a-z_0-9]|[a-z_0-9][a-z_0-9\-]*[a-z_0-9\.])$/i', $domain)) + if (preg_match('/^(?:(?:[a-z_0-9]|[a-z_0-9][a-z_0-9\-]*[a-z_0-9])\.)*(?:[a-z_0-9]|[a-z_0-9][a-z_0-9\-]*[a-z_0-9\.])$/i', $domain)) { return true; - else + } else { return false; + } } /* returns true if $macaddr is a valid MAC address */ @@ -829,27 +878,31 @@ function is_macaddr($macaddr, $partial=false) { returns NULL if a reserved word is used returns FALSE for bad chars in the name - this allows calling code to determine what the problem was. aliases cannot be: - bad chars: anything except a-z 0-9 and underscore - bad names: empty string, pure numeric, pure underscore - reserved words: pre-defined service/protocol/port names which should not be ambiguous, and the words "port" and "pass" */ + bad chars: anything except a-z 0-9 and underscore + bad names: empty string, pure numeric, pure underscore + reserved words: pre-defined service/protocol/port names which should not be ambiguous, and the words "port" and "pass" */ function is_validaliasname($name) { /* Array of reserved words */ $reserved = array("port", "pass"); - if (!is_string($name) || strlen($name) >= 32 || preg_match('/(^_*$|^\d*$|[^a-z0-9_])/i', $name)) + if (!is_string($name) || strlen($name) >= 32 || preg_match('/(^_*$|^\d*$|[^a-z0-9_])/i', $name)) { return false; - if (in_array($name, $reserved, true) || getservbyname($name, "tcp") || getservbyname($name, "udp") || getprotobyname($name)) + } + if (in_array($name, $reserved, true) || getservbyname($name, "tcp") || getservbyname($name, "udp") || getprotobyname($name)) { return; /* return NULL */ + } return true; } /* returns true if $port is a valid TCP/UDP port */ function is_port($port) { - if (ctype_digit($port) && ((intval($port) >= 1) && (intval($port) <= 65535))) + if (ctype_digit($port) && ((intval($port) >= 1) && (intval($port) <= 65535))) { return true; - if (getservbyname($port, "tcp") || getservbyname($port, "udp")) + } + if (getservbyname($port, "tcp") || getservbyname($port, "udp")) { return true; + } return false; } @@ -867,19 +920,22 @@ function is_portoralias($port) { if (is_alias($port)) { if (is_array($config['aliases']['alias'])) { foreach ($config['aliases']['alias'] as $alias) { - if ($alias['name'] == $port && preg_match("/port/i", $alias['type'])) + if ($alias['name'] == $port && preg_match("/port/i", $alias['type'])) { return true; } } - return false; - } else + } + return false; + } else { return is_port($port); + } } /* create ranges of sequential port numbers (200:215) and remove duplicates */ function group_ports($ports) { - if (!is_array($ports) || empty($ports)) + if (!is_array($ports) || empty($ports)) { return; + } $uniq = array(); foreach ($ports as $port) { @@ -890,12 +946,15 @@ function group_ports($ports) { $begin = $end; $end = $aux; } - for ($i = $begin; $i <= $end; $i++) - if (!in_array($i, $uniq)) + for ($i = $begin; $i <= $end; $i++) { + if (!in_array($i, $uniq)) { $uniq[] = $i; + } + } } else if (is_port($port)) { - if (!in_array($port, $uniq)) + if (!in_array($port, $uniq)) { $uniq[] = $port; + } } } sort($uniq, SORT_NUMERIC); @@ -908,10 +967,11 @@ function group_ports($ports) { } $last = end($result); - if (is_portrange($last)) + if (is_portrange($last)) { list($begin, $end) = explode(":", $last); - else + } else { $begin = $end = $last; + } if ($port == ($end+1)) { $end++; @@ -931,18 +991,20 @@ function is_valid_shaperbw($val) { /* returns true if $test is in the range between $start and $end */ function is_inrange_v4($test, $start, $end) { - if ( (ip2ulong($test) <= ip2ulong($end)) && (ip2ulong($test) >= ip2ulong($start)) ) + if ((ip2ulong($test) <= ip2ulong($end)) && (ip2ulong($test) >= ip2ulong($start))) { return true; - else + } else { return false; + } } /* returns true if $test is in the range between $start and $end */ function is_inrange_v6($test, $start, $end) { - if ( (inet_pton($test) <= inet_pton($end)) && (inet_pton($test) >= inet_pton($start)) ) + if ((inet_pton($test) <= inet_pton($end)) && (inet_pton($test) >= inet_pton($start))) { return true; - else + } else { return false; + } } /* returns true if $test is in the range between $start and $end */ @@ -956,45 +1018,49 @@ function get_configured_carp_interface_list($carpinterface = '', $family = 'inet $iflist = array(); - if(is_array($config['virtualip']['vip'])) { + if (is_array($config['virtualip']['vip'])) { $viparr = &$config['virtualip']['vip']; foreach ($viparr as $vip) { switch ($vip['mode']) { - case "carp": - if (!empty($carpinterface)) { - if ($carpinterface == "_vip{$vip['uniqid']}") { - switch ($what) { - case 'subnet': - if ($family == 'inet' && is_ipaddrv4($vip['subnet'])) - return $vip['subnet_bits']; - else if ($family == 'inet6' && is_ipaddrv6($vip['subnet'])) - return $vip['subnet_bits']; - break; - case 'iface': - if ($family == 'inet' && is_ipaddrv4($vip['subnet'])) - return $vip['interface']; - else if ($family == 'inet6' && is_ipaddrv6($vip['subnet'])) - return $vip['interface']; - break; - case 'vip': - if ($family == 'inet' && is_ipaddrv4($vip['subnet'])) - return $vip; - else if ($family == 'inet6' && is_ipaddrv6($vip['subnet'])) - return $vip; - break; - case 'ip': - default: - if ($family == 'inet' && is_ipaddrv4($vip['subnet'])) - return $vip['subnet']; - else if ($family == 'inet6' && is_ipaddrv6($vip['subnet'])) - return $vip['subnet']; - break; + case "carp": + if (!empty($carpinterface)) { + if ($carpinterface == "_vip{$vip['uniqid']}") { + switch ($what) { + case 'subnet': + if ($family == 'inet' && is_ipaddrv4($vip['subnet'])) { + return $vip['subnet_bits']; + } else if ($family == 'inet6' && is_ipaddrv6($vip['subnet'])) { + return $vip['subnet_bits']; + } + break; + case 'iface': + if ($family == 'inet' && is_ipaddrv4($vip['subnet'])) { + return $vip['interface']; + } else if ($family == 'inet6' && is_ipaddrv6($vip['subnet'])) { + return $vip['interface']; + } + break; + case 'vip': + if ($family == 'inet' && is_ipaddrv4($vip['subnet'])) { + return $vip; + } else if ($family == 'inet6' && is_ipaddrv6($vip['subnet'])) { + return $vip; + } + break; + case 'ip': + default: + if ($family == 'inet' && is_ipaddrv4($vip['subnet'])) { + return $vip['subnet']; + } else if ($family == 'inet6' && is_ipaddrv6($vip['subnet'])) { + return $vip['subnet']; + } + break; + } } + } else { + $iflist["_vip{$vip['uniqid']}"] = $vip['subnet']; } - } else { - $iflist["_vip{$vip['uniqid']}"] = $vip['subnet']; - } - break; + break; } } } @@ -1008,14 +1074,15 @@ function get_configured_ip_aliases_list($returnfullentry = false) { $alias_list=array(); - if(is_array($config['virtualip']['vip'])) { + if (is_array($config['virtualip']['vip'])) { $viparr = &$config['virtualip']['vip']; foreach ($viparr as $vip) { if ($vip['mode']=="ipalias") { - if ($returnfullentry) + if ($returnfullentry) { $alias_list[$vip['subnet']] = $vip; - else + } else { $alias_list[$vip['subnet']] = $vip['interface']; + } } } } @@ -1029,13 +1096,14 @@ function get_configured_vips_list() { $alias_list=array(); - if(is_array($config['virtualip']['vip'])) { + if (is_array($config['virtualip']['vip'])) { $viparr = &$config['virtualip']['vip']; foreach ($viparr as $vip) { - if ($vip['mode'] == "carp") + if ($vip['mode'] == "carp") { $alias_list[] = array("ipaddr" => $vip['subnet'], "if" => "{$vip['interface']}_vip{$vip['vhid']}"); - else + } else { $alias_list[] = array("ipaddr" => $vip['subnet'], "if" => $vip['interface']); + } } } @@ -1044,16 +1112,17 @@ function get_configured_vips_list() { /* comparison function for sorting by the order in which interfaces are normally created */ function compare_interface_friendly_names($a, $b) { - if ($a == $b) + if ($a == $b) { return 0; - else if ($a == 'wan') + } else if ($a == 'wan') { return -1; - else if ($b == 'wan') + } else if ($b == 'wan') { return 1; - else if ($a == 'lan') + } else if ($a == 'lan') { return -1; - else if ($b == 'lan') + } else if ($b == 'lan') { return 1; + } return strnatcmp($a, $b); } @@ -1065,11 +1134,13 @@ function get_configured_interface_list($only_opt = false, $withdisabled = false) $iflist = array(); /* if list */ - foreach($config['interfaces'] as $if => $ifdetail) { - if ($only_opt && ($if == "wan" || $if == "lan")) + foreach ($config['interfaces'] as $if => $ifdetail) { + if ($only_opt && ($if == "wan" || $if == "lan")) { continue; - if (isset($ifdetail['enable']) || $withdisabled == true) + } + if (isset($ifdetail['enable']) || $withdisabled == true) { $iflist[$if] = $if; + } } return $iflist; @@ -1082,13 +1153,15 @@ function get_configured_interface_list_by_realif($only_opt = false, $withdisable $iflist = array(); /* if list */ - foreach($config['interfaces'] as $if => $ifdetail) { - if ($only_opt && ($if == "wan" || $if == "lan")) + foreach ($config['interfaces'] as $if => $ifdetail) { + if ($only_opt && ($if == "wan" || $if == "lan")) { continue; + } if (isset($ifdetail['enable']) || $withdisabled == true) { $tmpif = get_real_interface($if); - if (!empty($tmpif)) + if (!empty($tmpif)) { $iflist[$tmpif] = $if; + } } } @@ -1102,14 +1175,16 @@ function get_configured_interface_with_descr($only_opt = false, $withdisabled = $iflist = array(); /* if list */ - foreach($config['interfaces'] as $if => $ifdetail) { - if ($only_opt && ($if == "wan" || $if == "lan")) + foreach ($config['interfaces'] as $if => $ifdetail) { + if ($only_opt && ($if == "wan" || $if == "lan")) { continue; + } if (isset($ifdetail['enable']) || $withdisabled == true) { - if(empty($ifdetail['descr'])) + if (empty($ifdetail['descr'])) { $iflist[$if] = strtoupper($if); - else + } else { $iflist[$if] = strtoupper($ifdetail['descr']); + } } } @@ -1124,26 +1199,29 @@ function get_configured_interface_with_descr($only_opt = false, $withdisabled = function get_configured_ip_addresses() { global $config; - if (!function_exists('get_interface_ip')) + if (!function_exists('get_interface_ip')) { require_once("interfaces.inc"); + } $ip_array = array(); $interfaces = get_configured_interface_list(); if (is_array($interfaces)) { - foreach($interfaces as $int) { + foreach ($interfaces as $int) { $ipaddr = get_interface_ip($int); $ip_array[$int] = $ipaddr; } } $interfaces = get_configured_carp_interface_list(); - if (is_array($interfaces)) - foreach($interfaces as $int => $ipaddr) + if (is_array($interfaces)) { + foreach ($interfaces as $int => $ipaddr) { $ip_array[$int] = $ipaddr; + } + } /* pppoe server */ if (is_array($config['pppoes']) && is_array($config['pppoes']['pppoe'])) { - foreach($config['pppoes']['pppoe'] as $pppoe) { + foreach ($config['pppoes']['pppoe'] as $pppoe) { if ($pppoe['mode'] == "server") { - if(is_ipaddr($pppoe['localip'])) { + if (is_ipaddr($pppoe['localip'])) { $int = "pppoes". $pppoe['pppoeid']; $ip_array[$int] = $pppoe['localip']; } @@ -1163,16 +1241,18 @@ function get_configured_ipv6_addresses() { require_once("interfaces.inc"); $ipv6_array = array(); $interfaces = get_configured_interface_list(); - if(is_array($interfaces)) { - foreach($interfaces as $int) { + if (is_array($interfaces)) { + foreach ($interfaces as $int) { $ipaddrv6 = get_interface_ipv6($int); $ipv6_array[$int] = $ipaddrv6; } } $interfaces = get_configured_carp_interface_list(); - if(is_array($interfaces)) - foreach($interfaces as $int => $ipaddrv6) + if (is_array($interfaces)) { + foreach ($interfaces as $int => $ipaddrv6) { $ipv6_array[$int] = $ipaddrv6; + } + } return $ipv6_array; } @@ -1188,7 +1268,7 @@ function get_interface_list($mode = "active", $keyby = "physical", $vfaces = "") global $config; $upints = array(); /* get a list of virtual interface types */ - if(!$vfaces) { + if (!$vfaces) { $vfaces = array ( 'bridge', 'ppp', @@ -1214,24 +1294,26 @@ function get_interface_list($mode = "active", $keyby = "physical", $vfaces = "") 'ipfw' ); } - switch($mode) { - case "active": - $upints = pfSense_interface_listget(IFF_UP); - break; - case "media": - $intlist = pfSense_interface_listget(); - $ifconfig = ""; - exec("/sbin/ifconfig -a", $ifconfig); - $regexp = '/(' . implode('|', $intlist) . '):\s/'; - $ifstatus = preg_grep('/status:/', $ifconfig); - foreach($ifstatus as $status) { - $int = array_shift($intlist); - if(stristr($status, "active")) $upints[] = $int; - } - break; - default: - $upints = pfSense_interface_listget(); - break; + switch ($mode) { + case "active": + $upints = pfSense_interface_listget(IFF_UP); + break; + case "media": + $intlist = pfSense_interface_listget(); + $ifconfig = ""; + exec("/sbin/ifconfig -a", $ifconfig); + $regexp = '/(' . implode('|', $intlist) . '):\s/'; + $ifstatus = preg_grep('/status:/', $ifconfig); + foreach ($ifstatus as $status) { + $int = array_shift($intlist); + if (stristr($status, "active")) { + $upints[] = $int; + } + } + break; + default: + $upints = pfSense_interface_listget(); + break; } /* build interface list with netstat */ $linkinfo = ""; @@ -1241,30 +1323,33 @@ function get_interface_list($mode = "active", $keyby = "physical", $vfaces = "") $ipinfo = ""; exec("/usr/bin/netstat -inW -f inet | awk '{ print $1, $4 }'", $ipinfo); array_shift($ipinfo); - foreach($linkinfo as $link) { + foreach ($linkinfo as $link) { $friendly = ""; $alink = explode(" ", $link); $ifname = rtrim(trim($alink[0]), '*'); /* trim out all numbers before checking for vfaces */ if (!in_array(array_shift(preg_split('/\d/', $ifname)), $vfaces) && - !stristr($ifname, "_vlan") && !stristr($ifname, "_wlan")) { + !stristr($ifname, "_vlan") && !stristr($ifname, "_wlan")) { $toput = array( "mac" => trim($alink[1]), "up" => in_array($ifname, $upints) ); - foreach($ipinfo as $ip) { + foreach ($ipinfo as $ip) { $aip = explode(" ", $ip); - if($aip[0] == $ifname) { + if ($aip[0] == $ifname) { $toput['ipaddr'] = $aip[1]; } } if (is_array($config['interfaces'])) { - foreach($config['interfaces'] as $name => $int) - if($int['if'] == $ifname) $friendly = $name; + foreach ($config['interfaces'] as $name => $int) { + if ($int['if'] == $ifname) { + $friendly = $name; + } + } } - switch($keyby) { + switch ($keyby) { case "physical": - if($friendly != "") { + if ($friendly != "") { $toput['friendly'] = $friendly; } $dmesg_arr = array(); @@ -1276,7 +1361,7 @@ function get_interface_list($mode = "active", $keyby = "physical", $vfaces = "") case "ppp": case "friendly": - if($friendly != "") { + if ($friendly != "") { $toput['if'] = $ifname; $iflist[$friendly] = $toput; } @@ -1303,8 +1388,9 @@ function log_error($error) { $page = basename($files[0]); } syslog(LOG_ERR, "$page: $error"); - if ($g['debug']) + if ($g['debug']) { syslog(LOG_WARNING, var_dump(debug_backtrace())); + } return; } @@ -1320,8 +1406,9 @@ function log_auth($error) { global $g; $page = $_SERVER['SCRIPT_NAME']; syslog(LOG_AUTH, "$page: $error"); - if ($g['debug']) + if ($g['debug']) { syslog(LOG_WARNING, var_dump(debug_backtrace())); + } return; } @@ -1346,8 +1433,9 @@ function mwexec($command, $mute = false, $clearsigmask = false) { global $g; if ($g['debug']) { - if (!$_SERVER['REMOTE_ADDR']) + if (!$_SERVER['REMOTE_ADDR']) { echo "mwexec(): $command\n"; + } } $oarr = array(); $retval = 0; @@ -1361,9 +1449,10 @@ function mwexec($command, $mute = false, $clearsigmask = false) { pcntl_sigprocmask(SIG_SETMASK, $oldset); } - if(isset($config['system']['developerspew'])) + if (isset($config['system']['developerspew'])) { $mute = false; - if(($retval <> 0) && ($mute === false)) { + } + if (($retval <> 0) && ($mute === false)) { $output = implode(" ", $oarr); log_error(sprintf(gettext("The command '%1\$s' returned exit code '%2\$d', the output was '%3\$s' "), $command, $retval, $output)); unset($output); @@ -1377,8 +1466,9 @@ function mwexec_bg($command, $clearsigmask = false) { global $g; if ($g['debug']) { - if (!$_SERVER['REMOTE_ADDR']) + if (!$_SERVER['REMOTE_ADDR']) { echo "mwexec(): $command\n"; + } } if ($clearsigmask) { @@ -1395,9 +1485,10 @@ function mwexec_bg($command, $clearsigmask = false) { /* unlink a file, if it exists */ function unlink_if_exists($fn) { $to_do = glob($fn); - if(is_array($to_do)) { - foreach($to_do as $filename) + if (is_array($to_do)) { + foreach ($to_do as $filename) { @unlink($filename); + } } else { @unlink($fn); } @@ -1410,8 +1501,9 @@ function alias_make_table($config) { if (is_array($config['aliases']['alias'])) { foreach ($config['aliases']['alias'] as $alias) { - if ($alias['name']) + if ($alias['name']) { $aliastable[$alias['name']] = $alias['address']; + } } } } @@ -1428,8 +1520,9 @@ function alias_get_type($name) { if (is_array($config['aliases']['alias'])) { foreach ($config['aliases']['alias'] as $alias) { - if ($name == $alias['name']) + if ($name == $alias['name']) { return $alias['type']; + } } } @@ -1440,12 +1533,13 @@ function alias_get_type($name) { function alias_expand($name) { global $aliastable; - if (isset($aliastable[$name])) + if (isset($aliastable[$name])) { return "\${$name}"; - else if (is_ipaddr($name) || is_subnet($name) || is_port($name) || is_portrange($name)) + } else if (is_ipaddr($name) || is_subnet($name) || is_port($name) || is_portrange($name)) { return "{$name}"; - else + } else { return null; + } } function alias_expand_urltable($name) { @@ -1456,10 +1550,11 @@ function alias_expand_urltable($name) { if (is_array($config['aliases']['alias'])) { foreach ($config['aliases']['alias'] as $alias) { if (preg_match("/urltable/i", $alias['type']) && ($alias['name'] == $name)) { - if (is_URL($alias["url"]) && file_exists($urltable_filename) && filesize($urltable_filename)) + if (is_URL($alias["url"]) && file_exists($urltable_filename) && filesize($urltable_filename)) { return $urltable_filename; - else if (process_alias_urltable($name, $alias["url"], 0, true)) + } else if (process_alias_urltable($name, $alias["url"], 0, true)) { return $urltable_filename; + } } } } @@ -1470,8 +1565,9 @@ function alias_expand_urltable($name) { function verify_digital_signature($fname) { global $g; - if(!file_exists("/usr/local/sbin/gzsig")) + if (!file_exists("/usr/local/sbin/gzsig")) { return 4; + } return mwexec("/usr/local/sbin/gzsig verify {$g['etc_path']}/pubkey.pem < " . escapeshellarg($fname)); } @@ -1485,10 +1581,11 @@ function arp_get_mac_by_ip($ip) { if ($arpoutput[0]) { $arpi = explode(" ", $arpoutput[0]); $macaddr = $arpi[3]; - if (is_macaddr($macaddr)) + if (is_macaddr($macaddr)) { return $macaddr; - else + } else { return false; + } } return false; @@ -1509,28 +1606,29 @@ function mac_format($clientmac) { $mac = explode(":", $clientmac); $mac_format = $cpzone ? $config['captiveportal'][$cpzone]['radmac_format'] : false; - switch($mac_format) { - case 'singledash': - return "$mac[0]$mac[1]$mac[2]-$mac[3]$mac[4]$mac[5]"; + switch ($mac_format) { + case 'singledash': + return "$mac[0]$mac[1]$mac[2]-$mac[3]$mac[4]$mac[5]"; - case 'ietf': - return "$mac[0]-$mac[1]-$mac[2]-$mac[3]-$mac[4]-$mac[5]"; + case 'ietf': + return "$mac[0]-$mac[1]-$mac[2]-$mac[3]-$mac[4]-$mac[5]"; - case 'cisco': - return "$mac[0]$mac[1].$mac[2]$mac[3].$mac[4]$mac[5]"; + case 'cisco': + return "$mac[0]$mac[1].$mac[2]$mac[3].$mac[4]$mac[5]"; - case 'unformatted': - return "$mac[0]$mac[1]$mac[2]$mac[3]$mac[4]$mac[5]"; + case 'unformatted': + return "$mac[0]$mac[1]$mac[2]$mac[3]$mac[4]$mac[5]"; - default: - return $clientmac; + default: + return $clientmac; } } function resolve_retry($hostname, $retries = 5) { - if (is_ipaddr($hostname)) + if (is_ipaddr($hostname)) { return $hostname; + } for ($i = 0; $i < $retries; $i++) { // FIXME: gethostbyname does not work for AAAA hostnames, boo, hiss @@ -1579,11 +1677,13 @@ function return_dir_as_array($dir, $filter_regex = '') { if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { - if (($file == ".") || ($file == "..")) + if (($file == ".") || ($file == "..")) { continue; + } - if (empty($filter_regex) || preg_match($filter_regex, $file)) + if (empty($filter_regex) || preg_match($filter_regex, $file)) { array_push($dir_array, $file); + } } closedir($dh); } @@ -1598,10 +1698,11 @@ function run_plugins($directory) { $files = return_dir_as_array($directory); if (is_array($files)) { foreach ($files as $file) { - if (stristr($file, ".sh") == true) + if (stristr($file, ".sh") == true) { mwexec($directory . $file . " start"); - else if (!is_dir($directory . "/" . $file) && stristr($file,".inc")) + } else if (!is_dir($directory . "/" . $file) && stristr($file,".inc")) { require_once($directory . "/" . $file); + } } } } @@ -1629,8 +1730,9 @@ function make_dirs($path, $mode = 0755) { foreach (explode('/', $path) as $dir) { $base .= "/$dir"; if (!is_dir($base)) { - if (!@mkdir($base, $mode)) + if (!@mkdir($base, $mode)) { return false; + } } } return true; @@ -1642,23 +1744,26 @@ function make_dirs($path, $mode = 0755) { * name) and return an array of key/value pairs set for those that exist */ function get_sysctl($names) { - if (empty($names)) + if (empty($names)) { return array(); + } if (is_array($names)) { $name_list = array(); foreach ($names as $name) { $name_list[] = escapeshellarg($name); } - } else + } else { $name_list = array(escapeshellarg($names)); + } exec("/sbin/sysctl -i " . implode(" ", $name_list), $output); $values = array(); foreach ($output as $line) { $line = explode(": ", $line, 2); - if (count($line) == 2) + if (count($line) == 2) { $values[$line[0]] = $line[1]; + } } return $values; @@ -1670,12 +1775,14 @@ function get_sysctl($names) { * return the value for sysctl $name or empty string if it doesn't exist */ function get_single_sysctl($name) { - if (empty($name)) + if (empty($name)) { return ""; + } $value = get_sysctl($name); - if (empty($value) || !isset($value[$name])) + if (empty($value) || !isset($value[$name])) { return ""; + } return $value[$name]; } @@ -1686,8 +1793,9 @@ function get_single_sysctl($name) { * an array with keys set for those that succeeded */ function set_sysctl($values) { - if (empty($values)) + if (empty($values)) { return array(); + } $value_list = array(); foreach ($values as $key => $value) { @@ -1706,8 +1814,9 @@ function set_sysctl($values) { $ret = array(); foreach ($output as $line) { $line = explode(": ", $line, 2); - if (count($line) == 2) + if (count($line) == 2) { $ret[$line[0]] = true; + } } return $ret; @@ -1716,16 +1825,18 @@ function set_sysctl($values) { /* * set_single_sysctl($name, $value) * Wrapper to set_sysctl() to make it simple to set only one sysctl - * returns boolean meaning if it suceed + * returns boolean meaning if it succeeded */ function set_single_sysctl($name, $value) { - if (empty($name)) + if (empty($name)) { return false; + } $result = set_sysctl(array($name => $value)); - if (!isset($result[$name]) || $result[$name] != $value) + if (!isset($result[$name]) || $result[$name] != $value) { return false; + } return true; } @@ -1753,8 +1864,9 @@ function mute_kernel_msgs() { case "jail": return; } - if($config['system']['enableserial']) + if ($config['system']['enableserial']) { return; + } exec("/sbin/conscontrol mute on"); } @@ -1773,9 +1885,10 @@ function unmute_kernel_msgs() { function start_devd() { global $g; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; - /* Use the undocumented -q options of devd to quite its log spamming */ + } + /* Use the undocumented -q options of devd to quiet its log spamming */ $_gb = exec("/sbin/devd -q"); sleep(1); unset($_gb); @@ -1786,8 +1899,9 @@ function is_interface_vlan_mismatch() { if (is_array($config['vlans']['vlan'])) { foreach ($config['vlans']['vlan'] as $vlan) { - if (does_interface_exist($vlan['if']) == false) + if (does_interface_exist($vlan['if']) == false) { return true; + } } } @@ -1806,22 +1920,24 @@ function is_interface_mismatch() { // Do not check these interfaces. $i++; continue; - } - else if (does_interface_exist($ifcfg['if']) == false) { + } else if (does_interface_exist($ifcfg['if']) == false) { $missing_interfaces[] = $ifcfg['if']; $do_assign = true; - } else + } else { $i++; + } } } - if (file_exists("{$g['tmp_path']}/assign_complete")) + if (file_exists("{$g['tmp_path']}/assign_complete")) { $do_assign = false; + } - if (!empty($missing_interfaces) && $do_assign) + if (!empty($missing_interfaces) && $do_assign) { file_put_contents("{$g['tmp_path']}/missing_interfaces", implode(' ', $missing_interfaces)); - else + } else { @unlink("{$g['tmp_path']}/missing_interfaces"); + } return $do_assign; } @@ -1853,17 +1969,22 @@ function isAjax() { * returns 1 char of user input or null if no input. ******/ function timeout($timer = 9) { - while(!isset($key)) { - if ($timer >= 9) { echo chr(8) . chr(8) . ($timer==9 ? chr(32) : null) . "{$timer}"; } - else { echo chr(8). "{$timer}"; } + while (!isset($key)) { + if ($timer >= 9) { + echo chr(8) . chr(8) . ($timer==9 ? chr(32) : null) . "{$timer}"; + } else { + echo chr(8). "{$timer}"; + } `/bin/stty -icanon min 0 time 25`; $key = trim(`KEY=\`dd count=1 2>/dev/null\`; echo \$KEY`); `/bin/stty icanon`; - if ($key == '') + if ($key == '') { unset($key); + } $timer--; - if ($timer == 0) + if ($timer == 0) { break; + } } return $key; } @@ -1878,7 +1999,7 @@ function timeout($timer = 9) { ******/ function msort($array, $id="id", $sort_ascending=true) { $temp_array = array(); - while(count($array)>0) { + while (count($array)>0) { $lowest_id = 0; $index=0; foreach ($array as $item) { @@ -1911,15 +2032,17 @@ function msort($array, $id="id", $sort_ascending=true) { ******/ function is_URL($url) { $match = preg_match("'\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))'", $url); - if($match) + if ($match) { return true; + } return false; } function is_file_included($file = "") { $files = get_included_files(); - if (in_array($file, $files)) + if (in_array($file, $files)) { return true; + } return false; } @@ -1928,14 +2051,17 @@ function is_file_included($file = "") { * Replace a value on a deep associative array using regex */ function array_replace_values_recursive($data, $match, $replace) { - if (empty($data)) + if (empty($data)) { return $data; + } - if (is_string($data)) + if (is_string($data)) { $data = preg_replace("/{$match}/", $replace, $data); - else if (is_array($data)) - foreach ($data as $k => $v) + } else if (is_array($data)) { + foreach ($data as $k => $v) { $data[$k] = array_replace_values_recursive($v, $match, $replace); + } + } return $data; } @@ -1954,30 +2080,30 @@ function array_merge_recursive_unique($array0, $array1) { $result = array(); // loop available array - foreach($arrays as $array) { + foreach ($arrays as $array) { // The first remaining array is $array. We are processing it. So - // we remove it from remaing arrays. + // we remove it from remaining arrays. array_shift($remains); // We don't care non array param, like array_merge since PHP 5.0. - if(is_array($array)) { + if (is_array($array)) { // Loop values - foreach($array as $key => $value) { - if(is_array($value)) { + foreach ($array as $key => $value) { + if (is_array($value)) { // we gather all remaining arrays that have such key available $args = array(); - foreach($remains as $remain) { - if(array_key_exists($key, $remain)) { + foreach ($remains as $remain) { + if (array_key_exists($key, $remain)) { array_push($args, $remain[$key]); } } - if(count($args) > 2) { + if (count($args) > 2) { // put the recursion $result[$key] = call_user_func_array(__FUNCTION__, $args); } else { - foreach($value as $vkey => $vval) { + foreach ($value as $vkey => $vval) { $result[$key][$vkey] = $vval; } } @@ -2010,26 +2136,29 @@ function get_staticroutes($returnsubnetsonly = false, $returnhostnames = false) global $config, $aliastable; /* Bail if there are no routes, but return an array always so callers don't have to check. */ - if (!is_array($config['staticroutes']['route'])) + if (!is_array($config['staticroutes']['route'])) { return array(); + } $allstaticroutes = array(); $allsubnets = array(); /* Loop through routes and expand aliases as we find them. */ foreach ($config['staticroutes']['route'] as $route) { if (is_alias($route['network'])) { - if (!isset($aliastable[$route['network']])) + if (!isset($aliastable[$route['network']])) { continue; + } $subnets = preg_split('/\s+/', $aliastable[$route['network']]); foreach ($subnets as $net) { if (!is_subnet($net)) { - if (is_ipaddrv4($net)) + if (is_ipaddrv4($net)) { $net .= "/32"; - else if (is_ipaddrv6($net)) + } else if (is_ipaddrv6($net)) { $net .= "/128"; - else if ($returnhostnames === false || !is_fqdn($net)) + } else if ($returnhostnames === false || !is_fqdn($net)) { continue; + } } $temproute = $route; $temproute['network'] = $net; @@ -2041,10 +2170,11 @@ function get_staticroutes($returnsubnetsonly = false, $returnhostnames = false) $allsubnets[] = $route['network']; } } - if ($returnsubnetsonly) + if ($returnsubnetsonly) { return $allsubnets; - else + } else { return $allstaticroutes; + } } /****f* util/get_alias_list @@ -2065,13 +2195,11 @@ function get_alias_list($type = null) { foreach ($config['aliases']['alias'] as $alias) { if ($type === null) { $result[] = $alias['name']; - } - else if (is_array($type)) { + } else if (is_array($type)) { if (in_array($alias['type'], $type)) { $result[] = $alias['name']; } - } - else if ($type === $alias['type']) { + } else if ($type === $alias['type']) { $result[] = $alias['name']; } } @@ -2096,22 +2224,25 @@ function get_current_theme() { global $config, $g; /* * if user has selected a custom template, use it. - * otherwise default to pfsense tempalte + * otherwise default to pfsense template */ - if (($g["disablethemeselection"] === true) && !empty($g["default_theme"]) && (is_dir($g["www_path"].'/themes/'.$g["default_theme"]))) + if (($g["disablethemeselection"] === true) && !empty($g["default_theme"]) && (is_dir($g["www_path"].'/themes/'.$g["default_theme"]))) { $theme = $g["default_theme"]; - elseif($config['theme'] <> "" && (is_dir($g["www_path"].'/themes/'.$config['theme']))) + } elseif ($config['theme'] <> "" && (is_dir($g["www_path"].'/themes/'.$config['theme']))) { $theme = $config['theme']; - else + } else { $theme = "pfsense"; + } /* * If this device is an apple ipod/iphone * switch the theme to one that works with it. */ $lowres_ua = array("iPhone", "iPod", "iPad", "Android", "BlackBerry", "Opera Mini", "Opera Mobi", "PlayBook", "IEMobile"); - foreach($lowres_ua as $useragent) - if(strstr($_SERVER['HTTP_USER_AGENT'], $useragent)) + foreach ($lowres_ua as $useragent) { + if (strstr($_SERVER['HTTP_USER_AGENT'], $useragent)) { $theme = (empty($g['theme_lowres']) && (is_dir($g["www_path"].'/themes/'.$g['theme_lowres']))) ? "pfsense" : $g['theme_lowres']; + } + } return $theme; } @@ -2119,16 +2250,18 @@ function get_current_theme() { function prefer_ipv4_or_ipv6() { global $config; - if (isset($config['system']['prefer_ipv4'])) + if (isset($config['system']['prefer_ipv4'])) { mwexec("/etc/rc.d/ip6addrctl prefer_ipv4"); - else + } else { mwexec("/etc/rc.d/ip6addrctl prefer_ipv6"); + } } /* Redirect to page passing parameters via POST */ function post_redirect($page, $params) { - if (!is_array($params)) + if (!is_array($params)) { return; + } print "
        \n"; foreach ($params as $key => $value) { diff --git a/etc/inc/uuid.php b/etc/inc/uuid.php index 9eaf2fdf7d..700f39281e 100644 --- a/etc/inc/uuid.php +++ b/etc/inc/uuid.php @@ -44,7 +44,7 @@ class UUID { const FMT_BINARY = 102; const FMT_QWORD = 1; /* Quad-word, 128-bit (not impl.) */ const FMT_DWORD = 2; /* Double-word, 64-bit (not impl.) */ - const FMT_WORD = 4; /* Word, 32-bit (not impl.) */ + const FMT_WORD = 4; /* Word, 32-bit (not impl.) */ const FMT_SHORT = 8; /* Short (not impl.) */ const FMT_BYTE = 16; /* Byte */ const FMT_DEFAULT = 16; @@ -169,7 +169,7 @@ class UUID { $raw .= $node; /* Hash the namespace and node and convert to a byte array */ - $val = $hash($raw, true); + $val = $hash($raw, true); $tmp = unpack('C16', $val); foreach (array_keys($tmp) as $key) $byte[$key - 1] = $tmp[$key]; @@ -187,7 +187,7 @@ class UUID { $field['time_hi'] &= 0x0fff; $field['time_hi'] |= ($version << 12); - return ($field); + return ($field); } static private function generateNameMD5($ns, $node) { return self::generateName($ns, $node, "md5", @@ -221,7 +221,7 @@ class UUID { $uuid['time_low'] = $low; $uuid['time_mid'] = $high & 0x0000ffff; $uuid['time_hi'] = ($high & 0x0fff) | (self::UUID_TIME << 12); - + /* * We don't support saved state information and generate * a random clock sequence each time. From 6b16c91c511723b8343fe6339b8e6c16b648c186 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Tue, 3 Mar 2015 11:41:37 +0545 Subject: [PATCH 151/257] Add missing BR tags and fix display with pfsense_ng_fs theme Fixes #4481 Similar issue to commit https://github.com/pfsense/pfsense/commit/5cfd948144741ba0d6981f89b2e40257cb9ef2b1 Note: services_dhcpv6_edit.php - these fields are not present so nothing to edit/fix. --- usr/local/www/services_dhcp_edit.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/services_dhcp_edit.php b/usr/local/www/services_dhcp_edit.php index e91a23d4d2..bbf2cd28d2 100644 --- a/usr/local/www/services_dhcp_edit.php +++ b/usr/local/www/services_dhcp_edit.php @@ -504,11 +504,11 @@ include("head.inc");



        - +



        - +

        From 58c58dcfa7b13aef5e3a0997bce61018fba6d3ec Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Tue, 3 Mar 2015 00:16:33 -0600 Subject: [PATCH 152/257] Remove "Prefer old SA" option, and ignore it in all existing configurations. Breaks things in many cases with strongSwan. For the very rare circumstances where this is actually desirable, it's just a sysctl that can be set in tunables. --- etc/inc/vpn.inc | 12 +----------- usr/local/www/vpn_ipsec_settings.php | 18 ------------------ 2 files changed, 1 insertion(+), 29 deletions(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 283e455069..3ec14dedb9 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -105,8 +105,6 @@ function vpn_ipsec_configure($restart = false) unlink_if_exists("{$g['vardb_path']}/ipsecpinghosts"); touch("{$g['vardb_path']}/ipsecpinghosts"); - vpn_ipsec_configure_preferoldsa(); - $syscfg = $config['system']; $ipseccfg = $config['ipsec']; if (!isset($ipseccfg['enable'])) { @@ -1771,12 +1769,4 @@ EOD; return 0; } -function vpn_ipsec_configure_preferoldsa() { - global $config; - if(isset($config['ipsec']['preferoldsa'])) - set_single_sysctl("net.key.preferred_oldsa", "-30"); - else - set_single_sysctl("net.key.preferred_oldsa", "0"); -} - -?> +?> \ No newline at end of file diff --git a/usr/local/www/vpn_ipsec_settings.php b/usr/local/www/vpn_ipsec_settings.php index 5c3ea2773e..39c1862b66 100644 --- a/usr/local/www/vpn_ipsec_settings.php +++ b/usr/local/www/vpn_ipsec_settings.php @@ -41,7 +41,6 @@ require_once("shaper.inc"); require_once("ipsec.inc"); require_once("vpn.inc"); -$pconfig['preferoldsa_enable'] = isset($config['ipsec']['preferoldsa']); foreach ($ipsec_loglevels as $lkey => $ldescr) { if (!empty($config['ipsec']["ipsec_{$lkey}"])) $pconfig["ipsec_{$lkey}"] = $config['ipsec']["ipsec_{$lkey}"]; @@ -115,11 +114,6 @@ if ($_POST) { if (!$input_errors) { - if($_POST['preferoldsa_enable'] == "yes") - $config['ipsec']['preferoldsa'] = true; - elseif (isset($config['ipsec']['preferoldsa'])) - unset($config['ipsec']['preferoldsa']); - if (is_array($config['ipsec'])) { foreach ($ipsec_loglevels as $lkey => $ldescr) { if (empty($_POST["ipsec_{$lkey}"])) { @@ -182,7 +176,6 @@ if ($_POST) { else $savemsg = gettext($retval); - vpn_ipsec_configure_preferoldsa(); vpn_ipsec_configure($needsrestart); vpn_ipsec_configure_loglevels(); @@ -242,17 +235,6 @@ function maxmss_checked(obj) { - - - - /> - -
        - - - From ebfb1d0bbcc7697ac1302ef82d1203898134e27e Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Tue, 3 Mar 2015 12:13:17 +0545 Subject: [PATCH 153/257] Standardise power mode selection boxes I noticed that this looked a little odd, the boxes for AC and Battery Power Mode are 1 after the other on the same line, then the 3rd box for unknown power mode is on a new line. Maybe make them all on their own line, like this? --- usr/local/www/system_advanced_misc.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/system_advanced_misc.php b/usr/local/www/system_advanced_misc.php index d97bdfa402..bafd30fbca 100644 --- a/usr/local/www/system_advanced_misc.php +++ b/usr/local/www/system_advanced_misc.php @@ -396,7 +396,7 @@ function tmpvar_checked(obj) { -    +
         :  " /> - " onclick="window.location.href=''" /> + " onclick="window.location.href=''" /> From 86481f75ecf588be3a61669fa1947d08413262a4 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Tue, 3 Mar 2015 12:38:40 +0545 Subject: [PATCH 155/257] system_groupmanager edit cancel button looks small It looks smaller and different to the Save button. This makes it the same. --- usr/local/www/system_groupmanager.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/system_groupmanager.php b/usr/local/www/system_groupmanager.php index 0ace794922..7132a45005 100644 --- a/usr/local/www/system_groupmanager.php +++ b/usr/local/www/system_groupmanager.php @@ -458,7 +458,7 @@ function presubmit() {   " /> - " onclick="window.location.href='/system_groupmanager.php'" /> + " onclick="window.location.href='/system_groupmanager.php'" /> From 47aa60f9711902978096ced6ee26e87adef337f3 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Tue, 3 Mar 2015 12:57:03 +0545 Subject: [PATCH 156/257] Make the Power Mode selection boxes line up by putting the text and selection boxes into a 2-column table so that it can be rendered with the boxes lined up vertically. --- usr/local/www/system_advanced_misc.php | 58 ++++++++++++++++---------- 1 file changed, 35 insertions(+), 23 deletions(-) diff --git a/usr/local/www/system_advanced_misc.php b/usr/local/www/system_advanced_misc.php index bafd30fbca..6d927dfef8 100644 --- a/usr/local/www/system_advanced_misc.php +++ b/usr/local/www/system_advanced_misc.php @@ -389,30 +389,42 @@ function tmpvar_checked(obj) { />

        -  :  - + + + + + + + + + + + + + +
          + +
          + +
          + +

        -  :  - -
        -  :  - -

        Date: Tue, 3 Mar 2015 16:33:56 +0545 Subject: [PATCH 157/257] Make the DHCP network booting options line up by putting the text and selection boxes into a 2-column table so that it can be rendered with the boxes lined up vertically. --- usr/local/www/services_dhcp.php | 42 ++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/usr/local/www/services_dhcp.php b/usr/local/www/services_dhcp.php index 778d360610..a92b14adb0 100644 --- a/usr/local/www/services_dhcp.php +++ b/usr/local/www/services_dhcp.php @@ -1119,14 +1119,40 @@ include("head.inc"); /> 
        - -
        - -
        - -
        - -
        + + + + + + + + + + + + + + + + + +
        + + +
        +
        + + +
        +
        + + +
        +
        + + +
        +
        - From 6cf2c8b0a087f92a400fc22803df78fb4979a62c Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Tue, 3 Mar 2015 17:51:34 +0545 Subject: [PATCH 158/257] Code style etc inc z end of code style review for the etc folder tree --- etc/inc/zeromq.inc | 117 ++++++++++++++++++++++++++++----------------- 1 file changed, 72 insertions(+), 45 deletions(-) diff --git a/etc/inc/zeromq.inc b/etc/inc/zeromq.inc index a8503fccdd..eb1d432d3d 100644 --- a/etc/inc/zeromq.inc +++ b/etc/inc/zeromq.inc @@ -1,4 +1,4 @@ -connect("{$protocol}://{$ipaddress}:{$port}"); @@ -59,30 +59,34 @@ function zeromq_send($protocol = "tcp", $ipaddress = "127.0.0.1", $port = "8888" /* xmlrpc_params_to_php() the result and return */ $unserializedresult = unserialize($result); - + /* Return the result to the caller */ return $unserializedresult; } function zeromq_server($protocol = "tcp", $ipaddress = "127.0.0.1", $port = "8888") { global $debug; - if(!$ipaddress || !$port) { - if($debug) + if (!$ipaddress || !$port) { + if ($debug) { echo "ERROR: You must pass, proto, ipaddress and port\n"; + } return; } - if($debug) + if ($debug) { echo "Creating ZMQSocket()\n"; + } $server = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REP); - if($debug) + if ($debug) { echo "Binding to {$protocol}://{$ipaddress}:{$port}\n"; + } $server->bind("{$protocol}://{$ipaddress}:{$port}"); - if($debug) + if ($debug) { echo "Entering while() loop\n"; + } while ($msg = $server->recv()) { // Convert the XML to a PHP array $message = unserialize($msg); - if($debug) { + if ($debug) { echo "Message received:\n"; print_r($message); } @@ -121,54 +125,61 @@ function zeromq_server($protocol = "tcp", $ipaddress = "127.0.0.1", $port = "888 $function_to_call = "get_notices_zeromq"; break; } - if(!$function_to_call) { - if($debug) + if (!$function_to_call) { + if ($debug) { echo "ERROR: Could not find a function to call"; + } return; } else { - if($debug) + if ($debug) { echo "Invoking function {$message[2]}()\n;"; + } } /* Call function that is being invoked */ $result = $function_to_call($message); /* echo back the result */ - $server->send($result); + $server->send($result); } } function zeromq_auth($params) { - global $config, $g, $debug; + global $config, $g, $debug; $username = $params[0]; $passwd = $params[1]; - + $user = getUserEntry($username); if (!$user) { - if($debug) + if ($debug) { echo "Could not locate user $username with getUserEntry()\n"; + } return false; } if (is_account_disabled($username) || is_account_expired($username)) { - if($debug) + if ($debug) { echo "Returning account expired/disabled\n"; + } return false; } - + if ($user['password']) { $passwd = crypt($passwd, $user['password']); - if ($passwd == $user['password']) + if ($passwd == $user['password']) { return true; + } } if ($user['md5-hash']) { $passwd = md5($passwd); - if ($passwd == $user['md5-hash']) + if ($passwd == $user['md5-hash']) { return true; + } } - if($debug) + if ($debug) { echo "zeromq_auth() fall through == false\n"; + } return false; } @@ -176,32 +187,37 @@ function zeromq_auth($params) { function exec_php_zeromq($raw_params) { global $config, $g, $debug; $params = $raw_params; - if(zeromq_auth($raw_params) == false) { - if($debug) + if (zeromq_auth($raw_params) == false) { + if ($debug) { echo "Auth failed in exec_shell_zeromq()\n"; + } return ZEROMQ_AUTH_FAIL; } $exec_php = $params[3]; - if($debug) + if ($debug) { echo "Running exec_php_zeromq(): {$exec_php}\n"; + } eval($exec_php); - if($toreturn) { + if ($toreturn) { return serialize($toreturn); - } else + } else { return ZEROMQ_FASLE; + } } function exec_shell_zeromq($raw_params) { global $config, $g, $debug; $params = $raw_params; - if(zeromq_auth($raw_params) == false) { - if($debug) + if (zeromq_auth($raw_params) == false) { + if ($debug) { echo "Auth failed in exec_shell_zeromq()\n"; + } return ZEROMQ_AUTH_FAIL; } $shell_cmd = $params[3]; - if($debug) + if ($debug) { echo "Running exec_shell_zeromq(): {$shell_cmd}\n"; + } mwexec($shell_cmd); return ZEROMQ_FASLE; } @@ -209,8 +225,9 @@ function exec_shell_zeromq($raw_params) { function backup_config_section_zeromq($raw_params) { global $config, $g, $debug; $params = $raw_params; - if(zeromq_auth($raw_params) == false) + if (zeromq_auth($raw_params) == false) { return ZEROMQ_AUTH_FAIL; + } $val = array_intersect_key($config, array_flip($params[3])); return serialize($val); } @@ -218,8 +235,9 @@ function backup_config_section_zeromq($raw_params) { function restore_config_section_zeromq($raw_params) { global $config, $g, $debug; $params = $raw_params; - if(zeromq_auth($raw_params) == false) + if (zeromq_auth($raw_params) == false) { return ZEROMQ_AUTH_FAIL; + } $config = array_merge($config, $params[3]); $mergedkeys = implode(",", array_keys($params[3])); write_config(sprintf(gettext("Merged in config (%s sections) from ZeroMQ client."),$mergedkeys)); @@ -229,8 +247,9 @@ function restore_config_section_zeromq($raw_params) { function merge_installedpackages_section_zeromq($raw_params) { global $config, $g, $debug; $params = $raw_params; - if(zeromq_auth($raw_params) == false) + if (zeromq_auth($raw_params) == false) { return ZEROMQ_AUTH_FAIL; + } $config['installedpackages'] = array_merge($config['installedpackages'], $params[0]); $mergedkeys = implode(",", array_keys($params[3])); write_config(sprintf(gettext("Merged in config (%s sections) from ZeroMQ client."),$mergedkeys)); @@ -240,8 +259,9 @@ function merge_installedpackages_section_zeromq($raw_params) { function merge_config_section_zeromq($raw_params) { global $config, $g, $debug; $params = $raw_params; - if(zeromq_auth($raw_params) == false) - return ZEROMQ_AUTH_FAIL; + if (zeromq_auth($raw_params) == false) { + return ZEROMQ_AUTH_FAIL; + } $config = array_merge_recursive_unique($config, $params[0]); $mergedkeys = implode(",", array_keys($params[3])); write_config("Merged in config ({$mergedkeys} sections) from ZeroMQ client."); @@ -251,8 +271,9 @@ function merge_config_section_zeromq($raw_params) { function filter_configure_zeromq($raw_params) { global $config, $g, $debug; $params = $raw_params; - if(zeromq_auth($raw_params) == false) + if (zeromq_auth($raw_params) == false) { return ZEROMQ_AUTH_FAIL; + } filter_configure(); system_routing_configure(); setup_gateways_monitor(); @@ -260,10 +281,11 @@ function filter_configure_zeromq($raw_params) { require_once("openvpn.inc"); openvpn_resync_all(); services_dhcpd_configure(); - if (isset($config['dnsmasq']['enable'])) + if (isset($config['dnsmasq']['enable'])) { services_dnsmasq_configure(); - elseif (isset($config['unbound']['enable'])) + } elseif (isset($config['unbound']['enable'])) { services_unbound_configure(); + } local_sync_accounts(); return ZEROMQ_FASLE; } @@ -271,8 +293,9 @@ function filter_configure_zeromq($raw_params) { function interfaces_carp_configure_zeromq($raw_params) { global $config, $g, $debug; $params = $raw_params; - if(zeromq_auth($raw_params) == false) + if (zeromq_auth($raw_params) == false) { return ZEROMQ_AUTH_FAIL; + } interfaces_sync_setup(); interfaces_vips_configure(); return ZEROMQ_FASLE; @@ -281,16 +304,18 @@ function interfaces_carp_configure_zeromq($raw_params) { function check_firmware_version_zeromq($raw_params) { global $config, $g, $debug; $params = $raw_params; - if(zeromq_auth($raw_params) == false) + if (zeromq_auth($raw_params) == false) { return ZEROMQ_AUTH_FAIL; + } return serialize(check_firmware_version(false)); } function reboot_zeromq($raw_params) { global $config, $g, $debug; $params = $raw_params; - if(zeromq_auth($raw_params) == false) + if (zeromq_auth($raw_params) == false) { return ZEROMQ_AUTH_FAIL; + } mwexec_bg("/etc/rc.reboot"); return ZEROMQ_FASLE; } @@ -298,11 +323,13 @@ function reboot_zeromq($raw_params) { function get_notices_zeromq($raw_params) { global $config, $g, $debug; $params = $raw_params; - if(zeromq_auth($raw_params) == false) + if (zeromq_auth($raw_params) == false) { return ZEROMQ_AUTH_FAIL; - if(!function_exists("get_notices")) + } + if (!function_exists("get_notices")) { require("notices.inc"); - if(!$params) { + } + if (!$params) { $toreturn = get_notices(); } else { $toreturn = get_notices($params); From dedc40f7ded5f88aee4720aa8a3a57667b975254 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Tue, 3 Mar 2015 21:47:59 +0545 Subject: [PATCH 159/257] Fix password box in diag_authentication In 2.2 when I go to Diagnostics->Authentication the password field shows the little lock icon, but the text input area starts over the top of the icon and as I type in the field the password "dots" go over the lock icon. This does not happen in 2.1.5 - the password entry cursor sits after the lock icon. This problem is also not evident on most other password entry fields in 2.2 I stared at it for a while, then saw that in other places the password field is not literally called "password", so I thought what the heck, I will change the field name - it fixed the display issue!!! What??? Anyway, this fixes the display issue on my system. If someone knows really why having the field name/id="password" is a problem then they could fix the underlying reason - but this works around whatever is the issue. If you think this is an OK fix then I will also find the couple of other places swhere this happens and make the same "fix". --- usr/local/www/diag_authentication.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/usr/local/www/diag_authentication.php b/usr/local/www/diag_authentication.php index b403db6b53..df68560055 100644 --- a/usr/local/www/diag_authentication.php +++ b/usr/local/www/diag_authentication.php @@ -51,11 +51,11 @@ if ($_POST) { if (!$authcfg) $input_errors[] = $_POST['authmode'] . " " . gettext("is not a valid authentication server"); - if (empty($_POST['username']) || empty($_POST['password'])) + if (empty($_POST['username']) || empty($_POST['passwordfld'])) $input_errors[] = gettext("A username and password must be specified."); if (!$input_errors) { - if (authenticate_user($_POST['username'], $_POST['password'], $authcfg)) { + if (authenticate_user($_POST['username'], $_POST['passwordfld'], $authcfg)) { $savemsg = gettext("User") . ": " . $_POST['username'] . " " . gettext("authenticated successfully."); $groups = getUserGroups($_POST['username'], $authcfg); $savemsg .= "
        " . gettext("This user is a member of these groups") . ":
        "; @@ -112,7 +112,7 @@ include("head.inc"); - + From 1dbe220c9b201550bf9f10c45ab14b8d30c4bacd Mon Sep 17 00:00:00 2001 From: jim-p Date: Tue, 3 Mar 2015 14:18:46 -0500 Subject: [PATCH 160/257] Tweak the carp demotion factors slightly to avoid CARP transitions that are most likely unnecessary. --- etc/inc/globals.inc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/etc/inc/globals.inc b/etc/inc/globals.inc index 2194de1639..c1ae233982 100644 --- a/etc/inc/globals.inc +++ b/etc/inc/globals.inc @@ -166,6 +166,8 @@ $sysctls = array("net.inet.ip.portrange.first" => "1024", "net.enc.out.ipsec_filter_mask" => "0x0001", "net.enc.in.ipsec_bpf_mask" => "0x0002", "net.enc.in.ipsec_filter_mask" => "0x0002" + "net.inet.carp.senderr_demotion_factor" => 0, /* Do not demote CARP for interface send errors */ + "net.pfsync.carp_demotion_factor" => 0 /* Do not demote CARP for pfsync errors */ ); /* Include override values for the above if needed. If the file doesn't exist, don't try to load it. */ From e03b6bbcf5815fb2ddefe6fc16aa6e4c4e60a2eb Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Tue, 3 Mar 2015 23:40:03 -0600 Subject: [PATCH 161/257] Enable UnicastOnly in radvd for ovpn* interfaces. Ticket #4455 --- etc/inc/services.inc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/etc/inc/services.inc b/etc/inc/services.inc index 7fee002f02..a3e584260b 100644 --- a/etc/inc/services.inc +++ b/etc/inc/services.inc @@ -129,6 +129,9 @@ function services_radvd_configure($blacklist = array()) { $radvdconf .= "# Generated for DHCPv6 Server $dhcpv6if\n"; $radvdconf .= "interface {$realif} {\n"; + if (strstr($realif, "ovpn")) { + $radvdconf .= "\tUnicastOnly on;\n"; + } $radvdconf .= "\tAdvSendAdvert on;\n"; $radvdconf .= "\tMinRtrAdvInterval 5;\n"; $radvdconf .= "\tMaxRtrAdvInterval 20;\n"; From 24ad8e26a6437e32afe3330b79d2565c052c993e Mon Sep 17 00:00:00 2001 From: jim-p Date: Wed, 4 Mar 2015 07:22:36 -0500 Subject: [PATCH 162/257] Add missing comma. Fixes #4485 --- etc/inc/globals.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/globals.inc b/etc/inc/globals.inc index c1ae233982..3e6d13d352 100644 --- a/etc/inc/globals.inc +++ b/etc/inc/globals.inc @@ -165,7 +165,7 @@ $sysctls = array("net.inet.ip.portrange.first" => "1024", "net.enc.out.ipsec_bpf_mask" => "0x0001", "net.enc.out.ipsec_filter_mask" => "0x0001", "net.enc.in.ipsec_bpf_mask" => "0x0002", - "net.enc.in.ipsec_filter_mask" => "0x0002" + "net.enc.in.ipsec_filter_mask" => "0x0002", "net.inet.carp.senderr_demotion_factor" => 0, /* Do not demote CARP for interface send errors */ "net.pfsync.carp_demotion_factor" => 0 /* Do not demote CARP for pfsync errors */ ); From 9bfb45ab2810edd13c3799510f5d090d01f82791 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 4 Mar 2015 15:46:30 -0600 Subject: [PATCH 163/257] Skip any numeric-only aliases in the ruleset to prevent errors from those who configured them on previous versions where that was allowed. Ticket --- etc/inc/filter.inc | 5 +++++ etc/inc/util.inc | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index 3e3fb25e8b..af1494bb10 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -707,6 +707,11 @@ function filter_generate_aliases() { $extralias = ""; $aliasnesting = array(); $aliasaddrnesting = array(); + if (is_numericint($aliased['name'])) { + // skip aliases with numeric-only names. redmine #4289 + file_notice("Filter_Reload", "Aliases with numeric-only names are not valid. Skipping alias " . $aliased['name']); + continue; + } $addrlist = filter_generate_nested_alias($aliased['name'], $aliased['address'], $aliasnesting, $aliasaddrnesting); switch ($aliased['type']) { case "host": diff --git a/etc/inc/util.inc b/etc/inc/util.inc index 05b33edacf..2f0b318f5b 100644 --- a/etc/inc/util.inc +++ b/etc/inc/util.inc @@ -1533,6 +1533,10 @@ function alias_get_type($name) { function alias_expand($name) { global $aliastable; + // alias names cannot be strictly numeric. redmine #4289 + if (is_numericint($name)) + return null; + if (isset($aliastable[$name])) { return "\${$name}"; } else if (is_ipaddr($name) || is_subnet($name) || is_port($name) || is_portrange($name)) { From 8106d4467a32b1f19704bad3c928e9fd0282b113 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 4 Mar 2015 16:16:18 -0600 Subject: [PATCH 164/257] allow enabling Unbound when dnsmasq is enabled, if they're using diff ports. Ticket #4332 --- usr/local/www/services_unbound.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/usr/local/www/services_unbound.php b/usr/local/www/services_unbound.php index 4e307b3439..33dbe46edc 100644 --- a/usr/local/www/services_unbound.php +++ b/usr/local/www/services_unbound.php @@ -110,7 +110,8 @@ if ($_POST) { system_dhcpleases_configure(); } else { if (isset($_POST['enable']) && isset($config['dnsmasq']['enable'])) { - $input_errors[] = "The DNS Forwarder is enabled. Disable it before enabling the DNS Resolver."; + if ($_POST['port'] == $config['dnsmasq']['port']) + $input_errors[] = "The DNS Forwarder is enabled using this port. Choose a non-conflicting port, or disable the DNS Forwarder."; } if (empty($_POST['active_interface'])) { From eae1fb1df242d8cc492796890c0d29fc599f76f7 Mon Sep 17 00:00:00 2001 From: jim-p Date: Thu, 5 Mar 2015 09:00:18 -0500 Subject: [PATCH 165/257] Be more strict about the file to restore or delete when working with full backups. --- .../www/system_firmware_restorefullbackup.php | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/usr/local/www/system_firmware_restorefullbackup.php b/usr/local/www/system_firmware_restorefullbackup.php index c482a299c2..b31d096601 100644 --- a/usr/local/www/system_firmware_restorefullbackup.php +++ b/usr/local/www/system_firmware_restorefullbackup.php @@ -87,18 +87,22 @@ if($_GET['downloadbackup']) { } if ($_GET['deletefile']) { - $filename = $_GET['deletefile']; - if(file_exists("/root/{$filename}")) { + $filename = basename($_GET['deletefile']); + if(file_exists("/root/{$filename}") && (preg_match("/pfSense-full-backup-\d+-\d+\.tgz/", $filename) == 1)) { unlink("/root/" . $filename); - $savemsg = gettext("$filename has been deleted."); + $savemsg = htmlspecialchars($filename) . " " . gettext("has been deleted."); + } else { + $savemsg = htmlspecialchars($filename) . " " . gettext("has not been been deleted (invalid backup file or file does not exist)."); } } if ($_POST['restorefile']) { - $filename = $_POST['restorefile']; - if(file_exists("/root/{$filename}")) { + $filename = basename($_POST['restorefile']); + if(file_exists("/root/{$filename}") && (preg_match("/pfSense-full-backup-\d+-\d+\.tgz/", $filename) == 1)) { mwexec_bg("/etc/rc.restore_full_backup /root/" . escapeshellcmd($filename)); - $savemsg = gettext("The firewall is currently restoring $filename"); + $savemsg = gettext("The firewall is currently restoring") . " " . htmlspecialchars($filename); + } else { + $savemsg = htmlspecialchars($filename) . " " . gettext("has not been been restored (invalid backup file or file does not exist)."); } } From 44a06d7de570f3f3faea4d48647280b4b431fdc0 Mon Sep 17 00:00:00 2001 From: jim-p Date: Thu, 5 Mar 2015 09:32:05 -0500 Subject: [PATCH 166/257] Improve validation and encoding of the zone for Captive Portal Status --- usr/local/www/status_captiveportal.php | 33 +++++++++++++++----------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/usr/local/www/status_captiveportal.php b/usr/local/www/status_captiveportal.php index 5c608c4fd4..90d3d28fbe 100644 --- a/usr/local/www/status_captiveportal.php +++ b/usr/local/www/status_captiveportal.php @@ -60,6 +60,11 @@ $a_cp =& $config['captiveportal']; if (count($a_cp) == 1) $cpzone = current(array_keys($a_cp)); +/* If the zone does not exist, do not display the invalid zone */ +if (!array_key_exists($cpzone, $a_cp)) { + $cpzone = ""; +} + if (isset($cpzone) && !empty($cpzone) && isset($a_cp[$cpzone]['zoneid'])) $cpzoneid = $a_cp[$cpzone]['zoneid']; @@ -112,11 +117,11 @@ $mac_man = load_mac_manufacturer_table(); @@ -135,7 +140,7 @@ $mac_man = load_mac_manufacturer_table();
        - + @@ -154,14 +159,14 @@ $mac_man = load_mac_manufacturer_table(); - - - + + + - - + + - + @@ -187,7 +192,7 @@ $mac_man = load_mac_manufacturer_table(); - ')">"> + ')">"> From c678ca656b66d2135277bbed1f890e84555f6a27 Mon Sep 17 00:00:00 2001 From: jim-p Date: Thu, 5 Mar 2015 09:40:32 -0500 Subject: [PATCH 167/257] Jettison unused dragtable code from firewall_rules.php, it was broken and inactive and only causing trouble. --- usr/local/www/firewall_rules.php | 94 +------------------------------- 1 file changed, 2 insertions(+), 92 deletions(-) diff --git a/usr/local/www/firewall_rules.php b/usr/local/www/firewall_rules.php index 6110afb5e4..c05b0010a9 100644 --- a/usr/local/www/firewall_rules.php +++ b/usr/local/www/firewall_rules.php @@ -75,54 +75,6 @@ if ($_POST['if']) $ifdescs = get_configured_interface_with_descr(); -// Drag and drop reordering -if($_REQUEST['dragdroporder']) { - // First create a new ruleset array and tmp arrays - $a_filter_before = array(); - $a_filter_order = array(); - $a_filter_order_tmp = array(); - $a_filter_after = array(); - $found = false; - $drag_order = $_REQUEST['dragtable']; - // Next traverse through rules building a new order for interface - for ($i = 0; isset($a_filter[$i]); $i++) { - if(( $_REQUEST['if'] == "FloatingRules" && isset($a_filter[$i]['floating']) ) || ( $a_filter[$i]['interface'] == $_REQUEST['if'] && !isset($a_filter[$i]['floating']) )) { - $a_filter_order_tmp[] = $a_filter[$i]; - $found = true; - } else if (!$found) - $a_filter_before[] = $a_filter[$i]; - else - $a_filter_after[] = $a_filter[$i]; - } - // Reorder rules with the posted order - for ($i = 0; $i

        -You must apply the changes in order for them to take effect."), "apply" , gettext("Apply changes") , "firewall_rules.php?if={$_REQUEST['if']}&dragdroporder=true&{$dragtable}"); -} else { - print_info_box_np(gettext("The firewall rule configuration has been changed.") . "
        " . gettext("You must apply the changes in order for them to take effect."), "apply", "", true); -} -?> +" . gettext("You must apply the changes in order for them to take effect."), "apply", "", true); ?>
        -

        - loader -

         

        -
        @@ -467,7 +407,7 @@ if($_REQUEST['undodrag']) { - + - From e52c3c88cb63624f08cce977ca1f512c28b32f3c Mon Sep 17 00:00:00 2001 From: jim-p Date: Thu, 5 Mar 2015 09:55:00 -0500 Subject: [PATCH 168/257] Stricter validation and encoding for traffic shaper queues. --- usr/local/www/firewall_shaper.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/firewall_shaper.php b/usr/local/www/firewall_shaper.php index 99ec1f6bc7..835085bd71 100644 --- a/usr/local/www/firewall_shaper.php +++ b/usr/local/www/firewall_shaper.php @@ -64,7 +64,7 @@ read_altq_config(); if ($_GET) { if ($_GET['queue']) - $qname = trim($_GET['queue']); + $qname = htmlspecialchars(trim($_GET['queue'])); if ($_GET['interface']) $interface = htmlspecialchars(trim($_GET['interface'])); if ($_GET['action']) @@ -164,7 +164,7 @@ if ($_GET) { $q->SetInterface($interface); $output_form .= $q->build_form(); $output_form .= ""; + $output_form .= " value=\"".htmlspecialchars($qname)."\" />"; $newjavascript = $q->build_javascript(); unset($q); $newqueue = true; From 32787389519d667b94da5f0884d4bd1045d89838 Mon Sep 17 00:00:00 2001 From: jim-p Date: Thu, 5 Mar 2015 10:00:56 -0500 Subject: [PATCH 169/257] Do not render the services_unbound_acls page with an invalid ID. --- usr/local/www/services_unbound_acls.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/usr/local/www/services_unbound_acls.php b/usr/local/www/services_unbound_acls.php index 936f3eeacf..7a1af28e01 100644 --- a/usr/local/www/services_unbound_acls.php +++ b/usr/local/www/services_unbound_acls.php @@ -46,6 +46,11 @@ if (isset($_POST['aclid'])) { $id = $_POST['aclid']; } +if (!empty($id) && !is_numeric($id)) { + pfSenseHeader("services_unbound_acls.php"); + exit; +} + $act = $_GET['act']; if (isset($_POST['act'])) { $act = $_POST['act']; From 6d1db7eca805d632c12e794a52715e3d703fefc6 Mon Sep 17 00:00:00 2001 From: jim-p Date: Thu, 5 Mar 2015 10:08:52 -0500 Subject: [PATCH 170/257] Encode and check values for filtering variables in diag_logs_filter.php --- usr/local/www/diag_logs_filter.php | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/usr/local/www/diag_logs_filter.php b/usr/local/www/diag_logs_filter.php index a0640c3933..7dac52b909 100644 --- a/usr/local/www/diag_logs_filter.php +++ b/usr/local/www/diag_logs_filter.php @@ -114,7 +114,7 @@ $nentries = $config['syslog']['nentries']; if ($filterlogentries_qty) $nentries = $filterlogentries_qty; -if (!$nentries) +if (!$nentries || !is_numeric($nentries)) $nentries = 50; if ($_POST['clear']) @@ -179,41 +179,41 @@ include("head.inc");
        -
        +
        -
        +
        -
        +
        -
        +
        -
        +
        -
        +
        -
        +
        -
        +
        -
        +
        " />
        @@ -271,11 +271,11 @@ include("head.inc");
        -
        +
        -
        +
         
        @@ -313,7 +313,7 @@ include("head.inc"); From 5c7c369f5f2c9584ad53a5657965deb2d6661da2 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 5 Mar 2015 19:35:12 -0600 Subject: [PATCH 171/257] Remove the harden-glue option entirely and hard code it to yes. Ticket #4402 --- conf.default/config.xml | 1 - etc/inc/unbound.inc | 3 +-- usr/local/www/services_unbound_advanced.php | 15 --------------- 3 files changed, 1 insertion(+), 18 deletions(-) diff --git a/conf.default/config.xml b/conf.default/config.xml index a728142cef..46afa50872 100644 --- a/conf.default/config.xml +++ b/conf.default/config.xml @@ -274,7 +274,6 @@ - diff --git a/etc/inc/unbound.inc b/etc/inc/unbound.inc index bef0f4a794..22abb5d7b2 100644 --- a/etc/inc/unbound.inc +++ b/etc/inc/unbound.inc @@ -213,7 +213,6 @@ EOF; $port = (is_port($config['unbound']['port'])) ? $config['unbound']['port'] : "53"; $hide_identity = isset($config['unbound']['hideidentity']) ? "yes" : "no"; $hide_version = isset($config['unbound']['hideversion']) ? "yes" : "no"; - $harden_glue = isset($config['unbound']['hardenglue']) ? "yes" : "no"; $harden_dnssec_stripped = isset($config['unbound']['dnssecstripped']) ? "yes" : "no"; $prefetch = isset($config['unbound']['prefetch']) ? "yes" : "no"; $prefetch_key = isset($config['unbound']['prefetchkey']) ? "yes" : "no"; @@ -290,7 +289,7 @@ port: {$port} verbosity: {$verbosity} hide-identity: {$hide_identity} hide-version: {$hide_version} -harden-glue: {$harden_glue} +harden-glue: yes do-ip4: yes do-ip6: yes do-udp: yes diff --git a/usr/local/www/services_unbound_advanced.php b/usr/local/www/services_unbound_advanced.php index 0bd7bfc365..56c52b6611 100644 --- a/usr/local/www/services_unbound_advanced.php +++ b/usr/local/www/services_unbound_advanced.php @@ -58,9 +58,6 @@ if (isset($config['unbound']['prefetch'])) { if (isset($config['unbound']['prefetchkey'])) { $pconfig['prefetchkey'] = true; } -if (isset($config['unbound']['hardenglue'])) { - $pconfig['hardenglue'] = true; -} if (isset($config['unbound']['dnssecstripped'])) { $pconfig['dnssecstripped'] = true; } @@ -153,11 +150,6 @@ if ($_POST) { } else { unset($config['unbound']['prefetchkey']); } - if (isset($_POST['hardenglue'])) { - $config['unbound']['hardenglue'] = true; - } else { - unset($config['unbound']['hardenglue']); - } if (isset($_POST['dnssecstripped'])) { $config['unbound']['dnssecstripped'] = true; } else { @@ -257,13 +249,6 @@ include_once("head.inc"); ", "");?> - - - - />
        - - - From 879d59d88a25e85cae5b9b117888b3f231cdbaf7 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 5 Mar 2015 21:40:23 -0600 Subject: [PATCH 172/257] Don't save config if input validation fails. Add input validation preventing "Harden DNSSEC Data" from being enabled if DNSSEC support isn't enabled. --- usr/local/www/services_unbound_advanced.php | 103 +++++++++++--------- 1 file changed, 55 insertions(+), 48 deletions(-) diff --git a/usr/local/www/services_unbound_advanced.php b/usr/local/www/services_unbound_advanced.php index 56c52b6611..0712ce9a8c 100644 --- a/usr/local/www/services_unbound_advanced.php +++ b/usr/local/www/services_unbound_advanced.php @@ -130,56 +130,63 @@ if ($_POST) { if (isset($_POST['log_verbosity']) && !in_array($_POST['log_verbosity'], array('0', '1', '2', '3', '4', '5'), true)) { $input_errors[] = "A valid value must be specified for Log level verbosity."; } - if (isset($_POST['hideidentity'])) { - $config['unbound']['hideidentity'] = true; - } else { - unset($config['unbound']['hideidentity']); + if (isset($_POST['dnssecstripped']) && !isset($config['unbound']['dnssec'])) { + $input_errors[] = "Harden DNSSEC Data option can only be enabled if DNSSEC support is enabled."; } - if (isset($_POST['hideversion'])) { - $config['unbound']['hideversion'] = true; - } else { - unset($config['unbound']['hideversion']); - } - if (isset($_POST['prefetch'])) { - $config['unbound']['prefetch'] = true; - } else { - unset($config['unbound']['prefetch']); - } - if (isset($_POST['prefetchkey'])) { - $config['unbound']['prefetchkey'] = true; - } else { - unset($config['unbound']['prefetchkey']); - } - if (isset($_POST['dnssecstripped'])) { - $config['unbound']['dnssecstripped'] = true; - } else { - unset($config['unbound']['dnssecstripped']); - } - $config['unbound']['msgcachesize'] = $_POST['msgcachesize']; - $config['unbound']['outgoing_num_tcp'] = $_POST['outgoing_num_tcp']; - $config['unbound']['incoming_num_tcp'] = $_POST['incoming_num_tcp']; - $config['unbound']['edns_buffer_size'] = $_POST['edns_buffer_size']; - $config['unbound']['num_queries_per_thread'] = $_POST['num_queries_per_thread']; - $config['unbound']['jostle_timeout'] = $_POST['jostle_timeout']; - $config['unbound']['cache_max_ttl'] = $_POST['cache_max_ttl']; - $config['unbound']['cache_min_ttl'] = $_POST['cache_min_ttl']; - $config['unbound']['infra_host_ttl'] = $_POST['infra_host_ttl']; - $config['unbound']['infra_cache_numhosts'] = $_POST['infra_cache_numhosts']; - $config['unbound']['unwanted_reply_threshold'] = $_POST['unwanted_reply_threshold']; - $config['unbound']['log_verbosity'] = $_POST['log_verbosity']; - if (isset($_POST['disable_auto_added_access_control'])) { - $config['unbound']['disable_auto_added_access_control'] = true; - } else { - unset($config['unbound']['disable_auto_added_access_control']); - } - if (isset($_POST['use_caps'])) { - $config['unbound']['use_caps'] = true; - } else { - unset($config['unbound']['use_caps']); - } - write_config("DNS Resolver configured."); + + if (!$input_errors) { - mark_subsystem_dirty('unbound'); + if (isset($_POST['hideidentity'])) { + $config['unbound']['hideidentity'] = true; + } else { + unset($config['unbound']['hideidentity']); + } + if (isset($_POST['hideversion'])) { + $config['unbound']['hideversion'] = true; + } else { + unset($config['unbound']['hideversion']); + } + if (isset($_POST['prefetch'])) { + $config['unbound']['prefetch'] = true; + } else { + unset($config['unbound']['prefetch']); + } + if (isset($_POST['prefetchkey'])) { + $config['unbound']['prefetchkey'] = true; + } else { + unset($config['unbound']['prefetchkey']); + } + if (isset($_POST['dnssecstripped'])) { + $config['unbound']['dnssecstripped'] = true; + } else { + unset($config['unbound']['dnssecstripped']); + } + $config['unbound']['msgcachesize'] = $_POST['msgcachesize']; + $config['unbound']['outgoing_num_tcp'] = $_POST['outgoing_num_tcp']; + $config['unbound']['incoming_num_tcp'] = $_POST['incoming_num_tcp']; + $config['unbound']['edns_buffer_size'] = $_POST['edns_buffer_size']; + $config['unbound']['num_queries_per_thread'] = $_POST['num_queries_per_thread']; + $config['unbound']['jostle_timeout'] = $_POST['jostle_timeout']; + $config['unbound']['cache_max_ttl'] = $_POST['cache_max_ttl']; + $config['unbound']['cache_min_ttl'] = $_POST['cache_min_ttl']; + $config['unbound']['infra_host_ttl'] = $_POST['infra_host_ttl']; + $config['unbound']['infra_cache_numhosts'] = $_POST['infra_cache_numhosts']; + $config['unbound']['unwanted_reply_threshold'] = $_POST['unwanted_reply_threshold']; + $config['unbound']['log_verbosity'] = $_POST['log_verbosity']; + if (isset($_POST['disable_auto_added_access_control'])) { + $config['unbound']['disable_auto_added_access_control'] = true; + } else { + unset($config['unbound']['disable_auto_added_access_control']); + } + if (isset($_POST['use_caps'])) { + $config['unbound']['use_caps'] = true; + } else { + unset($config['unbound']['use_caps']); + } + write_config("DNS Resolver configured."); + + mark_subsystem_dirty('unbound'); + } } } From f54229df8cb7d80f0da888dd04001e732470b1d0 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 5 Mar 2015 22:12:32 -0600 Subject: [PATCH 173/257] fix up text --- .../share/locale/en/LC_MESSAGES/pfSense.pot | 4 ++-- .../share/locale/ja/LC_MESSAGES/pfSense.po | 4 ++-- .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo | Bin 643027 -> 643027 bytes .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po | 4 ++-- .../share/locale/tr/LC_MESSAGES/pfSense.mo | Bin 578284 -> 578284 bytes .../share/locale/tr/LC_MESSAGES/pfSense.po | 4 ++-- usr/local/www/firewall_rules_edit.php | 4 ++-- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot index c9ba827cd8..aeefa9af4a 100644 --- a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot +++ b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot @@ -11894,7 +11894,7 @@ msgstr "" #: usr/local/www/firewall_rules_edit.php:382 #, php-format -msgid "%s is only valid with protocol tcp." +msgid "%s is only valid with protocol TCP." msgstr "" #: usr/local/www/firewall_rules_edit.php:384 @@ -11928,7 +11928,7 @@ msgid "You can not use a IPv4 or IPv6 address in combined IPv4 + IPv6 rules." msgstr "" #: usr/local/www/firewall_rules_edit.php:495 -msgid "OS detection is only valid with protocol tcp." +msgid "OS detection is only valid with protocol TCP." msgstr "" #: usr/local/www/firewall_rules_edit.php:497 diff --git a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po index afac78fa55..af481c115f 100644 --- a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po @@ -19316,7 +19316,7 @@ msgstr "ã‚ãªãŸã¯ã€IPv4フィルタルールã«IPv6ゲートウェイを割 #: usr/local/www/firewall_rules_edit.php:329 #: usr/local/www/firewall_rules_edit.php:329 #, php-format -msgid "%s is only valid with protocol tcp." +msgid "%s is only valid with protocol TCP." msgstr "%sã¯ãƒ—ロトコルTCPã§ã®ã¿æœ‰åйã§ã™ã€‚" #: usr/local/www/firewall_rules_edit.php:299 @@ -19376,7 +19376,7 @@ msgstr "ã‚ãªãŸã¯ã€IPv6ルールã§IPv4アドレスを使用ã™ã‚‹ã“ã¨ã¯ #: usr/local/www/firewall_rules_edit.php:436 #: usr/local/www/firewall_rules_edit.php:442 #: usr/local/www/firewall_rules_edit.php:442 -msgid "OS detection is only valid with protocol tcp." +msgid "OS detection is only valid with protocol TCP." msgstr "OS検出ã€ãƒ—ロトコルã¯TCPã§ã®ã¿æœ‰åйã§ã™ã€‚" #: usr/local/www/firewall_rules_edit.php:406 diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo index e0a0fb23ec05d39e882c8e06590341aed60abd97..f1fc3357e36d34c541a3e175f46f31f20981f885 100644 GIT binary patch delta 59 zcmcaSU;XlY^@c5syjPh+oCDegt}<>HxXSeWKA87w3v>IgEi6FH3dC$c%nrmH+kb80 HyeS0$EqxrX delta 59 zcmcaSU;XlY^@c5syjPh^k_*}et}<>HxXSeWKA87w3v>IgEi6FH3dC$c%nrmH+kb80 HyeS0$O1&L# diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po index 81c5b3da09..5a4f366f0e 100644 --- a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po @@ -16255,7 +16255,7 @@ msgstr "Voc #: usr/local/www/firewall_rules_edit.php:323 #: usr/local/www/firewall_rules_edit.php:329 #, php-format -msgid "%s is only valid with protocol tcp." +msgid "%s is only valid with protocol TCP." msgstr "%s é válido somente com o protocolo TCP." #: usr/local/www/firewall_rules_edit.php:299 @@ -16306,7 +16306,7 @@ msgstr "Voc #: usr/local/www/firewall_rules_edit.php:433 #: usr/local/www/firewall_rules_edit.php:436 #: usr/local/www/firewall_rules_edit.php:442 -msgid "OS detection is only valid with protocol tcp." +msgid "OS detection is only valid with protocol TCP." msgstr "Detecção de OS somente é válida com o protocolo tcp." #: usr/local/www/firewall_rules_edit.php:406 diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.mo index 37a2f27435d06f43bc01afcaecd9e7818f59647c..f0131a01162dafd2cc8840a5363498008587f307 100644 GIT binary patch delta 68 zcmaE}RQb(P<%TVc{A-y*oCDg0)-rAvTFdldGdGZ@$Kan-l9-t{-M^kmzFjAg8Hibc Rm=%cGfS7%|P9n#FLI7;r7oz|G delta 68 zcmaE}RQb(P<%TVc{A-y@k_*~})-rAvTFdldGdGZ@$Kan-l9-t{-M^kmzFjAg8Hibc Rm=%cGfS7%|P9n#FLI9B47-Ikc diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po index e3753eb14c..4de2d6f1be 100644 --- a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po @@ -12345,7 +12345,7 @@ msgstr "IPv4 ve IPv6 için uygulanacak ICMP türü kurallarını atayamazsınız #: usr/local/www/firewall_rules_edit.php:382 #, php-format -msgid "%s is only valid with protocol tcp." +msgid "%s is only valid with protocol TCP." msgstr "%s sadece TCP protokolü ile çalışır." #: usr/local/www/firewall_rules_edit.php:384 @@ -12383,7 +12383,7 @@ msgstr "" "kullanamazsınız." #: usr/local/www/firewall_rules_edit.php:495 -msgid "OS detection is only valid with protocol tcp." +msgid "OS detection is only valid with protocol TCP." msgstr "İşletim sistemi tespiti sadece TCP protokolünde çalışır." #: usr/local/www/firewall_rules_edit.php:497 diff --git a/usr/local/www/firewall_rules_edit.php b/usr/local/www/firewall_rules_edit.php index 37a694cd3b..24be80dc63 100644 --- a/usr/local/www/firewall_rules_edit.php +++ b/usr/local/www/firewall_rules_edit.php @@ -379,7 +379,7 @@ if ($_POST) { if($_POST['statetype'] == "modulate state" or $_POST['statetype'] == "synproxy state") { if( $_POST['proto'] != "tcp" ) - $input_errors[] = sprintf(gettext("%s is only valid with protocol tcp."),$_POST['statetype']); + $input_errors[] = sprintf(gettext("%s is only valid with protocol TCP."),$_POST['statetype']); if(($_POST['statetype'] == "synproxy state") && ($_POST['gateway'] != "")) $input_errors[] = sprintf(gettext("%s is only valid if the gateway is set to 'default'."),$_POST['statetype']); } @@ -492,7 +492,7 @@ if ($_POST) { } if ($_POST['os']) { if( $_POST['proto'] != "tcp" ) - $input_errors[] = gettext("OS detection is only valid with protocol tcp."); + $input_errors[] = gettext("OS detection is only valid with protocol TCP."); if (!in_array($_POST['os'], $ostypes)) $input_errors[] = gettext("Invalid OS detection selection. Please select a valid OS."); } From a97a77a2a52184476e78e6f697b8d44706eb5692 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Fri, 6 Mar 2015 10:12:08 +0545 Subject: [PATCH 174/257] Be nicer when checking if alias is numeric Because an ordinary port can be numeric here. Forum https://forum.pfsense.org/index.php?topic=89906.0 --- etc/inc/util.inc | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/etc/inc/util.inc b/etc/inc/util.inc index 2f0b318f5b..6dc24ded8a 100644 --- a/etc/inc/util.inc +++ b/etc/inc/util.inc @@ -1533,11 +1533,11 @@ function alias_get_type($name) { function alias_expand($name) { global $aliastable; - // alias names cannot be strictly numeric. redmine #4289 - if (is_numericint($name)) - return null; - if (isset($aliastable[$name])) { + // alias names cannot be strictly numeric. redmine #4289 + if (is_numericint($name)) { + return null; + } return "\${$name}"; } else if (is_ipaddr($name) || is_subnet($name) || is_port($name) || is_portrange($name)) { return "{$name}"; From df966626606fe7c60c3d7301f3843280b746a7a6 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 5 Mar 2015 23:49:14 -0600 Subject: [PATCH 175/257] Destroy stf interface when 6rd or 6to4 tunnel is disabled. Fixes #4471 --- etc/inc/interfaces.inc | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index c27958a934..850b2137ed 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -1318,9 +1318,15 @@ function interface_bring_down($interface = "wan", $destroy = false, $ifacecfg = case "6to4": $realif = "{$interface}_stf"; if (does_interface_exist("$realif")) { - $ip6 = get_interface_ipv6($interface); - if (is_ipaddrv6($ip6)) { - mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 {$ip6} delete", true); + /* destroy stf interface if tunnel is being disabled or tunnel type is being changed */ + if (($ifcfg['ipaddrv6'] == '6rd' && (!isset($config['interfaces'][$interface]['ipaddrv6']) || $config['interfaces'][$interface]['ipaddrv6'] != '6rd')) || + ($ifcfg['ipaddrv6'] == '6to4' && (!isset($config['interfaces'][$interface]['ipaddrv6']) || $config['interfaces'][$interface]['ipaddrv6'] != '6to4'))) { + $destroy = true; + } else { + /* get_interface_ipv6() returns empty value if interface is being disabled */ + $ip6 = get_interface_ipv6($interface); + if (is_ipaddrv6($ip6)) + mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " inet6 {$ip6} delete", true); } interface_ipalias_cleanup($interface, "inet6"); if ($destroy == true) { From 29de629ebd363c4d3e34d1a7bc68bd8d7f8a4c47 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Fri, 6 Mar 2015 00:39:31 -0600 Subject: [PATCH 176/257] Use the parent interface, not the _vip for interfaces_use. Part of Ticket #4482 --- etc/inc/vpn.inc | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 3ec14dedb9..f1dbfd6f3a 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -185,7 +185,10 @@ function vpn_ipsec_configure($restart = false) $ifacesuse[] = get_real_interface($vpninterface[0]); } else { $vpninterface = get_failover_interface($ph1ent['interface']); - if (!empty($vpninterface)) + if (strpos($vpninterface, '_vip')) { + $vpninterface = explode('_vip', $vpninterface); + $ifacesuse[] = get_real_interface($vpninterface[0]); + } elseif (!empty($vpninterface)) $ifacesuse[] = $vpninterface; } @@ -620,7 +623,13 @@ EOD; $vpninterface = $vpninterface[0]; } else { $ifacesuse = get_failover_interface($ph1ent['interface']); - $vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse); + if (strpos($ifacesuse, '_vip')) { + $vpninterface = explode('_vip', $ifacesuse); + $ifacesuse = get_real_interface($vpninterface[0]); + $vpninterface = $vpninterface[0]; + } else { + $vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse); + } } if (!empty($ifacesuse) && interface_has_gateway($vpninterface)) { From c406924f3ef4996ff0eaa5fc6cf1a04c39220a5f Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Fri, 6 Mar 2015 00:45:37 -0600 Subject: [PATCH 177/257] same change as previous commit, for IPv6. Ticket #4482 --- etc/inc/vpn.inc | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index f1dbfd6f3a..1a3902cc68 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -652,7 +652,13 @@ EOD; $vpninterface = $vpninterface[0]; } else { $ifacesuse = get_failover_interface($ph1ent['interface']); - $vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse); + if (strpos($ifacesuse, '_vip')) { + $vpninterface = explode('_vip', $ifacesuse); + $ifacesuse = get_real_interface($vpninterface[0]); + $vpninterface = $vpninterface[0]; + } else { + $vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse); + } } if (!empty($ifacesuse) && interface_has_gateway($vpninterface)) { From a115e2e14a79a06cfd9a60ae9b534aed074c060c Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Fri, 6 Mar 2015 00:55:42 -0600 Subject: [PATCH 178/257] Use get_failover_interface here to find appropriate interface. Ticket #4482 --- etc/inc/ipsec.inc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/etc/inc/ipsec.inc b/etc/inc/ipsec.inc index 0780e2f1c4..bbc5ac2647 100644 --- a/etc/inc/ipsec.inc +++ b/etc/inc/ipsec.inc @@ -193,10 +193,11 @@ function ipsec_get_phase1_src(& $ph1ent) { if ($ph1ent['interface']) { if (!is_ipaddr($ph1ent['interface'])) { + $if = get_failover_interface($ph1ent['interface']); if ($ph1ent['protocol'] == "inet6") { - $interfaceip = get_interface_ipv6($ph1ent['interface']); + $interfaceip = get_interface_ipv6($if); } else { - $interfaceip = get_interface_ip($ph1ent['interface']); + $interfaceip = get_interface_ip($if); } } else { $interfaceip=$ph1ent['interface']; From 8cb4f5b12ac9784c4f39e6dc15950e4b97de08cb Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Fri, 6 Mar 2015 03:35:47 -0600 Subject: [PATCH 179/257] touch up text --- usr/local/share/locale/en/LC_MESSAGES/pfSense.pot | 2 +- usr/local/share/locale/tr/LC_MESSAGES/pfSense.po | 2 +- usr/local/www/services_ntpd.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot index aeefa9af4a..9e357dd89e 100644 --- a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot +++ b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot @@ -20908,7 +20908,7 @@ msgid "" msgstr "" #: usr/local/www/services_ntpd.php:327 -msgid "Enable rrd graphs of NTP statistics (default: disabled)." +msgid "Enable RRD graphs of NTP statistics (default: disabled)." msgstr "" #: usr/local/www/services_ntpd.php:333 diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po index 4de2d6f1be..cfe8aa028a 100644 --- a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po @@ -22172,7 +22172,7 @@ msgid "" msgstr "" #: usr/local/www/services_ntpd.php:327 -msgid "Enable rrd graphs of NTP statistics (default: disabled)." +msgid "Enable RRD graphs of NTP statistics (default: disabled)." msgstr "" #: usr/local/www/services_ntpd.php:333 diff --git a/usr/local/www/services_ntpd.php b/usr/local/www/services_ntpd.php index 8c2dcaa6a0..88b38fa263 100644 --- a/usr/local/www/services_ntpd.php +++ b/usr/local/www/services_ntpd.php @@ -326,7 +326,7 @@ include("head.inc"); NTP graphs /> - + From 4ad7848c25221221c287c70e0c53c98aa3f05926 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Fri, 6 Mar 2015 16:43:04 +0545 Subject: [PATCH 180/257] DNS Forwarder Host Override Edit make the pencil symbols appear In most places in the GUI a little pencil symbol appears before text input fields. For example it already appears for the Host, Domain and Description fields in this very form when you "Enter additional names for this host." But in the main 4 fields of this form, the pencil does not display. This fixes it to be the same as elsewhere. I guess this is the "standard" supposed to be used. If so, then I will find the other places where class="formfld unknown" has the "unknown" missing. --- usr/local/www/services_dnsmasq_edit.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/usr/local/www/services_dnsmasq_edit.php b/usr/local/www/services_dnsmasq_edit.php index 3eaf27d061..d8d168ad1e 100644 --- a/usr/local/www/services_dnsmasq_edit.php +++ b/usr/local/www/services_dnsmasq_edit.php @@ -214,7 +214,7 @@ include("head.inc"); - +

        @@ -222,21 +222,21 @@ include("head.inc"); - +

        - +

        192.168.100.100 fd00:abcd::1
        - +
        From 277810659aa80c7a8f30a35e1575a7796007ce51 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Fri, 6 Mar 2015 11:26:18 -0300 Subject: [PATCH 181/257] Remove multiple spaces from dns_split as a seatbelt, also fix the message since field is expected to be space separated and not comma. Ticket #4418 --- usr/local/www/vpn_ipsec_mobile.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/usr/local/www/vpn_ipsec_mobile.php b/usr/local/www/vpn_ipsec_mobile.php index 2b70809be1..8fed8e9cdc 100644 --- a/usr/local/www/vpn_ipsec_mobile.php +++ b/usr/local/www/vpn_ipsec_mobile.php @@ -146,6 +146,8 @@ if ($_POST['submit']) { if ($pconfig['dns_split_enable']) { if (!empty($pconfig['dns_split'])) { + /* Replace multiple spaces by single */ + $pconfig['dns_split'] = preg_replace('/\s+/', ' ', trim($pconfig['dns_split'])); $domain_array=explode(' ', $pconfig['dns_split']); foreach ($domain_array as $curdomain) { if (!is_domain($curdomain)) { @@ -513,7 +515,7 @@ function login_banner_change() { onclick="dns_split_change()" /> -
        +
        From 877740eed5c70124c86281b24e8709ae734934a6 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Fri, 6 Mar 2015 11:28:40 -0300 Subject: [PATCH 182/257] dns_split was a comma separated list and moved to use space as separator, provide upgrade code to make sure old configs are converted. Since there was a config upgrade version 11.7 only on master, I pushed it to 11.8 and used dns_split one as 11.7 to be able to backport it to RELENG_2_2. Ticket #4418 --- conf.default/config.xml | 2 +- etc/inc/globals.inc | 2 +- etc/inc/upgrade_config.inc | 13 +++++++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/conf.default/config.xml b/conf.default/config.xml index 46afa50872..6a6da59da5 100644 --- a/conf.default/config.xml +++ b/conf.default/config.xml @@ -1,6 +1,6 @@ - 11.7 + 11.8 pfsense_ng diff --git a/etc/inc/globals.inc b/etc/inc/globals.inc index 3e6d13d352..caf06ae2a7 100644 --- a/etc/inc/globals.inc +++ b/etc/inc/globals.inc @@ -73,7 +73,7 @@ $g = array( "disablecrashreporter" => false, "crashreporterurl" => "https://crashreporter.pfsense.org/crash_reporter.php", "debug" => false, - "latest_config" => "11.7", + "latest_config" => "11.8", "nopkg_platforms" => array("cdrom"), "minimum_ram_warning" => "101", "minimum_ram_warning_text" => "128 MB", diff --git a/etc/inc/upgrade_config.inc b/etc/inc/upgrade_config.inc index 89bef330a9..bdba3ebb7f 100644 --- a/etc/inc/upgrade_config.inc +++ b/etc/inc/upgrade_config.inc @@ -3738,6 +3738,19 @@ function upgrade_115_to_116() { function upgrade_116_to_117() { global $config; + if (!isset($config['ipsec']['client']) || + !isset($config['ipsec']['client']['dns_split']) || + empty($config['ipsec']['client']['dns_split'])) { + return; + } + + $config['ipsec']['client']['dns_split'] = + preg_replace('/\s*,\s*/', ' ', trim($config['ipsec']['client']['dns_split'])); +} + +function upgrade_117_to_118() { + global $config; + if (!isset($config['installedpackages']['miniupnpd']['config'][0])) { return; } From b93bc1fd4995e731a51d461c8c4b08610ddbf7c1 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Fri, 6 Mar 2015 11:29:25 -0300 Subject: [PATCH 183/257] Stop trying to fix dns_split during strongswan config generation, we have an upgrade code in place for that, it should fix #4418 --- etc/inc/vpn.inc | 8 -------- 1 file changed, 8 deletions(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 1a3902cc68..1299859a31 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -414,14 +414,6 @@ EOD; } if (!empty($a_client['dns_split'])) { - $ipsec_dns = explode(',', $a_client['dns_split']); - foreach ($ipsec_dns as $ipsecidx => $ipsecdns) { - $ipsecdns = trim($ipsecdns); - $ipsec_dns[$ipsecidx] = "\"{$ipsecdns}\""; - } - $a_client['dns_split'] = implode(' ', $ipsec_dns); - unset($ipsec_dns); - $strongswan .= "\t\t\t28675 = {$a_client['dns_split']}\n"; } From 588d3cf606229474acf28920d4f66c415b896aa8 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Fri, 6 Mar 2015 11:45:30 -0300 Subject: [PATCH 184/257] Check if it's an array before call foreach(). Ticket --- etc/inc/vpn.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 1299859a31..c271224101 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -382,7 +382,7 @@ EOD; $strongswan .= "\t\t\tnbns = " . implode(",", $cfgservers) . "\n"; unset($cfgservers); - if (isset($a_client['net_list'])) { + if (isset($a_client['net_list']) && is_array($a_phase2)) { $net_list = ''; foreach ($a_phase2 as $ph2ent) { if (isset($ph2ent['disabled'])) From 0a4fbd990e6f529d32aed440fb9c806cd25ee06d Mon Sep 17 00:00:00 2001 From: jim-p Date: Fri, 6 Mar 2015 12:26:21 -0500 Subject: [PATCH 185/257] Expand CARP demotion error, add button to reset demotion status. --- usr/local/www/carp_status.php | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/usr/local/www/carp_status.php b/usr/local/www/carp_status.php index fc8de57be4..1faebf0818 100644 --- a/usr/local/www/carp_status.php +++ b/usr/local/www/carp_status.php @@ -112,7 +112,13 @@ if($_POST['disablecarp'] <> "") { } } -$carp_detected_problems = ((get_single_sysctl("net.inet.carp.demotion")) > 0); +$carp_detected_problems = get_single_sysctl("net.inet.carp.demotion"); + +if (!empty($_POST['resetdemotion'])) { + set_single_sysctl("net.inet.carp.demotion", "-{$carp_detected_problems}"); + sleep(1); + $carp_detected_problems = get_single_sysctl("net.inet.carp.demotion"); +} $pgtitle = array(gettext("Status"),gettext("CARP")); $shortcut_section = "carp"; @@ -125,8 +131,21 @@ include("head.inc");
        -" . gettext("Check link status on all interfaces with configured CARP VIPs.")); ?> + 0) { + print_info_box( + gettext("CARP has detected a problem and this unit has been demoted to BACKUP status.") . "
        " . + gettext("Check the link status on all interfaces with configured CARP VIPs.") . "
        " . + gettext("Search the") . + " " . + gettext("system log") . + " " . + gettext("for CARP demotion-related events.") . "
        " . + "" + ); +} ?>
        @@ -195,6 +214,7 @@ include("head.inc"); $icon = "\"init\""; } else $icon = ""; + } } echo ""; echo ""; From 08af94cb8931fde47e7057d2997082a09525318d Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Sat, 7 Mar 2015 14:16:14 -0600 Subject: [PATCH 186/257] Check for console="comconsole* rather than just *comconsole* in loader.conf, so it doesn't match just having comconsole_speed in loader.conf. Ticket #4464 --- usr/local/www/diag_backup.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/diag_backup.php b/usr/local/www/diag_backup.php index ba4ee27935..a83bdabcc7 100644 --- a/usr/local/www/diag_backup.php +++ b/usr/local/www/diag_backup.php @@ -414,7 +414,7 @@ if ($_POST) { $config = parse_config(true); if (file_exists("/boot/loader.conf")) { $loaderconf = file_get_contents("/boot/loader.conf"); - if (strpos($loaderconf, "comconsole")) { + if (strpos($loaderconf, "console=\"comconsole")) { $config['system']['enableserial'] = true; write_config("Restore serial console enabling in configuration."); } From 51b24a30a86843c4b7aecff6f87d4835b02255a4 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Sun, 8 Mar 2015 00:43:23 -0600 Subject: [PATCH 187/257] Update help to current config structure, touch up text while here. Fixes #4492 --- usr/local/sbin/pfSsh.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/usr/local/sbin/pfSsh.php b/usr/local/sbin/pfSsh.php index 6700c1ce4a..e165fcd28f 100755 --- a/usr/local/sbin/pfSsh.php +++ b/usr/local/sbin/pfSsh.php @@ -124,12 +124,12 @@ $show_help_text = << Date: Sun, 8 Mar 2015 18:04:48 -0500 Subject: [PATCH 188/257] Missing $ --- usr/local/www/services_unbound.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/services_unbound.php b/usr/local/www/services_unbound.php index 33dbe46edc..04b6fb6948 100644 --- a/usr/local/www/services_unbound.php +++ b/usr/local/www/services_unbound.php @@ -281,7 +281,7 @@ function show_advanced_dns() { $ldescr): $selected = ""; if (in_array($laddr, $pconfig['outgoing_interface'])) $selected = 'selected="selected"'; From 10192c304155238bb0533440b6e4c708d01eeb46 Mon Sep 17 00:00:00 2001 From: k-paulius Date: Sun, 8 Mar 2015 18:15:03 -0500 Subject: [PATCH 190/257] Remove extra closing brackets --- usr/local/www/xmlrpc.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/xmlrpc.php b/usr/local/www/xmlrpc.php index 49fad44ad2..ec6d458d36 100755 --- a/usr/local/www/xmlrpc.php +++ b/usr/local/www/xmlrpc.php @@ -213,9 +213,9 @@ function restore_config_section_xmlrpc($raw_params) { foreach ($config['virtualip']['vip'] as $vipindex => $vip) { if ($vip['mode'] == "carp") $oldvips["{$vip['interface']}_vip{$vip['vhid']}"] = "{$vip['password']}{$vip['advskew']}{$vip['subnet']}{$vip['subnet_bits']}{$vip['advbase']}"; - else if ($vip['mode'] == "ipalias" && (substr($vip['interface'], 0, 4) == '_vip') || strpos($vip['interface'], "lo0"))) + else if ($vip['mode'] == "ipalias" && (substr($vip['interface'], 0, 4) == '_vip') || strpos($vip['interface'], "lo0")) $oldvips[$vip['subnet']] = "{$vip['interface']}{$vip['subnet']}{$vip['subnet_bits']}"; - else if (($vip['mode'] == "ipalias" || $vip['mode'] == 'proxyarp') && !(substr($vip['interface'], 0, 4) == '_vip') || strpos($vip['interface'], "lo0"))) + else if (($vip['mode'] == "ipalias" || $vip['mode'] == 'proxyarp') && !(substr($vip['interface'], 0, 4) == '_vip') || strpos($vip['interface'], "lo0")) $vipbackup[] = $vip; } } From ef1dfb8873e65c90f935b10786afdb349ace1d18 Mon Sep 17 00:00:00 2001 From: k-paulius Date: Sun, 8 Mar 2015 18:17:26 -0500 Subject: [PATCH 191/257] Add missing opening bracket --- usr/local/www/carp_status.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/carp_status.php b/usr/local/www/carp_status.php index 1faebf0818..9524aef838 100644 --- a/usr/local/www/carp_status.php +++ b/usr/local/www/carp_status.php @@ -212,7 +212,7 @@ include("head.inc"); $icon = "\"backup\""; } else if($status == "INIT") { $icon = "\"init\""; - } else + } else { $icon = ""; } } From fc4e8df89e80d438088755b043aa344de20782e7 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Mon, 9 Mar 2015 17:20:36 +0545 Subject: [PATCH 192/257] Code style etc inc vwx3 rebased version with conflicts resolved due to a bunch of recent changes in vpn.inc --- etc/inc/voucher.inc | 426 +++++++++++++------------ etc/inc/vpn.inc | 648 +++++++++++++++++++++++--------------- etc/inc/vslb.inc | 163 +++++----- etc/inc/wizardapp.inc | 26 +- etc/inc/xmlparse.inc | 142 +++++---- etc/inc/xmlparse_attr.inc | 40 ++- etc/inc/xmlreader.inc | 265 ++++++++-------- etc/inc/xmlrpc.inc | 100 +++--- 8 files changed, 1011 insertions(+), 799 deletions(-) diff --git a/etc/inc/voucher.inc b/etc/inc/voucher.inc index f6b7248a20..25c12eeb0d 100644 --- a/etc/inc/voucher.inc +++ b/etc/inc/voucher.inc @@ -3,29 +3,29 @@ voucher.inc Copyright (C) 2010-2012 Ermal Luci Copyright (C) 2010 Scott Ullrich - Copyright (C) 2007 Marcel Wiget - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + Copyright (C) 2007 Marcel Wiget + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. */ @@ -35,8 +35,9 @@ */ /* include all configuration functions */ -if(!function_exists('captiveportal_syslog')) +if (!function_exists('captiveportal_syslog')) { require_once("captiveportal.inc"); +} function xmlrpc_sync_voucher_expire($vouchers, $syncip, $port, $password, $username) { global $g, $config, $cpzone; @@ -44,12 +45,14 @@ function xmlrpc_sync_voucher_expire($vouchers, $syncip, $port, $password, $usern $protocol = "http"; if (is_array($config['system']) && is_array($config['system']['webgui']) && !empty($config['system']['webgui']['protocol']) && - $config['system']['webgui']['protocol'] == "https") + $config['system']['webgui']['protocol'] == "https") { $protocol = "https"; - if ($protocol == "https" || $port == "443") + } + if ($protocol == "https" || $port == "443") { $url = "https://{$syncip}"; - else + } else { $url = "http://{$syncip}"; + } /* Construct code that is run on remote machine */ $method = 'pfsense.exec_php'; @@ -73,12 +76,12 @@ EOF; $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials($username, $password); $resp = $cli->send($msg, "250"); - if(!is_object($resp)) { + if (!is_object($resp)) { $error = "A communications error occurred while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Communications error occurred", ""); return false; - } elseif($resp->faultCode()) { + } elseif ($resp->faultCode()) { $error = "An error code was received while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Error code received", ""); @@ -98,12 +101,14 @@ function xmlrpc_sync_voucher_disconnect($dbent, $syncip, $port, $password, $user $protocol = "http"; if (is_array($config['system']) && is_array($config['system']['webgui']) && !empty($config['system']['webgui']['protocol']) && - $config['system']['webgui']['protocol'] == "https") + $config['system']['webgui']['protocol'] == "https") { $protocol = "https"; - if ($protocol == "https" || $port == "443") + } + if ($protocol == "https" || $port == "443") { $url = "https://{$syncip}"; - else + } else { $url = "http://{$syncip}"; + } /* Construct code that is run on remote machine */ $dbent_str = serialize($dbent); @@ -131,12 +136,12 @@ EOF; $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials($username, $password); $resp = $cli->send($msg, "250"); - if(!is_object($resp)) { + if (!is_object($resp)) { $error = "A communications error occurred while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Communications error occurred", ""); return false; - } elseif($resp->faultCode()) { + } elseif ($resp->faultCode()) { $error = "An error code was received while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Error code received", ""); @@ -156,12 +161,14 @@ function xmlrpc_sync_used_voucher($voucher_received, $syncip, $port, $password, $protocol = "http"; if (is_array($config['system']) && is_array($config['system']['webgui']) && !empty($config['system']['webgui']['protocol']) && - $config['system']['webgui']['protocol'] == "https") + $config['system']['webgui']['protocol'] == "https") { $protocol = "https"; - if ($protocol == "https" || $port == "443") + } + if ($protocol == "https" || $port == "443") { $url = "https://{$syncip}"; - else + } else { $url = "http://{$syncip}"; + } /* Construct code that is run on remote machine */ $method = 'pfsense.exec_php'; @@ -188,12 +195,12 @@ EOF; $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials($username, $password); $resp = $cli->send($msg, "250"); - if(!is_object($resp)) { + if (!is_object($resp)) { $error = "A communications error occurred while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Communications error occurred", ""); return null; // $timeleft - } elseif($resp->faultCode()) { + } elseif ($resp->faultCode()) { $error = "An error code was received while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Error code received", ""); @@ -202,16 +209,18 @@ EOF; log_error("CaptivePortalVoucherSync XMLRPC reload data success with {$url}:{$port} (pfsense.exec_php)."); } $toreturn = XML_RPC_Decode($resp->value()); - if (!is_array($config['voucher'])) + if (!is_array($config['voucher'])) { $config['voucher'] = array(); + } if (is_array($toreturn['voucher']) && is_array($toreturn['voucher']['roll'])) { $config['voucher'][$cpzone]['roll'] = $toreturn['voucher']['roll']; write_config("Captive Portal Voucher database synchronized with {$url}"); voucher_configure_zone(true); unset($toreturn['voucher']); - } else if (!isset($toreturn['timeleft'])) + } else if (!isset($toreturn['timeleft'])) { return null; + } return $toreturn['timeleft']; } @@ -220,7 +229,7 @@ function voucher_expire($voucher_received) { global $g, $config, $cpzone; // XMLRPC Call over to the master Voucher node - if(!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { + if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { $syncip = $config['voucher'][$cpzone]['vouchersyncdbip']; $syncport = $config['voucher'][$cpzone]['vouchersyncport']; $syncpass = $config['voucher'][$cpzone]['vouchersyncpass']; @@ -241,7 +250,7 @@ function voucher_expire($voucher_received) { } // split into an array. Useful for multiple vouchers given - $a_vouchers_received = preg_split("/[\t\n\r ]+/s", $voucher_received); + $a_vouchers_received = preg_split("/[\t\n\r ]+/s", $voucher_received); $active_dirty = false; $unsetindexes = array(); @@ -249,31 +258,35 @@ function voucher_expire($voucher_received) { // Roll# and Ticket# using the external readvoucher binary foreach ($a_vouchers_received as $voucher) { $v = escapeshellarg($voucher); - if (strlen($voucher) < 3) + if (strlen($voucher) < 3) { continue; // seems too short to be a voucher! + } unset($output); $_gb = exec("/usr/local/bin/voucher -c {$g['varetc_path']}/voucher_{$cpzone}.cfg -k {$g['varetc_path']}/voucher_{$cpzone}.public -- $v", $output); list($status, $roll, $nr) = explode(" ", $output[0]); if ($status == "OK") { - // check if we have this ticket on a registered roll for this ticket + // check if we have this ticket on a registered roll for this ticket if ($tickets_per_roll[$roll] && ($nr <= $tickets_per_roll[$roll])) { - // voucher is from a registered roll. - if (!isset($active_vouchers[$roll])) + // voucher is from a registered roll. + if (!isset($active_vouchers[$roll])) { $active_vouchers[$roll] = voucher_read_active_db($roll); + } // valid voucher. Store roll# and ticket# if (!empty($active_vouchers[$roll][$voucher])) { $active_dirty = true; unset($active_vouchers[$roll][$voucher]); } // check if voucher already marked as used - if (!isset($bitstring[$roll])) + if (!isset($bitstring[$roll])) { $bitstring[$roll] = voucher_read_used_db($roll); + } $pos = $nr >> 3; // divide by 8 -> octet $mask = 1 << ($nr % 8); // mark bit for this voucher as used - if (!(ord($bitstring[$roll][$pos]) & $mask)) + if (!(ord($bitstring[$roll][$pos]) & $mask)) { $bitstring[$roll][$pos] = chr(ord($bitstring[$roll][$pos]) | $mask); + } captiveportal_syslog("{$voucher} ({$roll}/{$nr}) forced to expire"); /* Check if this voucher has any active sessions */ @@ -283,17 +296,20 @@ function voucher_expire($voucher_received) { captiveportal_logportalauth($cpentry[4],$cpentry[3],$cpentry[2],"FORCLY TERMINATING VOUCHER {$voucher} SESSION"); $unsetindexes[] = $cpentry[5]; } - } else + } else { captiveportal_syslog("$voucher ($roll/$nr): not found on any registered Roll"); - } else + } + } else { // hmm, thats weird ... not what I expected captiveportal_syslog("$voucher invalid: {$output[0]}!!"); + } } // Refresh active DBs if ($active_dirty == true) { - foreach ($active_vouchers as $roll => $active) + foreach ($active_vouchers as $roll => $active) { voucher_write_active_db($roll, $active); + } unset($active_vouchers); /* Trigger a sync of the vouchers on config */ @@ -303,9 +319,10 @@ function voucher_expire($voucher_received) { // Write back the used DB's if (is_array($bitstring)) { foreach ($bitstring as $roll => $used) { - if(is_array($used)) { - foreach($used as $u) + if (is_array($used)) { + foreach ($used as $u) { voucher_write_used_db($roll, base64_encode($u)); + } } else { voucher_write_used_db($roll, base64_encode($used)); } @@ -316,13 +333,14 @@ function voucher_expire($voucher_received) { unlock($voucherlck); /* Write database */ - if (!empty($unsetindexes)) + if (!empty($unsetindexes)) { captiveportal_remove_entries($unsetindexes); + } return true; } -/* +/* * Authenticate a voucher and return the remaining time credit in minutes * if $test is set, don't mark the voucher as used nor add it to the list * of active vouchers @@ -332,11 +350,12 @@ function voucher_expire($voucher_received) { function voucher_auth($voucher_received, $test = 0) { global $g, $config, $cpzone, $dbc; - if (!isset($config['voucher'][$cpzone]['enable'])) + if (!isset($config['voucher'][$cpzone]['enable'])) { return 0; + } // XMLRPC Call over to the master Voucher node - if(!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { + if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { $syncip = $config['voucher'][$cpzone]['vouchersyncdbip']; $syncport = $config['voucher'][$cpzone]['vouchersyncport']; $syncpass = $config['voucher'][$cpzone]['vouchersyncpass']; @@ -357,7 +376,7 @@ function voucher_auth($voucher_received, $test = 0) { } // split into an array. Useful for multiple vouchers given - $a_vouchers_received = preg_split("/[\t\n\r ]+/s", $voucher_received); + $a_vouchers_received = preg_split("/[\t\n\r ]+/s", $voucher_received); $error = 0; $test_result = array(); // used to display for voucher test option in GUI $total_minutes = 0; @@ -368,8 +387,9 @@ function voucher_auth($voucher_received, $test = 0) { // Roll# and Ticket# using the external readvoucher binary foreach ($a_vouchers_received as $voucher) { $v = escapeshellarg($voucher); - if (strlen($voucher) < 3) + if (strlen($voucher) < 3) { continue; // seems too short to be a voucher! + } $result = exec("/usr/local/bin/voucher -c {$g['varetc_path']}/voucher_{$cpzone}.cfg -k {$g['varetc_path']}/voucher_{$cpzone}.public -- $v"); list($status, $roll, $nr) = explode(" ", $result); @@ -379,11 +399,12 @@ function voucher_auth($voucher_received, $test = 0) { $first_voucher = $voucher; $first_voucher_roll = $roll; } - // check if we have this ticket on a registered roll for this ticket + // check if we have this ticket on a registered roll for this ticket if ($tickets_per_roll[$roll] && ($nr <= $tickets_per_roll[$roll])) { - // voucher is from a registered roll. - if (!isset($active_vouchers[$roll])) + // voucher is from a registered roll. + if (!isset($active_vouchers[$roll])) { $active_vouchers[$roll] = voucher_read_active_db($roll); + } // valid voucher. Store roll# and ticket# if (!empty($active_vouchers[$roll][$voucher])) { list($timestamp,$minutes) = explode(",", $active_vouchers[$roll][$voucher]); @@ -395,8 +416,9 @@ function voucher_auth($voucher_received, $test = 0) { // voucher not used. Check if ticket Id is on the roll (not too high) // and if the ticket is marked used. // check if voucher already marked as used - if (!isset($bitstring[$roll])) + if (!isset($bitstring[$roll])) { $bitstring[$roll] = voucher_read_used_db($roll); + } $pos = $nr >> 3; // divide by 8 -> octet $mask = 1 << ($nr % 8); if (ord($bitstring[$roll][$pos]) & $mask) { @@ -440,26 +462,29 @@ function voucher_auth($voucher_received, $test = 0) { // the user wouldn't know that he used at least one invalid voucher. if ($error) { unlock($voucherlck); - if ($total_minutes > 0) // probably not needed, but want to make sure + if ($total_minutes > 0) { // probably not needed, but want to make sure $total_minutes = 0; // we only report -1 (expired) or 0 (no access) + } return $total_minutes; // well, at least one voucher had errors. Say NO ACCESS } // If we did a XMLRPC sync earlier check the timeleft if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { - if (!is_null($remote_time_used)) + if (!is_null($remote_time_used)) { $total_minutes = $remote_time_used; - else if ($remote_time_used < $total_minutes) + } else if ($remote_time_used < $total_minutes) { $total_minutes -= $remote_time_used; + } } // All given vouchers were valid and this isn't simply a test. // Write back the used DB's if (is_array($bitstring)) { foreach ($bitstring as $roll => $used) { - if(is_array($used)) { - foreach($used as $u) + if (is_array($used)) { + foreach ($used as $u) { voucher_write_used_db($roll, base64_encode($u)); + } } else { voucher_write_used_db($roll, base64_encode($used)); } @@ -493,15 +518,17 @@ function voucher_configure($sync = false) { if (is_array($config['voucher'])) { foreach ($config['voucher'] as $voucherzone => $vcfg) { - if (platform_booting()) - echo gettext("Enabling voucher support... "); + if (platform_booting()) { + echo gettext("Enabling voucher support... "); + } $cpzone = $voucherzone; $error = voucher_configure_zone($sync); if (platform_booting()) { - if ($error) + if ($error) { echo "error\n"; - else + } else { echo "done\n"; + } } } } @@ -510,70 +537,72 @@ function voucher_configure($sync = false) { function voucher_configure_zone($sync = false) { global $config, $g, $cpzone; - if (!isset($config['voucher'][$cpzone]['enable'])) + if (!isset($config['voucher'][$cpzone]['enable'])) { return 0; + } - if ($sync == true) - captiveportal_syslog("Writing voucher db from sync data..."); + if ($sync == true) { + captiveportal_syslog("Writing voucher db from sync data..."); + } $voucherlck = lock("voucher{$cpzone}", LOCK_EX); - /* write public key used to verify vouchers */ - $pubkey = base64_decode($config['voucher'][$cpzone]['publickey']); - $fd = fopen("{$g['varetc_path']}/voucher_{$cpzone}.public", "w"); - if (!$fd) { - captiveportal_syslog("Voucher error: cannot write voucher.public\n"); - unlock($voucherlck); - return 1; - } - fwrite($fd, $pubkey); - fclose($fd); - @chmod("{$g['varetc_path']}/voucher_{$cpzone}.public", 0600); + /* write public key used to verify vouchers */ + $pubkey = base64_decode($config['voucher'][$cpzone]['publickey']); + $fd = fopen("{$g['varetc_path']}/voucher_{$cpzone}.public", "w"); + if (!$fd) { + captiveportal_syslog("Voucher error: cannot write voucher.public\n"); + unlock($voucherlck); + return 1; + } + fwrite($fd, $pubkey); + fclose($fd); + @chmod("{$g['varetc_path']}/voucher_{$cpzone}.public", 0600); - /* write config file used by voucher binary to decode vouchers */ - $fd = fopen("{$g['varetc_path']}/voucher_{$cpzone}.cfg", "w"); - if (!$fd) { - printf(gettext("Error: cannot write voucher.cfg") . "\n"); - unlock($voucherlck); - return 1; - } - fwrite($fd, "{$config['voucher'][$cpzone]['rollbits']},{$config['voucher'][$cpzone]['ticketbits']},{$config['voucher'][$cpzone]['checksumbits']},{$config['voucher'][$cpzone]['magic']},{$config['voucher'][$cpzone]['charset']}\n"); - fclose($fd); - @chmod("{$g['varetc_path']}/voucher_{$cpzone}.cfg", 0600); + /* write config file used by voucher binary to decode vouchers */ + $fd = fopen("{$g['varetc_path']}/voucher_{$cpzone}.cfg", "w"); + if (!$fd) { + printf(gettext("Error: cannot write voucher.cfg") . "\n"); + unlock($voucherlck); + return 1; + } + fwrite($fd, "{$config['voucher'][$cpzone]['rollbits']},{$config['voucher'][$cpzone]['ticketbits']},{$config['voucher'][$cpzone]['checksumbits']},{$config['voucher'][$cpzone]['magic']},{$config['voucher'][$cpzone]['charset']}\n"); + fclose($fd); + @chmod("{$g['varetc_path']}/voucher_{$cpzone}.cfg", 0600); unlock($voucherlck); - if ((platform_booting() || $sync == true) && is_array($config['voucher'][$cpzone]['roll'])) { + if ((platform_booting() || $sync == true) && is_array($config['voucher'][$cpzone]['roll'])) { $voucherlck = lock("voucher{$cpzone}", LOCK_EX); - // create active and used DB per roll on ramdisk from config - foreach ($config['voucher'][$cpzone]['roll'] as $rollent) { + // create active and used DB per roll on ramdisk from config + foreach ($config['voucher'][$cpzone]['roll'] as $rollent) { - $roll = $rollent['number']; - voucher_write_used_db($roll, $rollent['used']); - $minutes = $rollent['minutes']; - $active_vouchers = array(); - $a_active = &$rollent['active']; - if (is_array($a_active)) { - foreach ($a_active as $activent) { - $voucher = $activent['voucher']; - $timestamp = $activent['timestamp']; - $minutes = $activent['minutes']; - // its tempting to check for expired timestamps, but during - // bootup, we most likely don't have the correct time. - $active_vouchers[$voucher] = "$timestamp,$minutes"; - } - } - voucher_write_active_db($roll, $active_vouchers); - } + $roll = $rollent['number']; + voucher_write_used_db($roll, $rollent['used']); + $minutes = $rollent['minutes']; + $active_vouchers = array(); + $a_active = &$rollent['active']; + if (is_array($a_active)) { + foreach ($a_active as $activent) { + $voucher = $activent['voucher']; + $timestamp = $activent['timestamp']; + $minutes = $activent['minutes']; + // its tempting to check for expired timestamps, but during + // bootup, we most likely don't have the correct time. + $active_vouchers[$voucher] = "$timestamp,$minutes"; + } + } + voucher_write_active_db($roll, $active_vouchers); + } unlock($voucherlck); - } + } return 0; } -/* write bitstring of used vouchers to ramdisk. +/* write bitstring of used vouchers to ramdisk. * Bitstring must already be base64_encoded! */ function voucher_write_used_db($roll, $vdb) { @@ -583,12 +612,13 @@ function voucher_write_used_db($roll, $vdb) { if ($fd) { fwrite($fd, $vdb . "\n"); fclose($fd); - } else + } else { voucher_log(LOG_ERR, sprintf(gettext('cant write %1$s/voucher_%s_used_%2$s.db'), $g['vardb_path'], $cpzone, $roll)); + } } /* return assoc array of active vouchers with activation timestamp - * voucher is index. + * voucher is index. */ function voucher_read_active_db($roll) { global $g, $cpzone; @@ -603,10 +633,11 @@ function voucher_read_active_db($roll) { $line = trim(fgets($fd)); if ($line) { list($voucher,$timestamp,$minutes) = explode(",", $line); // voucher,timestamp - if ((($timestamp + (60*$minutes)) - time()) > 0) + if ((($timestamp + (60*$minutes)) - time()) > 0) { $active[$voucher] = "$timestamp,$minutes"; - else + } else { $dirty=1; + } } } fclose($fd); @@ -623,74 +654,77 @@ function voucher_read_active_db($roll) { /* store array of active vouchers back to DB */ function voucher_write_active_db($roll, $active) { - global $g, $cpzone; + global $g, $cpzone; - if (!is_array($active)) + if (!is_array($active)) { return; - $fd = fopen("{$g['vardb_path']}/voucher_{$cpzone}_active_$roll.db", "w"); - if ($fd) { - foreach($active as $voucher => $value) - fwrite($fd, "$voucher,$value\n"); - fclose($fd); - } + } + $fd = fopen("{$g['vardb_path']}/voucher_{$cpzone}_active_$roll.db", "w"); + if ($fd) { + foreach ($active as $voucher => $value) { + fwrite($fd, "$voucher,$value\n"); + } + fclose($fd); + } } /* return how many vouchers are marked used on a roll */ function voucher_used_count($roll) { - global $g, $cpzone; + global $g, $cpzone; - $bitstring = voucher_read_used_db($roll); - $max = strlen($bitstring) * 8; - $used = 0; - for ($i = 1; $i <= $max; $i++) { - // check if ticket already used or not. - $pos = $i >> 3; // divide by 8 -> octet - $mask = 1 << ($i % 8); // mask to test bit in octet - if (ord($bitstring[$pos]) & $mask) - $used++; - } - unset($bitstring); + $bitstring = voucher_read_used_db($roll); + $max = strlen($bitstring) * 8; + $used = 0; + for ($i = 1; $i <= $max; $i++) { + // check if ticket already used or not. + $pos = $i >> 3; // divide by 8 -> octet + $mask = 1 << ($i % 8); // mask to test bit in octet + if (ord($bitstring[$pos]) & $mask) { + $used++; + } + } + unset($bitstring); - return $used; + return $used; } function voucher_read_used_db($roll) { - global $g, $cpzone; + global $g, $cpzone; - $vdb = ""; - $file = "{$g['vardb_path']}/voucher_{$cpzone}_used_$roll.db"; - if (file_exists($file)) { - $fd = fopen($file, "r"); - if ($fd) { - $vdb = trim(fgets($fd)); - fclose($fd); - } else { - voucher_log(LOG_ERR, sprintf(gettext('cant read %1$s/voucher_%s_used_%2$s.db'), $g['vardb_path'], $cpzone, $roll)); - } - } - return base64_decode($vdb); + $vdb = ""; + $file = "{$g['vardb_path']}/voucher_{$cpzone}_used_$roll.db"; + if (file_exists($file)) { + $fd = fopen($file, "r"); + if ($fd) { + $vdb = trim(fgets($fd)); + fclose($fd); + } else { + voucher_log(LOG_ERR, sprintf(gettext('cant read %1$s/voucher_%s_used_%2$s.db'), $g['vardb_path'], $cpzone, $roll)); + } + } + return base64_decode($vdb); } function voucher_unlink_db($roll) { - global $g, $cpzone; - @unlink("{$g['vardb_path']}/voucher_{$cpzone}_used_$roll.db"); - @unlink("{$g['vardb_path']}/voucher_{$cpzone}_active_$roll.db"); + global $g, $cpzone; + @unlink("{$g['vardb_path']}/voucher_{$cpzone}_used_$roll.db"); + @unlink("{$g['vardb_path']}/voucher_{$cpzone}_active_$roll.db"); } /* we share the log with captiveportal for now */ function voucher_log($priority, $message) { - $message = trim($message); - openlog("logportalauth", LOG_PID, LOG_LOCAL4); - syslog($priority, sprintf(gettext("Voucher: %s"),$message)); - closelog(); + $message = trim($message); + openlog("logportalauth", LOG_PID, LOG_LOCAL4); + syslog($priority, sprintf(gettext("Voucher: %s"),$message)); + closelog(); } /* Save active and used voucher DB into XML config and write it to flash * Called during reboot -> system_reboot_cleanup() and every active voucher change */ function voucher_save_db_to_config() { - global $config, $g, $cpzone; + global $config, $g, $cpzone; if (is_array($config['voucher'])) { foreach ($config['voucher'] as $voucherzone => $vcfg) { @@ -701,42 +735,44 @@ function voucher_save_db_to_config() { } function voucher_save_db_to_config_zone() { - global $config, $g, $cpzone; - - if (!isset($config['voucher'][$cpzone]['enable'])) - return; // no vouchers or don't want to save DB's + global $config, $g, $cpzone; - if (!is_array($config['voucher'][$cpzone]['roll'])) - return; + if (!isset($config['voucher'][$cpzone]['enable'])) { + return; // no vouchers or don't want to save DB's + } - $voucherlck = lock("voucher{$cpzone}", LOCK_EX); + if (!is_array($config['voucher'][$cpzone]['roll'])) { + return; + } - // walk all active rolls and save runtime DB's to flash - $a_roll = &$config['voucher'][$cpzone]['roll']; - while (list($key, $value) = each($a_roll)) { - $rollent = &$a_roll[$key]; - $roll = $rollent['number']; - $bitmask = voucher_read_used_db($roll); - $rollent['used'] = base64_encode($bitmask); - $active_vouchers = voucher_read_active_db($roll); - $db = array(); + $voucherlck = lock("voucher{$cpzone}", LOCK_EX); + + // walk all active rolls and save runtime DB's to flash + $a_roll = &$config['voucher'][$cpzone]['roll']; + while (list($key, $value) = each($a_roll)) { + $rollent = &$a_roll[$key]; + $roll = $rollent['number']; + $bitmask = voucher_read_used_db($roll); + $rollent['used'] = base64_encode($bitmask); + $active_vouchers = voucher_read_active_db($roll); + $db = array(); $dbi = 1; - foreach($active_vouchers as $voucher => $line) { - list($timestamp,$minutes) = explode(",", $line); - $activent['voucher'] = $voucher; - $activent['timestamp'] = $timestamp; - $activent['minutes'] = $minutes; - $db["v{$dbi}"] = $activent; - $dbi++; - } - $rollent['active'] = $db; - unset($active_vouchers); - } + foreach ($active_vouchers as $voucher => $line) { + list($timestamp,$minutes) = explode(",", $line); + $activent['voucher'] = $voucher; + $activent['timestamp'] = $timestamp; + $activent['minutes'] = $minutes; + $db["v{$dbi}"] = $activent; + $dbi++; + } + $rollent['active'] = $db; + unset($active_vouchers); + } - unlock($voucherlck); + unlock($voucherlck); - write_config("Syncing vouchers"); - return; + write_config("Syncing vouchers"); + return; } ?> diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index c271224101..a148d0e116 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -48,15 +48,17 @@ function vpn_ipsec_configure_loglevels($forconfig = false) $cfgtext = array(); foreach ($ipsec_loglevels as $lkey => $ldescr) { - if (!isset($config['ipsec']["ipsec_{$lkey}"]) && !$forconfig) + if (!isset($config['ipsec']["ipsec_{$lkey}"]) && !$forconfig) { mwexec("/usr/local/sbin/ipsec stroke loglevel {$lkey} -- -1", false); - else if (is_numeric($config['ipsec']["ipsec_{$lkey}"]) && - intval($config['ipsec']["ipsec_{$lkey}"]) >= 0 && intval($config['ipsec']["ipsec_{$lkey}"]) <= 5) + } else if (is_numeric($config['ipsec']["ipsec_{$lkey}"]) && + intval($config['ipsec']["ipsec_{$lkey}"]) >= 0 && intval($config['ipsec']["ipsec_{$lkey}"]) <= 5) { $forconfig ? $cfgtext[] = "${lkey} " . (intval($config['ipsec']["ipsec_{$lkey}"]) - 1) : mwexec("/usr/local/sbin/ipsec stroke loglevel {$lkey} " . (intval($config['ipsec']["ipsec_{$lkey}"]) - 1) , false); + } } - if ($forconfig) + if ($forconfig) { return implode(',', $cfgtext); + } } /* include all configuration functions */ @@ -65,30 +67,30 @@ function vpn_ipsec_convert_to_modp($index) $convertion = ""; switch ($index) { - case '1': - $convertion = "modp768"; - break; - case '2': - $convertion = "modp1024"; - break; - case '5': - $convertion = "modp1536"; - break; - case '14': - $convertion = "modp2048"; - break; - case '15': - $convertion = "modp3072"; - break; - case '16': - $convertion = "modp4096"; - break; - case '17': - $convertion = "modp6144"; - break; - case '18': - $convertion = "modp8192"; - break; + case '1': + $convertion = "modp768"; + break; + case '2': + $convertion = "modp1024"; + break; + case '5': + $convertion = "modp1536"; + break; + case '14': + $convertion = "modp2048"; + break; + case '15': + $convertion = "modp3072"; + break; + case '16': + $convertion = "modp4096"; + break; + case '17': + $convertion = "modp6144"; + break; + case '18': + $convertion = "modp8192"; + break; } return $convertion; @@ -98,8 +100,9 @@ function vpn_ipsec_configure($restart = false) { global $config, $g, $sa, $sn, $p1_ealgos, $p2_ealgos; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; + } /* get the automatic ping_hosts.sh ready */ unlink_if_exists("{$g['vardb_path']}/ipsecpinghosts"); @@ -136,30 +139,41 @@ function vpn_ipsec_configure($restart = false) mwexec("/sbin/ifconfig enc0 up"); set_single_sysctl("net.inet.ip.ipsec_in_use", "1"); /* needed for config files */ - if (!is_dir("{$g['varetc_path']}/ipsec")) + if (!is_dir("{$g['varetc_path']}/ipsec")) { mkdir("{$g['varetc_path']}/ipsec"); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d"); - if (!is_dir($capath)) + } + if (!is_dir($capath)) { mkdir($capath); - if (!is_dir($keypath)) + } + if (!is_dir($keypath)) { mkdir($keypath); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/crls")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/crls")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d/crls"); - if (!is_dir($certpath)) + } + if (!is_dir($certpath)) { mkdir($certpath); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/aacerts")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/aacerts")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d/aacerts"); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/acerts")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/acerts")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d/acerts"); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/ocspcerts")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/ocspcerts")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d/ocspcerts"); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/reqs")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/reqs")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d/reqs"); - + } - if (platform_booting()) + + if (platform_booting()) { echo gettext("Configuring IPsec VPN... "); + } /* fastforwarding is not compatible with ipsec tunnels */ set_single_sysctl("net.inet.ip.fastforwarding", "0"); @@ -177,51 +191,59 @@ function vpn_ipsec_configure($restart = false) $ipsecpinghosts = ""; /* step through each phase1 entry */ foreach ($a_phase1 as $ph1ent) { - if (isset($ph1ent['disabled'])) + if (isset($ph1ent['disabled'])) { continue; + } if (strpos($ph1ent['interface'], '_vip')) { $vpninterface = explode('_vip', $ph1ent['interface']); $ifacesuse[] = get_real_interface($vpninterface[0]); - } else { - $vpninterface = get_failover_interface($ph1ent['interface']); + } else { + $vpninterface = get_failover_interface($ph1ent['interface']); if (strpos($vpninterface, '_vip')) { $vpninterface = explode('_vip', $vpninterface); $ifacesuse[] = get_real_interface($vpninterface[0]); - } elseif (!empty($vpninterface)) + } elseif (!empty($vpninterface)) { $ifacesuse[] = $vpninterface; + } } - - if ($ph1ent['mode'] == "aggressive" && ($ph1ent['authentication_method'] == "pre_shared_key" || $ph1ent['authentication_method'] == "xauth_psk_server")) + + if ($ph1ent['mode'] == "aggressive" && ($ph1ent['authentication_method'] == "pre_shared_key" || $ph1ent['authentication_method'] == "xauth_psk_server")) { $aggressive_mode_psk = true; + } $ikeid = $ph1ent['ikeid']; $listeniflist = get_real_interface($a_phase1['interface']); $ep = ipsec_get_phase1_src($ph1ent); - if (!is_ipaddr($ep)) + if (!is_ipaddr($ep)) { continue; + } - if(!in_array($ep,$ipmap)) + if (!in_array($ep,$ipmap)) { $ipmap[] = $ep; + } /* see if this tunnel has a hostname for the remote-gateway. If so, try to resolve it now and add it to the list for filterdns */ - if (isset ($ph1ent['mobile'])) + if (isset ($ph1ent['mobile'])) { continue; + } $rg = $ph1ent['remote-gateway']; if (!is_ipaddr($rg)) { $filterdns_list[] = "{$rg}"; add_hostname_to_watch($rg); - if (!platform_booting()) + if (!platform_booting()) { $rg = resolve_retry($rg); - if (!is_ipaddr($rg)) + } + if (!is_ipaddr($rg)) { continue; + } } - if(array_search($rg, $rgmap)) { + if (array_search($rg, $rgmap)) { log_error("The remote gateway {$rg} already exists on another phase 1 entry"); continue; } @@ -230,23 +252,27 @@ function vpn_ipsec_configure($restart = false) if (is_array($a_phase2)) { /* step through each phase2 entry */ foreach ($a_phase2 as $ph2ent) { - if (isset($ph2ent['disabled'])) + if (isset($ph2ent['disabled'])) { continue; + } - if ($ikeid != $ph2ent['ikeid']) + if ($ikeid != $ph2ent['ikeid']) { continue; + } /* add an ipsec pinghosts entry */ if ($ph2ent['pinghost']) { - if (!is_array($iflist)) + if (!is_array($iflist)) { $iflist = get_configured_interface_list(); + } $srcip = null; $local_subnet = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']); - if(is_ipaddrv6($ph2ent['pinghost'])) { + if (is_ipaddrv6($ph2ent['pinghost'])) { foreach ($iflist as $ifent => $ifname) { $interface_ip = get_interface_ipv6($ifent); - if(!is_ipaddrv6($interface_ip)) + if (!is_ipaddrv6($interface_ip)) { continue; + } if (ip_in_subnet($interface_ip, $local_subnet)) { $srcip = $interface_ip; break; @@ -255,8 +281,9 @@ function vpn_ipsec_configure($restart = false) } else { foreach ($iflist as $ifent => $ifname) { $interface_ip = get_interface_ip($ifent); - if(!is_ipaddrv4($interface_ip)) + if (!is_ipaddrv4($interface_ip)) { continue; + } if ($local_subnet == "0.0.0.0/0" || ip_in_subnet($interface_ip, $local_subnet)) { $srcip = $interface_ip; break; @@ -274,13 +301,14 @@ function vpn_ipsec_configure($restart = false) } } $dstip = $ph2ent['pinghost']; - if(is_ipaddrv6($dstip)) { + if (is_ipaddrv6($dstip)) { $family = "inet6"; } else { $family = "inet"; } - if (is_ipaddr($srcip)) + if (is_ipaddr($srcip)) { $ipsecpinghosts[] = "{$srcip}|{$dstip}|3|||||{$family}|\n"; + } } } } @@ -291,35 +319,40 @@ function vpn_ipsec_configure($restart = false) unset($iflist); $accept_unencrypted = ""; - if (isset($config['ipsec']['acceptunencryptedmainmode'])) + if (isset($config['ipsec']['acceptunencryptedmainmode'])) { $accept_unencrypted = "accept_unencrypted_mainmode_messages = yes"; + } $stronconf = ''; - if (file_exists("{$g['varetc_path']}/ipsec/strongswan.conf")) + if (file_exists("{$g['varetc_path']}/ipsec/strongswan.conf")) { $stronconf = file_get_contents("{$g['varetc_path']}/ipsec/strongswan.conf"); + } $i_dont_care_about_security_and_use_aggressive_mode_psk = ""; if ($aggressive_mode_psk) { log_error("WARNING: Setting i_dont_care_about_security_and_use_aggressive_mode_psk option because a phase 1 is configured using aggressive mode with pre-shared keys. This is not a secure configuration."); - if (!empty($stronconf) && strpos($stronconf, 'i_dont_care_about_security_and_use_aggressive_mode_psk') === FALSE) + if (!empty($stronconf) && strpos($stronconf, 'i_dont_care_about_security_and_use_aggressive_mode_psk') === FALSE) { $restart = true; + } $i_dont_care_about_security_and_use_aggressive_mode_psk = "i_dont_care_about_security_and_use_aggressive_mode_psk=yes"; - } + } $unity_enabled = 'yes'; - if (isset($config['ipsec']['unityplugin'])) + if (isset($config['ipsec']['unityplugin'])) { $unity_enabled = 'no'; + } - if (!empty($ifacesuse)) + if (!empty($ifacesuse)) { $ifacesuse = 'interfaces_use = ' . implode(',', array_unique($ifacesuse)); - else + } else { $ifacesuse = ''; + } unset($stronconf); $strongswan = << 0) + if ($firstsed > 0) { $strongswan .= ","; - if ($authcfg == "system") + } + if ($authcfg == "system") { $authcfg = "Local Database"; + } $strongswan .= $authcfg; $firstsed = 1; } @@ -477,8 +527,9 @@ EOD; if (is_array($a_phase1) && count($a_phase1)) { foreach ($a_phase1 as $ph1ent) { - if (isset($ph1ent['disabled'])) + if (isset($ph1ent['disabled'])) { continue; + } if (strstr($ph1ent['authentication_method'], 'rsa') || in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls'))) { @@ -515,16 +566,18 @@ EOD; list ($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local'); list ($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap); - if (empty($peerid_data)) + if (empty($peerid_data)) { continue; + } $myid = isset($ph1ent['mobile']) ? trim($myid_data) : "%any"; $peerid = ($peerid_data != 'allusers') ? trim($peerid_data) : ''; if (!empty($ph1ent['pre-shared-key'])) { - if ($myid_type == 'fqdn' && !empty($myid_data)) + if ($myid_type == 'fqdn' && !empty($myid_data)) { $pskconf .= "@{$myid} {$peerid} : PSK 0s" . base64_encode(trim($ph1ent['pre-shared-key'])) . "\n"; - else + } else { $pskconf .= "{$myid} {$peerid} : PSK 0s" . base64_encode(trim($ph1ent['pre-shared-key'])) . "\n"; + } } } } @@ -543,10 +596,12 @@ EOD; /* add PSKs for mobile clients */ if (is_array($ipseccfg['mobilekey'])) { foreach ($ipseccfg['mobilekey'] as $key) { - if ($key['ident'] == "allusers") + if ($key['ident'] == "allusers") { $key['ident'] = '%any'; - if (empty($key['type'])) + } + if (empty($key['type'])) { $key['type'] = 'PSK'; + } $pskconf .= "%any {$key['ident']} : {$key['type']} 0s" . base64_encode($key['pre-shared-key']) . "\n"; } unset($key); @@ -558,8 +613,9 @@ EOD; $uniqueids = 'yes'; if (!empty($config['ipsec']['uniqueids'])) { - if (in_array($uniqueids, $ipsec_idhandling)) + if (in_array($uniqueids, $ipsec_idhandling)) { $uniqueids = $config['ipsec']['uniqueids']; + } } $natfilterrules = false; /* begin ipsec.conf */ @@ -572,17 +628,20 @@ EOD; $ipsecconf .= "\tcharondebug=\"" . vpn_ipsec_configure_loglevels(true) . "\"\n"; foreach ($a_phase1 as $ph1ent) { - if (isset($ph1ent['disabled'])) + if (isset($ph1ent['disabled'])) { continue; + } - if ($ph1ent['mode'] == "aggressive") + if ($ph1ent['mode'] == "aggressive") { $aggressive = "yes"; - else + } else { $aggressive = "no"; + } $ep = ipsec_get_phase1_src($ph1ent); - if (!$ep) + if (!$ep) { continue; + } $ikeid = $ph1ent['ikeid']; $keyexchange = "ikev1"; @@ -591,22 +650,25 @@ EOD; if ($ph1ent['iketype'] == "ikev2") { $keyexchange = "ikev2"; //$passive = "start"; - } else if ($ph1ent['iketype'] == "auto") + } else if ($ph1ent['iketype'] == "auto") { $keyexchange = "ike"; + } } if (isset($ph1ent['mobile'])) { $right_spec = "%any"; $passive = 'add'; } else { - if (isset($ph1ent['responderonly'])) + if (isset($ph1ent['responderonly'])) { $passive = 'add'; + } $right_spec = $ph1ent['remote-gateway']; - if (is_ipaddr($right_spec)) + if (is_ipaddr($right_spec)) { $sourcehost = $right_spec; - else + } else { $sourcehost = $rgmap['remote-gateway']; + } if ($ph1ent['protocol'] == 'inet') { if (strpos($ph1ent['interface'], '_vip')) { @@ -623,7 +685,7 @@ EOD; $vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse); } } - + if (!empty($ifacesuse) && interface_has_gateway($vpninterface)) { $gatewayip = get_interface_gateway($vpninterface); $interfaceip = get_interface_ip($vpninterface); @@ -652,7 +714,7 @@ EOD; $vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse); } } - + if (!empty($ifacesuse) && interface_has_gateway($vpninterface)) { $gatewayip = get_interface_gateway_v6($vpninterface); $interfaceip = get_interface_ipv6($vpninterface); @@ -670,124 +732,142 @@ EOD; } list ($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local'); - if ($myid_type != 'address') + if ($myid_type != 'address') { $myid_data = "{$myid_type}:{$myid_data}"; + } /* Only specify peer ID if we are not dealing with a mobile PSK-only tunnel */ $peerid_spec = ''; if (!isset($ph1ent['mobile'])) { list ($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap); - if ($peerid_type != 'address') + if ($peerid_type != 'address') { $peerid_spec = "{$peerid_type}:{$peerid_data}"; - else + } else { $peerid_spec = $peerid_data; + } } if (is_array($ph1ent['encryption-algorithm']) && !empty($ph1ent['encryption-algorithm']['name']) && !empty($ph1ent['hash-algorithm'])) { $ealgosp1 = ''; $ealg_id = $ph1ent['encryption-algorithm']['name']; $ealg_kl = $ph1ent['encryption-algorithm']['keylen']; - if ($ealg_kl) + if ($ealg_kl) { $ealgosp1 = "ike = {$ealg_id}{$ealg_kl}-{$ph1ent['hash-algorithm']}"; - else + } else { $ealgosp1 = "ike = {$ealg_id}-{$ph1ent['hash-algorithm']}"; + } $modp = vpn_ipsec_convert_to_modp($ph1ent['dhgroup']); - if (!empty($modp)) + if (!empty($modp)) { $ealgosp1 .= "-{$modp}"; + } $ealgosp1 .= "!"; } if ($ph1ent['dpd_delay'] && $ph1ent['dpd_maxfail']) { - if ($passive == "route") + if ($passive == "route") { $dpdline = "dpdaction = restart"; - else + } else { $dpdline = "dpdaction = clear"; + } $dpdline .= "\n\tdpddelay = {$ph1ent['dpd_delay']}s"; $dpdtimeout = $ph1ent['dpd_delay'] * ($ph1ent['dpd_maxfail'] + 1); $dpdline .= "\n\tdpdtimeout = {$dpdtimeout}s"; - } else + } else { $dpdline = "dpdaction = none"; + } $ikelifeline = ''; - if ($ph1ent['lifetime']) + if ($ph1ent['lifetime']) { $ikelifeline = "ikelifetime = {$ph1ent['lifetime']}s"; + } $rightsourceip = NULL; - if (isset($ph1ent['mobile']) && !empty($a_client['pool_address'])) + if (isset($ph1ent['mobile']) && !empty($a_client['pool_address'])) { $rightsourceip = "\trightsourceip = {$a_client['pool_address']}/{$a_client['pool_netbits']}\n"; + } $authentication = ""; switch ($ph1ent['authentication_method']) { - case 'eap-mschapv2': - if (isset($ph1ent['mobile'])) { - $authentication = "eap_identity=%any\n\t"; - $authentication .= "leftauth=pubkey\n\trightauth=eap-mschapv2"; - if (!empty($ph1ent['certref'])) + case 'eap-mschapv2': + if (isset($ph1ent['mobile'])) { + $authentication = "eap_identity=%any\n\t"; + $authentication .= "leftauth=pubkey\n\trightauth=eap-mschapv2"; + if (!empty($ph1ent['certref'])) { + $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; + } + } + break; + case 'eap-tls': + if (isset($ph1ent['mobile'])) { + $authentication = "eap_identity=%identity\n\t"; + $authentication .= "leftauth=pubkey\n\trightauth=eap-tls"; + if (!empty($ph1ent['certref'])) { + $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; + } + } else { + $authentication = "leftauth=eap-tls\n\trightauth=eap-tls"; + if (!empty($ph1ent['certref'])) { + $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; + } + } + break; + case 'xauth_rsa_server': + $authentication = "leftauth = pubkey\n\trightauth = pubkey"; + $authentication .= "\n\trightauth2 = xauth-generic"; + if (!empty($ph1ent['certref'])) { $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - } - break; - case 'eap-tls': - if (isset($ph1ent['mobile'])) { - $authentication = "eap_identity=%identity\n\t"; - $authentication .= "leftauth=pubkey\n\trightauth=eap-tls"; - if (!empty($ph1ent['certref'])) + } + break; + case 'xauth_psk_server': + $authentication = "leftauth = psk\n\trightauth = psk"; + $authentication .= "\n\trightauth2 = xauth-generic"; + break; + case 'pre_shared_key': + $authentication = "leftauth = psk\n\trightauth = psk"; + break; + case 'rsasig': + $authentication = "leftauth = pubkey\n\trightauth = pubkey"; + if (!empty($ph1ent['certref'])) { $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - } else { - $authentication = "leftauth=eap-tls\n\trightauth=eap-tls"; - if (!empty($ph1ent['certref'])) + } + break; + case 'hybrid_rsa_server': + $authentication = "leftauth = xauth-generic\n\trightauth = pubkey"; + $authentication .= "\n\trightauth2 = xauth"; + if (!empty($ph1ent['certref'])) { $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - } - break; - case 'xauth_rsa_server': - $authentication = "leftauth = pubkey\n\trightauth = pubkey"; - $authentication .= "\n\trightauth2 = xauth-generic"; - if (!empty($ph1ent['certref'])) - $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - break; - case 'xauth_psk_server': - $authentication = "leftauth = psk\n\trightauth = psk"; - $authentication .= "\n\trightauth2 = xauth-generic"; - break; - case 'pre_shared_key': - $authentication = "leftauth = psk\n\trightauth = psk"; - break; - case 'rsasig': - $authentication = "leftauth = pubkey\n\trightauth = pubkey"; - if (!empty($ph1ent['certref'])) - $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - break; - case 'hybrid_rsa_server': - $authentication = "leftauth = xauth-generic\n\trightauth = pubkey"; - $authentication .= "\n\trightauth2 = xauth"; - if (!empty($ph1ent['certref'])) - $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - break; + } + break; } $left_spec = $ep; - if (isset($ph1ent['reauth_enable'])) + if (isset($ph1ent['reauth_enable'])) { $reauth = "reauth = no"; - else + } else { $reauth = "reauth = yes"; - if (isset($ph1ent['rekey_enable'])) + } + if (isset($ph1ent['rekey_enable'])) { $rekey = "rekey = no"; - else + } else { $rekey = "rekey = yes"; + } - if ($ph1ent['nat_traversal'] == 'off') + if ($ph1ent['nat_traversal'] == 'off') { $forceencaps = 'forceencaps = no'; - else if ($ph1ent['nat_traversal'] == 'force') + } else if ($ph1ent['nat_traversal'] == 'force') { $forceencaps = 'forceencaps = yes'; - else + } else { $forceencaps = 'forceencaps = no'; - - if ($ph1ent['mobike'] == 'on') + } + + if ($ph1ent['mobike'] == 'on') { $mobike = 'mobike = yes'; - else + } else { $mobike = 'mobike = no'; + } $ipseclifetime = 0; $rightsubnet_spec = array(); @@ -797,14 +877,17 @@ EOD; $ealgoESPsp2arr = array(); if (is_array($a_phase2) && count($a_phase2)) { foreach ($a_phase2 as $ph2ent) { - if ($ikeid != $ph2ent['ikeid']) + if ($ikeid != $ph2ent['ikeid']) { continue; + } - if (isset($ph2ent['disabled'])) + if (isset($ph2ent['disabled'])) { continue; + } - if (isset($ph2ent['mobile']) && !isset($a_client['enable'])) + if (isset($ph2ent['mobile']) && !isset($a_client['enable'])) { continue; + } if (($ph2ent['mode'] == 'tunnel') or ($ph2ent['mode'] == 'tunnel6')) { $tunneltype = "type = tunnel"; @@ -813,8 +896,8 @@ EOD; $leftsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']); /* Do not print localid in some cases, such as a pure-psk or psk/xauth single phase2 mobile tunnel */ - if (($localid_type == "none" || $localid_type == "mobile") - && isset($ph1ent['mobile']) && (ipsec_get_number_of_phase2($ikeid)==1)) { + if (($localid_type == "none" || $localid_type == "mobile") && + isset($ph1ent['mobile']) && (ipsec_get_number_of_phase2($ikeid)==1)) { $left_spec = '%any'; } else { if ($localid_type != "address") { @@ -828,11 +911,13 @@ EOD; if (!empty($ph2ent['natlocalid'])) { $natleftsubnet_data = ipsec_idinfo_to_cidr($ph2ent['natlocalid'], false, $ph2ent['mode']); if ($ph2ent['natlocalid']['type'] != "address") { - if (is_subnet($natleftsubnet_data)) + if (is_subnet($natleftsubnet_data)) { $leftsubnet_data = "{$natleftsubnet_data}|{$leftsubnet_data}"; + } } else { - if (is_ipaddr($natleftsubnet_data)) + if (is_ipaddr($natleftsubnet_data)) { $leftsubnet_data = "{$natleftsubnet_data}|{$leftsubnet_data}"; + } } $natfilterrules = true; } @@ -862,8 +947,9 @@ EOD; } } - if (isset($a_client['pfs_group'])) + if (isset($a_client['pfs_group'])) { $ph2ent['pfsgroup'] = $a_client['pfs_group']; + } if ($ph2ent['protocol'] == 'esp') { if (is_array($ph2ent['encryption-algorithm-option'])) { @@ -872,8 +958,9 @@ EOD; $ealg_kl = $ealg['keylen']; if (!empty($ealg_kl) && $ealg_kl == "auto") { - if (empty($p2_ealgos) || !is_array($p2_ealgos)) + if (empty($p2_ealgos) || !is_array($p2_ealgos)) { require("ipsec.inc"); + } $key_hi = $p2_ealgos[$ealg_id]['keysel']['hi']; $key_lo = $p2_ealgos[$ealg_id]['keysel']['lo']; $key_step = $p2_ealgos[$ealg_id]['keysel']['step']; @@ -887,15 +974,17 @@ EOD; $halgo = str_replace('hmac_', '', $halgo); $tmpealgo = "{$ealg_id}{$keylen}-{$halgo}"; $modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']); - if (!empty($modp)) + if (!empty($modp)) { $tmpealgo .= "-{$modp}"; + } $ealgoESPsp2arr[] = $tmpealgo; } } else { $tmpealgo = "{$ealg_id}{$keylen}"; $modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']); - if (!empty($modp)) + if (!empty($modp)) { $tmpealgo .= "-{$modp}"; + } $ealgoESPsp2arr[] = $tmpealgo; } } @@ -906,15 +995,17 @@ EOD; $halgo = str_replace('hmac_', '', $halgo); $tmpealgo = "{$ealg_id}{$ealg_kl}-{$halgo}"; $modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']); - if (!empty($modp)) + if (!empty($modp)) { $tmpealgo .= "-{$modp}"; + } $ealgoESPsp2arr[] = $tmpealgo; } } else { $tmpealgo = "{$ealg_id}{$ealg_kl}"; $modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']); - if (!empty($modp)) + if (!empty($modp)) { $tmpealgo .= "-{$modp}"; + } $ealgoESPsp2arr[] = $tmpealgo; } } @@ -925,8 +1016,9 @@ EOD; $modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']); foreach ($ph2ent['hash-algorithm-option'] as $tmpAHalgo) { $tmpAHalgo = str_replace('hmac_', '', $tmpAHalgo); - if (!empty($modp)) + if (!empty($modp)) { $tmpAHalgo = "-{$modp}"; + } $ealgoAHsp2arr[] = $tmpAHalgo; } } @@ -935,8 +1027,9 @@ EOD; $reqids[] = $ph2ent['reqid']; if (!empty($ph2ent['lifetime'])) { - if ($ipseclifetime == 0 || intval($ipseclifetime) > intval($ph2ent['lifetime'])) + if ($ipseclifetime == 0 || intval($ipseclifetime) > intval($ph2ent['lifetime'])) { $ipseclifetime = intval($ph2ent['lifetime']); + } } } @@ -963,61 +1056,74 @@ EOD; $ipsecconnect .= "\tcompress = yes\n"; $enablecompression = true; } - if (!empty($ikelifeline)) + if (!empty($ikelifeline)) { $ipsecconnect .= "\t{$ikelifeline}\n"; - if ($ipseclifetime > 0) + } + if ($ipseclifetime > 0) { $ipsecconnect .= "\tlifetime = {$ipseclifetime}s\n"; - if (!empty($rightsourceip)) + } + if (!empty($rightsourceip)) { $ipsecconnect .= "{$rightsourceip}"; - if (!empty($ealgosp1)) + } + if (!empty($ealgosp1)) { $ipsecconnect .= "\t{$ealgosp1}\n"; - if (!empty($ealgoAHsp2arr)) + } + if (!empty($ealgoAHsp2arr)) { $ipsecconnect .= "\tah = " . join(',', $ealgoAHsp2arr) . "!\n"; - if (!empty($ealgoESPsp2arr)) + } + if (!empty($ealgoESPsp2arr)) { $ipsecconnect .= "\tesp = " . join(',', $ealgoESPsp2arr) . "!\n"; - if (!empty($authentication)) + } + if (!empty($authentication)) { $ipsecconnect .= "\t{$authentication}\n"; - if (!empty($peerid_spec)) + } + if (!empty($peerid_spec)) { $ipsecconnect .= "\trightid = {$peerid_spec}\n"; - if ($keyexchange == 'ikev1') + } + if ($keyexchange == 'ikev1') { $ipsecconnect .= "\taggressive = {$aggressive}\n"; + } if (!isset($ph1ent['mobile']) && $keyexchange == 'ikev1') { if (!empty($rightsubnet_spec)) { $ipsecfin = ''; foreach ($rightsubnet_spec as $idx => $rsubnet) { $ipsecfin .= "\nconn con{$ph1ent['ikeid']}00{$idx}\n"; - if (!empty($reqids[$idx])) + if (!empty($reqids[$idx])) { $ipsecfin .= "\treqid = " . $reqids[$idx] . "\n"; + } $ipsecfin .= $ipsecconnect; $ipsecfin .= "\trightsubnet = {$rsubnet}\n"; $ipsecfin .= "\tleftsubnet = " . $leftsubnet_spec[$idx] . "\n"; } - } else + } else { log_error("No phase2 specifications for tunnel with REQID = {$ikeid}"); + } } else { $ipsecfin = "\nconn con{$ph1ent['ikeid']}\n"; - if (!empty($reqids[$idx])) + if (!empty($reqids[$idx])) { $ipsecfin .= "\treqid = " . $reqids[0] . "\n"; + } $ipsecfin .= $ipsecconnect; if (!isset($ph1ent['mobile']) && !empty($rightsubnet_spec)) { $tempsubnets = array(); - foreach ($rightsubnet_spec as $rightsubnet) + foreach ($rightsubnet_spec as $rightsubnet) { $tempsubnets[$rightsubnet] = $rightsubnet; + } $ipsecfin .= "\trightsubnet = " . join(",", $tempsubnets) . "\n"; unset($tempsubnets, $rightsubnet); } if (!empty($leftsubnet_spec)) { $tempsubnets = array(); - foreach ($leftsubnet_spec as $leftsubnet) + foreach ($leftsubnet_spec as $leftsubnet) { $tempsubnets[$leftsubnet] = $leftsubnet; + } $ipsecfin .= "\tleftsubnet = " . join(",", $leftsubnet_spec) . "\n"; unset($tempsubnets, $leftsubnet); } } $ipsecconf .= $ipsecfin; unset($ipsecfin); - } } @@ -1025,14 +1131,15 @@ EOD; unset($ipsecconf); /* end ipsec.conf */ - if ($enablecompression === true) + if ($enablecompression === true) { set_single_sysctl('net.inet.ipcomp.ipcomp_enable', 1); - else + } else { set_single_sysctl('net.inet.ipcomp.ipcomp_enable', 0); + } - /* mange process */ + /* manage process */ if ($restart === true) { - mwexec("/usr/local/sbin/ipsec restart", false); + mwexec("/usr/local/sbin/ipsec restart", false); } else { if (isvalidpid("{$g['varrun_path']}/charon.pid")) { /* Read secrets */ @@ -1040,28 +1147,31 @@ EOD; /* Update configuration changes */ mwexec("/usr/local/sbin/ipsec update", false); } else { - mwexec("/usr/local/sbin/ipsec start", false); + mwexec("/usr/local/sbin/ipsec start", false); } } - if ($natfilterrules == true) + if ($natfilterrules == true) { filter_configure(); + } /* start filterdns, if necessary */ if (count($filterdns_list) > 0) { $interval = 60; - if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval'])) + if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval'])) { $interval = $ipseccfg['dns-interval']; + } $hostnames = ""; array_unique($filterdns_list); - foreach ($filterdns_list as $hostname) + foreach ($filterdns_list as $hostname) { $hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload ipsecdns\"'\n"; + } file_put_contents("{$g['varetc_path']}/ipsec/filterdns-ipsec.hosts", $hostnames); unset($hostnames); - if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) + if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) { sigkillbypid("{$g['varrun_path']}/filterdns-ipsec.pid", "HUP"); - else { + } else { mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-ipsec.pid -i {$interval} -c {$g['varetc_path']}/ipsec/filterdns-ipsec.hosts -d 1"); } } else { @@ -1069,8 +1179,9 @@ EOD; @unlink("{$g['varrun_path']}/filterdns-ipsec.pid"); } - if (platform_booting()) + if (platform_booting()) { echo "done\n"; + } return count($filterdns_list); } @@ -1111,8 +1222,9 @@ function vpn_ipsec_force_reload($interface = "") { function vpn_setup() { global $g; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; + } /* start pptpd */ vpn_pptpd_configure(); @@ -1130,8 +1242,9 @@ function vpn_netgraph_support() { $realif = get_real_interface($iface); /* Get support for netgraph(4) from the nic */ $ifinfo = pfSense_get_interface_addresses($realif); - if (!empty($ifinfo) && in_array($ifinfo['iftype'], array("ether", "vlan", "bridge"))) + if (!empty($ifinfo) && in_array($ifinfo['iftype'], array("ether", "vlan", "bridge"))) { pfSense_ngctl_attach(".", $realif); + } } } @@ -1142,11 +1255,13 @@ function vpn_pptpd_configure() { $pptpdcfg = $config['pptpd']; if (platform_booting()) { - if (!$pptpdcfg['mode'] || ($pptpdcfg['mode'] == "off")) + if (!$pptpdcfg['mode'] || ($pptpdcfg['mode'] == "off")) { return 0; + } - if (platform_booting(true)) + if (platform_booting(true)) { echo gettext("Configuring PPTP VPN service... "); + } } else { /* kill mpd */ killbypid("{$g['varrun_path']}/pptp-vpn.pid"); @@ -1171,11 +1286,12 @@ function vpn_pptpd_configure() { } /* make sure pptp-vpn directory exists */ - if (!file_exists("{$g['varetc_path']}/pptp-vpn")) + if (!file_exists("{$g['varetc_path']}/pptp-vpn")) { mkdir("{$g['varetc_path']}/pptp-vpn"); + } switch ($pptpdcfg['mode']) { - case 'server' : + case 'server': /* write mpd.conf */ $fd = fopen("{$g['varetc_path']}/pptp-vpn/mpd.conf", "w"); if (!$fd) { @@ -1238,23 +1354,27 @@ EOD; EOD; } - if (isset($pptpdcfg["wins"]) && $pptpdcfg['wins'] != "") + if (isset($pptpdcfg["wins"]) && $pptpdcfg['wins'] != "") { $mpdconf .= " set ipcp nbns {$pptpdcfg['wins']}\n"; + } if (!empty($pptpdcfg['dns1'])) { $mpdconf .= " set ipcp dns " . $pptpdcfg['dns1']; - if (!empty($pptpdcfg['dns2'])) + if (!empty($pptpdcfg['dns2'])) { $mpdconf .= " " . $pptpdcfg['dns2']; + } $mpdconf .= "\n"; } elseif (isset ($config['dnsmasq']['enable'])) { $mpdconf .= " set ipcp dns " . get_interface_ip("lan"); - if ($syscfg['dnsserver'][0]) + if ($syscfg['dnsserver'][0]) { $mpdconf .= " " . $syscfg['dnsserver'][0]; + } $mpdconf .= "\n"; } elseif (isset($config['unbound']['enable'])) { $mpdconf .= " set ipcp dns " . get_interface_ip("lan"); - if ($syscfg['dnsserver'][0]) + if ($syscfg['dnsserver'][0]) { $mpdconf .= " " . $syscfg['dnsserver'][0]; + } $mpdconf .= "\n"; } elseif (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) { $mpdconf .= " set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n"; @@ -1267,15 +1387,15 @@ EOD; set radius server {$pptpdcfg['radius']['server']['ip']} "{$pptpdcfg['radius']['server']['secret']}" {$authport} {$acctport} EOD; - if (isset ($pptpdcfg['radius']['server2']['enable'])) { - $authport = (isset($pptpdcfg['radius']['server2']['port']) && strlen($pptpdcfg['radius']['server2']['port']) > 1) ? $pptpdcfg['radius']['server2']['port'] : 1812; - $acctport = $authport + 1; - $mpdconf .=<< 1) ? $pptpdcfg['radius']['server2']['port'] : 1812; + $acctport = $authport + 1; + $mpdconf .=<< \ No newline at end of file +?> diff --git a/etc/inc/vslb.inc b/etc/inc/vslb.inc index d0c5244f74..74b978f506 100644 --- a/etc/inc/vslb.inc +++ b/etc/inc/vslb.inc @@ -121,33 +121,34 @@ class SendMonitor extends Monitor { function echo_lbaction($action) { global $config; - + // Index actions by name $actions_a = array(); - for ($i=0; isset($config['load_balancer']['lbaction'][$i]); $i++) + for ($i=0; isset($config['load_balancer']['lbaction'][$i]); $i++) { $actions_a[$config['load_balancer']['lbaction'][$i]['name']] = $config['load_balancer']['lbaction'][$i]; + } $ret = ""; $ret .= "{$actions_a[$action]['direction']} {$actions_a[$action]['type']} {$actions_a[$action]['action']}"; - switch($actions_a[$action]['action']) { - case 'append': - $ret .= " \"{$actions_a[$action]['options']['value']}\" to \"{$actions_a[$action]['options']['akey']}\""; - break; - case 'change': - $ret .= " \"{$actions_a[$action]['options']['akey']}\" to \"{$actions_a[$action]['options']['value']}\""; - break; - case 'expect': - $ret .= " \"{$actions_a[$action]['options']['value']}\" from \"{$actions_a[$action]['options']['akey']}\""; - break; - case 'filter': - $ret .= " \"{$actions_a[$action]['options']['value']}\" from \"{$actions_a[$action]['options']['akey']}\""; - break; - case 'hash': - $ret .= " \"{$actions_a[$action]['options']['akey']}\""; - break; - case 'log': - $ret .= " \"{$actions_a[$action]['options']['akey']}\""; - break; + switch ($actions_a[$action]['action']) { + case 'append': + $ret .= " \"{$actions_a[$action]['options']['value']}\" to \"{$actions_a[$action]['options']['akey']}\""; + break; + case 'change': + $ret .= " \"{$actions_a[$action]['options']['akey']}\" to \"{$actions_a[$action]['options']['value']}\""; + break; + case 'expect': + $ret .= " \"{$actions_a[$action]['options']['value']}\" from \"{$actions_a[$action]['options']['akey']}\""; + break; + case 'filter': + $ret .= " \"{$actions_a[$action]['options']['value']}\" from \"{$actions_a[$action]['options']['akey']}\""; + break; + case 'hash': + $ret .= " \"{$actions_a[$action]['options']['akey']}\""; + break; + case 'log': + $ret .= " \"{$actions_a[$action]['options']['akey']}\""; + break; } return $ret; } @@ -169,29 +170,29 @@ function relayd_configure($kill_first=false) { $check_a = array(); foreach ((array)$config['load_balancer']['monitor_type'] as $type) { - switch($type['type']) { - case 'icmp': - $mon = new ICMPMonitor($type['options']); - break; - case 'tcp': - $mon = new TCPMonitor($type['options']); - break; - case 'http': - $mon = new HTTPMonitor($type['options']); - break; - case 'https': - $mon = new HTTPSMonitor($type['options']); - break; - case 'send': - $mon = new SendMonitor($type['options']); - break; + switch ($type['type']) { + case 'icmp': + $mon = new ICMPMonitor($type['options']); + break; + case 'tcp': + $mon = new TCPMonitor($type['options']); + break; + case 'http': + $mon = new HTTPMonitor($type['options']); + break; + case 'https': + $mon = new HTTPSMonitor($type['options']); + break; + case 'send': + $mon = new SendMonitor($type['options']); + break; } - if($mon) { + if ($mon) { $check_a[$type['name']] = $mon->p(); } } - - + + $fd = fopen("{$g['varetc_path']}/relayd.conf", "w"); $conf .= "log updates \n"; @@ -199,27 +200,27 @@ function relayd_configure($kill_first=false) { if not specified by the user: - use a 1000 ms timeout value as in pfsense 2.0.1 and above - leave interval and prefork empty, relayd will use its default values */ - + if (isset($setting['timeout']) && !empty($setting['timeout'])) { $conf .= "timeout ".$setting['timeout']." \n"; } else { $conf .= "timeout 1000 \n"; } - + if (isset($setting['interval']) && !empty($setting['interval'])) { $conf .= "interval ".$setting['interval']." \n"; } - + if (isset($setting['prefork']) && !empty($setting['prefork'])) { $conf .= "prefork ".$setting['prefork']." \n"; } - + /* reindex pools by name as we loop through the pools array */ $pools = array(); /* Virtual server pools */ - if(is_array($pool_a)) { + if (is_array($pool_a)) { for ($i = 0; isset($pool_a[$i]); $i++) { - if(is_array($pool_a[$i]['servers'])) { + if (is_array($pool_a[$i]['servers'])) { if (!empty($pool_a[$i]['retry'])) { $retrytext = " retry {$pool_a[$i]['retry']}"; } else { @@ -231,8 +232,7 @@ function relayd_configure($kill_first=false) { foreach (subnetv4_expand($server) as $ip) { $conf .= "\t{$ip}{$retrytext}\n"; } - } - else { + } else { $conf .= "\t{$server}{$retrytext}\n"; } } @@ -242,11 +242,11 @@ function relayd_configure($kill_first=false) { } } } -// if(is_array($protocol_a)) { +// if (is_array($protocol_a)) { // for ($i = 0; isset($protocol_a[$i]); $i++) { // $proto = "{$protocol_a[$i]['type']} protocol \"{$protocol_a[$i]['name']}\" {\n"; -// if(is_array($protocol_a[$i]['lbaction'])) { -// if($protocol_a[$i]['lbaction'][0] == "") { +// if (is_array($protocol_a[$i]['lbaction'])) { +// if ($protocol_a[$i]['lbaction'][0] == "") { // continue; // } // for ($a = 0; isset($protocol_a[$i]['lbaction'][$a]); $a++) { @@ -262,25 +262,22 @@ function relayd_configure($kill_first=false) { $conf .= "\t" . "tcp { nodelay, sack, socket buffer 1024, backlog 1000 }\n"; $conf .= "}\n"; - if(is_array($vs_a)) { + if (is_array($vs_a)) { for ($i = 0; isset($vs_a[$i]); $i++) { - + $append_port_to_name = false; if (is_alias($pools[$vs_a[$i]['poolname']]['port'])) { $dest_port_array = filter_expand_alias_array($pools[$vs_a[$i]['poolname']]['port']); $append_port_to_name = true; - } - else { + } else { $dest_port_array = array($pools[$vs_a[$i]['poolname']]['port']); } if (is_alias($vs_a[$i]['port'])) { $src_port_array = filter_expand_alias_array($vs_a[$i]['port']); $append_port_to_name = true; - } - else if ($vs_a[$i]['port']) { + } else if ($vs_a[$i]['port']) { $src_port_array = array($vs_a[$i]['port']); - } - else { + } else { $src_port_array = $dest_port_array; } @@ -291,18 +288,15 @@ function relayd_configure($kill_first=false) { log_error("item is $item"); if (is_subnetv4($item)) { $ip_list = array_merge($ip_list, subnetv4_expand($item)); - } - else { + } else { $ip_list[] = $item; } } $append_ip_to_name = true; - } - else if (is_subnetv4($vs_a[$i]['ipaddr'])) { + } else if (is_subnetv4($vs_a[$i]['ipaddr'])) { $ip_list = subnetv4_expand($vs_a[$i]['ipaddr']); $append_ip_to_name = true; - } - else { + } else { $ip_list = array($vs_a[$i]['ipaddr']); } @@ -330,26 +324,29 @@ function relayd_configure($kill_first=false) { $conf .= " protocol \"{$vs_a[$i]['relay_protocol']}\"\n"; } $lbmode = ""; - if ( $pools[$vs_a[$i]['poolname']]['mode'] == "loadbalance" ) { + if ($pools[$vs_a[$i]['poolname']]['mode'] == "loadbalance") { $lbmode = "mode loadbalance"; } $conf .= " forward to <{$vs_a[$i]['poolname']}> port {$dest_port} {$lbmode} {$check_a[$pools[$vs_a[$i]['poolname']]['monitor']]} \n"; - if (isset($vs_a[$i]['sitedown']) && strlen($vs_a[$i]['sitedown']) > 0 && ($vs_a[$i]['relay_protocol'] != 'dns')) + if (isset($vs_a[$i]['sitedown']) && strlen($vs_a[$i]['sitedown']) > 0 && ($vs_a[$i]['relay_protocol'] != 'dns')) { $conf .= " forward to <{$vs_a[$i]['sitedown']}> port {$dest_port} {$lbmode} {$check_a[$pools[$vs_a[$i]['poolname']]['monitor']]} \n"; + } $conf .= "}\n"; } else { $conf .= "redirect \"{$name}\" {\n"; $conf .= " listen on {$ip} port {$src_port}\n"; $conf .= " forward to <{$vs_a[$i]['poolname']}> port {$dest_port} {$check_a[$pools[$vs_a[$i]['poolname']]['monitor']]} \n"; - if (isset($config['system']['lb_use_sticky'])) + if (isset($config['system']['lb_use_sticky'])) { $conf .= " sticky-address\n"; + } /* sitedown MUST use the same port as the primary pool - sucks, but it's a relayd thing */ - if (isset($vs_a[$i]['sitedown']) && strlen($vs_a[$i]['sitedown']) > 0 && ($vs_a[$i]['relay_protocol'] != 'dns')) + if (isset($vs_a[$i]['sitedown']) && strlen($vs_a[$i]['sitedown']) > 0 && ($vs_a[$i]['relay_protocol'] != 'dns')) { $conf .= " forward to <{$vs_a[$i]['sitedown']}> port {$dest_port} {$check_a[$pools[$vs_a[$i]['sitedown']]['monitor']]} \n"; + } $conf .= "}\n"; } @@ -384,7 +381,7 @@ function relayd_configure($kill_first=false) { cleanup_lb_anchor("*"); } } else { - if (! empty($vs_a)) { + if (!empty($vs_a)) { // not running and there is a config, start it /* Remove all active relayd anchors so it can start fresh. */ cleanup_lb_anchor("*"); @@ -418,9 +415,9 @@ Id Type Name Avlblty Status # relayctl show redirects Id Type Name Avlblty Status 1 redirect testvs2 active - total: 2 sessions - last: 2/60s 2/h 2/d sessions - average: 1/60s 0/h 0/d sessions + total: 2 sessions + last: 2/60s 2/h 2/d sessions + average: 1/60s 0/h 0/d sessions 0 redirect testvs active */ $rdr_a = array(); @@ -433,7 +430,7 @@ Id Type Name Avlblty Status $line = $rdr_a[$i]; if (preg_match("/^[0-9]+/", $line)) { $regs = array(); - if($x = preg_match("/^[0-9]+\s+redirect\s+([^\s]+)\s+([^\s]+)/", $line, $regs)) { + if ($x = preg_match("/^[0-9]+\s+redirect\s+([^\s]+)\s+([^\s]+)/", $line, $regs)) { $cur_entry = trim($regs[1]); $vs[trim($regs[1])] = array(); $vs[trim($regs[1])]['status'] = trim($regs[2]); @@ -451,7 +448,7 @@ Id Type Name Avlblty Status $line = $relay_a[$i]; if (preg_match("/^[0-9]+/", $line)) { $regs = array(); - if($x = preg_match("/^[0-9]+\s+relay\s+([^\s]+)\s+([^\s]+)/", $line, $regs)) { + if ($x = preg_match("/^[0-9]+\s+relay\s+([^\s]+)\s+([^\s]+)/", $line, $regs)) { $cur_entry = trim($regs[1]); $vs[trim($regs[1])] = array(); $vs[trim($regs[1])]['status'] = trim($regs[2]); @@ -471,7 +468,7 @@ function get_lb_summary() { $relayctl = array(); exec('/usr/local/sbin/relayctl show summary 2>&1', $relayctl); $relay_hosts=Array(); - foreach( (array) $relayctl as $line) { + foreach ((array) $relayctl as $line) { $t = explode("\t", $line); switch (trim($t[1])) { case "table": @@ -510,16 +507,19 @@ function cleanup_lb_anchor($anchorname = "*") { function cleanup_lb_mark_anchor($name) { global $g; /* Nothing to do! */ - if (empty($name)) + if (empty($name)) { return; + } $filename = "{$g['tmp_path']}/relayd_anchors_remove"; $cleanup_anchors = array(); /* Read in any currently unapplied name changes */ - if (file_exists($filename)) + if (file_exists($filename)) { $cleanup_anchors = explode("\n", file_get_contents($filename)); + } /* Only add the anchor to the list if it's not already there. */ - if (!in_array($name, $cleanup_anchors)) + if (!in_array($name, $cleanup_anchors)) { $cleanup_anchors[] = $name; + } file_put_contents($filename, implode("\n", $cleanup_anchors)); } @@ -534,14 +534,15 @@ function cleanup_lb_marked() { } else { $cleanup_anchors = explode("\n", file_get_contents($filename)); /* Nothing to do! */ - if (empty($cleanup_anchors)) + if (empty($cleanup_anchors)) { return; + } } /* Load current names so we can make sure we don't remove an anchor that is still in use. */ $vs_a = $config['load_balancer']['virtual_server']; $active_vsnames = array(); - if(is_array($vs_a)) { + if (is_array($vs_a)) { foreach ($vs_a as $vs) { $active_vsnames[] = $vs['name']; } diff --git a/etc/inc/wizardapp.inc b/etc/inc/wizardapp.inc index 091f73aa53..b94c76be66 100644 --- a/etc/inc/wizardapp.inc +++ b/etc/inc/wizardapp.inc @@ -107,7 +107,7 @@ $gamesplist['gamesforwindowslive'] = array(); $gamesplist['arma2'] = array(); /* ARMA 2 */ $gamesplist['arma2'][] = array('arma2', 'udp', '2302', '2310', 'both'); - + $gamesplist['arma3'] = array(); /* ARMA 3 */ $gamesplist['arma3'][] = array('arma3-game-traffic', 'udp', '2302', '2302', 'both'); @@ -128,7 +128,7 @@ $gamesplist['battlefield2'] = array(); $gamesplist['battlefield2'][] = array('BF2-29900-29901-TCP', 'tcp', '29900', '29901', 'both'); $gamesplist['battlefield2'][] = array('BF2-27900', 'udp', '27900', '27900', 'both'); $gamesplist['battlefield2'][] = array('BF2-55123-55125', 'udp', '55123', '55125', 'both'); - + $gamesplist['battlefield3'] = array(); /* Battlefield 3 and Battlefield 4 */ $gamesplist['battlefield3'][] = array('BF3-1', 'tcp', '9988', '9988', 'both'); @@ -217,7 +217,7 @@ $gamesplist['dirt3'] = array(); /* ARMA 2 */ $gamesplist['dirt3'][] = array('Dirt3-1', 'tcp', '2300', '2400', 'both'); $gamesplist['dirt3'][] = array('Dirt3-2', 'udp', '2300', '2400', 'both'); - $gamesplist['dirt3'][] = array('Dirt3-3', 'udp', '6073', '6073', 'both'); + $gamesplist['dirt3'][] = array('Dirt3-3', 'udp', '6073', '6073', 'both'); $gamesplist['dirt3'][] = array('Dirt3-4', 'tcp', '47624', '47624', 'both'); $gamesplist['doom3'] = array(); @@ -277,7 +277,7 @@ $gamesplist['farcry3'] = array(); /* FarCry 3*/ $gamesplist['farcry3'][] = array('FarCry3-game', 'udp', '9000', '9000', 'both'); $gamesplist['farcry3'][] = array('FarCry3-punkbuster', 'udp', '10009', '10009', 'both'); - + $gamesplist['gunzonline'] = array(); /* GunZ Online */ $gamesplist['gunzonline'][] = array('GunZOnline', 'udp', '7700', '7700', 'both'); @@ -327,7 +327,7 @@ $gamesplist['planetside'] = array(); $gamesplist['planetside'][] = array('PlanetSide2', 'udp', '3016', '3021', 'both'); $gamesplist['planetside'][] = array('PlanetSide2', 'udp', '45000', '45010', 'both'); $gamesplist['planetside'][] = array('PlanetSide2', 'udp', '30000', '30500', 'both'); - + $gamesplist['planetside2'] = array(); /* PlanetSide 2 */ $gamesplist['planetside2'][] = array('PlanetSide2-game', 'udp', '20040', '20199', 'both'); @@ -337,7 +337,7 @@ $gamesplist['planetside2'] = array(); $gamesplist['quakeiii'] = array(); /* quake3 */ $gamesplist['quakeiii'][] = array('Quake3', 'udp', '27910', '27919', 'both'); - + $gamesplist['quakeiv'] = array(); /* quake4 */ $gamesplist['quakeiv'][] = array('QuakeIV-server-udp', 'udp', '27650', '27650', 'both'); @@ -385,12 +385,12 @@ $voiplist['Asterisk'] = array(); $voiplist['Asterisk'][] = array('Asterisk', 'udp', '5060', '5069', 'both'); $voiplist['Asterisk'][] = array('Asterisk', 'udp', '10000', '20000', 'both'); - /* VoicePulse server */ + /* VoicePulse server */ $voiplist['VoicePulse'] = array(); $voiplist['VoicePulse'][] = array('VoicePulse', 'udp', '16384', '16482', 'both'); $voiplist['VoicePulse'][] = array('VoicePulse', 'udp', '4569', '4569', 'both'); - /* Panasonic Hybrid PBX */ + /* Panasonic Hybrid PBX */ $voiplist['Panasonic'] = array(); $voiplist['Panasonic'][] = array('Panasonic1', 'udp', '8000', '8063', 'both'); $voiplist['Panasonic'][] = array('Panasonic2', 'udp', '9300', '9301', 'both'); @@ -401,7 +401,7 @@ $p2plist = array(); /* To add p2p clients, push Descr,Protocol,Start,End,src/dest/both onto p2plist */ $p2plist['aimster'] = array(); $p2plist['aimster'][] = array('Aimster', 'tcp', '7668', '7668', 'both'); - $p2plist['bittorrent'] = array(); + $p2plist['bittorrent'] = array(); $p2plist['bittorrent'][] = array('BitTorrent', 'tcp', '6881', '6999', 'both'); $p2plist['bittorrent'][] = array('BitTorrent', 'udp', '6881', '6999', 'both'); $p2plist['buddyshare'] = array(); @@ -420,7 +420,7 @@ $p2plist = array(); $p2plist['edonkey2000'][] = array('EDonkey2000', 'tcp', '4661', '4665', 'both'); $p2plist['fastTrack'] = array(); $p2plist['fastTrack'][] = array('FastTrack', 'tcp', '1214', '1214', 'both'); - $p2plist['gnutella'] = array(); + $p2plist['gnutella'] = array(); $p2plist['gnutella'][] = array('Gnutella-TCP', 'tcp', '6346', '6346', 'both'); $p2plist['gnutella'][] = array('Gnutella-UDP', 'udp', '6346', '6346', 'both'); $p2plist['grouper'] = array(); @@ -509,7 +509,7 @@ $othersplist = array(); $othersplist['msnmessenger'][] = array('MSN2', 'tcp', '6891', '6900', 'both'); $othersplist['msnmessenger'][] = array('MSN3', 'tcp', '6901', '6901', 'both'); $othersplist['msnmessenger'][] = array('MSN4', 'udp', '6901', '6901', 'both'); - + $othersplist['teamspeak'] = array(); /* teamspeak */ $othersplist['teamspeak'][] = array('TeamSpeak-1', 'tcp', '14534', '14534', 'both'); @@ -624,7 +624,7 @@ $othersplist = array(); $othersplist['git'] = array(); /* GIT */ $othersplist['git'][] = array('git', 'tcp', '9418', '9418', 'both'); - + $othersplist['hbci'] = array(); /* HBCI */ $othersplist['hbci'][] = array('HBCI', 'tcp', '3000', '3000', 'both'); @@ -641,7 +641,7 @@ $othersplist = array(); /* nntp */ $othersplist['nntp'][] = array('NNTP1', 'tcp', '119', '119', 'both'); $othersplist['nntp'][] = array('NNTP2', 'udp', '119', '119', 'both'); - + $othersplist['slingbox'] = array(); /* slingbox */ $othersplist['slingbox'][] = array('Slingbox1', 'tcp', '5001', '5001', 'both'); diff --git a/etc/inc/xmlparse.inc b/etc/inc/xmlparse.inc index 3b32719846..e7af433412 100644 --- a/etc/inc/xmlparse.inc +++ b/etc/inc/xmlparse.inc @@ -37,30 +37,30 @@ function listtags() { * I know it's a pain, but it's a pain to find stuff too if it's not */ $ret = array( - 'acls', 'alias', 'aliasurl', 'allowedip', 'allowedhostname', 'authserver', - 'bridged', 'build_port_path', - 'ca', 'cacert', 'cert', 'crl', 'clone', 'config', 'container', 'columnitem', - 'depends_on_package', 'disk', 'dnsserver', 'dnsupdate', 'domainoverrides', 'dyndns', - 'earlyshellcmd', 'element', 'encryption-algorithm-option', - 'field', 'fieldname', - 'gateway_item', 'gateway_group', 'gif', 'gre', 'group', - 'hash-algorithm-option', 'hosts', 'member', 'ifgroupentry', 'igmpentry', 'interface_array', 'item', 'key', - 'lagg', 'lbaction', 'lbpool', 'l7rules', 'lbprotocol', - 'member', 'menu', 'tab', 'mobilekey', 'monitor_type', 'mount', + 'acls', 'alias', 'aliasurl', 'allowedip', 'allowedhostname', 'authserver', + 'bridged', 'build_port_path', + 'ca', 'cacert', 'cert', 'crl', 'clone', 'config', 'container', 'columnitem', + 'depends_on_package', 'disk', 'dnsserver', 'dnsupdate', 'domainoverrides', 'dyndns', + 'earlyshellcmd', 'element', 'encryption-algorithm-option', + 'field', 'fieldname', + 'gateway_item', 'gateway_group', 'gif', 'gre', 'group', + 'hash-algorithm-option', 'hosts', 'member', 'ifgroupentry', 'igmpentry', 'interface_array', 'item', 'key', + 'lagg', 'lbaction', 'lbpool', 'l7rules', 'lbprotocol', + 'member', 'menu', 'tab', 'mobilekey', 'monitor_type', 'mount', 'npt', 'ntpserver', - 'onetoone', 'openvpn-server', 'openvpn-client', 'openvpn-csc', 'option', - 'package', 'passthrumac', 'phase1', 'phase2', 'ppp', 'pppoe', 'priv', 'proxyarpnet', 'pool', + 'onetoone', 'openvpn-server', 'openvpn-client', 'openvpn-csc', 'option', + 'package', 'passthrumac', 'phase1', 'phase2', 'ppp', 'pppoe', 'priv', 'proxyarpnet', 'pool', 'qinqentry', 'queue', - 'pages', 'pipe', 'radnsserver', 'roll', 'route', 'row', 'rrddatafile', 'rule', + 'pages', 'pipe', 'radnsserver', 'roll', 'route', 'row', 'rrddatafile', 'rule', 'schedule', 'service', 'servernat', 'servers', - 'serversdisabled', 'shellcmd', 'staticmap', 'subqueue', + 'serversdisabled', 'shellcmd', 'staticmap', 'subqueue', 'timerange', 'tunnel', 'user', 'vip', 'virtual_server', 'vlan', 'winsserver', 'wolentry', 'widget' ); return array_flip($ret); } -/* Package XML tags that should be treat as a list not as a traditional array */ +/* Package XML tags that should be treated as a list not as a traditional array */ function listtags_pkg() { $ret = array('build_port_path', 'depends_on_package', 'onetoone', 'queue', 'rule', 'servernat', 'alias', 'additional_files_needed', 'tab', 'template', 'menu', 'rowhelperfield', 'service', 'step', 'package', 'columnitem', 'option', 'item', 'field', 'package', 'file'); @@ -91,8 +91,8 @@ function startElement($parser, $name, $attrs) { } else if (isset($ptr)) { /* multiple entries not allowed for this element, bail out */ die(sprintf(gettext('XML error: %1$s at line %2$d cannot occur more than once') . "\n", - $name, - xml_get_current_line_number($parser))); + $name, + xml_get_current_line_number($parser))); } $depth++; @@ -112,8 +112,9 @@ function endElement($parser, $name) { array_pop($curpath); - if (isset($listtags[strtolower($name)])) + if (isset($listtags[strtolower($name)])) { array_pop($curpath); + } $depth--; } @@ -143,26 +144,27 @@ function cData($parser, $data) { function parse_xml_config($cffile, $rootobj, $isstring = "false") { global $listtags; $listtags = listtags(); - if (isset($GLOBALS['custom_listtags'])) { - foreach($GLOBALS['custom_listtags'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags'])) { + foreach ($GLOBALS['custom_listtags'] as $tag) { + $listtags[$tag] = $tag; + } + } return parse_xml_config_raw($cffile, $rootobj, $isstring); } function parse_xml_config_pkg($cffile, $rootobj, $isstring = "false") { global $listtags; $listtags = listtags_pkg(); - if (isset($GLOBALS['custom_listtags_pkg'])) { - foreach($GLOBALS['custom_listtags_pkg'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags_pkg'])) { + foreach ($GLOBALS['custom_listtags_pkg'] as $tag) { + $listtags[$tag] = $tag; + } + } $cfg =parse_xml_config_raw($cffile, $rootobj, $isstring); - if ($cfg == -1) + if ($cfg == -1) { return array(); - + } + return $cfg; } @@ -178,7 +180,7 @@ function parse_xml_config_raw($cffile, $rootobj, $isstring = "false") { xml_set_element_handler($xml_parser, "startElement", "endElement"); xml_set_character_data_handler($xml_parser, "cdata"); - xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE, 1); + xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE, 1); if (!($fp = fopen($cffile, "r"))) { log_error(gettext("Error: could not open XML input") . "\n"); @@ -188,21 +190,24 @@ function parse_xml_config_raw($cffile, $rootobj, $isstring = "false") { while ($data = fread($fp, 4096)) { if (!xml_parse($xml_parser, $data, feof($fp))) { log_error(sprintf(gettext('XML error: %1$s at line %2$d in %3$s') . "\n", - xml_error_string(xml_get_error_code($xml_parser)), - xml_get_current_line_number($xml_parser), - $cffile)); + xml_error_string(xml_get_error_code($xml_parser)), + xml_get_current_line_number($xml_parser), + $cffile)); return -1; } } xml_parser_free($xml_parser); if ($rootobj) { - if (!is_array($rootobj)) + if (!is_array($rootobj)) { $rootobj = array($rootobj); - foreach ($rootobj as $rootobj_name) - if ($parsedcfg[$rootobj_name]) + } + foreach ($rootobj as $rootobj_name) { + if ($parsedcfg[$rootobj_name]) { break; - + } + } + if (!$parsedcfg[$rootobj_name]) { log_error(sprintf(gettext("XML error: no %s object found!") . "\n", implode(" or ", $rootobj))); return -1; @@ -236,18 +241,20 @@ function dump_xml_config_sub($arr, $indent) { $xmlconfig .= "\n"; } } else { - if($cval === false) continue; + if ($cval === false) { + continue; + } $xmlconfig .= str_repeat("\t", $indent); - if((is_bool($cval) && $cval == true) || ($cval === "")) { + if ((is_bool($cval) && $cval == true) || ($cval === "")) { $xmlconfig .= "<$ent/>\n"; - } else if ((substr($ent, 0, 5) == "descr") - || (substr($ent, 0, 6) == "detail") - || (substr($ent, 0, 12) == "login_banner") - || (substr($ent, 0, 9) == "ldap_attr") - || (substr($ent, 0, 9) == "ldap_bind") - || (substr($ent, 0, 11) == "ldap_basedn") - || (substr($ent, 0, 18) == "ldap_authcn") - || (substr($ent, 0, 19) == "ldap_extended_query")) { + } else if ((substr($ent, 0, 5) == "descr") || + (substr($ent, 0, 6) == "detail") || + (substr($ent, 0, 12) == "login_banner") || + (substr($ent, 0, 9) == "ldap_attr") || + (substr($ent, 0, 9) == "ldap_bind") || + (substr($ent, 0, 11) == "ldap_basedn") || + (substr($ent, 0, 18) == "ldap_authcn") || + (substr($ent, 0, 19) == "ldap_extended_query")) { $xmlconfig .= "<$ent>\n"; } else { $xmlconfig .= "<$ent>" . htmlentities($cval) . "\n"; @@ -271,17 +278,18 @@ function dump_xml_config_sub($arr, $indent) { $xmlconfig .= "<$ent/>\n"; } else if (!is_bool($val)) { $xmlconfig .= str_repeat("\t", $indent); - if ((substr($ent, 0, 5) == "descr") - || (substr($ent, 0, 6) == "detail") - || (substr($ent, 0, 12) == "login_banner") - || (substr($ent, 0, 9) == "ldap_attr") - || (substr($ent, 0, 9) == "ldap_bind") - || (substr($ent, 0, 11) == "ldap_basedn") - || (substr($ent, 0, 18) == "ldap_authcn") - || (substr($ent, 0, 19) == "ldap_extended_query")) + if ((substr($ent, 0, 5) == "descr") || + (substr($ent, 0, 6) == "detail") || + (substr($ent, 0, 12) == "login_banner") || + (substr($ent, 0, 9) == "ldap_attr") || + (substr($ent, 0, 9) == "ldap_bind") || + (substr($ent, 0, 11) == "ldap_basedn") || + (substr($ent, 0, 18) == "ldap_authcn") || + (substr($ent, 0, 19) == "ldap_extended_query")) $xmlconfig .= "<$ent>\n"; - else + else { $xmlconfig .= "<$ent>" . htmlentities($val) . "\n"; + } } } } @@ -292,22 +300,22 @@ function dump_xml_config_sub($arr, $indent) { function dump_xml_config($arr, $rootobj) { global $listtags; $listtags = listtags(); - if (isset($GLOBALS['custom_listtags'])) { - foreach($GLOBALS['custom_listtags'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags'])) { + foreach ($GLOBALS['custom_listtags'] as $tag) { + $listtags[$tag] = $tag; + } + } return dump_xml_config_raw($arr, $rootobj); } function dump_xml_config_pkg($arr, $rootobj) { global $listtags; $listtags = listtags_pkg(); - if (isset($GLOBALS['custom_listtags_pkg'])) { - foreach($GLOBALS['custom_listtags_pkg'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags_pkg'])) { + foreach ($GLOBALS['custom_listtags_pkg'] as $tag) { + $listtags[$tag] = $tag; + } + } return dump_xml_config_raw($arr, $rootobj); } diff --git a/etc/inc/xmlparse_attr.inc b/etc/inc/xmlparse_attr.inc index 933caba696..a024c20a76 100644 --- a/etc/inc/xmlparse_attr.inc +++ b/etc/inc/xmlparse_attr.inc @@ -52,8 +52,9 @@ function startElement_attr($parser, $name, $attrs) { } foreach ($curpath as $path) { $ptr =& $ptr[$path]; - if (isset($writeattrs)) + if (isset($writeattrs)) { $attrptr =& $attrptr[$path]; + } } /* is it an element that belongs to a list? */ @@ -68,16 +69,17 @@ function startElement_attr($parser, $name, $attrs) { array_push($curpath, count($ptr)); if (isset($writeattrs)) { - if (!is_array($attrptr)) + if (!is_array($attrptr)) { $attrptr = array(); + } $attrptr[count($ptr)] = $attrs; } } else if (isset($ptr)) { /* multiple entries not allowed for this element, bail out */ die(sprintf(gettext('XML error: %1$s at line %2$d cannot occur more than once') . "\n", - $name, - xml_get_current_line_number($parser))); + $name, + xml_get_current_line_number($parser))); } else if (isset($writeattrs)) { $attrptr = $attrs; } @@ -99,8 +101,9 @@ function endElement_attr($parser, $name) { array_pop($curpath); - if (in_array(strtolower($name), $listtags)) + if (in_array(strtolower($name), $listtags)) { array_pop($curpath); + } $depth--; } @@ -130,8 +133,9 @@ function cData_attr($parser, $data) { function parse_xml_regdomain(&$rdattributes, $rdfile = '', $rootobj = 'regulatory-data') { global $g, $listtags; - if (empty($rdfile)) + if (empty($rdfile)) { $rdfile = $g['etc_path'] . '/regdomain.xml'; + } $listtags = listtags_rd(); $parsed_xml = array(); @@ -147,15 +151,19 @@ function parse_xml_regdomain(&$rdattributes, $rdfile = '', $rootobj = 'regulator // unset parts that aren't used before making cache foreach ($rdmain['regulatory-domains']['rd'] as $rdkey => $rdentry) { - if (isset($rdmain['regulatory-domains']['rd'][$rdkey]['netband'])) + if (isset($rdmain['regulatory-domains']['rd'][$rdkey]['netband'])) { unset($rdmain['regulatory-domains']['rd'][$rdkey]['netband']); - if (isset($rdattributes['regulatory-domains']['rd'][$rdkey]['netband'])) + } + if (isset($rdattributes['regulatory-domains']['rd'][$rdkey]['netband'])) { unset($rdattributes['regulatory-domains']['rd'][$rdkey]['netband']); + } } - if (isset($rdmain['shared-frequency-bands'])) + if (isset($rdmain['shared-frequency-bands'])) { unset($rdmain['shared-frequency-bands']); - if (isset($rdattributes['shared-frequency-bands'])) + } + if (isset($rdattributes['shared-frequency-bands'])) { unset($rdattributes['shared-frequency-bands']); + } $parsed_xml = array('main' => $rdmain, 'attributes' => $rdattributes); $rdcache = fopen($g['tmp_path'] . '/regdomain.cache', "w"); @@ -174,14 +182,15 @@ function parse_xml_config_raw_attr($cffile, $rootobj, &$parsed_attributes, $isst $depth = 0; $havedata = 0; - if (isset($parsed_attributes)) + if (isset($parsed_attributes)) { $parsedattrs = array(); + } $xml_parser = xml_parser_create(); xml_set_element_handler($xml_parser, "startElement_attr", "endElement_attr"); xml_set_character_data_handler($xml_parser, "cData_attr"); - xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE, 1); + xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE, 1); if (!($fp = fopen($cffile, "r"))) { log_error(gettext("Error: could not open XML input") . "\n"); @@ -195,8 +204,8 @@ function parse_xml_config_raw_attr($cffile, $rootobj, &$parsed_attributes, $isst while ($data = fread($fp, 4096)) { if (!xml_parse($xml_parser, $data, feof($fp))) { log_error(sprintf(gettext('XML error: %1$s at line %2$d') . "\n", - xml_error_string(xml_get_error_code($xml_parser)), - xml_get_current_line_number($xml_parser))); + xml_error_string(xml_get_error_code($xml_parser)), + xml_get_current_line_number($xml_parser))); if (isset($parsed_attributes)) { $parsed_attributes = array(); unset($parsedattrs); @@ -216,8 +225,9 @@ function parse_xml_config_raw_attr($cffile, $rootobj, &$parsed_attributes, $isst } if (isset($parsed_attributes)) { - if ($parsedattrs[$rootobj]) + if ($parsedattrs[$rootobj]) { $parsed_attributes = $parsedattrs[$rootobj]; + } unset($parsedattrs); } diff --git a/etc/inc/xmlreader.inc b/etc/inc/xmlreader.inc index a0563ae0b7..960acb1bf2 100644 --- a/etc/inc/xmlreader.inc +++ b/etc/inc/xmlreader.inc @@ -37,9 +37,9 @@ /* The following items will be treated as arrays in config.xml */ function listtags() { /* - * Please keep this list alpha sorted and no longer than 80 characters - * I know it's a pain, but it's a pain to find stuff too if it's not - */ + * Please keep this list alpha sorted and no longer than 80 characters + * I know it's a pain, but it's a pain to find stuff too if it's not + */ $ret = array( 'acls', 'alias', 'aliasurl', 'allowedip', 'allowedhostname', 'authserver', 'bridged', 'build_port_path', @@ -72,61 +72,64 @@ function listtags_pkg() { } function add_elements(&$cfgarray, &$parser) { - global $listtags; + global $listtags; - while ($parser->read()) { - switch ($parser->nodeType) { - case XMLReader::WHITESPACE: - case XMLReader::SIGNIFICANT_WHITESPACE: - break; - case XMLReader::ELEMENT: - if (isset($listtags[strtolower($parser->name)])) { - $cfgref =& $cfgarray[$parser->name][count($cfgarray[$parser->name])]; - if (!$parser->isEmptyElement) { - add_elements($cfgref, $parser); - } else - $cfgref = array(); - - } else { - if (isset($cfgarray[$parser->name]) && (!is_array($cfgarray[$parser->name]) || !isset($cfgarray[$parser->name][0]))) { - $nodebkp = $cfgarray[$parser->name]; - $cfgarray[$parser->name] = array(); - $cfgarray[$parser->name][] = $nodebkp; - $cfgref =& $cfgarray[$parser->name][0]; - unset($nodebkp); - } else - $cfgref =& $cfgarray[$parser->name]; - - if ($parser->isEmptyElement) { - if (is_array($cfgref)) - $cfgref[] = array(); - else - $cfgref = ""; + while ($parser->read()) { + switch ($parser->nodeType) { + case XMLReader::WHITESPACE: + case XMLReader::SIGNIFICANT_WHITESPACE: + break; + case XMLReader::ELEMENT: + if (isset($listtags[strtolower($parser->name)])) { + $cfgref =& $cfgarray[$parser->name][count($cfgarray[$parser->name])]; + if (!$parser->isEmptyElement) { + add_elements($cfgref, $parser); + } else { + $cfgref = array(); + } } else { - if (is_array($cfgref)) { - $cfgref =& $cfgarray[$parser->name][count($cfgarray[$parser->name])]; - add_elements($cfgref, $parser); - } else - add_elements($cfgref, $parser); - } - } + if (isset($cfgarray[$parser->name]) && (!is_array($cfgarray[$parser->name]) || !isset($cfgarray[$parser->name][0]))) { + $nodebkp = $cfgarray[$parser->name]; + $cfgarray[$parser->name] = array(); + $cfgarray[$parser->name][] = $nodebkp; + $cfgref =& $cfgarray[$parser->name][0]; + unset($nodebkp); + } else { + $cfgref =& $cfgarray[$parser->name]; + } - $i = 0; - while ($parser->moveToAttributeNo($i)) { - $cfgref[$parser->name] = $parser->value; - $i++; - } - break; - case XMLReader::TEXT: - case XMLReader::CDATA: - $cfgarray = $parser->value; - break; - case XMLReader::END_ELEMENT: - return; - break; - default: - break; - } + if ($parser->isEmptyElement) { + if (is_array($cfgref)) { + $cfgref[] = array(); + } else { + $cfgref = ""; + } + } else { + if (is_array($cfgref)) { + $cfgref =& $cfgarray[$parser->name][count($cfgarray[$parser->name])]; + add_elements($cfgref, $parser); + } else { + add_elements($cfgref, $parser); + } + } + } + + $i = 0; + while ($parser->moveToAttributeNo($i)) { + $cfgref[$parser->name] = $parser->value; + $i++; + } + break; + case XMLReader::TEXT: + case XMLReader::CDATA: + $cfgarray = $parser->value; + break; + case XMLReader::END_ELEMENT: + return; + break; + default: + break; + } } } @@ -134,11 +137,11 @@ function parse_xml_config($cffile, $rootobj, $isstring = "false") { global $listtags; $listtags = listtags(); - if (isset($GLOBALS['custom_listtags'])) { - foreach($GLOBALS['custom_listtags'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags'])) { + foreach ($GLOBALS['custom_listtags'] as $tag) { + $listtags[$tag] = $tag; + } + } return parse_xml_config_raw($cffile, $rootobj); } @@ -147,11 +150,11 @@ function parse_xml_config_pkg($cffile, $rootobj, $isstring = "false") { global $listtags; $listtags = listtags_pkg(); - if (isset($GLOBALS['custom_listtags_pkg'])) { - foreach($GLOBALS['custom_listtags_pkg'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags_pkg'])) { + foreach ($GLOBALS['custom_listtags_pkg'] as $tag) { + $listtags[$tag] = $tag; + } + } return parse_xml_config_raw($cffile, $rootobj, $isstring); } @@ -164,16 +167,20 @@ function parse_xml_config_raw($cffile, $rootobj, $isstring = "false") { if ($par->open($cffile, "UTF-8", LIBXML_NOERROR | LIBXML_NOWARNING)) { add_elements($parsedcfg, $par); $par->close(); - } else + } else { log_error(sprintf(gettext("Error returned while trying to parse %s"), $cffile)); + } if ($rootobj) { - if (!is_array($rootobj)) + if (!is_array($rootobj)) { $rootobj = array($rootobj); - foreach ($rootobj as $rootobj_name) - if ($parsedcfg[$rootobj_name]) + } + foreach ($rootobj as $rootobj_name) { + if ($parsedcfg[$rootobj_name]) { break; - + } + } + return $parsedcfg[$rootobj_name]; } else { return $parsedcfg; @@ -181,55 +188,59 @@ function parse_xml_config_raw($cffile, $rootobj, $isstring = "false") { } function dump_xml_config_sub(& $writer, $arr) { - global $listtags; + global $listtags; - foreach ($arr as $ent => $val) { - if (is_array($val)) { - /* is it just a list of multiple values? */ - if (isset($listtags[strtolower($ent)])) { - foreach ($val as $cval) { - if (is_array($cval)) { - if (empty($cval)) - $writer->writeElement($ent); - else { - $writer->startElement($ent); - dump_xml_config_sub($writer, $cval); - $writer->endElement(); - } - } else { - if($cval === false) continue; - if ((is_bool($val) && ($val == true)) || ($val === "")) - $writer->writeElement($ent); - else if (!is_bool($val)) + foreach ($arr as $ent => $val) { + if (is_array($val)) { + /* is it just a list of multiple values? */ + if (isset($listtags[strtolower($ent)])) { + foreach ($val as $cval) { + if (is_array($cval)) { + if (empty($cval)) { + $writer->writeElement($ent); + } else { + $writer->startElement($ent); + dump_xml_config_sub($writer, $cval); + $writer->endElement(); + } + } else { + if ($cval === false) { + continue; + } + if ((is_bool($val) && ($val == true)) || ($val === "")) { + $writer->writeElement($ent); + } else if (!is_bool($val)) { $writer->writeElement($ent, $cval); - } - } - } else if (empty($val)) { - $writer->writeElement($ent); - } else { - /* it's an array */ - $writer->startElement($ent); - dump_xml_config_sub($writer, $val); - $writer->endElement(); - } - } else { - if ((is_bool($val) && ($val == true)) || ($val === "")) - $writer->writeElement($ent); - else if (!is_bool($val)) - $writer->writeElement($ent, $val); - } - } + } + } + } + } else if (empty($val)) { + $writer->writeElement($ent); + } else { + /* it's an array */ + $writer->startElement($ent); + dump_xml_config_sub($writer, $val); + $writer->endElement(); + } + } else { + if ((is_bool($val) && ($val == true)) || ($val === "")) { + $writer->writeElement($ent); + } else if (!is_bool($val)) { + $writer->writeElement($ent, $val); + } + } + } } function dump_xml_config($arr, $rootobj) { global $listtags; $listtags = listtags(); - if (isset($GLOBALS['custom_listtags'])) { - foreach($GLOBALS['custom_listtags'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags'])) { + foreach ($GLOBALS['custom_listtags'] as $tag) { + $listtags[$tag] = $tag; + } + } return dump_xml_config_raw($arr, $rootobj); } @@ -237,30 +248,30 @@ function dump_xml_config_pkg($arr, $rootobj) { global $listtags; $listtags = listtags_pkg(); - if (isset($GLOBALS['custom_listtags_pkg'])) { - foreach($GLOBALS['custom_listtags_pkg'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags_pkg'])) { + foreach ($GLOBALS['custom_listtags_pkg'] as $tag) { + $listtags[$tag] = $tag; + } + } return dump_xml_config_raw($arr, $rootobj); } function dump_xml_config_raw($arr, $rootobj) { - $writer = new XMLWriter(); - $writer->openMemory(); - $writer->setIndent(true); - $writer->setIndentString("\t"); - $writer->startDocument("1.0", "UTF-8"); - $writer->startElement($rootobj); + $writer = new XMLWriter(); + $writer->openMemory(); + $writer->setIndent(true); + $writer->setIndentString("\t"); + $writer->startDocument("1.0", "UTF-8"); + $writer->startElement($rootobj); - dump_xml_config_sub($writer, $arr); + dump_xml_config_sub($writer, $arr); - $writer->endElement(); - $writer->endDocument(); - $xmlconfig = $writer->outputMemory(true); + $writer->endElement(); + $writer->endDocument(); + $xmlconfig = $writer->outputMemory(true); - return $xmlconfig; + return $xmlconfig; } ?> diff --git a/etc/inc/xmlrpc.inc b/etc/inc/xmlrpc.inc index bce1c1c7f8..e96e783247 100644 --- a/etc/inc/xmlrpc.inc +++ b/etc/inc/xmlrpc.inc @@ -29,7 +29,7 @@ */ /* - pfSense_BUILDER_BINARIES: + pfSense_BUILDER_BINARIES: pfSense_MODULE: utils */ @@ -40,41 +40,43 @@ require_once("xmlrpc_client.inc"); * xmlrpc_params_to_php: Convert params array passed from XMLRPC server into a PHP array and return it. */ function xmlrpc_params_to_php($params) { - $array = array(); - for($i = 0; $i < $params->getNumParams(); $i++) { - $value = $params->getParam($i); - $array[] = XML_RPC_decode($value); - } - return $array; + $array = array(); + for ($i = 0; $i < $params->getNumParams(); $i++) { + $value = $params->getParam($i); + $array[] = XML_RPC_decode($value); + } + return $array; } - + /* * xmlrpc_value_to_php: Convert an XMLRPC value into a PHP scalar/array and return it. */ function xmlrpc_value_to_php($raw_value) { /* - switch($raw_value->kindOf()) { - case "scalar": - if($raw_value->scalartyp() == "boolean") $return = (boolean) $raw_value->scalarval(); - $return = $raw_value->scalarval(); - break; - case "array": - $return = array(); - for($i = 0; $i < $raw_value->arraysize(); $i++) { - $value = $raw_value->arraymem($i); - $return[] = xmlrpc_value_to_php($value); - } - break; - case "struct": - $return = array(); - for($i = 0; $i < $raw_value->arraysize(); $i++) { - list($key, $value) = $raw_value->structeach(); - $return[$key] = xmlrpc_value_to_php($value); - } - break; - } + switch ($raw_value->kindOf()) { + case "scalar": + if ($raw_value->scalartyp() == "boolean") { + $return = (boolean) $raw_value->scalarval(); + } + $return = $raw_value->scalarval(); + break; + case "array": + $return = array(); + for ($i = 0; $i < $raw_value->arraysize(); $i++) { + $value = $raw_value->arraymem($i); + $return[] = xmlrpc_value_to_php($value); + } + break; + case "struct": + $return = array(); + for ($i = 0; $i < $raw_value->arraysize(); $i++) { + list($key, $value) = $raw_value->structeach(); + $return[$key] = xmlrpc_value_to_php($value); + } + break; + } */ - return XML_RPC_decode($raw_value); + return XML_RPC_decode($raw_value); } /* @@ -84,21 +86,23 @@ function php_value_to_xmlrpc($value, $force_array = false) { $toreturn = XML_RPC_encode($value); return $force_array ? array($toreturn) : $toreturn; /* - if(gettype($value) == "array") { - $xmlrpc_type = "array"; - $toreturn = array(); - foreach($value as $key => $val) { - if(is_string($key)) $xmlrpc_type = "struct"; - $toreturn[$key] = php_value_to_xmlrpc($val); - } - return new XML_RPC_Value($toreturn, $xmlrpc_type); - } else { - if($force_array == true) { - return new XML_RPC_Value(array(new XML_RPC_Value($value, gettype($value))), "array"); - } else { - return new XML_RPC_Value($value, gettype($value)); - } - } + if (gettype($value) == "array") { + $xmlrpc_type = "array"; + $toreturn = array(); + foreach ($value as $key => $val) { + if (is_string($key)) { + $xmlrpc_type = "struct"; + } + $toreturn[$key] = php_value_to_xmlrpc($val); + } + return new XML_RPC_Value($toreturn, $xmlrpc_type); + } else { + if ($force_array == true) { + return new XML_RPC_Value(array(new XML_RPC_Value($value, gettype($value))), "array"); + } else { + return new XML_RPC_Value($value, gettype($value)); + } + } */ } @@ -114,13 +118,13 @@ function xmlrpc_auth(&$params) { /* XXX: Should clarify from old behaviour what is in params[0] that differs from params['xmlrpcauth'] */ if (isset($config['system']['webgui']['authmode'])) { $authcfg = auth_get_authserver($config['system']['webgui']['authmode']); - if (authenticate_user("admin", $params[0], $authcfg) || - authenticate_user("admin", $params[0])) { + if (authenticate_user("admin", $params[0], $authcfg) || + authenticate_user("admin", $params[0])) { array_shift($params); unset($params['xmlrpcauth']); return true; - } else if (!empty($params['xmlrpcauth']) && (authenticate_user("admin", $params['xmlrpcauth'], $authcfg) || - authenticate_user("admin", $params['xmlrpcauth']))) { + } else if (!empty($params['xmlrpcauth']) && (authenticate_user("admin", $params['xmlrpcauth'], $authcfg) || + authenticate_user("admin", $params['xmlrpcauth']))) { array_shift($params); unset($params['xmlrpcauth']); return true; From 5bd0ba3e5de5c5f3a8ebb01ec0db15125dcdb523 Mon Sep 17 00:00:00 2001 From: jim-p Date: Mon, 9 Mar 2015 10:22:14 -0400 Subject: [PATCH 193/257] Add missing 'break' statement that broke switching from a PPP type to 'none'. --- usr/local/www/interfaces.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 795569c6f0..cdb9028090 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -522,6 +522,7 @@ if ($_POST['apply']) { $input_errors[] = gettext("This interface is referenced by IPv4 VIPs. Please delete those before setting the interface to 'none' configuration."); } } + break; case "dhcp": if (in_array($wancfg['ipaddr'], array("ppp", "pppoe", "pptp", "l2tp"))) $input_errors[] = sprintf(gettext("You have to reassign the interface to be able to configure as %s."),$_POST['type']); @@ -575,6 +576,7 @@ if ($_POST['apply']) { $input_errors[] = gettext("This interface is referenced by IPv6 VIPs. Please delete those before setting the interface to 'none' configuration."); } } + break; case "dhcp6": if (in_array($wancfg['ipaddrv6'], array())) $input_errors[] = sprintf(gettext("You have to reassign the interface to be able to configure as %s."),$_POST['type6']); From 261f727120eb57ee1274830fd2b999e3eb826593 Mon Sep 17 00:00:00 2001 From: jim-p Date: Mon, 9 Mar 2015 10:35:26 -0400 Subject: [PATCH 194/257] Allow reassignment from PPP types to DHCP. From testing, it appears to work OK, this input validation appears to be outdated. If there is some edge case that this catches, perhaps it needs to be a more specific test. --- usr/local/www/interfaces.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index cdb9028090..764c962054 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -523,10 +523,6 @@ if ($_POST['apply']) { } } break; - case "dhcp": - if (in_array($wancfg['ipaddr'], array("ppp", "pppoe", "pptp", "l2tp"))) - $input_errors[] = sprintf(gettext("You have to reassign the interface to be able to configure as %s."),$_POST['type']); - break; case "ppp": $reqdfields = explode(" ", "port phone"); $reqdfieldsn = array(gettext("Modem Port"),gettext("Phone Number")); From 7926283050154cb3f7c8fdd368096746714e5513 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Mon, 9 Mar 2015 17:20:36 +0545 Subject: [PATCH 195/257] Code style etc inc vwx3 rebased version with conflicts resolved due to a bunch of recent changes in vpn.inc --- etc/inc/voucher.inc | 426 +++++++++++++------------ etc/inc/vpn.inc | 648 +++++++++++++++++++++++--------------- etc/inc/vslb.inc | 163 +++++----- etc/inc/wizardapp.inc | 26 +- etc/inc/xmlparse.inc | 142 +++++---- etc/inc/xmlparse_attr.inc | 40 ++- etc/inc/xmlreader.inc | 265 ++++++++-------- etc/inc/xmlrpc.inc | 100 +++--- 8 files changed, 1011 insertions(+), 799 deletions(-) diff --git a/etc/inc/voucher.inc b/etc/inc/voucher.inc index f6b7248a20..25c12eeb0d 100644 --- a/etc/inc/voucher.inc +++ b/etc/inc/voucher.inc @@ -3,29 +3,29 @@ voucher.inc Copyright (C) 2010-2012 Ermal Luci Copyright (C) 2010 Scott Ullrich - Copyright (C) 2007 Marcel Wiget - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + Copyright (C) 2007 Marcel Wiget + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. */ @@ -35,8 +35,9 @@ */ /* include all configuration functions */ -if(!function_exists('captiveportal_syslog')) +if (!function_exists('captiveportal_syslog')) { require_once("captiveportal.inc"); +} function xmlrpc_sync_voucher_expire($vouchers, $syncip, $port, $password, $username) { global $g, $config, $cpzone; @@ -44,12 +45,14 @@ function xmlrpc_sync_voucher_expire($vouchers, $syncip, $port, $password, $usern $protocol = "http"; if (is_array($config['system']) && is_array($config['system']['webgui']) && !empty($config['system']['webgui']['protocol']) && - $config['system']['webgui']['protocol'] == "https") + $config['system']['webgui']['protocol'] == "https") { $protocol = "https"; - if ($protocol == "https" || $port == "443") + } + if ($protocol == "https" || $port == "443") { $url = "https://{$syncip}"; - else + } else { $url = "http://{$syncip}"; + } /* Construct code that is run on remote machine */ $method = 'pfsense.exec_php'; @@ -73,12 +76,12 @@ EOF; $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials($username, $password); $resp = $cli->send($msg, "250"); - if(!is_object($resp)) { + if (!is_object($resp)) { $error = "A communications error occurred while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Communications error occurred", ""); return false; - } elseif($resp->faultCode()) { + } elseif ($resp->faultCode()) { $error = "An error code was received while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Error code received", ""); @@ -98,12 +101,14 @@ function xmlrpc_sync_voucher_disconnect($dbent, $syncip, $port, $password, $user $protocol = "http"; if (is_array($config['system']) && is_array($config['system']['webgui']) && !empty($config['system']['webgui']['protocol']) && - $config['system']['webgui']['protocol'] == "https") + $config['system']['webgui']['protocol'] == "https") { $protocol = "https"; - if ($protocol == "https" || $port == "443") + } + if ($protocol == "https" || $port == "443") { $url = "https://{$syncip}"; - else + } else { $url = "http://{$syncip}"; + } /* Construct code that is run on remote machine */ $dbent_str = serialize($dbent); @@ -131,12 +136,12 @@ EOF; $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials($username, $password); $resp = $cli->send($msg, "250"); - if(!is_object($resp)) { + if (!is_object($resp)) { $error = "A communications error occurred while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Communications error occurred", ""); return false; - } elseif($resp->faultCode()) { + } elseif ($resp->faultCode()) { $error = "An error code was received while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Error code received", ""); @@ -156,12 +161,14 @@ function xmlrpc_sync_used_voucher($voucher_received, $syncip, $port, $password, $protocol = "http"; if (is_array($config['system']) && is_array($config['system']['webgui']) && !empty($config['system']['webgui']['protocol']) && - $config['system']['webgui']['protocol'] == "https") + $config['system']['webgui']['protocol'] == "https") { $protocol = "https"; - if ($protocol == "https" || $port == "443") + } + if ($protocol == "https" || $port == "443") { $url = "https://{$syncip}"; - else + } else { $url = "http://{$syncip}"; + } /* Construct code that is run on remote machine */ $method = 'pfsense.exec_php'; @@ -188,12 +195,12 @@ EOF; $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials($username, $password); $resp = $cli->send($msg, "250"); - if(!is_object($resp)) { + if (!is_object($resp)) { $error = "A communications error occurred while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Communications error occurred", ""); return null; // $timeleft - } elseif($resp->faultCode()) { + } elseif ($resp->faultCode()) { $error = "An error code was received while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("CaptivePortalVoucherSync", $error, "Error code received", ""); @@ -202,16 +209,18 @@ EOF; log_error("CaptivePortalVoucherSync XMLRPC reload data success with {$url}:{$port} (pfsense.exec_php)."); } $toreturn = XML_RPC_Decode($resp->value()); - if (!is_array($config['voucher'])) + if (!is_array($config['voucher'])) { $config['voucher'] = array(); + } if (is_array($toreturn['voucher']) && is_array($toreturn['voucher']['roll'])) { $config['voucher'][$cpzone]['roll'] = $toreturn['voucher']['roll']; write_config("Captive Portal Voucher database synchronized with {$url}"); voucher_configure_zone(true); unset($toreturn['voucher']); - } else if (!isset($toreturn['timeleft'])) + } else if (!isset($toreturn['timeleft'])) { return null; + } return $toreturn['timeleft']; } @@ -220,7 +229,7 @@ function voucher_expire($voucher_received) { global $g, $config, $cpzone; // XMLRPC Call over to the master Voucher node - if(!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { + if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { $syncip = $config['voucher'][$cpzone]['vouchersyncdbip']; $syncport = $config['voucher'][$cpzone]['vouchersyncport']; $syncpass = $config['voucher'][$cpzone]['vouchersyncpass']; @@ -241,7 +250,7 @@ function voucher_expire($voucher_received) { } // split into an array. Useful for multiple vouchers given - $a_vouchers_received = preg_split("/[\t\n\r ]+/s", $voucher_received); + $a_vouchers_received = preg_split("/[\t\n\r ]+/s", $voucher_received); $active_dirty = false; $unsetindexes = array(); @@ -249,31 +258,35 @@ function voucher_expire($voucher_received) { // Roll# and Ticket# using the external readvoucher binary foreach ($a_vouchers_received as $voucher) { $v = escapeshellarg($voucher); - if (strlen($voucher) < 3) + if (strlen($voucher) < 3) { continue; // seems too short to be a voucher! + } unset($output); $_gb = exec("/usr/local/bin/voucher -c {$g['varetc_path']}/voucher_{$cpzone}.cfg -k {$g['varetc_path']}/voucher_{$cpzone}.public -- $v", $output); list($status, $roll, $nr) = explode(" ", $output[0]); if ($status == "OK") { - // check if we have this ticket on a registered roll for this ticket + // check if we have this ticket on a registered roll for this ticket if ($tickets_per_roll[$roll] && ($nr <= $tickets_per_roll[$roll])) { - // voucher is from a registered roll. - if (!isset($active_vouchers[$roll])) + // voucher is from a registered roll. + if (!isset($active_vouchers[$roll])) { $active_vouchers[$roll] = voucher_read_active_db($roll); + } // valid voucher. Store roll# and ticket# if (!empty($active_vouchers[$roll][$voucher])) { $active_dirty = true; unset($active_vouchers[$roll][$voucher]); } // check if voucher already marked as used - if (!isset($bitstring[$roll])) + if (!isset($bitstring[$roll])) { $bitstring[$roll] = voucher_read_used_db($roll); + } $pos = $nr >> 3; // divide by 8 -> octet $mask = 1 << ($nr % 8); // mark bit for this voucher as used - if (!(ord($bitstring[$roll][$pos]) & $mask)) + if (!(ord($bitstring[$roll][$pos]) & $mask)) { $bitstring[$roll][$pos] = chr(ord($bitstring[$roll][$pos]) | $mask); + } captiveportal_syslog("{$voucher} ({$roll}/{$nr}) forced to expire"); /* Check if this voucher has any active sessions */ @@ -283,17 +296,20 @@ function voucher_expire($voucher_received) { captiveportal_logportalauth($cpentry[4],$cpentry[3],$cpentry[2],"FORCLY TERMINATING VOUCHER {$voucher} SESSION"); $unsetindexes[] = $cpentry[5]; } - } else + } else { captiveportal_syslog("$voucher ($roll/$nr): not found on any registered Roll"); - } else + } + } else { // hmm, thats weird ... not what I expected captiveportal_syslog("$voucher invalid: {$output[0]}!!"); + } } // Refresh active DBs if ($active_dirty == true) { - foreach ($active_vouchers as $roll => $active) + foreach ($active_vouchers as $roll => $active) { voucher_write_active_db($roll, $active); + } unset($active_vouchers); /* Trigger a sync of the vouchers on config */ @@ -303,9 +319,10 @@ function voucher_expire($voucher_received) { // Write back the used DB's if (is_array($bitstring)) { foreach ($bitstring as $roll => $used) { - if(is_array($used)) { - foreach($used as $u) + if (is_array($used)) { + foreach ($used as $u) { voucher_write_used_db($roll, base64_encode($u)); + } } else { voucher_write_used_db($roll, base64_encode($used)); } @@ -316,13 +333,14 @@ function voucher_expire($voucher_received) { unlock($voucherlck); /* Write database */ - if (!empty($unsetindexes)) + if (!empty($unsetindexes)) { captiveportal_remove_entries($unsetindexes); + } return true; } -/* +/* * Authenticate a voucher and return the remaining time credit in minutes * if $test is set, don't mark the voucher as used nor add it to the list * of active vouchers @@ -332,11 +350,12 @@ function voucher_expire($voucher_received) { function voucher_auth($voucher_received, $test = 0) { global $g, $config, $cpzone, $dbc; - if (!isset($config['voucher'][$cpzone]['enable'])) + if (!isset($config['voucher'][$cpzone]['enable'])) { return 0; + } // XMLRPC Call over to the master Voucher node - if(!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { + if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { $syncip = $config['voucher'][$cpzone]['vouchersyncdbip']; $syncport = $config['voucher'][$cpzone]['vouchersyncport']; $syncpass = $config['voucher'][$cpzone]['vouchersyncpass']; @@ -357,7 +376,7 @@ function voucher_auth($voucher_received, $test = 0) { } // split into an array. Useful for multiple vouchers given - $a_vouchers_received = preg_split("/[\t\n\r ]+/s", $voucher_received); + $a_vouchers_received = preg_split("/[\t\n\r ]+/s", $voucher_received); $error = 0; $test_result = array(); // used to display for voucher test option in GUI $total_minutes = 0; @@ -368,8 +387,9 @@ function voucher_auth($voucher_received, $test = 0) { // Roll# and Ticket# using the external readvoucher binary foreach ($a_vouchers_received as $voucher) { $v = escapeshellarg($voucher); - if (strlen($voucher) < 3) + if (strlen($voucher) < 3) { continue; // seems too short to be a voucher! + } $result = exec("/usr/local/bin/voucher -c {$g['varetc_path']}/voucher_{$cpzone}.cfg -k {$g['varetc_path']}/voucher_{$cpzone}.public -- $v"); list($status, $roll, $nr) = explode(" ", $result); @@ -379,11 +399,12 @@ function voucher_auth($voucher_received, $test = 0) { $first_voucher = $voucher; $first_voucher_roll = $roll; } - // check if we have this ticket on a registered roll for this ticket + // check if we have this ticket on a registered roll for this ticket if ($tickets_per_roll[$roll] && ($nr <= $tickets_per_roll[$roll])) { - // voucher is from a registered roll. - if (!isset($active_vouchers[$roll])) + // voucher is from a registered roll. + if (!isset($active_vouchers[$roll])) { $active_vouchers[$roll] = voucher_read_active_db($roll); + } // valid voucher. Store roll# and ticket# if (!empty($active_vouchers[$roll][$voucher])) { list($timestamp,$minutes) = explode(",", $active_vouchers[$roll][$voucher]); @@ -395,8 +416,9 @@ function voucher_auth($voucher_received, $test = 0) { // voucher not used. Check if ticket Id is on the roll (not too high) // and if the ticket is marked used. // check if voucher already marked as used - if (!isset($bitstring[$roll])) + if (!isset($bitstring[$roll])) { $bitstring[$roll] = voucher_read_used_db($roll); + } $pos = $nr >> 3; // divide by 8 -> octet $mask = 1 << ($nr % 8); if (ord($bitstring[$roll][$pos]) & $mask) { @@ -440,26 +462,29 @@ function voucher_auth($voucher_received, $test = 0) { // the user wouldn't know that he used at least one invalid voucher. if ($error) { unlock($voucherlck); - if ($total_minutes > 0) // probably not needed, but want to make sure + if ($total_minutes > 0) { // probably not needed, but want to make sure $total_minutes = 0; // we only report -1 (expired) or 0 (no access) + } return $total_minutes; // well, at least one voucher had errors. Say NO ACCESS } // If we did a XMLRPC sync earlier check the timeleft if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) { - if (!is_null($remote_time_used)) + if (!is_null($remote_time_used)) { $total_minutes = $remote_time_used; - else if ($remote_time_used < $total_minutes) + } else if ($remote_time_used < $total_minutes) { $total_minutes -= $remote_time_used; + } } // All given vouchers were valid and this isn't simply a test. // Write back the used DB's if (is_array($bitstring)) { foreach ($bitstring as $roll => $used) { - if(is_array($used)) { - foreach($used as $u) + if (is_array($used)) { + foreach ($used as $u) { voucher_write_used_db($roll, base64_encode($u)); + } } else { voucher_write_used_db($roll, base64_encode($used)); } @@ -493,15 +518,17 @@ function voucher_configure($sync = false) { if (is_array($config['voucher'])) { foreach ($config['voucher'] as $voucherzone => $vcfg) { - if (platform_booting()) - echo gettext("Enabling voucher support... "); + if (platform_booting()) { + echo gettext("Enabling voucher support... "); + } $cpzone = $voucherzone; $error = voucher_configure_zone($sync); if (platform_booting()) { - if ($error) + if ($error) { echo "error\n"; - else + } else { echo "done\n"; + } } } } @@ -510,70 +537,72 @@ function voucher_configure($sync = false) { function voucher_configure_zone($sync = false) { global $config, $g, $cpzone; - if (!isset($config['voucher'][$cpzone]['enable'])) + if (!isset($config['voucher'][$cpzone]['enable'])) { return 0; + } - if ($sync == true) - captiveportal_syslog("Writing voucher db from sync data..."); + if ($sync == true) { + captiveportal_syslog("Writing voucher db from sync data..."); + } $voucherlck = lock("voucher{$cpzone}", LOCK_EX); - /* write public key used to verify vouchers */ - $pubkey = base64_decode($config['voucher'][$cpzone]['publickey']); - $fd = fopen("{$g['varetc_path']}/voucher_{$cpzone}.public", "w"); - if (!$fd) { - captiveportal_syslog("Voucher error: cannot write voucher.public\n"); - unlock($voucherlck); - return 1; - } - fwrite($fd, $pubkey); - fclose($fd); - @chmod("{$g['varetc_path']}/voucher_{$cpzone}.public", 0600); + /* write public key used to verify vouchers */ + $pubkey = base64_decode($config['voucher'][$cpzone]['publickey']); + $fd = fopen("{$g['varetc_path']}/voucher_{$cpzone}.public", "w"); + if (!$fd) { + captiveportal_syslog("Voucher error: cannot write voucher.public\n"); + unlock($voucherlck); + return 1; + } + fwrite($fd, $pubkey); + fclose($fd); + @chmod("{$g['varetc_path']}/voucher_{$cpzone}.public", 0600); - /* write config file used by voucher binary to decode vouchers */ - $fd = fopen("{$g['varetc_path']}/voucher_{$cpzone}.cfg", "w"); - if (!$fd) { - printf(gettext("Error: cannot write voucher.cfg") . "\n"); - unlock($voucherlck); - return 1; - } - fwrite($fd, "{$config['voucher'][$cpzone]['rollbits']},{$config['voucher'][$cpzone]['ticketbits']},{$config['voucher'][$cpzone]['checksumbits']},{$config['voucher'][$cpzone]['magic']},{$config['voucher'][$cpzone]['charset']}\n"); - fclose($fd); - @chmod("{$g['varetc_path']}/voucher_{$cpzone}.cfg", 0600); + /* write config file used by voucher binary to decode vouchers */ + $fd = fopen("{$g['varetc_path']}/voucher_{$cpzone}.cfg", "w"); + if (!$fd) { + printf(gettext("Error: cannot write voucher.cfg") . "\n"); + unlock($voucherlck); + return 1; + } + fwrite($fd, "{$config['voucher'][$cpzone]['rollbits']},{$config['voucher'][$cpzone]['ticketbits']},{$config['voucher'][$cpzone]['checksumbits']},{$config['voucher'][$cpzone]['magic']},{$config['voucher'][$cpzone]['charset']}\n"); + fclose($fd); + @chmod("{$g['varetc_path']}/voucher_{$cpzone}.cfg", 0600); unlock($voucherlck); - if ((platform_booting() || $sync == true) && is_array($config['voucher'][$cpzone]['roll'])) { + if ((platform_booting() || $sync == true) && is_array($config['voucher'][$cpzone]['roll'])) { $voucherlck = lock("voucher{$cpzone}", LOCK_EX); - // create active and used DB per roll on ramdisk from config - foreach ($config['voucher'][$cpzone]['roll'] as $rollent) { + // create active and used DB per roll on ramdisk from config + foreach ($config['voucher'][$cpzone]['roll'] as $rollent) { - $roll = $rollent['number']; - voucher_write_used_db($roll, $rollent['used']); - $minutes = $rollent['minutes']; - $active_vouchers = array(); - $a_active = &$rollent['active']; - if (is_array($a_active)) { - foreach ($a_active as $activent) { - $voucher = $activent['voucher']; - $timestamp = $activent['timestamp']; - $minutes = $activent['minutes']; - // its tempting to check for expired timestamps, but during - // bootup, we most likely don't have the correct time. - $active_vouchers[$voucher] = "$timestamp,$minutes"; - } - } - voucher_write_active_db($roll, $active_vouchers); - } + $roll = $rollent['number']; + voucher_write_used_db($roll, $rollent['used']); + $minutes = $rollent['minutes']; + $active_vouchers = array(); + $a_active = &$rollent['active']; + if (is_array($a_active)) { + foreach ($a_active as $activent) { + $voucher = $activent['voucher']; + $timestamp = $activent['timestamp']; + $minutes = $activent['minutes']; + // its tempting to check for expired timestamps, but during + // bootup, we most likely don't have the correct time. + $active_vouchers[$voucher] = "$timestamp,$minutes"; + } + } + voucher_write_active_db($roll, $active_vouchers); + } unlock($voucherlck); - } + } return 0; } -/* write bitstring of used vouchers to ramdisk. +/* write bitstring of used vouchers to ramdisk. * Bitstring must already be base64_encoded! */ function voucher_write_used_db($roll, $vdb) { @@ -583,12 +612,13 @@ function voucher_write_used_db($roll, $vdb) { if ($fd) { fwrite($fd, $vdb . "\n"); fclose($fd); - } else + } else { voucher_log(LOG_ERR, sprintf(gettext('cant write %1$s/voucher_%s_used_%2$s.db'), $g['vardb_path'], $cpzone, $roll)); + } } /* return assoc array of active vouchers with activation timestamp - * voucher is index. + * voucher is index. */ function voucher_read_active_db($roll) { global $g, $cpzone; @@ -603,10 +633,11 @@ function voucher_read_active_db($roll) { $line = trim(fgets($fd)); if ($line) { list($voucher,$timestamp,$minutes) = explode(",", $line); // voucher,timestamp - if ((($timestamp + (60*$minutes)) - time()) > 0) + if ((($timestamp + (60*$minutes)) - time()) > 0) { $active[$voucher] = "$timestamp,$minutes"; - else + } else { $dirty=1; + } } } fclose($fd); @@ -623,74 +654,77 @@ function voucher_read_active_db($roll) { /* store array of active vouchers back to DB */ function voucher_write_active_db($roll, $active) { - global $g, $cpzone; + global $g, $cpzone; - if (!is_array($active)) + if (!is_array($active)) { return; - $fd = fopen("{$g['vardb_path']}/voucher_{$cpzone}_active_$roll.db", "w"); - if ($fd) { - foreach($active as $voucher => $value) - fwrite($fd, "$voucher,$value\n"); - fclose($fd); - } + } + $fd = fopen("{$g['vardb_path']}/voucher_{$cpzone}_active_$roll.db", "w"); + if ($fd) { + foreach ($active as $voucher => $value) { + fwrite($fd, "$voucher,$value\n"); + } + fclose($fd); + } } /* return how many vouchers are marked used on a roll */ function voucher_used_count($roll) { - global $g, $cpzone; + global $g, $cpzone; - $bitstring = voucher_read_used_db($roll); - $max = strlen($bitstring) * 8; - $used = 0; - for ($i = 1; $i <= $max; $i++) { - // check if ticket already used or not. - $pos = $i >> 3; // divide by 8 -> octet - $mask = 1 << ($i % 8); // mask to test bit in octet - if (ord($bitstring[$pos]) & $mask) - $used++; - } - unset($bitstring); + $bitstring = voucher_read_used_db($roll); + $max = strlen($bitstring) * 8; + $used = 0; + for ($i = 1; $i <= $max; $i++) { + // check if ticket already used or not. + $pos = $i >> 3; // divide by 8 -> octet + $mask = 1 << ($i % 8); // mask to test bit in octet + if (ord($bitstring[$pos]) & $mask) { + $used++; + } + } + unset($bitstring); - return $used; + return $used; } function voucher_read_used_db($roll) { - global $g, $cpzone; + global $g, $cpzone; - $vdb = ""; - $file = "{$g['vardb_path']}/voucher_{$cpzone}_used_$roll.db"; - if (file_exists($file)) { - $fd = fopen($file, "r"); - if ($fd) { - $vdb = trim(fgets($fd)); - fclose($fd); - } else { - voucher_log(LOG_ERR, sprintf(gettext('cant read %1$s/voucher_%s_used_%2$s.db'), $g['vardb_path'], $cpzone, $roll)); - } - } - return base64_decode($vdb); + $vdb = ""; + $file = "{$g['vardb_path']}/voucher_{$cpzone}_used_$roll.db"; + if (file_exists($file)) { + $fd = fopen($file, "r"); + if ($fd) { + $vdb = trim(fgets($fd)); + fclose($fd); + } else { + voucher_log(LOG_ERR, sprintf(gettext('cant read %1$s/voucher_%s_used_%2$s.db'), $g['vardb_path'], $cpzone, $roll)); + } + } + return base64_decode($vdb); } function voucher_unlink_db($roll) { - global $g, $cpzone; - @unlink("{$g['vardb_path']}/voucher_{$cpzone}_used_$roll.db"); - @unlink("{$g['vardb_path']}/voucher_{$cpzone}_active_$roll.db"); + global $g, $cpzone; + @unlink("{$g['vardb_path']}/voucher_{$cpzone}_used_$roll.db"); + @unlink("{$g['vardb_path']}/voucher_{$cpzone}_active_$roll.db"); } /* we share the log with captiveportal for now */ function voucher_log($priority, $message) { - $message = trim($message); - openlog("logportalauth", LOG_PID, LOG_LOCAL4); - syslog($priority, sprintf(gettext("Voucher: %s"),$message)); - closelog(); + $message = trim($message); + openlog("logportalauth", LOG_PID, LOG_LOCAL4); + syslog($priority, sprintf(gettext("Voucher: %s"),$message)); + closelog(); } /* Save active and used voucher DB into XML config and write it to flash * Called during reboot -> system_reboot_cleanup() and every active voucher change */ function voucher_save_db_to_config() { - global $config, $g, $cpzone; + global $config, $g, $cpzone; if (is_array($config['voucher'])) { foreach ($config['voucher'] as $voucherzone => $vcfg) { @@ -701,42 +735,44 @@ function voucher_save_db_to_config() { } function voucher_save_db_to_config_zone() { - global $config, $g, $cpzone; - - if (!isset($config['voucher'][$cpzone]['enable'])) - return; // no vouchers or don't want to save DB's + global $config, $g, $cpzone; - if (!is_array($config['voucher'][$cpzone]['roll'])) - return; + if (!isset($config['voucher'][$cpzone]['enable'])) { + return; // no vouchers or don't want to save DB's + } - $voucherlck = lock("voucher{$cpzone}", LOCK_EX); + if (!is_array($config['voucher'][$cpzone]['roll'])) { + return; + } - // walk all active rolls and save runtime DB's to flash - $a_roll = &$config['voucher'][$cpzone]['roll']; - while (list($key, $value) = each($a_roll)) { - $rollent = &$a_roll[$key]; - $roll = $rollent['number']; - $bitmask = voucher_read_used_db($roll); - $rollent['used'] = base64_encode($bitmask); - $active_vouchers = voucher_read_active_db($roll); - $db = array(); + $voucherlck = lock("voucher{$cpzone}", LOCK_EX); + + // walk all active rolls and save runtime DB's to flash + $a_roll = &$config['voucher'][$cpzone]['roll']; + while (list($key, $value) = each($a_roll)) { + $rollent = &$a_roll[$key]; + $roll = $rollent['number']; + $bitmask = voucher_read_used_db($roll); + $rollent['used'] = base64_encode($bitmask); + $active_vouchers = voucher_read_active_db($roll); + $db = array(); $dbi = 1; - foreach($active_vouchers as $voucher => $line) { - list($timestamp,$minutes) = explode(",", $line); - $activent['voucher'] = $voucher; - $activent['timestamp'] = $timestamp; - $activent['minutes'] = $minutes; - $db["v{$dbi}"] = $activent; - $dbi++; - } - $rollent['active'] = $db; - unset($active_vouchers); - } + foreach ($active_vouchers as $voucher => $line) { + list($timestamp,$minutes) = explode(",", $line); + $activent['voucher'] = $voucher; + $activent['timestamp'] = $timestamp; + $activent['minutes'] = $minutes; + $db["v{$dbi}"] = $activent; + $dbi++; + } + $rollent['active'] = $db; + unset($active_vouchers); + } - unlock($voucherlck); + unlock($voucherlck); - write_config("Syncing vouchers"); - return; + write_config("Syncing vouchers"); + return; } ?> diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index c271224101..a148d0e116 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -48,15 +48,17 @@ function vpn_ipsec_configure_loglevels($forconfig = false) $cfgtext = array(); foreach ($ipsec_loglevels as $lkey => $ldescr) { - if (!isset($config['ipsec']["ipsec_{$lkey}"]) && !$forconfig) + if (!isset($config['ipsec']["ipsec_{$lkey}"]) && !$forconfig) { mwexec("/usr/local/sbin/ipsec stroke loglevel {$lkey} -- -1", false); - else if (is_numeric($config['ipsec']["ipsec_{$lkey}"]) && - intval($config['ipsec']["ipsec_{$lkey}"]) >= 0 && intval($config['ipsec']["ipsec_{$lkey}"]) <= 5) + } else if (is_numeric($config['ipsec']["ipsec_{$lkey}"]) && + intval($config['ipsec']["ipsec_{$lkey}"]) >= 0 && intval($config['ipsec']["ipsec_{$lkey}"]) <= 5) { $forconfig ? $cfgtext[] = "${lkey} " . (intval($config['ipsec']["ipsec_{$lkey}"]) - 1) : mwexec("/usr/local/sbin/ipsec stroke loglevel {$lkey} " . (intval($config['ipsec']["ipsec_{$lkey}"]) - 1) , false); + } } - if ($forconfig) + if ($forconfig) { return implode(',', $cfgtext); + } } /* include all configuration functions */ @@ -65,30 +67,30 @@ function vpn_ipsec_convert_to_modp($index) $convertion = ""; switch ($index) { - case '1': - $convertion = "modp768"; - break; - case '2': - $convertion = "modp1024"; - break; - case '5': - $convertion = "modp1536"; - break; - case '14': - $convertion = "modp2048"; - break; - case '15': - $convertion = "modp3072"; - break; - case '16': - $convertion = "modp4096"; - break; - case '17': - $convertion = "modp6144"; - break; - case '18': - $convertion = "modp8192"; - break; + case '1': + $convertion = "modp768"; + break; + case '2': + $convertion = "modp1024"; + break; + case '5': + $convertion = "modp1536"; + break; + case '14': + $convertion = "modp2048"; + break; + case '15': + $convertion = "modp3072"; + break; + case '16': + $convertion = "modp4096"; + break; + case '17': + $convertion = "modp6144"; + break; + case '18': + $convertion = "modp8192"; + break; } return $convertion; @@ -98,8 +100,9 @@ function vpn_ipsec_configure($restart = false) { global $config, $g, $sa, $sn, $p1_ealgos, $p2_ealgos; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; + } /* get the automatic ping_hosts.sh ready */ unlink_if_exists("{$g['vardb_path']}/ipsecpinghosts"); @@ -136,30 +139,41 @@ function vpn_ipsec_configure($restart = false) mwexec("/sbin/ifconfig enc0 up"); set_single_sysctl("net.inet.ip.ipsec_in_use", "1"); /* needed for config files */ - if (!is_dir("{$g['varetc_path']}/ipsec")) + if (!is_dir("{$g['varetc_path']}/ipsec")) { mkdir("{$g['varetc_path']}/ipsec"); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d"); - if (!is_dir($capath)) + } + if (!is_dir($capath)) { mkdir($capath); - if (!is_dir($keypath)) + } + if (!is_dir($keypath)) { mkdir($keypath); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/crls")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/crls")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d/crls"); - if (!is_dir($certpath)) + } + if (!is_dir($certpath)) { mkdir($certpath); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/aacerts")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/aacerts")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d/aacerts"); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/acerts")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/acerts")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d/acerts"); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/ocspcerts")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/ocspcerts")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d/ocspcerts"); - if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/reqs")) + } + if (!is_dir("{$g['varetc_path']}/ipsec/ipsec.d/reqs")) { mkdir("{$g['varetc_path']}/ipsec/ipsec.d/reqs"); - + } - if (platform_booting()) + + if (platform_booting()) { echo gettext("Configuring IPsec VPN... "); + } /* fastforwarding is not compatible with ipsec tunnels */ set_single_sysctl("net.inet.ip.fastforwarding", "0"); @@ -177,51 +191,59 @@ function vpn_ipsec_configure($restart = false) $ipsecpinghosts = ""; /* step through each phase1 entry */ foreach ($a_phase1 as $ph1ent) { - if (isset($ph1ent['disabled'])) + if (isset($ph1ent['disabled'])) { continue; + } if (strpos($ph1ent['interface'], '_vip')) { $vpninterface = explode('_vip', $ph1ent['interface']); $ifacesuse[] = get_real_interface($vpninterface[0]); - } else { - $vpninterface = get_failover_interface($ph1ent['interface']); + } else { + $vpninterface = get_failover_interface($ph1ent['interface']); if (strpos($vpninterface, '_vip')) { $vpninterface = explode('_vip', $vpninterface); $ifacesuse[] = get_real_interface($vpninterface[0]); - } elseif (!empty($vpninterface)) + } elseif (!empty($vpninterface)) { $ifacesuse[] = $vpninterface; + } } - - if ($ph1ent['mode'] == "aggressive" && ($ph1ent['authentication_method'] == "pre_shared_key" || $ph1ent['authentication_method'] == "xauth_psk_server")) + + if ($ph1ent['mode'] == "aggressive" && ($ph1ent['authentication_method'] == "pre_shared_key" || $ph1ent['authentication_method'] == "xauth_psk_server")) { $aggressive_mode_psk = true; + } $ikeid = $ph1ent['ikeid']; $listeniflist = get_real_interface($a_phase1['interface']); $ep = ipsec_get_phase1_src($ph1ent); - if (!is_ipaddr($ep)) + if (!is_ipaddr($ep)) { continue; + } - if(!in_array($ep,$ipmap)) + if (!in_array($ep,$ipmap)) { $ipmap[] = $ep; + } /* see if this tunnel has a hostname for the remote-gateway. If so, try to resolve it now and add it to the list for filterdns */ - if (isset ($ph1ent['mobile'])) + if (isset ($ph1ent['mobile'])) { continue; + } $rg = $ph1ent['remote-gateway']; if (!is_ipaddr($rg)) { $filterdns_list[] = "{$rg}"; add_hostname_to_watch($rg); - if (!platform_booting()) + if (!platform_booting()) { $rg = resolve_retry($rg); - if (!is_ipaddr($rg)) + } + if (!is_ipaddr($rg)) { continue; + } } - if(array_search($rg, $rgmap)) { + if (array_search($rg, $rgmap)) { log_error("The remote gateway {$rg} already exists on another phase 1 entry"); continue; } @@ -230,23 +252,27 @@ function vpn_ipsec_configure($restart = false) if (is_array($a_phase2)) { /* step through each phase2 entry */ foreach ($a_phase2 as $ph2ent) { - if (isset($ph2ent['disabled'])) + if (isset($ph2ent['disabled'])) { continue; + } - if ($ikeid != $ph2ent['ikeid']) + if ($ikeid != $ph2ent['ikeid']) { continue; + } /* add an ipsec pinghosts entry */ if ($ph2ent['pinghost']) { - if (!is_array($iflist)) + if (!is_array($iflist)) { $iflist = get_configured_interface_list(); + } $srcip = null; $local_subnet = ipsec_idinfo_to_cidr($ph2ent['localid'], true, $ph2ent['mode']); - if(is_ipaddrv6($ph2ent['pinghost'])) { + if (is_ipaddrv6($ph2ent['pinghost'])) { foreach ($iflist as $ifent => $ifname) { $interface_ip = get_interface_ipv6($ifent); - if(!is_ipaddrv6($interface_ip)) + if (!is_ipaddrv6($interface_ip)) { continue; + } if (ip_in_subnet($interface_ip, $local_subnet)) { $srcip = $interface_ip; break; @@ -255,8 +281,9 @@ function vpn_ipsec_configure($restart = false) } else { foreach ($iflist as $ifent => $ifname) { $interface_ip = get_interface_ip($ifent); - if(!is_ipaddrv4($interface_ip)) + if (!is_ipaddrv4($interface_ip)) { continue; + } if ($local_subnet == "0.0.0.0/0" || ip_in_subnet($interface_ip, $local_subnet)) { $srcip = $interface_ip; break; @@ -274,13 +301,14 @@ function vpn_ipsec_configure($restart = false) } } $dstip = $ph2ent['pinghost']; - if(is_ipaddrv6($dstip)) { + if (is_ipaddrv6($dstip)) { $family = "inet6"; } else { $family = "inet"; } - if (is_ipaddr($srcip)) + if (is_ipaddr($srcip)) { $ipsecpinghosts[] = "{$srcip}|{$dstip}|3|||||{$family}|\n"; + } } } } @@ -291,35 +319,40 @@ function vpn_ipsec_configure($restart = false) unset($iflist); $accept_unencrypted = ""; - if (isset($config['ipsec']['acceptunencryptedmainmode'])) + if (isset($config['ipsec']['acceptunencryptedmainmode'])) { $accept_unencrypted = "accept_unencrypted_mainmode_messages = yes"; + } $stronconf = ''; - if (file_exists("{$g['varetc_path']}/ipsec/strongswan.conf")) + if (file_exists("{$g['varetc_path']}/ipsec/strongswan.conf")) { $stronconf = file_get_contents("{$g['varetc_path']}/ipsec/strongswan.conf"); + } $i_dont_care_about_security_and_use_aggressive_mode_psk = ""; if ($aggressive_mode_psk) { log_error("WARNING: Setting i_dont_care_about_security_and_use_aggressive_mode_psk option because a phase 1 is configured using aggressive mode with pre-shared keys. This is not a secure configuration."); - if (!empty($stronconf) && strpos($stronconf, 'i_dont_care_about_security_and_use_aggressive_mode_psk') === FALSE) + if (!empty($stronconf) && strpos($stronconf, 'i_dont_care_about_security_and_use_aggressive_mode_psk') === FALSE) { $restart = true; + } $i_dont_care_about_security_and_use_aggressive_mode_psk = "i_dont_care_about_security_and_use_aggressive_mode_psk=yes"; - } + } $unity_enabled = 'yes'; - if (isset($config['ipsec']['unityplugin'])) + if (isset($config['ipsec']['unityplugin'])) { $unity_enabled = 'no'; + } - if (!empty($ifacesuse)) + if (!empty($ifacesuse)) { $ifacesuse = 'interfaces_use = ' . implode(',', array_unique($ifacesuse)); - else + } else { $ifacesuse = ''; + } unset($stronconf); $strongswan = << 0) + if ($firstsed > 0) { $strongswan .= ","; - if ($authcfg == "system") + } + if ($authcfg == "system") { $authcfg = "Local Database"; + } $strongswan .= $authcfg; $firstsed = 1; } @@ -477,8 +527,9 @@ EOD; if (is_array($a_phase1) && count($a_phase1)) { foreach ($a_phase1 as $ph1ent) { - if (isset($ph1ent['disabled'])) + if (isset($ph1ent['disabled'])) { continue; + } if (strstr($ph1ent['authentication_method'], 'rsa') || in_array($ph1ent['authentication_method'], array('eap-mschapv2', 'eap-tls'))) { @@ -515,16 +566,18 @@ EOD; list ($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local'); list ($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap); - if (empty($peerid_data)) + if (empty($peerid_data)) { continue; + } $myid = isset($ph1ent['mobile']) ? trim($myid_data) : "%any"; $peerid = ($peerid_data != 'allusers') ? trim($peerid_data) : ''; if (!empty($ph1ent['pre-shared-key'])) { - if ($myid_type == 'fqdn' && !empty($myid_data)) + if ($myid_type == 'fqdn' && !empty($myid_data)) { $pskconf .= "@{$myid} {$peerid} : PSK 0s" . base64_encode(trim($ph1ent['pre-shared-key'])) . "\n"; - else + } else { $pskconf .= "{$myid} {$peerid} : PSK 0s" . base64_encode(trim($ph1ent['pre-shared-key'])) . "\n"; + } } } } @@ -543,10 +596,12 @@ EOD; /* add PSKs for mobile clients */ if (is_array($ipseccfg['mobilekey'])) { foreach ($ipseccfg['mobilekey'] as $key) { - if ($key['ident'] == "allusers") + if ($key['ident'] == "allusers") { $key['ident'] = '%any'; - if (empty($key['type'])) + } + if (empty($key['type'])) { $key['type'] = 'PSK'; + } $pskconf .= "%any {$key['ident']} : {$key['type']} 0s" . base64_encode($key['pre-shared-key']) . "\n"; } unset($key); @@ -558,8 +613,9 @@ EOD; $uniqueids = 'yes'; if (!empty($config['ipsec']['uniqueids'])) { - if (in_array($uniqueids, $ipsec_idhandling)) + if (in_array($uniqueids, $ipsec_idhandling)) { $uniqueids = $config['ipsec']['uniqueids']; + } } $natfilterrules = false; /* begin ipsec.conf */ @@ -572,17 +628,20 @@ EOD; $ipsecconf .= "\tcharondebug=\"" . vpn_ipsec_configure_loglevels(true) . "\"\n"; foreach ($a_phase1 as $ph1ent) { - if (isset($ph1ent['disabled'])) + if (isset($ph1ent['disabled'])) { continue; + } - if ($ph1ent['mode'] == "aggressive") + if ($ph1ent['mode'] == "aggressive") { $aggressive = "yes"; - else + } else { $aggressive = "no"; + } $ep = ipsec_get_phase1_src($ph1ent); - if (!$ep) + if (!$ep) { continue; + } $ikeid = $ph1ent['ikeid']; $keyexchange = "ikev1"; @@ -591,22 +650,25 @@ EOD; if ($ph1ent['iketype'] == "ikev2") { $keyexchange = "ikev2"; //$passive = "start"; - } else if ($ph1ent['iketype'] == "auto") + } else if ($ph1ent['iketype'] == "auto") { $keyexchange = "ike"; + } } if (isset($ph1ent['mobile'])) { $right_spec = "%any"; $passive = 'add'; } else { - if (isset($ph1ent['responderonly'])) + if (isset($ph1ent['responderonly'])) { $passive = 'add'; + } $right_spec = $ph1ent['remote-gateway']; - if (is_ipaddr($right_spec)) + if (is_ipaddr($right_spec)) { $sourcehost = $right_spec; - else + } else { $sourcehost = $rgmap['remote-gateway']; + } if ($ph1ent['protocol'] == 'inet') { if (strpos($ph1ent['interface'], '_vip')) { @@ -623,7 +685,7 @@ EOD; $vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse); } } - + if (!empty($ifacesuse) && interface_has_gateway($vpninterface)) { $gatewayip = get_interface_gateway($vpninterface); $interfaceip = get_interface_ip($vpninterface); @@ -652,7 +714,7 @@ EOD; $vpninterface = convert_real_interface_to_friendly_interface_name($ifacesuse); } } - + if (!empty($ifacesuse) && interface_has_gateway($vpninterface)) { $gatewayip = get_interface_gateway_v6($vpninterface); $interfaceip = get_interface_ipv6($vpninterface); @@ -670,124 +732,142 @@ EOD; } list ($myid_type, $myid_data) = ipsec_find_id($ph1ent, 'local'); - if ($myid_type != 'address') + if ($myid_type != 'address') { $myid_data = "{$myid_type}:{$myid_data}"; + } /* Only specify peer ID if we are not dealing with a mobile PSK-only tunnel */ $peerid_spec = ''; if (!isset($ph1ent['mobile'])) { list ($peerid_type, $peerid_data) = ipsec_find_id($ph1ent, 'peer', $rgmap); - if ($peerid_type != 'address') + if ($peerid_type != 'address') { $peerid_spec = "{$peerid_type}:{$peerid_data}"; - else + } else { $peerid_spec = $peerid_data; + } } if (is_array($ph1ent['encryption-algorithm']) && !empty($ph1ent['encryption-algorithm']['name']) && !empty($ph1ent['hash-algorithm'])) { $ealgosp1 = ''; $ealg_id = $ph1ent['encryption-algorithm']['name']; $ealg_kl = $ph1ent['encryption-algorithm']['keylen']; - if ($ealg_kl) + if ($ealg_kl) { $ealgosp1 = "ike = {$ealg_id}{$ealg_kl}-{$ph1ent['hash-algorithm']}"; - else + } else { $ealgosp1 = "ike = {$ealg_id}-{$ph1ent['hash-algorithm']}"; + } $modp = vpn_ipsec_convert_to_modp($ph1ent['dhgroup']); - if (!empty($modp)) + if (!empty($modp)) { $ealgosp1 .= "-{$modp}"; + } $ealgosp1 .= "!"; } if ($ph1ent['dpd_delay'] && $ph1ent['dpd_maxfail']) { - if ($passive == "route") + if ($passive == "route") { $dpdline = "dpdaction = restart"; - else + } else { $dpdline = "dpdaction = clear"; + } $dpdline .= "\n\tdpddelay = {$ph1ent['dpd_delay']}s"; $dpdtimeout = $ph1ent['dpd_delay'] * ($ph1ent['dpd_maxfail'] + 1); $dpdline .= "\n\tdpdtimeout = {$dpdtimeout}s"; - } else + } else { $dpdline = "dpdaction = none"; + } $ikelifeline = ''; - if ($ph1ent['lifetime']) + if ($ph1ent['lifetime']) { $ikelifeline = "ikelifetime = {$ph1ent['lifetime']}s"; + } $rightsourceip = NULL; - if (isset($ph1ent['mobile']) && !empty($a_client['pool_address'])) + if (isset($ph1ent['mobile']) && !empty($a_client['pool_address'])) { $rightsourceip = "\trightsourceip = {$a_client['pool_address']}/{$a_client['pool_netbits']}\n"; + } $authentication = ""; switch ($ph1ent['authentication_method']) { - case 'eap-mschapv2': - if (isset($ph1ent['mobile'])) { - $authentication = "eap_identity=%any\n\t"; - $authentication .= "leftauth=pubkey\n\trightauth=eap-mschapv2"; - if (!empty($ph1ent['certref'])) + case 'eap-mschapv2': + if (isset($ph1ent['mobile'])) { + $authentication = "eap_identity=%any\n\t"; + $authentication .= "leftauth=pubkey\n\trightauth=eap-mschapv2"; + if (!empty($ph1ent['certref'])) { + $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; + } + } + break; + case 'eap-tls': + if (isset($ph1ent['mobile'])) { + $authentication = "eap_identity=%identity\n\t"; + $authentication .= "leftauth=pubkey\n\trightauth=eap-tls"; + if (!empty($ph1ent['certref'])) { + $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; + } + } else { + $authentication = "leftauth=eap-tls\n\trightauth=eap-tls"; + if (!empty($ph1ent['certref'])) { + $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; + } + } + break; + case 'xauth_rsa_server': + $authentication = "leftauth = pubkey\n\trightauth = pubkey"; + $authentication .= "\n\trightauth2 = xauth-generic"; + if (!empty($ph1ent['certref'])) { $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - } - break; - case 'eap-tls': - if (isset($ph1ent['mobile'])) { - $authentication = "eap_identity=%identity\n\t"; - $authentication .= "leftauth=pubkey\n\trightauth=eap-tls"; - if (!empty($ph1ent['certref'])) + } + break; + case 'xauth_psk_server': + $authentication = "leftauth = psk\n\trightauth = psk"; + $authentication .= "\n\trightauth2 = xauth-generic"; + break; + case 'pre_shared_key': + $authentication = "leftauth = psk\n\trightauth = psk"; + break; + case 'rsasig': + $authentication = "leftauth = pubkey\n\trightauth = pubkey"; + if (!empty($ph1ent['certref'])) { $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - } else { - $authentication = "leftauth=eap-tls\n\trightauth=eap-tls"; - if (!empty($ph1ent['certref'])) + } + break; + case 'hybrid_rsa_server': + $authentication = "leftauth = xauth-generic\n\trightauth = pubkey"; + $authentication .= "\n\trightauth2 = xauth"; + if (!empty($ph1ent['certref'])) { $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - } - break; - case 'xauth_rsa_server': - $authentication = "leftauth = pubkey\n\trightauth = pubkey"; - $authentication .= "\n\trightauth2 = xauth-generic"; - if (!empty($ph1ent['certref'])) - $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - break; - case 'xauth_psk_server': - $authentication = "leftauth = psk\n\trightauth = psk"; - $authentication .= "\n\trightauth2 = xauth-generic"; - break; - case 'pre_shared_key': - $authentication = "leftauth = psk\n\trightauth = psk"; - break; - case 'rsasig': - $authentication = "leftauth = pubkey\n\trightauth = pubkey"; - if (!empty($ph1ent['certref'])) - $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - break; - case 'hybrid_rsa_server': - $authentication = "leftauth = xauth-generic\n\trightauth = pubkey"; - $authentication .= "\n\trightauth2 = xauth"; - if (!empty($ph1ent['certref'])) - $authentication .= "\n\tleftcert={$certpath}/cert-{$ph1ent['ikeid']}.crt"; - break; + } + break; } $left_spec = $ep; - if (isset($ph1ent['reauth_enable'])) + if (isset($ph1ent['reauth_enable'])) { $reauth = "reauth = no"; - else + } else { $reauth = "reauth = yes"; - if (isset($ph1ent['rekey_enable'])) + } + if (isset($ph1ent['rekey_enable'])) { $rekey = "rekey = no"; - else + } else { $rekey = "rekey = yes"; + } - if ($ph1ent['nat_traversal'] == 'off') + if ($ph1ent['nat_traversal'] == 'off') { $forceencaps = 'forceencaps = no'; - else if ($ph1ent['nat_traversal'] == 'force') + } else if ($ph1ent['nat_traversal'] == 'force') { $forceencaps = 'forceencaps = yes'; - else + } else { $forceencaps = 'forceencaps = no'; - - if ($ph1ent['mobike'] == 'on') + } + + if ($ph1ent['mobike'] == 'on') { $mobike = 'mobike = yes'; - else + } else { $mobike = 'mobike = no'; + } $ipseclifetime = 0; $rightsubnet_spec = array(); @@ -797,14 +877,17 @@ EOD; $ealgoESPsp2arr = array(); if (is_array($a_phase2) && count($a_phase2)) { foreach ($a_phase2 as $ph2ent) { - if ($ikeid != $ph2ent['ikeid']) + if ($ikeid != $ph2ent['ikeid']) { continue; + } - if (isset($ph2ent['disabled'])) + if (isset($ph2ent['disabled'])) { continue; + } - if (isset($ph2ent['mobile']) && !isset($a_client['enable'])) + if (isset($ph2ent['mobile']) && !isset($a_client['enable'])) { continue; + } if (($ph2ent['mode'] == 'tunnel') or ($ph2ent['mode'] == 'tunnel6')) { $tunneltype = "type = tunnel"; @@ -813,8 +896,8 @@ EOD; $leftsubnet_data = ipsec_idinfo_to_cidr($ph2ent['localid'], false, $ph2ent['mode']); /* Do not print localid in some cases, such as a pure-psk or psk/xauth single phase2 mobile tunnel */ - if (($localid_type == "none" || $localid_type == "mobile") - && isset($ph1ent['mobile']) && (ipsec_get_number_of_phase2($ikeid)==1)) { + if (($localid_type == "none" || $localid_type == "mobile") && + isset($ph1ent['mobile']) && (ipsec_get_number_of_phase2($ikeid)==1)) { $left_spec = '%any'; } else { if ($localid_type != "address") { @@ -828,11 +911,13 @@ EOD; if (!empty($ph2ent['natlocalid'])) { $natleftsubnet_data = ipsec_idinfo_to_cidr($ph2ent['natlocalid'], false, $ph2ent['mode']); if ($ph2ent['natlocalid']['type'] != "address") { - if (is_subnet($natleftsubnet_data)) + if (is_subnet($natleftsubnet_data)) { $leftsubnet_data = "{$natleftsubnet_data}|{$leftsubnet_data}"; + } } else { - if (is_ipaddr($natleftsubnet_data)) + if (is_ipaddr($natleftsubnet_data)) { $leftsubnet_data = "{$natleftsubnet_data}|{$leftsubnet_data}"; + } } $natfilterrules = true; } @@ -862,8 +947,9 @@ EOD; } } - if (isset($a_client['pfs_group'])) + if (isset($a_client['pfs_group'])) { $ph2ent['pfsgroup'] = $a_client['pfs_group']; + } if ($ph2ent['protocol'] == 'esp') { if (is_array($ph2ent['encryption-algorithm-option'])) { @@ -872,8 +958,9 @@ EOD; $ealg_kl = $ealg['keylen']; if (!empty($ealg_kl) && $ealg_kl == "auto") { - if (empty($p2_ealgos) || !is_array($p2_ealgos)) + if (empty($p2_ealgos) || !is_array($p2_ealgos)) { require("ipsec.inc"); + } $key_hi = $p2_ealgos[$ealg_id]['keysel']['hi']; $key_lo = $p2_ealgos[$ealg_id]['keysel']['lo']; $key_step = $p2_ealgos[$ealg_id]['keysel']['step']; @@ -887,15 +974,17 @@ EOD; $halgo = str_replace('hmac_', '', $halgo); $tmpealgo = "{$ealg_id}{$keylen}-{$halgo}"; $modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']); - if (!empty($modp)) + if (!empty($modp)) { $tmpealgo .= "-{$modp}"; + } $ealgoESPsp2arr[] = $tmpealgo; } } else { $tmpealgo = "{$ealg_id}{$keylen}"; $modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']); - if (!empty($modp)) + if (!empty($modp)) { $tmpealgo .= "-{$modp}"; + } $ealgoESPsp2arr[] = $tmpealgo; } } @@ -906,15 +995,17 @@ EOD; $halgo = str_replace('hmac_', '', $halgo); $tmpealgo = "{$ealg_id}{$ealg_kl}-{$halgo}"; $modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']); - if (!empty($modp)) + if (!empty($modp)) { $tmpealgo .= "-{$modp}"; + } $ealgoESPsp2arr[] = $tmpealgo; } } else { $tmpealgo = "{$ealg_id}{$ealg_kl}"; $modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']); - if (!empty($modp)) + if (!empty($modp)) { $tmpealgo .= "-{$modp}"; + } $ealgoESPsp2arr[] = $tmpealgo; } } @@ -925,8 +1016,9 @@ EOD; $modp = vpn_ipsec_convert_to_modp($ph2ent['pfsgroup']); foreach ($ph2ent['hash-algorithm-option'] as $tmpAHalgo) { $tmpAHalgo = str_replace('hmac_', '', $tmpAHalgo); - if (!empty($modp)) + if (!empty($modp)) { $tmpAHalgo = "-{$modp}"; + } $ealgoAHsp2arr[] = $tmpAHalgo; } } @@ -935,8 +1027,9 @@ EOD; $reqids[] = $ph2ent['reqid']; if (!empty($ph2ent['lifetime'])) { - if ($ipseclifetime == 0 || intval($ipseclifetime) > intval($ph2ent['lifetime'])) + if ($ipseclifetime == 0 || intval($ipseclifetime) > intval($ph2ent['lifetime'])) { $ipseclifetime = intval($ph2ent['lifetime']); + } } } @@ -963,61 +1056,74 @@ EOD; $ipsecconnect .= "\tcompress = yes\n"; $enablecompression = true; } - if (!empty($ikelifeline)) + if (!empty($ikelifeline)) { $ipsecconnect .= "\t{$ikelifeline}\n"; - if ($ipseclifetime > 0) + } + if ($ipseclifetime > 0) { $ipsecconnect .= "\tlifetime = {$ipseclifetime}s\n"; - if (!empty($rightsourceip)) + } + if (!empty($rightsourceip)) { $ipsecconnect .= "{$rightsourceip}"; - if (!empty($ealgosp1)) + } + if (!empty($ealgosp1)) { $ipsecconnect .= "\t{$ealgosp1}\n"; - if (!empty($ealgoAHsp2arr)) + } + if (!empty($ealgoAHsp2arr)) { $ipsecconnect .= "\tah = " . join(',', $ealgoAHsp2arr) . "!\n"; - if (!empty($ealgoESPsp2arr)) + } + if (!empty($ealgoESPsp2arr)) { $ipsecconnect .= "\tesp = " . join(',', $ealgoESPsp2arr) . "!\n"; - if (!empty($authentication)) + } + if (!empty($authentication)) { $ipsecconnect .= "\t{$authentication}\n"; - if (!empty($peerid_spec)) + } + if (!empty($peerid_spec)) { $ipsecconnect .= "\trightid = {$peerid_spec}\n"; - if ($keyexchange == 'ikev1') + } + if ($keyexchange == 'ikev1') { $ipsecconnect .= "\taggressive = {$aggressive}\n"; + } if (!isset($ph1ent['mobile']) && $keyexchange == 'ikev1') { if (!empty($rightsubnet_spec)) { $ipsecfin = ''; foreach ($rightsubnet_spec as $idx => $rsubnet) { $ipsecfin .= "\nconn con{$ph1ent['ikeid']}00{$idx}\n"; - if (!empty($reqids[$idx])) + if (!empty($reqids[$idx])) { $ipsecfin .= "\treqid = " . $reqids[$idx] . "\n"; + } $ipsecfin .= $ipsecconnect; $ipsecfin .= "\trightsubnet = {$rsubnet}\n"; $ipsecfin .= "\tleftsubnet = " . $leftsubnet_spec[$idx] . "\n"; } - } else + } else { log_error("No phase2 specifications for tunnel with REQID = {$ikeid}"); + } } else { $ipsecfin = "\nconn con{$ph1ent['ikeid']}\n"; - if (!empty($reqids[$idx])) + if (!empty($reqids[$idx])) { $ipsecfin .= "\treqid = " . $reqids[0] . "\n"; + } $ipsecfin .= $ipsecconnect; if (!isset($ph1ent['mobile']) && !empty($rightsubnet_spec)) { $tempsubnets = array(); - foreach ($rightsubnet_spec as $rightsubnet) + foreach ($rightsubnet_spec as $rightsubnet) { $tempsubnets[$rightsubnet] = $rightsubnet; + } $ipsecfin .= "\trightsubnet = " . join(",", $tempsubnets) . "\n"; unset($tempsubnets, $rightsubnet); } if (!empty($leftsubnet_spec)) { $tempsubnets = array(); - foreach ($leftsubnet_spec as $leftsubnet) + foreach ($leftsubnet_spec as $leftsubnet) { $tempsubnets[$leftsubnet] = $leftsubnet; + } $ipsecfin .= "\tleftsubnet = " . join(",", $leftsubnet_spec) . "\n"; unset($tempsubnets, $leftsubnet); } } $ipsecconf .= $ipsecfin; unset($ipsecfin); - } } @@ -1025,14 +1131,15 @@ EOD; unset($ipsecconf); /* end ipsec.conf */ - if ($enablecompression === true) + if ($enablecompression === true) { set_single_sysctl('net.inet.ipcomp.ipcomp_enable', 1); - else + } else { set_single_sysctl('net.inet.ipcomp.ipcomp_enable', 0); + } - /* mange process */ + /* manage process */ if ($restart === true) { - mwexec("/usr/local/sbin/ipsec restart", false); + mwexec("/usr/local/sbin/ipsec restart", false); } else { if (isvalidpid("{$g['varrun_path']}/charon.pid")) { /* Read secrets */ @@ -1040,28 +1147,31 @@ EOD; /* Update configuration changes */ mwexec("/usr/local/sbin/ipsec update", false); } else { - mwexec("/usr/local/sbin/ipsec start", false); + mwexec("/usr/local/sbin/ipsec start", false); } } - if ($natfilterrules == true) + if ($natfilterrules == true) { filter_configure(); + } /* start filterdns, if necessary */ if (count($filterdns_list) > 0) { $interval = 60; - if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval'])) + if (!empty($ipseccfg['dns-interval']) && is_numeric($ipseccfg['dns-interval'])) { $interval = $ipseccfg['dns-interval']; + } $hostnames = ""; array_unique($filterdns_list); - foreach ($filterdns_list as $hostname) + foreach ($filterdns_list as $hostname) { $hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload ipsecdns\"'\n"; + } file_put_contents("{$g['varetc_path']}/ipsec/filterdns-ipsec.hosts", $hostnames); unset($hostnames); - if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) + if (isvalidpid("{$g['varrun_path']}/filterdns-ipsec.pid")) { sigkillbypid("{$g['varrun_path']}/filterdns-ipsec.pid", "HUP"); - else { + } else { mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-ipsec.pid -i {$interval} -c {$g['varetc_path']}/ipsec/filterdns-ipsec.hosts -d 1"); } } else { @@ -1069,8 +1179,9 @@ EOD; @unlink("{$g['varrun_path']}/filterdns-ipsec.pid"); } - if (platform_booting()) + if (platform_booting()) { echo "done\n"; + } return count($filterdns_list); } @@ -1111,8 +1222,9 @@ function vpn_ipsec_force_reload($interface = "") { function vpn_setup() { global $g; - if ($g['platform'] == 'jail') + if ($g['platform'] == 'jail') { return; + } /* start pptpd */ vpn_pptpd_configure(); @@ -1130,8 +1242,9 @@ function vpn_netgraph_support() { $realif = get_real_interface($iface); /* Get support for netgraph(4) from the nic */ $ifinfo = pfSense_get_interface_addresses($realif); - if (!empty($ifinfo) && in_array($ifinfo['iftype'], array("ether", "vlan", "bridge"))) + if (!empty($ifinfo) && in_array($ifinfo['iftype'], array("ether", "vlan", "bridge"))) { pfSense_ngctl_attach(".", $realif); + } } } @@ -1142,11 +1255,13 @@ function vpn_pptpd_configure() { $pptpdcfg = $config['pptpd']; if (platform_booting()) { - if (!$pptpdcfg['mode'] || ($pptpdcfg['mode'] == "off")) + if (!$pptpdcfg['mode'] || ($pptpdcfg['mode'] == "off")) { return 0; + } - if (platform_booting(true)) + if (platform_booting(true)) { echo gettext("Configuring PPTP VPN service... "); + } } else { /* kill mpd */ killbypid("{$g['varrun_path']}/pptp-vpn.pid"); @@ -1171,11 +1286,12 @@ function vpn_pptpd_configure() { } /* make sure pptp-vpn directory exists */ - if (!file_exists("{$g['varetc_path']}/pptp-vpn")) + if (!file_exists("{$g['varetc_path']}/pptp-vpn")) { mkdir("{$g['varetc_path']}/pptp-vpn"); + } switch ($pptpdcfg['mode']) { - case 'server' : + case 'server': /* write mpd.conf */ $fd = fopen("{$g['varetc_path']}/pptp-vpn/mpd.conf", "w"); if (!$fd) { @@ -1238,23 +1354,27 @@ EOD; EOD; } - if (isset($pptpdcfg["wins"]) && $pptpdcfg['wins'] != "") + if (isset($pptpdcfg["wins"]) && $pptpdcfg['wins'] != "") { $mpdconf .= " set ipcp nbns {$pptpdcfg['wins']}\n"; + } if (!empty($pptpdcfg['dns1'])) { $mpdconf .= " set ipcp dns " . $pptpdcfg['dns1']; - if (!empty($pptpdcfg['dns2'])) + if (!empty($pptpdcfg['dns2'])) { $mpdconf .= " " . $pptpdcfg['dns2']; + } $mpdconf .= "\n"; } elseif (isset ($config['dnsmasq']['enable'])) { $mpdconf .= " set ipcp dns " . get_interface_ip("lan"); - if ($syscfg['dnsserver'][0]) + if ($syscfg['dnsserver'][0]) { $mpdconf .= " " . $syscfg['dnsserver'][0]; + } $mpdconf .= "\n"; } elseif (isset($config['unbound']['enable'])) { $mpdconf .= " set ipcp dns " . get_interface_ip("lan"); - if ($syscfg['dnsserver'][0]) + if ($syscfg['dnsserver'][0]) { $mpdconf .= " " . $syscfg['dnsserver'][0]; + } $mpdconf .= "\n"; } elseif (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) { $mpdconf .= " set ipcp dns " . join(" ", $syscfg['dnsserver']) . "\n"; @@ -1267,15 +1387,15 @@ EOD; set radius server {$pptpdcfg['radius']['server']['ip']} "{$pptpdcfg['radius']['server']['secret']}" {$authport} {$acctport} EOD; - if (isset ($pptpdcfg['radius']['server2']['enable'])) { - $authport = (isset($pptpdcfg['radius']['server2']['port']) && strlen($pptpdcfg['radius']['server2']['port']) > 1) ? $pptpdcfg['radius']['server2']['port'] : 1812; - $acctport = $authport + 1; - $mpdconf .=<< 1) ? $pptpdcfg['radius']['server2']['port'] : 1812; + $acctport = $authport + 1; + $mpdconf .=<< \ No newline at end of file +?> diff --git a/etc/inc/vslb.inc b/etc/inc/vslb.inc index d0c5244f74..74b978f506 100644 --- a/etc/inc/vslb.inc +++ b/etc/inc/vslb.inc @@ -121,33 +121,34 @@ class SendMonitor extends Monitor { function echo_lbaction($action) { global $config; - + // Index actions by name $actions_a = array(); - for ($i=0; isset($config['load_balancer']['lbaction'][$i]); $i++) + for ($i=0; isset($config['load_balancer']['lbaction'][$i]); $i++) { $actions_a[$config['load_balancer']['lbaction'][$i]['name']] = $config['load_balancer']['lbaction'][$i]; + } $ret = ""; $ret .= "{$actions_a[$action]['direction']} {$actions_a[$action]['type']} {$actions_a[$action]['action']}"; - switch($actions_a[$action]['action']) { - case 'append': - $ret .= " \"{$actions_a[$action]['options']['value']}\" to \"{$actions_a[$action]['options']['akey']}\""; - break; - case 'change': - $ret .= " \"{$actions_a[$action]['options']['akey']}\" to \"{$actions_a[$action]['options']['value']}\""; - break; - case 'expect': - $ret .= " \"{$actions_a[$action]['options']['value']}\" from \"{$actions_a[$action]['options']['akey']}\""; - break; - case 'filter': - $ret .= " \"{$actions_a[$action]['options']['value']}\" from \"{$actions_a[$action]['options']['akey']}\""; - break; - case 'hash': - $ret .= " \"{$actions_a[$action]['options']['akey']}\""; - break; - case 'log': - $ret .= " \"{$actions_a[$action]['options']['akey']}\""; - break; + switch ($actions_a[$action]['action']) { + case 'append': + $ret .= " \"{$actions_a[$action]['options']['value']}\" to \"{$actions_a[$action]['options']['akey']}\""; + break; + case 'change': + $ret .= " \"{$actions_a[$action]['options']['akey']}\" to \"{$actions_a[$action]['options']['value']}\""; + break; + case 'expect': + $ret .= " \"{$actions_a[$action]['options']['value']}\" from \"{$actions_a[$action]['options']['akey']}\""; + break; + case 'filter': + $ret .= " \"{$actions_a[$action]['options']['value']}\" from \"{$actions_a[$action]['options']['akey']}\""; + break; + case 'hash': + $ret .= " \"{$actions_a[$action]['options']['akey']}\""; + break; + case 'log': + $ret .= " \"{$actions_a[$action]['options']['akey']}\""; + break; } return $ret; } @@ -169,29 +170,29 @@ function relayd_configure($kill_first=false) { $check_a = array(); foreach ((array)$config['load_balancer']['monitor_type'] as $type) { - switch($type['type']) { - case 'icmp': - $mon = new ICMPMonitor($type['options']); - break; - case 'tcp': - $mon = new TCPMonitor($type['options']); - break; - case 'http': - $mon = new HTTPMonitor($type['options']); - break; - case 'https': - $mon = new HTTPSMonitor($type['options']); - break; - case 'send': - $mon = new SendMonitor($type['options']); - break; + switch ($type['type']) { + case 'icmp': + $mon = new ICMPMonitor($type['options']); + break; + case 'tcp': + $mon = new TCPMonitor($type['options']); + break; + case 'http': + $mon = new HTTPMonitor($type['options']); + break; + case 'https': + $mon = new HTTPSMonitor($type['options']); + break; + case 'send': + $mon = new SendMonitor($type['options']); + break; } - if($mon) { + if ($mon) { $check_a[$type['name']] = $mon->p(); } } - - + + $fd = fopen("{$g['varetc_path']}/relayd.conf", "w"); $conf .= "log updates \n"; @@ -199,27 +200,27 @@ function relayd_configure($kill_first=false) { if not specified by the user: - use a 1000 ms timeout value as in pfsense 2.0.1 and above - leave interval and prefork empty, relayd will use its default values */ - + if (isset($setting['timeout']) && !empty($setting['timeout'])) { $conf .= "timeout ".$setting['timeout']." \n"; } else { $conf .= "timeout 1000 \n"; } - + if (isset($setting['interval']) && !empty($setting['interval'])) { $conf .= "interval ".$setting['interval']." \n"; } - + if (isset($setting['prefork']) && !empty($setting['prefork'])) { $conf .= "prefork ".$setting['prefork']." \n"; } - + /* reindex pools by name as we loop through the pools array */ $pools = array(); /* Virtual server pools */ - if(is_array($pool_a)) { + if (is_array($pool_a)) { for ($i = 0; isset($pool_a[$i]); $i++) { - if(is_array($pool_a[$i]['servers'])) { + if (is_array($pool_a[$i]['servers'])) { if (!empty($pool_a[$i]['retry'])) { $retrytext = " retry {$pool_a[$i]['retry']}"; } else { @@ -231,8 +232,7 @@ function relayd_configure($kill_first=false) { foreach (subnetv4_expand($server) as $ip) { $conf .= "\t{$ip}{$retrytext}\n"; } - } - else { + } else { $conf .= "\t{$server}{$retrytext}\n"; } } @@ -242,11 +242,11 @@ function relayd_configure($kill_first=false) { } } } -// if(is_array($protocol_a)) { +// if (is_array($protocol_a)) { // for ($i = 0; isset($protocol_a[$i]); $i++) { // $proto = "{$protocol_a[$i]['type']} protocol \"{$protocol_a[$i]['name']}\" {\n"; -// if(is_array($protocol_a[$i]['lbaction'])) { -// if($protocol_a[$i]['lbaction'][0] == "") { +// if (is_array($protocol_a[$i]['lbaction'])) { +// if ($protocol_a[$i]['lbaction'][0] == "") { // continue; // } // for ($a = 0; isset($protocol_a[$i]['lbaction'][$a]); $a++) { @@ -262,25 +262,22 @@ function relayd_configure($kill_first=false) { $conf .= "\t" . "tcp { nodelay, sack, socket buffer 1024, backlog 1000 }\n"; $conf .= "}\n"; - if(is_array($vs_a)) { + if (is_array($vs_a)) { for ($i = 0; isset($vs_a[$i]); $i++) { - + $append_port_to_name = false; if (is_alias($pools[$vs_a[$i]['poolname']]['port'])) { $dest_port_array = filter_expand_alias_array($pools[$vs_a[$i]['poolname']]['port']); $append_port_to_name = true; - } - else { + } else { $dest_port_array = array($pools[$vs_a[$i]['poolname']]['port']); } if (is_alias($vs_a[$i]['port'])) { $src_port_array = filter_expand_alias_array($vs_a[$i]['port']); $append_port_to_name = true; - } - else if ($vs_a[$i]['port']) { + } else if ($vs_a[$i]['port']) { $src_port_array = array($vs_a[$i]['port']); - } - else { + } else { $src_port_array = $dest_port_array; } @@ -291,18 +288,15 @@ function relayd_configure($kill_first=false) { log_error("item is $item"); if (is_subnetv4($item)) { $ip_list = array_merge($ip_list, subnetv4_expand($item)); - } - else { + } else { $ip_list[] = $item; } } $append_ip_to_name = true; - } - else if (is_subnetv4($vs_a[$i]['ipaddr'])) { + } else if (is_subnetv4($vs_a[$i]['ipaddr'])) { $ip_list = subnetv4_expand($vs_a[$i]['ipaddr']); $append_ip_to_name = true; - } - else { + } else { $ip_list = array($vs_a[$i]['ipaddr']); } @@ -330,26 +324,29 @@ function relayd_configure($kill_first=false) { $conf .= " protocol \"{$vs_a[$i]['relay_protocol']}\"\n"; } $lbmode = ""; - if ( $pools[$vs_a[$i]['poolname']]['mode'] == "loadbalance" ) { + if ($pools[$vs_a[$i]['poolname']]['mode'] == "loadbalance") { $lbmode = "mode loadbalance"; } $conf .= " forward to <{$vs_a[$i]['poolname']}> port {$dest_port} {$lbmode} {$check_a[$pools[$vs_a[$i]['poolname']]['monitor']]} \n"; - if (isset($vs_a[$i]['sitedown']) && strlen($vs_a[$i]['sitedown']) > 0 && ($vs_a[$i]['relay_protocol'] != 'dns')) + if (isset($vs_a[$i]['sitedown']) && strlen($vs_a[$i]['sitedown']) > 0 && ($vs_a[$i]['relay_protocol'] != 'dns')) { $conf .= " forward to <{$vs_a[$i]['sitedown']}> port {$dest_port} {$lbmode} {$check_a[$pools[$vs_a[$i]['poolname']]['monitor']]} \n"; + } $conf .= "}\n"; } else { $conf .= "redirect \"{$name}\" {\n"; $conf .= " listen on {$ip} port {$src_port}\n"; $conf .= " forward to <{$vs_a[$i]['poolname']}> port {$dest_port} {$check_a[$pools[$vs_a[$i]['poolname']]['monitor']]} \n"; - if (isset($config['system']['lb_use_sticky'])) + if (isset($config['system']['lb_use_sticky'])) { $conf .= " sticky-address\n"; + } /* sitedown MUST use the same port as the primary pool - sucks, but it's a relayd thing */ - if (isset($vs_a[$i]['sitedown']) && strlen($vs_a[$i]['sitedown']) > 0 && ($vs_a[$i]['relay_protocol'] != 'dns')) + if (isset($vs_a[$i]['sitedown']) && strlen($vs_a[$i]['sitedown']) > 0 && ($vs_a[$i]['relay_protocol'] != 'dns')) { $conf .= " forward to <{$vs_a[$i]['sitedown']}> port {$dest_port} {$check_a[$pools[$vs_a[$i]['sitedown']]['monitor']]} \n"; + } $conf .= "}\n"; } @@ -384,7 +381,7 @@ function relayd_configure($kill_first=false) { cleanup_lb_anchor("*"); } } else { - if (! empty($vs_a)) { + if (!empty($vs_a)) { // not running and there is a config, start it /* Remove all active relayd anchors so it can start fresh. */ cleanup_lb_anchor("*"); @@ -418,9 +415,9 @@ Id Type Name Avlblty Status # relayctl show redirects Id Type Name Avlblty Status 1 redirect testvs2 active - total: 2 sessions - last: 2/60s 2/h 2/d sessions - average: 1/60s 0/h 0/d sessions + total: 2 sessions + last: 2/60s 2/h 2/d sessions + average: 1/60s 0/h 0/d sessions 0 redirect testvs active */ $rdr_a = array(); @@ -433,7 +430,7 @@ Id Type Name Avlblty Status $line = $rdr_a[$i]; if (preg_match("/^[0-9]+/", $line)) { $regs = array(); - if($x = preg_match("/^[0-9]+\s+redirect\s+([^\s]+)\s+([^\s]+)/", $line, $regs)) { + if ($x = preg_match("/^[0-9]+\s+redirect\s+([^\s]+)\s+([^\s]+)/", $line, $regs)) { $cur_entry = trim($regs[1]); $vs[trim($regs[1])] = array(); $vs[trim($regs[1])]['status'] = trim($regs[2]); @@ -451,7 +448,7 @@ Id Type Name Avlblty Status $line = $relay_a[$i]; if (preg_match("/^[0-9]+/", $line)) { $regs = array(); - if($x = preg_match("/^[0-9]+\s+relay\s+([^\s]+)\s+([^\s]+)/", $line, $regs)) { + if ($x = preg_match("/^[0-9]+\s+relay\s+([^\s]+)\s+([^\s]+)/", $line, $regs)) { $cur_entry = trim($regs[1]); $vs[trim($regs[1])] = array(); $vs[trim($regs[1])]['status'] = trim($regs[2]); @@ -471,7 +468,7 @@ function get_lb_summary() { $relayctl = array(); exec('/usr/local/sbin/relayctl show summary 2>&1', $relayctl); $relay_hosts=Array(); - foreach( (array) $relayctl as $line) { + foreach ((array) $relayctl as $line) { $t = explode("\t", $line); switch (trim($t[1])) { case "table": @@ -510,16 +507,19 @@ function cleanup_lb_anchor($anchorname = "*") { function cleanup_lb_mark_anchor($name) { global $g; /* Nothing to do! */ - if (empty($name)) + if (empty($name)) { return; + } $filename = "{$g['tmp_path']}/relayd_anchors_remove"; $cleanup_anchors = array(); /* Read in any currently unapplied name changes */ - if (file_exists($filename)) + if (file_exists($filename)) { $cleanup_anchors = explode("\n", file_get_contents($filename)); + } /* Only add the anchor to the list if it's not already there. */ - if (!in_array($name, $cleanup_anchors)) + if (!in_array($name, $cleanup_anchors)) { $cleanup_anchors[] = $name; + } file_put_contents($filename, implode("\n", $cleanup_anchors)); } @@ -534,14 +534,15 @@ function cleanup_lb_marked() { } else { $cleanup_anchors = explode("\n", file_get_contents($filename)); /* Nothing to do! */ - if (empty($cleanup_anchors)) + if (empty($cleanup_anchors)) { return; + } } /* Load current names so we can make sure we don't remove an anchor that is still in use. */ $vs_a = $config['load_balancer']['virtual_server']; $active_vsnames = array(); - if(is_array($vs_a)) { + if (is_array($vs_a)) { foreach ($vs_a as $vs) { $active_vsnames[] = $vs['name']; } diff --git a/etc/inc/wizardapp.inc b/etc/inc/wizardapp.inc index 091f73aa53..b94c76be66 100644 --- a/etc/inc/wizardapp.inc +++ b/etc/inc/wizardapp.inc @@ -107,7 +107,7 @@ $gamesplist['gamesforwindowslive'] = array(); $gamesplist['arma2'] = array(); /* ARMA 2 */ $gamesplist['arma2'][] = array('arma2', 'udp', '2302', '2310', 'both'); - + $gamesplist['arma3'] = array(); /* ARMA 3 */ $gamesplist['arma3'][] = array('arma3-game-traffic', 'udp', '2302', '2302', 'both'); @@ -128,7 +128,7 @@ $gamesplist['battlefield2'] = array(); $gamesplist['battlefield2'][] = array('BF2-29900-29901-TCP', 'tcp', '29900', '29901', 'both'); $gamesplist['battlefield2'][] = array('BF2-27900', 'udp', '27900', '27900', 'both'); $gamesplist['battlefield2'][] = array('BF2-55123-55125', 'udp', '55123', '55125', 'both'); - + $gamesplist['battlefield3'] = array(); /* Battlefield 3 and Battlefield 4 */ $gamesplist['battlefield3'][] = array('BF3-1', 'tcp', '9988', '9988', 'both'); @@ -217,7 +217,7 @@ $gamesplist['dirt3'] = array(); /* ARMA 2 */ $gamesplist['dirt3'][] = array('Dirt3-1', 'tcp', '2300', '2400', 'both'); $gamesplist['dirt3'][] = array('Dirt3-2', 'udp', '2300', '2400', 'both'); - $gamesplist['dirt3'][] = array('Dirt3-3', 'udp', '6073', '6073', 'both'); + $gamesplist['dirt3'][] = array('Dirt3-3', 'udp', '6073', '6073', 'both'); $gamesplist['dirt3'][] = array('Dirt3-4', 'tcp', '47624', '47624', 'both'); $gamesplist['doom3'] = array(); @@ -277,7 +277,7 @@ $gamesplist['farcry3'] = array(); /* FarCry 3*/ $gamesplist['farcry3'][] = array('FarCry3-game', 'udp', '9000', '9000', 'both'); $gamesplist['farcry3'][] = array('FarCry3-punkbuster', 'udp', '10009', '10009', 'both'); - + $gamesplist['gunzonline'] = array(); /* GunZ Online */ $gamesplist['gunzonline'][] = array('GunZOnline', 'udp', '7700', '7700', 'both'); @@ -327,7 +327,7 @@ $gamesplist['planetside'] = array(); $gamesplist['planetside'][] = array('PlanetSide2', 'udp', '3016', '3021', 'both'); $gamesplist['planetside'][] = array('PlanetSide2', 'udp', '45000', '45010', 'both'); $gamesplist['planetside'][] = array('PlanetSide2', 'udp', '30000', '30500', 'both'); - + $gamesplist['planetside2'] = array(); /* PlanetSide 2 */ $gamesplist['planetside2'][] = array('PlanetSide2-game', 'udp', '20040', '20199', 'both'); @@ -337,7 +337,7 @@ $gamesplist['planetside2'] = array(); $gamesplist['quakeiii'] = array(); /* quake3 */ $gamesplist['quakeiii'][] = array('Quake3', 'udp', '27910', '27919', 'both'); - + $gamesplist['quakeiv'] = array(); /* quake4 */ $gamesplist['quakeiv'][] = array('QuakeIV-server-udp', 'udp', '27650', '27650', 'both'); @@ -385,12 +385,12 @@ $voiplist['Asterisk'] = array(); $voiplist['Asterisk'][] = array('Asterisk', 'udp', '5060', '5069', 'both'); $voiplist['Asterisk'][] = array('Asterisk', 'udp', '10000', '20000', 'both'); - /* VoicePulse server */ + /* VoicePulse server */ $voiplist['VoicePulse'] = array(); $voiplist['VoicePulse'][] = array('VoicePulse', 'udp', '16384', '16482', 'both'); $voiplist['VoicePulse'][] = array('VoicePulse', 'udp', '4569', '4569', 'both'); - /* Panasonic Hybrid PBX */ + /* Panasonic Hybrid PBX */ $voiplist['Panasonic'] = array(); $voiplist['Panasonic'][] = array('Panasonic1', 'udp', '8000', '8063', 'both'); $voiplist['Panasonic'][] = array('Panasonic2', 'udp', '9300', '9301', 'both'); @@ -401,7 +401,7 @@ $p2plist = array(); /* To add p2p clients, push Descr,Protocol,Start,End,src/dest/both onto p2plist */ $p2plist['aimster'] = array(); $p2plist['aimster'][] = array('Aimster', 'tcp', '7668', '7668', 'both'); - $p2plist['bittorrent'] = array(); + $p2plist['bittorrent'] = array(); $p2plist['bittorrent'][] = array('BitTorrent', 'tcp', '6881', '6999', 'both'); $p2plist['bittorrent'][] = array('BitTorrent', 'udp', '6881', '6999', 'both'); $p2plist['buddyshare'] = array(); @@ -420,7 +420,7 @@ $p2plist = array(); $p2plist['edonkey2000'][] = array('EDonkey2000', 'tcp', '4661', '4665', 'both'); $p2plist['fastTrack'] = array(); $p2plist['fastTrack'][] = array('FastTrack', 'tcp', '1214', '1214', 'both'); - $p2plist['gnutella'] = array(); + $p2plist['gnutella'] = array(); $p2plist['gnutella'][] = array('Gnutella-TCP', 'tcp', '6346', '6346', 'both'); $p2plist['gnutella'][] = array('Gnutella-UDP', 'udp', '6346', '6346', 'both'); $p2plist['grouper'] = array(); @@ -509,7 +509,7 @@ $othersplist = array(); $othersplist['msnmessenger'][] = array('MSN2', 'tcp', '6891', '6900', 'both'); $othersplist['msnmessenger'][] = array('MSN3', 'tcp', '6901', '6901', 'both'); $othersplist['msnmessenger'][] = array('MSN4', 'udp', '6901', '6901', 'both'); - + $othersplist['teamspeak'] = array(); /* teamspeak */ $othersplist['teamspeak'][] = array('TeamSpeak-1', 'tcp', '14534', '14534', 'both'); @@ -624,7 +624,7 @@ $othersplist = array(); $othersplist['git'] = array(); /* GIT */ $othersplist['git'][] = array('git', 'tcp', '9418', '9418', 'both'); - + $othersplist['hbci'] = array(); /* HBCI */ $othersplist['hbci'][] = array('HBCI', 'tcp', '3000', '3000', 'both'); @@ -641,7 +641,7 @@ $othersplist = array(); /* nntp */ $othersplist['nntp'][] = array('NNTP1', 'tcp', '119', '119', 'both'); $othersplist['nntp'][] = array('NNTP2', 'udp', '119', '119', 'both'); - + $othersplist['slingbox'] = array(); /* slingbox */ $othersplist['slingbox'][] = array('Slingbox1', 'tcp', '5001', '5001', 'both'); diff --git a/etc/inc/xmlparse.inc b/etc/inc/xmlparse.inc index 3b32719846..e7af433412 100644 --- a/etc/inc/xmlparse.inc +++ b/etc/inc/xmlparse.inc @@ -37,30 +37,30 @@ function listtags() { * I know it's a pain, but it's a pain to find stuff too if it's not */ $ret = array( - 'acls', 'alias', 'aliasurl', 'allowedip', 'allowedhostname', 'authserver', - 'bridged', 'build_port_path', - 'ca', 'cacert', 'cert', 'crl', 'clone', 'config', 'container', 'columnitem', - 'depends_on_package', 'disk', 'dnsserver', 'dnsupdate', 'domainoverrides', 'dyndns', - 'earlyshellcmd', 'element', 'encryption-algorithm-option', - 'field', 'fieldname', - 'gateway_item', 'gateway_group', 'gif', 'gre', 'group', - 'hash-algorithm-option', 'hosts', 'member', 'ifgroupentry', 'igmpentry', 'interface_array', 'item', 'key', - 'lagg', 'lbaction', 'lbpool', 'l7rules', 'lbprotocol', - 'member', 'menu', 'tab', 'mobilekey', 'monitor_type', 'mount', + 'acls', 'alias', 'aliasurl', 'allowedip', 'allowedhostname', 'authserver', + 'bridged', 'build_port_path', + 'ca', 'cacert', 'cert', 'crl', 'clone', 'config', 'container', 'columnitem', + 'depends_on_package', 'disk', 'dnsserver', 'dnsupdate', 'domainoverrides', 'dyndns', + 'earlyshellcmd', 'element', 'encryption-algorithm-option', + 'field', 'fieldname', + 'gateway_item', 'gateway_group', 'gif', 'gre', 'group', + 'hash-algorithm-option', 'hosts', 'member', 'ifgroupentry', 'igmpentry', 'interface_array', 'item', 'key', + 'lagg', 'lbaction', 'lbpool', 'l7rules', 'lbprotocol', + 'member', 'menu', 'tab', 'mobilekey', 'monitor_type', 'mount', 'npt', 'ntpserver', - 'onetoone', 'openvpn-server', 'openvpn-client', 'openvpn-csc', 'option', - 'package', 'passthrumac', 'phase1', 'phase2', 'ppp', 'pppoe', 'priv', 'proxyarpnet', 'pool', + 'onetoone', 'openvpn-server', 'openvpn-client', 'openvpn-csc', 'option', + 'package', 'passthrumac', 'phase1', 'phase2', 'ppp', 'pppoe', 'priv', 'proxyarpnet', 'pool', 'qinqentry', 'queue', - 'pages', 'pipe', 'radnsserver', 'roll', 'route', 'row', 'rrddatafile', 'rule', + 'pages', 'pipe', 'radnsserver', 'roll', 'route', 'row', 'rrddatafile', 'rule', 'schedule', 'service', 'servernat', 'servers', - 'serversdisabled', 'shellcmd', 'staticmap', 'subqueue', + 'serversdisabled', 'shellcmd', 'staticmap', 'subqueue', 'timerange', 'tunnel', 'user', 'vip', 'virtual_server', 'vlan', 'winsserver', 'wolentry', 'widget' ); return array_flip($ret); } -/* Package XML tags that should be treat as a list not as a traditional array */ +/* Package XML tags that should be treated as a list not as a traditional array */ function listtags_pkg() { $ret = array('build_port_path', 'depends_on_package', 'onetoone', 'queue', 'rule', 'servernat', 'alias', 'additional_files_needed', 'tab', 'template', 'menu', 'rowhelperfield', 'service', 'step', 'package', 'columnitem', 'option', 'item', 'field', 'package', 'file'); @@ -91,8 +91,8 @@ function startElement($parser, $name, $attrs) { } else if (isset($ptr)) { /* multiple entries not allowed for this element, bail out */ die(sprintf(gettext('XML error: %1$s at line %2$d cannot occur more than once') . "\n", - $name, - xml_get_current_line_number($parser))); + $name, + xml_get_current_line_number($parser))); } $depth++; @@ -112,8 +112,9 @@ function endElement($parser, $name) { array_pop($curpath); - if (isset($listtags[strtolower($name)])) + if (isset($listtags[strtolower($name)])) { array_pop($curpath); + } $depth--; } @@ -143,26 +144,27 @@ function cData($parser, $data) { function parse_xml_config($cffile, $rootobj, $isstring = "false") { global $listtags; $listtags = listtags(); - if (isset($GLOBALS['custom_listtags'])) { - foreach($GLOBALS['custom_listtags'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags'])) { + foreach ($GLOBALS['custom_listtags'] as $tag) { + $listtags[$tag] = $tag; + } + } return parse_xml_config_raw($cffile, $rootobj, $isstring); } function parse_xml_config_pkg($cffile, $rootobj, $isstring = "false") { global $listtags; $listtags = listtags_pkg(); - if (isset($GLOBALS['custom_listtags_pkg'])) { - foreach($GLOBALS['custom_listtags_pkg'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags_pkg'])) { + foreach ($GLOBALS['custom_listtags_pkg'] as $tag) { + $listtags[$tag] = $tag; + } + } $cfg =parse_xml_config_raw($cffile, $rootobj, $isstring); - if ($cfg == -1) + if ($cfg == -1) { return array(); - + } + return $cfg; } @@ -178,7 +180,7 @@ function parse_xml_config_raw($cffile, $rootobj, $isstring = "false") { xml_set_element_handler($xml_parser, "startElement", "endElement"); xml_set_character_data_handler($xml_parser, "cdata"); - xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE, 1); + xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE, 1); if (!($fp = fopen($cffile, "r"))) { log_error(gettext("Error: could not open XML input") . "\n"); @@ -188,21 +190,24 @@ function parse_xml_config_raw($cffile, $rootobj, $isstring = "false") { while ($data = fread($fp, 4096)) { if (!xml_parse($xml_parser, $data, feof($fp))) { log_error(sprintf(gettext('XML error: %1$s at line %2$d in %3$s') . "\n", - xml_error_string(xml_get_error_code($xml_parser)), - xml_get_current_line_number($xml_parser), - $cffile)); + xml_error_string(xml_get_error_code($xml_parser)), + xml_get_current_line_number($xml_parser), + $cffile)); return -1; } } xml_parser_free($xml_parser); if ($rootobj) { - if (!is_array($rootobj)) + if (!is_array($rootobj)) { $rootobj = array($rootobj); - foreach ($rootobj as $rootobj_name) - if ($parsedcfg[$rootobj_name]) + } + foreach ($rootobj as $rootobj_name) { + if ($parsedcfg[$rootobj_name]) { break; - + } + } + if (!$parsedcfg[$rootobj_name]) { log_error(sprintf(gettext("XML error: no %s object found!") . "\n", implode(" or ", $rootobj))); return -1; @@ -236,18 +241,20 @@ function dump_xml_config_sub($arr, $indent) { $xmlconfig .= "\n"; } } else { - if($cval === false) continue; + if ($cval === false) { + continue; + } $xmlconfig .= str_repeat("\t", $indent); - if((is_bool($cval) && $cval == true) || ($cval === "")) { + if ((is_bool($cval) && $cval == true) || ($cval === "")) { $xmlconfig .= "<$ent/>\n"; - } else if ((substr($ent, 0, 5) == "descr") - || (substr($ent, 0, 6) == "detail") - || (substr($ent, 0, 12) == "login_banner") - || (substr($ent, 0, 9) == "ldap_attr") - || (substr($ent, 0, 9) == "ldap_bind") - || (substr($ent, 0, 11) == "ldap_basedn") - || (substr($ent, 0, 18) == "ldap_authcn") - || (substr($ent, 0, 19) == "ldap_extended_query")) { + } else if ((substr($ent, 0, 5) == "descr") || + (substr($ent, 0, 6) == "detail") || + (substr($ent, 0, 12) == "login_banner") || + (substr($ent, 0, 9) == "ldap_attr") || + (substr($ent, 0, 9) == "ldap_bind") || + (substr($ent, 0, 11) == "ldap_basedn") || + (substr($ent, 0, 18) == "ldap_authcn") || + (substr($ent, 0, 19) == "ldap_extended_query")) { $xmlconfig .= "<$ent>\n"; } else { $xmlconfig .= "<$ent>" . htmlentities($cval) . "\n"; @@ -271,17 +278,18 @@ function dump_xml_config_sub($arr, $indent) { $xmlconfig .= "<$ent/>\n"; } else if (!is_bool($val)) { $xmlconfig .= str_repeat("\t", $indent); - if ((substr($ent, 0, 5) == "descr") - || (substr($ent, 0, 6) == "detail") - || (substr($ent, 0, 12) == "login_banner") - || (substr($ent, 0, 9) == "ldap_attr") - || (substr($ent, 0, 9) == "ldap_bind") - || (substr($ent, 0, 11) == "ldap_basedn") - || (substr($ent, 0, 18) == "ldap_authcn") - || (substr($ent, 0, 19) == "ldap_extended_query")) + if ((substr($ent, 0, 5) == "descr") || + (substr($ent, 0, 6) == "detail") || + (substr($ent, 0, 12) == "login_banner") || + (substr($ent, 0, 9) == "ldap_attr") || + (substr($ent, 0, 9) == "ldap_bind") || + (substr($ent, 0, 11) == "ldap_basedn") || + (substr($ent, 0, 18) == "ldap_authcn") || + (substr($ent, 0, 19) == "ldap_extended_query")) $xmlconfig .= "<$ent>\n"; - else + else { $xmlconfig .= "<$ent>" . htmlentities($val) . "\n"; + } } } } @@ -292,22 +300,22 @@ function dump_xml_config_sub($arr, $indent) { function dump_xml_config($arr, $rootobj) { global $listtags; $listtags = listtags(); - if (isset($GLOBALS['custom_listtags'])) { - foreach($GLOBALS['custom_listtags'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags'])) { + foreach ($GLOBALS['custom_listtags'] as $tag) { + $listtags[$tag] = $tag; + } + } return dump_xml_config_raw($arr, $rootobj); } function dump_xml_config_pkg($arr, $rootobj) { global $listtags; $listtags = listtags_pkg(); - if (isset($GLOBALS['custom_listtags_pkg'])) { - foreach($GLOBALS['custom_listtags_pkg'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags_pkg'])) { + foreach ($GLOBALS['custom_listtags_pkg'] as $tag) { + $listtags[$tag] = $tag; + } + } return dump_xml_config_raw($arr, $rootobj); } diff --git a/etc/inc/xmlparse_attr.inc b/etc/inc/xmlparse_attr.inc index 933caba696..a024c20a76 100644 --- a/etc/inc/xmlparse_attr.inc +++ b/etc/inc/xmlparse_attr.inc @@ -52,8 +52,9 @@ function startElement_attr($parser, $name, $attrs) { } foreach ($curpath as $path) { $ptr =& $ptr[$path]; - if (isset($writeattrs)) + if (isset($writeattrs)) { $attrptr =& $attrptr[$path]; + } } /* is it an element that belongs to a list? */ @@ -68,16 +69,17 @@ function startElement_attr($parser, $name, $attrs) { array_push($curpath, count($ptr)); if (isset($writeattrs)) { - if (!is_array($attrptr)) + if (!is_array($attrptr)) { $attrptr = array(); + } $attrptr[count($ptr)] = $attrs; } } else if (isset($ptr)) { /* multiple entries not allowed for this element, bail out */ die(sprintf(gettext('XML error: %1$s at line %2$d cannot occur more than once') . "\n", - $name, - xml_get_current_line_number($parser))); + $name, + xml_get_current_line_number($parser))); } else if (isset($writeattrs)) { $attrptr = $attrs; } @@ -99,8 +101,9 @@ function endElement_attr($parser, $name) { array_pop($curpath); - if (in_array(strtolower($name), $listtags)) + if (in_array(strtolower($name), $listtags)) { array_pop($curpath); + } $depth--; } @@ -130,8 +133,9 @@ function cData_attr($parser, $data) { function parse_xml_regdomain(&$rdattributes, $rdfile = '', $rootobj = 'regulatory-data') { global $g, $listtags; - if (empty($rdfile)) + if (empty($rdfile)) { $rdfile = $g['etc_path'] . '/regdomain.xml'; + } $listtags = listtags_rd(); $parsed_xml = array(); @@ -147,15 +151,19 @@ function parse_xml_regdomain(&$rdattributes, $rdfile = '', $rootobj = 'regulator // unset parts that aren't used before making cache foreach ($rdmain['regulatory-domains']['rd'] as $rdkey => $rdentry) { - if (isset($rdmain['regulatory-domains']['rd'][$rdkey]['netband'])) + if (isset($rdmain['regulatory-domains']['rd'][$rdkey]['netband'])) { unset($rdmain['regulatory-domains']['rd'][$rdkey]['netband']); - if (isset($rdattributes['regulatory-domains']['rd'][$rdkey]['netband'])) + } + if (isset($rdattributes['regulatory-domains']['rd'][$rdkey]['netband'])) { unset($rdattributes['regulatory-domains']['rd'][$rdkey]['netband']); + } } - if (isset($rdmain['shared-frequency-bands'])) + if (isset($rdmain['shared-frequency-bands'])) { unset($rdmain['shared-frequency-bands']); - if (isset($rdattributes['shared-frequency-bands'])) + } + if (isset($rdattributes['shared-frequency-bands'])) { unset($rdattributes['shared-frequency-bands']); + } $parsed_xml = array('main' => $rdmain, 'attributes' => $rdattributes); $rdcache = fopen($g['tmp_path'] . '/regdomain.cache', "w"); @@ -174,14 +182,15 @@ function parse_xml_config_raw_attr($cffile, $rootobj, &$parsed_attributes, $isst $depth = 0; $havedata = 0; - if (isset($parsed_attributes)) + if (isset($parsed_attributes)) { $parsedattrs = array(); + } $xml_parser = xml_parser_create(); xml_set_element_handler($xml_parser, "startElement_attr", "endElement_attr"); xml_set_character_data_handler($xml_parser, "cData_attr"); - xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE, 1); + xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE, 1); if (!($fp = fopen($cffile, "r"))) { log_error(gettext("Error: could not open XML input") . "\n"); @@ -195,8 +204,8 @@ function parse_xml_config_raw_attr($cffile, $rootobj, &$parsed_attributes, $isst while ($data = fread($fp, 4096)) { if (!xml_parse($xml_parser, $data, feof($fp))) { log_error(sprintf(gettext('XML error: %1$s at line %2$d') . "\n", - xml_error_string(xml_get_error_code($xml_parser)), - xml_get_current_line_number($xml_parser))); + xml_error_string(xml_get_error_code($xml_parser)), + xml_get_current_line_number($xml_parser))); if (isset($parsed_attributes)) { $parsed_attributes = array(); unset($parsedattrs); @@ -216,8 +225,9 @@ function parse_xml_config_raw_attr($cffile, $rootobj, &$parsed_attributes, $isst } if (isset($parsed_attributes)) { - if ($parsedattrs[$rootobj]) + if ($parsedattrs[$rootobj]) { $parsed_attributes = $parsedattrs[$rootobj]; + } unset($parsedattrs); } diff --git a/etc/inc/xmlreader.inc b/etc/inc/xmlreader.inc index a0563ae0b7..960acb1bf2 100644 --- a/etc/inc/xmlreader.inc +++ b/etc/inc/xmlreader.inc @@ -37,9 +37,9 @@ /* The following items will be treated as arrays in config.xml */ function listtags() { /* - * Please keep this list alpha sorted and no longer than 80 characters - * I know it's a pain, but it's a pain to find stuff too if it's not - */ + * Please keep this list alpha sorted and no longer than 80 characters + * I know it's a pain, but it's a pain to find stuff too if it's not + */ $ret = array( 'acls', 'alias', 'aliasurl', 'allowedip', 'allowedhostname', 'authserver', 'bridged', 'build_port_path', @@ -72,61 +72,64 @@ function listtags_pkg() { } function add_elements(&$cfgarray, &$parser) { - global $listtags; + global $listtags; - while ($parser->read()) { - switch ($parser->nodeType) { - case XMLReader::WHITESPACE: - case XMLReader::SIGNIFICANT_WHITESPACE: - break; - case XMLReader::ELEMENT: - if (isset($listtags[strtolower($parser->name)])) { - $cfgref =& $cfgarray[$parser->name][count($cfgarray[$parser->name])]; - if (!$parser->isEmptyElement) { - add_elements($cfgref, $parser); - } else - $cfgref = array(); - - } else { - if (isset($cfgarray[$parser->name]) && (!is_array($cfgarray[$parser->name]) || !isset($cfgarray[$parser->name][0]))) { - $nodebkp = $cfgarray[$parser->name]; - $cfgarray[$parser->name] = array(); - $cfgarray[$parser->name][] = $nodebkp; - $cfgref =& $cfgarray[$parser->name][0]; - unset($nodebkp); - } else - $cfgref =& $cfgarray[$parser->name]; - - if ($parser->isEmptyElement) { - if (is_array($cfgref)) - $cfgref[] = array(); - else - $cfgref = ""; + while ($parser->read()) { + switch ($parser->nodeType) { + case XMLReader::WHITESPACE: + case XMLReader::SIGNIFICANT_WHITESPACE: + break; + case XMLReader::ELEMENT: + if (isset($listtags[strtolower($parser->name)])) { + $cfgref =& $cfgarray[$parser->name][count($cfgarray[$parser->name])]; + if (!$parser->isEmptyElement) { + add_elements($cfgref, $parser); + } else { + $cfgref = array(); + } } else { - if (is_array($cfgref)) { - $cfgref =& $cfgarray[$parser->name][count($cfgarray[$parser->name])]; - add_elements($cfgref, $parser); - } else - add_elements($cfgref, $parser); - } - } + if (isset($cfgarray[$parser->name]) && (!is_array($cfgarray[$parser->name]) || !isset($cfgarray[$parser->name][0]))) { + $nodebkp = $cfgarray[$parser->name]; + $cfgarray[$parser->name] = array(); + $cfgarray[$parser->name][] = $nodebkp; + $cfgref =& $cfgarray[$parser->name][0]; + unset($nodebkp); + } else { + $cfgref =& $cfgarray[$parser->name]; + } - $i = 0; - while ($parser->moveToAttributeNo($i)) { - $cfgref[$parser->name] = $parser->value; - $i++; - } - break; - case XMLReader::TEXT: - case XMLReader::CDATA: - $cfgarray = $parser->value; - break; - case XMLReader::END_ELEMENT: - return; - break; - default: - break; - } + if ($parser->isEmptyElement) { + if (is_array($cfgref)) { + $cfgref[] = array(); + } else { + $cfgref = ""; + } + } else { + if (is_array($cfgref)) { + $cfgref =& $cfgarray[$parser->name][count($cfgarray[$parser->name])]; + add_elements($cfgref, $parser); + } else { + add_elements($cfgref, $parser); + } + } + } + + $i = 0; + while ($parser->moveToAttributeNo($i)) { + $cfgref[$parser->name] = $parser->value; + $i++; + } + break; + case XMLReader::TEXT: + case XMLReader::CDATA: + $cfgarray = $parser->value; + break; + case XMLReader::END_ELEMENT: + return; + break; + default: + break; + } } } @@ -134,11 +137,11 @@ function parse_xml_config($cffile, $rootobj, $isstring = "false") { global $listtags; $listtags = listtags(); - if (isset($GLOBALS['custom_listtags'])) { - foreach($GLOBALS['custom_listtags'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags'])) { + foreach ($GLOBALS['custom_listtags'] as $tag) { + $listtags[$tag] = $tag; + } + } return parse_xml_config_raw($cffile, $rootobj); } @@ -147,11 +150,11 @@ function parse_xml_config_pkg($cffile, $rootobj, $isstring = "false") { global $listtags; $listtags = listtags_pkg(); - if (isset($GLOBALS['custom_listtags_pkg'])) { - foreach($GLOBALS['custom_listtags_pkg'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags_pkg'])) { + foreach ($GLOBALS['custom_listtags_pkg'] as $tag) { + $listtags[$tag] = $tag; + } + } return parse_xml_config_raw($cffile, $rootobj, $isstring); } @@ -164,16 +167,20 @@ function parse_xml_config_raw($cffile, $rootobj, $isstring = "false") { if ($par->open($cffile, "UTF-8", LIBXML_NOERROR | LIBXML_NOWARNING)) { add_elements($parsedcfg, $par); $par->close(); - } else + } else { log_error(sprintf(gettext("Error returned while trying to parse %s"), $cffile)); + } if ($rootobj) { - if (!is_array($rootobj)) + if (!is_array($rootobj)) { $rootobj = array($rootobj); - foreach ($rootobj as $rootobj_name) - if ($parsedcfg[$rootobj_name]) + } + foreach ($rootobj as $rootobj_name) { + if ($parsedcfg[$rootobj_name]) { break; - + } + } + return $parsedcfg[$rootobj_name]; } else { return $parsedcfg; @@ -181,55 +188,59 @@ function parse_xml_config_raw($cffile, $rootobj, $isstring = "false") { } function dump_xml_config_sub(& $writer, $arr) { - global $listtags; + global $listtags; - foreach ($arr as $ent => $val) { - if (is_array($val)) { - /* is it just a list of multiple values? */ - if (isset($listtags[strtolower($ent)])) { - foreach ($val as $cval) { - if (is_array($cval)) { - if (empty($cval)) - $writer->writeElement($ent); - else { - $writer->startElement($ent); - dump_xml_config_sub($writer, $cval); - $writer->endElement(); - } - } else { - if($cval === false) continue; - if ((is_bool($val) && ($val == true)) || ($val === "")) - $writer->writeElement($ent); - else if (!is_bool($val)) + foreach ($arr as $ent => $val) { + if (is_array($val)) { + /* is it just a list of multiple values? */ + if (isset($listtags[strtolower($ent)])) { + foreach ($val as $cval) { + if (is_array($cval)) { + if (empty($cval)) { + $writer->writeElement($ent); + } else { + $writer->startElement($ent); + dump_xml_config_sub($writer, $cval); + $writer->endElement(); + } + } else { + if ($cval === false) { + continue; + } + if ((is_bool($val) && ($val == true)) || ($val === "")) { + $writer->writeElement($ent); + } else if (!is_bool($val)) { $writer->writeElement($ent, $cval); - } - } - } else if (empty($val)) { - $writer->writeElement($ent); - } else { - /* it's an array */ - $writer->startElement($ent); - dump_xml_config_sub($writer, $val); - $writer->endElement(); - } - } else { - if ((is_bool($val) && ($val == true)) || ($val === "")) - $writer->writeElement($ent); - else if (!is_bool($val)) - $writer->writeElement($ent, $val); - } - } + } + } + } + } else if (empty($val)) { + $writer->writeElement($ent); + } else { + /* it's an array */ + $writer->startElement($ent); + dump_xml_config_sub($writer, $val); + $writer->endElement(); + } + } else { + if ((is_bool($val) && ($val == true)) || ($val === "")) { + $writer->writeElement($ent); + } else if (!is_bool($val)) { + $writer->writeElement($ent, $val); + } + } + } } function dump_xml_config($arr, $rootobj) { global $listtags; $listtags = listtags(); - if (isset($GLOBALS['custom_listtags'])) { - foreach($GLOBALS['custom_listtags'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags'])) { + foreach ($GLOBALS['custom_listtags'] as $tag) { + $listtags[$tag] = $tag; + } + } return dump_xml_config_raw($arr, $rootobj); } @@ -237,30 +248,30 @@ function dump_xml_config_pkg($arr, $rootobj) { global $listtags; $listtags = listtags_pkg(); - if (isset($GLOBALS['custom_listtags_pkg'])) { - foreach($GLOBALS['custom_listtags_pkg'] as $tag) { - $listtags[$tag] = $tag; - } - } + if (isset($GLOBALS['custom_listtags_pkg'])) { + foreach ($GLOBALS['custom_listtags_pkg'] as $tag) { + $listtags[$tag] = $tag; + } + } return dump_xml_config_raw($arr, $rootobj); } function dump_xml_config_raw($arr, $rootobj) { - $writer = new XMLWriter(); - $writer->openMemory(); - $writer->setIndent(true); - $writer->setIndentString("\t"); - $writer->startDocument("1.0", "UTF-8"); - $writer->startElement($rootobj); + $writer = new XMLWriter(); + $writer->openMemory(); + $writer->setIndent(true); + $writer->setIndentString("\t"); + $writer->startDocument("1.0", "UTF-8"); + $writer->startElement($rootobj); - dump_xml_config_sub($writer, $arr); + dump_xml_config_sub($writer, $arr); - $writer->endElement(); - $writer->endDocument(); - $xmlconfig = $writer->outputMemory(true); + $writer->endElement(); + $writer->endDocument(); + $xmlconfig = $writer->outputMemory(true); - return $xmlconfig; + return $xmlconfig; } ?> diff --git a/etc/inc/xmlrpc.inc b/etc/inc/xmlrpc.inc index bce1c1c7f8..e96e783247 100644 --- a/etc/inc/xmlrpc.inc +++ b/etc/inc/xmlrpc.inc @@ -29,7 +29,7 @@ */ /* - pfSense_BUILDER_BINARIES: + pfSense_BUILDER_BINARIES: pfSense_MODULE: utils */ @@ -40,41 +40,43 @@ require_once("xmlrpc_client.inc"); * xmlrpc_params_to_php: Convert params array passed from XMLRPC server into a PHP array and return it. */ function xmlrpc_params_to_php($params) { - $array = array(); - for($i = 0; $i < $params->getNumParams(); $i++) { - $value = $params->getParam($i); - $array[] = XML_RPC_decode($value); - } - return $array; + $array = array(); + for ($i = 0; $i < $params->getNumParams(); $i++) { + $value = $params->getParam($i); + $array[] = XML_RPC_decode($value); + } + return $array; } - + /* * xmlrpc_value_to_php: Convert an XMLRPC value into a PHP scalar/array and return it. */ function xmlrpc_value_to_php($raw_value) { /* - switch($raw_value->kindOf()) { - case "scalar": - if($raw_value->scalartyp() == "boolean") $return = (boolean) $raw_value->scalarval(); - $return = $raw_value->scalarval(); - break; - case "array": - $return = array(); - for($i = 0; $i < $raw_value->arraysize(); $i++) { - $value = $raw_value->arraymem($i); - $return[] = xmlrpc_value_to_php($value); - } - break; - case "struct": - $return = array(); - for($i = 0; $i < $raw_value->arraysize(); $i++) { - list($key, $value) = $raw_value->structeach(); - $return[$key] = xmlrpc_value_to_php($value); - } - break; - } + switch ($raw_value->kindOf()) { + case "scalar": + if ($raw_value->scalartyp() == "boolean") { + $return = (boolean) $raw_value->scalarval(); + } + $return = $raw_value->scalarval(); + break; + case "array": + $return = array(); + for ($i = 0; $i < $raw_value->arraysize(); $i++) { + $value = $raw_value->arraymem($i); + $return[] = xmlrpc_value_to_php($value); + } + break; + case "struct": + $return = array(); + for ($i = 0; $i < $raw_value->arraysize(); $i++) { + list($key, $value) = $raw_value->structeach(); + $return[$key] = xmlrpc_value_to_php($value); + } + break; + } */ - return XML_RPC_decode($raw_value); + return XML_RPC_decode($raw_value); } /* @@ -84,21 +86,23 @@ function php_value_to_xmlrpc($value, $force_array = false) { $toreturn = XML_RPC_encode($value); return $force_array ? array($toreturn) : $toreturn; /* - if(gettype($value) == "array") { - $xmlrpc_type = "array"; - $toreturn = array(); - foreach($value as $key => $val) { - if(is_string($key)) $xmlrpc_type = "struct"; - $toreturn[$key] = php_value_to_xmlrpc($val); - } - return new XML_RPC_Value($toreturn, $xmlrpc_type); - } else { - if($force_array == true) { - return new XML_RPC_Value(array(new XML_RPC_Value($value, gettype($value))), "array"); - } else { - return new XML_RPC_Value($value, gettype($value)); - } - } + if (gettype($value) == "array") { + $xmlrpc_type = "array"; + $toreturn = array(); + foreach ($value as $key => $val) { + if (is_string($key)) { + $xmlrpc_type = "struct"; + } + $toreturn[$key] = php_value_to_xmlrpc($val); + } + return new XML_RPC_Value($toreturn, $xmlrpc_type); + } else { + if ($force_array == true) { + return new XML_RPC_Value(array(new XML_RPC_Value($value, gettype($value))), "array"); + } else { + return new XML_RPC_Value($value, gettype($value)); + } + } */ } @@ -114,13 +118,13 @@ function xmlrpc_auth(&$params) { /* XXX: Should clarify from old behaviour what is in params[0] that differs from params['xmlrpcauth'] */ if (isset($config['system']['webgui']['authmode'])) { $authcfg = auth_get_authserver($config['system']['webgui']['authmode']); - if (authenticate_user("admin", $params[0], $authcfg) || - authenticate_user("admin", $params[0])) { + if (authenticate_user("admin", $params[0], $authcfg) || + authenticate_user("admin", $params[0])) { array_shift($params); unset($params['xmlrpcauth']); return true; - } else if (!empty($params['xmlrpcauth']) && (authenticate_user("admin", $params['xmlrpcauth'], $authcfg) || - authenticate_user("admin", $params['xmlrpcauth']))) { + } else if (!empty($params['xmlrpcauth']) && (authenticate_user("admin", $params['xmlrpcauth'], $authcfg) || + authenticate_user("admin", $params['xmlrpcauth']))) { array_shift($params); unset($params['xmlrpcauth']); return true; From e185c5846a35963259e774562982773031cbb174 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Mon, 9 Mar 2015 22:55:18 +0545 Subject: [PATCH 196/257] Pencil symbols These are places in the GUI where the cursor sits not in the far left side of the input box and there is odd-looking white space to the left of the cursor. Normally there would be a little input graphic in the white space to the left of the cursor (a pencil, a computer screen, a lock symbol...) This change makes the pencil be displayed in all those places. --- usr/local/www/diag_dns.php | 2 +- usr/local/www/diag_ping.php | 2 +- usr/local/www/diag_testport.php | 6 +++--- usr/local/www/diag_traceroute.php | 2 +- usr/local/www/firewall_nat_1to1_edit.php | 2 +- usr/local/www/services_rfc2136_edit.php | 2 +- usr/local/www/services_unbound_host_edit.php | 8 ++++---- usr/local/www/services_wol_edit.php | 4 ++-- usr/local/www/status_rrd_graph.php | 4 ++-- 9 files changed, 16 insertions(+), 16 deletions(-) diff --git a/usr/local/www/diag_dns.php b/usr/local/www/diag_dns.php index a4368cdcc7..d99c5ba0b5 100644 --- a/usr/local/www/diag_dns.php +++ b/usr/local/www/diag_dns.php @@ -187,7 +187,7 @@ include("head.inc"); ?>
        " . convert_friendly_interface_to_friendly_descr($carp['interface']) . "@{$vhid}  " . $ipaddress . " 
        + diff --git a/usr/local/www/diag_testport.php b/usr/local/www/diag_testport.php index 8f899a4aca..b64075e158 100644 --- a/usr/local/www/diag_testport.php +++ b/usr/local/www/diag_testport.php @@ -112,18 +112,18 @@ include("head.inc"); ?> + diff --git a/usr/local/www/diag_traceroute.php b/usr/local/www/diag_traceroute.php index ed65f40c54..8cdbf931a6 100644 --- a/usr/local/www/diag_traceroute.php +++ b/usr/local/www/diag_traceroute.php @@ -99,7 +99,7 @@ if (!isset($do_traceroute)) { + diff --git a/usr/local/www/firewall_nat_1to1_edit.php b/usr/local/www/firewall_nat_1to1_edit.php index 6700cd341d..783e4bff05 100644 --- a/usr/local/www/firewall_nat_1to1_edit.php +++ b/usr/local/www/firewall_nat_1to1_edit.php @@ -335,7 +335,7 @@ if ($input_errors) diff --git a/usr/local/www/services_unbound_host_edit.php b/usr/local/www/services_unbound_host_edit.php index b31c7dfd9a..5c20e6ce6b 100644 --- a/usr/local/www/services_unbound_host_edit.php +++ b/usr/local/www/services_unbound_host_edit.php @@ -215,7 +215,7 @@ include("head.inc"); @@ -223,7 +223,7 @@ include("head.inc"); @@ -231,7 +231,7 @@ include("head.inc"); @@ -239,7 +239,7 @@ include("head.inc"); diff --git a/usr/local/www/services_wol_edit.php b/usr/local/www/services_wol_edit.php index 9c232835cd..da43c6f6f5 100644 --- a/usr/local/www/services_wol_edit.php +++ b/usr/local/www/services_wol_edit.php @@ -143,7 +143,7 @@ include("head.inc"); @@ -151,7 +151,7 @@ include("head.inc"); diff --git a/usr/local/www/status_rrd_graph.php b/usr/local/www/status_rrd_graph.php index cd9209d55f..d67ddbebdc 100644 --- a/usr/local/www/status_rrd_graph.php +++ b/usr/local/www/status_rrd_graph.php @@ -568,9 +568,9 @@ function get_dates($curperiod, $graph) { $end_fmt = strftime("%m/%d/%Y %H:%M:%S", $end); ?> - + - + " /> Date: Mon, 9 Mar 2015 18:52:13 +0100 Subject: [PATCH 197/257] Fixes #4446 Correct ipalias removal on top of carp during configuration sync. --- usr/local/www/xmlrpc.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/usr/local/www/xmlrpc.php b/usr/local/www/xmlrpc.php index ec6d458d36..82a900c6a4 100755 --- a/usr/local/www/xmlrpc.php +++ b/usr/local/www/xmlrpc.php @@ -280,7 +280,11 @@ function restore_config_section_xmlrpc($raw_params) { } /* Cleanup remaining old carps */ foreach ($oldvips as $oldvipif => $oldvippar) { - $oldvipif = get_real_interface($oldvippar['interface']); + if (strstr($oldvippar['interface'], '_vip')) { + $oldvipif = explode('_vip', $oldvippar['interface']); + $oldvipif = $oldvipif[0]; + } else + $oldvipif = get_real_interface($oldvippar['interface']); if (!empty($oldvipif)) { if (is_ipaddrv6($oldvipif)) mwexec("/sbin/ifconfig " . escapeshellarg($oldvipif) . " inet6 " . escapeshellarg($oldvipar['subnet']) . " delete"); From 6127c541cc84fab64acc6a447905b11517725086 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Mon, 9 Mar 2015 19:01:40 +0100 Subject: [PATCH 198/257] Revert "Fixes #4446 Correct ipalias removal on top of carp during configuration sync." master works differently and get_real_interface() resolves vips as well. This reverts commit 8896fe1cebdc97dcbeb59249f3bb2abd1601b979. --- usr/local/www/xmlrpc.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/usr/local/www/xmlrpc.php b/usr/local/www/xmlrpc.php index 82a900c6a4..ec6d458d36 100755 --- a/usr/local/www/xmlrpc.php +++ b/usr/local/www/xmlrpc.php @@ -280,11 +280,7 @@ function restore_config_section_xmlrpc($raw_params) { } /* Cleanup remaining old carps */ foreach ($oldvips as $oldvipif => $oldvippar) { - if (strstr($oldvippar['interface'], '_vip')) { - $oldvipif = explode('_vip', $oldvippar['interface']); - $oldvipif = $oldvipif[0]; - } else - $oldvipif = get_real_interface($oldvippar['interface']); + $oldvipif = get_real_interface($oldvippar['interface']); if (!empty($oldvipif)) { if (is_ipaddrv6($oldvipif)) mwexec("/sbin/ifconfig " . escapeshellarg($oldvipif) . " inet6 " . escapeshellarg($oldvipar['subnet']) . " delete"); From 3853b43613835a750f85f54d8df9a12de42fa43c Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Tue, 10 Mar 2015 20:27:11 +0545 Subject: [PATCH 199/257] Fix SNMP Bind Interface list in master The format of the array returned by get_possible_listen_ips() was changed. This use of the returned array was not quite changed correctly. This fixes it so the drop-down list of SNMP Bind Interfaces is displayed correctly. Note that the change to get_possible_listen_ips() (which also moved the function from system.inc to interfaces.inc) and associated effects is only in master. It has not been applied to RELENG_2_2 yet. So this fix is only needed in master. I noticed this when using various files from master on a test system. --- usr/local/www/services_snmp.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/services_snmp.php b/usr/local/www/services_snmp.php index cfdd95851a..d3beb2c6a5 100644 --- a/usr/local/www/services_snmp.php +++ b/usr/local/www/services_snmp.php @@ -425,8 +425,8 @@ function enable_change(whichone) { if ($lip == $pconfig['bindip']) $selected = "selected=\"selected\""; ?> - Date: Tue, 10 Mar 2015 22:55:39 +0545 Subject: [PATCH 200/257] Fix password box cursor position Similar to https://github.com/pfsense/pfsense/commit/dedc40f7ded5f88aee4720aa8a3a57667b975254 The password field shows the little lock icon, but the text input area starts over the top of the icon and as I type in the field the password "dots" go over the lock icon in each of these data entry places. Changing the field name/id to not be "password" but to be "passwordfld", "passwordfld1" "passwordfld2" and the like fixes it. Something does not like the field being called just "password". In interfaces.php I also changed the field "username" to be "ppp_username". This standardized it to work in a similar way to pppoe_username pptp_username fields. It looks easier to understand for me. --- usr/local/www/interfaces.php | 24 ++++++++++++------------ usr/local/www/interfaces_ppps_edit.php | 12 ++++++------ usr/local/www/services_dyndns_edit.php | 6 +++--- usr/local/www/vpn_pptp_users_edit.php | 16 ++++++++-------- 4 files changed, 29 insertions(+), 29 deletions(-) diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 764c962054..be0933062b 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -114,8 +114,8 @@ if ($wancfg['if'] == $a_ppps[$pppid]['if']) { $pconfig['ptpid'] = $a_ppps[$pppid]['ptpid']; $pconfig['port'] = $a_ppps[$pppid]['ports']; if ($a_ppps[$pppid]['type'] == "ppp") { - $pconfig['username'] = $a_ppps[$pppid]['username']; - $pconfig['password'] = base64_decode($a_ppps[$pppid]['password']); + $pconfig['ppp_username'] = $a_ppps[$pppid]['username']; + $pconfig['ppp_password'] = base64_decode($a_ppps[$pppid]['password']); $pconfig['phone'] = $a_ppps[$pppid]['phone']; $pconfig['apn'] = $a_ppps[$pppid]['apn']; @@ -982,8 +982,8 @@ if ($_POST['apply']) { $a_ppps[$pppid]['type'] = $_POST['type']; $a_ppps[$pppid]['if'] = $_POST['type'].$_POST['ptpid']; $a_ppps[$pppid]['ports'] = $_POST['port']; - $a_ppps[$pppid]['username'] = $_POST['username']; - $a_ppps[$pppid]['password'] = base64_encode($_POST['password']); + $a_ppps[$pppid]['username'] = $_POST['ppp_username']; + $a_ppps[$pppid]['password'] = base64_encode($_POST['ppp_password']); $a_ppps[$pppid]['phone'] = $_POST['phone']; $a_ppps[$pppid]['apn'] = $_POST['apn']; $wancfg['if'] = $_POST['type'] . $_POST['ptpid']; @@ -1597,8 +1597,8 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), success: function(data,textStatus,response) { var xmldoc = response.responseXML; var provider = xmldoc.getElementsByTagName('connection')[0]; - jQuery('#username').val(''); - jQuery('#password').val(''); + jQuery('#ppp_username').val(''); + jQuery('#ppp_password').val(''); if(provider.getElementsByTagName('apn')[0].firstChild.data == "CDMA") { jQuery('#phone').val('#777'); jQuery('#apn').val(''); @@ -1606,10 +1606,10 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), jQuery('#phone').val('*99#'); jQuery('#apn').val(provider.getElementsByTagName('apn')[0].firstChild.data); } - username = provider.getElementsByTagName('username')[0].firstChild.data; - password = provider.getElementsByTagName('password')[0].firstChild.data; - jQuery('#username').val(username); - jQuery('#password').val(password); + ppp_username = provider.getElementsByTagName('ppp_username')[0].firstChild.data; + ppp_password = provider.getElementsByTagName('ppp_password')[0].firstChild.data; + jQuery('#ppp_username').val(ppp_username); + jQuery('#ppp_password').val(ppp_password); } }); } @@ -2615,13 +2615,13 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), diff --git a/usr/local/www/interfaces_ppps_edit.php b/usr/local/www/interfaces_ppps_edit.php index cad370891c..77384902d7 100644 --- a/usr/local/www/interfaces_ppps_edit.php +++ b/usr/local/www/interfaces_ppps_edit.php @@ -195,10 +195,10 @@ if ($_POST) { break; case "pppoe": if ($_POST['ondemand']) { - $reqdfields = explode(" ", "interfaces username password ondemand idletimeout"); + $reqdfields = explode(" ", "interfaces username passwordfld ondemand idletimeout"); $reqdfieldsn = array(gettext("Link Interface(s)"),gettext("Username"),gettext("Password"),gettext("Dial on demand"),gettext("Idle timeout value")); } else { - $reqdfields = explode(" ", "interfaces username password"); + $reqdfields = explode(" ", "interfaces username passwordfld"); $reqdfieldsn = array(gettext("Link Interface(s)"),gettext("Username"),gettext("Password")); } do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); @@ -206,10 +206,10 @@ if ($_POST) { case "l2tp": case "pptp": if ($_POST['ondemand']) { - $reqdfields = explode(" ", "interfaces username password localip subnet gateway ondemand idletimeout"); + $reqdfields = explode(" ", "interfaces username passwordfld localip subnet gateway ondemand idletimeout"); $reqdfieldsn = array(gettext("Link Interface(s)"),gettext("Username"),gettext("Password"),gettext("Local IP address"),gettext("Subnet"),gettext("Remote IP address"),gettext("Dial on demand"),gettext("Idle timeout value")); } else { - $reqdfields = explode(" ", "interfaces username password localip subnet gateway"); + $reqdfields = explode(" ", "interfaces username passwordfld localip subnet gateway"); $reqdfieldsn = array(gettext("Link Interface(s)"),gettext("Username"),gettext("Password"),gettext("Local IP address"),gettext("Subnet"),gettext("Remote IP address")); } do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); @@ -276,7 +276,7 @@ if ($_POST) { $ppp['if'] = $ppp['type'].$ppp['ptpid']; $ppp['ports'] = implode(',',$_POST['interfaces']); $ppp['username'] = $_POST['username']; - $ppp['password'] = base64_encode($_POST['password']); + $ppp['password'] = base64_encode($_POST['passwordfld']); $ppp['ondemand'] = $_POST['ondemand'] ? true : false; if (!empty($_POST['idletimeout'])) $ppp['idletimeout'] = $_POST['idletimeout']; @@ -528,7 +528,7 @@ $types = array("select" => gettext("Select"), "ppp" => "PPP", "pppoe" => "PPPoE" diff --git a/usr/local/www/services_dyndns_edit.php b/usr/local/www/services_dyndns_edit.php index 80d1743f51..aa2bf43201 100644 --- a/usr/local/www/services_dyndns_edit.php +++ b/usr/local/www/services_dyndns_edit.php @@ -100,7 +100,7 @@ if ($_POST) { if ($pconfig['type'] != "custom" && $pconfig['type'] != "custom-v6") { $reqdfields[] = "host"; $reqdfieldsn[] = gettext("Hostname"); - $reqdfields[] = "password"; + $reqdfields[] = "passwordfld"; $reqdfieldsn[] = gettext("Password"); $reqdfields[] = "username"; $reqdfieldsn[] = gettext("Username"); @@ -133,7 +133,7 @@ if ($_POST) { $dyndns = array(); $dyndns['type'] = $_POST['type']; $dyndns['username'] = $_POST['username']; - $dyndns['password'] = $_POST['password']; + $dyndns['password'] = $_POST['passwordfld']; $dyndns['host'] = $_POST['host']; $dyndns['mx'] = $_POST['mx']; $dyndns['wildcard'] = $_POST['wildcard'] ? true : false; @@ -370,7 +370,7 @@ function _onTypeChange(type){ From 0a0978d78fffde2f9b020b6f687e4fdfee60acd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Tue, 10 Mar 2015 21:45:03 +0100 Subject: [PATCH 201/257] Fixes #4427 Correct traffic shaper wizard to properly save and use Voip provided settings --- usr/local/www/wizards/traffic_shaper_wizard_multi_all.inc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/usr/local/www/wizards/traffic_shaper_wizard_multi_all.inc b/usr/local/www/wizards/traffic_shaper_wizard_multi_all.inc index 9fc4f08adf..b16d897f9c 100644 --- a/usr/local/www/wizards/traffic_shaper_wizard_multi_all.inc +++ b/usr/local/www/wizards/traffic_shaper_wizard_multi_all.inc @@ -532,8 +532,8 @@ function step3_stepsubmitphpaction() { if (!$_POST['enable']) return; - if($_POST['address']) { - if(!is_ipaddroralias($_POST['address'])) { + if($_POST['upstream_sip_server']) { + if(!is_ipaddroralias($_POST['upstream_sip_server'])) { /* item is not an ip or alias. error out */ $savemsg=gettext("Address must be a valid IP address or Firewall Alias. Please correct this value to continue."); $stepid--; @@ -603,6 +603,10 @@ function step3_stepsubmitphpaction() { unset($config['ezshaper']['step3']); $config['ezshaper']['step3'] = array(); + if (!empty($_POST['upstream_sip_server'])) + $config['ezshaper']['step3']['address'] = $_POST['upstream_sip_server']; + if ($_POST['enable'] == 'on') + $config['ezshaper']['step3']['enable'] = 'on'; for ($i = 0; $i < $localint; $i++) { $config['ezshaper']['step3']["local{$i}download"] = $_POST["local{$i}download"]; $config['ezshaper']['step3']["local{$i}downloadspeed"] = $_POST["local{$i}downloadspeed"]; From 30ea15dc6337b0907c2401b11dbe66216f081e62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ermal=20LU=C3=87I?= Date: Tue, 10 Mar 2015 21:46:53 +0100 Subject: [PATCH 202/257] Fixes #4427 Correct traffic shaper wizard to properly save and use Voip provided settings --- usr/local/www/wizards/traffic_shaper_wizard_dedicated.inc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/usr/local/www/wizards/traffic_shaper_wizard_dedicated.inc b/usr/local/www/wizards/traffic_shaper_wizard_dedicated.inc index 9c006c86c3..b2f5ed9a40 100644 --- a/usr/local/www/wizards/traffic_shaper_wizard_dedicated.inc +++ b/usr/local/www/wizards/traffic_shaper_wizard_dedicated.inc @@ -489,8 +489,8 @@ function step3_stepsubmitphpaction() { if (!$_POST['enable']) return; - if($_POST['address']) { - if(!is_ipaddroralias($_POST['address'])) { + if($_POST['upstream_sip_server']) { + if(!is_ipaddroralias($_POST['upstream_sip_server'])) { /* item is not an ip or alias. error out */ $savemsg=gettext("Address must be a valid IP address or Firewall Alias. Please correct this value to continue."); $stepid--; @@ -555,6 +555,10 @@ function step3_stepsubmitphpaction() { unset($config['ezshaper']['step3']); $config['ezshaper']['step3'] = array(); + if (!empty($_POST['upstream_sip_server'])) + $config['ezshaper']['step3']['address'] = $_POST['upstream_sip_server']; + if ($_POST['enable'] == 'on') + $config['ezshaper']['step3']['enable'] = 'on'; for ($i = 0; $i < $steps; $i++) { $config['ezshaper']['step3']["local{$i}download"] = $_POST["local{$i}download"]; $config['ezshaper']['step3']["local{$i}downloadspeed"] = $_POST["local{$i}downloadspeed"]; From 24acc8f4668d23bd4a0cd515c6e1de84affd6069 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Tue, 10 Mar 2015 17:17:10 -0500 Subject: [PATCH 203/257] Don't enable interfaces_use by default. Add checkbox to enable on Advanced tab, in case there are scenarios where it's desirable. Ticket #4341 --- etc/inc/vpn.inc | 8 ++++++-- usr/local/www/vpn_ipsec_settings.php | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index a148d0e116..9c1e6db218 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -342,8 +342,12 @@ function vpn_ipsec_configure($restart = false) $unity_enabled = 'no'; } - if (!empty($ifacesuse)) { - $ifacesuse = 'interfaces_use = ' . implode(',', array_unique($ifacesuse)); + if (isset($config['ipsec']['enableinterfacesuse'])) { + if (!empty($ifacesuse)) { + $ifacesuse = 'interfaces_use = ' . implode(',', array_unique($ifacesuse)); + } else { + $ifacesuse = ''; + } } else { $ifacesuse = ''; } diff --git a/usr/local/www/vpn_ipsec_settings.php b/usr/local/www/vpn_ipsec_settings.php index 39c1862b66..c944ef77ee 100644 --- a/usr/local/www/vpn_ipsec_settings.php +++ b/usr/local/www/vpn_ipsec_settings.php @@ -47,6 +47,7 @@ foreach ($ipsec_loglevels as $lkey => $ldescr) { } $pconfig['unityplugin'] = isset($config['ipsec']['unityplugin']); $pconfig['compression'] = isset($config['ipsec']['compression']); +$pconfig['enableinterfacesuse'] = isset($config['ipsec']['enableinterfacesuse']); $pconfig['acceptunencryptedmainmode'] = isset($config['ipsec']['acceptunencryptedmainmode']); $pconfig['maxmss_enable'] = isset($config['system']['maxmss_enable']); $pconfig['maxmss'] = $config['system']['maxmss']; @@ -134,6 +135,15 @@ if ($_POST) { $needsrestart = true; unset($config['ipsec']['compression']); } + + if($_POST['enableinterfacesuse'] == "yes") { + if (!isset($config['ipsec']['enableinterfacesuse'])) + $needsrestart = true; + $config['ipsec']['enableinterfacesuse'] = true; + } elseif (isset($config['ipsec']['enableinterfacesuse'])) { + $needsrestart = true; + unset($config['ipsec']['enableinterfacesuse']); + } if($_POST['unityplugin'] == "yes") { if (!isset($config['ipsec']['unityplugin'])) @@ -295,6 +305,15 @@ function maxmss_checked(obj) { + + + + From 23645bf703578919ba52e857ed2e221db08ef61a Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Tue, 10 Mar 2015 11:13:44 -0300 Subject: [PATCH 210/257] Enable beast protection by default for new installations, there is a code in place to disable it when a hifn card is present --- conf.default/config.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/conf.default/config.xml b/conf.default/config.xml index 6a6da59da5..8bf9299a4a 100644 --- a/conf.default/config.xml +++ b/conf.default/config.xml @@ -41,6 +41,7 @@ https + yes From 05036071e21b31a97fa9d0ac8b38d7abaa3af0d3 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 11 Mar 2015 09:44:27 -0300 Subject: [PATCH 211/257] Disable SNMP hostres module on APU boards until we figure out why it's crashing on this specific board. Ticket #4403 --- etc/inc/services.inc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/etc/inc/services.inc b/etc/inc/services.inc index a3e584260b..a1521a3f27 100644 --- a/etc/inc/services.inc +++ b/etc/inc/services.inc @@ -2272,12 +2272,17 @@ begemotSnmpdModulePath."pf" = "/usr/lib/snmp_pf.so" EOD; } - if (isset($config['snmpd']['modules']['hostres'])) { + /* XXX: hostres module crashes APU - ticket #4403 */ + $specplatform = system_identify_specific_platform(); + if (isset($config['snmpd']['modules']['hostres']) && + $specplatform['name'] != 'APU') { $snmpdconf .= << Date: Wed, 11 Mar 2015 10:07:25 -0300 Subject: [PATCH 212/257] Add a log message when hostres SNMP module is ignored on APU boards --- etc/inc/services.inc | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/etc/inc/services.inc b/etc/inc/services.inc index a1521a3f27..c3e2fe2296 100644 --- a/etc/inc/services.inc +++ b/etc/inc/services.inc @@ -2272,16 +2272,19 @@ begemotSnmpdModulePath."pf" = "/usr/lib/snmp_pf.so" EOD; } - /* XXX: hostres module crashes APU - ticket #4403 */ - $specplatform = system_identify_specific_platform(); - if (isset($config['snmpd']['modules']['hostres']) && - $specplatform['name'] != 'APU') { - $snmpdconf .= << Date: Wed, 11 Mar 2015 13:51:28 -0300 Subject: [PATCH 213/257] Remove double // on config tag Spotted by: BBCan177 --- conf.default/config.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conf.default/config.xml b/conf.default/config.xml index 8bf9299a4a..8cb688a7ec 100644 --- a/conf.default/config.xml +++ b/conf.default/config.xml @@ -41,7 +41,7 @@ https - + yes From 87bf8d4d0eaa358c6dbac9aa54ca64f69a2bbef9 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 11 Mar 2015 13:55:39 -0300 Subject: [PATCH 214/257] Revert "Remove double // on config tag" This reverts commit 8df86e1fc6cb5a8b0d39bfe7f790c6df6dede222. --- conf.default/config.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conf.default/config.xml b/conf.default/config.xml index 8cb688a7ec..8bf9299a4a 100644 --- a/conf.default/config.xml +++ b/conf.default/config.xml @@ -41,7 +41,7 @@ https - + yes From e75c2bf512288999b83b2ffe83e2b0cc4d7d2e8e Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 11 Mar 2015 13:55:42 -0300 Subject: [PATCH 215/257] Revert "Enable beast protection by default for new installations, there is a code in place to disable it when a hifn card is present" This reverts commit 23645bf703578919ba52e857ed2e221db08ef61a. --- conf.default/config.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/conf.default/config.xml b/conf.default/config.xml index 8bf9299a4a..6a6da59da5 100644 --- a/conf.default/config.xml +++ b/conf.default/config.xml @@ -41,7 +41,6 @@ https - yes From 3a0a59c812f5719ff672c52f0f77c699513b713f Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 11 Mar 2015 14:03:29 -0300 Subject: [PATCH 216/257] Remove BEAST protection option since default cipher is now good and works with hifn cards --- etc/inc/system.inc | 22 ++------------- usr/local/www/system_advanced_admin.php | 37 ------------------------- 2 files changed, 2 insertions(+), 57 deletions(-) diff --git a/etc/inc/system.inc b/etc/inc/system.inc index 03f18a11d8..1cfdfb59ce 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -1461,28 +1461,10 @@ EOD; $lighty_config .= "ssl.use-sslv2 = \"disable\"\n"; $lighty_config .= "ssl.use-sslv3 = \"disable\"\n"; - /* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */ - $fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r"); - if ($fd) { - while (!feof($fd)) { - $dmesgl = fgets($fd); - if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) { - unset($config['system']['webgui']['beast_protection']); - log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")"); - break; - } - } - fclose($fd); - } - // where ssl.cipher-list is set, this is automatically enabled, but set it explicitly anyway. $lighty_config .= "ssl.honor-cipher-order = \"enable\"\n"; - - if (isset($config['system']['webgui']['beast_protection'])) { - $lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n"; - } else { - $lighty_config .= "ssl.cipher-list = \"AES128+EECDH:AES256+EECDH:AES128+EDH:AES256+EDH:AES128-SHA:AES256-SHA:!aNULL:!eNULL:!DSS\"\n"; - } + + $lighty_config .= "ssl.cipher-list = \"AES128+EECDH:AES256+EECDH:AES128+EDH:AES256+EDH:AES128-SHA:AES256-SHA:!aNULL:!eNULL:!DSS\"\n"; if (!(empty($ca) || (strlen(trim($ca)) == 0))) { $lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n"; diff --git a/usr/local/www/system_advanced_admin.php b/usr/local/www/system_advanced_admin.php index 11dc9814ef..36eb7a36bd 100644 --- a/usr/local/www/system_advanced_admin.php +++ b/usr/local/www/system_advanced_admin.php @@ -58,7 +58,6 @@ $pconfig['disableconsolemenu'] = isset($config['system']['disableconsolemenu']); $pconfig['noantilockout'] = isset($config['system']['webgui']['noantilockout']); $pconfig['nodnsrebindcheck'] = isset($config['system']['webgui']['nodnsrebindcheck']); $pconfig['nohttpreferercheck'] = isset($config['system']['webgui']['nohttpreferercheck']); -$pconfig['beast_protection'] = isset($config['system']['webgui']['beast_protection']); $pconfig['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']); $pconfig['loginautocomplete'] = isset($config['system']['webgui']['loginautocomplete']); $pconfig['althostnames'] = $config['system']['webgui']['althostnames']; @@ -171,11 +170,6 @@ if ($_POST) { else unset($config['system']['webgui']['nohttpreferercheck']); - if ($_POST['beast_protection'] == "yes") - $config['system']['webgui']['beast_protection'] = true; - else - unset($config['system']['webgui']['beast_protection']); - if ($_POST['pagenamefirst'] == "yes") $config['system']['webgui']['pagenamefirst'] = true; else @@ -257,21 +251,6 @@ if ($_POST) { } } -unset($hwcrypto); -$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r"); -if ($fd) { - while (!feof($fd)) { - $dmesgl = fgets($fd); - if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches)) { - unset($pconfig['beast_protection']); - $disable_beast_option = "disabled"; - $hwcrypto = $matches[1]; - break; - } - } - fclose($fd); -} - $pgtitle = array(gettext("System"),gettext("Advanced: Admin Access")); include("head.inc"); @@ -487,22 +466,6 @@ function prot_change() { "webConfigurator access in certain corner cases such as using external scripts to interact with this system. More information on HTTP_REFERER is available from Wikipedia."); ?> - - - - + + + + + + + +
        + + + + + + + + + + + + + + + + - From 04bbb3a588bcab2cebb159f635d85836b0dbaea5 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 11 Mar 2015 14:59:42 -0300 Subject: [PATCH 219/257] Revert "Use a consistent variable name here. related to Ticket #4446" This reverts commit 309162b96d6ad0db09c132cc0aabc890bfe1909f. --- usr/local/www/xmlrpc.php | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/usr/local/www/xmlrpc.php b/usr/local/www/xmlrpc.php index 13e98ff787..ec6d458d36 100755 --- a/usr/local/www/xmlrpc.php +++ b/usr/local/www/xmlrpc.php @@ -279,12 +279,8 @@ function restore_config_section_xmlrpc($raw_params) { } } /* Cleanup remaining old carps */ - foreach ($oldvips as $oldvipif => $oldvipar) { - if (strstr($oldvipar['interface'], '_vip')) { - $oldvipif = explode('_vip', $oldvipar['interface']); - $oldvipif = $oldvipif[0]; - } else - $oldvipif = get_real_interface($oldvipar['interface']); + foreach ($oldvips as $oldvipif => $oldvippar) { + $oldvipif = get_real_interface($oldvippar['interface']); if (!empty($oldvipif)) { if (is_ipaddrv6($oldvipif)) mwexec("/sbin/ifconfig " . escapeshellarg($oldvipif) . " inet6 " . escapeshellarg($oldvipar['subnet']) . " delete"); From c14781e3c07dd9f82c0f0445eb5eed6c8fdb98ac Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 11 Mar 2015 16:00:01 -0300 Subject: [PATCH 220/257] Save vip interface and subnet to use to delete old vips from secondary nodes. Fixes #4446 --- usr/local/www/xmlrpc.php | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/usr/local/www/xmlrpc.php b/usr/local/www/xmlrpc.php index ec6d458d36..796701405c 100755 --- a/usr/local/www/xmlrpc.php +++ b/usr/local/www/xmlrpc.php @@ -211,12 +211,17 @@ function restore_config_section_xmlrpc($raw_params) { if (isset($params[0]['virtualip'])) { if (is_array($config['virtualip']['vip'])) { foreach ($config['virtualip']['vip'] as $vipindex => $vip) { - if ($vip['mode'] == "carp") - $oldvips["{$vip['interface']}_vip{$vip['vhid']}"] = "{$vip['password']}{$vip['advskew']}{$vip['subnet']}{$vip['subnet_bits']}{$vip['advbase']}"; - else if ($vip['mode'] == "ipalias" && (substr($vip['interface'], 0, 4) == '_vip') || strpos($vip['interface'], "lo0")) - $oldvips[$vip['subnet']] = "{$vip['interface']}{$vip['subnet']}{$vip['subnet_bits']}"; - else if (($vip['mode'] == "ipalias" || $vip['mode'] == 'proxyarp') && !(substr($vip['interface'], 0, 4) == '_vip') || strpos($vip['interface'], "lo0")) + if ($vip['mode'] == "carp") { + $oldvips["{$vip['interface']}_vip{$vip['vhid']}"]['content'] = "{$vip['password']}{$vip['advskew']}{$vip['subnet']}{$vip['subnet_bits']}{$vip['advbase']}"; + $oldvips["{$vip['interface']}_vip{$vip['vhid']}"]['interface'] = $vip['interface']; + $oldvips["{$vip['interface']}_vip{$vip['vhid']}"]['subnet'] = $vip['subnet']; + } else if ($vip['mode'] == "ipalias" && (substr($vip['interface'], 0, 4) == '_vip' || strpos($vip['interface'], "lo0"))) { + $oldvips[$vip['subnet']]['content'] = "{$vip['interface']}{$vip['subnet']}{$vip['subnet_bits']}"; + $oldvips[$vip['subnet']]['interface'] = $vip['interface']; + $oldvips[$vip['subnet']]['subnet'] = $vip['subnet']; + } else if (($vip['mode'] == "ipalias" || $vip['mode'] == 'proxyarp') && !(substr($vip['interface'], 0, 4) == '_vip') || strpos($vip['interface'], "lo0")) { $vipbackup[] = $vip; + } } } } @@ -247,7 +252,7 @@ function restore_config_section_xmlrpc($raw_params) { $anyproxyarp = false; foreach ($config['virtualip']['vip'] as $vip) { if ($vip['mode'] == "carp" && isset($oldvips["{$vip['interface']}_vip{$vip['vhid']}"])) { - if ($oldvips["{$vip['interface']}_vip{$vip['vhid']}"] == "{$vip['password']}{$vip['advskew']}{$vip['subnet']}{$vip['subnet_bits']}{$vip['advbase']}") { + if ($oldvips["{$vip['interface']}_vip{$vip['vhid']}"]['content'] == "{$vip['password']}{$vip['advskew']}{$vip['subnet']}{$vip['subnet_bits']}{$vip['advbase']}") { if (does_vip_exist($vip)) { unset($oldvips["{$vip['interface']}_vip{$vip['vhid']}"]); continue; // Skip reconfiguring this vips since nothing has changed. @@ -255,7 +260,7 @@ function restore_config_section_xmlrpc($raw_params) { } unset($oldvips["{$vip['interface']}_vip{$vip['vhid']}"]); } else if ($vip['mode'] == "ipalias" && strstr($vip['interface'], "_vip") && isset($oldvips[$vip['subnet']])) { - if ($oldvips[$vip['subnet']] == "{$vip['interface']}{$vip['subnet']}{$vip['subnet_bits']}") { + if ($oldvips[$vip['subnet']]['content'] == "{$vip['interface']}{$vip['subnet']}{$vip['subnet_bits']}") { if (does_vip_exist($vip)) { unset($oldvips[$vip['subnet']]); continue; // Skip reconfiguring this vips since nothing has changed. @@ -279,8 +284,8 @@ function restore_config_section_xmlrpc($raw_params) { } } /* Cleanup remaining old carps */ - foreach ($oldvips as $oldvipif => $oldvippar) { - $oldvipif = get_real_interface($oldvippar['interface']); + foreach ($oldvips as $oldvipar) { + $oldvipif = get_real_interface($oldvipar['interface']); if (!empty($oldvipif)) { if (is_ipaddrv6($oldvipif)) mwexec("/sbin/ifconfig " . escapeshellarg($oldvipif) . " inet6 " . escapeshellarg($oldvipar['subnet']) . " delete"); From 830ceadf0225bfcd0a2c98fb8091e7deefa6dc8a Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 11 Mar 2015 17:46:54 -0300 Subject: [PATCH 221/257] Remove -U from mtree call used to restore files permissions, this is replacing symlink targets by the old values. Ticket #4328 --- etc/rc.firmware | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/rc.firmware b/etc/rc.firmware index bde99dbca6..8d87a776bc 100755 --- a/etc/rc.firmware +++ b/etc/rc.firmware @@ -66,7 +66,7 @@ backup_chflags() { restore_chflags() { TOPROCESS="bin lib libexec sbin usr" for files in $TOPROCESS; do - cd / && /usr/bin/bzcat /tmp/chflags.dist.${files}.bz2 | /usr/sbin/mtree -PU -p /${files} >> /conf/upgrade_log.txt 2>&1 + cd / && /usr/bin/bzcat /tmp/chflags.dist.${files}.bz2 | /usr/sbin/mtree -P -p /${files} >> /conf/upgrade_log.txt 2>&1 done } From 02acc7afdf137d2da969f120e7318584e58c7993 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 11 Mar 2015 19:14:16 -0300 Subject: [PATCH 222/257] Detect when broken rc.firmware is running, fix it and restart. This should fix #4328 --- tmp/pre_upgrade_command | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tmp/pre_upgrade_command b/tmp/pre_upgrade_command index d1461875a5..2bcdfb23d9 100644 --- a/tmp/pre_upgrade_command +++ b/tmp/pre_upgrade_command @@ -21,6 +21,27 @@ if [ "${PRIOR_VERSION}" = "8" ] && grep -q 'sh /etc/rc.reboot' /etc/rc.firmware; kill ${PID} >/dev/null 2>&1 kill -9 ${PID} >/dev/null 2>&1 sed -i '' -e 's,sh /,/tmp/sh.old /,' /etc/rc.firmware + # To avoid restarting rc.firmware twice because of #4328 + sed -i '' -e '/^restore_chflags()/, /^}/ s/mtree *-PU/mtree -P/' /etc/rc.firmware + /etc/rc.firmware pfSenseupgrade "${IMG}" + exit + fi +fi + +# One more hack to workaround #4328 +if grep -q 'mtree *-PU' /etc/rc.firmware; then + PROC=$(ps axwww | grep '/etc/rc.firmware *pfSenseupgrade') + PID='' + IMG='' + if [ -n "${PROC}" ]; then + PID=$(echo "${PROC}" | awk '{print $1}') + IMG=$(echo "${PROC}" | sed 's,^.*pfSenseupgrade *,,') + fi + + if [ -n "${PID}" -a -n "${IMG}" -a -f "${IMG}" ]; then + kill ${PID} >/dev/null 2>&1 + kill -9 ${PID} >/dev/null 2>&1 + sed -i '' -e '/^restore_chflags()/, /^}/ s/mtree *-PU/mtree -P/' /etc/rc.firmware /etc/rc.firmware pfSenseupgrade "${IMG}" exit fi From 214c81026b6b13dc750ac971afce975117b6c493 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 11 Mar 2015 20:54:53 -0300 Subject: [PATCH 223/257] Proper fix #4443, do not unset carp entry when content differ, also set correct real interface and use subnet to check IP protocol --- usr/local/www/xmlrpc.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/usr/local/www/xmlrpc.php b/usr/local/www/xmlrpc.php index 796701405c..a11ad5fcde 100755 --- a/usr/local/www/xmlrpc.php +++ b/usr/local/www/xmlrpc.php @@ -258,7 +258,6 @@ function restore_config_section_xmlrpc($raw_params) { continue; // Skip reconfiguring this vips since nothing has changed. } } - unset($oldvips["{$vip['interface']}_vip{$vip['vhid']}"]); } else if ($vip['mode'] == "ipalias" && strstr($vip['interface'], "_vip") && isset($oldvips[$vip['subnet']])) { if ($oldvips[$vip['subnet']]['content'] == "{$vip['interface']}{$vip['subnet']}{$vip['subnet_bits']}") { if (does_vip_exist($vip)) { @@ -287,7 +286,7 @@ function restore_config_section_xmlrpc($raw_params) { foreach ($oldvips as $oldvipar) { $oldvipif = get_real_interface($oldvipar['interface']); if (!empty($oldvipif)) { - if (is_ipaddrv6($oldvipif)) + if (is_ipaddrv6($oldvipar['subnet'])) mwexec("/sbin/ifconfig " . escapeshellarg($oldvipif) . " inet6 " . escapeshellarg($oldvipar['subnet']) . " delete"); else pfSense_interface_deladdress($oldvipif, $oldvipar['subnet']); From a2c2c3b4b3e8325d6d5c0f207084a165c87052f1 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 12 Mar 2015 06:29:22 +0545 Subject: [PATCH 224/257] White space in filter.inc --- etc/inc/filter.inc | 90 +++++++++++++++++++++++----------------------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index a58d514dea..93901e86a3 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -306,58 +306,58 @@ function filter_configure_sync($delete_states_if_needed = true) { } else { $limitrules .= "set optimization normal\n"; } - + $timeoutlist = ""; - if (isset($config['system']['tcpfirsttimeout']) && is_numericint($config['system']['tcpfirsttimeout'])) { - $timeoutlist .= " tcp.first {$config['system']['tcpfirsttimeout']} "; - } - if (isset($config['system']['tcpopeningtimeout']) && is_numericint($config['system']['tcpopeningtimeout'])) { - $timeoutlist .= " tcp.opening {$config['system']['tcpopeningtimeout']} "; - } - if (isset($config['system']['tcpestablishedtimeout']) && is_numericint($config['system']['tcpestablishedtimeout'])) { - $timeoutlist .= " tcp.established {$config['system']['tcpestablishedtimeout']} "; - } - if (isset($config['system']['tcpclosingtimeout']) && is_numericint($config['system']['tcpclosingtimeout'])) { - $timeoutlist .= " tcp.closing {$config['system']['tcpclosingtimeout']} "; - } - if (isset($config['system']['tcpfinwaittimeout']) && is_numericint($config['system']['tcpfinwaittimeout'])) { - $timeoutlist .= " tcp.finwait {$config['system']['tcpfinwaittimeout']} "; - } - if (isset($config['system']['tcpclosedtimeout']) && is_numericint($config['system']['tcpclosedtimeout'])) { - $timeoutlist .= " tcp.closed {$config['system']['tcpclosedtimeout']} "; - } - if (isset($config['system']['udpfirsttimeout']) && is_numericint($config['system']['udpfirsttimeout'])) { - $timeoutlist .= " udp.first {$config['system']['udpfirsttimeout']} "; - } - if (isset($config['system']['udpsingletimeout']) && is_numericint($config['system']['udpsingletimeout'])) { - $timeoutlist .= " udp.single {$config['system']['udpsingletimeout']} "; - } - if (isset($config['system']['udpmultipletimeout']) && is_numericint($config['system']['udpmultipletimeout'])) { - $timeoutlist .= " udp.multiple {$config['system']['udpmultipletimeout']} "; - } - if (isset($config['system']['icmpfirsttimeout']) && is_numericint($config['system']['icmpfirsttimeout'])) { - $timeoutlist .= " icmp.first {$config['system']['icmpfirsttimeout']} "; - } - if (isset($config['system']['icmperrortimeout']) && is_numericint($config['system']['icmperrortimeout'])) { - $timeoutlist .= " icmp.error {$config['system']['icmperrortimeout']} "; - } - if (isset($config['system']['otherfirsttimeout']) && is_numericint($config['system']['otherfirsttimeout'])) { - $timeoutlist .= " other.first {$config['system']['otherfirsttimeout']} "; - } - if (isset($config['system']['othersingletimeout']) && is_numericint($config['system']['othersingletimeout'])) { - $timeoutlist .= " other.single {$config['system']['othersingletimeout']} "; - } - if (isset($config['system']['othermultipletimeout']) && is_numericint($config['system']['othermultipletimeout'])) { - $timeoutlist .= " other.multiple {$config['system']['othermultipletimeout']} "; - } - + if (isset($config['system']['tcpfirsttimeout']) && is_numericint($config['system']['tcpfirsttimeout'])) { + $timeoutlist .= " tcp.first {$config['system']['tcpfirsttimeout']} "; + } + if (isset($config['system']['tcpopeningtimeout']) && is_numericint($config['system']['tcpopeningtimeout'])) { + $timeoutlist .= " tcp.opening {$config['system']['tcpopeningtimeout']} "; + } + if (isset($config['system']['tcpestablishedtimeout']) && is_numericint($config['system']['tcpestablishedtimeout'])) { + $timeoutlist .= " tcp.established {$config['system']['tcpestablishedtimeout']} "; + } + if (isset($config['system']['tcpclosingtimeout']) && is_numericint($config['system']['tcpclosingtimeout'])) { + $timeoutlist .= " tcp.closing {$config['system']['tcpclosingtimeout']} "; + } + if (isset($config['system']['tcpfinwaittimeout']) && is_numericint($config['system']['tcpfinwaittimeout'])) { + $timeoutlist .= " tcp.finwait {$config['system']['tcpfinwaittimeout']} "; + } + if (isset($config['system']['tcpclosedtimeout']) && is_numericint($config['system']['tcpclosedtimeout'])) { + $timeoutlist .= " tcp.closed {$config['system']['tcpclosedtimeout']} "; + } + if (isset($config['system']['udpfirsttimeout']) && is_numericint($config['system']['udpfirsttimeout'])) { + $timeoutlist .= " udp.first {$config['system']['udpfirsttimeout']} "; + } + if (isset($config['system']['udpsingletimeout']) && is_numericint($config['system']['udpsingletimeout'])) { + $timeoutlist .= " udp.single {$config['system']['udpsingletimeout']} "; + } + if (isset($config['system']['udpmultipletimeout']) && is_numericint($config['system']['udpmultipletimeout'])) { + $timeoutlist .= " udp.multiple {$config['system']['udpmultipletimeout']} "; + } + if (isset($config['system']['icmpfirsttimeout']) && is_numericint($config['system']['icmpfirsttimeout'])) { + $timeoutlist .= " icmp.first {$config['system']['icmpfirsttimeout']} "; + } + if (isset($config['system']['icmperrortimeout']) && is_numericint($config['system']['icmperrortimeout'])) { + $timeoutlist .= " icmp.error {$config['system']['icmperrortimeout']} "; + } + if (isset($config['system']['otherfirsttimeout']) && is_numericint($config['system']['otherfirsttimeout'])) { + $timeoutlist .= " other.first {$config['system']['otherfirsttimeout']} "; + } + if (isset($config['system']['othersingletimeout']) && is_numericint($config['system']['othersingletimeout'])) { + $timeoutlist .= " other.single {$config['system']['othersingletimeout']} "; + } + if (isset($config['system']['othermultipletimeout']) && is_numericint($config['system']['othermultipletimeout'])) { + $timeoutlist .= " other.multiple {$config['system']['othermultipletimeout']} "; + } + if ($timeoutlist <> "") { $limitrules .= "set timeout { $timeoutlist }\n"; } if (!empty($config['system']['adaptivestart']) && !empty($config['system']['adaptiveend'])) { $limitrules .= "set timeout { adaptive.start {$config['system']['adaptivestart']}, adaptive.end {$config['system']['adaptiveend']} }\n"; - } + } if ($config['system']['maximumstates'] <> "" && is_numeric($config['system']['maximumstates'])) { /* User defined maximum states in Advanced menu. */ From c014babde0e09248d235be93c74bae98d38cebf3 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 11 Mar 2015 20:38:57 -0500 Subject: [PATCH 225/257] Move libstrongswan-unity.so when Unity plugin is disabled so it can't modify the P2. Workaround for Ticket #4178 --- etc/inc/vpn.inc | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index eda11be995..3bc4d70a88 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -340,6 +340,15 @@ function vpn_ipsec_configure($restart = false) $unity_enabled = 'yes'; if (isset($config['ipsec']['unityplugin'])) { $unity_enabled = 'no'; + if (file_exists("/usr/local/lib/ipsec/plugins/libstrongswan-unity.so")) { + conf_mount_rw(); + mwexec("mv /usr/local/lib/ipsec/plugins/libstrongswan-unity.so /usr/local/lib/ipsec/plugins/libstrongswan-unity.MOVED"); + conf_mount_ro(); + } + } else if (file_exists("/usr/local/lib/ipsec/plugins/libstrongswan-unity.MOVED")) { + conf_mount_rw(); + mwexec("mv /usr/local/lib/ipsec/plugins/libstrongswan-unity.MOVED /usr/local/lib/ipsec/plugins/libstrongswan-unity.so"); + conf_mount_ro(); } if (isset($config['ipsec']['enableinterfacesuse'])) { From b8c3654c3fa14b72e18eeed3afc546c6b5c59d86 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 11 Mar 2015 22:00:43 -0500 Subject: [PATCH 226/257] clean up unique IDs text a bit. --- usr/local/www/vpn_ipsec_settings.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/vpn_ipsec_settings.php b/usr/local/www/vpn_ipsec_settings.php index c944ef77ee..6f49c7896f 100644 --- a/usr/local/www/vpn_ipsec_settings.php +++ b/usr/local/www/vpn_ipsec_settings.php @@ -276,7 +276,7 @@ function maxmss_checked(obj) { From 486d7278481b1f4d61c28d18ab5ba164ab5e9c70 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 00:09:28 -0500 Subject: [PATCH 227/257] Fix IPsec on CARP IPs, broken when fixing IPsec with gateway groups and VIPs. --- etc/inc/ipsec.inc | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/etc/inc/ipsec.inc b/etc/inc/ipsec.inc index bbc5ac2647..b014b35755 100644 --- a/etc/inc/ipsec.inc +++ b/etc/inc/ipsec.inc @@ -193,12 +193,16 @@ function ipsec_get_phase1_src(& $ph1ent) { if ($ph1ent['interface']) { if (!is_ipaddr($ph1ent['interface'])) { + if (strpos($ph1ent['interface'], '_vip')) { + $if = $ph1ent['interface']; + } else { $if = get_failover_interface($ph1ent['interface']); - if ($ph1ent['protocol'] == "inet6") { - $interfaceip = get_interface_ipv6($if); - } else { - $interfaceip = get_interface_ip($if); - } + } + if ($ph1ent['protocol'] == "inet6") { + $interfaceip = get_interface_ipv6($if); + } else { + $interfaceip = get_interface_ip($if); + } } else { $interfaceip=$ph1ent['interface']; } From 524a0140260c2abb65b7d0b19700c49faea0aedf Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 00:52:12 -0500 Subject: [PATCH 228/257] use-compression is no longer a valid config option in lighttpd, it can't be enabled. This just throws an error in the log, remove it. --- etc/inc/system.inc | 3 --- 1 file changed, 3 deletions(-) diff --git a/etc/inc/system.inc b/etc/inc/system.inc index 3d032d4f68..1cfdfb59ce 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -1464,9 +1464,6 @@ EOD; // where ssl.cipher-list is set, this is automatically enabled, but set it explicitly anyway. $lighty_config .= "ssl.honor-cipher-order = \"enable\"\n"; - // Explicit disable compression to mitigate CRIME attack - $lighty_config .= "ssl.use-compression = \"disable\"\n"; - $lighty_config .= "ssl.cipher-list = \"AES128+EECDH:AES256+EECDH:AES128+EDH:AES256+EDH:AES128-SHA:AES256-SHA:!aNULL:!eNULL:!DSS\"\n"; if (!(empty($ca) || (strlen(trim($ca)) == 0))) { From 47360140558cb879105e67e6fd823e90cb9325fb Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 12 Mar 2015 12:02:04 +0545 Subject: [PATCH 229/257] White space in ipsec.inc --- etc/inc/ipsec.inc | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/etc/inc/ipsec.inc b/etc/inc/ipsec.inc index b014b35755..8d0520304e 100644 --- a/etc/inc/ipsec.inc +++ b/etc/inc/ipsec.inc @@ -193,16 +193,16 @@ function ipsec_get_phase1_src(& $ph1ent) { if ($ph1ent['interface']) { if (!is_ipaddr($ph1ent['interface'])) { - if (strpos($ph1ent['interface'], '_vip')) { - $if = $ph1ent['interface']; - } else { - $if = get_failover_interface($ph1ent['interface']); - } - if ($ph1ent['protocol'] == "inet6") { - $interfaceip = get_interface_ipv6($if); - } else { - $interfaceip = get_interface_ip($if); - } + if (strpos($ph1ent['interface'], '_vip')) { + $if = $ph1ent['interface']; + } else { + $if = get_failover_interface($ph1ent['interface']); + } + if ($ph1ent['protocol'] == "inet6") { + $interfaceip = get_interface_ipv6($if); + } else { + $interfaceip = get_interface_ip($if); + } } else { $interfaceip=$ph1ent['interface']; } From 6a2eb517c90596823dd426441ab567fbb18ed4ca Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 14:49:15 -0500 Subject: [PATCH 230/257] If we bail not being able to find the P1 source, log an error. Conflicts: etc/inc/vpn.inc --- etc/inc/vpn.inc | 1 + 1 file changed, 1 insertion(+) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 3bc4d70a88..28d0bf515b 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -217,6 +217,7 @@ function vpn_ipsec_configure($restart = false) $ep = ipsec_get_phase1_src($ph1ent); if (!is_ipaddr($ep)) { + log_error("IPsec ERROR: Could not find phase 1 source for connection {$ph1ent['descr']}. Omitting from configuration file."); continue; } From 89e6f7af272856a3ae2d01c19e164f42351a1bf1 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 15:07:20 -0500 Subject: [PATCH 231/257] Touch up wifi text --- .../share/locale/en/LC_MESSAGES/pfSense.pot | 4 ++-- .../share/locale/ja/LC_MESSAGES/pfSense.po | 4 ++-- .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo | Bin 643027 -> 643027 bytes .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po | 4 ++-- .../share/locale/tr/LC_MESSAGES/pfSense.mo | Bin 578284 -> 578284 bytes .../share/locale/tr/LC_MESSAGES/pfSense.po | 6 +++--- usr/local/www/interfaces.php | 6 +++--- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot index 9e357dd89e..ea24858cf1 100644 --- a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot +++ b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot @@ -14843,7 +14843,7 @@ msgid "Enable IEEE802.1X Authentication" msgstr "" #: usr/local/www/interfaces.php:3283 -msgid "Setting this option will enable 802.1x authentication." +msgid "Setting this option will enable 802.1X authentication." msgstr "" #: usr/local/www/interfaces.php:3284 @@ -14871,7 +14871,7 @@ msgid "802.1X Authentication Server Port" msgstr "" #: usr/local/www/interfaces.php:3298 usr/local/www/interfaces.php:3319 -msgid "Leave blank for the default 1812 port." +msgid "Leave blank for the default port 1812." msgstr "" #: usr/local/www/interfaces.php:3302 diff --git a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po index af481c115f..512b1852b1 100644 --- a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po @@ -23324,7 +23324,7 @@ msgstr "IEEE802.1Xèªè¨¼ã‚’有効ã«ã—ã¾ã™" #: usr/local/www/interfaces.php:2538 usr/local/www/interfaces.php:2568 #: usr/local/www/interfaces.php:2614 usr/local/www/interfaces.php:2603 #: usr/local/www/interfaces.php:2603 -msgid "Setting this option will enable 802.1x authentication." +msgid "Setting this option will enable 802.1X authentication." msgstr "ã“ã®ã‚ªãƒ—ションを設定ã™ã‚‹ã¨ã€ 802.1xèªè¨¼ã‚’有効ã«ã—ã¾ã™ã€‚" #: usr/local/www/interfaces.php:2371 @@ -23381,7 +23381,7 @@ msgstr "802.1Xèªè¨¼ã‚µãƒ¼ãƒãƒ¼ãƒãƒ¼ãƒˆ" #: usr/local/www/interfaces.php:2650 usr/local/www/interfaces.php:2618 #: usr/local/www/interfaces.php:2639 usr/local/www/interfaces.php:2618 #: usr/local/www/interfaces.php:2639 -msgid "Leave blank for the default 1812 port." +msgid "Leave blank for the default port 1812." msgstr "デフォルト1812ãƒãƒ¼ãƒˆã«å¯¾ã—ã¦ã¯ç©ºç™½ã®ã¾ã¾ã«ã—ã¾ã™ã€‚" #: usr/local/www/interfaces.php:2389 usr/local/www/interfaces.php:2569 diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo index f1fc3357e36d34c541a3e175f46f31f20981f885..e728619313ecd13aee7c0f95b4eb4d987f1273b4 100644 GIT binary patch delta 59 zcmcaSU;XlY^@bM47N#xCF=dh&Am-S< JTAov50|1aT6!HK7 delta 59 zcmcaSU;XlY^@bM47N#xCF=d>F7KTO&1^GoK+f&P!T~{(zw6B(D0b*7lW&>h&Am-S< JTAov50|1V<6%qgd diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po index 5a4f366f0e..26b2953f26 100644 --- a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po @@ -19876,7 +19876,7 @@ msgstr "Habilita Autentica #: usr/local/www/interfaces.php:2538 usr/local/www/interfaces.php:2568 #: usr/local/www/interfaces.php:2614 usr/local/www/interfaces.php:2603 #: usr/local/www/interfaces.php:2639 -msgid "Setting this option will enable 802.1x authentication." +msgid "Setting this option will enable 802.1X authentication." msgstr "Configurando essa opção habilitará a autenticação 802.1x." #: usr/local/www/interfaces.php:2371 @@ -19929,7 +19929,7 @@ msgstr "Porta do Servidor de Autentica #: usr/local/www/interfaces.php:2650 usr/local/www/interfaces.php:2618 #: usr/local/www/interfaces.php:2639 usr/local/www/interfaces.php:2654 #: usr/local/www/interfaces.php:2675 -msgid "Leave blank for the default 1812 port." +msgid "Leave blank for the default port 1812." msgstr "Deixe em branco para usar a porta padrão 1812." #: usr/local/www/interfaces.php:2389 usr/local/www/interfaces.php:2569 diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.mo index f0131a01162dafd2cc8840a5363498008587f307..21dfee0b847ffa1a3d41067b829f7a140611e10b 100644 GIT binary patch delta 71 zcmaE}RQb(P<%Sl<7N#xCJJmT0@{39o3@r?ewjWYw=9|qJ(SGp|GZ3?Ezj%ms`9Fkw Rd*eYiAZFj*c#tDo5C9ZF9Pa=C delta 71 zcmaE}RQb(P<%Sl<7N#xCJJmT2Eewqm3i69ewjWYw=9|q}(SGp|GZ3?Ezj%ms`9Fkw Rd*eYiAZFj*c#tDo5C9Km9S;Bi diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po index cfe8aa028a..e4c3c5bee3 100644 --- a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po @@ -15479,7 +15479,7 @@ msgid "Enable IEEE802.1X Authentication" msgstr "IEEE802.1x Kimlik DoÄŸrulamayı EtkinleÅŸtir" #: usr/local/www/interfaces.php:3283 -msgid "Setting this option will enable 802.1x authentication." +msgid "Setting this option will enable 802.1X authentication." msgstr "" "Bu seçeneÄŸi etkinleÅŸtirmek 802.1x kimlik doÄŸrulamanın devreye girmesini " "saÄŸlayacaktır." @@ -15511,7 +15511,7 @@ msgid "802.1X Authentication Server Port" msgstr "802.1x Kimlik doÄŸrulama Sunucu Portu" #: usr/local/www/interfaces.php:3298 usr/local/www/interfaces.php:3319 -msgid "Leave blank for the default 1812 port." +msgid "Leave blank for the default port 1812." msgstr "Varsayılan port olan 1812'yi kullanmak için boÅŸ bırakın." #: usr/local/www/interfaces.php:3302 @@ -19019,7 +19019,7 @@ msgstr "" #: usr/local/www/services_captiveportal.php:733 msgid "Leave this field blank to use the default port (1812)." -msgstr "Varsayılan 1812 portunu kullanmak için boÅŸ bırakınız." +msgstr "Varsayılan port 1812unu kullanmak için boÅŸ bırakınız." #: usr/local/www/services_captiveportal.php:736 #: usr/local/www/services_captiveportal.php:756 diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index be0933062b..c5b39ec6c6 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -3277,7 +3277,7 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), @@ -3292,7 +3292,7 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), @@ -3313,7 +3313,7 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), From 95df2de5aaecdfaac04cedbe61923f36e58c28c0 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 16:48:36 -0500 Subject: [PATCH 232/257] Add more input validation for wireless parameters. Ticket #4516 --- usr/local/www/interfaces.php | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index c5b39ec6c6..b52a44a524 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -771,9 +771,45 @@ if ($_POST['apply']) { if ($_POST['mode'] == 'hostap') { $reqdfields[] = "ssid"; $reqdfieldsn[] = gettext("SSID"); + if (stristr($_POST['standard'], '11n')) { + if (!($_POST['wme_enable'])) { + $input_errors[] = gettext("802.11n standards require enabling WME."); + } + } } do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); check_wireless_mode(); + if (isset($_POST['wpa_group_rekey']) && (!is_numericint($_POST['wpa_group_rekey']) || $_POST['wpa_group_rekey'] < 1 || $_POST['wpa_group_rekey'] > 9999)) { + $input_errors[] = gettext("Key Rotation must be an integer between 1 and 9999."); + } + if (isset($_POST['wpa_gmk_rekey']) && (!is_numericint($_POST['wpa_gmk_rekey']) || $_POST['wpa_gmk_rekey'] < 1 || $_POST['wpa_gmk_rekey'] > 9999)) { + $input_errors[] = gettext("Master Key Regeneration must be an integer between 1 and 9999."); + } + if (isset($_POST['wpa_group_rekey']) && isset($_POST['wpa_gmk_rekey'])) { + if ($_POST['wpa_group_rekey'] > $_POST['wpa_gmk_rekey']) { + $input_errors[] = gettext("Master Key Regeneration must be greater than Key Rotation."); + } + } + if (!empty($_POST['auth_server_addr'])) { + if (!is_domain($_POST['auth_server_addr']) && !is_ipaddr($_POST['auth_server_addr'])) { + $input_errors[] = gettext("802.1X Authentication Server must be an IP or hostname."); + } + } + if (!empty($_POST['auth_server_addr2'])) { + if (!is_domain($_POST['auth_server_addr2']) && !is_ipaddr($_POST['auth_server_addr2'])) { + $input_errors[] = gettext("Secondary 802.1X Authentication Server must be an IP or hostname."); + } + } + if (!empty($_POST['auth_server_port'])) { + if (!is_port($_POST['auth_server_port'])) { + $input_errors[] = gettext("802.1X Authentication Server Port must be a valid port number (1-65535)."); + } + } + if (!empty($_POST['auth_server_port2'])) { + if (!is_port($_POST['auth_server_port2'])) { + $input_errors[] = gettext("Secondary 802.1X Authentication Server Port must be a valid port number (1-65535)."); + } + } /* loop through keys and enforce size */ for ($i = 1; $i <= 4; $i++) { if ($_POST['key' . $i]) { From 6cd14b43eeb1442fea6a9515977b137af39a3ae5 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 18:22:25 -0500 Subject: [PATCH 233/257] Add more validation for wireless config settings. Ticket #4516 --- usr/local/www/interfaces.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index b52a44a524..7020726194 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -810,6 +810,28 @@ if ($_POST['apply']) { $input_errors[] = gettext("Secondary 802.1X Authentication Server Port must be a valid port number (1-65535)."); } } + if (isset($_POST['channel']) && !is_numericint($_POST['channel'])) { + if (!is_numericint($_POST['channel'])) { + $input_errors[] = gettext("Invalid channel specified."); + } else { + if ($_POST['channel'] > 255 || $_POST['channel'] < 0) { + $input_errors[] = gettext("Channel must be between 0-255."); + } + } + } + if (!empty($_POST['distance']) && !is_numericint($_POST['distance'])) { + $input_errors[] = gettext("Distance must be an integer."); + } + if (isset($_POST['standard']) && (stristr($_POST['standard'], '11na') || stristr($_POST['standard'], '11a'))) { + if ($_POST['channel'] != 0 && $_POST['channel'] < 15) { + $input_errors[] = gettext("Channel selected is not valid for 802.11a or 802.11na."); + } + } + if (isset($_POST['standard']) && ($_POST['standard'] = "11b" || $_POST['standard'] = "11g")) { + if ($_POST['channel'] > 14) { + $input_errors[] = gettext("Channel selected is not valid for 802.11b or 802.11g."); + } + } /* loop through keys and enforce size */ for ($i = 1; $i <= 4; $i++) { if ($_POST['key' . $i]) { From aec55f9aa49112ec8d793f8cae6277a3d5e08d9d Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 18:53:14 -0500 Subject: [PATCH 234/257] add more wireless validation. Ticket #4516 --- usr/local/www/interfaces.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 7020726194..8b30459b5e 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -827,11 +827,14 @@ if ($_POST['apply']) { $input_errors[] = gettext("Channel selected is not valid for 802.11a or 802.11na."); } } - if (isset($_POST['standard']) && ($_POST['standard'] = "11b" || $_POST['standard'] = "11g")) { + if (isset($_POST['standard']) && ($_POST['standard'] == "11b" || $_POST['standard'] == "11g")) { if ($_POST['channel'] > 14) { $input_errors[] = gettext("Channel selected is not valid for 802.11b or 802.11g."); } } + if (!empty($_POST['protmode']) && !in_array($_POST['protmode'], array("off", "cts", "rtscts"))) { + $input_errors[] = gettext("Invalid option chosen for OFDM Protection Mode"); + } /* loop through keys and enforce size */ for ($i = 1; $i <= 4; $i++) { if ($_POST['key' . $i]) { From f087d453987dd46f070c10cc3d97dfb0d87d8f46 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Thu, 12 Mar 2015 21:07:28 -0300 Subject: [PATCH 235/257] Do not start filterdns during boot until a proper fix is done. Ticket #4296 --- etc/inc/filter.inc | 36 +++++++++++++++++++----------------- etc/rc.bootup | 2 ++ 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index 93901e86a3..9e20344301 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -457,26 +457,28 @@ function filter_configure_sync($delete_states_if_needed = true) { update_filter_reload_status(gettext("Starting up layer7 daemon")); layer7_start_l7daemon(); - if (!empty($filterdns)) { - @file_put_contents("{$g['varetc_path']}/filterdns.conf", implode("", $filterdns)); - unset($filterdns); - if (isvalidpid("{$g['varrun_path']}/filterdns.pid")) { - sigkillbypid("{$g['varrun_path']}/filterdns.pid", "HUP"); - } else { - /* - * FilterDNS has three debugging levels. The default chosen is 1. - * Available are level 2 and greater then 2. - */ - if (isset($config['system']['aliasesresolveinterval']) && is_numeric($config['system']['aliasesresolveinterval'])) { - $resolve_interval = $config['system']['aliasesresolveinterval']; + if (!platform_booting()) { + if (!empty($filterdns)) { + @file_put_contents("{$g['varetc_path']}/filterdns.conf", implode("", $filterdns)); + unset($filterdns); + if (isvalidpid("{$g['varrun_path']}/filterdns.pid")) { + sigkillbypid("{$g['varrun_path']}/filterdns.pid", "HUP"); } else { - $resolve_interval = 300; + /* + * FilterDNS has three debugging levels. The default chosen is 1. + * Available are level 2 and greater then 2. + */ + if (isset($config['system']['aliasesresolveinterval']) && is_numeric($config['system']['aliasesresolveinterval'])) { + $resolve_interval = $config['system']['aliasesresolveinterval']; + } else { + $resolve_interval = 300; + } + mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns.pid -i {$resolve_interval} -c {$g['varetc_path']}/filterdns.conf -d 1"); } - mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns.pid -i {$resolve_interval} -c {$g['varetc_path']}/filterdns.conf -d 1"); + } else { + killbypid("{$g['varrun_path']}/filterdns.pid"); + @unlink("{$g['varrun_path']}/filterdns.pid"); } - } else { - killbypid("{$g['varrun_path']}/filterdns.pid"); - @unlink("{$g['varrun_path']}/filterdns.pid"); } /* run items scheduled for after filter configure run */ diff --git a/etc/rc.bootup b/etc/rc.bootup index 50190e10a5..a8f6b3f91b 100755 --- a/etc/rc.bootup +++ b/etc/rc.bootup @@ -458,6 +458,8 @@ unset($g['booting']); /* If there are ipsec dynamic hosts try again to reload the tunnels as rc.newipsecdns does */ if ($ipsec_dynamic_hosts) { vpn_ipsec_configure(); +} +if ($ipsec_dynamic_hosts || !empty($filterdns)) { filter_configure(); } From cc229ee94a897423d6eac771eefe8684c2fa1c2c Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Fri, 13 Mar 2015 07:30:52 +0545 Subject: [PATCH 236/257] Missin double equals in captiveportal.inc Looking at where this is nested inside various if statements, I do not think this error did too much harm - only to the $mac['descr'] - in this particular code flow $username is not used for important stuff after this point. --- etc/inc/captiveportal.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/captiveportal.inc b/etc/inc/captiveportal.inc index 002195f102..cbc197e16e 100644 --- a/etc/inc/captiveportal.inc +++ b/etc/inc/captiveportal.inc @@ -2068,7 +2068,7 @@ function portal_allow($clientip,$clientmac,$username,$password = null, $attribut $mac['logintype'] = "voucher"; } } - if ($username = "unauthenticated") { + if ($username == "unauthenticated") { $mac['descr'] = "Auto-added"; } else { $mac['descr'] = "Auto-added for user {$username}"; From ac0c435545c3eb9c553e556a328a93444c7d7f30 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 20:45:11 -0500 Subject: [PATCH 237/257] Set txpower since that seems to work fine now. Explicitly set authmode wpa here, though it's also handled by the supplicant/authenticator. Ticket #4516 Conflicts: etc/inc/interfaces.inc --- etc/inc/interfaces.inc | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index 850b2137ed..8c4032834a 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -2630,9 +2630,10 @@ function interface_wireless_configure($if, &$wl, &$wlcfg) { } /* handle txpower setting */ - /* if ($wlcfg['txpower'] <> "") + if($wlcfg['txpower'] <> "" && is_numeric($wlcfg['txpower'])) { $wlcmd[] = "txpower " . escapeshellarg($wlcfg['txpower']); - */ + } + /* handle wme option */ if (isset($wlcfg['wme']['enable'])) { $wlcmd[] = "wme"; @@ -2662,6 +2663,8 @@ function interface_wireless_configure($if, &$wl, &$wlcfg) { $i++; } $wlcmd[] = $wepset; + } else if (isset($wlcfg['wpa']['enable'])) { + $wlcmd[] = "authmode wpa wepmode off "; } else { $wlcmd[] = "authmode open wepmode off "; } From 6f5607f5556ae65810fa6ba3e9df5480ba8cc894 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 20:55:46 -0500 Subject: [PATCH 238/257] "Auto" channel with hostap doesn't work correctly at the moment, force choosing a specific channel with hostap mode for now. --- usr/local/www/interfaces.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 8b30459b5e..a37de63abe 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -776,6 +776,10 @@ if ($_POST['apply']) { $input_errors[] = gettext("802.11n standards require enabling WME."); } } + if (isset($_POST['channel']) && $_POST['channel'] == "0") { + // auto channel with hostap is broken, prevent this for now. + $input_errors[] = gettext("A specific channel, not auto, must be selected for Access Point mode."); + } } do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); check_wireless_mode(); From a819eab22247e04f22dfd586a60d10537efb5b54 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 21:01:42 -0500 Subject: [PATCH 239/257] Fix up text, remove "only for Atheros" since the option is only shown if a compatible card exists. --- .../share/locale/en/LC_MESSAGES/pfSense.pot | 2 +- .../share/locale/ja/LC_MESSAGES/pfSense.po | 2 +- .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo | Bin 643027 -> 642986 bytes .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po | 2 +- .../share/locale/tr/LC_MESSAGES/pfSense.mo | Bin 578284 -> 578243 bytes .../share/locale/tr/LC_MESSAGES/pfSense.po | 2 +- usr/local/www/interfaces.php | 2 +- 7 files changed, 5 insertions(+), 5 deletions(-) diff --git a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot index ea24858cf1..5abaca4fff 100644 --- a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot +++ b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot @@ -14540,7 +14540,7 @@ msgid "" msgstr "" #: usr/local/www/interfaces.php:3016 -msgid "(measured in Meters and works only for Atheros based cards !)" +msgid "(measured in meters)" msgstr "" #: usr/local/www/interfaces.php:3021 diff --git a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po index 512b1852b1..3bad34edca 100644 --- a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po @@ -22822,7 +22822,7 @@ msgstr "APã¨ã‚¯ãƒ©ã‚¤ã‚¢ãƒ³ãƒˆé–“ã®ã€Œæ³¨æ„ã“ã®ãƒ•ィールドã«ã¯ã€è· #: usr/local/www/interfaces.php:2271 usr/local/www/interfaces.php:2301 #: usr/local/www/interfaces.php:2347 usr/local/www/interfaces.php:2336 #: usr/local/www/interfaces.php:2336 -msgid "(measured in Meters and works only for Atheros based cards !)" +msgid "(measured in meters)" msgstr "ï¼ˆãƒ¡ãƒ¼ãƒˆãƒ«ã§æ¸¬å®šã—ã€å”¯ä¸€ã®Atherosベースã®ã‚«ãƒ¼ãƒ‰ã®ãŸã‚ã«åƒã ï¼ ï¼‰" #: usr/local/www/interfaces.php:2110 usr/local/www/interfaces.php:2288 diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo index e728619313ecd13aee7c0f95b4eb4d987f1273b4..a169377e090ea3abf270222409c739c392de9631 100644 GIT binary patch delta 52 zcmcaSUwzel^@c5s4{oyMrk11@6}R)>VgzC)AZ7+)79eH?Vm2UV-_C!Fr6`o=7iAYKr6`o=7iAYK gettext("None"), "staticv6" => gettext("Static IPv6"),

        - +
        From 664aef0be15e80a15690b3e6420a000a00a97c40 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 22:05:18 -0500 Subject: [PATCH 240/257] correct missing == in ipsec.inc --- etc/inc/ipsec.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/ipsec.inc b/etc/inc/ipsec.inc index 8d0520304e..aa8524cedb 100644 --- a/etc/inc/ipsec.inc +++ b/etc/inc/ipsec.inc @@ -663,7 +663,7 @@ function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array()) { if (!$addr) { return array(); } - } elseif ($side = "peer") { + } elseif ($side == "peer") { $id_type = $ph1ent['peerid_type']; $id_data = $ph1ent['peerid_data']; From 4958ca9eed04a1e7afabf3eb1214e30b253ca6b4 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 23:25:51 -0500 Subject: [PATCH 241/257] clean up input errors text --- .../share/locale/en/LC_MESSAGES/pfSense.pot | 4 ++-- .../share/locale/ja/LC_MESSAGES/pfSense.po | 2 +- .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo | Bin 642986 -> 642963 bytes .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po | 4 ++-- .../share/locale/tr/LC_MESSAGES/pfSense.mo | Bin 578243 -> 578220 bytes .../share/locale/tr/LC_MESSAGES/pfSense.po | 4 ++-- usr/local/www/interfaces.php | 4 ++-- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot index 5abaca4fff..95c4340ea6 100644 --- a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot +++ b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot @@ -13559,11 +13559,11 @@ msgstr "" #: usr/local/www/interfaces.php:805 msgid "" -"Invalid WEP key size. Sizes should be 40 (64) bit keys or 104 (128) bit." +"Invalid WEP key. Enter a valid 40, 64, 104 or 128 bit WEP key." msgstr "" #: usr/local/www/interfaces.php:813 -msgid "The length of the passphrase should be between 8 and 63 characters." +msgid "The passphrase must be between 8 and 63 characters long." msgstr "" #: usr/local/www/interfaces.php:1383 diff --git a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po index 3bad34edca..09134f27f6 100644 --- a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po @@ -21626,7 +21626,7 @@ msgstr ""無効ãªWEPキーã®ã‚µã‚¤ã‚ºã€‚サイズã¯40 ( 64 )ビットキ #: usr/local/www/interfaces.php:662 usr/local/www/interfaces.php:677 #: usr/local/www/interfaces.php:718 usr/local/www/interfaces.php:714 #: usr/local/www/interfaces.php:714 -msgid "The length of the passphrase should be between 8 and 63 characters." +msgid "The passphrase must be between 8 and 63 characters long." msgstr "パスフレーズã®é•·ã•ã¯8 〜63文字ã«ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚" #: usr/local/www/interfaces.php:659 diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo index a169377e090ea3abf270222409c739c392de9631..1b8f20bf32e8d67cf3f553b0294c1be4845c5cc8 100644 GIT binary patch delta 125 zcmZ2AUw!g?^@bM47N#xCLD_nG3a)u2sYMEj3T25onJEe;20996COQg+1||ymMGA&S z779t3B?{rL0SeivmF+#*%-egiS=xB{3lfWq3o?oli&GVHON&dU8&0)r>57#s!tIuoEI`Z(#B4y!4#XVWEh{;r!T?2$E~Eee diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po index 36fb1e46de..8249589e3e 100644 --- a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po @@ -18327,14 +18327,14 @@ msgstr "SSID" #: usr/local/www/interfaces.php:654 usr/local/www/interfaces.php:669 #: usr/local/www/interfaces.php:710 usr/local/www/interfaces.php:706 #: usr/local/www/interfaces.php:711 -msgid "Invalid WEP key size. Sizes should be 40 (64) bit keys or 104 (128) bit." +msgid "Invalid WEP key. Enter a valid 40, 64, 104 or 128 bit WEP key." msgstr "Tamanho de chave WEP inválido. Tamanhos devem ser de 40 (64) chaves de bit ou 104 (128) bits." #: usr/local/www/interfaces.php:591 usr/local/www/interfaces.php:665 #: usr/local/www/interfaces.php:662 usr/local/www/interfaces.php:677 #: usr/local/www/interfaces.php:718 usr/local/www/interfaces.php:714 #: usr/local/www/interfaces.php:719 -msgid "The length of the passphrase should be between 8 and 63 characters." +msgid "The passphrase must be between 8 and 63 characters long." msgstr "O tamanho da frase secreta deve ser entre 8 e 63 caracteres." #: usr/local/www/interfaces.php:659 diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.mo index 1e94d81e64d47691e0fc2cea6ece8d1d888afb61..a8d57498718447f543e2aa75af3017b3579f8ed9 100644 GIT binary patch delta 117 zcmX@SRC&!(<%Sl<7N#xCOJwx)6kPL4Qi~K470MEGGE)>x40IICOmq|s4NMgBixdov zEEJM5OBBLg0~E4TE4Sa1VgC4@zaX)=xFDk_u{c#Bx3suq`a2#Lc~*s-{JivbUS1X; RW(8t4AZFjr%geFtC;;5ZB^3Yw delta 165 zcmZ3pRQd2y<%Sl<7N#xCOJuARiZiQH^%N8of`N3gLUBfZX- 63) - $input_errors[] = gettext("The length of the passphrase should be between 8 and 63 characters."); + $input_errors[] = gettext("The passphrase must be between 8 and 63 characters long."); } } if (!$input_errors) { From 310ea4e25796080b1a7e1a0fa0a2c2f2c8a085cd Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Thu, 12 Mar 2015 23:43:31 -0500 Subject: [PATCH 242/257] Require WPA PSK where WPA-PSK is enabled. Clean up some other text. Ticket #4516 --- .../share/locale/en/LC_MESSAGES/pfSense.pot | 4 ++-- .../share/locale/ja/LC_MESSAGES/pfSense.po | 4 ++-- .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo | Bin 642963 -> 642980 bytes .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po | 4 ++-- .../share/locale/tr/LC_MESSAGES/pfSense.mo | Bin 578220 -> 578237 bytes .../share/locale/tr/LC_MESSAGES/pfSense.po | 4 ++-- usr/local/www/interfaces.php | 9 +++++++-- 7 files changed, 15 insertions(+), 10 deletions(-) diff --git a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot index 95c4340ea6..fff8739399 100644 --- a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot +++ b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot @@ -13563,7 +13563,7 @@ msgid "" msgstr "" #: usr/local/www/interfaces.php:813 -msgid "The passphrase must be between 8 and 63 characters long." +msgid "The WPA passphrase must be between 8 and 63 characters long." msgstr "" #: usr/local/www/interfaces.php:1383 @@ -14750,7 +14750,7 @@ msgid "PSK:" msgstr "" #: usr/local/www/interfaces.php:3214 -msgid "Passphrase must be from 8 to 63 characters." +msgid "WPA Passphrase must be between 8 and 63 characters long." msgstr "" #: usr/local/www/interfaces.php:3218 diff --git a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po index 09134f27f6..c5379e58a7 100644 --- a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po @@ -21626,7 +21626,7 @@ msgstr ""無効ãªWEPキーã®ã‚µã‚¤ã‚ºã€‚サイズã¯40 ( 64 )ビットキ #: usr/local/www/interfaces.php:662 usr/local/www/interfaces.php:677 #: usr/local/www/interfaces.php:718 usr/local/www/interfaces.php:714 #: usr/local/www/interfaces.php:714 -msgid "The passphrase must be between 8 and 63 characters long." +msgid "The WPA passphrase must be between 8 and 63 characters long." msgstr "パスフレーズã®é•·ã•ã¯8 〜63文字ã«ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚" #: usr/local/www/interfaces.php:659 @@ -23167,7 +23167,7 @@ msgstr "PSK :" #: usr/local/www/interfaces.php:2469 usr/local/www/interfaces.php:2499 #: usr/local/www/interfaces.php:2545 usr/local/www/interfaces.php:2534 #: usr/local/www/interfaces.php:2534 -msgid "Passphrase must be from 8 to 63 characters." +msgid "WPA Passphrase must be between 8 and 63 characters long." msgstr "パスフレーズã¯ã€8〜 63文字ã§ãªã‘れã°ãªã‚Šã¾ã›ã‚“。" #: usr/local/www/interfaces.php:2305 usr/local/www/interfaces.php:2485 diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo index 1b8f20bf32e8d67cf3f553b0294c1be4845c5cc8..419127ad83f49a072077c2db19f8d03381628f7f 100644 GIT binary patch delta 62 zcmbO{Uwz4Z^@bM47N#xC<%d|q0~{3srn6VFm~3Bsh&g#1Gf<$NwUPyhS%H`hh}nUd LV>@dlXI~fqutOAQ delta 97 zcmZ27Uw!g?^@bM47N#xC<%hHa5{ruqGKvz5Qx$Sci%S%eQWesQ@^cj|6iV_H%#0P1 vGZKpulS@*Iinp&j#GJZ~v0!@5A!d_ypGp=WW(8t4AZ7<*j_p2`oDpFF2cIL_ diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po index 8249589e3e..985b0dcc57 100644 --- a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po @@ -18334,7 +18334,7 @@ msgstr "Tamanho de chave WEP inv #: usr/local/www/interfaces.php:662 usr/local/www/interfaces.php:677 #: usr/local/www/interfaces.php:718 usr/local/www/interfaces.php:714 #: usr/local/www/interfaces.php:719 -msgid "The passphrase must be between 8 and 63 characters long." +msgid "The WPA passphrase must be between 8 and 63 characters long." msgstr "O tamanho da frase secreta deve ser entre 8 e 63 caracteres." #: usr/local/www/interfaces.php:659 @@ -19725,7 +19725,7 @@ msgstr "PSK:" #: usr/local/www/interfaces.php:2469 usr/local/www/interfaces.php:2499 #: usr/local/www/interfaces.php:2545 usr/local/www/interfaces.php:2534 #: usr/local/www/interfaces.php:2570 -msgid "Passphrase must be from 8 to 63 characters." +msgid "WPA Passphrase must be between 8 and 63 characters long." msgstr "Frase secreta deve ter de 8 a 63 caracteres." #: usr/local/www/interfaces.php:2305 usr/local/www/interfaces.php:2485 diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.mo index a8d57498718447f543e2aa75af3017b3579f8ed9..966197402f83f7423652f8853c722fa55cfc510f 100644 GIT binary patch delta 58 zcmZ3pRC(`G<%Sl<7N#xCTDh#@0geg*(~t15m~0QrWzL0WT#KQu_tU$~L#O&J- J@o>C43IJeU6zKo} delta 93 zcmdnHRC&!(<%Sl<7N#xCTDe*QiN(bQ8AXZ3sS3HJ#U% 63) - $input_errors[] = gettext("The passphrase must be between 8 and 63 characters long."); + $input_errors[] = gettext("The WPA passphrase must be between 8 and 63 characters long."); + } + if ($_POST['wpa_enable'] == "yes") { + if (empty($_POST['passphrase']) && stristr($_POST['wpa_key_mgmt'], "WPA-PSK")) { + $input_errors[] = gettext("A WPA Passphrase must be specified when WPA PSK is enabled."); + } } } if (!$input_errors) { @@ -3273,7 +3278,7 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"),
        - +  =  diff --git a/usr/local/www/diag_ping.php b/usr/local/www/diag_ping.php index 6d0afa2da5..bc60f71051 100644 --- a/usr/local/www/diag_ping.php +++ b/usr/local/www/diag_ping.php @@ -99,7 +99,7 @@ include("head.inc"); ?>
        -
        -
        - +
        - +

        -
        - +
        - +
        -
        +

        -
        +

        -
        +

        192.168.100.100 fd00:abcd::1
        -
        +
        - +
        - +
        - +
        - +
        - +
        - +

        diff --git a/usr/local/www/vpn_pptp_users_edit.php b/usr/local/www/vpn_pptp_users_edit.php index 936ac2043e..8b09a7f420 100644 --- a/usr/local/www/vpn_pptp_users_edit.php +++ b/usr/local/www/vpn_pptp_users_edit.php @@ -78,7 +78,7 @@ if ($_POST) { $reqdfields = explode(" ", "username"); $reqdfieldsn = array(gettext("Username")); } else { - $reqdfields = explode(" ", "username password"); + $reqdfields = explode(" ", "username passwordfld1"); $reqdfieldsn = array(gettext("Username"),gettext("Password")); } @@ -87,13 +87,13 @@ if ($_POST) { if (preg_match("/[^a-zA-Z0-9\.\-_]/", $_POST['username'])) $input_errors[] = gettext("The username contains invalid characters."); - if (preg_match("/^!/", $_POST['password'])) + if (preg_match("/^!/", $_POST['passwordfld1'])) $input_errors[] = gettext("The password cannot start with '!'."); - if (!preg_match("/^[\x20-\x7E]*$/", $_POST['password'])) + if (!preg_match("/^[\x20-\x7E]*$/", $_POST['passwordfld1'])) $input_errors[] = gettext("The password contains invalid characters."); - if (($_POST['password']) && ($_POST['password'] != $_POST['password2'])) { + if (($_POST['passwordfld1']) && ($_POST['passwordfld1'] != $_POST['passwordfld2'])) { $input_errors[] = gettext("The passwords do not match."); } if (($_POST['ip'] && !is_ipaddr($_POST['ip']))) { @@ -118,8 +118,8 @@ if ($_POST) { $secretent['name'] = $_POST['username']; $secretent['ip'] = $_POST['ip']; - if ($_POST['password']) - $secretent['password'] = $_POST['password']; + if ($_POST['passwordfld1']) + $secretent['password'] = $_POST['passwordfld1']; if (isset($id) && $a_secret[$id]) $a_secret[$id] = $secretent; @@ -155,8 +155,8 @@ include("head.inc");
        - -
        + +
         ()
        + /> + +
        + +
        From 309162b96d6ad0db09c132cc0aabc890bfe1909f Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Tue, 10 Mar 2015 19:00:06 -0500 Subject: [PATCH 204/257] Use a consistent variable name here. related to Ticket #4446 Conflicts: usr/local/www/xmlrpc.php --- usr/local/www/xmlrpc.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/usr/local/www/xmlrpc.php b/usr/local/www/xmlrpc.php index ec6d458d36..13e98ff787 100755 --- a/usr/local/www/xmlrpc.php +++ b/usr/local/www/xmlrpc.php @@ -279,8 +279,12 @@ function restore_config_section_xmlrpc($raw_params) { } } /* Cleanup remaining old carps */ - foreach ($oldvips as $oldvipif => $oldvippar) { - $oldvipif = get_real_interface($oldvippar['interface']); + foreach ($oldvips as $oldvipif => $oldvipar) { + if (strstr($oldvipar['interface'], '_vip')) { + $oldvipif = explode('_vip', $oldvipar['interface']); + $oldvipif = $oldvipif[0]; + } else + $oldvipif = get_real_interface($oldvipar['interface']); if (!empty($oldvipif)) { if (is_ipaddrv6($oldvipif)) mwexec("/sbin/ifconfig " . escapeshellarg($oldvipif) . " inet6 " . escapeshellarg($oldvipar['subnet']) . " delete"); From 34ba4e5d32d5a371f2ae3ee6b0d38393d62925f8 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Tue, 10 Mar 2015 19:19:33 -0500 Subject: [PATCH 205/257] Need global $ipsec_idhandling here. --- etc/inc/vpn.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/inc/vpn.inc b/etc/inc/vpn.inc index 9c1e6db218..eda11be995 100644 --- a/etc/inc/vpn.inc +++ b/etc/inc/vpn.inc @@ -98,7 +98,7 @@ function vpn_ipsec_convert_to_modp($index) function vpn_ipsec_configure($restart = false) { - global $config, $g, $sa, $sn, $p1_ealgos, $p2_ealgos; + global $config, $g, $sa, $sn, $p1_ealgos, $p2_ealgos, $ipsec_idhandling; if ($g['platform'] == 'jail') { return; From 23cb405565539c2fa0c3db9eba052afce343f8a8 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Tue, 10 Mar 2015 20:21:09 -0500 Subject: [PATCH 206/257] Check for not up, rather than down, as there are a variety of potential statuses that are not up. Ticket #4502 --- etc/inc/gwlb.inc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/etc/inc/gwlb.inc b/etc/inc/gwlb.inc index 68af1ffad5..f65605fc76 100644 --- a/etc/inc/gwlb.inc +++ b/etc/inc/gwlb.inc @@ -843,13 +843,13 @@ function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) { if (($gwsttng['ipprotocol'] == $ipprotocol) && isset($gwsttng['defaultgw'])) { $dfltgwfound = true; $dfltgwname = $gwname; - if (!isset($gwsttng['monitor_disable']) && stristr($gateways_status[$gwname]['status'], "down")) { + if (!isset($gwsttng['monitor_disable']) && $gateways_status[$gwname]['status'] != "none") { $dfltgwdown = true; } } /* Keep a record of the last up gateway */ /* XXX: Blacklist lan for now since it might cause issues to those who have a gateway set for it */ - if (empty($upgw) && ($gwsttng['ipprotocol'] == $ipprotocol) && (isset($gwsttng['monitor_disable']) || !stristr($gateways_status[$gwname]['status'], "down")) && $gwsttng[$gwname]['friendlyiface'] != "lan") { + if (empty($upgw) && ($gwsttng['ipprotocol'] == $ipprotocol) && (isset($gwsttng['monitor_disable']) || $gateways_status[$gwname]['status'] == "none") && $gwsttng[$gwname]['friendlyiface'] != "lan") { $upgw = $gwname; } if ($dfltgwdown == true && !empty($upgw)) { @@ -1249,4 +1249,4 @@ function gateway_is_gwgroup_member($name) { return $members; } -?> +?> \ No newline at end of file From 0f57551162abde8ac58c0b48c9d0595e08694682 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 11 Mar 2015 00:24:59 -0500 Subject: [PATCH 207/257] Update cipher-list in web interface to prefer PFS. Ticket #4230 --- etc/inc/system.inc | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/etc/inc/system.inc b/etc/inc/system.inc index 112c2183c3..03f18a11d8 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -1475,11 +1475,13 @@ EOD; fclose($fd); } + // where ssl.cipher-list is set, this is automatically enabled, but set it explicitly anyway. + $lighty_config .= "ssl.honor-cipher-order = \"enable\"\n"; + if (isset($config['system']['webgui']['beast_protection'])) { - $lighty_config .= "ssl.honor-cipher-order = \"enable\"\n"; $lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n"; } else { - $lighty_config .= "ssl.cipher-list = \"DHE-RSA-CAMELLIA256-SHA:DHE-DSS-CAMELLIA256-SHA:CAMELLIA256-SHA:DHE-DSS-AES256-SHA:AES256-SHA:DHE-RSA-CAMELLIA128-SHA:DHE-DSS-CAMELLIA128-SHA:CAMELLIA128-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:!aNULL:!eNULL:!3DES:@STRENGTH\"\n"; + $lighty_config .= "ssl.cipher-list = \"AES128+EECDH:AES256+EECDH:AES128+EDH:AES256+EDH:AES128-SHA:AES256-SHA:!aNULL:!eNULL:!DSS\"\n"; } if (!(empty($ca) || (strlen(trim($ca)) == 0))) { From 80dfff9a2bbadc31a7b60eddcf169fc2c2f01cb7 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 11 Mar 2015 01:30:14 -0500 Subject: [PATCH 208/257] Leave adaptive.start and end at their defaults (60% and 120% of the state limit, respectively) if not user-overridden. --- etc/inc/filter.inc | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index af1494bb10..c0cd4a14da 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -309,9 +309,7 @@ function filter_configure_sync($delete_states_if_needed = true) { if (!empty($config['system']['adaptivestart']) && !empty($config['system']['adaptiveend'])) { $limitrules .= "set timeout { adaptive.start {$config['system']['adaptivestart']}, adaptive.end {$config['system']['adaptiveend']} }\n"; - } else { - $limitrules .= "set timeout { adaptive.start 0, adaptive.end 0 }\n"; - } + } if ($config['system']['maximumstates'] <> "" && is_numeric($config['system']['maximumstates'])) { /* User defined maximum states in Advanced menu. */ From e99affae860d6a009cc67a7bef00474a5bf3ff62 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 11 Mar 2015 01:37:10 -0500 Subject: [PATCH 209/257] update description after adaptive start/end default change. --- usr/local/www/system_advanced_firewall.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/system_advanced_firewall.php b/usr/local/www/system_advanced_firewall.php index 28bd52cacf..43c985e3da 100644 --- a/usr/local/www/system_advanced_firewall.php +++ b/usr/local/www/system_advanced_firewall.php @@ -366,7 +366,7 @@ function update_description(itemnum) {

        - +
        - /> - -
        - -
        - " . sprintf(gettext("This option has been automatically disabled because a conflicting cryptographic accelerator card has been detected (%s)."), $hwcrypto) . "

        "; - } ?> - Wikipedia."); ?> -
        From 0d443728d5ba55565f23ee71db117dbc1e1bb496 Mon Sep 17 00:00:00 2001 From: Renato Botelho Date: Wed, 11 Mar 2015 14:09:22 -0300 Subject: [PATCH 217/257] Explicit disable ssl.use-compression on lighty config. It should fix #4230 --- etc/inc/system.inc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/etc/inc/system.inc b/etc/inc/system.inc index 1cfdfb59ce..3d032d4f68 100644 --- a/etc/inc/system.inc +++ b/etc/inc/system.inc @@ -1464,6 +1464,9 @@ EOD; // where ssl.cipher-list is set, this is automatically enabled, but set it explicitly anyway. $lighty_config .= "ssl.honor-cipher-order = \"enable\"\n"; + // Explicit disable compression to mitigate CRIME attack + $lighty_config .= "ssl.use-compression = \"disable\"\n"; + $lighty_config .= "ssl.cipher-list = \"AES128+EECDH:AES256+EECDH:AES128+EDH:AES256+EDH:AES128-SHA:AES256-SHA:!aNULL:!eNULL:!DSS\"\n"; if (!(empty($ca) || (strlen(trim($ca)) == 0))) { From 24dadbee0608731ce19713d905bedbf588518821 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 11 Mar 2015 13:22:17 -0500 Subject: [PATCH 218/257] add granular control of state timeouts. Ticket #4509 Conflicts: etc/inc/filter.inc --- etc/inc/filter.inc | 48 +++++ usr/local/www/system_advanced_firewall.php | 198 ++++++++++++++++++++- 2 files changed, 244 insertions(+), 2 deletions(-) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index c0cd4a14da..a58d514dea 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -306,6 +306,54 @@ function filter_configure_sync($delete_states_if_needed = true) { } else { $limitrules .= "set optimization normal\n"; } + + $timeoutlist = ""; + if (isset($config['system']['tcpfirsttimeout']) && is_numericint($config['system']['tcpfirsttimeout'])) { + $timeoutlist .= " tcp.first {$config['system']['tcpfirsttimeout']} "; + } + if (isset($config['system']['tcpopeningtimeout']) && is_numericint($config['system']['tcpopeningtimeout'])) { + $timeoutlist .= " tcp.opening {$config['system']['tcpopeningtimeout']} "; + } + if (isset($config['system']['tcpestablishedtimeout']) && is_numericint($config['system']['tcpestablishedtimeout'])) { + $timeoutlist .= " tcp.established {$config['system']['tcpestablishedtimeout']} "; + } + if (isset($config['system']['tcpclosingtimeout']) && is_numericint($config['system']['tcpclosingtimeout'])) { + $timeoutlist .= " tcp.closing {$config['system']['tcpclosingtimeout']} "; + } + if (isset($config['system']['tcpfinwaittimeout']) && is_numericint($config['system']['tcpfinwaittimeout'])) { + $timeoutlist .= " tcp.finwait {$config['system']['tcpfinwaittimeout']} "; + } + if (isset($config['system']['tcpclosedtimeout']) && is_numericint($config['system']['tcpclosedtimeout'])) { + $timeoutlist .= " tcp.closed {$config['system']['tcpclosedtimeout']} "; + } + if (isset($config['system']['udpfirsttimeout']) && is_numericint($config['system']['udpfirsttimeout'])) { + $timeoutlist .= " udp.first {$config['system']['udpfirsttimeout']} "; + } + if (isset($config['system']['udpsingletimeout']) && is_numericint($config['system']['udpsingletimeout'])) { + $timeoutlist .= " udp.single {$config['system']['udpsingletimeout']} "; + } + if (isset($config['system']['udpmultipletimeout']) && is_numericint($config['system']['udpmultipletimeout'])) { + $timeoutlist .= " udp.multiple {$config['system']['udpmultipletimeout']} "; + } + if (isset($config['system']['icmpfirsttimeout']) && is_numericint($config['system']['icmpfirsttimeout'])) { + $timeoutlist .= " icmp.first {$config['system']['icmpfirsttimeout']} "; + } + if (isset($config['system']['icmperrortimeout']) && is_numericint($config['system']['icmperrortimeout'])) { + $timeoutlist .= " icmp.error {$config['system']['icmperrortimeout']} "; + } + if (isset($config['system']['otherfirsttimeout']) && is_numericint($config['system']['otherfirsttimeout'])) { + $timeoutlist .= " other.first {$config['system']['otherfirsttimeout']} "; + } + if (isset($config['system']['othersingletimeout']) && is_numericint($config['system']['othersingletimeout'])) { + $timeoutlist .= " other.single {$config['system']['othersingletimeout']} "; + } + if (isset($config['system']['othermultipletimeout']) && is_numericint($config['system']['othermultipletimeout'])) { + $timeoutlist .= " other.multiple {$config['system']['othermultipletimeout']} "; + } + + if ($timeoutlist <> "") { + $limitrules .= "set timeout { $timeoutlist }\n"; + } if (!empty($config['system']['adaptivestart']) && !empty($config['system']['adaptiveend'])) { $limitrules .= "set timeout { adaptive.start {$config['system']['adaptivestart']}, adaptive.end {$config['system']['adaptiveend']} }\n"; diff --git a/usr/local/www/system_advanced_firewall.php b/usr/local/www/system_advanced_firewall.php index 43c985e3da..b24a781ac8 100644 --- a/usr/local/www/system_advanced_firewall.php +++ b/usr/local/www/system_advanced_firewall.php @@ -71,6 +71,20 @@ $pconfig['bypassstaticroutes'] = isset($config['filter']['bypassstaticroutes']); $pconfig['disablescrub'] = isset($config['system']['disablescrub']); $pconfig['tftpinterface'] = explode(",", $config['system']['tftpinterface']); $pconfig['disablevpnrules'] = isset($config['system']['disablevpnrules']); +$pconfig['tcpfirsttimeout'] = $config['system']['tcpfirsttimeout']; +$pconfig['tcpopeningtimeout'] = $config['system']['tcpopeningtimeout']; +$pconfig['tcpestablishedtimeout'] = $config['system']['tcpestablishedtimeout']; +$pconfig['tcpclosingtimeout'] = $config['system']['tcpclosingtimeout']; +$pconfig['tcpfinwaittimeout'] = $config['system']['tcpfinwaittimeout']; +$pconfig['tcpclosedtimeout'] = $config['system']['tcpclosedtimeout']; +$pconfig['udpfirsttimeout'] = $config['system']['udpfirsttimeout']; +$pconfig['udpsingletimeout'] = $config['system']['udpsingletimeout']; +$pconfig['udpmultipletimeout'] = $config['system']['udpmultipletimeout']; +$pconfig['icmpfirsttimeout'] = $config['system']['icmpfirsttimeout']; +$pconfig['icmperrortimeout'] = $config['system']['icmperrortimeout']; +$pconfig['otherfirsttimeout'] = $config['system']['otherfirsttimeout']; +$pconfig['othersingletimeout'] = $config['system']['othersingletimeout']; +$pconfig['othermultipletimeout'] = $config['system']['othermultipletimeout']; if ($_POST) { @@ -101,6 +115,48 @@ if ($_POST) { if ($_POST['reflectiontimeout'] && !is_numericint($_POST['reflectiontimeout'])) { $input_errors[] = gettext("The Reflection timeout must be an integer."); } + if ($_POST['tcpfirsttimeout'] && !is_numericint($_POST['tcpfirsttimeout'])) { + $input_errors[] = gettext("The TCP first timeout value must be an integer."); + } + if ($_POST['tcpopeningtimeout'] && !is_numericint($_POST['tcpopeningtimeout'])) { + $input_errors[] = gettext("The TCP opening timeout value must be an integer."); + } + if ($_POST['tcpestablishedtimeout'] && !is_numericint($_POST['tcpestablishedtimeout'])) { + $input_errors[] = gettext("The TCP established timeout value must be an integer."); + } + if ($_POST['tcpclosingtimeout'] && !is_numericint($_POST['tcpclosingtimeout'])) { + $input_errors[] = gettext("The TCP closing timeout value must be an integer."); + } + if ($_POST['tcpfinwaittimeout'] && !is_numericint($_POST['tcpfinwaittimeout'])) { + $input_errors[] = gettext("The TCP FIN wait timeout value must be an integer."); + } + if ($_POST['tcpclosedtimeout'] && !is_numericint($_POST['tcpclosedtimeout'])) { + $input_errors[] = gettext("The TCP closed timeout value must be an integer."); + } + if ($_POST['udpfirsttimeout'] && !is_numericint($_POST['udpfirsttimeout'])) { + $input_errors[] = gettext("The UDP first timeout value must be an integer."); + } + if ($_POST['udpsingletimeout'] && !is_numericint($_POST['udpsingletimeout'])) { + $input_errors[] = gettext("The UDP single timeout value must be an integer."); + } + if ($_POST['udpmultipletimeout'] && !is_numericint($_POST['udpmultipletimeout'])) { + $input_errors[] = gettext("The UDP multiple timeout value must be an integer."); + } + if ($_POST['icmpfirsttimeout'] && !is_numericint($_POST['icmpfirsttimeout'])) { + $input_errors[] = gettext("The ICMP first timeout value must be an integer."); + } + if ($_POST['icmperrortimeout'] && !is_numericint($_POST['icmperrortimeout'])) { + $input_errors[] = gettext("The ICMP error timeout value must be an integer."); + } + if ($_POST['otherfirsttimeout'] && !is_numericint($_POST['otherfirsttimeout'])) { + $input_errors[] = gettext("The Other first timeout value must be an integer."); + } + if ($_POST['othersingletimeout'] && !is_numericint($_POST['othersingletimeout'])) { + $input_errors[] = gettext("The Other single timeout value must be an integer."); + } + if ($_POST['othermultipletimeout'] && !is_numericint($_POST['othermultipletimeout'])) { + $input_errors[] = gettext("The Other multiple timeout value must be an integer."); + } ob_flush(); flush(); @@ -150,6 +206,77 @@ if ($_POST) { $config['system']['aliasesresolveinterval'] = $_POST['aliasesresolveinterval']; $config['system']['maximumtableentries'] = $_POST['maximumtableentries']; + if (!empty($_POST['tcpfirsttimeout'])) { + $config['system']['tcpfirsttimeout'] = $_POST['tcpfirsttimeout']; + } else { + unset($config['system']['tcpfirsttimeout']); + } + if (!empty($_POST['tcpopeningtimeout'])) { + $config['system']['tcpopeningtimeout'] = $_POST['tcpopeningtimeout']; + } else { + unset($config['system']['tcpopeningtimeout']); + } + if (!empty($_POST['tcpestablishedtimeout'])) { + $config['system']['tcpestablishedtimeout'] = $_POST['tcpestablishedtimeout']; + } else { + unset($config['system']['tcpestablishedtimeout']); + } + if (!empty($_POST['tcpclosingtimeout'])) { + $config['system']['tcpclosingtimeout'] = $_POST['tcpclosingtimeout']; + } else { + unset($config['system']['tcpclosingtimeout']); + } + if (!empty($_POST['tcpfinwaittimeout'])) { + $config['system']['tcpfinwaittimeout'] = $_POST['tcpfinwaittimeout']; + } else { + unset($config['system']['tcpfinwaittimeout']); + } + if (!empty($_POST['tcpclosedtimeout'])) { + $config['system']['tcpclosedtimeout'] = $_POST['tcpclosedtimeout']; + } else { + unset($config['system']['tcpclosedtimeout']); + } + if (!empty($_POST['udpfirsttimeout'])) { + $config['system']['udpfirsttimeout'] = $_POST['udpfirsttimeout']; + } else { + unset($config['system']['udpfirsttimeout']); + } + if (!empty($_POST['udpsingletimeout'])) { + $config['system']['udpsingletimeout'] = $_POST['udpsingletimeout']; + } else { + unset($config['system']['udpsingletimeout']); + } + if (!empty($_POST['udpmultipletimeout'])) { + $config['system']['udpmultipletimeout'] = $_POST['udpmultipletimeout']; + } else { + unset($config['system']['udpmultipletimeout']); + } + if (!empty($_POST['icmpfirsttimeout'])) { + $config['system']['icmpfirsttimeout'] = $_POST['icmpfirsttimeout']; + } else { + unset($config['system']['icmpfirsttimeout']); + } + if (!empty($_POST['icmperrortimeout'])) { + $config['system']['icmperrortimeout'] = $_POST['icmperrortimeout']; + } else { + unset($config['system']['icmperrortimeout']); + } + if (!empty($_POST['otherfirsttimeout'])) { + $config['system']['otherfirsttimeout'] = $_POST['otherfirsttimeout']; + } else { + unset($config['system']['otherfirsttimeout']); + } + if (!empty($_POST['othersingletimeout'])) { + $config['system']['othersingletimeout'] = $_POST['othersingletimeout']; + } else { + unset($config['system']['othersingletimeout']); + } + if (!empty($_POST['othermultipletimeout'])) { + $config['system']['othermultipletimeout'] = $_POST['othermultipletimeout']; + } else { + unset($config['system']['othermultipletimeout']); + } + if($_POST['natreflection'] == "proxy") { unset($config['system']['disablenatreflection']); unset($config['system']['enablenatreflectionpurenat']); @@ -547,13 +674,80 @@ function update_description(itemnum) { echo ""; ?> - +
        +
        +   +
        +
        + +

        +
        + +

        +
        + +

        +
        + +

        +
        + +

        +
        + +
        +
        + +

        +
        + +

        +
        + +
        +
        + +

        +
        + +
        +
        + +

        +
        + +

        +
        +
         
          " />
        - + \n"; foreach ($ipsec_idhandling as $value => $lvalue) { echo "
        /> -
        +

        :
        -
        +
        -
        +
        -
        +
        From 1188cdc865d6539469ffb9e3fcf50d0998cce751 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Fri, 13 Mar 2015 00:15:05 -0500 Subject: [PATCH 243/257] touch up interfaces.php text --- .../share/locale/en/LC_MESSAGES/pfSense.pot | 4 ++-- .../share/locale/ja/LC_MESSAGES/pfSense.po | 4 ++-- .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo | Bin 642980 -> 642962 bytes .../pt_BR.ISO8859-1/LC_MESSAGES/pfSense.po | 4 ++-- .../share/locale/tr/LC_MESSAGES/pfSense.mo | Bin 578237 -> 578219 bytes .../share/locale/tr/LC_MESSAGES/pfSense.po | 4 ++-- usr/local/www/interfaces.php | 4 ++-- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot index fff8739399..e62cdb34bf 100644 --- a/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot +++ b/usr/local/share/locale/en/LC_MESSAGES/pfSense.pot @@ -14815,7 +14815,7 @@ msgstr "" #: usr/local/www/interfaces.php:3262 msgid "" -"Allowed values are 1-9999 but should not be longer than Master Key " +"Allowed values are 1-9999. Must be longer than Master Key " "Regeneration time." msgstr "" @@ -14825,7 +14825,7 @@ msgstr "" #: usr/local/www/interfaces.php:3269 msgid "" -"Allowed values are 1-9999 but should not be shorter than Key Rotation time." +"Allowed values are 1-9999. Must be shorter than Key Rotation time." msgstr "" #: usr/local/www/interfaces.php:3273 diff --git a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po index c5379e58a7..053f69daaa 100644 --- a/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/ja/LC_MESSAGES/pfSense.po @@ -23278,7 +23278,7 @@ msgstr "キーローテーション" #: usr/local/www/interfaces.php:2593 usr/local/www/interfaces.php:2582 #: usr/local/www/interfaces.php:2582 msgid "" -"Allowed values are 1-9999 but should not be longer than Master Key " +"Allowed values are 1-9999. Must be longer than Master Key " "Regeneration time." msgstr ""指定ã§ãる値ã¯1ã‹ã‚‰9999ã§ã™ãŒã€ãƒžã‚¹ã‚¿ãƒ¼ã‚­ãƒ¼ã‚ˆã‚Šã‚‚é•·ãã™ã¹ãã§ã¯ãªã„ã€å†ç”Ÿæ™‚間。" @@ -23294,7 +23294,7 @@ msgstr "マスターキーã®å†ç”Ÿæˆ" #: usr/local/www/interfaces.php:2600 usr/local/www/interfaces.php:2589 #: usr/local/www/interfaces.php:2589 msgid "" -"Allowed values are 1-9999 but should not be shorter than Key Rotation time." +"Allowed values are 1-9999. Must be shorter than Key Rotation time." msgstr ""指定ã§ãる値ã¯1ã‹ã‚‰9999ã§ã™ãŒã€ã‚­ãƒ¼ãƒ­ãƒ¼ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³æ™‚間より短ãã™ã¹ãã§ã¯ãªã„。" #: usr/local/www/interfaces.php:2360 usr/local/www/interfaces.php:2540 diff --git a/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo b/usr/local/share/locale/pt_BR.ISO8859-1/LC_MESSAGES/pfSense.mo index 419127ad83f49a072077c2db19f8d03381628f7f..cac0c9ec498c29c4f778c7d65416f908ebf61848 100644 GIT binary patch delta 64 zcmZ27UwzVi^@bM4Ell+;ta=K*rNz^GU6?!|%=X7FOhC*G#4JF}3dC$c%nrmH+aJ4d H9_#`D21ywj delta 82 zcmbOKf O2E^>!zY23~+Xn!GEFJ&= diff --git a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po index e64d0f3393..71a21af344 100644 --- a/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po +++ b/usr/local/share/locale/tr/LC_MESSAGES/pfSense.po @@ -15445,7 +15445,7 @@ msgstr "Anahtar Rotasyonu" #: usr/local/www/interfaces.php:3262 msgid "" -"Allowed values are 1-9999 but should not be longer than Master Key " +"Allowed values are 1-9999. Must be longer than Master Key " "Regeneration time." msgstr "" "İzin verilen deÄŸerler 1 ile 9999 arasındadır ama Ana Anahtar Yenileme " @@ -15457,7 +15457,7 @@ msgstr "Ana Anahtar Yenileme" #: usr/local/www/interfaces.php:3269 msgid "" -"Allowed values are 1-9999 but should not be shorter than Key Rotation time." +"Allowed values are 1-9999. Must be shorter than Key Rotation time." msgstr "" "İzin verilen deÄŸerler 1 ile 9999 arasındadır ama Anahtar Rotasyon zamanından " "fazla olmamalıdır." diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 9bcd2e0bcf..e92fb369fa 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -3326,14 +3326,14 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), " /> -
        +
        " /> -
        +
        From 3fdd9cfa870946cd8347b1287f20e67630395f42 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Fri, 13 Mar 2015 01:19:47 -0500 Subject: [PATCH 244/257] Auto-size the interface box on the bridge edit page. --- usr/local/www/interfaces_bridge_edit.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/usr/local/www/interfaces_bridge_edit.php b/usr/local/www/interfaces_bridge_edit.php index bb68e63b26..6fc1d710e9 100644 --- a/usr/local/www/interfaces_bridge_edit.php +++ b/usr/local/www/interfaces_bridge_edit.php @@ -264,6 +264,7 @@ function show_source_port_range() { + @@ -272,7 +273,7 @@ function show_source_port_range() { @@ -3317,7 +3317,7 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), From 141d316c7fd415c5aa9112dc77ef37de33fc585b Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Fri, 13 Mar 2015 02:54:30 -0500 Subject: [PATCH 246/257] Default to 11ng if an option hasn't been configured. Previously we let the browser pick the first in the list (the first the card reported as available), which ended up being 802.11b. Ticket #4516 --- usr/local/www/interfaces.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 12c5044d31..5d027d8f5c 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -2953,8 +2953,14 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), foreach($wl_modes as $wl_standard => $wl_channels) { $rowIndex++; echo "\n"; } if ($rowIndex == 0) From 0a950c4b0a3df300ddce1894d83a9188fc8df47f Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Fri, 13 Mar 2015 03:06:36 -0500 Subject: [PATCH 247/257] Apply WME input validation to all modes, not just hostap. Ticket #4516 --- usr/local/www/interfaces.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 5d027d8f5c..0e32d7f122 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -771,16 +771,16 @@ if ($_POST['apply']) { if ($_POST['mode'] == 'hostap') { $reqdfields[] = "ssid"; $reqdfieldsn[] = gettext("SSID"); - if (stristr($_POST['standard'], '11n')) { - if (!($_POST['wme_enable'])) { - $input_errors[] = gettext("802.11n standards require enabling WME."); - } - } if (isset($_POST['channel']) && $_POST['channel'] == "0") { // auto channel with hostap is broken, prevent this for now. $input_errors[] = gettext("A specific channel, not auto, must be selected for Access Point mode."); } } + if (stristr($_POST['standard'], '11n')) { + if (!($_POST['wme_enable'])) { + $input_errors[] = gettext("802.11n standards require enabling WME."); + } + } do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); check_wireless_mode(); if (isset($_POST['wpa_group_rekey']) && (!is_numericint($_POST['wpa_group_rekey']) || $_POST['wpa_group_rekey'] < 1 || $_POST['wpa_group_rekey'] > 9999)) { From f2f34088ace895b0113b468b856ceb02301585d1 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Fri, 13 Mar 2015 03:15:10 -0500 Subject: [PATCH 248/257] txpower was disabled for good reason it would appear, it triggers syntax errors in some configurations. Disable it again since it's been disabled for years, and comment out the user-facing config portion for now since it doesn't do anything. Ticket #4516 --- etc/inc/interfaces.inc | 4 +++- usr/local/www/interfaces.php | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index 8c4032834a..a980d47285 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -2630,9 +2630,11 @@ function interface_wireless_configure($if, &$wl, &$wlcfg) { } /* handle txpower setting */ + // or don't. this has issues at the moment. + /* if($wlcfg['txpower'] <> "" && is_numeric($wlcfg['txpower'])) { $wlcmd[] = "txpower " . escapeshellarg($wlcfg['txpower']); - } + }*/ /* handle wme option */ if (isset($wlcfg['wme']['enable'])) { diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 0e32d7f122..2248aaad36 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -2986,6 +2986,7 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), + - + */ + ?>
        - $ifinfo) { From d31517e5fa795e1b16b45174552d4d6e6a10dc6c Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Fri, 13 Mar 2015 02:29:56 -0500 Subject: [PATCH 245/257] Default to WPA2, AES for new wireless interface configs. Ticket #4516 --- usr/local/www/interfaces.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index e92fb369fa..12c5044d31 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -3286,7 +3286,7 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"), @@ -3002,7 +3003,8 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"),
        From a08d505596b79a1ac0465d0ac898ca070c7d613f Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Fri, 13 Mar 2015 14:30:51 +0545 Subject: [PATCH 249/257] Update get_possible_traffic_source_addresses returned array format With this change it looks to me like the way it is intended to be, based on what was done to get_possible_listen_ips() Please review and check if this is what was intended for the code. With this change it should make the returned $sourceips array be in a consistent format the same way as get_possible_listen_ips() This is a fix for code that was only committed in master. So at this time the fix is only needed in master. --- etc/inc/interfaces.inc | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index a980d47285..9d02b911d1 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -5266,10 +5266,8 @@ function get_possible_traffic_source_addresses($include_ipv6_link_local=false) { if (is_array($config['openvpn']["openvpn-{$mode}"])) { foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) { if (!isset($setting['disable'])) { - $vpn = array(); - $vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid']; - $vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']); - $sourceips[] = $vpn; + $sourceips_key = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid']; + $sourceips[$sourceips_key] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']); } } } From 6fee314baed1bc82f3571c8acfc257057597b036 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Fri, 13 Mar 2015 23:10:14 +0545 Subject: [PATCH 250/257] pfSsh.php readline function return value This just looks wrong. But I guess the code path never comes through here because function readline() already exists in the environment of this script. --- usr/local/sbin/pfSsh.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/sbin/pfSsh.php b/usr/local/sbin/pfSsh.php index e165fcd28f..16aaa0a6b5 100755 --- a/usr/local/sbin/pfSsh.php +++ b/usr/local/sbin/pfSsh.php @@ -48,8 +48,8 @@ if(!function_exists("readline")) { $fp = fopen('php://stdin', 'r'); $textinput = chop(fgets($fp)); fclose($fp); + return $textinput; } - return $textinput; } function more($text, $count=24) { From 7d61beba45e06f4be2fc5436f14e879ec7dd2675 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Fri, 13 Mar 2015 23:28:12 +0545 Subject: [PATCH 251/257] Code Style sbin tmp usr Bits and pieces from sbin tmp and usr but not yet usr/local/www --- sbin/dhclient-script | 8 +- tmp/post_upgrade_command.php | 13 +- usr/local/bin/3gstats.php | 6 +- usr/local/bin/beep.sh | 32 ++-- usr/local/bin/captiveportal_gather_stats.php | 62 +++--- usr/local/bin/easyrule | 35 ++-- usr/local/bin/filterparser.php | 6 +- usr/local/bin/mail.php | 9 +- usr/local/bin/ping_hosts.sh | 6 +- usr/local/captiveportal/index.php | 31 +-- usr/local/captiveportal/radius_accounting.inc | 40 ++-- .../captiveportal/radius_authentication.inc | 40 ++-- usr/local/pkg/miniupnpd.inc | 171 ++++++++++------- usr/local/pkg/miniupnpd.xml | 10 +- usr/local/sbin/WipePackages.php | 12 +- usr/local/sbin/gmirror_status_check.php | 15 +- usr/local/sbin/openvpn.attributes.sh | 2 +- usr/local/sbin/ovpn-linkup | 2 +- usr/local/sbin/pfSsh.php | 176 +++++++++--------- usr/local/sbin/prefixes.php | 27 +-- usr/local/sbin/show_filter_reload_status.php | 30 +-- 21 files changed, 398 insertions(+), 335 deletions(-) diff --git a/sbin/dhclient-script b/sbin/dhclient-script index 3ce2b248b5..9d71aaf19b 100755 --- a/sbin/dhclient-script +++ b/sbin/dhclient-script @@ -187,7 +187,7 @@ delete_old_routes() { while [ $# -gt 1 ]; do $ROUTE delete "$1" "$2" shift; shift - /bin/rm -f /tmp/${interface}_router + /bin/rm -f /tmp/${interface}_router done fi @@ -236,7 +236,7 @@ add_new_routes() { else $ROUTE add default $router echo $ROUTE add default $router | $LOGGER - echo $router > /tmp/${interface}_router + echo $router > /tmp/${interface}_router fi ADDED_ROUTE=yes # 2nd and subsequent default routers error out, so explicitly @@ -251,7 +251,7 @@ add_new_routes() { while [ $# -gt 1 ]; do $ROUTE add $1 $2 if [ "$ADDED_ROUTE" = "no" ]; then - echo $2 > /tmp/${interface}_router + echo $2 > /tmp/${interface}_router fi shift; shift done @@ -266,7 +266,7 @@ add_new_resolv_conf() { $ROUTE delete $nameserver >/dev/null 2>&1 done fi - if [ -n "$new_domain_name_servers" ]; then + if [ -n "$new_domain_name_servers" ]; then /bin/rm -f /var/etc/nameserver_$interface ALLOWOVERRIDE=`/usr/bin/grep dnsallowoverride /conf/config.xml | /usr/bin/wc -l` for nameserver in $new_domain_name_servers; do diff --git a/tmp/post_upgrade_command.php b/tmp/post_upgrade_command.php index a33dbb6173..c2b6901d6d 100755 --- a/tmp/post_upgrade_command.php +++ b/tmp/post_upgrade_command.php @@ -6,18 +6,21 @@ require_once("config.inc"); require_once("functions.inc"); - if(file_exists("/usr/local/bin/git") && isset($config['system']['gitsync']['synconupgrade'])) { - if(!empty($config['system']['gitsync']['repositoryurl'])) + if (file_exists("/usr/local/bin/git") && isset($config['system']['gitsync']['synconupgrade'])) { + if (!empty($config['system']['gitsync']['repositoryurl'])) { exec("cd /root/pfsense/pfSenseGITREPO/pfSenseGITREPO && git config remote.origin.url " . escapeshellarg($config['system']['gitsync']['repositoryurl'])); - if(!empty($config['system']['gitsync']['branch'])) + } + if (!empty($config['system']['gitsync']['branch'])) { system("pfSsh.php playback gitsync " . escapeshellarg($config['system']['gitsync']['branch']) . " --upgrading"); + } } $newslicedir = ""; - if (isset($argv[1]) && $argv[1] != "") + if (isset($argv[1]) && $argv[1] != "") { $newslicedir = '/tmp/' . $argv[1]; + } - if($g['enableserial_force'] || file_exists("{$newslicedir}/enableserial_force")) { + if ($g['enableserial_force'] || file_exists("{$newslicedir}/enableserial_force")) { $config['system']['enableserial'] = true; write_config(); } diff --git a/usr/local/bin/3gstats.php b/usr/local/bin/3gstats.php index a8a8fec36e..daf0500b69 100755 --- a/usr/local/bin/3gstats.php +++ b/usr/local/bin/3gstats.php @@ -35,7 +35,7 @@ $record['bwdownstream'] = 0; $record['simstate'] = 0; $record['service'] = 0; -while(true) { +while (true) { $string = ""; $string = fgets($handle, 256); @@ -44,7 +44,7 @@ while(true) { $elements[0] = trim($elements[0]); $elements[1] = trim($elements[1]); - switch($elements[0]) { + switch ($elements[0]) { case "^MODE": $record['mode'] = $elements[1]; break; @@ -70,7 +70,7 @@ while(true) { break; } - if($i > 10) { + if ($i > 10) { $csv = $header; $csv .= implode(",", $record); $csv .= "\n"; diff --git a/usr/local/bin/beep.sh b/usr/local/bin/beep.sh index 29a918c1f6..ed9382dddc 100755 --- a/usr/local/bin/beep.sh +++ b/usr/local/bin/beep.sh @@ -17,7 +17,7 @@ if [ -f /var/log/dmesg.boot ]; then fi fi -# Check for different HZ +# Check for different HZ if [ -f /boot/loader.conf ]; then HZ=`/usr/bin/grep -c kern.hz /boot/loader.conf` if [ "$HZ" = "1" ]; then @@ -25,19 +25,19 @@ if [ -f /boot/loader.conf ]; then fi fi -if [ -c "/dev/speaker" ]; then - if [ "$1" = "start" ]; then - /usr/local/bin/beep -p 500 $NOTELENGTH - /usr/local/bin/beep -p 400 $NOTELENGTH - /usr/local/bin/beep -p 600 $NOTELENGTH - /usr/local/bin/beep -p 800 $NOTELENGTH - /usr/local/bin/beep -p 800 $NOTELENGTH - fi - if [ "$1" = "stop" ]; then - /usr/local/bin/beep -p 600 $NOTELENGTH - /usr/local/bin/beep -p 800 $NOTELENGTH - /usr/local/bin/beep -p 500 $NOTELENGTH - /usr/local/bin/beep -p 400 $NOTELENGTH - /usr/local/bin/beep -p 400 $NOTELENGTH - fi +if [ -c "/dev/speaker" ]; then + if [ "$1" = "start" ]; then + /usr/local/bin/beep -p 500 $NOTELENGTH + /usr/local/bin/beep -p 400 $NOTELENGTH + /usr/local/bin/beep -p 600 $NOTELENGTH + /usr/local/bin/beep -p 800 $NOTELENGTH + /usr/local/bin/beep -p 800 $NOTELENGTH + fi + if [ "$1" = "stop" ]; then + /usr/local/bin/beep -p 600 $NOTELENGTH + /usr/local/bin/beep -p 800 $NOTELENGTH + /usr/local/bin/beep -p 500 $NOTELENGTH + /usr/local/bin/beep -p 400 $NOTELENGTH + /usr/local/bin/beep -p 400 $NOTELENGTH + fi fi diff --git a/usr/local/bin/captiveportal_gather_stats.php b/usr/local/bin/captiveportal_gather_stats.php index c0766368c3..11cb2b9f14 100644 --- a/usr/local/bin/captiveportal_gather_stats.php +++ b/usr/local/bin/captiveportal_gather_stats.php @@ -2,31 +2,31 @@ $previous_user_timestamp) + if ($timestamp > $previous_user_timestamp) { $current_user_count = $current_user_count + 1; + } } // Write out the latest timestamp but not if it is empty @@ -98,13 +101,14 @@ if ($type == "loggedin") { /* If $timestamp is less than or equal to previous_user_timestamp return 0, * as we only want the 'X' number of users logged in since last RRD poll. */ - if($timestamp <= $previous_user_timestamp) + if ($timestamp <= $previous_user_timestamp) { $result = 0; - else { + } else { $result = $current_user_count; } -} elseif ($type == "concurrent") +} elseif ($type == "concurrent") { $result = $no_users; +} echo "$result"; diff --git a/usr/local/bin/easyrule b/usr/local/bin/easyrule index 9850aee7b9..f00a7cb4fa 100755 --- a/usr/local/bin/easyrule +++ b/usr/local/bin/easyrule @@ -10,11 +10,11 @@ modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -50,29 +50,32 @@ function pconfig_to_address(&$adr, $padr, $pmask, $pnot=false, $pbeginport=0, $p $adr = array(); - if ($padr == "any") + if ($padr == "any") { $adr['any'] = true; - else if (is_specialnet($padr)) + } else if (is_specialnet($padr)) { $adr['network'] = $padr; - else { + } else { $adr['address'] = $padr; - if ($pmask != 32) + if ($pmask != 32) { $adr['address'] .= "/" . $pmask; + } } - if ($pnot) + if ($pnot) { $adr['not'] = true; - else + } else { unset($adr['not']); + } if (($pbeginport != 0) && ($pbeginport != "any")) { - if ($pbeginport != $pendport) + if ($pbeginport != $pendport) { $adr['port'] = $pbeginport . "-" . $pendport; - else + } else { $adr['port'] = $pbeginport; + } } - if(is_alias($pbeginport)) { + if (is_alias($pbeginport)) { $adr['port'] = $pbeginport; } } @@ -81,12 +84,14 @@ function pconfig_to_address(&$adr, $padr, $pmask, $pnot=false, $pbeginport=0, $p function is_specialnet($net) { global $specialsrcdst; - if(!$net) + if (!$net) { return false; - if (in_array($net, $specialsrcdst)) + } + if (in_array($net, $specialsrcdst)) { return true; - else + } else { return false; + } } diff --git a/usr/local/bin/filterparser.php b/usr/local/bin/filterparser.php index da1f98ecb5..bec80167e7 100755 --- a/usr/local/bin/filterparser.php +++ b/usr/local/bin/filterparser.php @@ -31,8 +31,8 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - A quick CLI log parser. - Examples: + A quick CLI log parser. + Examples: clog /var/log/filter.log | tail -50 | /usr/local/www/filterparser.php clog -f /var/log/filter.log | /usr/local/www/filterparser.php */ @@ -45,7 +45,7 @@ include_once("filter_log.inc"); $log = fopen("php://stdin", "r"); $lastline = ""; -while(!feof($log)) { +while (!feof($log)) { $line = fgets($log); $line = rtrim($line); $flent = parse_filter_line(trim($line)); diff --git a/usr/local/bin/mail.php b/usr/local/bin/mail.php index a09f5c6476..1e62b8140b 100755 --- a/usr/local/bin/mail.php +++ b/usr/local/bin/mail.php @@ -7,18 +7,19 @@ $options = getopt("s::"); $message = ""; -if($options['s'] <> "") { +if ($options['s'] <> "") { $subject = $options['s']; } $in = file("php://stdin"); -foreach($in as $line){ +foreach ($in as $line){ $message .= "$line"; } -if (!empty($subject)) +if (!empty($subject)) { send_smtp_message($message, $subject); -else +} else { send_smtp_message($message); +} ?> \ No newline at end of file diff --git a/usr/local/bin/ping_hosts.sh b/usr/local/bin/ping_hosts.sh index d584dd1c56..eef64f39c7 100755 --- a/usr/local/bin/ping_hosts.sh +++ b/usr/local/bin/ping_hosts.sh @@ -5,9 +5,9 @@ # (C)2006 Scott Ullrich # All rights reserved. -# Format of file should be deliminted by | -# Field 1: Source ip -# Field 2: Destination ip +# Format of file should be delimited by | +# Field 1: Source IP +# Field 2: Destination IP # Field 3: Ping count # Field 4: Script to run when service is down # Field 5: Script to run once service is restored diff --git a/usr/local/captiveportal/index.php b/usr/local/captiveportal/index.php index 19b35d7359..357537fc2a 100644 --- a/usr/local/captiveportal/index.php +++ b/usr/local/captiveportal/index.php @@ -83,12 +83,13 @@ if ($orig_host != $ourhostname) { return; } -if (!empty($cpcfg['redirurl'])) +if (!empty($cpcfg['redirurl'])) { $redirurl = $cpcfg['redirurl']; -else if (preg_match("/redirurl=(.*)/", $orig_request, $matches)) +} else if (preg_match("/redirurl=(.*)/", $orig_request, $matches)) { $redirurl = urldecode($matches[1]); -else if ($_REQUEST['redirurl']) +} else if ($_REQUEST['redirurl']) { $redirurl = $_REQUEST['redirurl']; +} $macfilter = !isset($cpcfg['nomacfilter']); $passthrumac = isset($cpcfg['passthrumacadd']); @@ -111,14 +112,16 @@ if ($macfilter || $passthrumac) { /* find out if we need RADIUS + RADIUSMAC or not */ if (file_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db")) { $radius_enable = TRUE; - if (isset($cpcfg['radmac_enable'])) + if (isset($cpcfg['radmac_enable'])) { $radmac_enable = TRUE; + } } /* find radius context */ $radiusctx = 'first'; -if ($_POST['auth_user2']) +if ($_POST['auth_user2']) { $radiusctx = 'second'; +} if ($_POST['logout_id']) { echo << All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. The names of the authors may not be used to endorse or promote products + 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - This code cannot simply be copied and put under the GNU Public License or + This code cannot simply be copied and put under the GNU Public License or any other GPL-like (LGPL, GPL2) License. This code is made possible thx to samples made by Michael Bretterklieber @@ -45,7 +45,7 @@ define('GIGAWORDS_RIGHT_OPERAND', '4294967296'); // 2^32 /* -RADIUS ACCOUNTING START +RADIUS ACCOUNTING START ----------------------- */ @@ -202,9 +202,9 @@ function RADIUS_ACCOUNTING_STOP($ruleno,$username,$sessionid,$start_time,$radius $racct = new Auth_RADIUS_Acct_Stop; /* - Add support for more then one radiusserver. - At most 10 servers may be specified. - When multiple servers are given, they are tried in round-robin fashion until a valid response is received + Add support for more then one radiusserver. + At most 10 servers may be specified. + When multiple servers are given, they are tried in round-robin fashion until a valid response is received */ foreach ($radiusservers as $radsrv) { // Add a new server to our instance diff --git a/usr/local/captiveportal/radius_authentication.inc b/usr/local/captiveportal/radius_authentication.inc index 5f24506795..9938e24ee3 100644 --- a/usr/local/captiveportal/radius_authentication.inc +++ b/usr/local/captiveportal/radius_authentication.inc @@ -6,30 +6,30 @@ Copyright (c) 2006, Jonathan De Graeve All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. The names of the authors may not be used to endorse or promote products + 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - This code cannot simply be copied and put under the GNU Public License or + This code cannot simply be copied and put under the GNU Public License or any other GPL-like (LGPL, GPL2) License. This code is made possible thx to samples made by Michael Bretterklieber @@ -80,9 +80,9 @@ function RADIUS_AUTHENTICATION($username,$password,$radiusservers,$clientip,$cli $rauth = new $classname($username, $password); /* - * Add support for more then one radiusserver. - * At most 10 servers may be specified. - * When multiple servers are given, they are tried in round-robin fashion until a valid response is received + * Add support for more then one radiusserver. + * At most 10 servers may be specified. + * When multiple servers are given, they are tried in round-robin fashion until a valid response is received */ foreach ($radiusservers as $radsrv) { // Add a new server to our instance @@ -126,7 +126,7 @@ function RADIUS_AUTHENTICATION($username,$password,$radiusservers,$clientip,$cli if (PEAR::isError($rauth->start())) { $retvalue['auth_val'] = 1; - $retvalue['error'] = $rauth->getError(); + $retvalue['error'] = $rauth->getError(); // If we encounter an error immediately stop this function and go back $rauth->close(); diff --git a/usr/local/pkg/miniupnpd.inc b/usr/local/pkg/miniupnpd.inc index 34fab47841..0c816a1d5f 100644 --- a/usr/local/pkg/miniupnpd.inc +++ b/usr/local/pkg/miniupnpd.inc @@ -8,18 +8,24 @@ /* MiniUPnPd */ - function upnp_notice ($msg) { log_error("miniupnpd: {$msg}"); } - function upnp_warn ($msg) { log_error("miniupnpd: {$msg}"); } + function upnp_notice($msg) { + log_error("miniupnpd: {$msg}"); + } + + function upnp_warn($msg) { + log_error("miniupnpd: {$msg}"); + } function upnp_running () { - if((int)exec('/bin/pgrep -a miniupnpd | /usr/bin/wc -l') > 0) + if ((int)exec('/bin/pgrep -a miniupnpd | /usr/bin/wc -l') > 0) { return true; + } return false; } function upnp_write_config($file, $text) { $handle = fopen($file, 'w'); - if(!$handle) { + if (!$handle) { upnp_warn("Could not open {$file} for writing."); return; } @@ -45,30 +51,37 @@ } function upnp_validate_ip($ip, $check_cdir) { - /* validate cidr */ + /* validate cidr */ $ip_array = array(); - if($check_cdir) { + if ($check_cdir) { $ip_array = explode('/', $ip); - if(count($ip_array) == 2) { - if($ip_array[1] < 1 || $ip_array[1] > 32) + if (count($ip_array) == 2) { + if ($ip_array[1] < 1 || $ip_array[1] > 32) { return false; - } else - if(count($ip_array) != 1) + } + } else { + if (count($ip_array) != 1) { return false; - } else + } + } + } else { $ip_array[] = $ip; + } /* validate ip */ - if (!is_ipaddr($ip_array[0])) + if (!is_ipaddr($ip_array[0])) { return false; + } return true; } function upnp_validate_port($port) { - foreach(explode('-', $port) as $sub) - if($sub < 0 || $sub > 65535) + foreach (explode('-', $port) as $sub) { + if ($sub < 0 || $sub > 65535) { return false; - return true; + } + } + return true; } function before_form_miniupnpd(&$pkg) { @@ -77,48 +90,58 @@ } function validate_form_miniupnpd($post, &$input_errors) { - if($post['enable'] && (!$post['enable_upnp'] && !$post['enable_natpmp'])) + if ($post['enable'] && (!$post['enable_upnp'] && !$post['enable_natpmp'])) { $input_errors[] = 'At least one of \'UPnP\' or \'NAT-PMP\' must be allowed'; - if($post['iface_array']) - foreach($post['iface_array'] as $iface) { - if($iface == 'wan') + } + if ($post['iface_array']) { + foreach ($post['iface_array'] as $iface) { + if ($iface == 'wan') { $input_errors[] = 'It is a security risk to specify WAN in the \'Interface\' field'; - elseif ($iface == $post['ext_iface']) + } elseif ($iface == $post['ext_iface']) { $input_errors[] = 'You cannot select the external interface as an internal interface.'; + } } - if($post['overridewanip'] && !upnp_validate_ip($post['overridewanip'],false)) + } + if ($post['overridewanip'] && !upnp_validate_ip($post['overridewanip'],false)) { $input_errors[] = 'You must specify a valid ip address in the \'Override WAN address\' field'; - if(($post['download'] && !$post['upload']) || ($post['upload'] && !$post['download'])) + } + if (($post['download'] && !$post['upload']) || ($post['upload'] && !$post['download'])) { $input_errors[] = 'You must fill in both \'Maximum Download Speed\' and \'Maximum Upload Speed\' fields'; - if($post['download'] && $post['download'] <= 0) + } + if ($post['download'] && $post['download'] <= 0) { $input_errors[] = 'You must specify a value greater than 0 in the \'Maximum Download Speed\' field'; - if($post['upload'] && $post['upload'] <= 0) + } + if ($post['upload'] && $post['upload'] <= 0) { $input_errors[] = 'You must specify a value greater than 0 in the \'Maximum Upload Speed\' field'; - if($post['upnpqueue'] && !upnp_validate_queue($post['upnpqueue'])) + } + if ($post['upnpqueue'] && !upnp_validate_queue($post['upnpqueue'])) { $input_errors[] = 'You must specify a valid traffic shaping queue.'; + } /* user permissions validation */ $j = substr_count(implode(array_keys($post)), "permuser"); for ($i=0; $i<$j; $i++){ - if($post["permuser{$i}"]) { + if ($post["permuser{$i}"]) { $perm = explode(' ',$post["permuser{$i}"]); /* should explode to 4 args */ - if(count($perm) != 4) { + if (count($perm) != 4) { $input_errors[] = "You must follow the specified format in the 'User specified permissions {$i}' field"; } else { /* must with allow or deny */ - if(!($perm[0] == 'allow' || $perm[0] == 'deny')) + if (!($perm[0] == 'allow' || $perm[0] == 'deny')) { $input_errors[] = "You must begin with allow or deny in the 'User specified permissions {$i}' field"; + } /* verify port or port range */ - if(!upnp_validate_port($perm[1]) || !upnp_validate_port($perm[3])) - $input_errors[] = "You must specify a port or port range between 0 and 65535 in the 'User specified - permissions {$i}' field"; + if (!upnp_validate_port($perm[1]) || !upnp_validate_port($perm[3])) { + $input_errors[] = "You must specify a port or port range between 0 and 65535 in the 'User specified permissions {$i}' field"; + } /* verify ip address */ - if(!upnp_validate_ip($perm[2],true)) + if (!upnp_validate_ip($perm[2],true)) { $input_errors[] = "You must specify a valid ip address in the 'User specified permissions {$i}' field"; + } } } - } + } } function sync_package_miniupnpd() { @@ -128,13 +151,13 @@ $upnp_config = $config['installedpackages']['miniupnpd']['config'][0]; $config_file = '/var/etc/miniupnpd.conf'; - if (!isset($upnp_config['ext_iface']) || empty($upnp_config['ext_iface'])) + if (!isset($upnp_config['ext_iface']) || empty($upnp_config['ext_iface'])) { $ext_ifname = get_real_interface(); - else { + } else { $if = convert_friendly_interface_to_real_interface_name($upnp_config['ext_iface']); - if ($if != $upnp_config['ext_iface']) + if ($if != $upnp_config['ext_iface']) { $ext_ifname = $if; - else { + } else { $ext_ifname = get_real_interface(); upnp_warn("Could not resolve real interface for {$upnp_config['ext_iface']}, defaulting to WAN"); } @@ -145,60 +168,68 @@ $ifaces_active = ''; - /* since config is written before this file invoked we don't need to read post data */ - if($upnp_config['enable'] && !empty($upnp_config['iface_array'])) { + /* since config is written before this file is invoked we don't need to read post data */ + if ($upnp_config['enable'] && !empty($upnp_config['iface_array'])) { $iface_array = explode(',', $upnp_config['iface_array']); - foreach($iface_array as $iface) { + foreach ($iface_array as $iface) { /* Setting the same internal and external interface is not allowed. */ - if ($iface == $upnp_config['ext_iface']) + if ($iface == $upnp_config['ext_iface']) { continue; + } $if = convert_friendly_interface_to_real_interface_name($iface); /* above function returns iface if fail */ - if($if!=$iface) { + if ($if!=$iface) { $addr = find_interface_ip($if); $bits = find_interface_subnet($if); /* check that the interface has an ip address before adding parameters */ if (is_ipaddr($addr)) { $config_text .= "listening_ip={$if}\n"; - if(!$ifaces_active) { + if (!$ifaces_active) { $webgui_ip = $addr; $ifaces_active = $iface; - } else + } else { $ifaces_active .= ", {$iface}"; - } else + } + } else { upnp_warn("Interface {$iface} has no ip address, ignoring"); - } else + } + } else { upnp_warn("Could not resolve real interface for {$iface}"); + } } if (!empty($ifaces_active)) { /* override wan ip address, common for carp, etc */ - if($upnp_config['overridewanip']) + if ($upnp_config['overridewanip']) { $config_text .= "ext_ip={$upnp_config['overridewanip']}\n"; + } $download = $upnp_config['download']*1000; $upload = $upnp_config['upload']*1000; /* set upload and download bitrates */ - if(!empty($download) && !empty($upload)) { + if (!empty($download) && !empty($upload)) { $config_text .= "bitrate_down={$download}\n"; $config_text .= "bitrate_up={$upload}\n"; } - + /* enable logging of packets handled by miniupnpd rules */ - if($upnp_config['logpackets']) + if ($upnp_config['logpackets']) { $config_text .= "packet_log=yes\n"; - + } + /* enable system uptime instead of miniupnpd uptime */ - if($upnp_config['sysuptime']) + if ($upnp_config['sysuptime']) { $config_text .= "system_uptime=yes\n"; + } /* set webgui url */ - if(!empty($config['system']['webgui']['protocol'])) { + if (!empty($config['system']['webgui']['protocol'])) { $config_text .= "presentation_url={$config['system']['webgui']['protocol']}://{$webgui_ip}"; - if(!empty($config['system']['webgui']['port'])) + if (!empty($config['system']['webgui']['port'])) { $config_text .= ":{$config['system']['webgui']['port']}"; + } $config_text .= "/\n"; } @@ -208,23 +239,27 @@ /* set model number */ $config_text .= "model_number=".file_get_contents("/etc/version")."\n"; - + /* upnp access restrictions */ foreach($upnp_config['row'] as $row){ - if($row['permuser']) + if($row['permuser']) { $config_text .= "{$row["permuser"]}\n"; + } } - if($upnp_config['permdefault']) + if ($upnp_config['permdefault']) { $config_text .= "deny 0-65535 0.0.0.0/0 0-65535\n"; + } /* Recheck if queue is valid */ - if (!upnp_validate_queue($upnp_config['upnpqueue'])) + if (!upnp_validate_queue($upnp_config['upnpqueue'])) { unset($upnp_config['upnpqueue']); + } /* Add shaper queue */ - if($upnp_config['upnpqueue']) + if($upnp_config['upnpqueue']) { $config_text .= "queue={$upnp_config['upnpqueue']}\n"; + } /* Allow UPnP or NAT-PMP as requested */ $config_text .= "enable_upnp=" . ( $upnp_config['enable_upnp'] ? "yes\n" : "no\n" ); @@ -232,14 +267,13 @@ /* write out the configuration */ upnp_write_config($config_file, $config_text); - + /* if miniupnpd not running start it */ - if(!upnp_running()) { + if (!upnp_running()) { upnp_notice("Starting service on interface: {$ifaces_active}"); - upnp_action('start'); - } - /* or restart miniupnpd if settings were changed */ - else { + upnp_action('start'); + } else { + /* restart miniupnpd if settings were changed */ upnp_notice("Restarting service on interface: {$ifaces_active}"); upnp_action('restart'); } @@ -249,10 +283,11 @@ /* lets stop the service and remove the rc file */ if (file_exists($config_file)) { - if(!$upnp_config['enable']) + if (!$upnp_config['enable']) { upnp_notice('Stopping service: miniupnpd disabled'); - else - upnp_notice('Stopping service: no interfaces selected'); + } else { + upnp_notice('Stopping service: no interfaces selected'); + } upnp_action('stop'); @unlink($config_file); diff --git a/usr/local/pkg/miniupnpd.xml b/usr/local/pkg/miniupnpd.xml index c26587be88..e15bbd74ca 100644 --- a/usr/local/pkg/miniupnpd.xml +++ b/usr/local/pkg/miniupnpd.xml @@ -13,13 +13,13 @@ https://packages.pfsense.org/packages/config/miniupnpd/miniupnpd.inc - /usr/local/pkg/ - 0755 + /usr/local/pkg/ + 0755 https://packages.pfsense.org/packages/config/miniupnpd/status_upnp.php - /usr/local/www/ - 0755 + /usr/local/www/ + 0755 /usr/local/sbin/ @@ -42,7 +42,7 @@ enable checkbox enable_upnp,enable_natpmp,ext_iface,iface_array,download,upload,overridewanip,upnpqueue,logpackets,sysuptime,permdefault - + Allow UPnP Port Mapping enable_upnp diff --git a/usr/local/sbin/WipePackages.php b/usr/local/sbin/WipePackages.php index d802521028..44f24bfcbb 100755 --- a/usr/local/sbin/WipePackages.php +++ b/usr/local/sbin/WipePackages.php @@ -30,7 +30,7 @@ POSSIBILITY OF SUCH DAMAGE. */ -if(!function_exists("readline")) { +if (!function_exists("readline")) { echo "\nThis script requires the readline() libary which is not present on this system."; echo "\n\nSorry, but we cannot continue.\n"; die("Need readline() library"); @@ -42,23 +42,23 @@ require("config.inc"); echo "\nThis script will wipe all installed packages off of your pfSense installation.\n"; $command = readline("\nAre you sure you would like to continue [y/N]? "); -if(strtoupper($command) == "Y" || strtoupper($command) == "YES") { +if (strtoupper($command) == "Y" || strtoupper($command) == "YES") { $rmconfig = readline("\nWould you like to remove all package configuration information as well [y/N]? "); echo "\n\nStarting package wipe... One moment please... "; exec("cd /var/db/pkg/ && find . -exec 'pkg_delete {}' \; "); exec("rm -rf /var/db/pkg/*"); - - if(strtoupper($rmconfig) == "Y" || strtoupper($rmconfig) == "YES") { + + if (strtoupper($rmconfig) == "Y" || strtoupper($rmconfig) == "YES") { echo "\nRemoving pfSense package configuration information..."; - if($config['installedpackages']['package']) { + if ($config['installedpackages']['package']) { unset($config['installedpackages']['package']); write_config("Package wipe procedure completed."); } echo "\n"; } - + echo "\npfSense package wipe procedure has completed.\n\n"; } diff --git a/usr/local/sbin/gmirror_status_check.php b/usr/local/sbin/gmirror_status_check.php index d5a55c1dd3..4f73baf832 100644 --- a/usr/local/sbin/gmirror_status_check.php +++ b/usr/local/sbin/gmirror_status_check.php @@ -9,11 +9,11 @@ modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INClUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -54,8 +54,9 @@ if (file_exists($status_file)) { sort($previous_mirror_list); if (count($previous_mirror_status) > 0) { // Check list of current mirrors vs old mirrors, notify if one has appeared/disappeared - if ($mirror_list != $previous_mirror_list) + if ($mirror_list != $previous_mirror_list) { $notices[] = sprintf(gettext("List of mirrors changed. Old: (%s) New: (%s)"), implode(", ", $previous_mirror_list), implode(", ", $mirror_list)); + } // For each mirror, check the mirror status, notify if changed foreach ($mirror_list as $mirror) { @@ -73,11 +74,12 @@ if (file_exists($status_file)) { // Check the drive status as it may be different. asort($mirror_status[$mirror]['components']); asort($previous_mirror_status[$mirror]['components']); - if ($mirror_status[$mirror]['components'] != $previous_mirror_status[$mirror]['components']) + if ($mirror_status[$mirror]['components'] != $previous_mirror_status[$mirror]['components']) { $notices[] = sprintf(gettext("Mirror %s drive status changed. Old: (%s) New: (%s)"), $mirror, implode(", ", $previous_mirror_status[$mirror]['components']), implode(", ", $mirror_status[$mirror]['components'])); + } } } } @@ -87,7 +89,8 @@ if (count($notices)) { file_notice("gmirror", implode("\n ", $notices), "GEOM Mirror Status Change", 1); } // Write out current status if changed -if ($mirror_status != $previous_mirror_status) +if ($mirror_status != $previous_mirror_status) { file_put_contents($status_file, serialize($mirror_status)); +} ?> diff --git a/usr/local/sbin/openvpn.attributes.sh b/usr/local/sbin/openvpn.attributes.sh index b88d1dfbf6..add8e3218b 100755 --- a/usr/local/sbin/openvpn.attributes.sh +++ b/usr/local/sbin/openvpn.attributes.sh @@ -8,7 +8,7 @@ if [ "$script_type" = "client-connect" ]; then fi elif [ "$script_type" = "client-disconnect" ]; then command="/sbin/pfctl -a 'openvpn/$common_name' -F rules" - eval $command + eval $command /sbin/pfctl -k $ifconfig_pool_remote_ip /sbin/pfctl -K $ifconfig_pool_remote_ip fi diff --git a/usr/local/sbin/ovpn-linkup b/usr/local/sbin/ovpn-linkup index 7c9817a7af..1164835410 100755 --- a/usr/local/sbin/ovpn-linkup +++ b/usr/local/sbin/ovpn-linkup @@ -16,6 +16,6 @@ if [ "${dev_type}" = "tun" ]; then fi /usr/bin/touch /tmp/${1}up -# reload filter +# reload filter /usr/local/sbin/pfSctl -c "interface newip ${1}" exit 0 diff --git a/usr/local/sbin/pfSsh.php b/usr/local/sbin/pfSsh.php index e165fcd28f..642b32bad4 100755 --- a/usr/local/sbin/pfSsh.php +++ b/usr/local/sbin/pfSsh.php @@ -1,5 +1,5 @@ #!/usr/local/bin/php -f - + array("pipe", "r"), // stdin - 1 => array("pipe", "w"), // stdout - 2 => array("pipe", "w")); // stderr ?? instead of a file - + 0 => array("pipe", "r"), // stdin + 1 => array("pipe", "w"), // stdout + 2 => array("pipe", "w")); // stderr ?? instead of a file + $fd = proc_open("$command", $descriptorspec, $pipes); if (is_resource($fd)) { - fwrite($pipes[0], "{$text_to_pipe}"); - fclose($pipes[0]); - while($s= fgets($pipes[1], 1024)) { - // read from the pipe - $buffer .= $s; - } - fclose($pipes[1]); - fclose($pipes[2]); + fwrite($pipes[0], "{$text_to_pipe}"); + fclose($pipes[0]); + while ($s= fgets($pipes[1], 1024)) { + // read from the pipe + $buffer .= $s; + } + fclose($pipes[1]); + fclose($pipes[2]); } return $buffer; } -if(!function_exists("readline")) { +if (!function_exists("readline")) { function readline() { $fp = fopen('php://stdin', 'r'); $textinput = chop(fgets($fp)); @@ -53,21 +53,22 @@ if(!function_exists("readline")) { } function more($text, $count=24) { - $counter=0; - $lines = explode("\n", $text); - foreach($lines as $line) { - if($counter > $count) { - echo "Press RETURN to continue ..."; - $fp = fopen('php://stdin', 'r'); - $pressreturn = chop(fgets($fp)); - if($pressreturn == "q" || $pressreturn == "quit") - return; - fclose($fp); - $counter = 0; - } - echo "{$line}\n"; - $counter++; - } + $counter=0; + $lines = explode("\n", $text); + foreach ($lines as $line) { + if ($counter > $count) { + echo "Press RETURN to continue ..."; + $fp = fopen('php://stdin', 'r'); + $pressreturn = chop(fgets($fp)); + if ($pressreturn == "q" || $pressreturn == "quit") { + return; + } + fclose($fp); + $counter = 0; + } + echo "{$line}\n"; + $counter++; + } } function show_help() { @@ -75,7 +76,7 @@ function show_help() { $show_help_text = << "." and $file <> "..") { + foreach ($files as $file) { + if ($file <> "." and $file <> "..") { echo $file . " "; - if(function_exists("readline_add_history")) { + if (function_exists("readline_add_history")) { readline_add_history("playback $file"); $tccommands[] = "$file"; } @@ -183,8 +184,8 @@ $recording = false; $playback_file_split = array(); $playbackbuffer = ""; -if($argv[1]=="playback" or $argv[1]=="run") { - if(!file_exists("/etc/phpshellsessions/{$argv[2]}")) { +if ($argv[1]=="playback" or $argv[1]=="run") { + if (!file_exists("/etc/phpshellsessions/{$argv[2]}")) { echo "Could not locate playback file."; exit; } @@ -205,14 +206,14 @@ $tccommands[] = "reset"; $tccommands[] = "master"; $tccommands[] = "RELENG_1_2"; -while($shell_active == true) { +while ($shell_active == true) { $command = readline("{$g['product_name']} shell: "); readline_add_history($command); - $command_split = explode(" ", $command); - $first_command = $command_split[0]; - if($first_command == "playback" || $first_command == "run") { + $command_split = explode(" ", $command); + $first_command = $command_split[0]; + if ($first_command == "playback" || $first_command == "run") { $playback_file = $command_split[1]; - if(!$playback_file || !file_exists("/etc/phpshellsessions/{$playback_file}")) { + if (!$playback_file || !file_exists("/etc/phpshellsessions/{$playback_file}")) { $command = ""; echo "Could not locate playback file.\n"; } else { @@ -222,42 +223,43 @@ while($shell_active == true) { continue; } } - if($first_command == "exit" or $first_command == "quit") + if ($first_command == "exit" or $first_command == "quit") { die; - if($first_command == "help" or $first_command == "?") { + } + if ($first_command == "help" or $first_command == "?") { show_help(); $playbackbuffer = ""; continue; } - if($first_command == "exec" or $first_command == "exec;") { + if ($first_command == "exec" or $first_command == "exec;") { playback_text($playbackbuffer); $playbackbuffer = ""; continue; } - if($first_command == "stoprecording" || $first_command == "stoprecord" || $first_command == "stop") { - if($recording) { + if ($first_command == "stoprecording" || $first_command == "stoprecord" || $first_command == "stop") { + if ($recording) { fwrite($recording_fd, $playbackbuffer); fclose($recording_fd); $command = ""; conf_mount_ro(); echo "Recording stopped.\n"; - $recording = false; + $recording = false; } else { echo "No recording session in progress.\n"; $command = ""; } } - if($first_command == "showrecordings") { + if ($first_command == "showrecordings") { show_recordings(); - $command = ""; + $command = ""; } - if($first_command == "reset") { + if ($first_command == "reset") { $playbackbuffer = ""; echo "\nBuffer reset.\n\n"; continue; } - if($first_command == "record") { - if(!$command_split[1]) { + if ($first_command == "record") { + if (!$command_split[1]) { echo "usage: record playbackname\n"; $command = ""; } else { @@ -265,10 +267,10 @@ while($shell_active == true) { conf_mount_rw(); safe_mkdir("/etc/phpshellsessions"); $recording_fd = fopen("/etc/phpshellsessions/{$command_split[1]}","w"); - if(!$recording_fd) { + if (!$recording_fd) { echo "Could not start recording session.\n"; $command = ""; - } else { + } else { $recording = true; echo "Recording of {$command_split[1]} started.\n"; $command = ""; @@ -281,28 +283,30 @@ while($shell_active == true) { function show_recordings() { conf_mount_rw(); safe_mkdir("/etc/phpshellsessions"); - if($recording) + if ($recording) { conf_mount_ro(); + } echo "==> Sessions available for playback are:\n"; system("cd /etc/phpshellsessions && ls /etc/phpshellsessions"); - echo "==> end of list.\n"; + echo "==> end of list.\n"; } function returnlastchar($command) { $commandlen = strlen($command); $endofstring = substr($command, ($commandlen-1)); - return $endofstring; + return $endofstring; } function returnfirstchar($command) { $commandlen = strlen($command); $endofstring = substr($command, 0, 1); - return $endofstring; + return $endofstring; } function str_replace_all($search,$replace,$subject) { - while(strpos($subject,$search)!==false) + while (strpos($subject,$search)!==false) { $subject = str_replace($search,$replace,$subject); + } return $subject; } @@ -312,11 +316,11 @@ function playback_text($playback_file_contents) { $playback_text .= "require_once('globals.inc');\n"; $playback_text .= "require_once('config.inc');\n"; $toquote = '"'; - $toquotereplace = '\\"'; - foreach($playback_file_split as $pfs) { + $toquotereplace = '\\"'; + foreach ($playback_file_split as $pfs) { $firstchar = returnfirstchar($pfs); $currentline = $pfs; - if($firstchar == "!") { + if ($firstchar == "!") { /* XXX: encode " in $pfs */ $pfsa = str_replace($toquote, $toquotereplace, $currentline); $playback_text .= str_replace("!", "system(\"", $pfsa) . "\");\n"; diff --git a/usr/local/sbin/prefixes.php b/usr/local/sbin/prefixes.php index 85cb49641d..118bd9e80c 100644 --- a/usr/local/sbin/prefixes.php +++ b/usr/local/sbin/prefixes.php @@ -1,7 +1,7 @@ 0) { +if (count($routes) > 0) { foreach ($routes as $address => $prefix) { echo "/sbin/route change -inet6 {$prefix} {$address}\n"; } @@ -69,13 +69,14 @@ if(count($routes) > 0) { /* get clog from dhcpd */ $dhcpdlogfile = "/var/log/dhcpd.log"; $expires = array(); -if(file_exists($dhcpdlogfile)) { +if (file_exists($dhcpdlogfile)) { $fd = popen("clog $dhcpdlogfile", 'r'); while (($line = fgets($fd)) !== false) { //echo $line; - if(preg_match("/releases[ ]+prefix[ ]+([0-9a-f:]+\/[0-9]+)/i", $line, $expire)) { - if(in_array($expire[1], $routes)) + if (preg_match("/releases[ ]+prefix[ ]+([0-9a-f:]+\/[0-9]+)/i", $line, $expire)) { + if (in_array($expire[1], $routes)) { continue; + } $expires[$expire[1]] = $expire[1]; } } @@ -83,7 +84,7 @@ if(file_exists($dhcpdlogfile)) { } // echo "remove routes\n"; -if(count($expires) > 0) { +if (count($expires) > 0) { foreach ($expires as $prefix) { echo "/sbin/route delete -inet6 {$prefix['prefix']}\n"; } diff --git a/usr/local/sbin/show_filter_reload_status.php b/usr/local/sbin/show_filter_reload_status.php index 5251c3e744..daa35adfb7 100755 --- a/usr/local/sbin/show_filter_reload_status.php +++ b/usr/local/sbin/show_filter_reload_status.php @@ -3,24 +3,24 @@ $last_text = ""; -while(!stristr($status, "Done")) { - $status = get_status(); - if($status <> "") { - echo $status . "\n"; - } - sleep(1); +while (!stristr($status, "Done")) { + $status = get_status(); + if ($status <> "") { + echo $status . "\n"; + } + sleep(1); } function get_status() { - global $last_text; - $status = file_get_contents("/var/run/filter_reload_status"); - $status = str_replace("...", "", $status); - $status .= "..."; - if($status <> $last_text) { - $last_text = $status; - return $status; - } - return ""; + global $last_text; + $status = file_get_contents("/var/run/filter_reload_status"); + $status = str_replace("...", "", $status); + $status .= "..."; + if ($status <> $last_text) { + $last_text = $status; + return $status; + } + return ""; } ?> From 44b9fbdc819dd5088ceef92b558ba748432027d5 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Sat, 14 Mar 2015 20:24:25 +0545 Subject: [PATCH 252/257] Use subnet address in OPT net rules Example: LAN IP 10.0.1.1/24 OPT1 IP 10.0.2.1/24 Rules with SRC or DST LANnet correctly have 10.0.0.0/24 (the subnet base address) in /tmp/rules.debug Rules with SRC or DST OPT1net have 10.0.2.1/24 (the OPT1 IP address with OPT1 net mask) in /tmp/rules.debug It still works (I think) because actually 10.0.2.1/24 and 10.0.2.0/24 interpreted as a subnet still describes the same set of IP addresses, but it looks odd, as reported by: https://forum.pfsense.org/index.php?topic=90096.msg498474#msg498474 Same issue with IPv6 for OPT1net rules. This fixes the rule generation to that OPT1net uses the base subnet address in the rule, in the same way that LANnet and WANnet does. --- etc/inc/filter.inc | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/etc/inc/filter.inc b/etc/inc/filter.inc index 9e20344301..cf82b8468a 100644 --- a/etc/inc/filter.inc +++ b/etc/inc/filter.inc @@ -2430,11 +2430,11 @@ function filter_generate_address(& $rule, $target = "source", $isnat = false) { $matches = ""; if ($rule['ipprotocol'] == "inet6") { if (preg_match("/opt([0-9]*)$/", $rule[$target]['network'], $optmatch)) { - $opt_ip = $FilterIflist["opt{$optmatch[1]}"]['ipv6']; - if (!is_ipaddrv6($opt_ip)) { + $opt_sa = $FilterIflist["opt{$optmatch[1]}"]['sav6']; + if (!is_ipaddrv6($opt_sa)) { return ""; } - $src = $opt_ip . "/" . $FilterIflist["opt{$optmatch[1]}"]['snv6']; + $src = $opt_sa . "/" . $FilterIflist["opt{$optmatch[1]}"]['snv6']; /* check for opt$NUMip here */ } else if (preg_match("/opt([0-9]*)ip/", $rule[$target]['network'], $matches)) { $src = $FilterIflist["opt{$matches[1]}"]['ipv6']; @@ -2447,11 +2447,11 @@ function filter_generate_address(& $rule, $target = "source", $isnat = false) { } } else { if (preg_match("/opt([0-9]*)$/", $rule[$target]['network'], $optmatch)) { - $opt_ip = $FilterIflist["opt{$optmatch[1]}"]['ip']; - if (!is_ipaddrv4($opt_ip)) { + $opt_sa = $FilterIflist["opt{$optmatch[1]}"]['sa']; + if (!is_ipaddrv4($opt_sa)) { return ""; } - $src = $opt_ip . "/" . $FilterIflist["opt{$optmatch[1]}"]['sn']; + $src = $opt_sa . "/" . $FilterIflist["opt{$optmatch[1]}"]['sn']; /* check for opt$NUMip here */ } else if (preg_match("/opt([0-9]*)ip/", $rule[$target]['network'], $matches)) { $src = $FilterIflist["opt{$matches[1]}"]['ip']; From e5d58b682703befda3dfb994272df3544d931dd1 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Mon, 16 Mar 2015 20:11:00 +0545 Subject: [PATCH 253/257] Do not allow VLAN tag zero At the moment you can make a VLAN with tag 0. The input validation does not catch it because when $_POST['tag'] = "0" that evaluates to false by PHP. Always make the checks on 'tag' value whenever the 'tag' key is set at all. If the (required) 'tag' key is not set, then that is already checked for by do_input_validation(). --- usr/local/www/interfaces_vlan_edit.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr/local/www/interfaces_vlan_edit.php b/usr/local/www/interfaces_vlan_edit.php index 4f40cce9ff..4395d1259d 100644 --- a/usr/local/www/interfaces_vlan_edit.php +++ b/usr/local/www/interfaces_vlan_edit.php @@ -80,7 +80,7 @@ if ($_POST) { do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); - if ($_POST['tag'] && (!is_numericint($_POST['tag']) || ($_POST['tag'] < '1') || ($_POST['tag'] > '4094'))) { + if (isset($_POST['tag']) && (!is_numericint($_POST['tag']) || ($_POST['tag'] < '1') || ($_POST['tag'] > '4094'))) { $input_errors[] = gettext("The VLAN tag must be an integer between 1 and 4094."); } From 926e0a2fca6ae143665d18482cc62dac23c814b6 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Wed, 18 Mar 2015 17:48:36 +0545 Subject: [PATCH 254/257] Cleanup code path when adding a new user 1) Only attempt to delete the oldusername if it actually was non-empty - at the moment errors are logged in the system log when adding a new user, because the code was trying to delete the user name "". 2) Call local_user_set() first to create (change, whatever) the user record. This makes the user record exist for a new user. Then call local_user_set_groups() to sort out what groups the user should be in or not in. The existing code would fail to add a new user to the specified group/s because local_user_set_groups() was called too early, before the user actually existed. Typical system log errors from the old code: Mar 18 17:10:31 php-fpm[9542]: /system_usermanager.php: Tried to remove user but got user pw instead. Bailing. Mar 18 17:10:31 php-fpm[9542]: /system_usermanager.php: The command '/usr/sbin/pw groupmod admins -g 1999 -M '0,2003,2006,2008' 2>&1' returned exit code '67', the output was 'pw: user `2008' does not exist' From looking at the code history, I think this has been this way for a long time, not a new bug at all. Discussed in forum: https://forum.pfsense.org/index.php?topic=90700.msg501766#msg501766 --- usr/local/www/system_usermanager.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr/local/www/system_usermanager.php b/usr/local/www/system_usermanager.php index 9fce49742a..1bc91ad9bb 100644 --- a/usr/local/www/system_usermanager.php +++ b/usr/local/www/system_usermanager.php @@ -299,7 +299,7 @@ if ($_POST['save']) { isset($_POST['utype']) ? $userent['scope'] = $_POST['utype'] : $userent['scope'] = "system"; /* the user name was modified */ - if ($_POST['usernamefld'] <> $_POST['oldusername']) { + if (!empty($_POST['oldusername']) && ($_POST['usernamefld'] <> $_POST['oldusername'])) { $_SERVER['REMOTE_USER'] = $_POST['usernamefld']; local_user_del($userent); } @@ -361,8 +361,8 @@ if ($_POST['save']) { $a_user[] = $userent; } - local_user_set_groups($userent,$_POST['groups']); local_user_set($userent); + local_user_set_groups($userent,$_POST['groups']); write_config(); if(is_dir("/etc/inc/privhooks")) From 106f34513364b377e25c40edb4118fd0ee8089c2 Mon Sep 17 00:00:00 2001 From: Jose Luis Duran Date: Sat, 14 Feb 2015 08:29:36 -0200 Subject: [PATCH 255/257] Use `none` instead of a whitespace in sshd_config Use the `none` keyword instead of a whitespace to disable the FreeBSD version in sshd_config. --- etc/sshd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/sshd b/etc/sshd index 7fb0f7a10e..3a51b36e55 100755 --- a/etc/sshd +++ b/etc/sshd @@ -125,7 +125,7 @@ /* Run the server on another port if we have one defined */ $sshconf .= "Port $sshport\n"; /* Hide FreeBSD version */ - $sshconf .= "VersionAddendum \n"; + $sshconf .= "VersionAddendum none\n"; /* Apply package SSHDCond settings if config file exists */ if (file_exists("/etc/sshd_extra")) { From eb94d976ddb560daf7e08cac066c44c1adaf39ba Mon Sep 17 00:00:00 2001 From: Jared Dillard Date: Wed, 18 Mar 2015 14:04:16 -0500 Subject: [PATCH 256/257] change the location of jquery-ui images in each theme's css file --- .../_corporate/styles/jquery-ui-1.11.1.css | 32 +++++++++---------- .../code-red/styles/jquery-ui-1.11.1.css | 32 +++++++++---------- .../metallic/styles/jquery-ui-1.11.1.css | 32 +++++++++---------- .../nervecenter/styles/jquery-ui-1.11.1.css | 32 +++++++++---------- .../styles/jquery-ui-1.11.1.css | 32 +++++++++---------- .../pfsense/styles/jquery-ui-1.11.1.css | 32 +++++++++---------- .../pfsense_ng/styles/jquery-ui-1.11.1.css | 32 +++++++++---------- .../pfsense_ng_fs/styles/jquery-ui-1.11.1.css | 32 +++++++++---------- .../the_wall/styles/jquery-ui-1.11.1.css | 32 +++++++++---------- 9 files changed, 144 insertions(+), 144 deletions(-) diff --git a/usr/local/www/themes/_corporate/styles/jquery-ui-1.11.1.css b/usr/local/www/themes/_corporate/styles/jquery-ui-1.11.1.css index d1d14766cc..8a8c54f796 100644 --- a/usr/local/www/themes/_corporate/styles/jquery-ui-1.11.1.css +++ b/usr/local/www/themes/_corporate/styles/jquery-ui-1.11.1.css @@ -846,7 +846,7 @@ body .ui-tooltip { } .ui-widget-content { border: 1px solid #aaaaaa; - background: #c9c9c9 url("images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; + background: #c9c9c9 url("../../../javascript/jquery/images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; color: #333333; } .ui-widget-content a { @@ -854,7 +854,7 @@ body .ui-tooltip { } .ui-widget-header { border: 1px solid #bbbbbb; - /* background: #dddddd url("images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ + /* background: #dddddd url("../../../javascript/jquery/images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ color: #444444; font-weight: bold; } @@ -868,7 +868,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; - background: #eeeeee url("images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #3383bb; } @@ -885,7 +885,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #bbbbbb; - background: #f8f8f8 url("images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; + background: #f8f8f8 url("../../../javascript/jquery/images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #599fcf; } @@ -904,7 +904,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #999999; - background: #999999 url("images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; + background: #999999 url("../../../javascript/jquery/images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; font-weight: bold; color: #ffffff; } @@ -921,7 +921,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #ffffff; - background: #eeeeee url("images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; color: #444444; } .ui-state-highlight a, @@ -933,7 +933,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #c0402a; - background: #c0402a url("images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; + background: #c0402a url("../../../javascript/jquery/images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; color: #ffffff; } .ui-state-error a, @@ -979,27 +979,27 @@ body .ui-tooltip { } .ui-icon, .ui-widget-content .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-widget-header .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-state-default .ui-icon { - background-image: url("images/ui-icons_70b2e1_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_70b2e1_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-active .ui-icon { - background-image: url("images/ui-icons_454545_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_454545_256x240.png"); } .ui-state-highlight .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { - background-image: url("images/ui-icons_fbc856_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_fbc856_256x240.png"); } /* positioning */ @@ -1212,14 +1212,14 @@ body .ui-tooltip { /* Overlays */ .ui-widget-overlay { - background: #eeeeee url("images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; opacity: .8; filter: Alpha(Opacity=80); /* support: IE8 */ } .ui-widget-shadow { margin: -4px 0 0 -4px; padding: 4px; - background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; + background: #aaaaaa url("../../../javascript/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; opacity: .6; filter: Alpha(Opacity=60); /* support: IE8 */ border-radius: 0pxdow; diff --git a/usr/local/www/themes/code-red/styles/jquery-ui-1.11.1.css b/usr/local/www/themes/code-red/styles/jquery-ui-1.11.1.css index d1d14766cc..8a8c54f796 100644 --- a/usr/local/www/themes/code-red/styles/jquery-ui-1.11.1.css +++ b/usr/local/www/themes/code-red/styles/jquery-ui-1.11.1.css @@ -846,7 +846,7 @@ body .ui-tooltip { } .ui-widget-content { border: 1px solid #aaaaaa; - background: #c9c9c9 url("images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; + background: #c9c9c9 url("../../../javascript/jquery/images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; color: #333333; } .ui-widget-content a { @@ -854,7 +854,7 @@ body .ui-tooltip { } .ui-widget-header { border: 1px solid #bbbbbb; - /* background: #dddddd url("images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ + /* background: #dddddd url("../../../javascript/jquery/images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ color: #444444; font-weight: bold; } @@ -868,7 +868,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; - background: #eeeeee url("images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #3383bb; } @@ -885,7 +885,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #bbbbbb; - background: #f8f8f8 url("images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; + background: #f8f8f8 url("../../../javascript/jquery/images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #599fcf; } @@ -904,7 +904,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #999999; - background: #999999 url("images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; + background: #999999 url("../../../javascript/jquery/images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; font-weight: bold; color: #ffffff; } @@ -921,7 +921,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #ffffff; - background: #eeeeee url("images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; color: #444444; } .ui-state-highlight a, @@ -933,7 +933,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #c0402a; - background: #c0402a url("images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; + background: #c0402a url("../../../javascript/jquery/images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; color: #ffffff; } .ui-state-error a, @@ -979,27 +979,27 @@ body .ui-tooltip { } .ui-icon, .ui-widget-content .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-widget-header .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-state-default .ui-icon { - background-image: url("images/ui-icons_70b2e1_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_70b2e1_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-active .ui-icon { - background-image: url("images/ui-icons_454545_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_454545_256x240.png"); } .ui-state-highlight .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { - background-image: url("images/ui-icons_fbc856_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_fbc856_256x240.png"); } /* positioning */ @@ -1212,14 +1212,14 @@ body .ui-tooltip { /* Overlays */ .ui-widget-overlay { - background: #eeeeee url("images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; opacity: .8; filter: Alpha(Opacity=80); /* support: IE8 */ } .ui-widget-shadow { margin: -4px 0 0 -4px; padding: 4px; - background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; + background: #aaaaaa url("../../../javascript/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; opacity: .6; filter: Alpha(Opacity=60); /* support: IE8 */ border-radius: 0pxdow; diff --git a/usr/local/www/themes/metallic/styles/jquery-ui-1.11.1.css b/usr/local/www/themes/metallic/styles/jquery-ui-1.11.1.css index d1d14766cc..8a8c54f796 100644 --- a/usr/local/www/themes/metallic/styles/jquery-ui-1.11.1.css +++ b/usr/local/www/themes/metallic/styles/jquery-ui-1.11.1.css @@ -846,7 +846,7 @@ body .ui-tooltip { } .ui-widget-content { border: 1px solid #aaaaaa; - background: #c9c9c9 url("images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; + background: #c9c9c9 url("../../../javascript/jquery/images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; color: #333333; } .ui-widget-content a { @@ -854,7 +854,7 @@ body .ui-tooltip { } .ui-widget-header { border: 1px solid #bbbbbb; - /* background: #dddddd url("images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ + /* background: #dddddd url("../../../javascript/jquery/images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ color: #444444; font-weight: bold; } @@ -868,7 +868,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; - background: #eeeeee url("images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #3383bb; } @@ -885,7 +885,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #bbbbbb; - background: #f8f8f8 url("images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; + background: #f8f8f8 url("../../../javascript/jquery/images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #599fcf; } @@ -904,7 +904,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #999999; - background: #999999 url("images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; + background: #999999 url("../../../javascript/jquery/images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; font-weight: bold; color: #ffffff; } @@ -921,7 +921,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #ffffff; - background: #eeeeee url("images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; color: #444444; } .ui-state-highlight a, @@ -933,7 +933,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #c0402a; - background: #c0402a url("images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; + background: #c0402a url("../../../javascript/jquery/images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; color: #ffffff; } .ui-state-error a, @@ -979,27 +979,27 @@ body .ui-tooltip { } .ui-icon, .ui-widget-content .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-widget-header .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-state-default .ui-icon { - background-image: url("images/ui-icons_70b2e1_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_70b2e1_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-active .ui-icon { - background-image: url("images/ui-icons_454545_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_454545_256x240.png"); } .ui-state-highlight .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { - background-image: url("images/ui-icons_fbc856_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_fbc856_256x240.png"); } /* positioning */ @@ -1212,14 +1212,14 @@ body .ui-tooltip { /* Overlays */ .ui-widget-overlay { - background: #eeeeee url("images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; opacity: .8; filter: Alpha(Opacity=80); /* support: IE8 */ } .ui-widget-shadow { margin: -4px 0 0 -4px; padding: 4px; - background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; + background: #aaaaaa url("../../../javascript/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; opacity: .6; filter: Alpha(Opacity=60); /* support: IE8 */ border-radius: 0pxdow; diff --git a/usr/local/www/themes/nervecenter/styles/jquery-ui-1.11.1.css b/usr/local/www/themes/nervecenter/styles/jquery-ui-1.11.1.css index d1d14766cc..8a8c54f796 100644 --- a/usr/local/www/themes/nervecenter/styles/jquery-ui-1.11.1.css +++ b/usr/local/www/themes/nervecenter/styles/jquery-ui-1.11.1.css @@ -846,7 +846,7 @@ body .ui-tooltip { } .ui-widget-content { border: 1px solid #aaaaaa; - background: #c9c9c9 url("images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; + background: #c9c9c9 url("../../../javascript/jquery/images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; color: #333333; } .ui-widget-content a { @@ -854,7 +854,7 @@ body .ui-tooltip { } .ui-widget-header { border: 1px solid #bbbbbb; - /* background: #dddddd url("images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ + /* background: #dddddd url("../../../javascript/jquery/images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ color: #444444; font-weight: bold; } @@ -868,7 +868,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; - background: #eeeeee url("images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #3383bb; } @@ -885,7 +885,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #bbbbbb; - background: #f8f8f8 url("images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; + background: #f8f8f8 url("../../../javascript/jquery/images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #599fcf; } @@ -904,7 +904,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #999999; - background: #999999 url("images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; + background: #999999 url("../../../javascript/jquery/images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; font-weight: bold; color: #ffffff; } @@ -921,7 +921,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #ffffff; - background: #eeeeee url("images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; color: #444444; } .ui-state-highlight a, @@ -933,7 +933,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #c0402a; - background: #c0402a url("images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; + background: #c0402a url("../../../javascript/jquery/images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; color: #ffffff; } .ui-state-error a, @@ -979,27 +979,27 @@ body .ui-tooltip { } .ui-icon, .ui-widget-content .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-widget-header .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-state-default .ui-icon { - background-image: url("images/ui-icons_70b2e1_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_70b2e1_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-active .ui-icon { - background-image: url("images/ui-icons_454545_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_454545_256x240.png"); } .ui-state-highlight .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { - background-image: url("images/ui-icons_fbc856_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_fbc856_256x240.png"); } /* positioning */ @@ -1212,14 +1212,14 @@ body .ui-tooltip { /* Overlays */ .ui-widget-overlay { - background: #eeeeee url("images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; opacity: .8; filter: Alpha(Opacity=80); /* support: IE8 */ } .ui-widget-shadow { margin: -4px 0 0 -4px; padding: 4px; - background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; + background: #aaaaaa url("../../../javascript/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; opacity: .6; filter: Alpha(Opacity=60); /* support: IE8 */ border-radius: 0pxdow; diff --git a/usr/local/www/themes/pfsense-dropdown/styles/jquery-ui-1.11.1.css b/usr/local/www/themes/pfsense-dropdown/styles/jquery-ui-1.11.1.css index d1d14766cc..8a8c54f796 100644 --- a/usr/local/www/themes/pfsense-dropdown/styles/jquery-ui-1.11.1.css +++ b/usr/local/www/themes/pfsense-dropdown/styles/jquery-ui-1.11.1.css @@ -846,7 +846,7 @@ body .ui-tooltip { } .ui-widget-content { border: 1px solid #aaaaaa; - background: #c9c9c9 url("images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; + background: #c9c9c9 url("../../../javascript/jquery/images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; color: #333333; } .ui-widget-content a { @@ -854,7 +854,7 @@ body .ui-tooltip { } .ui-widget-header { border: 1px solid #bbbbbb; - /* background: #dddddd url("images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ + /* background: #dddddd url("../../../javascript/jquery/images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ color: #444444; font-weight: bold; } @@ -868,7 +868,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; - background: #eeeeee url("images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #3383bb; } @@ -885,7 +885,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #bbbbbb; - background: #f8f8f8 url("images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; + background: #f8f8f8 url("../../../javascript/jquery/images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #599fcf; } @@ -904,7 +904,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #999999; - background: #999999 url("images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; + background: #999999 url("../../../javascript/jquery/images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; font-weight: bold; color: #ffffff; } @@ -921,7 +921,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #ffffff; - background: #eeeeee url("images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; color: #444444; } .ui-state-highlight a, @@ -933,7 +933,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #c0402a; - background: #c0402a url("images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; + background: #c0402a url("../../../javascript/jquery/images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; color: #ffffff; } .ui-state-error a, @@ -979,27 +979,27 @@ body .ui-tooltip { } .ui-icon, .ui-widget-content .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-widget-header .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-state-default .ui-icon { - background-image: url("images/ui-icons_70b2e1_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_70b2e1_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-active .ui-icon { - background-image: url("images/ui-icons_454545_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_454545_256x240.png"); } .ui-state-highlight .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { - background-image: url("images/ui-icons_fbc856_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_fbc856_256x240.png"); } /* positioning */ @@ -1212,14 +1212,14 @@ body .ui-tooltip { /* Overlays */ .ui-widget-overlay { - background: #eeeeee url("images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; opacity: .8; filter: Alpha(Opacity=80); /* support: IE8 */ } .ui-widget-shadow { margin: -4px 0 0 -4px; padding: 4px; - background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; + background: #aaaaaa url("../../../javascript/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; opacity: .6; filter: Alpha(Opacity=60); /* support: IE8 */ border-radius: 0pxdow; diff --git a/usr/local/www/themes/pfsense/styles/jquery-ui-1.11.1.css b/usr/local/www/themes/pfsense/styles/jquery-ui-1.11.1.css index d1d14766cc..8a8c54f796 100644 --- a/usr/local/www/themes/pfsense/styles/jquery-ui-1.11.1.css +++ b/usr/local/www/themes/pfsense/styles/jquery-ui-1.11.1.css @@ -846,7 +846,7 @@ body .ui-tooltip { } .ui-widget-content { border: 1px solid #aaaaaa; - background: #c9c9c9 url("images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; + background: #c9c9c9 url("../../../javascript/jquery/images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; color: #333333; } .ui-widget-content a { @@ -854,7 +854,7 @@ body .ui-tooltip { } .ui-widget-header { border: 1px solid #bbbbbb; - /* background: #dddddd url("images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ + /* background: #dddddd url("../../../javascript/jquery/images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ color: #444444; font-weight: bold; } @@ -868,7 +868,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; - background: #eeeeee url("images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #3383bb; } @@ -885,7 +885,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #bbbbbb; - background: #f8f8f8 url("images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; + background: #f8f8f8 url("../../../javascript/jquery/images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #599fcf; } @@ -904,7 +904,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #999999; - background: #999999 url("images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; + background: #999999 url("../../../javascript/jquery/images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; font-weight: bold; color: #ffffff; } @@ -921,7 +921,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #ffffff; - background: #eeeeee url("images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; color: #444444; } .ui-state-highlight a, @@ -933,7 +933,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #c0402a; - background: #c0402a url("images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; + background: #c0402a url("../../../javascript/jquery/images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; color: #ffffff; } .ui-state-error a, @@ -979,27 +979,27 @@ body .ui-tooltip { } .ui-icon, .ui-widget-content .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-widget-header .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-state-default .ui-icon { - background-image: url("images/ui-icons_70b2e1_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_70b2e1_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-active .ui-icon { - background-image: url("images/ui-icons_454545_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_454545_256x240.png"); } .ui-state-highlight .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { - background-image: url("images/ui-icons_fbc856_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_fbc856_256x240.png"); } /* positioning */ @@ -1212,14 +1212,14 @@ body .ui-tooltip { /* Overlays */ .ui-widget-overlay { - background: #eeeeee url("images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; opacity: .8; filter: Alpha(Opacity=80); /* support: IE8 */ } .ui-widget-shadow { margin: -4px 0 0 -4px; padding: 4px; - background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; + background: #aaaaaa url("../../../javascript/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; opacity: .6; filter: Alpha(Opacity=60); /* support: IE8 */ border-radius: 0pxdow; diff --git a/usr/local/www/themes/pfsense_ng/styles/jquery-ui-1.11.1.css b/usr/local/www/themes/pfsense_ng/styles/jquery-ui-1.11.1.css index d1d14766cc..8a8c54f796 100644 --- a/usr/local/www/themes/pfsense_ng/styles/jquery-ui-1.11.1.css +++ b/usr/local/www/themes/pfsense_ng/styles/jquery-ui-1.11.1.css @@ -846,7 +846,7 @@ body .ui-tooltip { } .ui-widget-content { border: 1px solid #aaaaaa; - background: #c9c9c9 url("images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; + background: #c9c9c9 url("../../../javascript/jquery/images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; color: #333333; } .ui-widget-content a { @@ -854,7 +854,7 @@ body .ui-tooltip { } .ui-widget-header { border: 1px solid #bbbbbb; - /* background: #dddddd url("images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ + /* background: #dddddd url("../../../javascript/jquery/images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ color: #444444; font-weight: bold; } @@ -868,7 +868,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; - background: #eeeeee url("images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #3383bb; } @@ -885,7 +885,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #bbbbbb; - background: #f8f8f8 url("images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; + background: #f8f8f8 url("../../../javascript/jquery/images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #599fcf; } @@ -904,7 +904,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #999999; - background: #999999 url("images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; + background: #999999 url("../../../javascript/jquery/images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; font-weight: bold; color: #ffffff; } @@ -921,7 +921,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #ffffff; - background: #eeeeee url("images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; color: #444444; } .ui-state-highlight a, @@ -933,7 +933,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #c0402a; - background: #c0402a url("images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; + background: #c0402a url("../../../javascript/jquery/images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; color: #ffffff; } .ui-state-error a, @@ -979,27 +979,27 @@ body .ui-tooltip { } .ui-icon, .ui-widget-content .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-widget-header .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-state-default .ui-icon { - background-image: url("images/ui-icons_70b2e1_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_70b2e1_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-active .ui-icon { - background-image: url("images/ui-icons_454545_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_454545_256x240.png"); } .ui-state-highlight .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { - background-image: url("images/ui-icons_fbc856_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_fbc856_256x240.png"); } /* positioning */ @@ -1212,14 +1212,14 @@ body .ui-tooltip { /* Overlays */ .ui-widget-overlay { - background: #eeeeee url("images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; opacity: .8; filter: Alpha(Opacity=80); /* support: IE8 */ } .ui-widget-shadow { margin: -4px 0 0 -4px; padding: 4px; - background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; + background: #aaaaaa url("../../../javascript/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; opacity: .6; filter: Alpha(Opacity=60); /* support: IE8 */ border-radius: 0pxdow; diff --git a/usr/local/www/themes/pfsense_ng_fs/styles/jquery-ui-1.11.1.css b/usr/local/www/themes/pfsense_ng_fs/styles/jquery-ui-1.11.1.css index d1d14766cc..8a8c54f796 100644 --- a/usr/local/www/themes/pfsense_ng_fs/styles/jquery-ui-1.11.1.css +++ b/usr/local/www/themes/pfsense_ng_fs/styles/jquery-ui-1.11.1.css @@ -846,7 +846,7 @@ body .ui-tooltip { } .ui-widget-content { border: 1px solid #aaaaaa; - background: #c9c9c9 url("images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; + background: #c9c9c9 url("../../../javascript/jquery/images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; color: #333333; } .ui-widget-content a { @@ -854,7 +854,7 @@ body .ui-tooltip { } .ui-widget-header { border: 1px solid #bbbbbb; - /* background: #dddddd url("images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ + /* background: #dddddd url("../../../javascript/jquery/images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ color: #444444; font-weight: bold; } @@ -868,7 +868,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; - background: #eeeeee url("images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #3383bb; } @@ -885,7 +885,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #bbbbbb; - background: #f8f8f8 url("images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; + background: #f8f8f8 url("../../../javascript/jquery/images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #599fcf; } @@ -904,7 +904,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #999999; - background: #999999 url("images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; + background: #999999 url("../../../javascript/jquery/images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; font-weight: bold; color: #ffffff; } @@ -921,7 +921,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #ffffff; - background: #eeeeee url("images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; color: #444444; } .ui-state-highlight a, @@ -933,7 +933,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #c0402a; - background: #c0402a url("images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; + background: #c0402a url("../../../javascript/jquery/images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; color: #ffffff; } .ui-state-error a, @@ -979,27 +979,27 @@ body .ui-tooltip { } .ui-icon, .ui-widget-content .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-widget-header .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-state-default .ui-icon { - background-image: url("images/ui-icons_70b2e1_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_70b2e1_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-active .ui-icon { - background-image: url("images/ui-icons_454545_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_454545_256x240.png"); } .ui-state-highlight .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { - background-image: url("images/ui-icons_fbc856_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_fbc856_256x240.png"); } /* positioning */ @@ -1212,14 +1212,14 @@ body .ui-tooltip { /* Overlays */ .ui-widget-overlay { - background: #eeeeee url("images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; opacity: .8; filter: Alpha(Opacity=80); /* support: IE8 */ } .ui-widget-shadow { margin: -4px 0 0 -4px; padding: 4px; - background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; + background: #aaaaaa url("../../../javascript/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; opacity: .6; filter: Alpha(Opacity=60); /* support: IE8 */ border-radius: 0pxdow; diff --git a/usr/local/www/themes/the_wall/styles/jquery-ui-1.11.1.css b/usr/local/www/themes/the_wall/styles/jquery-ui-1.11.1.css index d1d14766cc..8a8c54f796 100644 --- a/usr/local/www/themes/the_wall/styles/jquery-ui-1.11.1.css +++ b/usr/local/www/themes/the_wall/styles/jquery-ui-1.11.1.css @@ -846,7 +846,7 @@ body .ui-tooltip { } .ui-widget-content { border: 1px solid #aaaaaa; - background: #c9c9c9 url("images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; + background: #c9c9c9 url("../../../javascript/jquery/images/ui-bg_inset-soft_50_c9c9c9_1x100.png") 50% bottom repeat-x; color: #333333; } .ui-widget-content a { @@ -854,7 +854,7 @@ body .ui-tooltip { } .ui-widget-header { border: 1px solid #bbbbbb; - /* background: #dddddd url("images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ + /* background: #dddddd url("../../../javascript/jquery/images/ui-bg_glass_35_dddddd_1x400.png") 50% 50% repeat-x; */ color: #444444; font-weight: bold; } @@ -868,7 +868,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; - background: #eeeeee url("images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_glass_60_eeeeee_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #3383bb; } @@ -885,7 +885,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #bbbbbb; - background: #f8f8f8 url("images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; + background: #f8f8f8 url("../../../javascript/jquery/images/ui-bg_glass_100_f8f8f8_1x400.png") 50% 50% repeat-x; font-weight: bold; color: #599fcf; } @@ -904,7 +904,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #999999; - background: #999999 url("images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; + background: #999999 url("../../../javascript/jquery/images/ui-bg_inset-hard_75_999999_1x100.png") 50% 50% repeat-x; font-weight: bold; color: #ffffff; } @@ -921,7 +921,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #ffffff; - background: #eeeeee url("images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_55_eeeeee_40x100.png") 50% 50% repeat-x; color: #444444; } .ui-state-highlight a, @@ -933,7 +933,7 @@ body .ui-tooltip { .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #c0402a; - background: #c0402a url("images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; + background: #c0402a url("../../../javascript/jquery/images/ui-bg_flat_55_c0402a_40x100.png") 50% 50% repeat-x; color: #ffffff; } .ui-state-error a, @@ -979,27 +979,27 @@ body .ui-tooltip { } .ui-icon, .ui-widget-content .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-widget-header .ui-icon { - background-image: url("images/ui-icons_999999_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_999999_256x240.png"); } .ui-state-default .ui-icon { - background-image: url("images/ui-icons_70b2e1_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_70b2e1_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-active .ui-icon { - background-image: url("images/ui-icons_454545_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_454545_256x240.png"); } .ui-state-highlight .ui-icon { - background-image: url("images/ui-icons_3383bb_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_3383bb_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { - background-image: url("images/ui-icons_fbc856_256x240.png"); + background-image: url("../../../javascript/jquery/images/ui-icons_fbc856_256x240.png"); } /* positioning */ @@ -1212,14 +1212,14 @@ body .ui-tooltip { /* Overlays */ .ui-widget-overlay { - background: #eeeeee url("images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; + background: #eeeeee url("../../../javascript/jquery/images/ui-bg_flat_0_eeeeee_40x100.png") 50% 50% repeat-x; opacity: .8; filter: Alpha(Opacity=80); /* support: IE8 */ } .ui-widget-shadow { margin: -4px 0 0 -4px; padding: 4px; - background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; + background: #aaaaaa url("../../../javascript/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x; opacity: .6; filter: Alpha(Opacity=60); /* support: IE8 */ border-radius: 0pxdow; From d325e90818db2b22fc2562c38493769f217230f2 Mon Sep 17 00:00:00 2001 From: Chris Buechler Date: Wed, 18 Mar 2015 23:52:46 -0500 Subject: [PATCH 257/257] Add option for wireless standard "auto", to omit "mode" entirely from ifconfig. This shouldn't be necessary, but specifying mode has proven to trigger driver problems that don't exist if it's left unspecified (such as FreeBSD PR 198680). Chosing "auto" fixes ath(4) BSS mode issues otherwise preventing it from connecting. --- etc/inc/interfaces.inc | 14 ++++++++++---- usr/local/www/interfaces.php | 5 +++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/etc/inc/interfaces.inc b/etc/inc/interfaces.inc index 9d02b911d1..4d27a0e6af 100644 --- a/etc/inc/interfaces.inc +++ b/etc/inc/interfaces.inc @@ -2533,7 +2533,10 @@ function interface_wireless_configure($if, &$wl, &$wlcfg) { $wlcmd[] = "up"; /* Set a/b/g standard */ $standard = str_replace(" Turbo", "", $wlcfg['standard']); - $wlcmd[] = "mode " . escapeshellarg($standard); + /* skip mode entirely for "auto" */ + if ($wlcfg['standard'] != "auto") { + $wlcmd[] = "mode " . escapeshellarg($standard); + } /* XXX: Disable ampdu for now on mwl when running in 11n mode * to prevent massive packet loss under certain conditions. */ @@ -2920,10 +2923,13 @@ EOD; } } - /* The mode must be specified in a separate command before ifconfig + /* 20150318 cmb - Note: the below no longer appears to be true on FreeBSD 10.x, so don't set + * mode twice (for now at least). This can be removed entirely in the future if no problems are found + + * The mode must be specified in a separate command before ifconfig * will allow the mode and channel at the same time in the next. */ - mwexec("/sbin/ifconfig " . escapeshellarg($if) . " mode " . escapeshellarg($standard)); - fwrite($wlan_setup_log, "/sbin/ifconfig " . escapeshellarg($if) . " mode " . escapeshellarg($standard) . "\n"); + //mwexec("/sbin/ifconfig " . escapeshellarg($if) . " mode " . escapeshellarg($standard)); + //fwrite($wlan_setup_log, "/sbin/ifconfig " . escapeshellarg($if) . " mode " . escapeshellarg($standard) . "\n"); /* configure wireless */ $wlcmd_args = implode(" ", $wlcmd); diff --git a/usr/local/www/interfaces.php b/usr/local/www/interfaces.php index 2248aaad36..8ca3247a4a 100644 --- a/usr/local/www/interfaces.php +++ b/usr/local/www/interfaces.php @@ -2950,6 +2950,11 @@ $types6 = array("none" => gettext("None"), "staticv6" => gettext("Static IPv6"),