From fc4e8df89e80d438088755b043aa344de20782e7 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Mon, 9 Mar 2015 17:20:36 +0545 Subject: [PATCH] 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;