Merge remote-tracking branch 'upstream/master' into origin/master

This commit is contained in:
Sjon Hortensius 2015-03-22 14:55:52 +01:00
commit 46bb8a0bd8
245 changed files with 15048 additions and 20317 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0"?>
<pfsense>
<version>11.6</version>
<version>11.8</version>
<lastchange/>
<theme>pfsense_ng</theme>
<system>
@ -272,5 +272,8 @@
<active_interface/>
<outgoing_interface/>
<custom_options/>
<hideidentity/>
<hideversion/>
<dnssecstripped/>
</unbound>
</pfsense>

View File

@ -12,7 +12,7 @@
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to the New BSD license, that is
* available through the world-wide-web at
* available through the world-wide-web at
* http://www.opensource.org/licenses/bsd-license.php
* If you did not receive a copy of the new BSDlicense and are unable
* to obtain it through the world-wide-web, please send a note to
@ -66,7 +66,7 @@ define("NET_IPV6_RESERVED_NSAP", 12);
define("NET_IPV6_RESERVED_IPX", 13);
/**
* Address Type: Reserved for Geographic-Based Unicast Addresses
* Address Type: Reserved for Geographic-Based Unicast Addresses
* (RFC 1884, Section 2.3)
* @see getAddressType()
*/
@ -148,11 +148,11 @@ class Net_IPv6
* @return Array the first element is the IP, the second the prefix length
* @since 1.2.0
* @access public
* @static
* @static
*/
static function separate($ip)
static function separate($ip)
{
$addr = $ip;
$spec = '';
@ -203,7 +203,7 @@ class Net_IPv6
* Tests for a prefix length specification in the address
* and removes the prefix length, if exists
*
* The method is technically identical to removeNetmaskSpec() and
* The method is technically identical to removeNetmaskSpec() and
* will be dropped in a future release.
*
* @param String $ip a valid ipv6 address
@ -240,7 +240,7 @@ class Net_IPv6
* @access public
* @static
*/
static function getNetmaskSpec($ip)
static function getNetmaskSpec($ip)
{
$elements = Net_IPv6::separate($ip);
@ -256,7 +256,7 @@ class Net_IPv6
* Tests for a prefix length specification in the address
* and returns the prefix length, if exists
*
* The method is technically identical to getNetmaskSpec() and
* The method is technically identical to getNetmaskSpec() and
* will be dropped in a future release.
*
* @param String $ip a valid ipv6 address
@ -266,9 +266,9 @@ class Net_IPv6
* @static
* @deprecated
*/
static function getPrefixLength($ip)
static function getPrefixLength($ip)
{
if (preg_match("/^([0-9a-fA-F:]{2,39})\/(\d{1,3})*$/",
if (preg_match("/^([0-9a-fA-F:]{2,39})\/(\d{1,3})*$/",
$ip, $matches)) {
return $matches[2];
@ -424,12 +424,12 @@ class Net_IPv6
* @see NET_IPV6_MULTICAST
* @see NET_IPV6_LOCAL_LINK
* @see NET_IPV6_LOCAL_SITE
* @see NET_IPV6_IPV4MAPPING
* @see NET_IPV6_UNSPECIFIED
* @see NET_IPV6_LOOPBACK
* @see NET_IPV6_IPV4MAPPING
* @see NET_IPV6_UNSPECIFIED
* @see NET_IPV6_LOOPBACK
* @see NET_IPV6_UNKNOWN_TYPE
*/
static function getAddressType($ip)
static function getAddressType($ip)
{
$ip = Net_IPv6::removeNetmaskSpec($ip);
$binip = Net_IPv6::_ip2Bin($ip);
@ -444,7 +444,7 @@ class Net_IPv6
} else if (0 == strncmp(str_repeat('0', 80).str_repeat('1', 16), $binip, 96)) { // ::ffff/96
return NET_IPV6_IPV4MAPPING;
return NET_IPV6_IPV4MAPPING;
} else if (0 == strncmp('1111111010', $binip, 10)) {
@ -462,7 +462,7 @@ class Net_IPv6
return NET_IPV6_MULTICAST;
} else if (0 == strncmp('00000000', $binip, 8)) {
} else if (0 == strncmp('00000000', $binip, 8)) {
return NET_IPV6_RESERVED;
@ -526,10 +526,10 @@ class Net_IPv6
* Example of calling with invalid input: 1::2:3:4:5:6:7:8:9 -> 1:0:2:3:4:5:6:7:8:9
*
* @param String $ip a (possibly) valid IPv6-address (hex format)
* @param Boolean $leadingZeros if true, leading zeros are added to each
* block of the address
* (FF01::101 ->
* FF01:0000:0000:0000:0000:0000:0000:0101)
* @param Boolean $leadingZeros if true, leading zeros are added to each
* block of the address
* (FF01::101 ->
* FF01:0000:0000:0000:0000:0000:0000:0101)
*
* @return String the uncompressed IPv6-address (hex format)
* @access public
@ -630,14 +630,14 @@ class Net_IPv6
}
if(true == $leadingZeros) {
$uipT = array();
$uiparts = explode(':', $uip);
foreach($uiparts as $p) {
$uipT[] = sprintf('%04s', $p);
}
$uip = implode(':', $uipT);
@ -665,14 +665,14 @@ class Net_IPv6
* Example: FF01:0:0:0:0:0:0:101 -> FF01::101
* 0:0:0:0:0:0:0:1 -> ::1
*
* When $ip is an already compressed address and $force is false, the method returns
* When $ip is an already compressed address and $force is false, the method returns
* the value as is, even if the address can be compressed further.
*
* Example: FF01::0:1 -> FF01::0:1
*
* To enforce maximum compression, you can set the second argument $force to true.
*
* Example: FF01::0:1 -> FF01::1
* Example: FF01::0:1 -> FF01::1
*
* @param String $ip a valid IPv6-address (hex format)
* @param boolean $force if true the address will be compressed as best as possible (since 1.2.0)
@ -683,14 +683,14 @@ class Net_IPv6
* @static
* @author elfrink at introweb dot nl
*/
static function compress($ip, $force = false)
static function compress($ip, $force = false)
{
if(false !== strpos($ip, '::')) { // its already compressed
if(true == $force) {
$ip = Net_IPv6::uncompress($ip);
$ip = Net_IPv6::uncompress($ip);
} else {
@ -748,6 +748,12 @@ class Net_IPv6
$cip = preg_replace('/((^:)|(:$))/', '', $cip);
$cip = preg_replace('/((^:)|(:$))/', '::', $cip);
if (empty($cip)) {
$cip = "::";
}
if ('' != $netmask) {
$cip = $cip.'/'.$netmask;
@ -792,20 +798,20 @@ class Net_IPv6
* Checks, if an IPv6 address can be compressed
*
* @param String $ip a valid IPv6 address
*
*
* @return Boolean true, if address can be compressed
*
*
* @access public
* @since 1.2.0b
* @static
* @author Manuel Schmitt
*/
static function isCompressible($ip)
static function isCompressible($ip)
{
return (bool)($ip != Net_IPv6::compress($address));
}
}
// }}}
// {{{ SplitV64()
@ -820,7 +826,7 @@ class Net_IPv6
* 0:0:0:0:0:FFFF:129.144.52.38
*
* @param String $ip a valid IPv6-address (hex format)
* @param Boolean $uncompress if true, the address will be uncompressed
* @param Boolean $uncompress if true, the address will be uncompressed
* before processing
*
* @return Array [0] contains the IPv6 part,
@ -871,14 +877,14 @@ class Net_IPv6
{
$elements = Net_IPv6::separate($ip);
$ip = $elements[0];
if('' != $elements[1] && ( !is_numeric($elements[1]) || 0 > $elements[1] || 128 < $elements[1])) {
return false;
}
}
$ipPart = Net_IPv6::SplitV64($ip);
$count = 0;
@ -895,14 +901,14 @@ class Net_IPv6
for ($i = 0; $i < count($ipv6); $i++) {
if(4 < strlen($ipv6[$i])) {
return false;
}
$dec = hexdec($ipv6[$i]);
$hex = strtoupper(preg_replace("/^[0]{1,3}(.*[0-9a-fA-F])$/",
"\\1",
"\\1",
$ipv6[$i]));
if ($ipv6[$i] >= 0 && $dec <= 65535
@ -961,8 +967,8 @@ class Net_IPv6
/**
* Returns the lowest and highest IPv6 address
* for a given IP and netmask specification
*
* The netmask may be a part of the $ip or
*
* The netmask may be a part of the $ip or
* the number of netmask bits is provided via $bits
*
* The result is an indexed array. The key 'start'
@ -984,7 +990,7 @@ class Net_IPv6
$ip = null;
$bitmask = null;
if ( null == $bits ) {
if ( null == $bits ) {
$elements = explode('/', $ipToParse);
@ -1027,14 +1033,14 @@ class Net_IPv6
/**
* Converts an IPv6 address from Hex into Binary representation.
*
* @param String $ip the IP to convert (a:b:c:d:e:f:g:h),
* @param String $ip the IP to convert (a:b:c:d:e:f:g:h),
* compressed IPs are allowed
*
* @return String the binary representation
* @access private
@ @since 1.1.0
*/
static function _ip2Bin($ip)
static function _ip2Bin($ip)
{
$binstr = '';

View File

@ -178,7 +178,7 @@ class PEAR
* but is included for forward compatibility, so subclass
* destructors should always call it.
*
* See the note in the class desciption about output from
* See the note in the class description about output from
* destructors.
*
* @access public
@ -403,7 +403,7 @@ class PEAR
}
/**
* This method deletes all occurences of the specified element from
* This method deletes all occurrences of the specified element from
* the expected error codes stack.
*
* @param mixed $error_code error code that should be deleted
@ -698,7 +698,7 @@ class PEAR
}
/**
* OS independant PHP extension load. Remember to take care
* OS independent PHP extension load. Remember to take care
* on the correct extension name for case sensitive OSes.
*
* @param string $ext The extension name
@ -819,7 +819,7 @@ function _PEAR_call_destructors()
/**
* Standard PEAR error class for PHP 4
*
* This class is supserseded by {@link PEAR_Exception} in PHP 5
* This class is superseded by {@link PEAR_Exception} in PHP 5
*
* @category pear
* @package PEAR

File diff suppressed because it is too large Load Diff

View File

@ -39,8 +39,9 @@
include_once("auth.inc");
include_once("priv.inc");
if (!function_exists('platform_booting'))
if (!function_exists('platform_booting')) {
require_once('globals.inc');
}
/* Authenticate user - exit if failed */
if (!session_auth()) {
@ -66,8 +67,9 @@ if (!isAllowedPage($_SERVER['REQUEST_URI'])) {
pfSenseHeader("/{$page}");
$username = empty($_SESSION["Username"]) ? "(system)" : $_SESSION['Username'];
if (!empty($_SERVER['REMOTE_ADDR']))
if (!empty($_SERVER['REMOTE_ADDR'])) {
$username .= '@' . $_SERVER['REMOTE_ADDR'];
}
log_error("{$username} attempted to access {$_SERVER['SCRIPT_NAME']} but does not have access to that page. Redirecting to {$page}.");
exit;
@ -75,12 +77,13 @@ if (!isAllowedPage($_SERVER['REQUEST_URI'])) {
display_error_form("201", gettext("No page assigned to this user! Click here to logout."));
exit;
}
} else
} else {
$_SESSION['Post_Login'] = true;
}
/*
* redirect browsers post-login to avoid pages
* taking action in reponse to a POST request
* taking action in response to a POST request
*/
if (!$_SESSION['Post_Login']) {
$_SESSION['Post_Login'] = true;
@ -101,12 +104,13 @@ session_commit();
function display_error_form($http_code, $desc) {
global $config, $g;
$g['theme'] = get_current_theme();
if(isAjax()) {
if (isAjax()) {
printf(gettext('Error: %1$s Description: %2$s'), $http_code, $desc);
return;
}
?>
<<<<<<< HEAD
<!DOCTYPE html>
<html lang="en">
<head>
@ -136,9 +140,9 @@ function display_login_form() {
unset($input_errors);
if(isAjax()) {
if (isAjax()) {
if (isset($_POST['login'])) {
if($_SESSION['Logged_In'] <> "True") {
if ($_SESSION['Logged_In'] <> "True") {
isset($_SESSION['Login_Error']) ? $login_error = $_SESSION['Login_Error'] : $login_error = gettext("unknown reason");
printf("showajaxmessage('" . gettext("Invalid login (%s).") . "')", $login_error);
}
@ -167,11 +171,11 @@ if (empty($FilterIflist)) {
filter_generate_optcfg_array();
}
foreach ($FilterIflist as $iflist) {
if ($iflist['ip'] == $http_host)
if ($iflist['ip'] == $http_host) {
$local_ip = true;
else if ($iflist['ipv6'] == $http_host)
} else if ($iflist['ipv6'] == $http_host) {
$local_ip = true;
else if (is_array($iflist['vips'])) {
} else if (is_array($iflist['vips'])) {
foreach ($iflist['vips'] as $vip) {
if ($vip['ip'] == $http_host) {
$local_ip = true;
@ -180,8 +184,9 @@ foreach ($FilterIflist as $iflist) {
}
unset($vip);
}
if ($local_ip == true)
if ($local_ip == true) {
break;
}
}
unset($FilterIflist);
unset($iflist);
@ -194,8 +199,9 @@ if ($local_ip == false) {
} else if (is_ipaddrv6($http_host) && !empty($ovpns['tunnel_networkv6']) && ip_in_subnet($http_host, $ovpns['tunnel_networkv6'])) {
$local_ip = true;
}
if ($local_ip == true)
if ($local_ip == true) {
break;
}
}
}
}

View File

@ -21,7 +21,7 @@ class basic_sasl_client_class
Function Start(&$client, &$message, &$interactions)
{
if($this->state!=SASL_BASIC_STATE_START)
if ($this->state!=SASL_BASIC_STATE_START)
{
$client->error="Basic authentication state is not at the start";
return(SASL_FAIL);
@ -33,19 +33,21 @@ class basic_sasl_client_class
$defaults=array(
);
$status=$client->GetCredentials($this->credentials,$defaults,$interactions);
if($status==SASL_CONTINUE)
if ($status==SASL_CONTINUE)
{
$message=$this->credentials["user"].":".$this->credentials["password"];
$this->state=SASL_BASIC_STATE_DONE;
}
else
{
Unset($message);
}
return($status);
}
Function Step(&$client, $response, &$message, &$interactions)
{
switch($this->state)
switch ($this->state)
{
case SASL_BASIC_STATE_DONE:
$client->error="Basic authentication was finished without success";

File diff suppressed because it is too large Load Diff

View File

@ -52,10 +52,13 @@ $openssl_crl_status = array(
function & lookup_ca($refid) {
global $config;
if (is_array($config['ca']))
foreach ($config['ca'] as & $ca)
if ($ca['refid'] == $refid)
if (is_array($config['ca'])) {
foreach ($config['ca'] as & $ca) {
if ($ca['refid'] == $refid) {
return $ca;
}
}
}
return false;
}
@ -63,13 +66,14 @@ function & lookup_ca($refid) {
function & lookup_ca_by_subject($subject) {
global $config;
if (is_array($config['ca']))
foreach ($config['ca'] as & $ca)
{
if (is_array($config['ca'])) {
foreach ($config['ca'] as & $ca) {
$ca_subject = cert_get_subject($ca['crt']);
if ($ca_subject == $subject)
if ($ca_subject == $subject) {
return $ca;
}
}
}
return false;
}
@ -77,46 +81,57 @@ function & lookup_ca_by_subject($subject) {
function & lookup_cert($refid) {
global $config;
if (is_array($config['cert']))
foreach ($config['cert'] as & $cert)
if ($cert['refid'] == $refid)
if (is_array($config['cert'])) {
foreach ($config['cert'] as & $cert) {
if ($cert['refid'] == $refid) {
return $cert;
}
}
}
return false;
}
function & lookup_cert_by_name($name) {
global $config;
if (is_array($config['cert']))
foreach ($config['cert'] as & $cert)
if ($cert['descr'] == $name)
if (is_array($config['cert'])) {
foreach ($config['cert'] as & $cert) {
if ($cert['descr'] == $name) {
return $cert;
}
}
}
}
function & lookup_crl($refid) {
global $config;
if (is_array($config['crl']))
foreach ($config['crl'] as & $crl)
if ($crl['refid'] == $refid)
if (is_array($config['crl'])) {
foreach ($config['crl'] as & $crl) {
if ($crl['refid'] == $refid) {
return $crl;
}
}
}
return false;
}
function ca_chain_array(& $cert) {
if($cert['caref']) {
if ($cert['caref']) {
$chain = array();
$crt = lookup_ca($cert['caref']);
$chain[] = $crt;
while ($crt) {
$caref = $crt['caref'];
if($caref)
if ($caref) {
$crt = lookup_ca($caref);
else
} else {
$crt = false;
if($crt)
}
if ($crt) {
$chain[] = $crt;
}
}
return $chain;
}
@ -124,15 +139,15 @@ function ca_chain_array(& $cert) {
}
function ca_chain(& $cert) {
if($cert['caref']) {
if ($cert['caref']) {
$ca = "";
$cas = ca_chain_array($cert);
if (is_array($cas))
foreach ($cas as & $ca_cert)
{
if (is_array($cas)) {
foreach ($cas as & $ca_cert) {
$ca .= base64_decode($ca_cert['crt']);
$ca .= "\n";
}
}
return $ca;
}
return "";
@ -142,35 +157,40 @@ function ca_import(& $ca, $str, $key="", $serial=0) {
global $config;
$ca['crt'] = base64_encode($str);
if (!empty($key))
if (!empty($key)) {
$ca['prv'] = base64_encode($key);
if (!empty($serial))
}
if (!empty($serial)) {
$ca['serial'] = $serial;
}
$subject = cert_get_subject($str, false);
$issuer = cert_get_issuer($str, false);
// Find my issuer unless self-signed
if($issuer <> $subject) {
if ($issuer <> $subject) {
$issuer_crt =& lookup_ca_by_subject($issuer);
if($issuer_crt)
if ($issuer_crt) {
$ca['caref'] = $issuer_crt['refid'];
}
}
/* Correct if child certificate was loaded first */
if (is_array($config['ca']))
foreach ($config['ca'] as & $oca)
{
if (is_array($config['ca'])) {
foreach ($config['ca'] as & $oca) {
$issuer = cert_get_issuer($oca['crt']);
if($ca['refid']<>$oca['refid'] && $issuer==$subject)
if ($ca['refid']<>$oca['refid'] && $issuer==$subject) {
$oca['caref'] = $ca['refid'];
}
}
if (is_array($config['cert']))
foreach ($config['cert'] as & $cert)
{
}
if (is_array($config['cert'])) {
foreach ($config['cert'] as & $cert) {
$issuer = cert_get_issuer($cert['crt']);
if($issuer==$subject)
if ($issuer==$subject) {
$cert['caref'] = $ca['refid'];
}
}
}
return true;
}
@ -185,20 +205,27 @@ function ca_create(& $ca, $keylen, $lifetime, $dn, $digest_alg = "sha256") {
// generate a new key pair
$res_key = openssl_pkey_new($args);
if (!$res_key) return false;
if (!$res_key) {
return false;
}
// generate a certificate signing request
$res_csr = openssl_csr_new($dn, $res_key, $args);
if (!$res_csr) return false;
if (!$res_csr) {
return false;
}
// self sign the certificate
$res_crt = openssl_csr_sign($res_csr, null, $res_key, $lifetime, $args);
if (!$res_crt) return false;
if (!$res_crt) {
return false;
}
// export our certificate data
if (!openssl_pkey_export($res_key, $str_key) ||
!openssl_x509_export($res_crt, $str_crt))
!openssl_x509_export($res_crt, $str_crt)) {
return false;
}
// return our ca information
$ca['crt'] = base64_encode($str_crt);
@ -211,12 +238,15 @@ function ca_create(& $ca, $keylen, $lifetime, $dn, $digest_alg = "sha256") {
function ca_inter_create(& $ca, $keylen, $lifetime, $dn, $caref, $digest_alg = "sha256") {
// Create Intermediate Certificate Authority
$signing_ca =& lookup_ca($caref);
if (!$signing_ca)
if (!$signing_ca) {
return false;
}
$signing_ca_res_crt = openssl_x509_read(base64_decode($signing_ca['crt']));
$signing_ca_res_key = openssl_pkey_get_private(array(0 => base64_decode($signing_ca['prv']) , 1 => ""));
if (!$signing_ca_res_crt || !$signing_ca_res_key) return false;
if (!$signing_ca_res_crt || !$signing_ca_res_key) {
return false;
}
$signing_ca_serial = ++$signing_ca['serial'];
$args = array(
@ -228,20 +258,27 @@ function ca_inter_create(& $ca, $keylen, $lifetime, $dn, $caref, $digest_alg = "
// generate a new key pair
$res_key = openssl_pkey_new($args);
if (!$res_key) return false;
if (!$res_key) {
return false;
}
// generate a certificate signing request
$res_csr = openssl_csr_new($dn, $res_key, $args);
if (!$res_csr) return false;
if (!$res_csr) {
return false;
}
// Sign the certificate
$res_crt = openssl_csr_sign($res_csr, $signing_ca_res_crt, $signing_ca_res_key, $lifetime, $args, $signing_ca_serial);
if (!$res_crt) return false;
if (!$res_crt) {
return false;
}
// export our certificate data
if (!openssl_pkey_export($res_key, $str_key) ||
!openssl_x509_export($res_crt, $str_crt))
!openssl_x509_export($res_crt, $str_crt)) {
return false;
}
// return our ca information
$ca['crt'] = base64_encode($str_crt);
@ -258,12 +295,13 @@ function cert_import(& $cert, $crt_str, $key_str) {
$subject = cert_get_subject($crt_str, false);
$issuer = cert_get_issuer($crt_str, false);
// Find my issuer unless self-signed
if($issuer <> $subject) {
if ($issuer <> $subject) {
$issuer_crt =& lookup_ca_by_subject($issuer);
if($issuer_crt)
if ($issuer_crt) {
$cert['caref'] = $issuer_crt['refid'];
}
}
return true;
}
@ -275,14 +313,17 @@ function cert_create(& $cert, $caref, $keylen, $lifetime, $dn, $type="user", $di
if ($type != "self-signed") {
$cert['caref'] = $caref;
$ca =& lookup_ca($caref);
if (!$ca)
if (!$ca) {
return false;
}
$ca_str_crt = base64_decode($ca['crt']);
$ca_str_key = base64_decode($ca['prv']);
$ca_res_crt = openssl_x509_read($ca_str_crt);
$ca_res_key = openssl_pkey_get_private(array(0 => $ca_str_key, 1 => ""));
if(!$ca_res_key) return false;
if (!$ca_res_key) {
return false;
}
$ca_serial = ++$ca['serial'];
}
@ -316,7 +357,9 @@ function cert_create(& $cert, $caref, $keylen, $lifetime, $dn, $type="user", $di
// generate a new key pair
$res_key = openssl_pkey_new($args);
if(!$res_key) return false;
if (!$res_key) {
return false;
}
// If this is a self-signed cert, blank out the CA and sign with the cert's key
if ($type == "self-signed") {
@ -329,17 +372,22 @@ function cert_create(& $cert, $caref, $keylen, $lifetime, $dn, $type="user", $di
// generate a certificate signing request
$res_csr = openssl_csr_new($dn, $res_key, $args);
if(!$res_csr) return false;
if (!$res_csr) {
return false;
}
// sign the certificate using an internal CA
$res_crt = openssl_csr_sign($res_csr, $ca_res_crt, $ca_res_key, $lifetime,
$args, $ca_serial);
if(!$res_crt) return false;
if (!$res_crt) {
return false;
}
// export our certificate data
if (!openssl_pkey_export($res_key, $str_key) ||
!openssl_x509_export($res_crt, $str_crt))
!openssl_x509_export($res_crt, $str_crt)) {
return false;
}
// return our certificate information
$cert['crt'] = base64_encode($str_crt);
@ -359,16 +407,21 @@ function csr_generate(& $cert, $keylen, $dn, $digest_alg = "sha256") {
// generate a new key pair
$res_key = openssl_pkey_new($args);
if(!$res_key) return false;
if (!$res_key) {
return false;
}
// generate a certificate signing request
$res_csr = openssl_csr_new($dn, $res_key, $args);
if(!$res_csr) return false;
if (!$res_csr) {
return false;
}
// export our request data
if (!openssl_pkey_export($res_key, $str_key) ||
!openssl_csr_export($res_csr, $str_csr))
!openssl_csr_export($res_csr, $str_csr)) {
return false;
}
// return our request information
$cert['csr'] = base64_encode($str_csr);
@ -388,20 +441,23 @@ function csr_complete(& $cert, $str_crt) {
function csr_get_subject($str_crt, $decode = true) {
if ($decode)
if ($decode) {
$str_crt = base64_decode($str_crt);
}
$components = openssl_csr_get_subject($str_crt);
if (empty($components) || !is_array($components))
if (empty($components) || !is_array($components)) {
return "unknown";
}
ksort($components);
foreach ($components as $a => $v) {
if (!strlen($subject))
if (!strlen($subject)) {
$subject = "{$a}={$v}";
else
} else {
$subject = "{$a}={$v}, {$subject}";
}
}
return $subject;
@ -409,14 +465,16 @@ function csr_get_subject($str_crt, $decode = true) {
function cert_get_subject($str_crt, $decode = true) {
if ($decode)
if ($decode) {
$str_crt = base64_decode($str_crt);
}
$inf_crt = openssl_x509_parse($str_crt);
$components = $inf_crt['subject'];
if (empty($components) || !is_array($components))
if (empty($components) || !is_array($components)) {
return "unknown";
}
ksort($components);
foreach ($components as $a => $v) {
@ -440,13 +498,15 @@ function cert_get_subject_array($crt) {
$inf_crt = openssl_x509_parse($str_crt);
$components = $inf_crt['subject'];
if (!is_array($components))
if (!is_array($components)) {
return;
}
$subject_array = array();
foreach($components as $a => $v)
foreach ($components as $a => $v) {
$subject_array[] = array('a' => $a, 'v' => $v);
}
return $subject_array;
}
@ -459,14 +519,16 @@ function cert_get_subject_hash($crt) {
function cert_get_issuer($str_crt, $decode = true) {
if ($decode)
if ($decode) {
$str_crt = base64_decode($str_crt);
}
$inf_crt = openssl_x509_parse($str_crt);
$components = $inf_crt['issuer'];
if (empty($components) || !is_array($components))
if (empty($components) || !is_array($components)) {
return "unknown";
}
ksort($components);
foreach ($components as $a => $v) {
@ -486,24 +548,26 @@ function cert_get_issuer($str_crt, $decode = true) {
}
/* this function works on x509 (crt), rsa key (prv), and req(csr) */
function cert_get_modulus($str_crt, $decode = true, $type = "crt"){
if ($decode)
function cert_get_modulus($str_crt, $decode = true, $type = "crt") {
if ($decode) {
$str_crt = base64_decode($str_crt);
}
$modulus = "";
if ( in_array($type, array("crt", "prv", "csr")) ) {
$type = str_replace( array("crt","prv","csr"), array("x509","rsa","req"), $type);
$modulus = exec("echo \"{$str_crt}\" | openssl {$type} -noout -modulus");
$type = str_replace( array("crt","prv","csr"), array("x509","rsa","req"), $type);
$modulus = exec("echo \"{$str_crt}\" | openssl {$type} -noout -modulus");
}
return $modulus;
}
function csr_get_modulus($str_crt, $decode = true){
function csr_get_modulus($str_crt, $decode = true) {
return cert_get_modulus($str_crt, $decode, "csr");
}
function cert_get_purpose($str_crt, $decode = true) {
if ($decode)
if ($decode) {
$str_crt = base64_decode($str_crt);
}
$crt_details = openssl_x509_parse($str_crt);
$purpose = array();
$purpose['ca'] = (stristr($crt_details['extensions']['basicConstraints'], 'CA:TRUE') === false) ? 'No': 'Yes';
@ -512,40 +576,48 @@ function cert_get_purpose($str_crt, $decode = true) {
}
function cert_get_dates($str_crt, $decode = true) {
if ($decode)
if ($decode) {
$str_crt = base64_decode($str_crt);
}
$crt_details = openssl_x509_parse($str_crt);
if ($crt_details['validFrom_time_t'] > 0)
if ($crt_details['validFrom_time_t'] > 0) {
$start = date('r', $crt_details['validFrom_time_t']);
if ($crt_details['validTo_time_t'] > 0)
}
if ($crt_details['validTo_time_t'] > 0) {
$end = date('r', $crt_details['validTo_time_t']);
}
return array($start, $end);
}
function cert_get_serial($str_crt, $decode = true) {
if ($decode)
if ($decode) {
$str_crt = base64_decode($str_crt);
}
$crt_details = openssl_x509_parse($str_crt);
if (isset($crt_details['serialNumber']) && !empty($crt_details['serialNumber']))
if (isset($crt_details['serialNumber']) && !empty($crt_details['serialNumber'])) {
return $crt_details['serialNumber'];
else
} else {
return NULL;
}
}
function prv_get_modulus($str_crt, $decode = true){
function prv_get_modulus($str_crt, $decode = true) {
return cert_get_modulus($str_crt, $decode, "prv");
}
function is_user_cert($certref) {
global $config;
if (!is_array($config['system']['user']))
if (!is_array($config['system']['user'])) {
return;
}
foreach ($config['system']['user'] as $user) {
if (!is_array($user['cert']))
if (!is_array($user['cert'])) {
continue;
}
foreach ($user['cert'] as $cert) {
if ($certref == $cert)
if ($certref == $cert) {
return true;
}
}
}
return false;
@ -553,51 +625,60 @@ function is_user_cert($certref) {
function is_openvpn_server_cert($certref) {
global $config;
if (!is_array($config['openvpn']['openvpn-server']))
if (!is_array($config['openvpn']['openvpn-server'])) {
return;
}
foreach ($config['openvpn']['openvpn-server'] as $ovpns) {
if ($ovpns['certref'] == $certref)
if ($ovpns['certref'] == $certref) {
return true;
}
}
return false;
}
function is_openvpn_client_cert($certref) {
global $config;
if (!is_array($config['openvpn']['openvpn-client']))
if (!is_array($config['openvpn']['openvpn-client'])) {
return;
}
foreach ($config['openvpn']['openvpn-client'] as $ovpnc) {
if ($ovpnc['certref'] == $certref)
if ($ovpnc['certref'] == $certref) {
return true;
}
}
return false;
}
function is_ipsec_cert($certref) {
global $config;
if (!is_array($config['ipsec']['phase1']))
if (!is_array($config['ipsec']['phase1'])) {
return;
}
foreach ($config['ipsec']['phase1'] as $ipsec) {
if ($ipsec['certref'] == $certref)
if ($ipsec['certref'] == $certref) {
return true;
}
}
return false;
}
function is_webgui_cert($certref) {
global $config;
if (($config['system']['webgui']['ssl-certref'] == $certref)
&& ($config['system']['webgui']['protocol'] != "http"))
if (($config['system']['webgui']['ssl-certref'] == $certref) &&
($config['system']['webgui']['protocol'] != "http")) {
return true;
}
}
function is_captiveportal_cert($certref) {
global $config;
if (!is_array($config['captiveportal']))
if (!is_array($config['captiveportal'])) {
return;
}
foreach ($config['captiveportal'] as $portal) {
if (isset($portal['enable']) && isset($portal['httpslogin']) && ($portal['certref'] == $certref))
if (isset($portal['enable']) && isset($portal['httpslogin']) && ($portal['certref'] == $certref)) {
return true;
}
}
return false;
}
@ -614,8 +695,9 @@ function cert_in_use($certref) {
function crl_create(& $crl, $caref, $name, $serial=0, $lifetime=9999) {
global $config;
$ca =& lookup_ca($caref);
if (!$ca)
if (!$ca) {
return false;
}
$crl['descr'] = $name;
$crl['caref'] = $caref;
$crl['serial'] = $serial;
@ -629,11 +711,13 @@ function crl_create(& $crl, $caref, $name, $serial=0, $lifetime=9999) {
function crl_update(& $crl) {
global $config;
$ca =& lookup_ca($crl['caref']);
if (!$ca)
if (!$ca) {
return false;
}
// If we have text but no certs, it was imported and cannot be updated.
if (($crl["method"] != "internal") && (!empty($crl['text']) && empty($crl['cert'])))
if (($crl["method"] != "internal") && (!empty($crl['text']) && empty($crl['cert']))) {
return false;
}
$crl['serial']++;
$ca_str_crt = base64_decode($ca['crt']);
$ca_str_key = base64_decode($ca['prv']);
@ -650,11 +734,13 @@ function crl_update(& $crl) {
function cert_revoke($cert, & $crl, $reason=OCSP_REVOKED_STATUS_UNSPECIFIED) {
global $config;
if (is_cert_revoked($cert, $crl['refid']))
if (is_cert_revoked($cert, $crl['refid'])) {
return true;
}
// If we have text but no certs, it was imported and cannot be updated.
if (!is_crl_internal($crl))
if (!is_crl_internal($crl)) {
return false;
}
$cert["reason"] = $reason;
$cert["revoke_time"] = time();
$crl["cert"][] = $cert;
@ -664,18 +750,21 @@ function cert_revoke($cert, & $crl, $reason=OCSP_REVOKED_STATUS_UNSPECIFIED) {
function cert_unrevoke($cert, & $crl) {
global $config;
if (!is_crl_internal($crl))
if (!is_crl_internal($crl)) {
return false;
}
foreach ($crl['cert'] as $id => $rcert) {
if (($rcert['refid'] == $cert['refid']) || ($rcert['descr'] == $cert['descr'])) {
unset($crl['cert'][$id]);
if (count($crl['cert']) == 0) {
// Protect against accidentally switching the type to imported, for older CRLs
if (!isset($crl['method']))
if (!isset($crl['method'])) {
$crl['method'] = "internal";
}
crl_update($crl);
} else
} else {
crl_update($crl);
}
return true;
}
}
@ -690,34 +779,40 @@ function cert_compare($cert1, $cert2) {
being identical. */
$c1 = base64_decode($cert1['crt']);
$c2 = base64_decode($cert2['crt']);
if ((cert_get_issuer($c1, false) == cert_get_issuer($c2, false))
&& (cert_get_subject($c1, false) == cert_get_subject($c2, false))
&& (cert_get_serial($c1, false) == cert_get_serial($c2, false))
&& (cert_get_modulus($c1, false) == cert_get_modulus($c2, false)))
if ((cert_get_issuer($c1, false) == cert_get_issuer($c2, false)) &&
(cert_get_subject($c1, false) == cert_get_subject($c2, false)) &&
(cert_get_serial($c1, false) == cert_get_serial($c2, false)) &&
(cert_get_modulus($c1, false) == cert_get_modulus($c2, false))) {
return true;
}
return false;
}
function is_cert_revoked($cert, $crlref = "") {
global $config;
if (!is_array($config['crl']))
if (!is_array($config['crl'])) {
return false;
}
if (!empty($crlref)) {
$crl = lookup_crl($crlref);
if (!is_array($crl['cert']))
if (!is_array($crl['cert'])) {
return false;
}
foreach ($crl['cert'] as $rcert) {
if (cert_compare($rcert, $cert))
if (cert_compare($rcert, $cert)) {
return true;
}
}
} else {
foreach ($config['crl'] as $crl) {
if (!is_array($crl['cert']))
if (!is_array($crl['cert'])) {
continue;
}
foreach ($crl['cert'] as $rcert) {
if (cert_compare($rcert, $cert))
if (cert_compare($rcert, $cert)) {
return true;
}
}
}
}
@ -726,11 +821,13 @@ function is_cert_revoked($cert, $crlref = "") {
function is_openvpn_server_crl($crlref) {
global $config;
if (!is_array($config['openvpn']['openvpn-server']))
if (!is_array($config['openvpn']['openvpn-server'])) {
return;
}
foreach ($config['openvpn']['openvpn-server'] as $ovpns) {
if (!empty($ovpns['crlref']) && ($ovpns['crlref'] == $crlref))
if (!empty($ovpns['crlref']) && ($ovpns['crlref'] == $crlref)) {
return true;
}
}
return false;
}
@ -749,8 +846,9 @@ function cert_get_cn($crt, $isref = false) {
if ($isref) {
$cert = lookup_cert($crt);
/* If it's not a valid cert, bail. */
if (!(is_array($cert) && !empty($cert['crt'])))
if (!(is_array($cert) && !empty($cert['crt']))) {
return "";
}
$cert = $cert['crt'];
} else {
$cert = $crt;
@ -758,8 +856,9 @@ function cert_get_cn($crt, $isref = false) {
$sub = cert_get_subject_array($cert);
if (is_array($sub)) {
foreach ($sub as $s) {
if (strtoupper($s['a']) == "CN")
if (strtoupper($s['a']) == "CN") {
return $s['v'];
}
}
}
return "";

View File

@ -54,7 +54,7 @@ function set_networking_interfaces_ports() {
$physmem = $memory[0];
$realmem = $memory[1];
if($physmem < $g['minimum_ram_warning']) {
if ($physmem < $g['minimum_ram_warning']) {
echo "\n\n\n";
echo gettext("DANGER! WARNING! ACHTUNG!") . "\n\n";
printf(gettext("%s requires *AT LEAST* %s RAM to function correctly.%s"), $g['product_name'], $g['minimum_ram_warning_text'], "\n");
@ -66,12 +66,13 @@ function set_networking_interfaces_ports() {
$iflist = get_interface_list();
/* Function flow is based on $key and $auto_assign or the lack thereof */
/* Function flow is based on $key and $auto_assign or the lack thereof */
$key = null;
/* Only present auto interface option if running from LiveCD and interface mismatch*/
if ((preg_match("/cdrom/", $g['platform'])) && is_interface_mismatch())
/* Only present auto interface option if running from LiveCD and interface mismatch*/
if ((preg_match("/cdrom/", $g['platform'])) && is_interface_mismatch()) {
$auto_assign = false;
}
echo <<<EOD
@ -80,7 +81,7 @@ Valid interfaces are:
EOD;
if(!is_array($iflist)) {
if (!is_array($iflist)) {
echo gettext("No interfaces found!") . "\n";
$iflist = array();
} else {
@ -92,13 +93,13 @@ EOD;
if ($auto_assign) {
echo <<<EOD
!!! LiveCD Detected: Auto Interface Option !!!!
BEGIN MANUAL CONFIGURATION OR WE WILL PROCEED WITH AUTO CONFIGURATION.
EOD;
}
}
echo <<<EOD
Do you want to set up VLANs first?
@ -111,9 +112,9 @@ EOD;
if ($auto_assign) {
$key = timeout();
} else
} else {
$key = chop(fgets($fp));
}
if (!isset($key) and $auto_assign) { // Auto Assign Interfaces
do {
@ -132,22 +133,22 @@ now is the time to do so.
We'll keep trying until you do.
Searching for active interfaces...
EOD;
unset($wanif, $lanif);
$media_iflist = $plugged_in = array();
$media_iflist = get_interface_list("media");
foreach ($media_iflist as $iface => $ifa) {
if ($ifa['up'])
if ($ifa['up']) {
$plugged_in[] = $iface;
}
}
$lanif = array_shift($plugged_in);
$wanif = array_shift($plugged_in);
if(isset($lanif) && !isset($wanif)) {
if (isset($lanif) && !isset($wanif)) {
foreach ($iflist as $iface => $ifa) {
if ($iface != $lanif) {
$wanif = $iface;
@ -158,110 +159,115 @@ EOD;
echo <<<EOD
Assigned WAN to : $wanif
Assigned WAN to : $wanif
Assigned LAN to : $lanif
If you don't like this assignment,
press any key to go back to manual configuration.
press any key to go back to manual configuration.
EOD;
$key = timeout(20);
if(isset($key))
if (isset($key)) {
return;
}
} while (!isset($wanif));
$config['system']['enablesshd'] = 'enabled';
$config['system']['enablesshd'] = 'enabled';
$key = 'y';
} else { //Manually assign interfaces
if (in_array($key, array('y', 'Y')))
} else { //Manually assign interfaces
if (in_array($key, array('y', 'Y'))) {
vlan_setup();
}
if (is_array($config['vlans']['vlan']) && count($config['vlans']['vlan'])) {
echo "\n\n" . gettext("VLAN interfaces:") . "\n\n";
foreach ($config['vlans']['vlan'] as $vlan) {
echo sprintf("% -16s%s\n", "{$vlan['if']}_vlan{$vlan['tag']}",
"VLAN tag {$vlan['tag']}, parent interface {$vlan['if']}");
$iflist[$vlan['if'] . '_vlan' . $vlan['tag']] = array();
}
}
echo <<<EOD
If you do not know the names of your interfaces, you may choose to use
auto-detection. In that case, disconnect all interfaces now before
hitting 'a' to initiate auto detection.
EOD;
do {
echo "\n" . gettext("Enter the WAN interface name or 'a' for auto-detection:") . " ";
$wanif = chop(fgets($fp));
if ($wanif === "") {
return;
}
if ($wanif === "a")
if ($wanif === "a") {
$wanif = autodetect_interface("WAN", $fp);
else if (!array_key_exists($wanif, $iflist)) {
} else if (!array_key_exists($wanif, $iflist)) {
printf(gettext("%sInvalid interface name '%s'%s"), "\n", $wanif, "\n");
unset($wanif);
continue;
}
} while (!$wanif);
do {
printf(gettext("%sEnter the LAN interface name or 'a' for auto-detection %s" .
"NOTE: this enables full Firewalling/NAT mode.%s" .
"NOTE: this enables full Firewalling/NAT mode.%s" .
"(or nothing if finished):%s"), "\n", "\n", "\n", " ");
$lanif = chop(fgets($fp));
if($lanif == "exit") {
if ($lanif == "exit") {
exit;
}
if($lanif == "") {
if ($lanif == "") {
/* It is OK to have just a WAN, without a LAN so break if the user does not want LAN. */
break;
}
if ($lanif === "a")
if ($lanif === "a") {
$lanif = autodetect_interface("LAN", $fp);
else if (!array_key_exists($lanif, $iflist)) {
} else if (!array_key_exists($lanif, $iflist)) {
printf(gettext("%sInvalid interface name '%s'%s"), "\n", $lanif, "\n");
unset($lanif);
continue;
}
} while (!$lanif);
/* optional interfaces */
$i = 0;
$optif = array();
if($lanif <> "") {
if ($lanif <> "") {
while (1) {
if ($optif[$i])
if ($optif[$i]) {
$i++;
}
$io = $i + 1;
if($config['interfaces']['opt' . $io]['descr'])
if ($config['interfaces']['opt' . $io]['descr']) {
printf(gettext("%sOptional interface %s description found: %s"), "\n", $io, $config['interfaces']['opt' . $io]['descr']);
}
printf(gettext("%sEnter the Optional %s interface name or 'a' for auto-detection%s" .
"(or nothing if finished):%s"), "\n", $io, "\n", " ");
$optif[$i] = chop(fgets($fp));
if ($optif[$i]) {
if ($optif[$i] === "a") {
$ad = autodetect_interface(gettext("Optional") . " " . $io, $fp);
if ($ad)
if ($ad) {
$optif[$i] = $ad;
else
} else {
unset($optif[$i]);
}
} else if (!array_key_exists($optif[$i], $iflist)) {
printf(gettext("%sInvalid interface name '%s'%s"), "\n", $optif[$i], "\n");
unset($optif[$i]);
@ -273,44 +279,46 @@ EOD;
}
}
}
/* check for double assignments */
$ifarr = array_merge(array($lanif, $wanif), $optif);
for ($i = 0; $i < (count($ifarr)-1); $i++) {
for ($j = ($i+1); $j < count($ifarr); $j++) {
if ($ifarr[$i] == $ifarr[$j]) {
echo <<<EOD
Error: you cannot assign the same interface name twice!
EOD;
fclose($fp);
return;
}
}
}
echo "\n" . gettext("The interfaces will be assigned as follows:") . "\n\n";
echo "WAN -> " . $wanif . "\n";
if ($lanif != "")
if ($lanif != "") {
echo "LAN -> " . $lanif . "\n";
}
for ($i = 0; $i < count($optif); $i++) {
echo "OPT" . ($i+1) . " -> " . $optif[$i] . "\n";
}
echo <<<EOD
Do you want to proceed [y|n]?
EOD;
$key = chop(fgets($fp));
$key = chop(fgets($fp));
}
if (in_array($key, array('y', 'Y'))) {
if($lanif) {
if (!is_array($config['interfaces']['lan']))
if ($lanif) {
if (!is_array($config['interfaces']['lan'])) {
$config['interfaces']['lan'] = array();
}
$config['interfaces']['lan']['if'] = $lanif;
$config['interfaces']['lan']['enable'] = true;
} elseif (!platform_booting() && !$auto_assign) {
@ -323,74 +331,97 @@ Would you like to remove the LAN IP address and
unload the interface now? [y|n]?
EODD;
if (strcasecmp(chop(fgets($fp)), "y") == 0) {
if(isset($config['interfaces']['lan']) && $config['interfaces']['lan']['if'])
mwexec("/sbin/ifconfig " . $config['interfaces']['lan']['if'] . " delete");
if (strcasecmp(chop(fgets($fp)), "y") == 0) {
if (isset($config['interfaces']['lan']) && $config['interfaces']['lan']['if']) {
mwexec("/sbin/ifconfig " . $config['interfaces']['lan']['if'] . " delete");
}
if(isset($config['interfaces']['lan']))
unset($config['interfaces']['lan']);
if(isset($config['dhcpd']['lan']))
unset($config['dhcpd']['lan']);
if(isset($config['interfaces']['lan']['if']))
unset($config['interfaces']['lan']['if']);
if(isset($config['interfaces']['wan']['blockpriv']))
unset($config['interfaces']['wan']['blockpriv']);
if(isset($config['shaper']))
unset($config['shaper']);
if(isset($config['ezshaper']))
unset($config['ezshaper']);
if(isset($config['nat']))
unset($config['nat']);
} else {
if(isset($config['interfaces']['lan']['if']))
mwexec("/sbin/ifconfig " . $config['interfaces']['lan']['if'] . " delete");
if(isset($config['interfaces']['lan']))
}
if (isset($config['interfaces']['lan'])) {
unset($config['interfaces']['lan']);
if(isset($config['dhcpd']['lan']))
}
if (isset($config['dhcpd']['lan'])) {
unset($config['dhcpd']['lan']);
if(isset($config['interfaces']['lan']['if']))
}
if (isset($config['interfaces']['lan']['if'])) {
unset($config['interfaces']['lan']['if']);
if(isset($config['interfaces']['wan']['blockpriv']))
}
if (isset($config['interfaces']['wan']['blockpriv'])) {
unset($config['interfaces']['wan']['blockpriv']);
if(isset($config['shaper']))
}
if (isset($config['shaper'])) {
unset($config['shaper']);
if(isset($config['ezshaper']))
}
if (isset($config['ezshaper'])) {
unset($config['ezshaper']);
if(isset($config['nat']))
unset($config['nat']);
}
if (isset($config['nat'])) {
unset($config['nat']);
}
} else {
if (isset($config['interfaces']['lan']['if'])) {
mwexec("/sbin/ifconfig " . $config['interfaces']['lan']['if'] . " delete");
}
if (isset($config['interfaces']['lan'])) {
unset($config['interfaces']['lan']);
}
if (isset($config['dhcpd']['lan'])) {
unset($config['dhcpd']['lan']);
}
if (isset($config['interfaces']['lan']['if'])) {
unset($config['interfaces']['lan']['if']);
}
if (isset($config['interfaces']['wan']['blockpriv'])) {
unset($config['interfaces']['wan']['blockpriv']);
}
if (isset($config['shaper'])) {
unset($config['shaper']);
}
if (isset($config['ezshaper'])) {
unset($config['ezshaper']);
}
if (isset($config['nat'])) {
unset($config['nat']);
}
}
if (preg_match($g['wireless_regex'], $lanif)) {
if (is_array($config['interfaces']['lan']) &&
(!is_array($config['interfaces']['lan']['wireless'])))
!is_array($config['interfaces']['lan']['wireless'])) {
$config['interfaces']['lan']['wireless'] = array();
}
} else {
if (isset($config['interfaces']['lan']))
if (isset($config['interfaces']['lan'])) {
unset($config['interfaces']['lan']['wireless']);
}
}
if (!is_array($config['interfaces']['wan']))
if (!is_array($config['interfaces']['wan'])) {
$config['interfaces']['wan'] = array();
}
$config['interfaces']['wan']['if'] = $wanif;
$config['interfaces']['wan']['enable'] = true;
if (preg_match($g['wireless_regex'], $wanif)) {
if (is_array($config['interfaces']['wan']) &&
(!is_array($config['interfaces']['wan']['wireless'])))
!is_array($config['interfaces']['wan']['wireless'])) {
$config['interfaces']['wan']['wireless'] = array();
}
} else {
if (isset($config['interfaces']['wan']))
if (isset($config['interfaces']['wan'])) {
unset($config['interfaces']['wan']['wireless']);
}
}
for ($i = 0; $i < count($optif); $i++) {
if (!is_array($config['interfaces']['opt' . ($i+1)]))
if (!is_array($config['interfaces']['opt' . ($i+1)])) {
$config['interfaces']['opt' . ($i+1)] = array();
}
$config['interfaces']['opt' . ($i+1)]['if'] = $optif[$i];
/* wireless interface? */
if (preg_match($g['wireless_regex'], $optif[$i])) {
if (!is_array($config['interfaces']['opt' . ($i+1)]['wireless']))
if (!is_array($config['interfaces']['opt' . ($i+1)]['wireless'])) {
$config['interfaces']['opt' . ($i+1)]['wireless'] = array();
}
} else {
unset($config['interfaces']['opt' . ($i+1)]['wireless']);
}
@ -402,8 +433,9 @@ EODD;
}
/* remove all other (old) optional interfaces */
for (; isset($config['interfaces']['opt' . ($i+1)]); $i++)
for (; isset($config['interfaces']['opt' . ($i+1)]); $i++) {
unset($config['interfaces']['opt' . ($i+1)]);
}
printf(gettext("%sWriting configuration..."), "\n");
write_config("Console assignment of interfaces");
@ -411,8 +443,9 @@ EODD;
fclose($fp);
if(platform_booting())
if (platform_booting()) {
return;
}
echo gettext("One moment while we reload the settings...");
echo gettext(" done!") . "\n";
@ -449,8 +482,6 @@ function interfaces_setup() {
global $iflist, $config, $g, $fp;
$iflist = get_interface_list();
}
function vlan_setup() {
@ -460,15 +491,16 @@ function vlan_setup() {
if (is_array($config['vlans']['vlan']) && count($config['vlans']['vlan'])) {
echo <<<EOD
echo <<<EOD
WARNING: all existing VLANs will be cleared if you proceed!
Do you want to proceed [y|n]?
EOD;
if (strcasecmp(chop(fgets($fp)), "y") != 0)
return;
if (strcasecmp(chop(fgets($fp)), "y") != 0) {
return;
}
}
$config['vlans']['vlan'] = array();
@ -480,7 +512,7 @@ EOD;
$vlan = array();
echo "\n\n" . gettext("VLAN Capable interfaces:") . "\n\n";
if(!is_array($iflist)) {
if (!is_array($iflist)) {
echo gettext("No interfaces found!") . "\n";
} else {
$vlan_capable=0;
@ -493,7 +525,7 @@ EOD;
}
}
if($vlan_capable == 0) {
if ($vlan_capable == 0) {
echo gettext("No VLAN capable interfaces detected.") . "\n";
return;
}
@ -518,7 +550,7 @@ EOD;
printf(gettext("%sInvalid VLAN tag '%s'%s"), "\n", $vlan['tag'], "\n");
continue;
}
$config['vlans']['vlan'][] = $vlan;
$vlanif++;
}

View File

@ -45,20 +45,22 @@
require_once("globals.inc");
/* do not load this file twice. */
if($config_parsed == true)
if ($config_parsed == true) {
return;
else
} else {
$config_parsed = true;
}
/* include globals from notices.inc /utility/XML parser files */
require_once('config.lib.inc');
require_once("notices.inc");
require_once("util.inc");
require_once("IPv6.inc");
if(file_exists("/cf/conf/use_xmlreader"))
if (file_exists("/cf/conf/use_xmlreader")) {
require_once("xmlreader.inc");
else
} else {
require_once("xmlparse.inc");
}
require_once("crypt.inc");
/* read platform */
@ -70,7 +72,7 @@ if (file_exists("{$g['etc_path']}/platform")) {
/* if /debugging exists, lets set $debugging
so we can output more information */
if(file_exists("/debugging")) {
if (file_exists("/debugging")) {
$debugging = true;
$g['debug'] = true;
}
@ -79,13 +81,14 @@ $config = parse_config();
/* set timezone */
$timezone = $config['system']['timezone'];
if (!$timezone)
$timezone = "Etc/UTC";
if (!$timezone) {
$timezone = "Etc/UTC";
}
date_default_timezone_set("$timezone");
if($config_parsed == true) {
if ($config_parsed == true) {
/* process packager manager custom rules */
if(is_dir("/usr/local/pkg/parse_config")) {
if (is_dir("/usr/local/pkg/parse_config")) {
run_plugins("/usr/local/pkg/parse_config/");
}
}

View File

@ -42,8 +42,9 @@
pfSense_MODULE: config
*/
if (!function_exists('platform_booting'))
if (!function_exists('platform_booting')) {
require_once('globals.inc');
}
/* do not load this file twice. */
//if (in_array("/etc/inc/config.inc", get_included_files()))
@ -52,24 +53,27 @@ if (!function_exists('platform_booting'))
// Set the memory limit to 128M on i386. When someone has something like 500+ tunnels
// the parser needs quite a bit of ram. Do not remove this line unless you
// know what you are doing. If in doubt, check with dev@ _/FIRST/_!
if(!$ARCH)
if (!$ARCH) {
$ARCH = php_uname("m");
}
// Set memory limit to 256M on amd64.
if($ARCH == "amd64")
if ($ARCH == "amd64") {
ini_set("memory_limit","256M");
else
} else {
ini_set("memory_limit","128M");
}
/* include globals from notices.inc /utility/XML parser files */
require_once("notices.inc");
require_once("util.inc");
require_once("IPv6.inc");
require_once('config.lib.inc');
if(file_exists("/cf/conf/use_xmlreader"))
if (file_exists("/cf/conf/use_xmlreader")) {
require_once("xmlreader.inc");
else
} else {
require_once("xmlparse.inc");
}
require_once("crypt.inc");
/* read platform */
@ -81,22 +85,23 @@ if (file_exists("{$g['etc_path']}/platform")) {
/* if /debugging exists, lets set $debugging
so we can output more information */
if(file_exists("/debugging")) {
if (file_exists("/debugging")) {
$debugging = true;
$g['debug'] = true;
}
if(platform_booting(true)) {
if (platform_booting(true)) {
echo ".";
if(file_exists("/cf/conf/config.xml")) {
if (file_exists("/cf/conf/config.xml")) {
$config_contents = file_get_contents("/cf/conf/config.xml");
if(stristr($config_contents, "<m0n0wall>") == true) {
if (stristr($config_contents, "<m0n0wall>") == true) {
echo ".";
/* user has just upgraded to m0n0wall, replace root xml tags */
/* user has just upgraded from m0n0wall, replace root xml tags */
log_error(gettext("Upgrading m0n0wall configuration to pfSense... "));
$config_contents = str_replace("m0n0wall","pfsense", $config_contents);
if (!config_validate("{$g['conf_path']}/config.xml"))
if (!config_validate("{$g['conf_path']}/config.xml")) {
log_error(gettext("ERROR! Could not convert m0n0wall -> pfsense in config.xml"));
}
conf_mount_rw();
file_put_contents("/cf/conf/config.xml", $config_contents);
conf_mount_ro();
@ -116,7 +121,7 @@ if(platform_booting(true)) {
/* config is on floppy disk for CD-ROM version */
$cfgdevice = $cfgpartition = "fd0";
$_gb = exec('/sbin/dmesg -a', $dmesg);
if(preg_match("/da0/", $dmesg) == true) {
if (preg_match("/da0/", $dmesg) == true) {
$cfgdevice = $cfgpartition = "da0" ;
if (mwexec("/sbin/mount -r /dev/{$cfgdevice} /cf")) {
/* could not mount, fallback to floppy */
@ -135,8 +140,9 @@ if(platform_booting(true)) {
$disks = explode(" ", get_single_sysctl("kern.disks"));
foreach ($disks as $mountdisk) {
/* skip mfs mounted filesystems */
if (strstr($mountdisk, "md"))
if (strstr($mountdisk, "md")) {
continue;
}
if (mwexec("/sbin/mount -r /dev/{$mountdisk}a {$g['cf_path']}") == 0) {
if (file_exists("{$g['cf_conf_path']}/config.xml")) {
/* found it */
@ -148,11 +154,14 @@ if(platform_booting(true)) {
mwexec("/sbin/umount -f {$g['cf_path']}");
if ($cfgdevice)
if ($cfgdevice) {
break;
}
}
if (mwexec("/sbin/mount -r /dev/{$mountdisk}d {$g['cf_path']}") == 0) {
if(platform_booting()) echo ".";
if (platform_booting()) {
echo ".";
}
if (file_exists("{$g['cf_conf_path']}/config.xml")) {
/* found it */
$cfgdevice = $mountdisk;
@ -163,15 +172,16 @@ if(platform_booting(true)) {
mwexec("/sbin/umount -f {$g['cf_path']}");
if ($cfgdevice)
if ($cfgdevice) {
break;
}
}
}
}
echo ".";
if (!$cfgdevice) {
$last_backup = discover_last_backup();
if($last_backup) {
if ($last_backup) {
log_error(gettext("No config.xml found, attempting last known config restore."));
file_notice("config.xml", gettext("No config.xml found, attempting last known config restore."), "pfSenseConfigurator", "");
restore_backup("/cf/conf/backup/{$last_backup}");
@ -201,13 +211,14 @@ $config = parse_config();
/* set timezone */
$timezone = $config['system']['timezone'];
if (!$timezone)
if (!$timezone) {
$timezone = "Etc/UTC";
}
date_default_timezone_set("$timezone");
if($config_parsed == true) {
if ($config_parsed == true) {
/* process packager manager custom rules */
if(is_dir("/usr/local/pkg/parse_config")) {
if (is_dir("/usr/local/pkg/parse_config")) {
run_plugins("/usr/local/pkg/parse_config/");
}
}

View File

@ -54,24 +54,27 @@
function encrypted_configxml() {
global $g, $config;
if (!file_exists($g['conf_path'] . "/config.xml"))
if (!file_exists($g['conf_path'] . "/config.xml")) {
return;
}
if (!platform_booting())
if (!platform_booting()) {
return;
}
$configtxt = file_get_contents($g['conf_path'] . "/config.xml");
if(tagfile_deformat($configtxt, $configtxt, "config.xml")) {
$configtxt = file_get_contents($g['conf_path'] . "/config.xml");
if (tagfile_deformat($configtxt, $configtxt, "config.xml")) {
$fp = fopen('php://stdin', 'r');
$data = "";
echo "\n\n*** Encrypted config.xml detected ***\n";
while($data == "") {
while ($data == "") {
echo "\nEnter the password to decrypt config.xml: ";
$decrypt_password = chop(fgets($fp));
$data = decrypt_data($configtxt, $decrypt_password);
if(!strstr($data, "<pfsense>"))
if (!strstr($data, "<pfsense>")) {
$data = "";
if($data) {
}
if ($data) {
$fd = fopen($g['conf_path'] . "/config.xml.tmp", "w");
fwrite($fd, $data);
fclose($fd);
@ -101,7 +104,7 @@ function parse_config($parse = false) {
if (!file_exists("{$g['conf_path']}/config.xml") || filesize("{$g['conf_path']}/config.xml") == 0) {
$last_backup = discover_last_backup();
if($last_backup) {
if ($last_backup) {
log_error(gettext("No config.xml found, attempting last known config restore."));
file_notice("config.xml", gettext("No config.xml found, attempting last known config restore."), "pfSenseConfigurator", "");
restore_backup("{$g['conf_path']}/backup/{$last_backup}");
@ -117,35 +120,38 @@ function parse_config($parse = false) {
// Check for encrypted config.xml
encrypted_configxml();
if(!$parse) {
if (!$parse) {
if (file_exists($g['tmp_path'] . '/config.cache')) {
$config = unserialize(file_get_contents($g['tmp_path'] . '/config.cache'));
if (is_null($config))
if (is_null($config)) {
$parse = true;
} else
}
} else {
$parse = true;
}
}
if ($parse == true) {
if(!file_exists($g['conf_path'] . "/config.xml")) {
if (platform_booting(true))
if (!file_exists($g['conf_path'] . "/config.xml")) {
if (platform_booting(true)) {
echo ".";
}
log_error("No config.xml found, attempting last known config restore.");
file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
$last_backup = discover_last_backup();
if ($last_backup)
if ($last_backup) {
restore_backup("/cf/conf/backup/{$last_backup}");
else {
} else {
log_error(gettext("Could not restore config.xml."));
unlock($lockkey);
die(gettext("Config.xml is corrupted and is 0 bytes. Could not restore a previous backup."));
}
}
$config = parse_xml_config($g['conf_path'] . '/config.xml', array($g['xml_rootobj'], 'pfsense'));
if($config == -1) {
if ($config == -1) {
$last_backup = discover_last_backup();
if ($last_backup)
if ($last_backup) {
restore_backup("/cf/conf/backup/{$last_backup}");
else {
} else {
log_error(gettext("Could not restore config.xml."));
unlock($lockkey);
die("Config.xml is corrupted and is 0 bytes. Could not restore a previous backup.");
@ -154,8 +160,9 @@ function parse_config($parse = false) {
generate_config_cache($config);
}
if (platform_booting(true))
if (platform_booting(true)) {
echo ".";
}
$config_parsed = true;
unlock($lockkey);
@ -181,10 +188,10 @@ function generate_config_cache($config) {
fclose($configcache);
unset($configcache);
/* Used for config.extra.xml */
if(file_exists($g['tmp_path'] . '/config.extra.cache') && $config_extra) {
if (file_exists($g['tmp_path'] . '/config.extra.cache') && $config_extra) {
$configcacheextra = fopen($g['tmp_path'] . '/config.extra.cache', "w");
fwrite($configcacheextra, serialize($config_extra));
fclose($configcacheextra);
fclose($configcacheextra);
unset($configcacheextra);
}
}
@ -193,8 +200,8 @@ function discover_last_backup() {
$backups = glob('/cf/conf/backup/*.xml');
$last_backup = "";
$last_mtime = 0;
foreach($backups as $backup) {
if(filemtime($backup) > $last_mtime) {
foreach ($backups as $backup) {
if (filemtime($backup) > $last_mtime) {
$last_mtime = filemtime($backup);
$last_backup = $backup;
}
@ -226,8 +233,9 @@ function restore_backup($file) {
function parse_config_bootup() {
global $config, $g;
if (platform_booting())
if (platform_booting()) {
echo ".";
}
$lockkey = lock('config');
if (!file_exists("{$g['conf_path']}/config.xml")) {
@ -244,12 +252,12 @@ function parse_config_bootup() {
}
} else {
$last_backup = discover_last_backup();
if($last_backup) {
if ($last_backup) {
log_error("No config.xml found, attempting last known config restore.");
file_notice("config.xml", gettext("No config.xml found, attempting last known config restore."), "pfSenseConfigurator", "");
restore_backup("/cf/conf/backup/{$last_backup}");
}
if(!file_exists("{$g['conf_path']}/config.xml")) {
if (!file_exists("{$g['conf_path']}/config.xml")) {
echo sprintf(gettext("XML configuration file not found. %s cannot continue booting."), $g['product_name']) . "\n";
unlock($lockkey);
mwexec("/sbin/halt");
@ -267,7 +275,7 @@ function parse_config_bootup() {
if (filesize("{$g['conf_path']}/config.xml") == 0) {
$last_backup = discover_last_backup();
if($last_backup) {
if ($last_backup) {
log_error(gettext("No config.xml found, attempting last known config restore."));
file_notice("config.xml", gettext("No config.xml found, attempting last known config restore."), "pfSenseConfigurator", "");
restore_backup("{$g['conf_path']}/backup/{$last_backup}");
@ -311,31 +319,34 @@ function conf_mount_rw() {
global $g, $config;
/* do not mount on cdrom platform */
if($g['platform'] == "cdrom" or $g['platform'] == "pfSense")
if ($g['platform'] == "cdrom" or $g['platform'] == "pfSense") {
return;
}
if ((refcount_reference(1000) > 1) && is_writable("/"))
if ((refcount_reference(1000) > 1) && is_writable("/")) {
return;
}
$status = mwexec("/sbin/mount -u -w -o sync,noatime {$g['cf_path']}");
if($status <> 0) {
if (platform_booting())
if ($status <> 0) {
if (platform_booting()) {
echo gettext("Disk is dirty. Running fsck -y") . "\n";
}
mwexec("/sbin/fsck -y {$g['cf_path']}");
$status = mwexec("/sbin/mount -u -w -o sync,noatime {$g['cf_path']}");
}
/* if the platform is soekris or wrap or pfSense, lets mount the
* compact flash cards root.
*/
*/
$status = mwexec("/sbin/mount -u -w -o sync,noatime /");
/* we could not mount this correctly. kick off fsck */
if($status <> 0) {
if ($status <> 0) {
log_error(gettext("File system is dirty. Launching FSCK for /"));
mwexec("/sbin/fsck -y /");
$status = mwexec("/sbin/mount -u -w -o sync,noatime /");
}
mark_subsystem_dirty('mount');
}
@ -351,17 +362,21 @@ function conf_mount_ro() {
/* Do not trust $g['platform'] since this can be clobbered during factory reset. */
$platform = trim(file_get_contents("/etc/platform"));
/* do not umount on cdrom or pfSense platforms */
if($platform == "cdrom" or $platform == "pfSense")
if ($platform == "cdrom" or $platform == "pfSense") {
return;
}
if (refcount_unreference(1000) > 0)
if (refcount_unreference(1000) > 0) {
return;
}
if(isset($config['system']['nanobsd_force_rw']))
if (isset($config['system']['nanobsd_force_rw'])) {
return;
}
if (platform_booting())
if (platform_booting()) {
return;
}
clear_subsystem_dirty('mount');
/* sync data, then force a remount of /cf */
@ -393,45 +408,51 @@ function convert_config() {
if (is_array($config['cron'])) {
$cron_item_count = count($config['cron']['item']);
for($x=0; $x<$cron_item_count; $x++) {
if(stristr($config['cron']['item'][$x]['command'], "rc.update_bogons.sh")) {
if($config['cron']['item'][$x]['hour'] == "*" ) {
$config['cron']['item'][$x]['hour'] = "3";
if (stristr($config['cron']['item'][$x]['command'], "rc.update_bogons.sh")) {
if ($config['cron']['item'][$x]['hour'] == "*" ) {
$config['cron']['item'][$x]['hour'] = "3";
write_config(gettext("Updated bogon update frequency to 3am"));
log_error(gettext("Updated bogon update frequency to 3am"));
}
}
}
}
}
if ($config['version'] == $g['latest_config'])
if ($config['version'] == $g['latest_config']) {
return; /* already at latest version */
}
// Save off config version
$prev_version = $config['version'];
include_once('auth.inc');
include_once('upgrade_config.inc');
if (file_exists("/etc/inc/upgrade_config_custom.inc"))
if (file_exists("/etc/inc/upgrade_config_custom.inc")) {
include_once("upgrade_config_custom.inc");
}
/* Loop and run upgrade_VER_to_VER() until we're at current version */
while ($config['version'] < $g['latest_config']) {
$cur = $config['version'] * 10;
$next = $cur + 1;
$migration_function = sprintf('upgrade_%03d_to_%03d', $cur, $next);
if (function_exists($migration_function))
if (function_exists($migration_function)) {
$migration_function();
}
$migration_function = "{$migration_function}_custom";
if (function_exists($migration_function))
if (function_exists($migration_function)) {
$migration_function();
}
$config['version'] = sprintf('%.1f', $next / 10);
if (platform_booting())
if (platform_booting()) {
echo ".";
}
}
$now = date("H:i:s");
log_error(sprintf(gettext("Ended Configuration upgrade at %s"), $now));
if ($prev_version != $config['version'])
if ($prev_version != $config['version']) {
write_config(sprintf(gettext('Upgraded config version level from %1$s to %2$s'), $prev_version, $config['version']));
}
}
/****f* config/safe_write_file
@ -457,7 +478,7 @@ function safe_write_file($file, $content, $force_binary) {
if (!$fd) {
// Unable to open temporary file for writing
return false;
}
}
if (!fwrite($fd, $content)) {
// Unable to write to temporary file
fclose($fd);
@ -495,8 +516,9 @@ function write_config($desc="Unknown", $backup = true) {
global $config, $g;
if (!empty($_SERVER['REMOTE_ADDR'])) {
if (!session_id())
if (!session_id()) {
@session_start();
}
if (!empty($_SESSION['Username']) && ($_SESSION['Username'] != "admin")) {
$user = getUserEntry($_SESSION['Username']);
if (is_array($user) && userHasPrivilege($user, "user-config-readonly")) {
@ -506,11 +528,13 @@ function write_config($desc="Unknown", $backup = true) {
}
}
if (!isset($argc))
if (!isset($argc)) {
session_commit();
}
if($backup)
if ($backup) {
backup_config();
}
$config['revision'] = make_config_revision_entry($desc);
@ -527,7 +551,7 @@ function write_config($desc="Unknown", $backup = true) {
file_notice("config.xml", sprintf(gettext("Unable to open %s/config.xml for writing in write_config()%s"), $g['cf_conf_path'], "\n"));
return -1;
}
cleanup_backupcache(true);
/* re-read configuration */
@ -544,10 +568,12 @@ function write_config($desc="Unknown", $backup = true) {
echo "\n\n Configuration could not be validated. A previous configuration was restored. \n";
echo "\n The failed configuration file has been saved as {$g['conf_path']}/config.xml.bad \n\n";
}
} else
} else {
log_error(gettext("Could not restore config.xml."));
} else
}
} else {
generate_config_cache($config);
}
unlock($lockkey);
@ -559,7 +585,7 @@ function write_config($desc="Unknown", $backup = true) {
/* sync carp entries to other firewalls */
carp_sync_client();
if(is_dir("/usr/local/pkg/write_config")) {
if (is_dir("/usr/local/pkg/write_config")) {
/* process packager manager custom rules */
run_plugins("/usr/local/pkg/write_config/");
}
@ -577,8 +603,9 @@ function reset_factory_defaults($lock = false) {
global $g;
conf_mount_rw();
if (!$lock)
if (!$lock) {
$lockkey = lock('config', LOCK_EX);
}
/* create conf directory, if necessary */
safe_mkdir("{$g['cf_conf_path']}");
@ -600,8 +627,9 @@ function reset_factory_defaults($lock = false) {
/* call the wizard */
touch("/conf/trigger_initial_wizard");
if (!$lock)
if (!$lock) {
unlock($lockkey);
}
conf_mount_ro();
setup_serial_port();
return 0;
@ -610,13 +638,14 @@ function reset_factory_defaults($lock = false) {
function config_restore($conffile) {
global $config, $g;
if (!file_exists($conffile))
if (!file_exists($conffile)) {
return 1;
}
backup_config();
conf_mount_rw();
$lockkey = lock('config', LOCK_EX);
unlink_if_exists("{$g['tmp_path']}/config.cache");
@ -638,16 +667,19 @@ function config_restore($conffile) {
function config_install($conffile) {
global $config, $g;
if (!file_exists($conffile))
if (!file_exists($conffile)) {
return 1;
}
if (!config_validate("{$conffile}"))
if (!config_validate("{$conffile}")) {
return 1;
}
if (platform_booting())
if (platform_booting()) {
echo gettext("Installing configuration...") . "\n";
else
} else {
log_error(gettext("Installing configuration ...."));
}
conf_mount_rw();
$lockkey = lock('config', LOCK_EX);
@ -657,13 +689,14 @@ function config_install($conffile) {
disable_security_checks();
/* unlink cache file if it exists */
if(file_exists("{$g['tmp_path']}/config.cache"))
if (file_exists("{$g['tmp_path']}/config.cache")) {
unlink("{$g['tmp_path']}/config.cache");
}
unlock($lockkey);
conf_mount_ro();
return 0;
return 0;
}
/*
@ -723,8 +756,9 @@ function cleanup_backupcache($lock = false) {
$revisions = get_config_backup_count();
if (!$lock)
if (!$lock) {
$lockkey = lock('config');
}
conf_mount_rw();
@ -740,9 +774,9 @@ function cleanup_backupcache($lock = false) {
$bakfiles = glob($g['cf_conf_path'] . "/backup/config-*");
$tocache = array();
foreach($bakfiles as $backup) { // Check for backups in the directory not represented in the cache.
foreach ($bakfiles as $backup) { // Check for backups in the directory not represented in the cache.
$backupsize = filesize($backup);
if($backupsize == 0) {
if ($backupsize == 0) {
unlink($backup);
continue;
}
@ -750,39 +784,45 @@ function cleanup_backupcache($lock = false) {
$backupexp = explode('.', array_pop($backupexp));
$tocheck = array_shift($backupexp);
unset($backupexp);
if(!in_array($tocheck, $baktimes)) {
if (!in_array($tocheck, $baktimes)) {
$i = true;
if (platform_booting())
if (platform_booting()) {
echo ".";
}
$newxml = parse_xml_config($backup, array($g['xml_rootobj'], 'pfsense'));
if($newxml == "-1") {
if ($newxml == "-1") {
log_error(sprintf(gettext("The backup cache file %s is corrupted. Unlinking."), $backup));
unlink($backup);
log_error(sprintf(gettext("The backup cache file %s is corrupted. Unlinking."), $backup));
continue;
}
if($newxml['revision']['description'] == "")
if ($newxml['revision']['description'] == "") {
$newxml['revision']['description'] = "Unknown";
if($newxml['version'] == "")
}
if ($newxml['version'] == "") {
$newxml['version'] = "?";
}
$tocache[$tocheck] = array('description' => $newxml['revision']['description'], 'version' => $newxml['version'], 'filesize' => $backupsize);
}
}
foreach($backups as $checkbak) {
if(count(preg_grep('/' . $checkbak['time'] . '/i', $bakfiles)) != 0) {
foreach ($backups as $checkbak) {
if (count(preg_grep('/' . $checkbak['time'] . '/i', $bakfiles)) != 0) {
$newbaks[] = $checkbak;
} else {
$i = true;
if (platform_booting()) print " " . $tocheck . "r";
}
}
foreach($newbaks as $todo) $tocache[$todo['time']] = array('description' => $todo['description'], 'version' => $todo['version'], 'filesize' => $todo['filesize']);
if(is_int($revisions) and (count($tocache) > $revisions)) {
foreach ($newbaks as $todo) {
$tocache[$todo['time']] = array('description' => $todo['description'], 'version' => $todo['version'], 'filesize' => $todo['filesize']);
}
if (is_int($revisions) and (count($tocache) > $revisions)) {
$toslice = array_slice(array_keys($tocache), 0, $revisions);
foreach($toslice as $sliced)
foreach ($toslice as $sliced) {
$newcache[$sliced] = $tocache[$sliced];
foreach($tocache as $version => $versioninfo) {
if(!in_array($version, array_keys($newcache))) {
}
foreach ($tocache as $version => $versioninfo) {
if (!in_array($version, array_keys($newcache))) {
unlink_if_exists($g['conf_path'] . '/backup/config-' . $version . '.xml');
}
}
@ -793,20 +833,22 @@ function cleanup_backupcache($lock = false) {
fclose($bakout);
conf_mount_ro();
if (!$lock)
if (!$lock) {
unlock($lockkey);
}
}
function get_backups() {
global $g;
if(file_exists("{$g['cf_conf_path']}/backup/backup.cache")) {
if (file_exists("{$g['cf_conf_path']}/backup/backup.cache")) {
$confvers = unserialize(file_get_contents("{$g['cf_conf_path']}/backup/backup.cache"));
$bakvers = array_keys($confvers);
$toreturn = array();
sort($bakvers);
// $bakvers = array_reverse($bakvers);
foreach(array_reverse($bakvers) as $bakver)
foreach (array_reverse($bakvers) as $bakver) {
$toreturn[] = array('time' => $bakver, 'description' => $confvers[$bakver]['description'], 'version' => $confvers[$bakver]['version'], 'filesize' => $confvers[$bakver]['filesize']);
}
} else {
return false;
}
@ -817,37 +859,38 @@ function get_backups() {
function backup_config() {
global $config, $g;
if($g['platform'] == "cdrom")
if ($g['platform'] == "cdrom") {
return;
}
conf_mount_rw();
/* Create backup directory if needed */
safe_mkdir("{$g['cf_conf_path']}/backup");
if($config['revision']['time'] == "") {
$baktime = 0;
} else {
$baktime = $config['revision']['time'];
}
if($config['revision']['description'] == "") {
$bakdesc = "Unknown";
} else {
$bakdesc = $config['revision']['description'];
}
if ($config['revision']['time'] == "") {
$baktime = 0;
} else {
$baktime = $config['revision']['time'];
}
if ($config['revision']['description'] == "") {
$bakdesc = "Unknown";
} else {
$bakdesc = $config['revision']['description'];
}
$bakver = ($config['version'] == "") ? "?" : $config['version'];
$bakfilename = $g['cf_conf_path'] . '/backup/config-' . $baktime . '.xml';
copy($g['cf_conf_path'] . '/config.xml', $bakfilename);
if(file_exists($g['cf_conf_path'] . '/backup/backup.cache')) {
$backupcache = unserialize(file_get_contents($g['cf_conf_path'] . '/backup/backup.cache'));
} else {
$backupcache = array();
}
if (file_exists($g['cf_conf_path'] . '/backup/backup.cache')) {
$backupcache = unserialize(file_get_contents($g['cf_conf_path'] . '/backup/backup.cache'));
} else {
$backupcache = array();
}
$backupcache[$baktime] = array('description' => $bakdesc, 'version' => $bakver, 'filesize' => filesize($bakfilename));
$bakout = fopen($g['cf_conf_path'] . '/backup/backup.cache', "w");
fwrite($bakout, serialize($backupcache));
fclose($bakout);
$bakout = fopen($g['cf_conf_path'] . '/backup/backup.cache', "w");
fwrite($bakout, serialize($backupcache));
fclose($bakout);
conf_mount_ro();
@ -874,33 +917,40 @@ function set_device_perms() {
function get_config_user() {
if (empty($_SESSION["Username"])) {
$username = getenv("USER");
if (empty($conuser) || $conuser == "root")
if (empty($conuser) || $conuser == "root") {
$username = "(system)";
} else
}
} else {
$username = $_SESSION["Username"];
}
if (!empty($_SERVER['REMOTE_ADDR']))
if (!empty($_SERVER['REMOTE_ADDR'])) {
$username .= '@' . $_SERVER['REMOTE_ADDR'];
}
return $username;
}
function make_config_revision_entry($desc = null, $override_user = null) {
if (empty($override_user))
if (empty($override_user)) {
$username = get_config_user();
else
} else {
$username = $override_user;
}
$revision = array();
if (time() > mktime(0, 0, 0, 9, 1, 2004)) /* make sure the clock settings are plausible */
if (time() > mktime(0, 0, 0, 9, 1, 2004)) { /* make sure the clock settings are plausible */
$revision['time'] = time();
}
/* Log the running script so it's not entirely unlogged what changed */
if ($desc == "Unknown")
if ($desc == "Unknown") {
$desc = sprintf(gettext("%s made unknown change"), $_SERVER['SCRIPT_NAME']);
if (!empty($desc))
}
if (!empty($desc)) {
$revision['description'] = "{$username}: " . $desc;
}
$revision['username'] = $username;
return $revision;
}
@ -920,9 +970,9 @@ function pfSense_clear_globals() {
global $config, $FilterIfList, $GatewaysList, $filterdns, $aliases, $aliastable;
$error = error_get_last();
if ( $error !== NULL) {
if ( $error['type'] != E_NOTICE ) {
if ($error !== NULL) {
if ($error['type'] != E_NOTICE) {
$errorstr = "PHP ERROR: Type: {$error['type']}, File: {$error['file']}, Line: {$error['line']}, Message: {$error['message']}";
// XXX: comment out for now, should re-enable post-2.2
//print($errorstr);
@ -930,21 +980,26 @@ function pfSense_clear_globals() {
}
}
if (isset($FilterIfList))
if (isset($FilterIfList)) {
unset($FilterIfList);
}
if (isset($GatewaysList))
if (isset($GatewaysList)) {
unset($GatewaysList);
}
/* Used for the hostname dns resolver */
if (isset($filterdns))
if (isset($filterdns)) {
unset($filterdns);
}
/* Used for aliases and interface macros */
if (isset($aliases))
if (isset($aliases)) {
unset($aliases);
if (isset($aliastable))
}
if (isset($aliastable)) {
unset($aliastable);
}
unset($config);
}

View File

@ -2,29 +2,29 @@
/* $Id$ */
/*
Copyright (C) 2008 Shrew Soft Inc
All rights reserved.
Copyright (C) 2008 Shrew Soft Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
pfSense_BUILDER_BINARIES: /usr/bin/openssl
pfSense_MODULE: crypto
@ -35,9 +35,9 @@
$file = tempnam("/tmp", "php-encrypt");
file_put_contents("{$file}.dec", $val);
exec("/usr/bin/openssl enc {$opt} -aes-256-cbc -in {$file}.dec -out {$file}.enc -k " . escapeshellarg($pass));
if (file_exists("{$file}.enc"))
if (file_exists("{$file}.enc")) {
$result = file_get_contents("{$file}.enc");
else {
} else {
$result = "";
log_error("Failed to encrypt/decrypt data!");
}
@ -84,8 +84,9 @@
$btag_pos = stripos($in, $btag_val);
$etag_pos = stripos($in, $etag_val);
if (($btag_pos === false) || ($etag_pos === false))
if (($btag_pos === false) || ($etag_pos === false)) {
return false;
}
$body_pos = $btag_pos + $btag_len;
$body_len = strlen($in);

View File

@ -27,9 +27,11 @@
* - Custom DDNS (any URL)
* - Custom DDNS IPv6 (any URL)
* - CloudFlare (www.cloudflare.com)
* - Eurodns (eurodns.com)
* - GratisDNS (gratisdns.dk)
* - Eurodns (eurodns.com)
* - GratisDNS (gratisdns.dk)
* - City Network (citynetwork.se)
* - GleSYS (glesys.com)
* - DNSimple (dnsimple.com)
* +----------------------------------------------------+
* Requirements:
* - PHP version 4.0.2 or higher with the CURL Library and the PCRE Library
@ -45,33 +47,35 @@
* - _debug()
* - _checkIP()
* +----------------------------------------------------+
* DynDNS Dynamic - Last Tested: 12 July 2005
* DynDNS Static - Last Tested: NEVER
* DynDNS Custom - Last Tested: NEVER
* No-IP - Last Tested: 20 July 2008
* HN.org - Last Tested: 12 July 2005
* EasyDNS - Last Tested: 20 July 2008
* DHS - Last Tested: 12 July 2005
* ZoneEdit - Last Tested: NEVER
* Dyns - Last Tested: NEVER
* ODS - Last Tested: 02 August 2005
* FreeDNS - Last Tested: 23 Feb 2011
* Loopia - Last Tested: NEVER
* StaticCling - Last Tested: 27 April 2006
* DNSexit - Last Tested: 20 July 2008
* OpenDNS - Last Tested: 4 August 2008
* Namecheap - Last Tested: 31 August 2010
* HE.net - Last Tested: 7 July 2013
* HE.net IPv6 - Last Tested: 7 July 2013
* HE.net Tunnel - Last Tested: 28 June 2011
* SelfHost - Last Tested: 26 December 2011
* DynDNS Dynamic - Last Tested: 12 July 2005
* DynDNS Static - Last Tested: NEVER
* DynDNS Custom - Last Tested: NEVER
* No-IP - Last Tested: 20 July 2008
* HN.org - Last Tested: 12 July 2005
* EasyDNS - Last Tested: 20 July 2008
* DHS - Last Tested: 12 July 2005
* ZoneEdit - Last Tested: NEVER
* Dyns - Last Tested: NEVER
* ODS - Last Tested: 02 August 2005
* FreeDNS - Last Tested: 23 Feb 2011
* Loopia - Last Tested: NEVER
* StaticCling - Last Tested: 27 April 2006
* DNSexit - Last Tested: 20 July 2008
* OpenDNS - Last Tested: 4 August 2008
* Namecheap - Last Tested: 31 August 2010
* HE.net - Last Tested: 7 July 2013
* HE.net IPv6 - Last Tested: 7 July 2013
* HE.net Tunnel - Last Tested: 28 June 2011
* SelfHost - Last Tested: 26 December 2011
* Amazon Route 53 - Last tested: 01 April 2012
* DNS-O-Matic - Last Tested: 9 September 2010
* CloudFlare - Last Tested: 30 May 2013
* Eurodns - Last Tested: 27 June 2013
* GratisDNS - Last Tested: 15 August 2012
* OVH DynHOST - Last Tested: NEVER
* City Network - Last Tested: 13 November 2013
* DNS-O-Matic - Last Tested: 9 September 2010
* CloudFlare - Last Tested: 30 May 2013
* Eurodns - Last Tested: 27 June 2013
* GratisDNS - Last Tested: 15 August 2012
* OVH DynHOST - Last Tested: NEVER
* City Network - Last Tested: 13 November 2013
* GleSYS - Last Tested: 3 February 2015
* DNSimple - Last Tested: 09 February 2015
* +====================================================+
*
* @author E.Kristensen
@ -116,24 +120,24 @@
var $_dnsDummyUpdateDone;
var $_forceUpdateNeeded;
var $_useIPv6;
/*
/*
* Public Constructor Function (added 12 July 05) [beta]
* - Gets the dice rolling for the update.
* - Gets the dice rolling for the update.
* - $dnsResultMatch should only be used with $dnsService = 'custom'
* - $dnsResultMatch is parsed for '%IP%', which is the IP the provider was updated to,
* - $dnsResultMatch is parsed for '%IP%', which is the IP the provider was updated to,
* - it is otherwise expected to be exactly identical to what is returned by the Provider.
* - $dnsUser, and $dnsPass indicate HTTP Auth for custom DNS, if they are needed in the URL (GET Variables), include them in $dnsUpdateURL.
* - $For custom requests, $dnsUpdateURL is parsed for '%IP%', which is replaced with the new IP.
*/
function updatedns ($dnsService = '', $dnsHost = '', $dnsUser = '', $dnsPass = '',
$dnsWildcard = 'OFF', $dnsMX = '', $dnsIf = '', $dnsBackMX = '',
$dnsServer = '', $dnsPort = '', $dnsUpdateURL = '', $forceUpdate = false,
$dnsZoneID ='', $dnsTTL='', $dnsResultMatch = '', $dnsRequestIf = '',
$dnsID = '', $dnsVerboseLog = false, $curlIpresolveV4 = false, $curlSslVerifypeer = true) {
$dnsWildcard = 'OFF', $dnsMX = '', $dnsIf = '', $dnsBackMX = '',
$dnsServer = '', $dnsPort = '', $dnsUpdateURL = '', $forceUpdate = false,
$dnsZoneID ='', $dnsTTL='', $dnsResultMatch = '', $dnsRequestIf = '',
$dnsID = '', $dnsVerboseLog = false, $curlIpresolveV4 = false, $curlSslVerifypeer = true) {
global $config, $g;
$this->_cacheFile = "{$g['conf_path']}/dyndns_{$dnsIf}{$dnsService}" . escapeshellarg($dnsHost) . "{$dnsID}.cache";
$this->_cacheFile_v6 = "{$g['conf_path']}/dyndns_{$dnsIf}{$dnsService}" . escapeshellarg($dnsHost) . "{$dnsID}_v6.cache";
$this->_debugFile = "{$g['varetc_path']}/dyndns_{$dnsIf}{$dnsService}" . escapeshellarg($dnsHost) . "{$dnsID}.debug";
@ -141,8 +145,9 @@
$this->_curlIpresolveV4 = $curlIpresolveV4;
$this->_curlSslVerifypeer = $curlSslVerifypeer;
$this->_dnsVerboseLog = $dnsVerboseLog;
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("DynDns: updatedns() starting");
}
$dyndnslck = lock("DDNS".$dnsID, LOCK_EX);
@ -167,14 +172,14 @@
if (!$dnsPass) $this->_error(4);
if (!$dnsHost) $this->_error(5);
}
switch ($dnsService) {
case 'he-net-v6':
case 'custom-v6':
$this->_useIPv6 = true;
break;
default:
$this->_useIPv6 = false;
case 'he-net-v6':
case 'custom-v6':
$this->_useIPv6 = true;
break;
default:
$this->_useIPv6 = false;
}
$this->_dnsService = strtolower($dnsService);
$this->_dnsUser = $dnsUser;
@ -191,84 +196,88 @@
$this->_dnsUpdateURL = $dnsUpdateURL;
$this->_dnsResultMatch = $dnsResultMatch;
$this->_dnsRequestIf = get_failover_interface($dnsRequestIf);
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("DynDNS ({$this->_dnsHost}): running get_failover_interface for {$dnsRequestIf}. found {$this->_dnsRequestIf}");
}
$this->_dnsRequestIfIP = get_interface_ip($dnsRequestIf);
$this->_dnsMaxCacheAgeDays = 25;
$this->_dnsDummyUpdateDone = false;
$this->_forceUpdateNeeded = $forceUpdate;
// Ensure that we were able to lookup the IP
if(!is_ipaddr($this->_dnsIP)) {
if (!is_ipaddr($this->_dnsIP)) {
log_error("DynDNS ({$this->_dnsHost}) There was an error trying to determine the public IP for interface - {$dnsIf}({$this->_if}). Probably interface is not a WAN interface.");
unlock($dyndnslck);
return;
}
$this->_debugID = rand(1000000, 9999999);
if ($forceUpdate == false && $this->_detectChange() == false) {
$this->_error(10);
} else {
switch ($this->_dnsService) {
case 'dnsomatic':
case 'dyndns':
case 'dyndns-static':
case 'dyndns-custom':
case 'dhs':
case 'noip':
case 'noip-free':
case 'easydns':
case 'hn':
case 'zoneedit':
case 'dyns':
case 'ods':
case 'freedns':
case 'loopia':
case 'staticcling':
case 'dnsexit':
case 'custom':
case 'custom-v6':
case 'opendns':
case 'namecheap':
case 'he-net':
case 'he-net-v6':
case 'selfhost':
case 'he-net-tunnelbroker':
case 'route53':
case 'cloudflare':
case 'eurodns':
case 'gratisdns':
case 'ovh-dynhost':
case 'citynetwork':
$this->_update();
if($this->_dnsDummyUpdateDone == true) {
// If a dummy update was needed, then sleep a while and do the update again to put the proper address back.
// Some providers (e.g. No-IP free accounts) need to have at least 1 address change every month.
// If the address has not changed recently, or the user did "Force Update", then the code does
// a dummy address change for providers like this.
sleep(10);
case 'glesys':
case 'dnsomatic':
case 'dyndns':
case 'dyndns-static':
case 'dyndns-custom':
case 'dhs':
case 'noip':
case 'noip-free':
case 'easydns':
case 'hn':
case 'zoneedit':
case 'dyns':
case 'ods':
case 'freedns':
case 'loopia':
case 'staticcling':
case 'dnsexit':
case 'custom':
case 'custom-v6':
case 'opendns':
case 'namecheap':
case 'he-net':
case 'he-net-v6':
case 'selfhost':
case 'he-net-tunnelbroker':
case 'route53':
case 'cloudflare':
case 'eurodns':
case 'gratisdns':
case 'ovh-dynhost':
case 'citynetwork':
case 'dnsimple':
$this->_update();
}
break;
default:
$this->_error(6);
break;
if ($this->_dnsDummyUpdateDone == true) {
// If a dummy update was needed, then sleep a while and do the update again to put the proper address back.
// Some providers (e.g. No-IP free accounts) need to have at least 1 address change every month.
// If the address has not changed recently, or the user did "Force Update", then the code does
// a dummy address change for providers like this.
sleep(10);
$this->_update();
}
break;
default:
$this->_error(6);
break;
}
}
unlock($dyndnslck);
}
/*
* Private Function (added 12 July 05) [beta]
* Send Update To Selected Service.
*/
function _update() {
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("DynDNS ({$this->_dnsHost}): DynDns _update() starting.");
}
if ($this->_dnsService != 'ods' and $this->_dnsService != 'route53 ') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
@ -279,20 +288,37 @@
}
switch ($this->_dnsService) {
case 'glesys':
$needsIP = TRUE;
if ($this->_dnsVerboseLog) {
log_error("DynDNS: ({$this->_dnsHost}) DNS update() starting.");
}
$server = 'https://api.glesys.com/domain/updaterecord/format/json';
curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass);
$post_data['recordid'] = $this->_dnsHost;
$post_data['data'] = $this->_dnsIP;
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
break;
case 'dyndns':
case 'dyndns-static':
case 'dyndns-custom':
$needsIP = FALSE;
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("DynDNS: ({$this->_dnsHost}) DNS update() starting.");
if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") $this->_dnsWildcard = "ON";
}
if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") {
$this->_dnsWildcard = "ON";
}
curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass);
$server = "https://members.dyndns.org/nic/update";
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, $server .$port . '?system=dyndns&hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP . '&wildcard='.$this->_dnsWildcard . '&mx=' . $this->_dnsMX . '&backmx=NO');
break;
case 'dhs':
@ -313,10 +339,12 @@
$post_data['submit'] = 'Update';
$server = "https://members.dhs.org/nic/hosts";
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
$port = ":" . $this->_dnsPort;
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, '{$server}{$port}');
curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
@ -326,13 +354,15 @@
$needsIP = TRUE;
$server = "https://dynupdate.no-ip.com/ducupdate.php";
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
if(($this->_dnsService == "noip-free") &&
($this->_forceUpdateNeeded == true) &&
($this->_dnsDummyUpdateDone == false)) {
}
if (($this->_dnsService == "noip-free") &&
($this->_forceUpdateNeeded == true) &&
($this->_dnsDummyUpdateDone == false)) {
// Update the IP to a dummy value to force No-IP free accounts to see a change.
$iptoset = "192.168.1.1";
$this->_dnsDummyUpdateDone = true;
@ -347,10 +377,12 @@
curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass);
$server = "https://members.easydns.com/dyn/dyndns.php";
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, $server . $port . '?hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP . '&wildcard=' . $this->_dnsWildcard . '&mx=' . $this->_dnsMX . '&backmx=' . $this->_dnsBackMX);
break;
case 'hn':
@ -358,10 +390,12 @@
curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass);
$server = "http://dup.hn.org/vanity/update";
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, $server . $port . '?ver=1&IP=' . $this->_dnsIP);
break;
case 'zoneedit':
@ -370,20 +404,24 @@
$server = "https://dynamic.zoneedit.com/auth/dynamic.html";
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, "{$server}{$port}?host=" .$this->_dnsHost);
break;
case 'dyns':
$needsIP = FALSE;
$server = "https://www.dyns.cx/postscript011.php";
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
$port = ":" . $this->_dnsPort;
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, $server . $port . '?username=' . urlencode($this->_dnsUser) . '&password=' . $this->_dnsPass . '&host=' . $this->_dnsHost);
break;
case 'ods':
@ -392,10 +430,12 @@
$misc_error = "";
$server = "ods.org";
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
$port = ":" . $this->_dnsPort;
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
$this->con['socket'] = fsockopen("{$server}{$port}", "7070", $misc_errno, $misc_error, 30);
/* Check that we have connected */
if (!$this->con['socket']) {
@ -407,7 +447,7 @@
$this->con['buffer']['all'] = trim(fgets($this->con['socket'], 4096));
$code = substr($this->con['buffer']['all'], 0, 3);
sleep(1);
switch($code) {
switch ($code) {
case 100:
fputs($this->con['socket'], "LOGIN ".$this->_dnsUser." ".$this->_dnsPass."\n");
break;
@ -443,25 +483,30 @@
curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass);
$server = "https://updates.opendns.com/nic/update?hostname=". $this->_dnsHost;
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, $server .$port);
break;
case 'staticcling':
$needsIP = FALSE;
curl_setopt($ch, CURLOPT_URL, 'https://www.staticcling.org/update.html?login='.$this->_dnsUser.'&pass='.$this->_dnsPass);
break;
break;
case 'dnsomatic':
/* Example syntax
/* Example syntax
https://username:password@updates.dnsomatic.com/nic/update?hostname=yourhostname&myip=ipaddress&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG
*/
$needsIP = FALSE;
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("DNS-O-Matic: DNS update() starting.");
if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") $this->_dnsWildcard = "ON";
}
if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") {
$this->_dnsWildcard = "ON";
}
/*
Reference: https://www.dnsomatic.com/wiki/api
DNS-O-Matic usernames are 3-25 characters.
@ -472,10 +517,12 @@
Encodes the given string according to RFC 3986.
*/
$server = "https://" . rawurlencode($this->_dnsUser) . ":" . rawurlencode($this->_dnsPass) . "@updates.dnsomatic.com/nic/update?hostname=";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, $server . $this->_dnsHost . '&myip=' . $this->_dnsIP . '&wildcard='.$this->_dnsWildcard . '&mx=' . $this->_dnsMX . '&backmx=NOCHG');
break;
case 'namecheap':
@ -483,8 +530,9 @@
https://dynamicdns.park-your-domain.com/update?host=[host_name]&domain=[domain.com]&password=[domain_password]&ip=[your_ip]
*/
$needsIP = FALSE;
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("Namecheap ({$this->_dnsHost}): DNS update() starting.");
}
$dparts = explode(".", trim($this->_dnsHost));
$domain_part_count = ($dparts[count($dparts)-1] == "uk") ? 3 : 2;
$domain_offset = count($dparts) - $domain_part_count;
@ -497,8 +545,9 @@
case 'he-net':
case 'he-net-v6':
$needsIP = FALSE;
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("HE.net ({$this->_dnsHost}): DNS update() starting.");
}
$server = "https://dyn.dns.he.net/nic/update?";
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
@ -506,30 +555,37 @@
break;
case 'he-net-tunnelbroker':
$needsIP = FALSE;
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("HE.net Tunnelbroker: DNS update() starting.");
}
$server = "https://ipv4.tunnelbroker.net/ipv4_end.php?";
curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser . ':' . $this->_dnsPass);
curl_setopt($ch, CURLOPT_URL, $server . 'tid=' . $this->_dnsHost);
break;
case 'selfhost':
$needsIP = FALSE;
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("SelfHost: DNS update() starting.");
if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") $this->_dnsWildcard = "ON";
}
if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") {
$this->_dnsWildcard = "ON";
}
curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass);
$server = "https://carol.selfhost.de/nic/update";
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, $server .$port . '?system=dyndns&hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP . '&wildcard='.$this->_dnsWildcard . '&mx=' . $this->_dnsMX . '&backmx=NO');
break;
case 'route53':
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("Route53 ({$this->_dnsHost}): DNS update() starting.");
}
/* Setting Variables */
$hostname = "{$this->_dnsHost}.";
$ZoneID = $this->_dnsZoneID;
@ -545,11 +601,11 @@
$r53 = new Route53($AccessKeyId, $SecretAccessKey);
/* Function to find old values of records in Route 53 */
if(!function_exists('Searchrecords')) {
if (!function_exists('Searchrecords')) {
function SearchRecords($records, $name) {
$result = array();
foreach($records as $record) {
if(strtolower($record['Name']) == strtolower($name)) {
foreach ($records as $record) {
if (strtolower($record['Name']) == strtolower($name)) {
$result [] = $record;
}
}
@ -560,7 +616,7 @@
$records = $r53->listResourceRecordSets("/hostedzone/$ZoneID");
/* Get IP for your hostname in Route 53 */
if(false !== ($a_result = SearchRecords($records['ResourceRecordSets'], "$hostname"))) {
if (false !== ($a_result = SearchRecords($records['ResourceRecordSets'], "$hostname"))) {
$OldTTL=$a_result[0][TTL];
$OldIP=$a_result[0][ResourceRecords][0];
} else {
@ -569,7 +625,7 @@
/* Check if we need to update DNS Record */
if ($OldIP !== $NewIP) {
if(!empty($OldIP)) {
if (!empty($OldIP)) {
/* Your Hostname already exists, deleting and creating it again */
$changes = array();
$changes[] = $r53->prepareChange(DELETE, $hostname, A, $OldTTL, $OldIP);
@ -585,22 +641,26 @@
break;
case 'custom':
case 'custom-v6':
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("Custom DDNS ({$this->_dnsHost}): DNS update() starting.");
}
if (strstr($this->dnsUpdateURL, "%IP%")) {$needsIP = TRUE;} else {$needsIP = FALSE;}
if ($this->_dnsUser != '') {
if ($this->_curlIpresolveV4)
if ($this->_curlIpresolveV4) {
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
if ($this->_curlSslVerifypeer)
}
if ($this->_curlSslVerifypeer) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
else
} else {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
}
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "{$this->_dnsUser}:{$this->_dnsPass}");
}
$server = str_replace("%IP%", $this->_dnsIP, $this->_dnsUpdateURL);
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("Sending request to: ".$server);
}
curl_setopt($ch, CURLOPT_URL, $server);
break;
case 'cloudflare':
@ -610,52 +670,76 @@
$URL = "https://{$dnsServer}/api.html?a=DIUP&email={$this->_dnsUser}&tkn={$this->_dnsPass}&ip={$this->_dnsIP}&hosts={$dnsHost}";
curl_setopt($ch, CURLOPT_URL, $URL);
break;
case 'eurodns':
case 'eurodns':
$needsIP = TRUE;
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("EuroDynDns ({$this->_dnsHost}) DNS update() starting.");
}
curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass);
$server = "https://eurodyndns.org/update/";
$server = "https://update.eurodyndns.org/update/";
$port = "";
if($this->_dnsPort)
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, $server .$port . '?hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP);
break;
case 'gratisdns':
$needsIP = FALSE;
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("GratisDNS.dk ({$this->_dnsHost}): DNS update() starting.");
}
$server = "https://ssl.gratisdns.dk/ddns.phtml";
list($hostname, $domain) = explode(".", $this->_dnsHost, 2);
curl_setopt($ch, CURLOPT_URL, $server . '?u=' . $this->_dnsUser . '&p=' . $this->_dnsPass . '&h=' . $this->_dnsHost . '&d=' . $domain);
break;
case 'ovh-dynhost':
$needsIP = FALSE;
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("OVH DynHOST: ({$this->_dnsHost}) DNS update() starting.");
}
if (isset($this->_dnsWildcard) && $this->_dnsWildcard != "OFF") $this->_dnsWildcard = "ON";
curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass);
$server = "https://www.ovh.com/nic/update";
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, $server .$port . '?system=dyndns&hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP . '&wildcard='.$this->_dnsWildcard . '&mx=' . $this->_dnsMX . '&backmx=NO');
break;
case 'citynetwork':
$needsIP = TRUE;
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("City Network: ({$this->_dnsHost}) DNS update() starting.");
}
curl_setopt($ch, CURLOPT_USERPWD, $this->_dnsUser.':'.$this->_dnsPass);
$server = 'https://dyndns.citynetwork.se/nic/update';
$port = "";
if($this->_dnsServer)
if ($this->_dnsServer) {
$server = $this->_dnsServer;
if($this->_dnsPort)
}
if ($this->_dnsPort) {
$port = ":" . $this->_dnsPort;
}
curl_setopt($ch, CURLOPT_URL, $server .$port . '?hostname=' . $this->_dnsHost . '&myip=' . $this->_dnsIP);
break;
case 'dnsimple':
/* Uses DNSimple's REST API
Requires username and Account API token passed in header
Piggybacks on Route 53's ZoneID field for DNSimple record ID
Data sent as JSON */
$needsIP = TRUE;
$server = 'https://api.dnsimple.com/v1/domains/';
$token = $this->_dnsUser . ':' . $this->_dnsPass;
$jsondata = '{"record":{"content":"' . $this->_dnsIP . '","ttl":"' . $this->_dnsTTL . '"}}';
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json','X-DNSimple-Token: ' . $token));
curl_setopt($ch, CURLOPT_URL, $server . $this->_dnsHost . '/records/' . $this->_dnsZoneID);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsondata);
break;
default:
break;
}
@ -683,6 +767,16 @@
return;
}
switch ($this->_dnsService) {
case 'glesys':
if (preg_match('/Record updated/i', $data)) {
$status = "GleSYS ({$this->_dnsHost}): (Success) IP Address Changed Successfully! (".$this->_dnsIP.")";
$successful_update = true;
} else {
$status = "GleSYS ({$this->_dnsHost}): (Unknown Response)";
log_error("GleSYS ({$this->_dnsHost}): PAYLOAD: {$data}");
$this->_debug($data);
}
break;
case 'dnsomatic':
if (preg_match('/badauth/i', $data)) {
$status = "DNS-O-Matic ({$this->_dnsHost}): The DNS-O-Matic username or password specified are incorrect. No updates will be distributed to services until this is resolved.";
@ -691,7 +785,7 @@
} else if (preg_match('/nohost/i', $data)) {
$status = "DNS-O-Matic ({$this->_dnsHost}): The hostname passed could not be matched to any services configured. The service field will be blank in the return code.";
} else if (preg_match('/numhost/i', $data)) {
$status = "DNS-O-Matic ({$this->_dnsHost}): You may update up to 20 hosts. numhost is returned if you try to update more than 20 or update a round-robin.";
$status = "DNS-O-Matic ({$this->_dnsHost}): You may update up to 20 hosts. numhost is returned if you try to update more than 20 or update a round-robin.";
} else if (preg_match('/abuse/i', $data)) {
$status = "DNS-O-Matic ({$this->_dnsHost}): The hostname is blocked for update abuse.";
} else if (preg_match('/good/i', $data)) {
@ -866,7 +960,7 @@
break;
case 'zoneedit':
if (preg_match('/799/i', $data)) {
$status = "phpDynDNS ({$this->_dnsHost}): (Error 799) Update Failed!";
$status = "phpDynDNS ({$this->_dnsHost}): (Error 799) Update Failed!";
} else if (preg_match('/700/i', $data)) {
$status = "phpDynDNS ({$this->_dnsHost}): (Error 700) Update Failed!";
} else if (preg_match('/200/i', $data)) {
@ -874,7 +968,7 @@
$successful_update = true;
} else if (preg_match('/201/i', $data)) {
$status = "phpDynDNS ({$this->_dnsHost}): (Success) IP Address Updated Successfully!";
$successful_update = true;
$successful_update = true;
} else {
$status = "phpDynDNS ({$this->_dnsHost}): (Unknown Response)";
log_error("phpDynDNS ({$this->_dnsHost}): PAYLOAD: {$data}");
@ -920,7 +1014,7 @@
$status = "phpDynDNS ({$this->_dnsHost}): (Unknown Response)";
log_error("phpDynDNS ({$this->_dnsHost}): PAYLOAD: {$data}");
$this->_debug($data);
}
}
break;
case 'dnsexit':
if (preg_match("/is the same/i", $data)) {
@ -1012,7 +1106,7 @@
$this->_debug($data);
}
break;
case 'he-net':
case 'he-net-v6':
if (preg_match("/badip/i", $data)) {
@ -1085,28 +1179,30 @@
$successful_update = false;
if ($this->_dnsResultMatch == "") {
$successful_update = true;
}else {
} else {
$this->_dnsResultMatch = str_replace("%IP%", $this->_dnsIP, $this->_dnsResultMatch);
$matches = preg_split("/(?<!\\\\)\\|/", $this->_dnsResultMatch);
foreach($matches as $match) {
foreach ($matches as $match) {
$match= str_replace("\\|", "|", $match);
if(strcmp($match, trim($data, "\t\n\r")) == 0)
if (strcmp($match, trim($data, "\t\n\r")) == 0) {
$successful_update = true;
}
}
unset ($matches);
}
if ($successful_update == true)
if ($successful_update == true) {
$status = "phpDynDNS: (Success) IP Address Updated Successfully!";
else
} else {
$status = "phpDynDNS: (Error) Result did not match.";
}
break;
case 'cloudflare':
// recieve multipe results
// receive multiple results
$data = explode("\n",$data);
$lines = count($data)-1;
// loop over the lines
for ($pos=0; ($successful_update || $pos == 0) && $pos < $lines; $pos++){
for ($pos=0; ($successful_update || $pos == 0) && $pos < $lines; $pos++) {
$resp = $data[$pos];
if (preg_match('/UAUTH/i', $resp)) {
$status = "DynDNS: The username specified is not authorized to update this hostname and domain.";
@ -1151,25 +1247,50 @@
break;
case 'gratisdns':
if (preg_match('/Forkerte værdier/i', $data)) {
$status = "phpDynDNS: (Error) Wrong values - Update could not be completed.";
$status = "phpDynDNS: (Error) Wrong values - Update could not be completed.";
} else if (preg_match('/Bruger login: Bruger eksistere ikke/i', $data)) {
$status = "phpDynDNS: (Error) Unknown username - User does not exist.";
$status = "phpDynDNS: (Error) Unknown username - User does not exist.";
} else if (preg_match('/Bruger login: 1Fejl i kodeord/i', $data)) {
$status = "phpDynDNS: (Error) Wrong password - Remember password is case sensitive.";
$status = "phpDynDNS: (Error) Wrong password - Remember password is case sensitive.";
} else if (preg_match('/Domæne kan IKKE administreres af bruger/i', $data)) {
$status = "phpDynDNS: (Error) User unable to administer the selected domain.";
$status = "phpDynDNS: (Error) User unable to administer the selected domain.";
} else if (preg_match('/OK/i', $data)) {
$status = "phpDynDNS: (Success) IP Address Updated Successfully!";
$successful_update = true;
$status = "phpDynDNS: (Success) IP Address Updated Successfully!";
$successful_update = true;
} else {
$status = "phpDynDNS: (Unknown Response)";
log_error("phpDynDNS: PAYLOAD: {$data}");
$this->_debug($data);
$status = "phpDynDNS: (Unknown Response)";
log_error("phpDynDNS: PAYLOAD: {$data}");
$this->_debug($data);
}
break;
case 'dnsimple':
/* Responds with HTTP 200 on success.
Responds with HTTP 4xx on error.
Returns JSON data as body */
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($data, 0, $header_size);
$body = substr($data, $header_size);
if (preg_match("/Status: 200\s/i", $header)) {
$status = "phpDynDNS ({$this->_dnsHost}): (Success) IP Address Updated Successfully!";
$successful_update = true;
} else if (preg_match("/Status: 4\d\d\s/i", $header)) {
$arrbody = json_decode($body, true);
$message = $arrbody['message'] . ".";
if (isset($arrbody['errors']['content'])) {
foreach ($arrbody['errors']['content'] as $key => $content) {
$message .= " " . $content . ".";
}
}
$status = "phpDynDNS ({$this->_dnsHost}): (Error) " . $message;
} else {
$status = "phpDynDNS ({$this->_dnsHost}): (Unknown Response)";
log_error("phpDynDNS ({$this->_dnsHost}): PAYLOAD: {$body}");
$this->_debug($body);
}
break;
}
if($successful_update == true) {
if ($successful_update == true) {
/* Write WAN IP to cache file */
$wan_ip = $this->_checkIP();
conf_mount_rw();
@ -1178,15 +1299,17 @@
notify_all_remote(sprintf(gettext("DynDNS updated IP Address on %s (%s) to %s"), convert_real_interface_to_friendly_descr($this->_if), $this->_if, $wan_ip));
log_error("phpDynDNS: updating cache file {$this->_cacheFile}: {$wan_ip}");
@file_put_contents($this->_cacheFile, "{$wan_ip}:{$currentTime}");
} else
} else {
@unlink($this->_cacheFile);
}
if ($this->_useIPv6 == true && $wan_ip > 0) {
$currentTime = time();
notify_all_remote(sprintf(gettext("DynDNS updated IPv6 Address on %s (%s) to %s"), convert_real_interface_to_friendly_descr($this->_if), $this->_if, $wan_ip));
log_error("phpDynDNS: updating cache file {$this->_cacheFile_v6}: {$wan_ip}");
@file_put_contents($this->_cacheFile_v6, "{$wan_ip}|{$currentTime}");
} else
} else {
@unlink($this->_cacheFile_v6);
}
conf_mount_ro();
}
$this->status = $status;
@ -1224,7 +1347,7 @@
break;
case 9:
$status = "Route 53: (Error) Invalid TTL";
break;
break;
case 10:
$error = "phpDynDNS ({$this->_dnsHost}): No change in my IP address and/or " . $this->_dnsMaxCacheAgeDays . " days has not passed. Not updating dynamic DNS entry.";
break;
@ -1247,9 +1370,10 @@
function _detectChange() {
global $debug;
if ($debug)
if ($debug) {
log_error("DynDns ({$this->_dnsHost}): _detectChange() starting.");
}
$currentTime = time();
$wan_ip = $this->_checkIP();
@ -1292,8 +1416,9 @@
$log_error .= "No Cached IP found.";
}
}
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error($log_error);
}
// Convert seconds = days * hr/day * min/hr * sec/min
$maxCacheAgeSecs = $this->_dnsMaxCacheAgeDays * 24 * 60 * 60;
@ -1325,7 +1450,7 @@
return true;
}
return false;
return false;
}
/*
@ -1337,8 +1462,9 @@
function _debug($data) {
global $g;
if (!$g['debug'])
if (!$g['debug']) {
return;
}
$string = date('m-d-y h:i:s').' - ('.$this->_debugID.') - ['.$this->_dnsService.'] - '.$data."\n";
conf_mount_rw();
$file = fopen($this->_debugFile, 'a');
@ -1349,25 +1475,29 @@
function _checkIP() {
global $debug;
if ($debug)
if ($debug) {
log_error("DynDns ({$this->_dnsHost}): _checkIP() starting.");
}
if ($this->_useIPv6 == true) {
$ip_address = find_interface_ipv6($this->_if);
if (!is_ipaddrv6($ip_address))
if (!is_ipaddrv6($ip_address)) {
return 0;
}
} else {
$ip_address = find_interface_ip($this->_if);
if (!is_ipaddr($ip_address))
if (!is_ipaddr($ip_address)) {
return 0;
}
}
if ($this->_useIPv6 == false && is_private_ip($ip_address)) {
$hosttocheck = "checkip.dyndns.org";
$try = 0;
while ($try < 3) {
$checkip = gethostbyname($hosttocheck);
if (is_ipaddr($checkip))
if (is_ipaddr($checkip)) {
break;
}
$try++;
}
if ($try >= 3) {
@ -1389,15 +1519,17 @@
preg_match('/Current IP Address: (.*)<\/body>/', $ip_result_decoded, $matches);
$ip_address = trim($matches[1]);
if (is_ipaddr($ip_address)) {
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("DynDns ({$this->_dnsHost}): {$ip_address} extracted from {$hosttocheck}");
}
} else {
log_error("DynDns ({$this->_dnsHost}): IP address could not be extracted from {$hosttocheck}");
return 0;
}
} else {
if ($this->_dnsVerboseLog)
if ($this->_dnsVerboseLog) {
log_error("DynDns ({$this->_dnsHost}): {$ip_address} extracted from local system.");
}
}
$this->_dnsIP = $ip_address;

View File

@ -43,30 +43,36 @@ function easyrule_find_rule_interface($int) {
/* Borrowed from firewall_rules.php */
$iflist = get_configured_interface_with_descr(false, true);
if ($config['pptpd']['mode'] == "server")
if ($config['pptpd']['mode'] == "server") {
$iflist['pptp'] = "PPTP VPN";
}
if ($config['pppoe']['mode'] == "server")
if ($config['pppoe']['mode'] == "server") {
$iflist['pppoe'] = "PPPoE Server";
}
if ($config['l2tp']['mode'] == "server")
$iflist['l2tp'] = "L2TP VPN";
if ($config['l2tp']['mode'] == "server") {
$iflist['l2tp'] = "L2TP VPN";
}
/* add ipsec interfaces */
if (isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable'])){
$iflist["enc0"] = "IPSEC";
}
if (isset($iflist[$int]))
if (isset($iflist[$int])) {
return $int;
foreach ($iflist as $if => $ifd) {
if (strtolower($int) == strtolower($ifd))
return $if;
}
if (substr($int, 0, 4) == "ovpn")
foreach ($iflist as $if => $ifd) {
if (strtolower($int) == strtolower($ifd)) {
return $if;
}
}
if (substr($int, 0, 4) == "ovpn") {
return "openvpn";
}
return false;
}
@ -80,11 +86,13 @@ function easyrule_block_rule_exists($int = 'wan', $ipproto = "inet") {
/* Search through the rules for one referencing our alias */
foreach ($config['filter']['rule'] as $rule) {
if (!is_array($rule) || !is_array($rule['source']))
if (!is_array($rule) || !is_array($rule['source'])) {
continue;
}
$checkproto = isset($rule['ipprotocol']) ? $rule['ipprotocol'] : "inet";
if ($rule['source']['address'] == $blockaliasname . strtoupper($int) && ($rule['interface'] == $int) && ($checkproto == $ipproto))
if ($rule['source']['address'] == $blockaliasname . strtoupper($int) && ($rule['interface'] == $int) && ($checkproto == $ipproto)) {
return true;
}
}
return false;
}
@ -93,12 +101,14 @@ function easyrule_block_rule_create($int = 'wan', $ipproto = "inet") {
global $blockaliasname, $config;
/* If the alias doesn't exist, exit.
* Can't create an empty alias, and we don't know a host */
if (easyrule_block_alias_getid($int) === false)
if (easyrule_block_alias_getid($int) === false) {
return false;
}
/* If the rule already exists, no need to do it again */
if (easyrule_block_rule_exists($int, $ipproto))
if (easyrule_block_rule_exists($int, $ipproto)) {
return true;
}
/* No rules, start a new array */
if (!is_array($config['filter']['rule'])) {
@ -125,13 +135,16 @@ function easyrule_block_rule_create($int = 'wan', $ipproto = "inet") {
function easyrule_block_alias_getid($int = 'wan') {
global $blockaliasname, $config;
if (!is_array($config['aliases']))
if (!is_array($config['aliases'])) {
return false;
}
/* Hunt down an alias with the name we want, return its id */
foreach ($config['aliases']['alias'] as $aliasid => $alias)
if ($alias['name'] == $blockaliasname . strtoupper($int))
foreach ($config['aliases']['alias'] as $aliasid => $alias) {
if ($alias['name'] == $blockaliasname . strtoupper($int)) {
return $aliasid;
}
}
return false;
}
@ -140,19 +153,22 @@ function easyrule_block_alias_add($host, $int = 'wan') {
global $blockaliasname, $config;
/* If the host isn't a valid IP address, bail */
$host = trim($host, "[]");
if (!is_ipaddr($host) && !is_subnet($host))
if (!is_ipaddr($host) && !is_subnet($host)) {
return false;
}
/* If there are no aliases, start an array */
if (!is_array($config['aliases']['alias']))
if (!is_array($config['aliases']['alias'])) {
$config['aliases']['alias'] = array();
}
$a_aliases = &$config['aliases']['alias'];
/* Try to get the ID if the alias already exists */
$id = easyrule_block_alias_getid($int);
if ($id === false)
if ($id === false) {
unset($id);
}
$alias = array();
@ -168,8 +184,9 @@ function easyrule_block_alias_add($host, $int = 'wan') {
if (isset($id) && $a_aliases[$id]) {
/* Make sure this IP isn't already in the list. */
if (in_array($host.'/'.$mask, explode(" ", $a_aliases[$id]['address'])))
if (in_array($host.'/'.$mask, explode(" ", $a_aliases[$id]['address']))) {
return true;
}
/* Since the alias already exists, just add to it. */
$alias['name'] = $a_aliases[$id]['name'];
$alias['type'] = $a_aliases[$id]['type'];
@ -179,8 +196,8 @@ function easyrule_block_alias_add($host, $int = 'wan') {
$alias['detail'] = $a_aliases[$id]['detail'] . gettext('Entry added') . ' ' . date('r') . '||';
} else {
/* Create a new alias with all the proper information */
$alias['name'] = $blockaliasname . strtoupper($int);
$alias['type'] = 'network';
$alias['name'] = $blockaliasname . strtoupper($int);
$alias['type'] = 'network';
$alias['descr'] = gettext("Hosts blocked from Firewall Log view");
$alias['address'] = $host . '/' . $mask;
@ -188,10 +205,11 @@ function easyrule_block_alias_add($host, $int = 'wan') {
}
/* Replace the old alias if needed, otherwise tack it on the end */
if (isset($id) && $a_aliases[$id])
if (isset($id) && $a_aliases[$id]) {
$a_aliases[$id] = $alias;
else
} else {
$a_aliases[] = $alias;
}
// Sort list
$a_aliases = msort($a_aliases, "name");
@ -203,8 +221,9 @@ function easyrule_block_host_add($host, $int = 'wan', $ipproto = "inet") {
global $retval;
/* Bail if the supplied host is not a valid IP address */
$host = trim($host, "[]");
if (!is_ipaddr($host) && !is_subnet($host))
if (!is_ipaddr($host) && !is_subnet($host)) {
return false;
}
/* Flag whether or not we need to reload the filter */
$dirty = false;
@ -263,18 +282,21 @@ function easyrule_pass_rule_add($int, $proto, $srchost, $dsthost, $dstport, $ipp
$filterent['ipprotocol'] = $ipproto;
$filterent['descr'] = gettext("Easy Rule: Passed from Firewall Log View");
if ($proto != "any")
if ($proto != "any") {
$filterent['protocol'] = $proto;
else
} else {
unset($filterent['protocol']);
}
/* Default to only allow echo requests, since that's what most people want and
* it should be a safe choice. */
if ($proto == "icmp")
if ($proto == "icmp") {
$filterent['icmptype'] = 'echoreq';
}
if ((strtolower($proto) == "icmp6") || (strtolower($proto) == "icmpv6"))
if ((strtolower($proto) == "icmp6") || (strtolower($proto) == "icmpv6")) {
$filterent['protocol'] = "icmp";
}
if (is_subnet($srchost)) {
list($srchost, $srcmask) = explode("/", $srchost);

File diff suppressed because it is too large Load Diff

View File

@ -45,33 +45,36 @@ function conv_log_filter($logfile, $nentries, $tail = 50, $filtertext = "", $fil
global $config, $g;
/* Make sure this is a number before using it in a system call */
if (!(is_numeric($tail)))
if (!(is_numeric($tail))) {
return;
}
if ($filtertext)
if ($filtertext) {
$tail = 5000;
}
/* Always do a reverse tail, to be sure we're grabbing the 'end' of the log. */
$logarr = "";
if(isset($config['system']['usefifolog']))
if (isset($config['system']['usefifolog'])) {
exec("/usr/sbin/fifolog_reader " . escapeshellarg($logfile) . " | /usr/bin/grep 'filterlog:' | /usr/bin/tail -r -n {$tail}", $logarr);
else
} else {
exec("/usr/local/sbin/clog " . escapeshellarg($logfile) . " | grep -v \"CLOG\" | grep -v \"\033\" | /usr/bin/grep 'filterlog:' | /usr/bin/tail -r -n {$tail}", $logarr);
}
$filterlog = array();
$counter = 0;
$filterinterface = strtoupper($filterinterface);
foreach ($logarr as $logent) {
if($counter >= $nentries)
if ($counter >= $nentries) {
break;
}
$flent = parse_filter_line($logent);
if (!$filterinterface || ($filterinterface == $flent['interface']))
{
if ( ( ($flent != "") && (!is_array($filtertext)) && (match_filter_line ($flent, $filtertext))) ||
( ($flent != "") && ( is_array($filtertext)) && (match_filter_field($flent, $filtertext)) ) ) {
if (!$filterinterface || ($filterinterface == $flent['interface'])) {
if ((($flent != "") && (!is_array($filtertext)) && (match_filter_line ($flent, $filtertext))) ||
(($flent != "") && ( is_array($filtertext)) && (match_filter_field($flent, $filtertext)))) {
$counter++;
$filterlog[] = $flent;
}
@ -88,34 +91,40 @@ function escape_filter_regex($filtertext) {
}
function match_filter_line($flent, $filtertext = "") {
if (!$filtertext)
if (!$filtertext) {
return true;
}
$filtertext = escape_filter_regex(str_replace(' ', '\s+', $filtertext));
return @preg_match("/{$filtertext}/i", implode(" ", array_values($flent)));
}
function match_filter_field($flent, $fields) {
foreach ($fields as $key => $field) {
if ($field == "All")
if ($field == "All") {
continue;
}
if ((strpos($field, '!') === 0)) {
$field = substr($field, 1);
if (strtolower($key) == 'act') {
if (in_arrayi($flent[$key], explode(" ", $field)))
if (in_arrayi($flent[$key], explode(" ", $field))) {
return false;
}
} else {
$field_regex = escape_filter_regex($field);
if (@preg_match("/{$field_regex}/i", $flent[$key]))
if (@preg_match("/{$field_regex}/i", $flent[$key])) {
return false;
}
}
} else {
if (strtolower($key) == 'act') {
if (!in_arrayi($flent[$key], explode(" ", $field)))
if (!in_arrayi($flent[$key], explode(" ", $field))) {
return false;
}
} else {
$field_regex = escape_filter_regex($field);
if (!@preg_match("/{$field_regex}/i", $flent[$key]))
if (!@preg_match("/{$field_regex}/i", $flent[$key])) {
return false;
}
}
}
}
@ -133,8 +142,9 @@ function parse_filter_line($line) {
$flent = array();
$log_split = "";
if (!preg_match("/(.*)\s(.*)\sfilterlog:\s(.*)$/", $line, $log_split))
if (!preg_match("/(.*)\s(.*)\sfilterlog:\s(.*)$/", $line, $log_split)) {
return "";
}
list($all, $flent['time'], $host, $rule) = $log_split;
@ -197,47 +207,50 @@ function parse_filter_line($line) {
$flent['icmp_type'] = $rule_data[$field++];
switch ($flent['icmp_type']) {
case "request":
case "reply":
$flent['icmp_id'] = $rule_data[$field++];
$flent['icmp_seq'] = $rule_data[$field++];
break;
case "unreachproto":
$flent['icmp_dstip'] = $rule_data[$field++];
$flent['icmp_protoid'] = $rule_data[$field++];
break;
case "unreachport":
$flent['icmp_dstip'] = $rule_data[$field++];
$flent['icmp_protoid'] = $rule_data[$field++];
$flent['icmp_port'] = $rule_data[$field++];
break;
case "unreach":
case "timexceed":
case "paramprob":
case "redirect":
case "maskreply":
$flent['icmp_descr'] = $rule_data[$field++];
break;
case "needfrag":
$flent['icmp_dstip'] = $rule_data[$field++];
$flent['icmp_mtu'] = $rule_data[$field++];
break;
case "tstamp":
$flent['icmp_id'] = $rule_data[$field++];
$flent['icmp_seq'] = $rule_data[$field++];
break;
case "tstampreply":
$flent['icmp_id'] = $rule_data[$field++];
$flent['icmp_seq'] = $rule_data[$field++];
$flent['icmp_otime'] = $rule_data[$field++];
$flent['icmp_rtime'] = $rule_data[$field++];
$flent['icmp_ttime'] = $rule_data[$field++];
break;
default :
$flent['icmp_descr'] = $rule_data[$field++];
break;
case "request":
case "reply":
$flent['icmp_id'] = $rule_data[$field++];
$flent['icmp_seq'] = $rule_data[$field++];
break;
case "unreachproto":
$flent['icmp_dstip'] = $rule_data[$field++];
$flent['icmp_protoid'] = $rule_data[$field++];
break;
case "unreachport":
$flent['icmp_dstip'] = $rule_data[$field++];
$flent['icmp_protoid'] = $rule_data[$field++];
$flent['icmp_port'] = $rule_data[$field++];
break;
case "unreach":
case "timexceed":
case "paramprob":
case "redirect":
case "maskreply":
$flent['icmp_descr'] = $rule_data[$field++];
break;
case "needfrag":
$flent['icmp_dstip'] = $rule_data[$field++];
$flent['icmp_mtu'] = $rule_data[$field++];
break;
case "tstamp":
$flent['icmp_id'] = $rule_data[$field++];
$flent['icmp_seq'] = $rule_data[$field++];
break;
case "tstampreply":
$flent['icmp_id'] = $rule_data[$field++];
$flent['icmp_seq'] = $rule_data[$field++];
$flent['icmp_otime'] = $rule_data[$field++];
$flent['icmp_rtime'] = $rule_data[$field++];
$flent['icmp_ttime'] = $rule_data[$field++];
break;
default :
$flent['icmp_descr'] = $rule_data[$field++];
break;
}
} else if ($flent['protoid'] == '2') { // IGMP
$flent['src'] = $flent['srcip'];
$flent['dst'] = $flent['dstip'];
} else if ($flent['protoid'] == '112') { // CARP
$flent['type'] = $rule_data[$field++];
$flent['ttl'] = $rule_data[$field++];
@ -247,8 +260,9 @@ function parse_filter_line($line) {
$flent['advbase'] = $rule_data[$field++];
}
} else {
if($g['debug'])
if ($g['debug']) {
log_error(sprintf(gettext("There was a error parsing rule number: %s. Please report to mailing list or forum."), $flent['rulenum']));
}
return "";
}
@ -256,7 +270,7 @@ function parse_filter_line($line) {
if (!((trim($flent['src']) == "") || (trim($flent['dst']) == "") || (trim($flent['time']) == ""))) {
return $flent;
} else {
if($g['debug']) {
if ($g['debug']) {
log_error(sprintf(gettext("There was a error parsing rule: %s. Please report to mailing list or forum."), $errline));
}
return "";
@ -264,8 +278,9 @@ function parse_filter_line($line) {
}
function get_port_with_service($port, $proto) {
if (!$port)
if (!$port) {
return '';
}
$service = getservbyport($port, $proto);
$portstr = "";
@ -281,27 +296,31 @@ function find_rule_by_number($rulenum, $trackernum, $type="block") {
global $g;
/* Passing arbitrary input to grep could be a Very Bad Thing(tm) */
if (!is_numeric($rulenum) || !is_numeric($trackernum) || !in_array($type, array('pass', 'block', 'match', 'rdr')))
if (!is_numeric($rulenum) || !is_numeric($trackernum) || !in_array($type, array('pass', 'block', 'match', 'rdr'))) {
return;
}
if ($trackernum == "0")
if ($trackernum == "0") {
$lookup_pattern = "^@{$rulenum}\([0-9]+\)[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]]";
else
} else {
$lookup_pattern = "^@[0-9]+\({$trackernum}\)[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]]";
}
/* At the moment, miniupnpd is the only thing I know of that
generates logging rdr rules */
unset($buffer);
if ($type == "rdr")
if ($type == "rdr") {
$_gb = exec("/sbin/pfctl -vvPsn -a \"miniupnpd\" | /usr/bin/egrep " . escapeshellarg("^@{$rulenum}"), $buffer);
else {
if (file_exists("{$g['tmp_path']}/rules.debug"))
} else {
if (file_exists("{$g['tmp_path']}/rules.debug")) {
$_gb = exec("/sbin/pfctl -vvPnf {$g['tmp_path']}/rules.debug 2>/dev/null | /usr/bin/egrep " . escapeshellarg($lookup_pattern), $buffer);
else
} else {
$_gb = exec("/sbin/pfctl -vvPsr | /usr/bin/egrep " . escapeshellarg($lookup_pattern), $buffer);
}
}
if (is_array($buffer))
if (is_array($buffer)) {
return $buffer[0];
}
return "";
}
@ -322,10 +341,11 @@ function buffer_rules_load() {
}
}
unset($buffer, $_gb);
if (file_exists("{$g['tmp_path']}/rules.debug"))
if (file_exists("{$g['tmp_path']}/rules.debug")) {
$_gb = exec("/sbin/pfctl -vvPnf {$g['tmp_path']}/rules.debug 2>/dev/null | /usr/bin/egrep '^@[0-9]+\([0-9]+\)[[:space:]].*[[:space:]]log[[:space:]]' | /usr/bin/egrep -v '^@[0-9]+\([0-9]+\)[[:space:]](nat|rdr|binat|no|scrub)'", $buffer);
else
} else {
$_gb = exec("/sbin/pfctl -vvPsr | /usr/bin/egrep '^@[0-9]+\([0-9]+\)[[:space:]].*[[:space:]]log[[:space:]]'", $buffer);
}
if (is_array($buffer)) {
foreach ($buffer as $line) {
@ -333,10 +353,11 @@ function buffer_rules_load() {
# pfctl rule number output with tracker number: @dd(dddddddddd)
$matches = array();
if (preg_match('/\@(?P<rulenum>\d+)\((?<trackernum>\d+)\)/', $key, $matches) == 1) {
if ($matches['trackernum'] > 0)
if ($matches['trackernum'] > 0) {
$key = $matches['trackernum'];
else
} else {
$key = "@{$matches['rulenum']}";
}
}
$buffer_rules_normal[$key] = $value;
}
@ -349,13 +370,14 @@ function buffer_rules_clear() {
unset($GLOBALS['buffer_rules_rdr']);
}
function find_rule_by_number_buffer($rulenum, $trackernum, $type){
function find_rule_by_number_buffer($rulenum, $trackernum, $type) {
global $g, $buffer_rules_rdr, $buffer_rules_normal;
if ($trackernum == "0")
if ($trackernum == "0") {
$lookup_key = "@{$rulenum}";
else
} else {
$lookup_key = $trackernum;
}
if ($type == "rdr") {
$ruleString = $buffer_rules_rdr[$lookup_key];
@ -371,23 +393,26 @@ function find_rule_by_number_buffer($rulenum, $trackernum, $type){
function find_action_image($action) {
global $g;
if ((strstr(strtolower($action), "p")) || (strtolower($action) == "rdr"))
if ((strstr(strtolower($action), "p")) || (strtolower($action) == "rdr")) {
return "/themes/{$g['theme']}/images/icons/icon_pass.gif";
else if(strstr(strtolower($action), "r"))
} else if (strstr(strtolower($action), "r")) {
return "/themes/{$g['theme']}/images/icons/icon_reject.gif";
else
} else {
return "/themes/{$g['theme']}/images/icons/icon_block.gif";
}
}
/* AJAX specific handlers */
function handle_ajax($nentries, $tail = 50) {
global $config;
if($_GET['lastsawtime'] or $_POST['lastsawtime']) {
if ($_GET['lastsawtime'] or $_POST['lastsawtime']) {
global $filter_logfile,$filterent;
if($_GET['lastsawtime'])
if ($_GET['lastsawtime']) {
$lastsawtime = $_GET['lastsawtime'];
if($_POST['lastsawtime'])
}
if ($_POST['lastsawtime']) {
$lastsawtime = $_POST['lastsawtime'];
}
/* compare lastsawrule's time stamp to filter logs.
* afterwards return the newer records so that client
* can update AJAX interface screen.
@ -396,12 +421,13 @@ function handle_ajax($nentries, $tail = 50) {
$filterlog = conv_log_filter($filter_logfile, $nentries, $tail);
/* We need this to always be in forward order for the AJAX update to work properly */
$filterlog = isset($config['syslog']['reverse']) ? array_reverse($filterlog) : $filterlog;
foreach($filterlog as $log_row) {
foreach ($filterlog as $log_row) {
$row_time = strtotime($log_row['time']);
$img = "<img border='0' src='" . find_action_image($log_row['act']) . "' alt={$log_row['act']} title={$log_row['act']} />";
if($row_time > $lastsawtime) {
if ($log_row['proto'] == "TCP")
if ($row_time > $lastsawtime) {
if ($log_row['proto'] == "TCP") {
$log_row['proto'] .= ":{$log_row['tcpflags']}";
}
$img = "<a href=\"#\" onClick=\"javascript:getURL('diag_logs_filter.php?getrulenum={$log_row['rulenum']},{$log_row['rulenum']}', outputrule);\">{$img}</a>";
$new_rules .= "{$img}||{$log_row['time']}||{$log_row['interface']}||{$log_row['srcip']}||{$log_row['srcport']}||{$log_row['dstip']}||{$log_row['dstport']}||{$log_row['proto']}||{$log_row['version']}||" . time() . "||\n";

View File

@ -1,47 +1,47 @@
<?php
/* $Id$ */
/*
functions.inc
Copyright (C) 2004-2006 Scott Ullrich
All rights reserved.
functions.inc
Copyright (C) 2004-2006 Scott Ullrich
All rights reserved.
originally part of m0n0wall (http://m0n0.ch/wall)
Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
All rights reserved.
originally part of m0n0wall (http://m0n0.ch/wall)
Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
pfSense_MODULE: utils
*/
/* BEGIN compatibility goo with HEAD */
if(!function_exists("gettext")) {
if (!function_exists("gettext")) {
function gettext($text) {
return $text;
}
}
if(!function_exists("pfSenseHeader")) {
if (!function_exists("pfSenseHeader")) {
/****f* pfsense-utils/pfSenseHeader
* NAME
* pfSenseHeader
@ -51,40 +51,101 @@ if(!function_exists("pfSenseHeader")) {
* Javascript header change or browser Location:
******/
function pfSenseHeader($text) {
global $_SERVER;
if (isAjax()) {
if ($_SERVER['HTTPS'] == "on")
$protocol = "https";
else
$protocol = "http";
global $_SERVER;
if (isAjax()) {
if ($_SERVER['HTTPS'] == "on") {
$protocol = "https";
} else {
$protocol = "http";
}
$port = ":{$_SERVER['SERVER_PORT']}";
if ($_SERVER['SERVER_PORT'] == "80" && $protocol == "http")
$port = "";
if ($_SERVER['SERVER_PORT'] == "443" && $protocol == "https")
$port = "";
$complete_url = "{$protocol}://{$_SERVER['SERVER_NAME']}{$port}/{$text}";
echo "\ndocument.location.href = '{$complete_url}';\n";
} else {
header("Location: $text");
}
$port = ":{$_SERVER['SERVER_PORT']}";
if ($_SERVER['SERVER_PORT'] == "80" && $protocol == "http") {
$port = "";
}
if ($_SERVER['SERVER_PORT'] == "443" && $protocol == "https") {
$port = "";
}
$complete_url = "{$protocol}://{$_SERVER['SERVER_NAME']}{$port}/{$text}";
echo "\ndocument.location.href = '{$complete_url}';\n";
} else {
header("Location: $text");
}
}
}
/* END compatibility goo with HEAD */
if(!function_exists("dom_title")) {
function dom_title($title_msg,$width=NULL){
/*fetch menu notices function*/
if (!function_exists("get_menu_messages")) {
function get_menu_messages() {
global $g,$config;
if (are_notices_pending()) {
$notices = get_notices();
$requests=array();
## Get Query Arguments from URL ###
foreach ($_REQUEST as $key => $value) {
if ($key != "PHPSESSID") {
$requests[] = $key.'='.$value;
}
}
if (is_array($requests)) {
$request_string = implode("&", $requests);
}
if (is_array($notices)) {
$notice_msgs = "<table colspan=\'6\' id=\'notice_table\'>";
$alert_style="style=\'color:#ffffff; filter:Glow(color=#ff0000, strength=12);\' ";
$notice = "<a href=\'#\' onclick=notice_action(\'acknowledge\',\'all\');domTT_close(this); {$alert_style}>".gettext("Acknowledge All Notices")."</a>";
$alert_link="title=\'".gettext("Click to Acknowledge")."\' {$alert_style}";
$domtt_width=500;
foreach ($notices as $key => $value) {
$date = date("m-d-y H:i:s", $key);
$noticemsg = ($value['notice'] != "" ? $value['notice'] : $value['id']);
$noticemsg = preg_replace("/(\"|\'|\n|<.?\w+>)/i","",$noticemsg);
if ((strlen($noticemsg)* 8) > $domtt_width) {
$domtt_width=(strlen($noticemsg) *8);
}
if ((strlen($noticemsg)* 8) > 900) {
$domtt_width= 900;
}
$alert_action ="onclick=notice_action(\'acknowledge\',\'{$key}\');domTT_close(this);jQuery(this).parent().parent().remove();";
$notice_msgs .= "<tr><td valign=\'top\' width=\'120\'><a href=\'#\' {$alert_link} {$alert_action}>{$date}</a></td><td valign=\'top\'><a href=\'#\' {$alert_link} {$alert_action}>[ ".htmlspecialchars($noticemsg)."]</a></td></tr>";
}
$notice_msgs .="</table>";
$domtt= "onclick=\"domTT_activate(this, event, 'caption', '{$notice}','content', '<br />{$notice_msgs}', 'trail', false, 'delay', 0, 'fade', 'both', 'fadeMax', 93, 'styleClass', 'niceTitle','width','{$domtt_width}','y',5,'type', 'sticky');\"";
$menu_messages="<div id='alerts'>\n";
if (count($notices)==1) {
$msg= sprintf("%1$02d",count($notices))." ".gettext("unread notice");
} else {
$msg= sprintf("%1$02d",count($notices))." ".gettext("unread notices");
}
$menu_messages.="<div id='marquee-text' style='z-index:1001;'><a href='#' {$domtt}><b> .:. {$msg} .:. </b></a></div>\n";
$menu_messages.="</div>\n";
}
} else {
$menu_messages='<div id="hostname">';
$menu_messages.=$config['system']['hostname'] . "." . $config['system']['domain'];
$menu_messages.='</div>';
}
return ($menu_messages);
}
}
if (!function_exists("dom_title")) {
function dom_title($title_msg,$width=NULL) {
$width=preg_replace("/\D+/","",$width);
if (!empty($width)){
if (!empty($width)) {
$width=",'width',$width";
}
if (!empty($title_msg)){
}
if (!empty($title_msg)) {
$title_msg=preg_replace("/\s+/"," ",$title_msg);
$title_msg=preg_replace("/'/","\'",$title_msg);
$title_msg=preg_replace("/'/","\'",$title_msg);
return "onmouseout=\"this.style.color = ''; domTT_mouseout(this, event);\" onmouseover=\"domTT_activate(this, event, 'content', '{$title_msg}', 'trail', true, 'delay', 250, 'fade', 'both', 'fadeMax', 93, 'styleClass', 'niceTitle' $width);\"";
}
}
}
}
/* include all configuration functions */
require_once("interfaces.inc");
require_once("gwlb.inc");

View File

@ -1,34 +1,34 @@
<?php
/* $Id$ */
/*
globals.inc
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004-2010 Scott Ullrich
globals.inc
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004-2010 Scott Ullrich
Originally Part of m0n0wall
Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
All rights reserved.
Originally Part of m0n0wall
Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
pfSense_MODULE: utils
@ -73,7 +73,7 @@ $g = array(
"disablecrashreporter" => false,
"crashreporterurl" => "https://crashreporter.pfsense.org/crash_reporter.php",
"debug" => false,
"latest_config" => "11.6",
"latest_config" => "11.8",
"nopkg_platforms" => array("cdrom"),
"minimum_ram_warning" => "101",
"minimum_ram_warning_text" => "128 MB",
@ -96,17 +96,24 @@ $iptos = array("lowdelay", "throughput", "reliability");
/* TCP flags */
$tcpflags = array("syn", "ack", "fin", "rst", "psh", "urg", "ece", "cwr");
if(file_exists("/etc/platform")) {
if (file_exists("/etc/platform")) {
$arch = php_uname("m");
/* Do not remove this, it is not needed for the snapshots URL but is needed later for the -RELEASE/stable URLs */
//$arch = ($arch == "i386") ? "" : '/' . $arch;
$current_version = trim(file_get_contents("{$g['etc_path']}/version"));
/* Full installs and NanoBSD use the same update directory and manifest in 2.x */
$g['update_url']="https://snapshots.pfsense.org/FreeBSD_releng/10.1/{$arch}/pfSense_HEAD/.updaters/";
$g['update_manifest']="https://updates.pfSense.org/manifest";
if (strstr($current_version, "-RELEASE")) {
/* This is only necessary for RELEASE */
$arch = ($arch == "i386") ? "" : '/' . $arch;
/* Full installs and NanoBSD use the same update directory and manifest in 2.x */
$g['update_url']="https://updates.pfsense.org/_updaters{$arch}";
$g['update_manifest']="https://updates.pfsense.org/manifest";
} else {
/* Full installs and NanoBSD use the same update directory and manifest in 2.x */
$g['update_url']="https://snapshots.pfsense.org/FreeBSD_releng/10.1/{$arch}/pfSense_HEAD/.updaters/";
$g['update_manifest']="https://updates.pfSense.org/manifest";
}
$g['platform'] = trim(file_get_contents("/etc/platform"));
if($g['platform'] == "nanobsd") {
if ($g['platform'] == "nanobsd") {
$g['firmware_update_text']="pfSense-*.img.gz";
$g['hidedownloadbackup'] = true;
$g['hidebackupbeforeupgrade'] = true;
@ -158,25 +165,31 @@ $sysctls = array("net.inet.ip.portrange.first" => "1024",
"net.enc.out.ipsec_bpf_mask" => "0x0001",
"net.enc.out.ipsec_filter_mask" => "0x0001",
"net.enc.in.ipsec_bpf_mask" => "0x0002",
"net.enc.in.ipsec_filter_mask" => "0x0002"
"net.enc.in.ipsec_filter_mask" => "0x0002",
"net.inet.carp.senderr_demotion_factor" => 0, /* Do not demote CARP for interface send errors */
"net.pfsync.carp_demotion_factor" => 0 /* Do not demote CARP for pfsync errors */
);
/* Include override values for the above if needed. If the file doesn't exist, don't try to load it. */
if (file_exists("/etc/inc/globals_override.inc"))
if (file_exists("/etc/inc/globals_override.inc")) {
@include("globals_override.inc");
}
function platform_booting($on_console = false) {
global $g;
if ($g['booting'] || file_exists("{$g['varrun_path']}/booting"))
if ($on_console == false || php_sapi_name() != 'fpm-fcgi')
if ($g['booting'] || file_exists("{$g['varrun_path']}/booting")) {
if ($on_console == false || php_sapi_name() != 'fpm-fcgi') {
return true;
}
}
return false;
}
if (file_exists("{$g['cf_conf_path']}/enableserial_force"))
if (file_exists("{$g['cf_conf_path']}/enableserial_force")) {
$g['enableserial_force'] = true;
}
$config_parsed = false;

View File

@ -46,8 +46,9 @@ function gmirror_get_status() {
$currentmirror = basename($all[0]);
$mirrors[$currentmirror]['name'] = basename($all[0]);
$mirrors[$currentmirror]['status'] = $all[1];
if (!is_array($mirrors[$currentmirror]['components']))
if (!is_array($mirrors[$currentmirror]['components'])) {
$mirrors[$currentmirror]['components'] = array();
}
$mirrors[$currentmirror]['components'][] = $all[2];
}
}
@ -119,8 +120,9 @@ function gmirror_get_unused_consumers() {
$all_consumers = array();
foreach ($consumerlist as $cl) {
$parts = explode(" ", $cl);
foreach ($parts as $part)
foreach ($parts as $part) {
$all_consumers[] = $part;
}
}
foreach ($disklist as $d) {
if (!is_consumer_used($d) && !in_array($d, $all_consumers)) {
@ -140,8 +142,9 @@ function gmirror_get_mirrors() {
/* List all consumers for a given mirror */
function gmirror_get_consumers_in_mirror($mirror) {
if (!is_valid_mirror($mirror))
if (!is_valid_mirror($mirror)) {
return array();
}
$consumers = array();
exec("/sbin/gmirror status -s " . escapeshellarg($mirror) . " | /usr/bin/awk '{print $3;}'", $consumers);
@ -150,8 +153,9 @@ function gmirror_get_consumers_in_mirror($mirror) {
/* Test if a given consumer is a member of an existing mirror */
function is_consumer_in_mirror($consumer, $mirror) {
if (!is_valid_consumer($consumer) || !is_valid_mirror($mirror))
if (!is_valid_consumer($consumer) || !is_valid_mirror($mirror)) {
return false;
}
$mirrorconsumers = gmirror_get_consumers_in_mirror($mirror);
return in_array(basename($consumer), $mirrorconsumers);
@ -175,8 +179,9 @@ function is_consumer_used($consumer) {
$mirrors = gmirror_get_mirrors();
foreach ($mirrors as $mirror) {
$consumers = gmirror_get_consumers_in_mirror($mirror);
if (in_array($consumer, $consumers))
if (in_array($consumer, $consumers)) {
return true;
}
}
return false;
}
@ -194,36 +199,41 @@ function is_valid_consumer($consumer) {
/* Remove all disconnected drives from a mirror */
function gmirror_forget_disconnected($mirror) {
if (!is_valid_mirror($mirror))
if (!is_valid_mirror($mirror)) {
return false;
}
return mwexec("/sbin/gmirror forget " . escapeshellarg($mirror));
}
/* Insert another consumer into a mirror */
function gmirror_insert_consumer($mirror, $consumer) {
if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer))
if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) {
return false;
}
return mwexec("/sbin/gmirror insert " . escapeshellarg($mirror) . " " . escapeshellarg($consumer));
}
/* Remove consumer from a mirror and clear its metadata */
function gmirror_remove_consumer($mirror, $consumer) {
if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer))
if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) {
return false;
}
return mwexec("/sbin/gmirror remove " . escapeshellarg($mirror) . " " . escapeshellarg($consumer));
}
/* Wipe geom info from drive (if mirror is not running) */
function gmirror_clear_consumer($consumer) {
if (!is_valid_consumer($consumer))
if (!is_valid_consumer($consumer)) {
return false;
}
return mwexec("/sbin/gmirror clear " . escapeshellarg($consumer));
}
/* Find the balance method used by a given mirror */
function gmirror_get_mirror_balance($mirror) {
if (!is_valid_mirror($mirror))
if (!is_valid_mirror($mirror)) {
return false;
}
$balancemethod = "";
exec("/sbin/gmirror list " . escapeshellarg($mirror) . " | /usr/bin/grep '^Balance:' | /usr/bin/awk '{print $2;}'", $balancemethod);
return $balancemethod[0];
@ -232,22 +242,25 @@ function gmirror_get_mirror_balance($mirror) {
/* Change balance algorithm of the mirror */
function gmirror_configure_balance($mirror, $balancemethod) {
global $balance_methods;
if (!is_valid_mirror($mirror) || !in_array($balancemethod, $balance_methods))
if (!is_valid_mirror($mirror) || !in_array($balancemethod, $balance_methods)) {
return false;
}
return mwexec("/sbin/gmirror configure -b " . escapeshellarg($balancemethod) . " " . escapeshellarg($mirror));
}
/* Force a mirror member to rebuild */
function gmirror_force_rebuild($mirror, $consumer) {
if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer))
if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) {
return false;
}
return mwexec("/sbin/gmirror rebuild " . escapeshellarg($mirror) . " " . escapeshellarg($consumer));
}
/* Show all metadata on the physical consumer */
function gmirror_get_consumer_metadata($consumer) {
if (!is_valid_consumer($consumer))
if (!is_valid_consumer($consumer)) {
return array();
}
$output = "";
exec("/sbin/gmirror dump " . escapeshellarg($consumer), $output);
return array_map('trim', $output);
@ -260,8 +273,9 @@ function gmirror_consumer_has_metadata($consumer) {
/* Find the mirror to which this consumer belongs */
function gmirror_get_consumer_metadata_mirror($consumer) {
if (!is_valid_consumer($consumer))
if (!is_valid_consumer($consumer)) {
return array();
}
$metadata = gmirror_get_consumer_metadata($consumer);
foreach ($metadata as $line) {
if (substr($line, 0, 5) == "name:") {
@ -273,22 +287,25 @@ function gmirror_get_consumer_metadata_mirror($consumer) {
/* Deactivate consumer, removing it from service in the mirror, but leave metadata intact */
function gmirror_deactivate_consumer($mirror, $consumer) {
if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer))
if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) {
return false;
}
return mwexec("/sbin/gmirror deactivate " . escapeshellarg($mirror) . " " . escapeshellarg($consumer));
}
/* Reactivate a deactivated consumer */
function gmirror_activate_consumer($mirror, $consumer) {
if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer))
if (!is_valid_mirror($mirror) || !is_valid_consumer($consumer)) {
return false;
}
return mwexec("/sbin/gmirror activate " . escapeshellarg($mirror) . " " . escapeshellarg($consumer));
}
/* Find the size of the given mirror */
function gmirror_get_mirror_size($mirror) {
if (!is_valid_mirror($mirror))
if (!is_valid_mirror($mirror)) {
return false;
}
$mirrorsize = "";
exec("/sbin/gmirror list " . escapeshellarg($mirror) . " | /usr/bin/grep 'Mediasize:' | /usr/bin/head -n 1 | /usr/bin/awk '{print $2;}'", $mirrorsize);
return $mirrorsize[0];
@ -298,8 +315,9 @@ function gmirror_get_mirror_size($mirror) {
list output is a little odd, we can't get the output for just the disk, if the disk contains
slices those get output also. */
function gmirror_get_all_unused_consumer_sizes_on_disk($disk) {
if (!is_valid_disk($disk) || !is_consumer_unused($disk))
if (!is_valid_disk($disk) || !is_consumer_unused($disk)) {
return array();
}
$output = "";
exec("/sbin/geom part list " . escapeshellarg($disk) . " | /usr/bin/egrep '(Name:|Mediasize:)' | /usr/bin/cut -c4- | /usr/bin/sed -l -e 'N;s/\\nMediasize://;P;D;' | /usr/bin/cut -c7-", $output);
if (empty($output)) {
@ -321,8 +339,9 @@ function gmirror_get_all_unused_consumer_sizes_on_disk($disk) {
function gmirror_get_unused_consumer_size($consumer) {
$consumersizes = gmirror_get_all_unused_consumer_sizes_on_disk($consumer);
foreach ($consumersizes as $csize) {
if ($csize['name'] == $consumer)
if ($csize['name'] == $consumer) {
return $csize['size'];
}
}
return -1;
}

View File

@ -3,100 +3,100 @@
pfSense_MODULE: notifications
*/
class Growl
{
const GROWL_PRIORITY_LOW = -2;
const GROWL_PRIORITY_MODERATE = -1;
const GROWL_PRIORITY_NORMAL = 0;
const GROWL_PRIORITY_HIGH = 1;
const GROWL_PRIORITY_EMERGENCY = 2;
class Growl
{
const GROWL_PRIORITY_LOW = -2;
const GROWL_PRIORITY_MODERATE = -1;
const GROWL_PRIORITY_NORMAL = 0;
const GROWL_PRIORITY_HIGH = 1;
const GROWL_PRIORITY_EMERGENCY = 2;
private $appName;
private $address;
private $notifications;
private $password;
private $port;
private $appName;
private $address;
private $notifications;
private $password;
private $port;
public function __construct($address, $password = '', $app_name = 'PHP-Growl')
{
$this->appName = utf8_encode($app_name);
$this->address = $address;
$this->notifications = array();
$this->password = $password;
$this->port = 9887;
}
public function addNotification($name, $enabled = true)
{
$this->notifications[] = array('name' => utf8_encode($name), 'enabled' => $enabled);
}
public function register()
{
$data = '';
$defaults = '';
$num_defaults = 0;
for($i = 0; $i < count($this->notifications); $i++)
{
$data .= pack('n', strlen($this->notifications[$i]['name'])) . $this->notifications[$i]['name'];
if($this->notifications[$i]['enabled'])
{
$defaults .= pack('c', $i);
$num_defaults++;
}
}
// pack(Protocol version, type, app name, number of notifications to register)
$data = pack('c2nc2', 1, 0, strlen($this->appName), count($this->notifications), $num_defaults) . $this->appName . $data . $defaults;
$data .= pack('H32', md5($data . $this->password));
return $this->send($data);
}
public function notify($name, $title, $message, $priority = 0, $sticky = false)
{
$name = utf8_encode($name);
$title = utf8_encode($title);
$message = utf8_encode($message);
$priority = intval($priority);
$flags = ($priority & 7) * 2;
if($priority < 0) $flags |= 8;
if($sticky) $flags |= 1;
// pack(protocol version, type, priority/sticky flags, notification name length, title length, message length. app name length)
$data = pack('c2n5', 1, 1, $flags, strlen($name), strlen($title), strlen($message), strlen($this->appName));
$data .= $name . $title . $message . $this->appName;
$data .= pack('H32', md5($data . $this->password));
return $this->send($data);
}
private function send($data)
{
if(function_exists('socket_create') && function_exists('socket_sendto'))
{
$sck = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($sck) {
socket_sendto($sck, $data, strlen($data), 0x100, $this->address, $this->port);
return true;
public function __construct($address, $password = '', $app_name = 'PHP-Growl')
{
$this->appName = utf8_encode($app_name);
$this->address = $address;
$this->notifications = array();
$this->password = $password;
$this->port = 9887;
}
}
elseif(function_exists('fsockopen'))
{
if ($this->address) {
$fp = @fsockopen('udp://' . $this->address, $this->port);
if ($fp) {
fwrite($fp, $data);
fclose($fp);
return true;
public function addNotification($name, $enabled = true)
{
$this->notifications[] = array('name' => utf8_encode($name), 'enabled' => $enabled);
}
public function register()
{
$data = '';
$defaults = '';
$num_defaults = 0;
for ($i = 0; $i < count($this->notifications); $i++)
{
$data .= pack('n', strlen($this->notifications[$i]['name'])) . $this->notifications[$i]['name'];
if ($this->notifications[$i]['enabled'])
{
$defaults .= pack('c', $i);
$num_defaults++;
}
}
}
}
return false;
}
}
// pack(Protocol version, type, app name, number of notifications to register)
$data = pack('c2nc2', 1, 0, strlen($this->appName), count($this->notifications), $num_defaults) . $this->appName . $data . $defaults;
$data .= pack('H32', md5($data . $this->password));
return $this->send($data);
}
public function notify($name, $title, $message, $priority = 0, $sticky = false)
{
$name = utf8_encode($name);
$title = utf8_encode($title);
$message = utf8_encode($message);
$priority = intval($priority);
$flags = ($priority & 7) * 2;
if ($priority < 0) $flags |= 8;
if ($sticky) $flags |= 1;
// pack(protocol version, type, priority/sticky flags, notification name length, title length, message length. app name length)
$data = pack('c2n5', 1, 1, $flags, strlen($name), strlen($title), strlen($message), strlen($this->appName));
$data .= $name . $title . $message . $this->appName;
$data .= pack('H32', md5($data . $this->password));
return $this->send($data);
}
private function send($data)
{
if (function_exists('socket_create') && function_exists('socket_sendto'))
{
$sck = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($sck) {
socket_sendto($sck, $data, strlen($data), 0x100, $this->address, $this->port);
return true;
}
}
elseif (function_exists('fsockopen'))
{
if ($this->address) {
$fp = @fsockopen('udp://' . $this->address, $this->port);
if ($fp) {
fwrite($fp, $data);
fclose($fp);
return true;
}
}
}
return false;
}
}
?>

View File

@ -63,8 +63,9 @@ function setup_gateways_monitor() {
}
$apinger_debug = "";
if (isset($config['system']['apinger_debug']))
if (isset($config['system']['apinger_debug'])) {
$apinger_debug = "debug on";
}
$apinger_default = return_apinger_defaults();
$apingerconfig = <<<EOD
@ -153,23 +154,26 @@ target default {
EOD;
$monitor_ips = array();
foreach($gateways_arr as $name => $gateway) {
foreach ($gateways_arr as $name => $gateway) {
/* Do not monitor if such was requested */
if (isset($gateway['monitor_disable']))
if (isset($gateway['monitor_disable'])) {
continue;
}
if (empty($gateway['monitor']) || !is_ipaddr($gateway['monitor'])) {
if (is_ipaddr($gateway['gateway']))
if (is_ipaddr($gateway['gateway'])) {
$gateway['monitor'] = $gateway['gateway'];
else /* No chance to get an ip to monitor skip target. */
} else { /* No chance to get an ip to monitor skip target. */
continue;
}
}
/* if the monitor address is already used before, skip */
if(in_array($gateway['monitor'], $monitor_ips))
if (in_array($gateway['monitor'], $monitor_ips)) {
continue;
}
/* Interface ip is needed since apinger will bind a socket to it.
* However the config GUI should already have checked this and when
/* Interface ip is needed since apinger will bind a socket to it.
* However the config GUI should already have checked this and when
* PPoE is used the IP address is set to "dynamic". So using is_ipaddrv4
* or is_ipaddrv6 to identify packet type would be wrong, especially as
* further checks (that can cope with the "dynamic" case) are present inside
@ -177,11 +181,13 @@ EOD;
*/
if ($gateway['ipprotocol'] == "inet") { // This is an IPv4 gateway...
$gwifip = find_interface_ip($gateway['interface'], true);
if (!is_ipaddrv4($gwifip))
if (!is_ipaddrv4($gwifip)) {
continue; //Skip this target
}
if ($gwifip == "0.0.0.0")
if ($gwifip == "0.0.0.0") {
continue; //Skip this target - the gateway is still waiting for DHCP
}
/*
* If the gateway is the same as the monitor we do not add a
@ -191,12 +197,13 @@ EOD;
*/
if (is_ipaddrv4($gateway['gateway']) && $gateway['monitor'] != $gateway['gateway']) {
log_error("Removing static route for monitor {$gateway['monitor']} and adding a new route through {$gateway['gateway']}");
if (interface_isppp_type($gateway['friendlyiface']))
if (interface_isppp_type($gateway['friendlyiface'])) {
mwexec("/sbin/route change -host " . escapeshellarg($gateway['monitor']) .
" -iface " . escapeshellarg($gateway['interface']), true);
else
} else {
mwexec("/sbin/route change -host " . escapeshellarg($gateway['monitor']) .
" " . escapeshellarg($gateway['gateway']), true);
}
pfSense_kill_states("0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmp");
}
@ -204,8 +211,9 @@ EOD;
if ($gateway['monitor'] == $gateway['gateway']) {
/* link locals really need a different src ip */
if (is_linklocal($gateway['gateway'])) {
if (!strpos($gateway['gateway'], '%'))
if (!strpos($gateway['gateway'], '%')) {
$gateway['gateway'] .= '%' . $gateway['interface'];
}
$gwifip = find_interface_ipv6_ll($gateway['interface'], true);
} else {
$gwifip = find_interface_ipv6($gateway['interface'], true);
@ -220,13 +228,16 @@ EOD;
}
/* Make sure srcip and target have scope defined when they are ll */
if (is_linklocal($gwifip) && !strpos($gwifip, '%'))
if (is_linklocal($gwifip) && !strpos($gwifip, '%')) {
$gwifip .= '%' . $gateway['interface'];
if (is_linklocal($gateway['monitor']) && !strpos($gateway['monitor'], '%'))
}
if (is_linklocal($gateway['monitor']) && !strpos($gateway['monitor'], '%')) {
$gateway['monitor'] .= "%{$gateway['interface']}";
}
if (!is_ipaddrv6($gwifip))
if (!is_ipaddrv6($gwifip)) {
continue; //Skip this target
}
/*
* If the gateway is the same as the monitor we do not add a
@ -236,17 +247,19 @@ EOD;
*/
if ($gateway['gateway'] != $gateway['monitor']) {
log_error("Removing static route for monitor {$gateway['monitor']} and adding a new route through {$gateway['gateway']}");
if (interface_isppp_type($gateway['friendlyiface']))
if (interface_isppp_type($gateway['friendlyiface'])) {
mwexec("/sbin/route change -host -inet6 " . escapeshellarg($gateway['monitor']) .
" -iface " . escapeshellarg($gateway['interface']), true);
else
} else {
mwexec("/sbin/route change -host -inet6 " . escapeshellarg($gateway['monitor']) .
" " . escapeshellarg($gateway['gateway']), true);
}
pfSense_kill_states("::0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmpv6");
}
} else
} else {
continue;
}
$monitor_ips[] = $gateway['monitor'];
$apingercfg = "target \"{$gateway['monitor']}\" {\n";
@ -256,35 +269,47 @@ EOD;
## How often the probe should be sent
if (!empty($gateway['interval']) && is_numeric($gateway['interval'])) {
$interval = intval($gateway['interval']); # Restrict to Integer
if ($interval < 1) $interval = 1; # Minimum
if ($interval != $apinger_default['interval']) # If not default value
if ($interval < 1) {
$interval = 1; # Minimum
}
if ($interval != $apinger_default['interval']) { # If not default value
$apingercfg .= " interval " . $interval . "s\n";
}
}
## How many replies should be used to compute average delay
## How many replies should be used to compute average delay
## for controlling "delay" alarms
if (!empty($gateway['avg_delay_samples']) && is_numeric($gateway['avg_delay_samples'])) {
$avg_delay_samples = intval($gateway['avg_delay_samples']); # Restrict to Integer
if ($avg_delay_samples < 1) $avg_delay_samples = 1; # Minimum
if ($avg_delay_samples != $apinger_default['avg_delay_samples']) # If not default value
if ($avg_delay_samples < 1) {
$avg_delay_samples = 1; # Minimum
}
if ($avg_delay_samples != $apinger_default['avg_delay_samples']) { # If not default value
$apingercfg .= " avg_delay_samples " . $avg_delay_samples . "\n";
}
}
## How many probes should be used to compute average loss
if (!empty($gateway['avg_loss_samples']) && is_numeric($gateway['avg_loss_samples'])) {
$avg_loss_samples = intval($gateway['avg_loss_samples']); # Restrict to Integer
if ($avg_loss_samples < 1) $avg_loss_samples = 1; # Minimum
if ($avg_loss_samples != $apinger_default['avg_loss_samples']) # If not default value
if ($avg_loss_samples < 1) {
$avg_loss_samples = 1; # Minimum
}
if ($avg_loss_samples != $apinger_default['avg_loss_samples']) { # If not default value
$apingercfg .= " avg_loss_samples " . $avg_loss_samples . "\n";
}
}
## The delay (in samples) after which loss is computed
## without this delays larger than interval would be treated as loss
if (!empty($gateway['avg_loss_delay_samples']) && is_numeric($gateway['avg_loss_delay_samples'])) {
$avg_loss_delay_samples = intval($gateway['avg_loss_delay_samples']); # Restrict to Integer
if ($avg_loss_delay_samples < 1) $avg_loss_delay_samples = 1; # Minimum
if ($avg_loss_delay_samples != $apinger_default['avg_loss_delay_samples']) # If not default value
if ($avg_loss_delay_samples < 1) {
$avg_loss_delay_samples = 1; # Minimum
}
if ($avg_loss_delay_samples != $apinger_default['avg_loss_delay_samples']) { # If not default value
$apingercfg .= " avg_loss_delay_samples " . $avg_loss_delay_samples . "\n";
}
}
$alarms = "";
@ -298,8 +323,9 @@ EOD;
$alarms .= "\"{$name}loss\"";
$override = true;
} else {
if ($override == true)
if ($override == true) {
$alarms .= ",";
}
$alarms .= "\"loss\"";
$override = true;
}
@ -308,13 +334,15 @@ EOD;
$alarmscfg .= "\tdelay_low {$gateway['latencylow']}ms\n";
$alarmscfg .= "\tdelay_high {$gateway['latencyhigh']}ms\n";
$alarmscfg .= "}\n";
if ($override == true)
if ($override == true) {
$alarms .= ",";
}
$alarms .= "\"{$name}delay\"";
$override = true;
} else {
if ($override == true)
if ($override == true) {
$alarms .= ",";
}
$alarms .= "\"delay\"";
$override = true;
}
@ -322,21 +350,25 @@ EOD;
$alarmscfg .= "alarm down \"{$name}down\" {\n";
$alarmscfg .= "\ttime {$gateway['down']}s\n";
$alarmscfg .= "}\n";
if ($override == true)
if ($override == true) {
$alarms .= ",";
}
$alarms .= "\"{$name}down\"";
$override = true;
} else {
if ($override == true)
if ($override == true) {
$alarms .= ",";
}
$alarms .= "\"down\"";
$override = true;
}
if ($override == true)
if ($override == true) {
$apingercfg .= "\talarms override {$alarms};\n";
}
if (isset($gateway['force_down']))
if (isset($gateway['force_down'])) {
$apingercfg .= "\tforce_down on\n";
}
$apingercfg .= " rrd file \"{$g['vardb_path']}/rrd/{$gateway['name']}-quality.rrd\"\n";
$apingercfg .= "}\n";
@ -345,18 +377,18 @@ EOD;
$apingerconfig .= $alarmscfg;
$apingerconfig .= $apingercfg;
# Create gateway quality RRD with settings more suitable for pfSense graph set,
# since apinger uses default step (300; 5 minutes) and other settings that don't
# Create gateway quality RRD with settings more suitable for pfSense graph set,
# since apinger uses default step (300; 5 minutes) and other settings that don't
# match the pfSense gateway quality graph set.
create_gateway_quality_rrd("{$g['vardb_path']}/rrd/{$gateway['name']}-quality.rrd");
}
@file_put_contents("{$g['varetc_path']}/apinger.conf", $apingerconfig);
unset($apingerconfig);
/* Restart apinger process */
if (isvalidpid("{$g['varrun_path']}/apinger.pid"))
/* Restart apinger process */
if (isvalidpid("{$g['varrun_path']}/apinger.pid")) {
sigkillbypid("{$g['varrun_path']}/apinger.pid", "HUP");
else {
} else {
/* start a new apinger process */
@unlink("{$g['varrun_path']}/apinger.status");
sleep(1);
@ -374,20 +406,23 @@ function return_gateways_status($byname = false) {
$apingerstatus = array();
/* Always get the latest status from apinger */
if (file_exists("{$g['varrun_path']}/apinger.pid"))
sigkillbypid("{$g['varrun_path']}/apinger.pid", "USR1");
if (file_exists("{$g['varrun_path']}/apinger.pid")) {
sigkillbypid("{$g['varrun_path']}/apinger.pid", "USR1");
}
if (file_exists("{$g['varrun_path']}/apinger.status")) {
$apingerstatus = file("{$g['varrun_path']}/apinger.status");
} else
} else {
$apingerstatus = array();
}
$status = array();
foreach($apingerstatus as $line) {
foreach ($apingerstatus as $line) {
$info = explode("|", $line);
if ($byname == false)
if ($byname == false) {
$target = $info[0];
else
} else {
$target = $info[2];
}
$status[$target] = array();
$status[$target]['monitorip'] = $info[0];
@ -402,26 +437,29 @@ function return_gateways_status($byname = false) {
/* tack on any gateways that have monitoring disabled
* or are down, which could cause gateway groups to fail */
$gateways_arr = return_gateways_array();
foreach($gateways_arr as $gwitem) {
if(!isset($gwitem['monitor_disable']))
foreach ($gateways_arr as $gwitem) {
if (!isset($gwitem['monitor_disable'])) {
continue;
if(!is_ipaddr($gwitem['monitorip'])) {
}
if (!is_ipaddr($gwitem['monitorip'])) {
$realif = $gwitem['interface'];
$tgtip = get_interface_gateway($realif);
if (!is_ipaddr($tgtip))
if (!is_ipaddr($tgtip)) {
$tgtip = "none";
}
$srcip = find_interface_ip($realif);
} else {
$tgtip = $gwitem['monitorip'];
$srcip = find_interface_ip($realif);
}
if($byname == true)
if ($byname == true) {
$target = $gwitem['name'];
else
} else {
$target = $tgtip;
}
/* failsafe for down interfaces */
if($target == "none") {
if ($target == "none") {
$target = $gwitem['name'];
$status[$target]['name'] = $gwitem['name'];
$status[$target]['lastcheck'] = date('r');
@ -464,16 +502,18 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
$i++;
if (empty($config['interfaces'][$gateway['interface']])) {
if ($inactive === false)
if ($inactive === false) {
continue;
else
} else {
$gateway['inactive'] = true;
}
}
$wancfg = $config['interfaces'][$gateway['interface']];
/* skip disabled interfaces */
if ($disabled === false && (!isset($wancfg['enable'])))
if ($disabled === false && (!isset($wancfg['enable']))) {
continue;
}
/* if the gateway is dynamic and we can find the IPv4, Great! */
if (empty($gateway['gateway']) || $gateway['gateway'] == "dynamic") {
@ -481,8 +521,9 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
/* we know which interfaces is dynamic, this should be made a function */
$gateway['gateway'] = get_interface_gateway($gateway['interface']);
/* no IP address found, set to dynamic */
if (!is_ipaddrv4($gateway['gateway']))
if (!is_ipaddrv4($gateway['gateway'])) {
$gateway['gateway'] = "dynamic";
}
$gateway['dynamic'] = true;
}
@ -491,23 +532,26 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
/* we know which interfaces is dynamic, this should be made a function, and for v6 too */
$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
/* no IPv6 address found, set to dynamic */
if (!is_ipaddrv6($gateway['gateway']))
if (!is_ipaddrv6($gateway['gateway'])) {
$gateway['gateway'] = "dynamic";
}
$gateway['dynamic'] = true;
}
} else {
/* getting this detection right is hard at this point because we still don't
* store the address family in the gateway item */
if (is_ipaddrv4($gateway['gateway']))
if (is_ipaddrv4($gateway['gateway'])) {
$gateway['ipprotocol'] = "inet";
else if(is_ipaddrv6($gateway['gateway']))
} else if (is_ipaddrv6($gateway['gateway'])) {
$gateway['ipprotocol'] = "inet6";
}
}
if (isset($gateway['monitor_disable']))
if (isset($gateway['monitor_disable'])) {
$gateway['monitor_disable'] = true;
else if (empty($gateway['monitor']))
} else if (empty($gateway['monitor'])) {
$gateway['monitor'] = $gateway['gateway'];
}
$gateway['friendlyiface'] = $gateway['interface'];
@ -538,38 +582,45 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
$gateways_arr_temp[$gateway['name']] = $gateway;
/* skip disabled gateways if the caller has not asked for them to be returned. */
if (!($disabled === false && isset($gateway['disabled'])))
if (!($disabled === false && isset($gateway['disabled']))) {
$gateways_arr[$gateway['name']] = $gateway;
}
}
}
unset($gateway);
/* Loop through all interfaces with a gateway and add it to a array */
if ($disabled == false)
if ($disabled == false) {
$iflist = get_configured_interface_with_descr();
else
} else {
$iflist = get_configured_interface_with_descr(false, true);
}
/* Process/add dynamic v4 gateways. */
foreach($iflist as $ifname => $friendly ) {
if(! interface_has_gateway($ifname))
foreach ($iflist as $ifname => $friendly ) {
if (! interface_has_gateway($ifname)) {
continue;
}
if (empty($config['interfaces'][$ifname]))
if (empty($config['interfaces'][$ifname])) {
continue;
}
$ifcfg = &$config['interfaces'][$ifname];
if(!isset($ifcfg['enable']))
if (!isset($ifcfg['enable'])) {
continue;
}
if(!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr']))
if (!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr'])) {
continue;
}
if (isset($interfaces_v4[$ifname]))
if (isset($interfaces_v4[$ifname])) {
continue;
}
$ctype = "";
switch($ifcfg['ipaddr']) {
switch ($ifcfg['ipaddr']) {
case "dhcp":
case "pppoe":
case "pptp":
@ -585,15 +636,17 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
if (is_array($config['openvpn']['openvpn-server'])) {
foreach ($config['openvpn']['openvpn-server'] as & $ovpnserverconf) {
if ($ovpnserverconf['vpnid'] == $ovpnid) {
if ($ovpnserverconf['dev_mode'] == "tap")
if ($ovpnserverconf['dev_mode'] == "tap") {
continue 3;
}
}
}
}
}
$ctype = "VPNv4";
} else if ($tunnelif == "gif" || $tunnelif == "gre")
} else if ($tunnelif == "gif" || $tunnelif == "gre") {
$ctype = "TUNNELv4";
}
break;
}
$ctype = "_". strtoupper($ctype);
@ -613,18 +666,21 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
$found_defaultv4 = 1;
}
/* Loopback dummy for dynamic interfaces without a IP */
if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true)
if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true) {
$gateway['gateway'] = "dynamic";
/* automatically skip known static and dynamic gateways that were previously processed */
foreach($gateways_arr_temp as $gateway_item) {
if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))
continue 2;
}
if (is_ipaddrv4($gateway['gateway']))
/* automatically skip known static and dynamic gateways that were previously processed */
foreach ($gateways_arr_temp as $gateway_item) {
if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
(($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
continue 2;
}
}
if (is_ipaddrv4($gateway['gateway'])) {
$gateway['monitor'] = $gateway['gateway'];
}
$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
$gateways_arr[$gateway['name']] = $gateway;
@ -632,29 +688,35 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
unset($gateway);
/* Process/add dynamic v6 gateways. */
foreach($iflist as $ifname => $friendly ) {
foreach ($iflist as $ifname => $friendly ) {
/* If the user has disabled IPv6, they probably don't want any IPv6 gateways. */
if (!isset($config['system']['ipv6allow']))
if (!isset($config['system']['ipv6allow'])) {
break;
}
if(! interface_has_gatewayv6($ifname))
if (! interface_has_gatewayv6($ifname)) {
continue;
}
if (empty($config['interfaces'][$ifname]))
if (empty($config['interfaces'][$ifname])) {
continue;
}
$ifcfg = &$config['interfaces'][$ifname];
if(!isset($ifcfg['enable']))
if (!isset($ifcfg['enable'])) {
continue;
}
if(!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6']))
if (!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) {
continue;
}
if(isset($interfaces_v6[$ifname]))
if (isset($interfaces_v6[$ifname])) {
continue;
}
$ctype = "";
switch($ifcfg['ipaddrv6']) {
switch ($ifcfg['ipaddrv6']) {
case "slaac":
case "dhcp6":
case "6to4":
@ -670,15 +732,17 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
if (is_array($config['openvpn']['openvpn-server'])) {
foreach ($config['openvpn']['openvpn-server'] as & $ovpnserverconf) {
if ($ovpnserverconf['vpnid'] == $ovpnid) {
if ($ovpnserverconf['dev_mode'] == "tap")
if ($ovpnserverconf['dev_mode'] == "tap") {
continue 3;
}
}
}
}
}
$ctype = "VPNv6";
} else if ($tunnelif == "gif" || $tunnelif == "gre")
} else if ($tunnelif == "gif" || $tunnelif == "gre") {
$ctype = "TUNNELv6";
}
break;
}
$ctype = "_". strtoupper($ctype);
@ -688,7 +752,7 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
$gateway['ipprotocol'] = "inet6";
$gateway['gateway'] = get_interface_gateway_v6($ifname, $gateway['dynamic']);
$gateway['interface'] = get_real_interface($ifname, "inet6");
switch($ifcfg['ipaddrv6']) {
switch ($ifcfg['ipaddrv6']) {
case "6rd":
case "6to4":
$gateway['dynamic'] = "default";
@ -705,18 +769,21 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
}
/* Loopback dummy for dynamic interfaces without a IP */
if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true)
if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true) {
$gateway['gateway'] = "dynamic";
/* automatically skip known static and dynamic gateways that were previously processed */
foreach($gateways_arr_temp as $gateway_item) {
if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))
continue 2;
}
if (is_ipaddrv6($gateway['gateway']))
/* automatically skip known static and dynamic gateways that were previously processed */
foreach ($gateways_arr_temp as $gateway_item) {
if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
(($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
continue 2;
}
}
if (is_ipaddrv6($gateway['gateway'])) {
$gateway['monitor'] = $gateway['gateway'];
}
$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
$gateways_arr[$gateway['name']] = $gateway;
@ -744,7 +811,7 @@ function return_gateways_array($disabled = false, $localhost = false, $inactive
}
}
if($localhost === true) {
if ($localhost === true) {
/* attach localhost for Null routes */
$gwlo4 = array();
$gwlo4['name'] = "Null4";
@ -776,27 +843,32 @@ function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) {
if (($gwsttng['ipprotocol'] == $ipprotocol) && isset($gwsttng['defaultgw'])) {
$dfltgwfound = true;
$dfltgwname = $gwname;
if (!isset($gwsttng['monitor_disable']) && stristr($gateways_status[$gwname]['status'], "down"))
if (!isset($gwsttng['monitor_disable']) && $gateways_status[$gwname]['status'] != "none") {
$dfltgwdown = true;
}
}
/* Keep a record of the last up gateway */
/* XXX: Blacklist lan for now since it might cause issues to those who have a gateway set for it */
if (empty($upgw) && ($gwsttng['ipprotocol'] == $ipprotocol) && (isset($gwsttng['monitor_disable']) || !stristr($gateways_status[$gwname]['status'], "down")) && $gwsttng[$gwname]['friendlyiface'] != "lan")
if (empty($upgw) && ($gwsttng['ipprotocol'] == $ipprotocol) && (isset($gwsttng['monitor_disable']) || $gateways_status[$gwname]['status'] == "none") && $gwsttng[$gwname]['friendlyiface'] != "lan") {
$upgw = $gwname;
if ($dfltgwdown == true && !empty($upgw))
}
if ($dfltgwdown == true && !empty($upgw)) {
break;
}
}
if ($dfltgwfound == false) {
$gwname = convert_friendly_interface_to_friendly_descr("wan");
if (!empty($gateways_status[$gwname]) && stristr($gateways_status[$gwname]['status'], "down"))
if (!empty($gateways_status[$gwname]) && stristr($gateways_status[$gwname]['status'], "down")) {
$dfltgwdown = true;
}
}
if ($dfltgwdown == true && !empty($upgw)) {
if ($gateways_arr[$upgw]['gateway'] == "dynamic")
if ($gateways_arr[$upgw]['gateway'] == "dynamic") {
$gateways_arr[$upgw]['gateway'] = get_interface_gateway($gateways_arr[$upgw]['friendlyiface']);
}
if (is_ipaddr($gateways_arr[$upgw]['gateway'])) {
log_error("Default gateway down setting {$upgw} as default!");
if(is_ipaddrv6($gateways_arr[$upgw]['gateway'])) {
if (is_ipaddrv6($gateways_arr[$upgw]['gateway'])) {
$inetfamily = "-inet6";
} else {
$inetfamily = "-inet";
@ -805,12 +877,15 @@ function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) {
}
} else if (!empty($dfltgwname)) {
$defaultgw = trim(exec("/sbin/route -n get -{$ipprotocol} default | /usr/bin/awk '/gateway:/ {print $2}'"), " \n");
if ($ipprotocol == 'inet6' && !is_ipaddrv6($gateways_arr[$dfltgwname]['gateway']))
if ($ipprotocol == 'inet6' && !is_ipaddrv6($gateways_arr[$dfltgwname]['gateway'])) {
return;
if ($ipprotocol == 'inet' && !is_ipaddrv4($gateways_arr[$dfltgwname]['gateway']))
}
if ($ipprotocol == 'inet' && !is_ipaddrv4($gateways_arr[$dfltgwname]['gateway'])) {
return;
if ($defaultgw != $gateways_arr[$dfltgwname]['gateway'])
}
if ($defaultgw != $gateways_arr[$dfltgwname]['gateway']) {
mwexec("/sbin/route change -{$ipprotocol} default {$gateways_arr[$dfltgwname]['gateway']}");
}
}
}
@ -841,14 +916,16 @@ function return_gateway_groups_array() {
list($gwname, $tier, $vipname) = explode("|", $item);
if (is_ipaddr($carplist[$vipname])) {
if (!is_array($gwvip_arr[$group['name']]))
if (!is_array($gwvip_arr[$group['name']])) {
$gwvip_arr[$group['name']] = array();
}
$gwvip_arr[$group['name']][$gwname] = $vipname;
}
/* Do it here rather than reiterating again the group in case no member is up. */
if (!is_array($backupplan[$tier]))
if (!is_array($backupplan[$tier])) {
$backupplan[$tier] = array();
}
$backupplan[$tier][] = $gwname;
/* check if the gateway is available before adding it to the array */
@ -873,12 +950,14 @@ function return_gateway_groups_array() {
notify_via_smtp($msg);
} else {
/* Online add member */
if (!is_array($tiers[$tier]))
if (!is_array($tiers[$tier])) {
$tiers[$tier] = array();
}
$tiers[$tier][] = $gwname;
}
} else if (isset($gateways_arr[$gwname]['monitor_disable']))
} else if (isset($gateways_arr[$gwname]['monitor_disable'])) {
$tiers[$tier][] = $gwname;
}
}
$tiers_count = count($tiers);
if ($tiers_count == 0) {
@ -903,10 +982,11 @@ function return_gateway_groups_array() {
$gateway = $gateways_arr[$member];
$int = $gateway['interface'];
$gatewayip = "";
if(is_ipaddr($gateway['gateway']))
if (is_ipaddr($gateway['gateway'])) {
$gatewayip = $gateway['gateway'];
else if (!empty($int))
} else if (!empty($int)) {
$gatewayip = get_interface_gateway($gateway['friendlyiface']);
}
if (!empty($int)) {
$gateway_groups_array[$group['name']]['ipprotocol'] = $gateway['ipprotocol'];
@ -915,18 +995,20 @@ function return_gateway_groups_array() {
$groupmember['int'] = $int;
$groupmember['gwip'] = $gatewayip;
$groupmember['weight'] = isset($gateway['weight']) ? $gateway['weight'] : 1;
if (is_array($gwvip_arr[$group['name']])&& !empty($gwvip_arr[$group['name']][$member]))
if (is_array($gwvip_arr[$group['name']])&& !empty($gwvip_arr[$group['name']][$member])) {
$groupmember['vip'] = $gwvip_arr[$group['name']][$member];
}
$gateway_groups_array[$group['name']][] = $groupmember;
}
}
}
}
/* we should have the 1st available tier now, exit stage left */
if (count($gateway_groups_array[$group['name']]) > 0)
if (count($gateway_groups_array[$group['name']]) > 0) {
break;
else
} else {
log_error("GATEWAYS: Group {$group['name']} did not have any gateways up on tier {$tieridx}!");
}
}
}
}
@ -937,25 +1019,27 @@ function return_gateway_groups_array() {
/* Update DHCP WAN Interface ip address in gateway group item */
function dhclient_update_gateway_groups_defaultroute($interface = "wan") {
global $config, $g;
foreach($config['gateways']['gateway_item'] as & $gw) {
if($gw['interface'] == $interface) {
foreach ($config['gateways']['gateway_item'] as & $gw) {
if ($gw['interface'] == $interface) {
$current_gw = get_interface_gateway($interface);
if($gw['gateway'] <> $current_gw) {
if ($gw['gateway'] <> $current_gw) {
$gw['gateway'] = $current_gw;
$changed = true;
}
}
}
if($changed && $current_gw)
if ($changed && $current_gw) {
write_config(sprintf(gettext('Updating gateway group gateway for %1$s - new gateway is %2$s'), $interfac, $current_gw));
}
}
function lookup_gateway_ip_by_name($name) {
$gateways_arr = return_gateways_array(false, true);
foreach ($gateways_arr as $gname => $gw) {
if ($gw['name'] === $name || $gname === $name)
if ($gw['name'] === $name || $gname === $name) {
return $gw['gateway'];
}
}
return false;
@ -966,8 +1050,9 @@ function lookup_gateway_monitor_ip_by_name($name) {
$gateways_arr = return_gateways_array(false, true);
if (!empty($gateways_arr[$name])) {
$gateway = $gateways_arr[$name];
if(!is_ipaddr($gateway['monitor']))
if (!is_ipaddr($gateway['monitor'])) {
return $gateway['gateway'];
}
return $gateway['monitor'];
}
@ -989,14 +1074,15 @@ function lookup_gateway_interface_by_name($name) {
function get_interface_gateway($interface, &$dynamic = false) {
global $config, $g;
if (substr($interface, 0, 4) == '_vip')
if (substr($interface, 0, 4) == '_vip') {
$interface = get_configured_carp_interface_list($interface, 'inet', 'iface');
}
$gw = NULL;
$gwcfg = $config['interfaces'][$interface];
if (!empty($gwcfg['gateway']) && is_array($config['gateways']['gateway_item'])) {
foreach($config['gateways']['gateway_item'] as $gateway) {
if(($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) {
foreach ($config['gateways']['gateway_item'] as $gateway) {
if (($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) {
$gw = $gateway['gateway'];
break;
}
@ -1007,11 +1093,12 @@ function get_interface_gateway($interface, &$dynamic = false) {
if (($gw == NULL || !is_ipaddrv4($gw)) && !is_ipaddrv4($gwcfg['ipaddr'])) {
$realif = get_real_interface($interface);
if (file_exists("{$g['tmp_path']}/{$realif}_router")) {
$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n");
$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n");
$dynamic = true;
}
if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw"))
if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw")) {
$dynamic = "default";
}
}
@ -1022,14 +1109,15 @@ function get_interface_gateway($interface, &$dynamic = false) {
function get_interface_gateway_v6($interface, &$dynamic = false) {
global $config, $g;
if (substr($interface, 0, 4) == '_vip')
if (substr($interface, 0, 4) == '_vip') {
$interface = get_configured_carp_interface_list($interface, 'inet6', 'iface');
}
$gw = NULL;
$gwcfg = $config['interfaces'][$interface];
if (!empty($gwcfg['gatewayv6']) && is_array($config['gateways']['gateway_item'])) {
foreach($config['gateways']['gateway_item'] as $gateway) {
if(($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) {
foreach ($config['gateways']['gateway_item'] as $gateway) {
if (($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) {
$gw = $gateway['gateway'];
break;
}
@ -1038,14 +1126,14 @@ function get_interface_gateway_v6($interface, &$dynamic = false) {
// for dynamic interfaces we handle them through the $interface_router file.
if (($gw == NULL || !is_ipaddrv6($gw)) && !is_ipaddrv6($gwcfg['ipaddrv6'])) {
$realif = get_real_interface($interface);
if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) {
$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n");
$dynamic = true;
}
if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6"))
$dynamic = "default";
$realif = get_real_interface($interface);
if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) {
$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n");
$dynamic = true;
}
if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6")) {
$dynamic = "default";
}
}
/* return gateway */
return ($gw);
@ -1059,29 +1147,37 @@ function validate_address_family($ipaddr, $gwname) {
$v4gw = false;
$v6gw = false;
if(is_ipaddrv4($ipaddr))
if (is_ipaddrv4($ipaddr)) {
$v4ip = true;
if(is_ipaddrv6($ipaddr))
}
if (is_ipaddrv6($ipaddr)) {
$v6ip = true;
if(is_ipaddrv4($gwname))
}
if (is_ipaddrv4($gwname)) {
$v4gw = true;
if(is_ipaddrv6($gwname))
}
if (is_ipaddrv6($gwname)) {
$v6gw = true;
}
if($v4ip && $v4gw)
if ($v4ip && $v4gw) {
return true;
if($v6ip && $v6gw)
}
if ($v6ip && $v6gw) {
return true;
}
/* still no match, carry on, lookup gateways */
if(is_ipaddrv4(lookup_gateway_ip_by_name($gwname)))
if (is_ipaddrv4(lookup_gateway_ip_by_name($gwname))) {
$v4gw = true;
if(is_ipaddrv6(lookup_gateway_ip_by_name($gwname)))
}
if (is_ipaddrv6(lookup_gateway_ip_by_name($gwname))) {
$v6gw = true;
}
$gw_array = return_gateways_array();
if(is_array($gw_array[$gwname])) {
switch($gw_array[$gwname]['ipprotocol']) {
if (is_array($gw_array[$gwname])) {
switch ($gw_array[$gwname]['ipprotocol']) {
case "inet":
$v4gw = true;
break;
@ -1091,10 +1187,12 @@ function validate_address_family($ipaddr, $gwname) {
}
}
if($v4ip && $v4gw)
if ($v4ip && $v4gw) {
return true;
if($v6ip && $v6gw)
}
if ($v6ip && $v6gw) {
return true;
}
return false;
}
@ -1103,15 +1201,16 @@ function validate_address_family($ipaddr, $gwname) {
function interface_gateway_group_member($interface) {
global $config;
if (is_array($config['gateways']['gateway_group']))
if (is_array($config['gateways']['gateway_group'])) {
$groups = $config['gateways']['gateway_group'];
else
} else {
return false;
}
$gateways_arr = return_gateways_array(false, true);
foreach($groups as $group) {
if(is_array($group['item'])) {
foreach($group['item'] as $item) {
foreach ($groups as $group) {
if (is_array($group['item'])) {
foreach ($group['item'] as $item) {
$elements = explode("|", $item);
$gwname = $elements[0];
if ($interface == $gateways_arr[$gwname]['interface']) {
@ -1129,23 +1228,25 @@ function interface_gateway_group_member($interface) {
function gateway_is_gwgroup_member($name) {
global $config;
if (is_array($config['gateways']['gateway_group']))
if (is_array($config['gateways']['gateway_group'])) {
$groups = $config['gateways']['gateway_group'];
else
} else {
return false;
}
$members = array();
foreach($groups as $group) {
foreach ($groups as $group) {
if (is_array($group['item'])) {
foreach($group['item'] as $item) {
foreach ($group['item'] as $item) {
$elements = explode("|", $item);
$gwname = $elements[0];
if ($name == $elements[0])
if ($name == $elements[0]) {
$members[] = $group['name'];
}
}
}
}
return $members;
}
?>
?>

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
<?php
/*
ipsec.attributes.php
Copyright (C) 2011-2012 Ermal Luçi
Copyright (C) 2011-2012 Ermal Luçi
Copyright (C) 2013-2015 Electric Sheep Fencing, LP
All rights reserved.
@ -29,13 +29,15 @@
if (empty($common_name)) {
$common_name = getenv("common_name");
if (empty($common_name))
if (empty($common_name)) {
$common_name = getenv("username");
}
}
function cisco_to_cidr($addr) {
if (!is_ipaddr($addr))
if (!is_ipaddr($addr)) {
return 0;
}
$mask = decbin(~ip2long($addr));
$mask = substr($mask, -32);
$k = 0;
@ -46,19 +48,21 @@ function cisco_to_cidr($addr) {
}
function cisco_extract_index($prule) {
$index = explode("#", $prule);
if (is_numeric($index[1]))
if (is_numeric($index[1])) {
return intval($index[1]);
else
} else {
syslog(LOG_WARNING, "Error parsing rule {$prule}: Could not extract index");
}
return -1;;
}
function parse_cisco_acl($attribs) {
global $attributes;
if (!is_array($attribs))
if (!is_array($attribs)) {
return "";
}
$devname = "enc0";
$finalrules = "";
@ -70,29 +74,31 @@ function parse_cisco_acl($attribs) {
$dir = "";
if (strstr($rule[0], "inacl")) {
$dir = "in";
} else if (strstr($rule[0], "outacl"))
} else if (strstr($rule[0], "outacl")) {
$dir = "out";
else if (strstr($rule[0], "dns-servers")) {
} else if (strstr($rule[0], "dns-servers")) {
$attributes['dns-servers'] = explode(" ", $rule[1]);
continue;
} else if (strstr($rule[0], "route")) {
if (!is_array($attributes['routes']))
if (!is_array($attributes['routes'])) {
$attributes['routes'] = array();
}
$attributes['routes'][] = $rule[1];
continue;
}
}
$rindex = cisco_extract_index($rule[0]);
if ($rindex < 0)
if ($rindex < 0) {
continue;
}
$rule = $rule[1];
$rule = explode(" ", $rule);
$tmprule = "";
$index = 0;
$isblock = false;
if ($rule[$index] == "permit")
if ($rule[$index] == "permit") {
$tmprule = "pass {$dir} quick on {$devname} ";
else if ($rule[$index] == "deny") {
} else if ($rule[$index] == "deny") {
//continue;
$isblock = true;
$tmprule = "block {$dir} quick on {$devname} ";
@ -103,11 +109,10 @@ function parse_cisco_acl($attribs) {
$index++;
switch ($rule[$index]) {
case "tcp":
case "udp":
$tmprule .= "proto {$rule[$index]} ";
break;
case "tcp":
case "udp":
$tmprule .= "proto {$rule[$index]} ";
break;
}
$index++;
@ -116,8 +121,9 @@ function parse_cisco_acl($attribs) {
$index++;
$tmprule .= "from {$rule[$index]} ";
$index++;
if ($isblock == true)
if ($isblock == true) {
$isblock = false;
}
} else if (trim($rule[$index]) == "any") {
$tmprule .= "from any";
$index++;
@ -127,16 +133,18 @@ function parse_cisco_acl($attribs) {
$netmask = cisco_to_cidr($rule[$index]);
$tmprule .= "/{$netmask} ";
$index++;
if ($isblock == true)
if ($isblock == true) {
$isblock = false;
}
}
/* Destination */
if (trim($rule[$index]) == "host") {
$index++;
$tmprule .= "to {$rule[$index]} ";
$index++;
if ($isblock == true)
if ($isblock == true) {
$isblock = false;
}
} else if (trim($rule[$index]) == "any") {
$index++;
$tmprule .= "to any";
@ -146,30 +154,36 @@ function parse_cisco_acl($attribs) {
$netmask = cisco_to_cidr($rule[$index]);
$tmprule .= "/{$netmask} ";
$index++;
if ($isblock == true)
if ($isblock == true) {
$isblock = false;
}
}
if ($isblock == true)
if ($isblock == true) {
continue;
}
if ($dir == "in")
if ($dir == "in") {
$inrules[$rindex] = $tmprule;
else if ($dir == "out")
} else if ($dir == "out") {
$outrules[$rindex] = $tmprule;
}
}
$state = "";
if (!empty($outrules))
if (!empty($outrules)) {
$state = "no state";
}
ksort($inrules, SORT_NUMERIC);
foreach ($inrules as $inrule)
foreach ($inrules as $inrule) {
$finalrules .= "{$inrule} {$state}\n";
}
if (!empty($outrules)) {
ksort($outrules, SORT_NUMERIC);
foreach ($outrules as $outrule)
foreach ($outrules as $outrule) {
$finalrules .= "{$outrule} {$state}\n";
}
}
}
return $finalrules;

View File

@ -31,7 +31,7 @@
*/
/*
pfSense_BUILDER_BINARIES:
pfSense_BUILDER_BINARIES:
pfSense_MODULE: openvpn
*/
/*
@ -54,12 +54,13 @@ require_once("interfaces.inc");
if (!function_exists("getNasID")) {
function getNasID()
{
global $g;
global $g;
$nasId = gethostname();
if(empty($nasId))
$nasId = $g['product_name'];
return $nasId;
$nasId = gethostname();
if (empty($nasId)) {
$nasId = $g['product_name'];
}
return $nasId;
}
}
@ -72,10 +73,11 @@ function getNasID()
if (!function_exists("getNasIP")) {
function getNasIP()
{
$nasIp = get_interface_ip();
if(!$nasIp)
$nasIp = "0.0.0.0";
return $nasIp;
$nasIp = get_interface_ip();
if (!$nasIp) {
$nasIp = "0.0.0.0";
}
return $nasIp;
}
}
/* setup syslog logging */
@ -123,13 +125,14 @@ if (($strictusercn === true) && ($common_name != $username)) {
$attributes = array();
foreach ($authmodes as $authmode) {
$authcfg = auth_get_authserver($authmode);
if (!$authcfg && $authmode != "local")
if (!$authcfg && $authmode != "local") {
continue;
}
$authenticated = authenticate_user($username, $password, $authcfg, $attributes);
if ($authenticated == true) {
if (stristr($authmode, "local")) {
$user = getUserEntry($username);
$user = getUserEntry($username);
if (!is_array($user) || !userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
$authenticated = false;
syslog(LOG_WARNING, "user '{$username}' cannot authenticate through IPsec since the required privileges are missing.\n");
@ -152,15 +155,17 @@ if ($authenticated == false) {
}
}
if (file_exists("/etc/inc/ipsec.attributes.php"))
include_once("/etc/inc/ipsec.attributes.php");
if (file_exists("/etc/inc/ipsec.attributes.php")) {
include_once("/etc/inc/ipsec.attributes.php");
}
syslog(LOG_NOTICE, "user '{$username}' authenticated\n");
closelog();
if (isset($_GET['username']))
if (isset($_GET['username'])) {
echo "OK";
else
} else {
exit (0);
}
?>

View File

@ -35,12 +35,14 @@
*/
/* IPsec defines */
global $ipsec_loglevels;
$ipsec_loglevels = array("dmn" => "Daemon", "mgr" => "SA Manager", "ike" => "IKE SA", "chd" => "IKE Child SA",
"job" => "Job Processing", "cfg" => "Configuration backend", "knl" => "Kernel Interface",
"net" => "Networking", "asn" => "ASN encoding", "enc" => "Message encoding",
"imc" => "Integrity checker", "imv" => "Integrity Verifier", "pts" => "Platform Trust Service",
"tls" => "TLS handler", "esp" => "IPsec traffic", "lib" => "StrongSwan Lib");
global $my_identifier_list;
$my_identifier_list = array(
'myaddress' => array( 'desc' => gettext('My IP address'), 'mobile' => true ),
'address' => array( 'desc' => gettext('IP address'), 'mobile' => true ),
@ -50,6 +52,7 @@ $my_identifier_list = array(
'keyid tag' => array( 'desc' => gettext('KeyID tag'), 'mobile' => true ),
'dyn_dns' => array( 'desc' => gettext('Dynamic DNS'), 'mobile' => true ));
global $peer_identifier_list;
$peer_identifier_list = array(
'peeraddress' => array( 'desc' => gettext('Peer IP address'), 'mobile' => false ),
'address' => array( 'desc' => gettext('IP address'), 'mobile' => false ),
@ -58,6 +61,12 @@ $peer_identifier_list = array(
'asn1dn' => array( 'desc' => gettext('ASN.1 distinguished Name'), 'mobile' => true ),
'keyid tag' => array( 'desc' =>gettext('KeyID tag'), 'mobile' => true ));
global $ipsec_idhandling;
$ipsec_idhandling = array(
'yes' => 'YES', 'no' => 'NO', 'never' => 'NEVER', 'keep' => 'KEEP'
);
global $p1_ealgos;
$p1_ealgos = array(
'aes' => array( 'name' => 'AES', 'keysel' => array( 'lo' => 128, 'hi' => 256, 'step' => 64 ) ),
'blowfish' => array( 'name' => 'Blowfish', 'keysel' => array( 'lo' => 128, 'hi' => 256, 'step' => 64 ) ),
@ -65,6 +74,7 @@ $p1_ealgos = array(
'cast128' => array( 'name' => 'CAST128' ),
'des' => array( 'name' => 'DES' ));
global $p2_ealgos;
$p2_ealgos = array(
'aes' => array( 'name' => 'AES', 'keysel' => array( 'lo' => 128, 'hi' => 256, 'step' => 64 ) ),
'aes128gcm' => array( 'name' => 'AES128-GCM', 'keysel' => array( 'lo' => 64, 'hi' => 128, 'step' => 32 ) ),
@ -75,6 +85,7 @@ $p2_ealgos = array(
'cast128' => array( 'name' => 'CAST128' ),
'des' => array( 'name' => 'DES' ));
global $p1_halgos;
$p1_halgos = array(
'md5' => 'MD5',
'sha1' => 'SHA1',
@ -84,6 +95,7 @@ $p1_halgos = array(
'aesxcbc' => 'AES-XCBC'
);
global $p1_dhgroups;
$p1_dhgroups = array(
1 => '1 (768 bit)',
2 => '2 (1024 bit)',
@ -98,6 +110,7 @@ $p1_dhgroups = array(
24 => '24 (2048(sub 256) bit)'
);
global $p2_halgos;
$p2_halgos = array(
'hmac_md5' => 'MD5',
'hmac_sha1' => 'SHA1',
@ -107,6 +120,7 @@ $p2_halgos = array(
'aesxcbc' => 'AES-XCBC'
);
global $p1_authentication_methods;
$p1_authentication_methods = array(
'hybrid_rsa_server' => array( 'name' => 'Hybrid RSA + Xauth', 'mobile' => true ),
'xauth_rsa_server' => array( 'name' => 'Mutual RSA + Xauth', 'mobile' => true ),
@ -116,20 +130,24 @@ $p1_authentication_methods = array(
'rsasig' => array( 'name' => 'Mutual RSA', 'mobile' => false ),
'pre_shared_key' => array( 'name' => 'Mutual PSK', 'mobile' => false ) );
global $ipsec_preshared_key_type;
$ipsec_preshared_key_type = array(
'PSK' => 'PSK',
'EAP' => 'EAP'
);
global $p2_modes;
$p2_modes = array(
'tunnel' => 'Tunnel IPv4',
'tunnel6' => 'Tunnel IPv6',
'transport' => 'Transport');
global $p2_protos;
$p2_protos = array(
'esp' => 'ESP',
'ah' => 'AH');
global $p2_pfskeygroups;
$p2_pfskeygroups = array(
0 => 'off',
1 => '1 (768 bit)',
@ -149,9 +167,11 @@ $p2_pfskeygroups = array(
function ipsec_ikeid_used($ikeid) {
global $config;
foreach ($config['ipsec']['phase1'] as $ph1ent)
if( $ikeid == $ph1ent['ikeid'] )
foreach ($config['ipsec']['phase1'] as $ph1ent) {
if ( $ikeid == $ph1ent['ikeid'] ) {
return true;
}
}
return false;
}
@ -159,8 +179,9 @@ function ipsec_ikeid_used($ikeid) {
function ipsec_ikeid_next() {
$ikeid = 1;
while(ipsec_ikeid_used($ikeid))
while (ipsec_ikeid_used($ikeid)) {
$ikeid++;
}
return $ikeid;
}
@ -172,20 +193,26 @@ function ipsec_get_phase1_src(& $ph1ent) {
if ($ph1ent['interface']) {
if (!is_ipaddr($ph1ent['interface'])) {
if ($ph1ent['protocol'] == "inet6") {
$interfaceip = get_interface_ipv6($ph1ent['interface']);
if (strpos($ph1ent['interface'], '_vip')) {
$if = $ph1ent['interface'];
} else {
$interfaceip = get_interface_ip($ph1ent['interface']);
$if = get_failover_interface($ph1ent['interface']);
}
if ($ph1ent['protocol'] == "inet6") {
$interfaceip = get_interface_ipv6($if);
} else {
$interfaceip = get_interface_ip($if);
}
} else {
$interfaceip=$ph1ent['interface'];
}
} else {
$if = "wan";
if ($ph1ent['protocol'] == "inet6")
if ($ph1ent['protocol'] == "inet6") {
$interfaceip = get_interface_ipv6($if);
else
} else {
$interfaceip = get_interface_ip($if);
}
}
return $interfaceip;
@ -197,15 +224,18 @@ function ipsec_get_phase1_src(& $ph1ent) {
function ipsec_get_phase1_dst(& $ph1ent) {
global $g;
if (empty($ph1ent['remote-gateway']))
if (empty($ph1ent['remote-gateway'])) {
return false;
}
$rg = $ph1ent['remote-gateway'];
if (!is_ipaddr($rg)) {
if(! platform_booting())
if (! platform_booting()) {
return resolve_retry($rg);
}
}
if(!is_ipaddr($rg))
if (!is_ipaddr($rg)) {
return false;
}
return $rg;
}
@ -219,10 +249,11 @@ function ipsec_idinfo_to_cidr(& $idinfo, $addrbits = false, $mode = "") {
switch ($idinfo['type']) {
case "address":
if ($addrbits) {
if ($mode == "tunnel6")
if ($mode == "tunnel6") {
return $idinfo['address']."/128";
else
} else {
return $idinfo['address']."/32";
}
} else
return $idinfo['address'];
break; /* NOTREACHED */
@ -234,8 +265,9 @@ function ipsec_idinfo_to_cidr(& $idinfo, $addrbits = false, $mode = "") {
return '0.0.0.0/0';
break; /* NOTREACHED */
default:
if (empty($mode) && !empty($idinfo['mode']))
if (empty($mode) && !empty($idinfo['mode'])) {
$mode = $idinfo['mode'];
}
if ($mode == "tunnel6") {
$address = get_interface_ipv6($idinfo['type']);
@ -261,10 +293,11 @@ function ipsec_idinfo_to_subnet(& $idinfo,$addrbits = false) {
switch ($idinfo['type']) {
case "address":
if ($addrbits) {
if ($idinfo['mode'] == "tunnel6")
if ($idinfo['mode'] == "tunnel6") {
return $idinfo['address']."/128";
else
} else {
return $idinfo['address']."/255.255.255.255";
}
} else
return $idinfo['address'];
break; /* NOTREACHED */
@ -298,24 +331,25 @@ function ipsec_idinfo_to_text(& $idinfo) {
global $config;
switch ($idinfo['type']) {
case "address":
return $idinfo['address'];
break; /* NOTREACHED */
case "network":
return $idinfo['address']."/".$idinfo['netbits'];
break; /* NOTREACHED */
case "mobile":
return gettext("Mobile Client");
break; /* NOTREACHED */
case "none":
return gettext("None");
break; /* NOTREACHED */
default:
if (!empty($config['interfaces'][$idinfo['type']]))
return convert_friendly_interface_to_friendly_descr($idinfo['type']);
else
return strtoupper($idinfo['type']);
break; /* NOTREACHED */
case "address":
return $idinfo['address'];
break; /* NOTREACHED */
case "network":
return $idinfo['address']."/".$idinfo['netbits'];
break; /* NOTREACHED */
case "mobile":
return gettext("Mobile Client");
break; /* NOTREACHED */
case "none":
return gettext("None");
break; /* NOTREACHED */
default:
if (!empty($config['interfaces'][$idinfo['type']])) {
return convert_friendly_interface_to_friendly_descr($idinfo['type']);
} else {
return strtoupper($idinfo['type']);
}
break; /* NOTREACHED */
}
}
@ -325,18 +359,21 @@ function ipsec_idinfo_to_text(& $idinfo) {
function ipsec_lookup_phase1(& $ph2ent,& $ph1ent) {
global $config;
if (!is_array($config['ipsec']))
if (!is_array($config['ipsec'])) {
return false;
if (!is_array($config['ipsec']['phase1']))
}
if (!is_array($config['ipsec']['phase1'])) {
return false;
if (empty($config['ipsec']['phase1']))
}
if (empty($config['ipsec']['phase1'])) {
return false;
}
foreach ($config['ipsec']['phase1'] as $ph1tmp) {
if ($ph1tmp['ikeid'] == $ph2ent['ikeid']) {
$ph1ent = $ph1tmp;
return $ph1ent;
}
if ($ph1tmp['ikeid'] == $ph2ent['ikeid']) {
$ph1ent = $ph1tmp;
return $ph1ent;
}
}
return false;
@ -349,8 +386,9 @@ function ipsec_phase1_status(&$ipsec_status, $ikeid) {
foreach ($ipsec_status as $ike) {
if ($ike['id'] == $ikeid) {
if ($ike['status'] == 'established')
if ($ike['status'] == 'established') {
return true;
}
}
}
@ -362,8 +400,9 @@ function ipsec_phase1_status(&$ipsec_status, $ikeid) {
*/
function ipsec_phase2_status(&$ipsec_status, &$phase2) {
if (ipsec_lookup_phase1($ph2ent,$ph1ent))
if (ipsec_lookup_phase1($ph2ent,$ph1ent)) {
return ipsec_phase1_status($ipsec_status, $ph1ent['ikeid']);
}
return false;
}
@ -388,8 +427,9 @@ function ipsec_smp_dump_status() {
$response = "";
while (!strstr($sread, "</message>")) {
$sread = fgets($fd);
if ($sread === false)
if ($sread === false) {
break;
}
$response .= $sread;
}
fclose($fd);
@ -420,13 +460,16 @@ function ipsec_dump_spd()
if ($fd) {
while (!feof($fd)) {
$line = chop(fgets($fd));
if (!$line)
if (!$line) {
continue;
if ($line == "No SPD entries.")
}
if ($line == "No SPD entries.") {
break;
}
if ($line[0] != "\t") {
if (is_array($cursp))
if (is_array($cursp)) {
$spd[] = $cursp;
}
$cursp = array();
$linea = explode(" ", $line);
$cursp['srcid'] = substr($linea[0], 0, strpos($linea[0], "["));
@ -435,13 +478,13 @@ function ipsec_dump_spd()
} else if (is_array($cursp)) {
$line = trim($line, "\t\r\n ");
$linea = explode(" ", $line);
switch($i)
{
switch ($i) {
case 1:
if ($linea[1] == "none") /* don't show default anti-lockout rule */
if ($linea[1] == "none") /* don't show default anti-lockout rule */ {
unset($cursp);
else
} else {
$cursp['dir'] = $linea[0];
}
break;
case 2:
$upperspec = explode("/", $linea[0]);
@ -453,8 +496,9 @@ function ipsec_dump_spd()
}
$i++;
}
if (is_array($cursp) && count($cursp))
if (is_array($cursp) && count($cursp)) {
$spd[] = $cursp;
}
pclose($fd);
}
@ -471,29 +515,29 @@ function ipsec_dump_sad()
if ($fd) {
while (!feof($fd)) {
$line = chop(fgets($fd));
if (!$line || $line[0] == " ")
if (!$line || $line[0] == " ") {
continue;
if ($line == "No SAD entries.")
}
if ($line == "No SAD entries.") {
break;
if ($line[0] != "\t")
{
if (is_array($cursa))
}
if ($line[0] != "\t") {
if (is_array($cursa)) {
$sad[] = $cursa;
}
$cursa = array();
list($cursa['src'],$cursa['dst']) = explode(" ", $line);
}
else
{
} else {
$line = trim($line, "\t\n\r ");
$linea = explode(" ", $line);
foreach ($linea as $idx => $linee) {
if ($linee == 'esp' || $linee == 'ah' || $linee[0] == '#')
if ($linee == 'esp' || $linee == 'ah' || $linee[0] == '#') {
$cursa['proto'] = $linee;
else if (substr($linee, 0, 3) == 'spi')
} else if (substr($linee, 0, 3) == 'spi') {
$cursa['spi'] = substr($linee, strpos($linee, 'x') + 1, -1);
else if (substr($linee, 0, 5) == 'reqid')
} else if (substr($linee, 0, 5) == 'reqid') {
$cursa['reqid'] = substr($linee, strpos($linee, 'x') + 1, -1);
else if (substr($linee, 0, 2) == 'E:') {
} else if (substr($linee, 0, 2) == 'E:') {
$cursa['ealgo'] = $linea[$idx + 1];
break;
} else if (substr($linee, 0, 2) == 'A:') {
@ -503,12 +547,12 @@ function ipsec_dump_sad()
$cursa['data'] = substr($linea[$idx + 1], 0, strpos($linea[$idx + 1], 'bytes') - 1) . ' B';
break;
}
}
}
}
if (is_array($cursa) && count($cursa))
if (is_array($cursa) && count($cursa)) {
$sad[] = $cursa;
}
pclose($fd);
}
@ -529,8 +573,9 @@ function ipsec_dump_mobile() {
}
/* This is needed for fixing #4130 */
if (filesize("{$g['tmp_path']}/strongswan_leases.xml") < 200)
if (filesize("{$g['tmp_path']}/strongswan_leases.xml") < 200) {
return array();
}
$custom_listtags = array('lease', 'pool');
$response = parse_xml_config("{$g['tmp_path']}/strongswan_leases.xml", "leases");
@ -552,13 +597,13 @@ function ipsec_mobilekey_sort() {
function ipsec_get_number_of_phase2($ikeid) {
global $config;
$a_phase2 = $config['ipsec']['phase2'];
$a_phase2 = $config['ipsec']['phase2'];
$nbph2=0;
if (is_array($a_phase2) && count($a_phase2)) {
foreach ($a_phase2 as $ph2tmp) {
if ($ph2tmp['ikeid'] == $ikeid) {
if (is_array($a_phase2) && count($a_phase2)) {
foreach ($a_phase2 as $ph2tmp) {
if ($ph2tmp['ikeid'] == $ikeid) {
$nbph2++;
}
}
@ -571,8 +616,9 @@ function ipsec_get_descr($ikeid) {
global $config;
if (!isset($config['ipsec']['phase1']) ||
!is_array($config['ipsec']['phase1']))
!is_array($config['ipsec']['phase1'])) {
return '';
}
foreach ($config['ipsec']['phase1'] as $p1) {
if ($p1['ikeid'] == $ikeid) {
@ -584,26 +630,28 @@ function ipsec_get_descr($ikeid) {
}
function ipsec_get_phase1($ikeid) {
global $config;
global $config;
if (!isset($config['ipsec']['phase1']) ||
!is_array($config['ipsec']['phase1']))
return '';
if (!isset($config['ipsec']['phase1']) ||
!is_array($config['ipsec']['phase1'])) {
return '';
}
$a_phase1 = $config['ipsec']['phase1'];
foreach ($a_phase1 as $p1) {
if ($p1['ikeid'] == $ikeid) {
return $p1;
}
}
unset($a_phase1);
$a_phase1 = $config['ipsec']['phase1'];
foreach ($a_phase1 as $p1) {
if ($p1['ikeid'] == $ikeid) {
return $p1;
}
}
unset($a_phase1);
}
function ipsec_fixup_ip($ipaddr) {
if (is_ipaddrv6($ipaddr) || is_subnetv6($ipaddr))
if (is_ipaddrv6($ipaddr) || is_subnetv6($ipaddr)) {
return Net_IPv6::compress(Net_IPv6::uncompress($ipaddr));
else
} else {
return $ipaddr;
}
}
function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array()) {
@ -612,65 +660,71 @@ function ipsec_find_id(& $ph1ent, $side = "local", $rgmap = array()) {
$id_data = $ph1ent['myid_data'];
$addr = ipsec_get_phase1_src($ph1ent);
if (!$addr)
if (!$addr) {
return array();
} elseif ($side = "peer") {
}
} elseif ($side == "peer") {
$id_type = $ph1ent['peerid_type'];
$id_data = $ph1ent['peerid_data'];
if (isset($ph1ent['mobile']))
if (isset($ph1ent['mobile'])) {
$addr = "%any";
else
} else {
$addr = $ph1ent['remote-gateway'];
} else
}
} else {
return array();
}
$thisid_type = $id_type;
switch ($thisid_type) {
case 'myaddress':
$thisid_type = 'address';
$thisid_data = $addr;
break;
case 'dyn_dns':
$thisid_type = 'dns';
$thisid_data = $id_data;
break;
case 'peeraddress':
$thisid_type = 'address';
$thisid_data = $rgmap[$ph1ent['remote-gateway']];
break;
case 'address':
$thisid_data = $id_data;
break;
case 'fqdn':
$thisid_data = "{$id_data}";
break;
case 'keyid tag':
$thisid_type = 'keyid';
$thisid_data = "{$thisid_data}";
break;
case 'user_fqdn':
$thisid_type = 'userfqdn';
$thisid_data = "{$id_data}";
break;
case 'asn1dn':
$thisid_data = $id_data;
$thisid_data = "{$id_data}";
break;
case 'myaddress':
$thisid_type = 'address';
$thisid_data = $addr;
break;
case 'dyn_dns':
$thisid_type = 'dns';
$thisid_data = $id_data;
break;
case 'peeraddress':
$thisid_type = 'address';
$thisid_data = $rgmap[$ph1ent['remote-gateway']];
break;
case 'address':
$thisid_data = $id_data;
break;
case 'fqdn':
$thisid_data = "{$id_data}";
break;
case 'keyid tag':
$thisid_type = 'keyid';
$thisid_data = "{$thisid_data}";
break;
case 'user_fqdn':
$thisid_type = 'userfqdn';
$thisid_data = "{$id_data}";
break;
case 'asn1dn':
$thisid_data = $id_data;
if ($thisid_data && $thisid_data[0] != '"') {
$thisid_data = "\"{$id_data}\"";
}
break;
}
return array($thisid_type, $thisid_data);
}
function ipsec_fixup_network($network) {
if (substr($network, -3) == '|/0')
if (substr($network, -3) == '|/0') {
$result = substr($network, 0, -3);
else {
} else {
$tmp = explode('|', $network);
if (isset($tmp[1]))
if (isset($tmp[1])) {
$result = $tmp[1];
else
} else {
$result = $tmp[0];
}
unset($tmp);
}
@ -680,14 +734,16 @@ function ipsec_fixup_network($network) {
function ipsec_new_reqid() {
global $config;
if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2']))
if (!is_array($config['ipsec']) || !is_array($config['ipsec']['phase2'])) {
return;
}
$ipsecreqid = lock('ipsecreqids', LOCK_EX);
$keyids = array();
$keyid = 1;
foreach ($config['ipsec']['phase2'] as $ph2)
foreach ($config['ipsec']['phase2'] as $ph2) {
$keyids[$ph2['reqid']] = $ph2['reqid'];
}
for ($i = 1; $i < 16000; $i++) {
if (!isset($keyids[$i])) {

View File

@ -5,29 +5,29 @@
*/
/*
Copyright (C) 2009 Janne Enberg <janne.enberg@lietu.net>
All rights reserved.
Copyright (C) 2009 Janne Enberg <janne.enberg@lietu.net>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
@ -40,24 +40,25 @@
* RESULT
* boolean - true if item was found and deleted
******/
function delete_id($id, &$array){
function delete_id($id, &$array) {
// Index to delete
$delete_index = NULL;
if (!is_array($array))
if (!is_array($array)) {
return false;
}
// Search for the item in the array
foreach ($array as $key => $item){
foreach ($array as $key => $item) {
// If this item is the one we want to delete
if(isset($item['associated-rule-id']) && $item['associated-rule-id']==$id ){
if (isset($item['associated-rule-id']) && $item['associated-rule-id']==$id ) {
$delete_index = $key;
break;
}
}
// If we found the item, unset it
if( $delete_index!==NULL ){
if ($delete_index!==NULL) {
unset($array[$delete_index]);
return true;
} else {
@ -78,14 +79,16 @@ function delete_id($id, &$array){
function get_id($id, &$array) {
// Use $foo = &get_id('id', array('id'=>'value'));
if (!is_array($array))
if (!is_array($array)) {
return false;
}
// Search for the item in the array
foreach ($array as $key => $item){
foreach ($array as $key => $item) {
// If this item is the one we want to delete
if (isset($item['associated-rule-id']) && $item['associated-rule-id']==$id)
if (isset($item['associated-rule-id']) && $item['associated-rule-id']==$id) {
return $key;
}
}
return false;
@ -97,7 +100,7 @@ function get_id($id, &$array) {
* RESULT
* string - unique id
******/
function get_unique_id(){
function get_unique_id() {
return uniqid("nat_", true);
}

View File

@ -84,8 +84,9 @@ function led_digit($led, $digitstring) {
$dstring = "d";
while ($i < strlen($digitstring)) {
$thisdigit = substr($digitstring, $i++, 1);
if (is_numeric($thisdigit))
if (is_numeric($thisdigit)) {
$dstring .= $thisdigit;
}
}
led_ctl($led, $dstring);
}
@ -123,8 +124,9 @@ function led_count() {
*/
function led_exists($led) {
global $led_root;
if (!is_numeric($led))
if (!is_numeric($led)) {
return false;
}
return file_exists("{$led_root}{$led}");
}

View File

@ -23,7 +23,7 @@ class login_sasl_client_class
Function Start(&$client, &$message, &$interactions)
{
if($this->state!=SASL_LOGIN_STATE_START)
if ($this->state!=SASL_LOGIN_STATE_START)
{
$client->error="LOGIN authentication state is not at the start";
return(SASL_FAIL);
@ -37,7 +37,7 @@ class login_sasl_client_class
"realm"=>""
);
$status=$client->GetCredentials($this->credentials,$defaults,$interactions);
if($status==SASL_CONTINUE)
if ($status==SASL_CONTINUE)
$this->state=SASL_LOGIN_STATE_IDENTIFY_USER;
Unset($message);
return($status);
@ -45,7 +45,7 @@ class login_sasl_client_class
Function Step(&$client, $response, &$message, &$interactions)
{
switch($this->state)
switch ($this->state)
{
case SASL_LOGIN_STATE_IDENTIFY_USER:
$message=$this->credentials["user"].(strlen($this->credentials["realm"]) ? "@".$this->credentials["realm"] : "");

View File

@ -33,7 +33,7 @@
* followed by the appropriate value or value pair. All markers
* are prefixed with a ##| sequence. The + suffix is used to
* denote the beginning of a tag block followed by the tag name.
* A - suffix is used to denote the end of a tag blaock. Values
* A - suffix is used to denote the end of a tag block. Values
* are denoted using the * suffix and can optionally be expressed
* as a key value pair. An example of a metadata tag block ...
*
@ -48,7 +48,7 @@
* metadata['<filename>']['INFO']['BLAH'][0] == true
* metadata['<filename>']['INFO']['TEXT'][0] == "SOME TEXT"
*
* NOTE: All statements must be at the begining of a line and
* NOTE: All statements must be at the beginning of a line and
* contiguous for a tag. The example shown above would not be
* processed due to the extra ' * ' comment chars.
*
@ -60,8 +60,9 @@
function list_phpfiles($path, & $found) {
if (!is_array($found))
if (!is_array($found)) {
$found = array();
}
$dir = opendir($path);
if (!$dir) {
@ -69,11 +70,13 @@ function list_phpfiles($path, & $found) {
return;
}
while($fname = readdir($dir)) {
if($fname == "." || $fname == ".." || $fname[0] == '.')
while ($fname = readdir($dir)) {
if ($fname == "." || $fname == ".." || $fname[0] == '.') {
continue;
if (fnmatch('*.php', $fname))
}
if (fnmatch('*.php', $fname)) {
$found[] = $fname;
}
}
}
@ -83,16 +86,19 @@ function list_phpfiles($path, & $found) {
function read_file_metadata($fpath, & $metadata, $taglist = false) {
if (!is_array($metadata))
if (!is_array($metadata)) {
$metadata = array();
}
if ($taglist)
if ($taglist) {
$taglist = explode(",", $taglist);
}
$fname = $fpath;
$slash = strrpos($fname,"/");
if ($slash)
if ($slash) {
$fname = substr($fname,$slash + 1);
}
$fdata = @file_get_contents($fpath);
if (!$fdata) {
@ -107,20 +113,24 @@ function read_file_metadata($fpath, & $metadata, $taglist = false) {
while (true) {
$tagbeg_off = stripos($fdata, "##|+", $offset);
if ($tagbeg_off === false)
if ($tagbeg_off === false) {
break;
}
$tagbeg_trm = stripos($fdata, "\n", $tagbeg_off);
if ($tagbeg_trm === false)
if ($tagbeg_trm === false) {
break;
}
$tagend_off = stripos($fdata, "##|-", $tagbeg_trm);
if ($tagend_off === false)
if ($tagend_off === false) {
break;
}
$tagend_trm = stripos($fdata, "\n", $tagend_off);
if ($tagend_trm === false)
if ($tagend_trm === false) {
break;
}
$tagbeg_len = $tagbeg_trm - $tagbeg_off;
$tagend_len = $tagend_trm - $tagend_off;
@ -146,17 +156,20 @@ function read_file_metadata($fpath, & $metadata, $taglist = false) {
$offset = $tagend_trm + 1;
if (is_array($taglist))
if (!in_array($tagbeg,$taglist))
if (is_array($taglist)) {
if (!in_array($tagbeg,$taglist)) {
continue;
}
}
$vals = array();
$lines = explode("\n",$mdata);
foreach ($lines as $line) {
if (!strlen($line))
if (!strlen($line)) {
continue;
}
$valtag = stripos($line, "##|*");
if ($valtag === false || $valtag) {
@ -189,12 +202,14 @@ function read_file_metadata($fpath, & $metadata, $taglist = false) {
$vals[$vname][] = $vdata;
}
if (count($vals))
if (count($vals)) {
$tags[$tagbeg] = $vals;
}
}
if (count($tags))
if (count($tags)) {
$metadata[$fname] = $tags;
}
}
?>

View File

@ -1,37 +1,35 @@
<?php
/****h* pfSense/notices
* NAME
* notices.inc - pfSense notice utilities
* DESCRIPTION
* This include contains the pfSense notice facilities.
* HISTORY
* $Id$
******
*
* Copyright (C) 2009 Scott Ullrich (sullrich@gmail.com)
* Copyright (C) 2005 Colin Smith (ethethlay@gmail.com)
* 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)
* RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
NAME
notices.inc - pfSense notice utilities
DESCRIPTION
This include contains the pfSense notice facilities.
HISTORY
$Id$
Copyright (C) 2009 Scott Ullrich (sullrich@gmail.com)
Copyright (C) 2005 Colin Smith (ethethlay@gmail.com)
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)
RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*
@ -43,6 +41,16 @@ require_once("globals.inc");
require_once("led.inc");
$notice_path = $g['tmp_path'] . '/notices';
$smtp_authentication_mechanisms = array(
'PLAIN' => 'PLAIN',
'LOGIN' => 'LOGIN');
/* Other SMTP Authentication Mechanisms that could be supported.
* Note that MD5 is no longer considered secure.
* 'GSSAPI' => 'GSSAPI ' . gettext("Generic Security Services Application Program Interface")
* 'DIGEST-MD5' => 'DIGEST-MD5 ' . gettext("Digest access authentication")
* 'MD5' => 'MD5'
* 'CRAM-MD5' => 'CRAM-MD5'
*/
/****f* notices/file_notice
* NAME
@ -61,7 +69,9 @@ function file_notice($id, $notice, $category = "General", $url = "", $priority =
* 0 = informational, 1 = warning, 2 = error, etc. This may also be arbitrary,
*/
global $notice_path;
if(!$queue = get_notices()) $queue = array();
if (!$queue = get_notices()) {
$queue = array();
}
$queuekey = time();
$toqueue = array(
'id' => $id,
@ -72,7 +82,7 @@ function file_notice($id, $notice, $category = "General", $url = "", $priority =
);
$queue[$queuekey] = $toqueue;
$queueout = fopen($notice_path, "w");
if(!$queueout) {
if (!$queueout) {
log_error(printf(gettext("Could not open %s for writing"), $notice_path));
return;
}
@ -80,8 +90,9 @@ function file_notice($id, $notice, $category = "General", $url = "", $priority =
fclose($queueout);
log_error("New alert found: $notice");
/* soekris */
if(file_exists("/dev/led/error"))
if (file_exists("/dev/led/error")) {
exec("/bin/echo 1 > /dev/led/error");
}
/* wrap & alix */
led_normalize();
led_morse(1, 'sos');
@ -101,13 +112,16 @@ function file_notice($id, $notice, $category = "General", $url = "", $priority =
function get_notices($category = "all") {
global $g;
if(file_exists("{$g['tmp_path']}/notices")) {
if (file_exists("{$g['tmp_path']}/notices")) {
$queue = unserialize(file_get_contents("{$g['tmp_path']}/notices"));
if(!$queue) return false;
if($category != 'all') {
foreach($queue as $time => $notice) {
if(strtolower($notice['category']) == strtolower($category))
if (!$queue) {
return false;
}
if ($category != 'all') {
foreach ($queue as $time => $notice) {
if (strtolower($notice['category']) == strtolower($category)) {
$toreturn[$time] = $notice;
}
}
return $toreturn;
} else {
@ -130,35 +144,38 @@ function close_notice($id) {
global $notice_path;
require_once("util.inc");
/* soekris */
if(file_exists("/dev/led/error"))
if (file_exists("/dev/led/error")) {
exec("/bin/echo 0 > /dev/led/error");
}
/* wrap & alix */
led_normalize();
$ids = array();
if(!$notices = get_notices()) return;
if($id == "all") {
if (!$notices = get_notices()) {
return;
}
if ($id == "all") {
unlink_if_exists($notice_path);
return;
}
foreach(array_keys($notices) as $time) {
if($id == $time) {
foreach (array_keys($notices) as $time) {
if ($id == $time) {
unset($notices[$id]);
break;
}
}
foreach($notices as $key => $notice) {
foreach ($notices as $key => $notice) {
$ids[$key] = $notice['id'];
}
foreach($ids as $time => $tocheck) {
if($id == $tocheck) {
foreach ($ids as $time => $tocheck) {
if ($id == $tocheck) {
unset($notices[$time]);
break;
}
}
if(count($notices) != 0) {
if (count($notices) != 0) {
$queueout = fopen($notice_path, "w");
fwrite($queueout, serialize($notices));
fclose($queueout);
fwrite($queueout, serialize($notices));
fclose($queueout);
} else {
unlink_if_exists($notice_path);
}
@ -175,14 +192,17 @@ function close_notice($id) {
* Outputs notices in XML formatted text
******/
function dump_xml_notices() {
if(file_exists("/cf/conf/use_xmlreader"))
if (file_exists("/cf/conf/use_xmlreader")) {
require_once("xmlreader.inc");
else
} else {
require_once("xmlparse.inc");
}
global $notice_path, $listtags;
$listtags[] = 'notice';
if(!$notices = get_notices()) return;
foreach($notices as $time => $notice) {
if (!$notices = get_notices()) {
return;
}
foreach ($notices as $time => $notice) {
$notice['time'] = $time;
$toput['notice'][] = $notice;
}
@ -190,6 +210,44 @@ function dump_xml_notices() {
return $xml;
}
/****f* notices/print_notices
* NAME
* print_notices
* INPUTS
* $notices, $category
* RESULT
* prints notices to the GUI
******/
function print_notices($notices, $category = "all") {
foreach ($notices as $notice) {
if ($category != "all") {
if (in_array($notice['category'], $category)) {
$categories[] = $notice['category'];
}
} else {
$categories[] = $notice['category'];
}
}
$categories = array_unique($categories);
sort($categories);
foreach ($categories as $category) {
$toreturn .= "<ul><li>{$category}<ul>";
foreach ($notices as $notice) {
if (strtolower($notice['category']) == strtolower($category)) {
if ($notice['id'] != "") {
if ($notice['url'] != "") {
$toreturn .= "<li><a href={$notice['url']}>{$notice['id']}</a> - {$notice['notice']}</li>";
} else {
$toreturn .= "<li>{$notice['id']} - {$notice['notice']}</li>";
}
}
}
}
$toreturn .= "</ul></li></ul>";
}
return $toreturn;
}
/****f* notices/print_notice_box
* NAME
* print_notice_box
@ -200,7 +258,9 @@ function dump_xml_notices() {
******/
function print_notice_box($category = "all") {
$notices = get_notices();
if(!$notices) return;
if (!$notices) {
return;
}
print_info_box_np(print_notices($notices, $category));
return;
}
@ -215,7 +275,7 @@ function print_notice_box($category = "all") {
******/
function are_notices_pending($category = "all") {
global $notice_path;
if(file_exists($notice_path)) {
if (file_exists($notice_path)) {
return true;
}
return false;
@ -231,17 +291,20 @@ function are_notices_pending($category = "all") {
******/
function notify_via_smtp($message, $force = false) {
global $config, $g;
if(platform_booting())
if (platform_booting()) {
return;
}
if(isset($config['notifications']['smtp']['disable']) && !$force)
if (isset($config['notifications']['smtp']['disable']) && !$force) {
return;
}
/* Do NOT send the same message twice */
if(file_exists("/var/db/notices_lastmsg.txt")) {
if (file_exists("/var/db/notices_lastmsg.txt")) {
$lastmsg = trim(file_get_contents("/var/db/notices_lastmsg.txt"));
if($lastmsg == $message)
if ($lastmsg == $message) {
return;
}
}
/* Store last message sent to avoid spamming */
@ -249,20 +312,26 @@ function notify_via_smtp($message, $force = false) {
fwrite($fd, $message);
fclose($fd);
send_smtp_message($message, "{$config['system']['hostname']}.{$config['system']['domain']} - Notification");
send_smtp_message($message, "{$config['system']['hostname']}.{$config['system']['domain']} - Notification", $force);
return;
}
function send_smtp_message($message, $subject = "(no subject)") {
function send_smtp_message($message, $subject = "(no subject)", $force = false) {
global $config, $g;
require_once("sasl.inc");
require_once("smtp.inc");
if(!$config['notifications']['smtp']['ipaddress'])
if (isset($config['notifications']['smtp']['disable']) && !$force) {
return;
}
if(!$config['notifications']['smtp']['notifyemailaddress'])
if (!$config['notifications']['smtp']['ipaddress']) {
return;
}
if (!$config['notifications']['smtp']['notifyemailaddress']) {
return;
}
$smtp = new smtp_class;
@ -279,13 +348,18 @@ function send_smtp_message($message, $subject = "(no subject)") {
$smtp->html_debug = 0;
$smtp->localhost=$config['system']['hostname'].".".$config['system']['domain'];
if($config['notifications']['smtp']['fromaddress'])
if ($config['notifications']['smtp']['fromaddress']) {
$from = $config['notifications']['smtp']['fromaddress'];
}
// Use SMTP Auth if fields are filled out
if($config['notifications']['smtp']['username'] &&
$config['notifications']['smtp']['password']) {
$smtp->authentication_mechanism = "PLAIN";
if ($config['notifications']['smtp']['username'] &&
$config['notifications']['smtp']['password']) {
if (isset($config['notifications']['smtp']['authentication_mechanism'])) {
$smtp->authentication_mechanism = $config['notifications']['smtp']['authentication_mechanism'];
} else {
$smtp->authentication_mechanism = "PLAIN";
}
$smtp->user = $config['notifications']['smtp']['username'];
$smtp->password = $config['notifications']['smtp']['password'];
}
@ -297,7 +371,7 @@ function send_smtp_message($message, $subject = "(no subject)") {
"Date: ".date("r")
);
if($smtp->SendMessage($from, preg_split('/\s*,\s*/', trim($to)), $headers, $message)) {
if ($smtp->SendMessage($from, preg_split('/\s*,\s*/', trim($to)), $headers, $message)) {
log_error(sprintf(gettext("Message sent to %s OK"), $to));
return;
} else {
@ -318,14 +392,16 @@ function notify_via_growl($message, $force=false) {
require_once("growl.class");
global $config,$g;
if (isset($config['notifications']['growl']['disable']) && !$force)
if (isset($config['notifications']['growl']['disable']) && !$force) {
return;
}
/* Do NOT send the same message twice */
if(file_exists("/var/db/growlnotices_lastmsg.txt")) {
if (file_exists("/var/db/growlnotices_lastmsg.txt")) {
$lastmsg = trim(file_get_contents("/var/db/growlnotices_lastmsg.txt"));
if($lastmsg == $message)
if ($lastmsg == $message) {
return;
}
}
$hostname = $config['system']['hostname'] . "." . $config['system']['domain'];
@ -334,7 +410,7 @@ function notify_via_growl($message, $force=false) {
$growl_name = $config['notifications']['growl']['name'];
$growl_notification = $config['notifications']['growl']['notification_name'];
if(!empty($growl_ip)) {
if (!empty($growl_ip)) {
$growl = new Growl($growl_ip, $growl_password, $growl_name);
$growl->notify("{$growl_notification}", gettext(sprintf("%s (%s) - Notification", $g['product_name'], $hostname)), "{$message}");
}
@ -361,8 +437,8 @@ function register_via_growl() {
$growl_name = $config['notifications']['growl']['name'];
$growl_notification = $config['notifications']['growl']['notification_name'];
if($growl_ip) {
$growl = new Growl($growl_ip, $growl_password, $growl_name);
if ($growl_ip) {
$growl = new Growl($growl_ip, $growl_password, $growl_name);
$growl->addNotification($growl_notification);
$growl->register();
}

View File

@ -18,12 +18,12 @@ class ntlm_sasl_client_class
Function Initialize(&$client)
{
if(!function_exists($function="mcrypt_encrypt")
|| !function_exists($function="hash"))
if (!function_exists($function="mcrypt_encrypt") ||
!function_exists($function="hash"))
{
$extensions=array(
"mcrypt_encrypt"=>"mcrypt",
"hash"=>"hash"
"hash"=>"hash"
);
$client->error="the extension ".$extensions[$function]." required by the NTLM SASL client class is not available in this PHP configuration";
return(0);
@ -33,7 +33,7 @@ class ntlm_sasl_client_class
Function ASCIIToUnicode($ascii)
{
for($unicode="",$a=0;$a<strlen($ascii);$a++)
for ($unicode="",$a=0;$a<strlen($ascii);$a++)
$unicode.=substr($ascii,$a,1).chr(0);
return($unicode);
}
@ -62,15 +62,15 @@ class ntlm_sasl_client_class
Function NTLMResponse($challenge,$password)
{
$unicode=$this->ASCIIToUnicode($password);
$md4=hash("md4", $unicode);
$md4=hash("md4", $unicode);
$padded=$md4.str_repeat(chr(0),21-strlen($md4));
$iv_size=mcrypt_get_iv_size(MCRYPT_DES,MCRYPT_MODE_ECB);
$iv=mcrypt_create_iv($iv_size,MCRYPT_RAND);
for($response="",$third=0;$third<21;$third+=7)
for ($response="",$third=0;$third<21;$third+=7)
{
for($packed="",$p=$third;$p<$third+7;$p++)
$packed.=str_pad(decbin(ord(substr($padded,$p,1))),8,"0",STR_PAD_LEFT);
for($key="",$p=0;$p<strlen($packed);$p+=7)
for ($packed="",$p=$third;$p<$third+7;$p++)
$packed.=str_pad(decbin(ord(substr($padded,$p,1))),8,"0",STR_PAD_LEFT);
for ($key="",$p=0;$p<strlen($packed);$p+=7)
{
$s=substr($packed,$p,7);
$b=$s.((substr_count($s,"1") % 2) ? "0" : "1");
@ -134,7 +134,7 @@ class ntlm_sasl_client_class
Function Start(&$client, &$message, &$interactions)
{
if($this->state!=SASL_NTLM_STATE_START)
if ($this->state!=SASL_NTLM_STATE_START)
{
$client->error="NTLM authentication state is not at the start";
return(SASL_FAIL);
@ -147,7 +147,7 @@ class ntlm_sasl_client_class
);
$defaults=array();
$status=$client->GetCredentials($this->credentials,$defaults,$interactions);
if($status==SASL_CONTINUE)
if ($status==SASL_CONTINUE)
$this->state=SASL_NTLM_STATE_IDENTIFY_DOMAIN;
Unset($message);
return($status);
@ -155,7 +155,7 @@ class ntlm_sasl_client_class
Function Step(&$client, $response, &$message, &$interactions)
{
switch($this->state)
switch ($this->state)
{
case SASL_NTLM_STATE_IDENTIFY_DOMAIN:
$message=$this->TypeMsg1($this->credentials["realm"],$this->credentials["workstation"]);

View File

@ -1,7 +1,7 @@
<?php
/*
openvpn.attributes.php
Copyright (C) 2011-2012 Ermal Luçi
Copyright (C) 2011-2012 Ermal Luçi
Copyright (C) 2013-2015 Electric Sheep Fencing, LP
All rights reserved.
@ -29,17 +29,20 @@
if (empty($common_name)) {
$common_name = getenv("common_name");
if (empty($common_name))
if (empty($common_name)) {
$common_name = getenv("username");
}
}
$devname = getenv("dev");
if (empty($devname))
if (empty($devname)) {
$devname = "openvpn";
}
function cisco_to_cidr($addr) {
if (!is_ipaddr($addr))
if (!is_ipaddr($addr)) {
return 0;
}
$mask = decbin(~ip2long($addr));
$mask = substr($mask, -32);
$k = 0;
@ -50,19 +53,21 @@ function cisco_to_cidr($addr) {
}
function cisco_extract_index($prule) {
$index = explode("#", $prule);
if (is_numeric($index[1]))
if (is_numeric($index[1])) {
return intval($index[1]);
else
} else {
syslog(LOG_WARNING, "Error parsing rule {$prule}: Could not extract index");
}
return -1;;
}
function parse_cisco_acl($attribs) {
global $devname, $attributes;
if (!is_array($attribs))
if (!is_array($attribs)) {
return "";
}
$finalrules = "";
if (is_array($attribs['ciscoavpair'])) {
$inrules = array();
@ -72,29 +77,31 @@ function parse_cisco_acl($attribs) {
$dir = "";
if (strstr($rule[0], "inacl")) {
$dir = "in";
} else if (strstr($rule[0], "outacl"))
} else if (strstr($rule[0], "outacl")) {
$dir = "out";
else if (strstr($rule[0], "dns-servers")) {
} else if (strstr($rule[0], "dns-servers")) {
$attributes['dns-servers'] = explode(" ", $rule[1]);
continue;
} else if (strstr($rule[0], "route")) {
if (!is_array($attributes['routes']))
if (!is_array($attributes['routes'])) {
$attributes['routes'] = array();
}
$attributes['routes'][] = $rule[1];
continue;
}
}
$rindex = cisco_extract_index($rule[0]);
if ($rindex < 0)
if ($rindex < 0) {
continue;
}
$rule = $rule[1];
$rule = explode(" ", $rule);
$tmprule = "";
$index = 0;
$isblock = false;
if ($rule[$index] == "permit")
if ($rule[$index] == "permit") {
$tmprule = "pass {$dir} quick on {$devname} ";
else if ($rule[$index] == "deny") {
} else if ($rule[$index] == "deny") {
//continue;
$isblock = true;
$tmprule = "block {$dir} quick on {$devname} ";
@ -105,11 +112,10 @@ function parse_cisco_acl($attribs) {
$index++;
switch ($rule[$index]) {
case "tcp":
case "udp":
$tmprule .= "proto {$rule[$index]} ";
break;
case "tcp":
case "udp":
$tmprule .= "proto {$rule[$index]} ";
break;
}
$index++;
@ -118,8 +124,9 @@ function parse_cisco_acl($attribs) {
$index++;
$tmprule .= "from {$rule[$index]} ";
$index++;
if ($isblock == true)
if ($isblock == true) {
$isblock = false;
}
} else if (trim($rule[$index]) == "any") {
$tmprule .= "from any";
$index++;
@ -129,16 +136,18 @@ function parse_cisco_acl($attribs) {
$netmask = cisco_to_cidr($rule[$index]);
$tmprule .= "/{$netmask} ";
$index++;
if ($isblock == true)
if ($isblock == true) {
$isblock = false;
}
}
/* Destination */
if (trim($rule[$index]) == "host") {
$index++;
$tmprule .= "to {$rule[$index]} ";
$index++;
if ($isblock == true)
if ($isblock == true) {
$isblock = false;
}
} else if (trim($rule[$index]) == "any") {
$index++;
$tmprule .= "to any";
@ -148,30 +157,36 @@ function parse_cisco_acl($attribs) {
$netmask = cisco_to_cidr($rule[$index]);
$tmprule .= "/{$netmask} ";
$index++;
if ($isblock == true)
if ($isblock == true) {
$isblock = false;
}
}
if ($isblock == true)
if ($isblock == true) {
continue;
}
if ($dir == "in")
if ($dir == "in") {
$inrules[$rindex] = $tmprule;
else if ($dir == "out")
} else if ($dir == "out") {
$outrules[$rindex] = $tmprule;
}
}
$state = "";
if (!empty($outrules))
if (!empty($outrules)) {
$state = "no state";
}
ksort($inrules, SORT_NUMERIC);
foreach ($inrules as $inrule)
foreach ($inrules as $inrule) {
$finalrules .= "{$inrule} {$state}\n";
}
if (!empty($outrules)) {
ksort($outrules, SORT_NUMERIC);
foreach ($outrules as $outrule)
foreach ($outrules as $outrule) {
$finalrules .= "{$outrule} {$state}\n";
}
}
}
return $finalrules;

View File

@ -32,7 +32,7 @@
*/
/*
pfSense_BUILDER_BINARIES:
pfSense_BUILDER_BINARIES:
pfSense_MODULE: openvpn
*/
/*
@ -55,12 +55,13 @@ require_once("interfaces.inc");
if (!function_exists("getNasID")) {
function getNasID()
{
global $g;
global $g;
$nasId = gethostname();
if(empty($nasId))
$nasId = $g['product_name'];
return $nasId;
$nasId = gethostname();
if (empty($nasId)) {
$nasId = $g['product_name'];
}
return $nasId;
}
}
@ -73,18 +74,19 @@ function getNasID()
if (!function_exists("getNasIP")) {
function getNasIP()
{
$nasIp = get_interface_ip();
if(!$nasIp)
$nasIp = "0.0.0.0";
return $nasIp;
$nasIp = get_interface_ip();
if (!$nasIp) {
$nasIp = "0.0.0.0";
}
return $nasIp;
}
}
/* setup syslog logging */
openlog("openvpn", LOG_ODELAY, LOG_AUTH);
if (isset($_GET)) {
if (isset($_GET['username'])) {
$authmodes = explode(",", $_GET['authcfg']);
$username = $_GET['username'];
$username = base64_decode(str_replace('%3D', '=', $_GET['username']));
$password = base64_decode(str_replace('%3D', '=', $_GET['password']));
$common_name = $_GET['cn'];
$modeid = $_GET['modeid'];
@ -98,7 +100,7 @@ if (isset($_GET)) {
if (!$username || !$password) {
syslog(LOG_ERR, "invalid user authentication environment");
if (isset($_GET)) {
if (isset($_GET['username'])) {
echo "FAILED";
closelog();
return;
@ -108,7 +110,7 @@ if (!$username || !$password) {
}
}
/* Replaced by a sed with propper variables used below(ldap parameters). */
/* Replaced by a sed with proper variables used below(ldap parameters). */
//<template>
if (file_exists("{$g['varetc_path']}/openvpn/{$modeid}.ca")) {
@ -120,7 +122,7 @@ $authenticated = false;
if (($strictusercn === true) && ($common_name != $username)) {
syslog(LOG_WARNING, "Username does not match certificate common name ({$username} != {$common_name}), access denied.\n");
if (isset($_GET)) {
if (isset($_GET['username'])) {
echo "FAILED";
closelog();
return;
@ -132,7 +134,7 @@ if (($strictusercn === true) && ($common_name != $username)) {
if (!is_array($authmodes)) {
syslog(LOG_WARNING, "No authentication server has been selected to authenticate against. Denying authentication for user {$username}");
if (isset($_GET)) {
if (isset($_GET['username'])) {
echo "FAILED";
closelog();
return;
@ -145,17 +147,19 @@ if (!is_array($authmodes)) {
$attributes = array();
foreach ($authmodes as $authmode) {
$authcfg = auth_get_authserver($authmode);
if (!$authcfg && $authmode != "local")
if (!$authcfg && $authmode != "local") {
continue;
}
$authenticated = authenticate_user($username, $password, $authcfg, $attributes);
if ($authenticated == true)
if ($authenticated == true) {
break;
}
}
if ($authenticated == false) {
syslog(LOG_WARNING, "user '{$username}' could not authenticate.\n");
if (isset($_GET)) {
if (isset($_GET['username'])) {
echo "FAILED";
closelog();
return;
@ -165,42 +169,47 @@ if ($authenticated == false) {
}
}
if (file_exists("/etc/inc/openvpn.attributes.php"))
include_once("/etc/inc/openvpn.attributes.php");
if (file_exists("/etc/inc/openvpn.attributes.php")) {
include_once("/etc/inc/openvpn.attributes.php");
}
$content = "";
if (is_array($attributes['dns-servers'])) {
foreach ($attributes['dns-servers'] as $dnssrv) {
if (is_ipaddr($dnssrv))
$content .= "push \"dhcp-option DNS {$dnssrv}\"\n";
}
foreach ($attributes['dns-servers'] as $dnssrv) {
if (is_ipaddr($dnssrv)) {
$content .= "push \"dhcp-option DNS {$dnssrv}\"\n";
}
}
}
if (is_array($attributes['routes'])) {
foreach ($attributes['routes'] as $route)
foreach ($attributes['routes'] as $route) {
$content .= "push \"route {$route} vpn_gateway\"\n";
}
}
if (isset($attributes['framed_ip'])) {
/* XXX: only use when TAP windows driver >= 8.2.x */
/* if (isset($attributes['framed_mask'])) {
$content .= "topology subnet\n";
$content .= "ifconfig-push {$attributes['framed_ip']} {$attributes['framed_mask']}";
} else {
/* if (isset($attributes['framed_mask'])) {
$content .= "topology subnet\n";
$content .= "ifconfig-push {$attributes['framed_ip']} {$attributes['framed_mask']}";
} else {
*/
$content .= "topology net30\n";
$content .= "ifconfig-push {$attributes['framed_ip']} ". long2ip((ip2long($attributes['framed_ip']) + 1));
// }
$content .= "topology net30\n";
$content .= "ifconfig-push {$attributes['framed_ip']} ". long2ip((ip2long($attributes['framed_ip']) + 1));
// }
}
if (!empty($content)) {
@file_put_contents("{$g['tmp_path']}/{$username}", $content);
}
if (!empty($content))
@file_put_contents("{$g['tmp_path']}/{$username}", $content);
syslog(LOG_NOTICE, "user '{$username}' authenticated\n");
closelog();
if (isset($_GET))
if (isset($_GET['username'])) {
echo "OK";
else
} else {
return (0);
}
?>

File diff suppressed because it is too large Load Diff

View File

@ -31,7 +31,7 @@
*/
/*
pfSense_BUILDER_BINARIES:
pfSense_BUILDER_BINARIES:
pfSense_MODULE: openvpn
*/
/*
@ -49,7 +49,7 @@ require_once("interfaces.inc");
openlog("openvpn", LOG_ODELAY, LOG_AUTH);
/* read data from command line */
if (isset($_GET)) {
if (isset($_GET['certdepth'])) {
$cert_depth = $_GET['certdepth'];
$cert_subject = urldecode($_GET['certsubject']);
$allowed_depth = $_GET['depth'];
@ -63,8 +63,9 @@ if (isset($_GET)) {
$subj = explode("/", $cert_subject);
foreach ($subj at $s) {
list($n, $v) = explode("=", $s);
if ($n == "CN")
if ($n == "CN") {
$common_name = $v;
}
}
*/
@ -73,7 +74,7 @@ foreach ($subj at $s) {
if (isset($allowed_depth) && ($cert_depth > $allowed_depth)) {
syslog(LOG_WARNING, "Certificate depth {$cert_depth} exceeded max allowed depth of {$allowed_depth}.\n");
if (isset($_GET)) {
if (isset($_GET['certdepth'])) {
echo "FAILED";
closelog();
return;
@ -87,9 +88,10 @@ if (isset($allowed_depth) && ($cert_depth > $allowed_depth)) {
//syslog(LOG_WARNING, "Found certificate {$argv[2]} with depth {$cert_depth}\n");
closelog();
if (isset($_GET))
if (isset($_GET['certdepth'])) {
echo "OK";
else
} else {
exit(0);
}
?>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -26,7 +26,7 @@ class plain_sasl_client_class
Function Start(&$client, &$message, &$interactions)
{
if($this->state!=SASL_PLAIN_STATE_START)
if ($this->state!=SASL_PLAIN_STATE_START)
{
$client->error="PLAIN authentication state is not at the start";
return(SASL_FAIL);
@ -42,9 +42,9 @@ class plain_sasl_client_class
"mode"=>""
);
$status=$client->GetCredentials($this->credentials,$defaults,$interactions);
if($status==SASL_CONTINUE)
if ($status==SASL_CONTINUE)
{
switch($this->credentials["mode"])
switch ($this->credentials["mode"])
{
case SASL_PLAIN_EXIM_MODE:
$message=$this->credentials["user"]."\0".$this->credentials["password"]."\0";
@ -65,11 +65,11 @@ class plain_sasl_client_class
Function Step(&$client, $response, &$message, &$interactions)
{
switch($this->state)
switch ($this->state)
{
/*
case SASL_PLAIN_STATE_IDENTIFY:
switch($this->credentials["mode"])
switch ($this->credentials["mode"])
{
case SASL_PLAIN_EXIM_MODE:
$message=$this->credentials["user"]."\0".$this->credentials["password"]."\0";

View File

@ -49,46 +49,57 @@ require_once("priv.defs.inc");
/* Load and process custom privs. */
function get_priv_files($directory) {
$dir_array = array();
if(!is_dir($directory))
if (!is_dir($directory)) {
return;
}
if ($dh = opendir($directory)) {
while (($file = readdir($dh)) !== false) {
$canadd = 0;
if($file == ".")
if ($file == ".") {
$canadd = 1;
if($file == "..")
}
if ($file == "..") {
$canadd = 1;
if($canadd == 0)
}
if ($canadd == 0) {
array_push($dir_array, $file);
}
}
closedir($dh);
}
if(!is_array($dir_array))
if (!is_array($dir_array)) {
return;
}
return $dir_array;
}
// Load and sort privs
$dir_array = get_priv_files("/etc/inc/priv");
foreach ($dir_array as $file)
if (!is_dir("/etc/inc/priv/{$file}") && stristr($file,".inc"))
foreach ($dir_array as $file) {
if (!is_dir("/etc/inc/priv/{$file}") && stristr($file,".inc")) {
include("/etc/inc/priv/{$file}");
if(is_dir("/usr/local/pkg/priv")) {
}
}
if (is_dir("/usr/local/pkg/priv")) {
$dir_array = get_priv_files("/usr/local/pkg/priv");
foreach ($dir_array as $file)
if (!is_dir("/usr/local/pkg/priv/{$file}") && stristr($file,".inc"))
foreach ($dir_array as $file) {
if (!is_dir("/usr/local/pkg/priv/{$file}") && stristr($file,".inc")) {
include("/usr/local/pkg/priv/{$file}");
}
}
}
if(is_array($priv_list))
if (is_array($priv_list)) {
sort_privs($priv_list);
}
function cmp_privkeys($a, $b) {
/* user privs at the top */
$auser = strncmp("user-", $a, 5);
$buser = strncmp("user-", $b, 5);
if($auser != $buser)
if ($auser != $buser) {
return $auser - $buser;
}
/* name compare others */
return strcasecmp($a, $b);
@ -103,27 +114,31 @@ function cmp_page_matches($page, & $matches, $fullwc = true) {
// $dbg_matches = implode(",", $matches);
// log_error("debug: checking page {$page} match with {$dbg_matches}");
if (!is_array($matches))
if (!is_array($matches)) {
return false;
}
/* skip any leading fwdslash */
$test = strpos($page, "/");
if ($test !== false && $test == 0)
if ($test !== false && $test == 0) {
$page = substr($page, 1);
}
/* look for a match */
foreach ($matches as $match) {
/* possibly ignore full wildcard match */
if (!$fullwc && !strcmp($match ,"*"))
if (!$fullwc && !strcmp($match ,"*")) {
continue;
}
/* compare exact or wildcard match */
$match = str_replace(array(".", "*","?"), array("\.", ".*","\?"), $match);
$result = preg_match("@^/{$match}$@", "/{$page}");
if ($result)
if ($result) {
return true;
}
}
return false;
@ -133,13 +148,16 @@ function map_page_privname($page) {
global $priv_list;
foreach ($priv_list as $pname => $pdata) {
if (strncmp($pname, "page-", 5))
if (strncmp($pname, "page-", 5)) {
continue;
}
$fullwc = false;
if (!strcasecmp($page,"any")||!strcmp($page,"*"))
if (!strcasecmp($page,"any")||!strcmp($page,"*")) {
$fullwc = true;
if (cmp_page_matches($page, $pdata['match'], $fullwc))
}
if (cmp_page_matches($page, $pdata['match'], $fullwc)) {
return $pname;
}
}
return false;
@ -151,30 +169,36 @@ function get_user_privdesc(& $user) {
$privs = array();
$user_privs = $user['priv'];
if (!is_array($user_privs))
if (!is_array($user_privs)) {
$user_privs = array();
}
$names = local_user_get_groups($user, true);
foreach ($names as $name) {
$group = getGroupEntry($name);
$group_privs = $group['priv'];
if (!is_array($group_privs))
if (!is_array($group_privs)) {
continue;
}
foreach ($group_privs as $pname) {
if (in_array($pname,$user_privs))
if (in_array($pname,$user_privs)) {
continue;
if (!$priv_list[$pname])
}
if (!$priv_list[$pname]) {
continue;
}
$priv = $priv_list[$pname];
$priv['group'] = $group['name'];
$privs[] = $priv;
}
}
foreach ($user_privs as $pname)
if($priv_list[$pname])
foreach ($user_privs as $pname) {
if ($priv_list[$pname]) {
$privs[] = $priv_list[$pname];
}
}
return $privs;
}
@ -182,19 +206,24 @@ function get_user_privdesc(& $user) {
function isAllowed($username, $page) {
global $_SESSION;
if (!isset($username))
if (!isset($username)) {
return false;
}
/* admin/root access check */
$user = getUserEntry($username);
if (isset($user))
if (isset($user['uid']))
if ($user['uid']==0)
if (isset($user)) {
if (isset($user['uid'])) {
if ($user['uid']==0) {
return true;
}
}
}
/* user privelege access check */
if (cmp_page_matches($page, $_SESSION['page-match']))
/* user privilege access check */
if (cmp_page_matches($page, $_SESSION['page-match'])) {
return true;
}
return false;
}
@ -206,68 +235,82 @@ function isAllowedPage($page) {
$username = $_SESSION['Username'];
if (!isset($username))
if (!isset($username)) {
return false;
}
/* admin/root access check */
$user = getUserEntry($username);
if (isset($user))
if (isset($user['uid']))
if ($user['uid']==0)
if (isset($user)) {
if (isset($user['uid'])) {
if ($user['uid']==0) {
return true;
}
}
}
/* user privelege access check */
/* user privilege access check */
return cmp_page_matches($page, $_SESSION['page-match']);
}
function getPrivPages(& $entry, & $allowed_pages) {
global $priv_list;
if (!is_array($entry['priv']))
if (!is_array($entry['priv'])) {
return;
}
foreach ($entry['priv'] as $pname) {
if (strncmp($pname, "page-", 5))
if (strncmp($pname, "page-", 5)) {
continue;
}
$priv = &$priv_list[$pname];
if (!is_array($priv))
if (!is_array($priv)) {
continue;
}
$matches = &$priv['match'];
if (!is_array($matches))
if (!is_array($matches)) {
continue;
foreach ($matches as $match)
}
foreach ($matches as $match) {
$allowed_pages[] = $match;
}
}
}
function getAllowedPages($username) {
global $config, $_SESSION;
if (!function_exists("ldap_connect"))
if (!function_exists("ldap_connect")) {
return;
}
$allowed_pages = array();
$allowed_groups = array();
$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
// obtain ldap groups if we are in ldap mode
if ($authcfg['type'] == "ldap")
if ($authcfg['type'] == "ldap") {
$allowed_groups = @ldap_get_groups($username, $authcfg);
else {
} else {
// search for a local user by name
$local_user = getUserEntry($username);
getPrivPages($local_user, $allowed_pages);
// obtain local groups if we have a local user
if ($local_user)
if ($local_user) {
$allowed_groups = local_user_get_groups($local_user);
}
}
// build a list of allowed pages
if (is_array($config['system']['group']) && is_array($allowed_groups))
foreach ($config['system']['group'] as $group)
if (in_array($group['name'], $allowed_groups))
if (is_array($config['system']['group']) && is_array($allowed_groups)) {
foreach ($config['system']['group'] as $group) {
if (in_array($group['name'], $allowed_groups)) {
getPrivPages($group, $allowed_pages);
}
}
}
// $dbg_pages = implode(",", $allowed_pages);
// $dbg_groups = implode(",", $allowed_groups);

View File

@ -6,30 +6,30 @@
Copyright (c) 2003, Michael Bretterklieber <michael@bretterklieber.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This code cannot simply be copied and put under the GNU Public License or
This code cannot simply be copied and put under the GNU Public License or
any other GPL-like (LGPL, GPL2) License.
This version of RADIUS.php has been modified by
@ -73,7 +73,7 @@ PEAR::loadExtension('radius');
*
* Abstract base class for RADIUS
*
* @package Auth_RADIUS
* @package Auth_RADIUS
*/
class Auth_RADIUS extends PEAR {
@ -138,7 +138,7 @@ class Auth_RADIUS extends PEAR {
*
* @return void
*/
function Auth_RADIUS()
function Auth_RADIUS()
{
$this->PEAR();
}
@ -146,8 +146,8 @@ class Auth_RADIUS extends PEAR {
/**
* Adds a RADIUS server to the list of servers for requests.
*
* At most 10 servers may be specified. When multiple servers
* are given, they are tried in round-robin fashion until a
* At most 10 servers may be specified. When multiple servers
* are given, they are tried in round-robin fashion until a
* valid response is received
*
* @access public
@ -158,7 +158,7 @@ class Auth_RADIUS extends PEAR {
* @param integer $maxtries Max. retries for each request
* @return void
*/
function addServer($servername = 'localhost', $port = 0, $sharedSecret = 'testing123', $timeout = 3, $maxtries = 2)
function addServer($servername = 'localhost', $port = 0, $sharedSecret = 'testing123', $timeout = 3, $maxtries = 2)
{
$this->_servers[] = array($servername, $port, $sharedSecret, $timeout, $maxtries);
}
@ -169,7 +169,7 @@ class Auth_RADIUS extends PEAR {
* @access public
* @return string
*/
function getError()
function getError()
{
return radius_strerror($this->res);
}
@ -181,7 +181,7 @@ class Auth_RADIUS extends PEAR {
* @param string $file Path to the configuration file
* @return void
*/
function setConfigfile($file)
function setConfigfile($file)
{
$this->_configfile = $file;
}
@ -195,7 +195,7 @@ class Auth_RADIUS extends PEAR {
* @param type $type Attribute-type
* @return bool true on success, false on error
*/
function putAttribute($attrib, $value, $type = null)
function putAttribute($attrib, $value, $type = null)
{
if ($type == null) {
$type = gettype($value);
@ -225,8 +225,8 @@ class Auth_RADIUS extends PEAR {
* @param mixed $port Attribute-value
* @param type $type Attribute-type
* @return bool true on success, false on error
*/
function putVendorAttribute($vendor, $attrib, $value, $type = null)
*/
function putVendorAttribute($vendor, $attrib, $value, $type = null)
{
if ($type == null) {
@ -270,11 +270,11 @@ class Auth_RADIUS extends PEAR {
}
/**
* Overwrite this.
* Overwrite this.
*
* @access public
*/
function open()
function open()
{
}
@ -339,7 +339,7 @@ class Auth_RADIUS extends PEAR {
* @return bool true on success, false on error
* @see addServer()
*/
function putServer($servername, $port = 0, $sharedsecret = 'testing123', $timeout = 3, $maxtries = 3)
function putServer($servername, $port = 0, $sharedsecret = 'testing123', $timeout = 3, $maxtries = 3)
{
if (!radius_add_server($this->res, $servername, $port, $sharedsecret, $timeout, $maxtries)) {
return false;
@ -354,7 +354,7 @@ class Auth_RADIUS extends PEAR {
* @param string $servername Servername or IP-Address
* @return bool true on success, false on error
*/
function putConfigfile($file)
function putConfigfile($file)
{
if (!radius_config($this->res, $file)) {
return false;
@ -363,11 +363,11 @@ class Auth_RADIUS extends PEAR {
}
/**
* Initiates a RADIUS request.
* Initiates a RADIUS request.
*
* @access public
* @return bool true on success, false on errors
*/
* @return bool true on success, false on errors
*/
function start()
{
if (!$this->open()) {
@ -447,7 +447,7 @@ class Auth_RADIUS extends PEAR {
if (!is_array($attrib)) {
return false;
}
}
$attr = $attrib['attr'];
$data = $attrib['data'];
@ -592,7 +592,7 @@ class Auth_RADIUS extends PEAR {
$this->attributes['url_logoff'] = radius_cvt_string($datav);
break;
}
}
}
elseif ($vendor == 14122) { /* RADIUS_VENDOR_WISPr Wi-Fi Alliance */
@ -719,9 +719,9 @@ class Auth_RADIUS extends PEAR {
*
* Class for authenticating using PAP (Plaintext)
*
* @package Auth_RADIUS
* @package Auth_RADIUS
*/
class Auth_RADIUS_PAP extends Auth_RADIUS
class Auth_RADIUS_PAP extends Auth_RADIUS
{
/**
@ -746,7 +746,7 @@ class Auth_RADIUS_PAP extends Auth_RADIUS
*
* @return bool true on success, false on error
*/
function open()
function open()
{
$this->res = radius_auth_open();
if (!$this->res) {
@ -756,7 +756,7 @@ class Auth_RADIUS_PAP extends Auth_RADIUS
}
/**
* Creates an authentication request
* Creates an authentication request
*
* Creates an authentication request.
* You MUST call this method before you can put any attribute
@ -772,7 +772,7 @@ class Auth_RADIUS_PAP extends Auth_RADIUS
}
/**
* Put authentication specific attributes
* Put authentication specific attributes
*
* @return void
*/
@ -792,10 +792,10 @@ class Auth_RADIUS_PAP extends Auth_RADIUS
* class Auth_RADIUS_CHAP_MD5
*
* Class for authenticating using CHAP-MD5 see RFC1994.
* Instead og the plaintext password the challenge and
* Instead og the plaintext password the challenge and
* the response are needed.
*
* @package Auth_RADIUS
* @package Auth_RADIUS
*/
class Auth_RADIUS_CHAP_MD5 extends Auth_RADIUS_PAP
{
@ -836,7 +836,7 @@ class Auth_RADIUS_CHAP_MD5 extends Auth_RADIUS_PAP
/**
* Put CHAP-MD5 specific attributes
*
* For authenticating using CHAP-MD5 via RADIUS you have to put the challenge
* For authenticating using CHAP-MD5 via RADIUS you have to put the challenge
* and the response. The chapid is inserted in the first byte of the response.
*
* @return void
@ -844,7 +844,7 @@ class Auth_RADIUS_CHAP_MD5 extends Auth_RADIUS_PAP
function putAuthAttributes()
{
if (isset($this->username)) {
$this->putAttribute(RADIUS_USER_NAME, $this->username);
$this->putAttribute(RADIUS_USER_NAME, $this->username);
}
if (isset($this->response)) {
$response = pack('C', $this->chapid) . $this->response;
@ -877,9 +877,9 @@ class Auth_RADIUS_CHAP_MD5 extends Auth_RADIUS_PAP
*
* Class for authenticating using MS-CHAPv1 see RFC2433
*
* @package Auth_RADIUS
* @package Auth_RADIUS
*/
class Auth_RADIUS_MSCHAPv1 extends Auth_RADIUS_CHAP_MD5
class Auth_RADIUS_MSCHAPv1 extends Auth_RADIUS_CHAP_MD5
{
/**
* LAN-Manager-Response
@ -895,9 +895,9 @@ class Auth_RADIUS_MSCHAPv1 extends Auth_RADIUS_CHAP_MD5
var $flags = 1;
/**
* Put MS-CHAPv1 specific attributes
* Put MS-CHAPv1 specific attributes
*
* For authenticating using MS-CHAPv1 via RADIUS you have to put the challenge
* For authenticating using MS-CHAPv1 via RADIUS you have to put the challenge
* and the response. The response has this structure:
* struct rad_mschapvalue {
* u_char ident;
@ -930,9 +930,9 @@ class Auth_RADIUS_MSCHAPv1 extends Auth_RADIUS_CHAP_MD5
*
* Class for authenticating using MS-CHAPv2 see RFC2759
*
* @package Auth_RADIUS
* @package Auth_RADIUS
*/
class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1
class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1
{
/**
* 16 Bytes binary challenge
@ -947,9 +947,9 @@ class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1
var $peerChallenge = null;
/**
* Put MS-CHAPv2 specific attributes
* Put MS-CHAPv2 specific attributes
*
* For authenticating using MS-CHAPv1 via RADIUS you have to put the challenge
* For authenticating using MS-CHAPv1 via RADIUS you have to put the challenge
* and the response. The response has this structure:
* struct rad_mschapv2value {
* u_char ident;
@ -964,11 +964,11 @@ class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1
function putAuthAttributes()
{
if (isset($this->username)) {
$this->putAttribute(RADIUS_USER_NAME, $this->username);
$this->putAttribute(RADIUS_USER_NAME, $this->username);
}
if (isset($this->response) && isset($this->peerChallenge)) {
// Response: chapid, flags (1 = use NT Response), Peer challenge, reserved, Response
$resp = pack('CCa16a8a24',$this->chapid , 1, $this->peerChallenge, str_repeat("\0", 8), $this->response);
// Response: chapid, flags (1 = use NT Response), Peer challenge, reserved, Response
$resp = pack('CCa16a8a24',$this->chapid , 1, $this->peerChallenge, str_repeat("\0", 8), $this->response);
$this->putVendorAttribute(RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP2_RESPONSE, $resp);
}
if (isset($this->challenge)) {
@ -983,7 +983,7 @@ class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1
* attributes are filled with Nullbytes to leave nothing in the mem.
*
* @access public
*/
*/
function close()
{
Auth_RADIUS_MSCHAPv1::close();
@ -995,10 +995,10 @@ class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1
* class Auth_RADIUS_Acct
*
* Class for RADIUS accounting
*
* @package Auth_RADIUS
*
* @package Auth_RADIUS
*/
class Auth_RADIUS_Acct extends Auth_RADIUS
class Auth_RADIUS_Acct extends Auth_RADIUS
{
/**
* Defines where the Authentication was made, possible values are:
@ -1011,19 +1011,19 @@ class Auth_RADIUS_Acct extends Auth_RADIUS
* Defines the type of the accounting request, on of:
* RADIUS_START, RADIUS_STOP, RADIUS_ACCOUNTING_ON, RADIUS_ACCOUNTING_OFF
* @var integer
*/
*/
var $status_type = null;
/**
* The time the user was logged in in seconds
* @var integer
*/
*/
var $session_time = null;
/**
* A uniq identifier for the session of the user, maybe the PHP-Session-Id
* @var string
*/
*/
var $session_id = null;
/**
@ -1066,7 +1066,7 @@ class Auth_RADIUS_Acct extends Auth_RADIUS
*
* @return bool true on success, false on error
*/
function open()
function open()
{
$this->res = radius_acct_open();
if (!$this->res) {
@ -1076,7 +1076,7 @@ class Auth_RADIUS_Acct extends Auth_RADIUS
}
/**
* Creates an accounting request
* Creates an accounting request
*
* Creates an accounting request.
* You MUST call this method before you can put any attribute.
@ -1094,10 +1094,10 @@ class Auth_RADIUS_Acct extends Auth_RADIUS
/**
* Put attributes for accounting.
*
* Here we put some accounting values. There many more attributes for accounting,
* Here we put some accounting values. There many more attributes for accounting,
* but for web-applications only certain attributes make sense.
* @return void
*/
*/
function putAuthAttributes()
{
if (isset($this->username)) {
@ -1121,10 +1121,10 @@ class Auth_RADIUS_Acct extends Auth_RADIUS
* class Auth_RADIUS_Acct_Start
*
* Class for RADIUS accounting. Its usualy used, after the user has logged in.
*
*
* @package Auth_RADIUS
*/
class Auth_RADIUS_Acct_Start extends Auth_RADIUS_Acct
class Auth_RADIUS_Acct_Start extends Auth_RADIUS_Acct
{
/**
* Defines the type of the accounting request.

View File

@ -61,14 +61,15 @@ function restore_rrd() {
}
unset($rrdrestore);
$_gb = exec("cd /;LANG=C /usr/bin/tar -tf {$g['cf_conf_path']}/rrd.tgz", $rrdrestore, $rrdreturn);
if($rrdreturn != 0) {
if ($rrdreturn != 0) {
log_error("RRD restore failed exited with $rrdreturn, the error is: $rrdrestore\n");
return;
}
foreach ($rrdrestore as $xml_file) {
$rrd_file = '/' . substr($xml_file, 0, -4) . '.rrd';
if (file_exists("{$rrd_file}"))
if (file_exists("{$rrd_file}")) {
@unlink($rrd_file);
}
file_put_contents("{$g['tmp_path']}/rrd_restore", $xml_file);
$_gb = exec("cd /;LANG=C /usr/bin/tar -xf {$g['cf_conf_path']}/rrd.tgz -T {$g['tmp_path']}/rrd_restore");
if (!file_exists("/{$xml_file}")) {
@ -107,7 +108,7 @@ function create_new_rrd($rrdcreatecmd) {
}
function migrate_rrd_format($rrdoldxml, $rrdnewxml) {
if(!file_exists("/tmp/rrd_notice_sent.txt")) {
if (!file_exists("/tmp/rrd_notice_sent.txt")) {
$_gb = exec("echo 'Converting RRD configuration to new format. This might take a bit...' | wall");
@touch("/tmp/rrd_notice_sent.txt");
}
@ -119,8 +120,8 @@ function migrate_rrd_format($rrdoldxml, $rrdnewxml) {
/* add data sources not found in the old array from the new array */
$i = 0;
foreach($rrdnewxml['ds'] as $ds) {
if(!is_array($rrdoldxml['ds'][$i])) {
foreach ($rrdnewxml['ds'] as $ds) {
if (!is_array($rrdoldxml['ds'][$i])) {
$rrdoldxml['ds'][$i] = $rrdnewxml['ds'][$i];
/* set unknown values to 0 */
$rrdoldxml['ds'][$i]['last_ds'] = " 0.0000000000e+00 ";
@ -134,16 +135,16 @@ function migrate_rrd_format($rrdoldxml, $rrdnewxml) {
$rracountold = count($rrdoldxml['rra']);
$rracountnew = count($rrdnewxml['rra']);
/* process each RRA, which contain a database */
foreach($rrdnewxml['rra'] as $rra) {
if(!is_array($rrdoldxml['rra'][$i])) {
foreach ($rrdnewxml['rra'] as $rra) {
if (!is_array($rrdoldxml['rra'][$i])) {
$rrdoldxml['rra'][$i] = $rrdnewxml['rra'][$i];
}
$d = 0;
/* process cdp_prep */
$cdp_prep = $rra['cdp_prep'];
foreach($cdp_prep['ds'] as $ds) {
if(!is_array($rrdoldxml['rra'][$i]['cdp_prep']['ds'][$d])) {
foreach ($cdp_prep['ds'] as $ds) {
if (!is_array($rrdoldxml['rra'][$i]['cdp_prep']['ds'][$d])) {
$rrdoldxml['rra'][$i]['cdp_prep']['ds'][$d] = $rrdnewxml['rra'][$i]['cdp_prep']['ds'][$d];
$rrdoldxml['rra'][$i]['cdp_prep']['ds'][$d]['primary_value'] = " 0.0000000000e+00 ";
$rrdoldxml['rra'][$i]['cdp_prep']['ds'][$d]['secondary_value'] = " 0.0000000000e+00 ";
@ -163,28 +164,28 @@ function migrate_rrd_format($rrdoldxml, $rrdnewxml) {
$rowsdata = $rows;
$rowsempty = array();
$r = 0;
while($r < $rowcountdiff) {
while ($r < $rowcountdiff) {
$rowsempty[] = $rrdnewxml['rra'][$i]['database']['row'][$r];
$r++;
}
$rows = $rowsempty + $rowsdata;
/* now foreach the rows in the database */
foreach($rows['row'] as $row) {
if(!is_array($rrdoldxml['rra'][$i]['database']['row'][$k])) {
foreach ($rows['row'] as $row) {
if (!is_array($rrdoldxml['rra'][$i]['database']['row'][$k])) {
$rrdoldxml['rra'][$i]['database']['row'][$k] = $rrdnewxml['rra'][$i]['database']['row'][$k];
}
$m = 0;
$vcountold = count($rrdoldxml['rra'][$i]['database']['row'][$k]['v']);
$vcountnew = count($rrdnewxml['rra'][$i]['database']['row'][$k]['v']);
foreach($row['v'] as $value) {
if(empty($rrdoldxml['rra'][$i]['database']['row'][$k]['v'][$m])) {
if(isset($valid)) {
foreach ($row['v'] as $value) {
if (empty($rrdoldxml['rra'][$i]['database']['row'][$k]['v'][$m])) {
if (isset($valid)) {
$rrdoldxml['rra'][$i]['database']['row'][$k]['v'][$m] = "0.0000000000e+00 ";
} else {
$rrdoldxml['rra'][$i]['database']['row'][$k]['v'][$m] = $rrdnewxml['rra'][$i]['database']['row'][$k]['v'][$m];
}
} else {
if($value <> " NaN ") {
if ($value <> " NaN ") {
$valid = true;
} else {
$valid = false;
@ -206,8 +207,9 @@ function migrate_rrd_format($rrdoldxml, $rrdnewxml) {
function enable_rrd_graphing() {
global $config, $g, $altq_list_queues;
if(platform_booting())
if (platform_booting()) {
echo gettext("Generating RRD graphs...");
}
$rrddbpath = "/var/db/rrd/";
$rrdgraphpath = "/usr/local/www/rrd";
@ -309,16 +311,17 @@ function enable_rrd_graphing() {
/* IPsec counters */
$ifdescrs['ipsec'] = "IPsec";
/* OpenVPN server counters */
if(is_array($config['openvpn']['openvpn-server'])) {
foreach($config['openvpn']['openvpn-server'] as $server) {
if (is_array($config['openvpn']['openvpn-server'])) {
foreach ($config['openvpn']['openvpn-server'] as $server) {
$serverid = "ovpns" . $server['vpnid'];
$ifdescrs[$serverid] = "{$server['description']}";
}
}
if (platform_booting()) {
if (!is_dir("{$g['vardb_path']}/rrd"))
if (!is_dir("{$g['vardb_path']}/rrd")) {
mkdir("{$g['vardb_path']}/rrd", 0775);
}
@chown("{$g['vardb_path']}/rrd", "nobody");
}
@ -326,7 +329,7 @@ function enable_rrd_graphing() {
/* process all real and pseudo interfaces */
foreach ($ifdescrs as $ifname => $ifdescr) {
$temp = get_real_interface($ifname);
if($temp <> "") {
if ($temp <> "") {
$realif = $temp;
}
@ -351,7 +354,7 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (platform_booting()) {
mwexec("$rrdtool update $rrddbpath$ifname$traffic N:U:U:U:U:U:U:U:U");
}
@ -384,7 +387,7 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (platform_booting()) {
mwexec("$rrdtool update $rrddbpath$ifname$packets N:U:U:U:U:U:U:U:U");
}
@ -397,7 +400,7 @@ function enable_rrd_graphing() {
$rrdupdatesh .= "END {print b4pi \":\" b4po \":\" b4bi \":\" b4bo \":\" b6pi \":\" b6po \":\" b6bi \":\" b6bo};'`\n";
/* WIRELESS, set up the rrd file */
if($config['interfaces'][$ifname]['wireless']['mode'] == "bss") {
if ($config['interfaces'][$ifname]['wireless']['mode'] == "bss") {
if (!file_exists("$rrddbpath$ifname$wireless")) {
$rrdcreate = "$rrdtool create $rrddbpath$ifname$wireless --step $rrdwirelessinterval ";
$rrdcreate .= "DS:snr:GAUGE:$wirelessvalid:0:1000 ";
@ -413,7 +416,7 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (platform_booting()) {
mwexec("$rrdtool update $rrddbpath$ifname$wireless N:U:U:U");
}
@ -424,7 +427,7 @@ function enable_rrd_graphing() {
}
/* OpenVPN, set up the rrd file */
if(stristr($ifname, "ovpns")) {
if (stristr($ifname, "ovpns")) {
if (!file_exists("$rrddbpath$ifname$vpnusers")) {
$rrdcreate = "$rrdtool create $rrddbpath$ifname$vpnusers --step $rrdvpninterval ";
$rrdcreate .= "DS:users:GAUGE:$vpnvalid:0:10000 ";
@ -438,13 +441,13 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (platform_booting()) {
mwexec("$rrdtool update $rrddbpath$ifname$vpnusers N:U");
}
if(is_array($config['openvpn']['openvpn-server'])) {
foreach($config['openvpn']['openvpn-server'] as $server) {
if("ovpns{$server['vpnid']}" == $ifname) {
if (is_array($config['openvpn']['openvpn-server'])) {
foreach ($config['openvpn']['openvpn-server'] as $server) {
if ("ovpns{$server['vpnid']}" == $ifname) {
$port = $server['local_port'];
$vpnid = $server['vpnid'];
}
@ -520,12 +523,12 @@ function enable_rrd_graphing() {
unset($rrdcreate);
}
if(platform_booting()) {
if (platform_booting()) {
$rrdqcommand = "-t ";
$rrducommand = "N";
$qi = 0;
foreach ($qlist as $qname => $q) {
if($qi == 0) {
if ($qi == 0) {
$rrdqcommand .= "{$qname}";
} else {
$rrdqcommand .= ":{$qname}";
@ -573,7 +576,7 @@ function enable_rrd_graphing() {
}
/* 3G interfaces */
if(preg_match("/ppp[0-9]+/i", $realif)) {
if (preg_match("/ppp[0-9]+/i", $realif)) {
if (!file_exists("$rrddbpath$ifname$cellular")) {
$rrdcreate = "$rrdtool create $rrddbpath$ifname$cellular --step $rrdcellularinterval ";
$rrdcreate .= "DS:rssi:GAUGE:$cellularvalid:0:100 ";
@ -588,7 +591,7 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (platform_booting()) {
mwexec("$rrdtool update $rrddbpath$ifname$cellular N:U:U:U");
}
@ -605,7 +608,7 @@ function enable_rrd_graphing() {
$ifname = "system";
/* STATES, create pf states database */
if(! file_exists("$rrddbpath$ifname$states")) {
if (!file_exists("$rrddbpath$ifname$states")) {
$rrdcreate = "$rrdtool create $rrddbpath$ifname$states --step $rrdstatesinterval ";
$rrdcreate .= "DS:pfrate:GAUGE:$statesvalid:0:10000000 ";
$rrdcreate .= "DS:pfstates:GAUGE:$statesvalid:0:10000000 ";
@ -622,7 +625,7 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (platform_booting()) {
mwexec("$rrdtool update $rrddbpath$ifname$states N:U:U:U:U:U");
}
@ -640,7 +643,7 @@ function enable_rrd_graphing() {
/* End pf states statistics */
/* CPU, create CPU statistics database */
if(! file_exists("$rrddbpath$ifname$proc")) {
if (!file_exists("$rrddbpath$ifname$proc")) {
$rrdcreate = "$rrdtool create $rrddbpath$ifname$proc --step $rrdprocinterval ";
$rrdcreate .= "DS:user:GAUGE:$procvalid:0:10000000 ";
$rrdcreate .= "DS:nice:GAUGE:$procvalid:0:10000000 ";
@ -657,7 +660,7 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (platform_booting()) {
mwexec("$rrdtool update $rrddbpath$ifname$proc N:U:U:U:U:U");
}
@ -670,7 +673,7 @@ function enable_rrd_graphing() {
/* End CPU statistics */
/* Memory, create Memory statistics database */
if(! file_exists("$rrddbpath$ifname$mem")) {
if (!file_exists("$rrddbpath$ifname$mem")) {
$rrdcreate = "$rrdtool create $rrddbpath$ifname$mem --step $rrdmeminterval ";
$rrdcreate .= "DS:active:GAUGE:$memvalid:0:10000000 ";
$rrdcreate .= "DS:inactive:GAUGE:$memvalid:0:10000000 ";
@ -695,7 +698,7 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (platform_booting()) {
mwexec("$rrdtool update $rrddbpath$ifname$mem N:U:U:U:U:U");
}
@ -708,7 +711,7 @@ function enable_rrd_graphing() {
/* End Memory statistics */
/* mbuf, create mbuf statistics database */
if(! file_exists("$rrddbpath$ifname$mbuf")) {
if (!file_exists("$rrddbpath$ifname$mbuf")) {
$rrdcreate = "$rrdtool create $rrddbpath$ifname$mbuf --step $rrdmbufinterval ";
$rrdcreate .= "DS:current:GAUGE:$mbufvalid:0:10000000 ";
$rrdcreate .= "DS:cache:GAUGE:$mbufvalid:0:10000000 ";
@ -732,7 +735,7 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (platform_booting()) {
mwexec("$rrdtool update $rrddbpath$ifname$mbuf N:U:U:U:U");
}
@ -745,7 +748,7 @@ function enable_rrd_graphing() {
/* SPAMD, set up the spamd rrd file */
if (isset($config['installedpackages']['spamdsettings']) &&
$config['installedpackages']['spamdsettings']['config'][0]['enablerrd']) {
$config['installedpackages']['spamdsettings']['config'][0]['enablerrd']) {
/* set up the spamd rrd file */
if (!file_exists("$rrddbpath$ifname$spamd")) {
$rrdcreate = "$rrdtool create $rrddbpath$ifname$spamd --step $rrdspamdinterval ";
@ -777,10 +780,11 @@ function enable_rrd_graphing() {
/* End System statistics */
/* Captive Portal statistics, set up the rrd file */
if(is_array($config['captiveportal'])) {
if (is_array($config['captiveportal'])) {
foreach ($config['captiveportal'] as $cpkey => $cp) {
if (!isset($cp['enable']))
if (!isset($cp['enable'])) {
continue;
}
$ifname= "captiveportal";
$concurrent_filename = $rrddbpath . $ifname . '-' . $cpkey . $captiveportalconcurrent;
@ -809,7 +813,7 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (platform_booting()) {
mwexec("$rrdtool update $concurrent_filename N:U");
}
@ -845,7 +849,7 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (platform_booting()) {
mwexec("$rrdtool update $loggedin_filename N:U");
}
@ -888,8 +892,8 @@ function enable_rrd_graphing() {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
mwexec("$rrdtool update $rrddbpath$ntpd N:U:U:U:U:U:U");
if (platform_booting()) {
mwexec("$rrdtool update $rrddbpath$ntpd N:U:U:U:U:U:U");
}
/* the ntp stats gathering function. */
@ -931,12 +935,13 @@ function enable_rrd_graphing() {
}
$databases = glob("{$rrddbpath}/*.rrd");
foreach($databases as $database) {
foreach ($databases as $database) {
chown($database, "nobody");
}
if(platform_booting())
if (platform_booting()) {
echo gettext("done.") . "\n";
}
}
@ -963,9 +968,10 @@ function create_gateway_quality_rrd($rrd_file) {
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if(platform_booting()) {
if (!is_dir("{$g['vardb_path']}/rrd"))
if (platform_booting()) {
if (!is_dir("{$g['vardb_path']}/rrd")) {
mkdir("{$g['vardb_path']}/rrd", 0775);
}
@chown("{$g['vardb_path']}/rrd", "nobody");

View File

@ -178,7 +178,7 @@ class sasl_client_class
<purpose>Retrieve the values of one or more credentials to be used by
the authentication mechanism classes.</purpose>
<usage>This is meant to be used by authentication mechanism driver
classes to retrieve the credentials that may be neede.</usage>
classes to retrieve the credentials that may be needed.</usage>
<returnvalue>The function may return <tt>SASL_CONTINUE</tt> if it
succeeded, or <tt>SASL_NOMECH</tt> if it was not possible to
retrieve one of the requested credentials.</returnvalue>
@ -359,7 +359,7 @@ class sasl_client_class
<type>INTEGER</type>
<documentation>
<purpose>Process the authentication steps after the initial step,
until the authetication iteration dialog is complete.</purpose>
until the authentication iteration dialog is complete.</purpose>
<usage>Call this function iteratively after a successful initial
step calling the <functionlink>Start</functionlink> function.</usage>
<returnvalue>The function returns <tt>SASL_CONTINUE</tt> if step was

View File

@ -1,36 +1,35 @@
<?php
/****h* pfSense/service-utils
* NAME
* service-utils.inc - Service facility
* DESCRIPTION
* This file contains various functions used by the pfSense service facility.
* HISTORY
* $Id$
******
*
* Copyright (C) 2005-2006 Colin Smith (ethethlay@gmail.com)
* 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)
* RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
NAME
service-utils.inc - Service facility
DESCRIPTION
This file contains various functions used by the pfSense service facility.
HISTORY
$Id$
Copyright (C) 2005-2006 Colin Smith (ethethlay@gmail.com)
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)
RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*
@ -51,11 +50,13 @@ function write_rcfile($params) {
safe_mkdir(RCFILEPREFIX);
$rcfile_fullname = RCFILEPREFIX . $params['file'];
if (!file_exists($rcfile_fullname) && !is_link($rcfile_fullname) && !touch($rcfile_fullname))
if (!file_exists($rcfile_fullname) && !is_link($rcfile_fullname) && !touch($rcfile_fullname)) {
return false;
}
if (!is_writable($rcfile_fullname) || empty($params['start']))
if (!is_writable($rcfile_fullname) || empty($params['start'])) {
return false;
}
$towrite = "#!/bin/sh\n";
$towrite .= "# This file was automatically generated\n# by the {$g['product_name']} service handler.\n\n";
@ -64,9 +65,9 @@ function write_rcfile($params) {
$towrite .= "rc_start() {\n";
$towrite .= "\t{$params['start']}\n";
$towrite .= "}\n\n";
if(!empty($params['stop'])) {
if (!empty($params['stop'])) {
$tokill =& $params['stop'];
} else if(!empty($params['executable'])) {
} else if (!empty($params['executable'])) {
/* just nuke the executable */
$tokill = "/usr/bin/killall " . escapeshellarg($params['executable']);
} else {
@ -90,23 +91,25 @@ function write_rcfile($params) {
function start_service($name) {
global $config;
if (empty($name))
if (empty($name)) {
return;
}
if (is_array($config['installedpackages']) && is_array($config['installedpackages']['service'])) {
foreach($config['installedpackages']['service'] as $service) {
if(strtolower($service['name']) == strtolower($name)) {
if($service['rcfile']) {
foreach ($config['installedpackages']['service'] as $service) {
if (strtolower($service['name']) == strtolower($name)) {
if ($service['rcfile']) {
$prefix = RCFILEPREFIX;
if (!empty($service['prefix'])) {
$prefix =& $service['prefix'];
}
if(file_exists("{$prefix}{$service['rcfile']}") || is_link("{$prefix}{$service['rcfile']}")) {
if (file_exists("{$prefix}{$service['rcfile']}") || is_link("{$prefix}{$service['rcfile']}")) {
mwexec_bg("{$prefix}{$service['rcfile']} start");
}
}
if (!empty($service['startcmd']))
if (!empty($service['startcmd'])) {
eval($service['startcmd']);
}
break;
}
}
@ -116,24 +119,26 @@ function start_service($name) {
function stop_service($name) {
global $config;
if (empty($name))
if (empty($name)) {
return;
}
if (is_array($config['installedpackages']) && is_array($config['installedpackages']['service'])) {
foreach($config['installedpackages']['service'] as $service) {
if(strtolower($service['name']) == strtolower($name)) {
if($service['rcfile']) {
foreach ($config['installedpackages']['service'] as $service) {
if (strtolower($service['name']) == strtolower($name)) {
if ($service['rcfile']) {
$prefix = RCFILEPREFIX;
if(!empty($service['prefix'])) {
if (!empty($service['prefix'])) {
$prefix =& $service['prefix'];
}
if(file_exists("{$prefix}{$service['rcfile']}") || is_link("{$prefix}{$service['rcfile']}")) {
if (file_exists("{$prefix}{$service['rcfile']}") || is_link("{$prefix}{$service['rcfile']}")) {
mwexec("{$prefix}{$service['rcfile']} stop");
}
return;
}
if (!empty($service['stopcmd']))
if (!empty($service['stopcmd'])) {
eval($service['stopcmd']);
}
break;
}
@ -144,16 +149,17 @@ function stop_service($name) {
function restart_service($name) {
global $config;
if (empty($name))
if (empty($name)) {
return;
}
stop_service($name);
start_service($name);
if (is_array($config['installedpackages']) && is_array($config['installedpackages']['service'])) {
foreach($config['installedpackages']['service'] as $service) {
if(strtolower($service['name']) == strtolower($name)) {
if($service['restartcmd']) {
foreach ($config['installedpackages']['service'] as $service) {
if (strtolower($service['name']) == strtolower($name)) {
if ($service['restartcmd']) {
eval($service['restartcmd']);
}
break;
@ -163,34 +169,38 @@ function restart_service($name) {
}
function is_pid_running($pidfile) {
if (!file_exists($pidfile))
if (!file_exists($pidfile)) {
return false;
}
return (isvalidpid($pidfile));
}
function is_dhcp_running($interface) {
$status = find_dhclient_process($interface);
if($status != 0)
if ($status != 0) {
return true;
}
return false;
}
function restart_service_if_running($service) {
global $config;
if(is_service_running($service))
if (is_service_running($service)) {
restart_service($service);
}
return;
}
function is_service_enabled($service_name) {
global $config;
if ($service_name == "")
if ($service_name == "") {
return false;
}
if (is_array($config['installedpackages'])) {
if (isset($config['installedpackages'][$service_name]['config'][0]['enable']) &&
((empty($config['installedpackages'][$service_name]['config'][0]['enable'])) ||
($config['installedpackages'][$service_name]['config'][0]['enable'] === 'off'))) {
((empty($config['installedpackages'][$service_name]['config'][0]['enable'])) ||
($config['installedpackages'][$service_name]['config'][0]['enable'] === 'off'))) {
return false;
}
}
@ -200,38 +210,42 @@ function is_service_enabled($service_name) {
function is_service_running($service, $ps = "") {
global $config;
if(is_array($config['installedpackages']['service'])) {
foreach($config['installedpackages']['service'] as $aservice) {
if(strtolower($service) == strtolower($aservice['name'])) {
if (is_array($config['installedpackages']['service'])) {
foreach ($config['installedpackages']['service'] as $aservice) {
if (strtolower($service) == strtolower($aservice['name'])) {
if ($aservice['custom_php_service_status_command'] <> "") {
eval("\$rc={$aservice['custom_php_service_status_command']};");
return $rc;
}
if(empty($aservice['executable']))
if (empty($aservice['executable'])) {
return false;
if (is_process_running($aservice['executable']))
}
if (is_process_running($aservice['executable'])) {
return true;
}
return false;
}
}
}
if (is_process_running($service))
if (is_process_running($service)) {
return true;
}
return false;
}
function get_services() {
global $config;
if (is_array($config['installedpackages']['service']))
if (is_array($config['installedpackages']['service'])) {
$services = $config['installedpackages']['service'];
else
} else {
$services = array();
}
/* Add services that are in the base.
*
/*
* Add services that are in the base.
*/
if (is_radvd_enabled()) {
$pconfig = array();
@ -275,8 +289,9 @@ function get_services() {
$ifdescrs = get_configured_interface_list();
foreach ($ifdescrs as $if) {
$oc = $config['interfaces'][$if];
if ($oc['if'] && (!link_interface_to_bridge($if)))
if ($oc['if'] && (!link_interface_to_bridge($if))) {
$iflist[$if] = $if;
}
}
if (isset($config['dhcrelay']['enable'])) {
@ -377,40 +392,48 @@ function get_services() {
function find_service_by_name($name) {
$services = get_services();
foreach ($services as $service)
if ($service["name"] == $name)
foreach ($services as $service) {
if ($service["name"] == $name) {
return $service;
}
}
return array();
}
function find_service_by_openvpn_vpnid($vpnid) {
$services = get_services();
foreach ($services as $service)
if (($service["name"] == "openvpn") && isset($service["vpnid"]) && ($service["vpnid"] == $vpnid))
foreach ($services as $service) {
if (($service["name"] == "openvpn") && isset($service["vpnid"]) && ($service["vpnid"] == $vpnid)) {
return $service;
}
}
return array();
}
function find_service_by_cp_zone($zone) {
$services = get_services();
foreach ($services as $service)
if (($service["name"] == "captiveportal") && isset($service["zone"]) && ($service["zone"] == $zone))
foreach ($services as $service) {
if (($service["name"] == "captiveportal") && isset($service["zone"]) && ($service["zone"] == $zone)) {
return $service;
}
}
return array();
}
function service_name_compare($a, $b) {
if (strtolower($a['name']) == strtolower($b['name']))
if (strtolower($a['name']) == strtolower($b['name'])) {
return 0;
}
return (strtolower($a['name']) < strtolower($b['name'])) ? -1 : 1;
}
function get_pkg_descr($package_name) {
global $config;
if (is_array($config['installedpackages']['package'])) {
foreach($config['installedpackages']['package'] as $pkg) {
if($pkg['name'] == $package_name)
foreach ($config['installedpackages']['package'] as $pkg) {
if ($pkg['name'] == $package_name) {
return $pkg['descr'];
}
}
}
return gettext("Not available.");
@ -424,8 +447,9 @@ function get_service_status($service) {
break;
case "captiveportal":
$running = is_pid_running("{$g['varrun_path']}/lighty-{$service['zone']}-CaptivePortal.pid");
if (isset($config['captiveportal'][$service['zone']]['httpslogin']))
if (isset($config['captiveportal'][$service['zone']]['httpslogin'])) {
$running = $running && is_pid_running("{$g['varrun_path']}/lighty-{$service['zone']}-CaptivePortal-SSL.pid");
}
break;
case "vhosts-http":
$running = is_pid_running("{$g['varrun_path']}/vhosts-http.pid");
@ -442,6 +466,30 @@ function get_service_status($service) {
return $running;
}
function get_service_status_icon($service, $withtext = true, $smallicon = false) {
global $g;
$output = "";
if (get_service_status($service)) {
$statustext = gettext("Running");
$output .= "<img style=\"vertical-align:middle\" title=\"" . sprintf(gettext("%s Service is"),$service["name"]) . " {$statustext}\" src=\"/themes/" . $g["theme"] . "/images/icons/";
$output .= ($smallicon) ? "icon_pass.gif" : "icon_service_running.gif";
$output .= "\" alt=\"status\" />&nbsp;";
if ($withtext) {
$output .= "&nbsp;" . $statustext;
}
} else {
$service_enabled = is_service_enabled($service['name']);
$statustext = ($service_enabled) ? gettext("Stopped") : gettext("Disabled");
$output .= "<img style=\"vertical-align:middle\" title=\"" . sprintf(gettext("%s Service is"),$service["name"]) . " {$statustext}\" src=\"/themes/" . $g["theme"] . "/images/icons/";
$output .= ($smallicon) ? "icon_block.gif" : "icon_service_stopped.gif";
$output .= "\" alt=\"status\" />&nbsp;";
if ($withtext) {
$output .= "&nbsp;<font color=\"white\">{$statustext}</font>";
}
}
return $output;
}
function get_service_control_links($service, $addname = false) {
$output = "";
$stitle = ($addname) ? $service['name'] . " " : "";
@ -457,7 +505,7 @@ function get_service_control_links($service, $addname = false) {
$link = '<a title="%s" href="status_services.php?mode=%s&amp;service='.$service['name'].'">';
}
if(get_service_status($service)) {
if (get_service_status($service)) {
$output .= sprintf($link, sprintf(gettext("Restart %sService"), $stitle), 'restartservice');
$output .= '<i class="icon icon-retweet"></i></a> ';
@ -466,7 +514,7 @@ function get_service_control_links($service, $addname = false) {
} else {
$service_enabled = is_service_enabled($service['name']);
if($service['name'] == 'openvpn' || $service['name'] == 'captiveportal' || $service_enabled) {
if ($service['name'] == 'openvpn' || $service['name'] == 'captiveportal' || $service_enabled) {
$output .= sprintf($link, sprintf(gettext("Start %sService"), $stitle), 'startservice');
$output .= '<i class="icon icon-play-circle"></i></a> ';
}
@ -477,7 +525,7 @@ function get_service_control_links($service, $addname = false) {
function service_control_start($name, $extras) {
global $g;
switch($name) {
switch ($name) {
case 'radvd':
services_radvd_configure();
break;
@ -527,8 +575,9 @@ function service_control_start($name, $extras) {
if (($vpnmode == "server") || ($vpnmode == "client")) {
$id = isset($extras['vpnid']) ? htmlspecialchars($extras['vpnid']) : htmlspecialchars($extras['id']);
$configfile = "{$g['varetc_path']}/openvpn/{$vpnmode}{$id}.conf";
if (file_exists($configfile))
if (file_exists($configfile)) {
openvpn_restart_by_vpnid($vpnmode, $id);
}
}
break;
case 'relayd':
@ -542,7 +591,7 @@ function service_control_start($name, $extras) {
}
function service_control_stop($name, $extras) {
global $g;
switch($name) {
switch ($name) {
case 'radvd':
killbypid("{$g['varrun_path']}/radvd.pid");
break;
@ -613,7 +662,7 @@ function service_control_stop($name, $extras) {
function service_control_restart($name, $extras) {
global $g;
switch($name) {
switch ($name) {
case 'radvd':
services_radvd_configure();
break;
@ -666,8 +715,9 @@ function service_control_restart($name, $extras) {
if ($vpnmode == "server" || $vpnmode == "client") {
$id = htmlspecialchars($extras['id']);
$configfile = "{$g['varetc_path']}/openvpn/{$vpnmode}{$id}.conf";
if (file_exists($configfile))
if (file_exists($configfile)) {
openvpn_restart_by_vpnid($vpnmode, $id);
}
}
break;
case 'relayd':

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -105,7 +105,7 @@ class smtp_class
{
if(feof($this->connection))
{
$this->error=gettext("reached the end of data while reading from the SMTP server conection");
$this->error=gettext("reached the end of data while reading from the SMTP server connection");
return("");
}
if(GetType($data=@fgets($this->connection,100))!="string"

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,7 @@
/*
unbound.inc
part of the pfSense project (https://www.pfsense.org)
Copyright (C) 2014 Warren Baker <warren@decoy.co.za>
Copyright (C) 2015 Warren Baker <warren@percol8.co.za>
All rights reserved.
Redistribution and use in source and binary forms, with or without
@ -55,7 +55,7 @@ function unbound_optimization() {
$optimization_settings = array();
/*
/*
* Set the number of threads equal to number of CPUs.
* Use 1 to disable threading, if for some reason this sysctl fails.
*/
@ -74,9 +74,6 @@ function unbound_optimization() {
$optimization['infra_cache_slabs'] = "infra-cache-slabs: {$optimize_num}";
$optimization['key_cache_slabs'] = "key-cache-slabs: {$optimize_num}";
// Size of the RRset cache
$optimization['rrset_cache_size'] = "rrset-cache-size: 8m";
/*
* Larger socket buffer for busy servers
* Check that it is set to 4MB (by default the OS has it configured to 4MB)
@ -98,8 +95,9 @@ function unbound_optimization() {
}
}
// Safety check in case kern.ipc.maxsockbuf is not available.
if (!isset($optimization['so_rcvbuf']))
if (!isset($optimization['so_rcvbuf'])) {
$optimization['so_rcvbuf'] = "#so-rcvbuf: 4m";
}
return $optimization;
@ -115,8 +113,9 @@ function unbound_generate_config() {
if (isset($config['unbound']['dnssec'])) {
$module_config = "validator iterator";
$anchor_file = "auto-trust-anchor-file: {$g['unbound_chroot_path']}/root.key";
} else
} else {
$module_config = "iterator";
}
// Setup DNS Rebinding
if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
@ -141,19 +140,22 @@ EOF;
$bindints .= "interface: ::0\n";
$bindints .= "interface-automatic: yes\n";
} else {
foreach($active_interfaces as $ubif) {
foreach ($active_interfaces as $ubif) {
if (is_ipaddr($ubif)) {
//$bindints .= "interface: $ubif\n"; -- until redmine #4062 is fixed, then uncomment this.
//$bindints .= "interface: $ubif\n"; -- until redmine #4062 is fixed, then uncomment this.
} else {
$intip = get_interface_ip($ubif);
if (is_ipaddrv4($intip))
if (is_ipaddrv4($intip)) {
$bindints .= "interface: $intip\n";
}
$intip = get_interface_ipv6($ubif);
if (is_ipaddrv6($intip))
if (!is_linklocal($intip)) // skipping link local for the moment to not break people's configs: https://redmine.pfsense.org/issues/4062
if (is_ipaddrv6($intip)) {
if (!is_linklocal($intip)) { // skipping link local for the moment to not break people's configs: https://redmine.pfsense.org/issues/4062
$bindints .= "interface: $intip\n";
}
}
}
}
}
}
} else {
$bindints .= "interface: 0.0.0.0\n";
@ -165,13 +167,15 @@ EOF;
if (!empty($config['unbound']['outgoing_interface'])) {
$outgoingints = "# Outgoing interfaces to be used\n";
$outgoing_interfaces = explode(",", $config['unbound']['outgoing_interface']);
foreach($outgoing_interfaces as $outif) {
foreach ($outgoing_interfaces as $outif) {
$outip = get_interface_ip($outif);
if (!is_null($outip))
if (!is_null($outip)) {
$outgoingints .= "outgoing-interface: $outip\n";
}
$outip = get_interface_ipv6($outif);
if (!is_null($outip))
if (!is_null($outip)) {
$outgoingints .= "outgoing-interface: $outip\n";
}
}
}
@ -200,15 +204,15 @@ EOF;
if ($config['unbound']['custom_options']) {
$custom_options_source = explode("\n", base64_decode($config['unbound']['custom_options']));
$custom_options = "# Unbound custom options\n";
foreach ($custom_options_source as $ent)
foreach ($custom_options_source as $ent) {
$custom_options .= $ent."\n";
}
}
// Server configuration variables
$port = (is_port($config['unbound']['port'])) ? $config['unbound']['port'] : "53";
$hide_identity = isset($config['unbound']['hideidentity']) ? "yes" : "no";
$hide_version = isset($config['unbound']['hideversion']) ? "yes" : "no";
$harden_glue = isset($config['unbound']['hardenglue']) ? "yes" : "no";
$harden_dnssec_stripped = isset($config['unbound']['dnssecstripped']) ? "yes" : "no";
$prefetch = isset($config['unbound']['prefetch']) ? "yes" : "no";
$prefetch_key = isset($config['unbound']['prefetchkey']) ? "yes" : "no";
@ -222,25 +226,29 @@ EOF;
$infra_host_ttl = (!empty($config['unbound']['infra_host_ttl'])) ? $config['unbound']['infra_host_ttl'] : "900";
$infra_cache_numhosts = (!empty($config['unbound']['infra_cache_numhosts'])) ? $config['unbound']['infra_cache_numhosts'] : "10000";
$unwanted_reply_threshold = (!empty($config['unbound']['unwanted_reply_threshold'])) ? $config['unbound']['unwanted_reply_threshold'] : "0";
if ($unwanted_reply_threshold == "disabled")
if ($unwanted_reply_threshold == "disabled") {
$unwanted_reply_threshold = "0";
}
$msg_cache_size = (!empty($config['unbound']['msgcachesize'])) ? $config['unbound']['msgcachesize'] : "4";
$verbosity = isset($config['unbound']['log_verbosity']) ? $config['unbound']['log_verbosity'] : 1;
$use_caps = isset($config['unbound']['use_caps']) ? "yes" : "no";
// Set up forwarding if it configured
if (isset($config['unbound']['forwarding'])) {
$dnsservers = array();
if (isset($config['system']['dnsallowoverride'])) {
$ns = array_unique(get_nameservers());
foreach($ns as $nameserver) {
if ($nameserver)
foreach ($ns as $nameserver) {
if ($nameserver) {
$dnsservers[] = $nameserver;
}
}
} else {
$ns = array_unique(get_dns_servers());
foreach($ns as $nameserver) {
if ($nameserver)
foreach ($ns as $nameserver) {
if ($nameserver) {
$dnsservers[] = $nameserver;
}
}
}
@ -251,11 +259,16 @@ forward-zone:
name: "."
EOD;
foreach($dnsservers as $dnsserver)
foreach ($dnsservers as $dnsserver) {
$forward_conf .= "\tforward-addr: $dnsserver\n";
}
}
} else
} else {
$forward_conf = "";
}
// Size of the RRset cache == 2 * msg-cache-size per Unbound's recommendations
$rrset_cache_size = $msg_cache_size * 2;
$unboundconf = <<<EOD
##########################
@ -276,8 +289,7 @@ port: {$port}
verbosity: {$verbosity}
hide-identity: {$hide_identity}
hide-version: {$hide_version}
harden-referral-path: no
harden-glue: {$harden_glue}
harden-glue: yes
do-ip4: yes
do-ip6: yes
do-udp: yes
@ -296,17 +308,19 @@ cache-max-ttl: {$cache_max_ttl}
cache-min-ttl: {$cache_min_ttl}
harden-dnssec-stripped: {$harden_dnssec_stripped}
msg-cache-size: {$msg_cache_size}m
rrset-cache-size: {$rrset_cache_size}m
{$optimization['number_threads']}
{$optimization['msg_cache_slabs']}
{$optimization['rrset_cache_slabs']}
{$optimization['infra_cache_slabs']}
{$optimization['key_cache_slabs']}
{$optimization['rrset_cache_size']}
outgoing-range: 4096
{$optimization['so_rcvbuf']}
{$anchor_file}
prefetch: {$prefetch}
prefetch-key: {$prefetch_key}
use-caps-for-id: {$use_caps}
# Statistics
{$statistics}
# Interface IP(s) to bind to
@ -378,19 +392,22 @@ function read_hosts() {
*/
$etc_hosts = array();
foreach (file('/etc/hosts') as $line) {
if (strpos($line, "dhcpleases automatically entered"))
if (strpos($line, "dhcpleases automatically entered")) {
break;
}
$d = preg_split('/\s+/', $line, -1, PREG_SPLIT_NO_EMPTY);
if (empty($d) || substr(reset($d), 0, 1) == "#")
if (empty($d) || substr(reset($d), 0, 1) == "#") {
continue;
}
$ip = array_shift($d);
$fqdn = array_shift($d);
$name = array_shift($d);
if (!empty($fqdn) && $fqdn != "empty") {
if (!empty($name) && $name != "empty")
if (!empty($name) && $name != "empty") {
array_push($etc_hosts, array(ipaddr => "$ip", fqdn => "$fqdn", name => "$name"));
else
} else {
array_push($etc_hosts, array(ipaddr => "$ip", fqdn => "$fqdn"));
}
}
}
return $etc_hosts;
@ -407,26 +424,31 @@ function sync_unbound_service() {
unbound_generate_config();
do_as_unbound_user("start");
require_once("service-utils.inc");
if (is_service_running("unbound"))
if (is_service_running("unbound")) {
do_as_unbound_user("restore_cache");
}
}
function unbound_acl_id_used($id) {
global $config;
if (is_array($config['unbound']['acls']))
foreach($config['unbound']['acls'] as & $acls)
if ($id == $acls['aclid'])
if (is_array($config['unbound']['acls'])) {
foreach ($config['unbound']['acls'] as & $acls) {
if ($id == $acls['aclid']) {
return true;
}
}
}
return false;
}
function unbound_get_next_id() {
$aclid = 0;
while(unbound_acl_id_used($aclid))
while (unbound_acl_id_used($aclid)) {
$aclid++;
}
return $aclid;
}
@ -435,23 +457,23 @@ function do_as_unbound_user($cmd) {
global $g;
switch ($cmd) {
case "start":
mwexec("/usr/local/sbin/unbound -c {$g['unbound_chroot_path']}/unbound.conf");
break;
case "stop":
mwexec("echo '/usr/local/sbin/unbound-control stop' | /usr/bin/su -m unbound", true);
break;
case "reload":
mwexec("echo '/usr/local/sbin/unbound-control reload' | /usr/bin/su -m unbound", true);
break;
case "unbound-anchor":
mwexec("echo '/usr/local/sbin/unbound-anchor -a {$g['unbound_chroot_path']}/root.key' | /usr/bin/su -m unbound", true);
break;
case "unbound-control-setup":
mwexec("echo '/usr/local/sbin/unbound-control-setup -d {$g['unbound_chroot_path']}' | /usr/bin/su -m unbound", true);
break;
default:
break;
case "start":
mwexec("/usr/local/sbin/unbound -c {$g['unbound_chroot_path']}/unbound.conf");
break;
case "stop":
mwexec("echo '/usr/local/sbin/unbound-control stop' | /usr/bin/su -m unbound", true);
break;
case "reload":
mwexec("echo '/usr/local/sbin/unbound-control reload' | /usr/bin/su -m unbound", true);
break;
case "unbound-anchor":
mwexec("echo '/usr/local/sbin/unbound-anchor -a {$g['unbound_chroot_path']}/root.key' | /usr/bin/su -m unbound", true);
break;
case "unbound-control-setup":
mwexec("echo '/usr/local/sbin/unbound-control-setup -d {$g['unbound_chroot_path']}' | /usr/bin/su -m unbound", true);
break;
default:
break;
}
}
@ -462,16 +484,17 @@ function unbound_add_domain_overrides($pvt_rev="") {
$sorted_domains = msort($domains, "domain");
$result = array();
foreach($sorted_domains as $domain) {
foreach ($sorted_domains as $domain) {
$domain_key = current($domain);
if (!isset($result[$domain_key]))
if (!isset($result[$domain_key])) {
$result[$domain_key] = array();
}
$result[$domain_key][] = $domain['ip'];
}
// Domain overrides that have multiple entries need multiple stub-addr: added
$domain_entries = "";
foreach($result as $domain=>$ips) {
foreach ($result as $domain=>$ips) {
if ($pvt_rev == "private") {
$domain_entries .= "private-domain: \"$domain\"\n";
$domain_entries .= "domain-insecure: \"$domain\"\n";
@ -482,15 +505,16 @@ function unbound_add_domain_overrides($pvt_rev="") {
} else {
$domain_entries .= "stub-zone:\n";
$domain_entries .= "\tname: \"$domain\"\n";
foreach($ips as $ip)
foreach ($ips as $ip) {
$domain_entries .= "\tstub-addr: $ip\n";
}
$domain_entries .= "\tstub-prime: no\n";
}
}
if ($pvt_rev != "")
if ($pvt_rev != "") {
return $domain_entries;
else {
} else {
create_unbound_chroot_path();
file_put_contents("{$g['unbound_chroot_path']}/domainoverrides.conf", $domain_entries);
}
@ -502,18 +526,24 @@ function unbound_add_host_entries() {
$unbound_entries = "local-zone: \"{$config['system']['domain']}\" transparent\n";
$hosts = read_hosts();
$added_ptr = array();
foreach ($hosts as $host) {
if (is_ipaddrv4($host['ipaddr']))
if (is_ipaddrv4($host['ipaddr'])) {
$type = 'A';
else if (is_ipaddrv6($host['ipaddr']))
} else if (is_ipaddrv6($host['ipaddr'])) {
$type = 'AAAA';
else
} else {
continue;
}
$unbound_entries .= "local-data-ptr: \"{$host['ipaddr']} {$host['fqdn']}\"\n";
if (!$added_ptr[$host['ipaddr']]) {
$unbound_entries .= "local-data-ptr: \"{$host['ipaddr']} {$host['fqdn']}\"\n";
$added_ptr[$host['ipaddr']] = true;
}
$unbound_entries .= "local-data: \"{$host['fqdn']} {$type} {$host['ipaddr']}\"\n";
if (isset($host['name']))
if (isset($host['name'])) {
$unbound_entries .= "local-data: \"{$host['name']} {$type} {$host['ipaddr']}\"\n";
}
}
// Write out entries
@ -533,28 +563,33 @@ function unbound_control($action) {
case "start":
// Start Unbound
if ($config['unbound']['enable'] == "on") {
if (!is_service_running("unbound"))
if (!is_service_running("unbound")) {
do_as_unbound_user("start");
}
}
break;
case "stop":
if ($config['unbound']['enable'] == "on")
if ($config['unbound']['enable'] == "on") {
do_as_unbound_user("stop");
}
break;
case "reload":
if ($config['unbound']['enable'] == "on")
if ($config['unbound']['enable'] == "on") {
do_as_unbound_user("reload");
}
break;
case "dump_cache":
// Dump Unbound's Cache
if ($config['unbound']['dumpcache'] == "on")
if ($config['unbound']['dumpcache'] == "on") {
do_as_unbound_user("dump_cache");
}
break;
case "restore_cache":
// Restore Unbound's Cache
if ((is_service_running("unbound")) && ($config['unbound']['dumpcache'] == "on")) {
if (file_exists($cache_dumpfile) && filesize($cache_dumpfile) > 0)
if (file_exists($cache_dumpfile) && filesize($cache_dumpfile) > 0) {
do_as_unbound_user("load_cache < /var/tmp/unbound_cache");
}
}
break;
default:
@ -570,10 +605,11 @@ function unbound_statistics() {
if ($config['stats'] == "on") {
$stats_interval = $config['unbound']['stats_interval'];
$cumulative_stats = $config['cumulative_stats'];
if ($config['extended_stats'] == "on")
if ($config['extended_stats'] == "on") {
$extended_stats = "yes";
else
} else {
$extended_stats = "no";
}
} else {
$stats_interval = "0";
$cumulative_stats = "no";
@ -601,13 +637,15 @@ function unbound_acls_config() {
// Add our networks for active interfaces including localhost
if (!empty($config['unbound']['active_interface'])) {
$active_interfaces = array_flip(explode(",", $config['unbound']['active_interface']));
if (in_array("all", $active_interfaces))
if (in_array("all", $active_interfaces)) {
$active_interfaces = get_configured_interface_with_descr();
} else
}
} else {
$active_interfaces = get_configured_interface_with_descr();
}
$bindints = "";
foreach($active_interfaces as $ubif => $ifdesc) {
foreach ($active_interfaces as $ubif => $ifdesc) {
$ifip = get_interface_ip($ubif);
if (is_ipaddrv4($ifip)) {
// IPv4 is handled via NAT networks below
@ -617,13 +655,14 @@ function unbound_acls_config() {
if (!is_linklocal($ifip)) {
$subnet_bits = get_interface_subnetv6($ubif);
$subnet_ip = gen_subnetv6($ifip, $subnet_bits);
// only add LAN-type interfaces
if (!interface_has_gateway($ubif))
// only add LAN-type interfaces
if (!interface_has_gateway($ubif)) {
$aclcfg .= "access-control: {$subnet_ip}/{$subnet_bits} allow\n";
}
}
// add for IPv6 static routes to local networks
// for safety, we include only routes reachable on an interface with no
// gateway specified - read: not an Internet connection.
// gateway specified - read: not an Internet connection.
$static_routes = get_staticroutes();
foreach ($static_routes as $route) {
if ((lookup_gateway_interface_by_name($route['gateway']) == $ubif) && !interface_has_gateway($ubif)) {
@ -633,7 +672,7 @@ function unbound_acls_config() {
}
}
}
// Generate IPv4 access-control entries using the same logic as automatic outbound NAT
if (empty($FilterIflist)) {
filter_generate_optcfg_array();
@ -641,17 +680,18 @@ function unbound_acls_config() {
$natnetworks_array = array();
$natnetworks_array = filter_nat_rules_automatic_tonathosts();
foreach ($natnetworks_array as $allowednet) {
$aclcfg .= "access-control: $allowednet allow \n";
}
$aclcfg .= "access-control: $allowednet allow \n";
}
}
// Configure the custom ACLs
if (is_array($config['unbound']['acls'])) {
foreach($config['unbound']['acls'] as $unbound_acl) {
foreach ($config['unbound']['acls'] as $unbound_acl) {
$aclcfg .= "#{$unbound_acl['aclname']}\n";
foreach($unbound_acl['row'] as $network) {
if ($unbound_acl['aclaction'] == "allow snoop")
foreach ($unbound_acl['row'] as $network) {
if ($unbound_acl['aclaction'] == "allow snoop") {
$unbound_acl['aclaction'] = "allow_snoop";
}
$aclcfg .= "access-control: {$network['acl_network']}/{$network['mask']} {$unbound_acl['aclaction']}\n";
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -44,7 +44,7 @@ class UUID {
const FMT_BINARY = 102;
const FMT_QWORD = 1; /* Quad-word, 128-bit (not impl.) */
const FMT_DWORD = 2; /* Double-word, 64-bit (not impl.) */
const FMT_WORD = 4; /* Word, 32-bit (not impl.) */
const FMT_WORD = 4; /* Word, 32-bit (not impl.) */
const FMT_SHORT = 8; /* Short (not impl.) */
const FMT_BYTE = 16; /* Byte */
const FMT_DEFAULT = 16;
@ -169,7 +169,7 @@ class UUID {
$raw .= $node;
/* Hash the namespace and node and convert to a byte array */
$val = $hash($raw, true);
$val = $hash($raw, true);
$tmp = unpack('C16', $val);
foreach (array_keys($tmp) as $key)
$byte[$key - 1] = $tmp[$key];
@ -187,7 +187,7 @@ class UUID {
$field['time_hi'] &= 0x0fff;
$field['time_hi'] |= ($version << 12);
return ($field);
return ($field);
}
static private function generateNameMD5($ns, $node) {
return self::generateName($ns, $node, "md5",
@ -221,7 +221,7 @@ class UUID {
$uuid['time_low'] = $low;
$uuid['time_mid'] = $high & 0x0000ffff;
$uuid['time_hi'] = ($high & 0x0fff) | (self::UUID_TIME << 12);
/*
* We don't support saved state information and generate
* a random clock sequence each time.

View File

@ -3,29 +3,29 @@
voucher.inc
Copyright (C) 2010-2012 Ermal Luci <eri@pfsense.org>
Copyright (C) 2010 Scott Ullrich <sullrich@gmail.com>
Copyright (C) 2007 Marcel Wiget <mwiget@mac.com>
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 <mwiget@mac.com>
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,29 +296,33 @@ function voucher_expire($voucher_received) {
captiveportal_logportalauth($cpentry[4],$cpentry[3],$cpentry[2],"FORCLY TERMINATING VOUCHER {$voucher} SESSION");
$unsetindexes[] = $cpentry[5];
}
} else
captiveportal_syslog("$voucher ($roll/$nr): not found on any registererd Roll");
} else
} else {
captiveportal_syslog("$voucher ($roll/$nr): not found on any registered Roll");
}
} else {
// hmm, thats weird ... not what I expected
captiveportal_syslog("$voucher invalid: {$output[0]}!!");
}
}
// 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);
/* Triger a sync of the vouchers on config */
/* Trigger a sync of the vouchers on config */
send_event("service sync vouchers");
}
// 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) {
@ -412,8 +434,8 @@ function voucher_auth($voucher_received, $test = 0) {
}
}
} else {
$test_result[] = "$voucher ($roll/$nr): not found on any registererd Roll";
captiveportal_syslog("$voucher ($roll/$nr): not found on any registererd Roll");
$test_result[] = "$voucher ($roll/$nr): not found on any registered Roll";
captiveportal_syslog("$voucher ($roll/$nr): not found on any registered Roll");
}
} else {
// hmm, thats weird ... not what I expected
@ -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));
}
@ -480,7 +505,7 @@ function voucher_auth($voucher_received, $test = 0) {
$active_vouchers[$first_voucher_roll][$first_voucher] = "$timestamp,$minutes";
voucher_write_active_db($first_voucher_roll, $active_vouchers[$first_voucher_roll]);
/* Triger a sync of the vouchers on config */
/* Trigger a sync of the vouchers on config */
send_event("service sync vouchers");
unlock($voucherlck);
@ -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 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,17 +633,18 @@ 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);
if ($dirty) { // if we found expired entries, lets save our snapshot
voucher_write_active_db($roll, $active);
/* Triger a sync of the vouchers on config */
/* Trigger a sync of the vouchers on config */
send_event("service sync vouchers");
}
}
@ -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("Synching vouchers");
return;
write_config("Syncing vouchers");
return;
}
?>

File diff suppressed because it is too large Load Diff

View File

@ -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'];
}

View File

@ -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');

View File

@ -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 .= "</$ent>\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><![CDATA[" . htmlentities($cval) . "]]></$ent>\n";
} else {
$xmlconfig .= "<$ent>" . htmlentities($cval) . "</$ent>\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><![CDATA[" . htmlentities($val) . "]]></$ent>\n";
else
else {
$xmlconfig .= "<$ent>" . htmlentities($val) . "</$ent>\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);
}

View File

@ -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);
}

View File

@ -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;
}
?>

View File

@ -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;

View File

@ -1,4 +1,4 @@
<?php
<?php
/*
zeromq.inc
part of the pfSense project (https://www.pfsense.org)
@ -32,12 +32,12 @@ define('ZEROMQ_TRUE', 'true');
define('ZEROMQ_FASLE', 'false');
$do_not_include_config_gui_inc = true;
require("auth.inc");
require_once("auth.inc");
//$debug = true;
//$debug = true;
/* zeromq_send: Send a message to a member node */
function zeromq_send($protocol = "tcp", $ipaddress = "127.0.0.1", $port = "8888",
function zeromq_send($protocol = "tcp", $ipaddress = "127.0.0.1", $port = "8888",
$method, $params, $username, $password) {
global $debug;
@ -49,7 +49,7 @@ function zeromq_send($protocol = "tcp", $ipaddress = "127.0.0.1", $port = "8888"
$method,
$params
);
/* Create new queue object */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ, "MySock1");
$queue->connect("{$protocol}://{$ipaddress}:{$port}");
@ -59,30 +59,34 @@ function zeromq_send($protocol = "tcp", $ipaddress = "127.0.0.1", $port = "8888"
/* xmlrpc_params_to_php() the result and return */
$unserializedresult = unserialize($result);
/* Return the result to the caller */
return $unserializedresult;
}
function zeromq_server($protocol = "tcp", $ipaddress = "127.0.0.1", $port = "8888") {
global $debug;
if(!$ipaddress || !$port) {
if($debug)
if (!$ipaddress || !$port) {
if ($debug) {
echo "ERROR: You must pass, proto, ipaddress and port\n";
}
return;
}
if($debug)
if ($debug) {
echo "Creating ZMQSocket()\n";
}
$server = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REP);
if($debug)
if ($debug) {
echo "Binding to {$protocol}://{$ipaddress}:{$port}\n";
}
$server->bind("{$protocol}://{$ipaddress}:{$port}");
if($debug)
if ($debug) {
echo "Entering while() loop\n";
}
while ($msg = $server->recv()) {
// Convert the XML to a PHP array
$message = unserialize($msg);
if($debug) {
if ($debug) {
echo "Message received:\n";
print_r($message);
}
@ -121,54 +125,61 @@ function zeromq_server($protocol = "tcp", $ipaddress = "127.0.0.1", $port = "888
$function_to_call = "get_notices_zeromq";
break;
}
if(!$function_to_call) {
if($debug)
if (!$function_to_call) {
if ($debug) {
echo "ERROR: Could not find a function to call";
}
return;
} else {
if($debug)
if ($debug) {
echo "Invoking function {$message[2]}()\n;";
}
}
/* Call function that is being invoked */
$result = $function_to_call($message);
/* echo back the result */
$server->send($result);
$server->send($result);
}
}
function zeromq_auth($params) {
global $config, $g, $debug;
global $config, $g, $debug;
$username = $params[0];
$passwd = $params[1];
$user = getUserEntry($username);
if (!$user) {
if($debug)
if ($debug) {
echo "Could not locate user $username with getUserEntry()\n";
}
return false;
}
if (is_account_disabled($username) || is_account_expired($username)) {
if($debug)
if ($debug) {
echo "Returning account expired/disabled\n";
}
return false;
}
if ($user['password']) {
$passwd = crypt($passwd, $user['password']);
if ($passwd == $user['password'])
if ($passwd == $user['password']) {
return true;
}
}
if ($user['md5-hash']) {
$passwd = md5($passwd);
if ($passwd == $user['md5-hash'])
if ($passwd == $user['md5-hash']) {
return true;
}
}
if($debug)
if ($debug) {
echo "zeromq_auth() fall through == false\n";
}
return false;
}
@ -176,32 +187,37 @@ function zeromq_auth($params) {
function exec_php_zeromq($raw_params) {
global $config, $g, $debug;
$params = $raw_params;
if(zeromq_auth($raw_params) == false) {
if($debug)
if (zeromq_auth($raw_params) == false) {
if ($debug) {
echo "Auth failed in exec_shell_zeromq()\n";
}
return ZEROMQ_AUTH_FAIL;
}
$exec_php = $params[3];
if($debug)
if ($debug) {
echo "Running exec_php_zeromq(): {$exec_php}\n";
}
eval($exec_php);
if($toreturn) {
if ($toreturn) {
return serialize($toreturn);
} else
} else {
return ZEROMQ_FASLE;
}
}
function exec_shell_zeromq($raw_params) {
global $config, $g, $debug;
$params = $raw_params;
if(zeromq_auth($raw_params) == false) {
if($debug)
if (zeromq_auth($raw_params) == false) {
if ($debug) {
echo "Auth failed in exec_shell_zeromq()\n";
}
return ZEROMQ_AUTH_FAIL;
}
$shell_cmd = $params[3];
if($debug)
if ($debug) {
echo "Running exec_shell_zeromq(): {$shell_cmd}\n";
}
mwexec($shell_cmd);
return ZEROMQ_FASLE;
}
@ -209,8 +225,9 @@ function exec_shell_zeromq($raw_params) {
function backup_config_section_zeromq($raw_params) {
global $config, $g, $debug;
$params = $raw_params;
if(zeromq_auth($raw_params) == false)
if (zeromq_auth($raw_params) == false) {
return ZEROMQ_AUTH_FAIL;
}
$val = array_intersect_key($config, array_flip($params[3]));
return serialize($val);
}
@ -218,8 +235,9 @@ function backup_config_section_zeromq($raw_params) {
function restore_config_section_zeromq($raw_params) {
global $config, $g, $debug;
$params = $raw_params;
if(zeromq_auth($raw_params) == false)
if (zeromq_auth($raw_params) == false) {
return ZEROMQ_AUTH_FAIL;
}
$config = array_merge($config, $params[3]);
$mergedkeys = implode(",", array_keys($params[3]));
write_config(sprintf(gettext("Merged in config (%s sections) from ZeroMQ client."),$mergedkeys));
@ -229,8 +247,9 @@ function restore_config_section_zeromq($raw_params) {
function merge_installedpackages_section_zeromq($raw_params) {
global $config, $g, $debug;
$params = $raw_params;
if(zeromq_auth($raw_params) == false)
if (zeromq_auth($raw_params) == false) {
return ZEROMQ_AUTH_FAIL;
}
$config['installedpackages'] = array_merge($config['installedpackages'], $params[0]);
$mergedkeys = implode(",", array_keys($params[3]));
write_config(sprintf(gettext("Merged in config (%s sections) from ZeroMQ client."),$mergedkeys));
@ -240,8 +259,9 @@ function merge_installedpackages_section_zeromq($raw_params) {
function merge_config_section_zeromq($raw_params) {
global $config, $g, $debug;
$params = $raw_params;
if(zeromq_auth($raw_params) == false)
return ZEROMQ_AUTH_FAIL;
if (zeromq_auth($raw_params) == false) {
return ZEROMQ_AUTH_FAIL;
}
$config = array_merge_recursive_unique($config, $params[0]);
$mergedkeys = implode(",", array_keys($params[3]));
write_config("Merged in config ({$mergedkeys} sections) from ZeroMQ client.");
@ -251,8 +271,9 @@ function merge_config_section_zeromq($raw_params) {
function filter_configure_zeromq($raw_params) {
global $config, $g, $debug;
$params = $raw_params;
if(zeromq_auth($raw_params) == false)
if (zeromq_auth($raw_params) == false) {
return ZEROMQ_AUTH_FAIL;
}
filter_configure();
system_routing_configure();
setup_gateways_monitor();
@ -260,10 +281,11 @@ function filter_configure_zeromq($raw_params) {
require_once("openvpn.inc");
openvpn_resync_all();
services_dhcpd_configure();
if (isset($config['dnsmasq']['enable']))
if (isset($config['dnsmasq']['enable'])) {
services_dnsmasq_configure();
elseif (isset($config['unbound']['enable']))
} elseif (isset($config['unbound']['enable'])) {
services_unbound_configure();
}
local_sync_accounts();
return ZEROMQ_FASLE;
}
@ -271,8 +293,9 @@ function filter_configure_zeromq($raw_params) {
function interfaces_carp_configure_zeromq($raw_params) {
global $config, $g, $debug;
$params = $raw_params;
if(zeromq_auth($raw_params) == false)
if (zeromq_auth($raw_params) == false) {
return ZEROMQ_AUTH_FAIL;
}
interfaces_sync_setup();
interfaces_vips_configure();
return ZEROMQ_FASLE;
@ -281,16 +304,18 @@ function interfaces_carp_configure_zeromq($raw_params) {
function check_firmware_version_zeromq($raw_params) {
global $config, $g, $debug;
$params = $raw_params;
if(zeromq_auth($raw_params) == false)
if (zeromq_auth($raw_params) == false) {
return ZEROMQ_AUTH_FAIL;
}
return serialize(check_firmware_version(false));
}
function reboot_zeromq($raw_params) {
global $config, $g, $debug;
$params = $raw_params;
if(zeromq_auth($raw_params) == false)
if (zeromq_auth($raw_params) == false) {
return ZEROMQ_AUTH_FAIL;
}
mwexec_bg("/etc/rc.reboot");
return ZEROMQ_FASLE;
}
@ -298,11 +323,13 @@ function reboot_zeromq($raw_params) {
function get_notices_zeromq($raw_params) {
global $config, $g, $debug;
$params = $raw_params;
if(zeromq_auth($raw_params) == false)
if (zeromq_auth($raw_params) == false) {
return ZEROMQ_AUTH_FAIL;
if(!function_exists("get_notices"))
}
if (!function_exists("get_notices")) {
require("notices.inc");
if(!$params) {
}
if (!$params) {
$toreturn = get_notices();
} else {
$toreturn = get_notices($params);

View File

@ -533,14 +533,10 @@
/usr/libexec/make_index
/usr/local/bin/after_installation_routines.sh
/usr/local/bin/atareinit
/usr/local/bin/athstats
/usr/local/bin/bsdiff
/usr/local/bin/bspatch
/usr/local/bin/c_rehash
/usr/local/bin/checkreload.sh
/usr/local/bin/cryptokeytest
/usr/local/bin/cryptostats
/usr/local/bin/cryptotest
/usr/local/bin/ez-ipupdate
/usr/local/bin/hifnstats
/usr/local/bin/ipsecstats
@ -629,9 +625,7 @@
/usr/local/lib/libmhash.so.2
/usr/local/lib/libpcre.a
/usr/local/lib/libpcre.la
/usr/local/lib/libpcre.so
/usr/local/lib/libpcre.so.0
/usr/local/lib/libpcre.so.1
/usr/local/lib/libpcrecpp.a
/usr/local/lib/libpcrecpp.la
/usr/local/lib/libpcrecpp.so
@ -883,6 +877,10 @@
/usr/local/www/auto_complete_helper.js
/usr/local/www/csrf/csrf-secret.php
/usr/local/www/datetimepicker.js
/usr/local/www/dfly-pg.gif
/usr/local/www/dfuife.cgi
/usr/local/www/dfuife.css
/usr/local/www/dfuife.js
/usr/local/www/diag_dhcp_leases.php
/usr/local/www/diag_logs_slbd.php
/usr/local/www/diag_showbogons.php
@ -899,6 +897,7 @@
/usr/local/www/firewall_shaper_edit.php
/usr/local/www/firewall_shaper_queues_edit.php
/usr/local/www/fred.png
/usr/local/www/fred-bg.png
/usr/local/www/ifstats.cgi
/usr/local/www/includes/javascript.inc.php
/usr/local/www/includes/log.inc.php

View File

@ -4,7 +4,7 @@ require_once("interfaces.inc");
require_once("util.inc");
set_single_sysctl("net.inet.carp.allow", "0");
if(is_array($config['virtualip']['vip'])) {
if (is_array($config['virtualip']['vip'])) {
$viparr = &$config['virtualip']['vip'];
foreach ($viparr as $vip) {
switch ($vip['mode']) {

View File

@ -3,18 +3,19 @@ require_once("config.inc");
require_once("interfaces.inc");
require_once("util.inc");
if(is_array($config['virtualip']['vip'])) {
if (is_array($config['virtualip']['vip'])) {
$viparr = &$config['virtualip']['vip'];
foreach ($viparr as $vip) {
switch ($vip['mode']) {
case "carp":
interface_carp_configure($vip);
sleep(1);
break;
case "ipalias":
if (strpos($vip['interface'], '_vip'))
interface_ipalias_configure($vip);
break;
case "carp":
interface_carp_configure($vip);
sleep(1);
break;
case "ipalias":
if (strpos($vip['interface'], '_vip')) {
interface_ipalias_configure($vip);
}
break;
}
}
}

View File

@ -10,7 +10,7 @@ require_once("filter.inc");
require_once("shaper.inc");
require_once("rrd.inc");
require_once("pfsense-utils.inc");
$GIT_PKG = "git"; // Either "git" or the full package URL
$GIT_BIN= "/usr/pbi/bin/git";
$GIT_REPO = "git://github.com/pfsense/pfsense.git";
@ -32,27 +32,29 @@ global $g;
global $argv;
global $command_split;
if(is_array($command_split))
if (is_array($command_split)) {
$temp_args = array_slice($command_split, 2);
else
} else {
$temp_args = array_slice($argv, 3);
}
$valid_args = array(
"--minimal" => "\tPerform a minimal copy of only the updated files.\n" .
"\tNot recommended if the system has files modified by any method other\n" .
"\tthan gitsync.\n",
"\tNot recommended if the system has files modified by any method other\n" .
"\tthan gitsync.\n",
"--help" => "\tDisplay this help list.\n"
);
$args = array();
$arg_count = 0;
while(!empty($temp_args)) {
while (!empty($temp_args)) {
$arg = array_shift($temp_args);
if($arg[0] == '-') {
switch($arg) {
if ($arg[0] == '-') {
switch ($arg) {
case "--help":
echo "Usage: playback gitsync [options] [[repository] <branch>]\nOptions:\n";
foreach($valid_args as $arg_name => $arg_desc)
foreach($valid_args as $arg_name => $arg_desc) {
echo $arg_name . "\n" . $arg_desc;
}
exit;
case "--upgrading":
// Disables all interactive functions and neither PHP
@ -73,7 +75,7 @@ while(!empty($temp_args)) {
unlink_if_exists("/tmp/config.cache");
conf_mount_rw();
if(!file_exists($GIT_BIN)) {
if (!file_exists($GIT_BIN)) {
echo "Cannot find git, fetching...\n";
require_once("config.inc");
require_once("util.inc");
@ -94,8 +96,9 @@ if(!file_exists($GIT_BIN)) {
if (($g['platform'] == "nanobsd")) {
$pkgtmpdir = "/usr/bin/env PKG_TMPDIR=/root/ ";
$pkgstagingdir = "/root/tmp";
if (!is_dir($pkgstagingdir))
if (!is_dir($pkgstagingdir)) {
mkdir($pkgstagingdir);
}
$pkgstaging = "-t {$pkgstagingdir}/instmp.XXXXXX";
}
system("{$pkgtmpdir}/usr/sbin/pkg_add {$pkgstaging} -r {$GIT_PKG}");
@ -107,34 +110,38 @@ if(!file_exists($GIT_BIN)) {
}
# Remove mainline if exists (older)
if(is_dir("/root/pfsense/mainline"))
if (is_dir("/root/pfsense/mainline")) {
exec("rm -rf /root/pfsense/mainline");
}
# Remove RELENG_1_2 if exists (older)
if(is_dir("/root/pfsense/RELENG_1_2"))
if (is_dir("/root/pfsense/RELENG_1_2")) {
exec("rm -rf /root/pfsense/RELENG_1_2");
}
# Remove HEAD if exists (older)
if(is_dir("/root/pfsense/HEAD"))
if (is_dir("/root/pfsense/HEAD")) {
exec("rm -rf /root/pfsense/HEAD");
}
if(file_exists("/root/cvssync_backup.tgz")) {
if (file_exists("/root/cvssync_backup.tgz")) {
$backup_date = `ls -lah /root/cvssync_backup.tgz | awk '{ print $6,$7,$8 }'`;
$tmp = array("RESTORE" => "Restores prior CVSSync backup data performed at {$backup_date}");
$branches = array_merge($branches, $tmp);
}
if(is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) {
if (is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) {
exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} config remote.origin.url", $output_str, $ret);
if(is_array($output_str) && !empty($output_str[0]))
if (is_array($output_str) && !empty($output_str[0])) {
$GIT_REPO = $output_str[0];
}
unset($output_str);
}
if(!$args[0] && !$upgrading) {
if (!$args[0] && !$upgrading) {
echo "\nCurrent repository is $GIT_REPO\n";
echo "\nPlease select which branch you would like to sync against:\n\n";
foreach($branches as $branchname => $branchdesc) {
foreach ($branches as $branchname => $branchdesc) {
echo "{$branchname} \t {$branchdesc}\n";
}
echo "\nOr alternatively you may enter a custom RCS branch URL (Git or HTTP).\n\n";
@ -144,51 +151,55 @@ if(!$args[0] && !$upgrading) {
$branch = $args[0];
}
if($args[1] == "NOBACKUP")
if ($args[1] == "NOBACKUP") {
$nobackup = true;
else
} else {
$nobackup = false;
}
// If the repository has been fetched before, build a list of its branches.
if(is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) {
if (is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) {
exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} branch -r", $branch_list, $ret);
if($ret == 0 && is_array($branch_list)) {
if ($ret == 0 && is_array($branch_list)) {
foreach ($branch_list as $branch_item) {
$branch_item = substr(strrchr($branch_item, "/"), 1);
if (!isset($branches[$branch_item]))
if (!isset($branches[$branch_item])) {
$branches[$branch_item] = " ";
}
}
}
}
$found = false;
foreach($branches as $branchname => $branchdesc) {
if($branchname == $branch)
foreach ($branches as $branchname => $branchdesc) {
if ($branchname == $branch) {
$found = true;
}
}
if(!$found) {
if(isURL($branch) && !$upgrading) {
if($args[1]) {
if (!$found) {
if (isURL($branch) && !$upgrading) {
if ($args[1]) {
$GIT_REPO = $branch;
$branch = $args[1];
$found = true;
}
else {
} else {
echo "\n";
echo "NOTE: $branch was not found.\n\n";
$command = readline("Is this a custom GIT URL? [y]? ");
if(strtolower($command) == "y" or $command == "") {
if (strtolower($command) == "y" or $command == "") {
$GIT_REPO = $branch;
$command = readline("Checkout which branch [${DEFAULT_BRANCH}]? ");
if($command == "")
if ($command == "") {
$branch = $DEFAULT_BRANCH;
if($command)
}
if ($command) {
$branch = $command;
}
$found = true;
}
}
}
if(!$found) {
if (!$found) {
echo "\nNo valid branch found. Exiting.\n\n";
conf_mount_ro();
exit;
@ -196,17 +207,18 @@ if(!$found) {
}
$merge_repos = array();
if(file_exists($GITSYNC_MERGE)) {
if (file_exists($GITSYNC_MERGE)) {
$gitsync_merges = file($GITSYNC_MERGE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if(!empty($gitsync_merges) && is_array($gitsync_merges)) {
if (!empty($gitsync_merges) && is_array($gitsync_merges)) {
echo "\n===> Automatic merge list read from ${GITSYNC_MERGE}\n";
foreach($gitsync_merges as $merge_line_num => $merge_line) {
foreach ($gitsync_merges as $merge_line_num => $merge_line) {
$merge_comments = explode("#", trim($merge_line));
if(empty($merge_comments[0]))
if (empty($merge_comments[0])) {
continue;
}
$merge_line = explode(" ", trim($merge_comments[0]));
if(count($merge_line) != 2 || empty($merge_line[0]) || empty($merge_line[1])) {
if (count($merge_line) != 2 || empty($merge_line[0]) || empty($merge_line[1])) {
echo "\nLine " . ($merge_line_num + 1) . " does not have the correct parameter count or has improper spacing.\n";
echo "Expected parameters: repository_url branch\n";
echo "Line read: " . implode(" ", $merge_line) . "\n\n";
@ -218,22 +230,23 @@ if(file_exists($GITSYNC_MERGE)) {
}
}
}
if(!$args[0] && !$upgrading) {
if (!$args[0] && !$upgrading) {
do {
echo "\nAdd a custom RCS branch URL (Git or HTTP) to merge in or press enter if done.\n\n";
$merge_repo = readline("> ");
if(!empty($merge_repo)) {
if (!empty($merge_repo)) {
$merge_branch = readline("Merge which branch [${DEFAULT_BRANCH}]? ");
if($merge_branch == "")
if ($merge_branch == "") {
$merge_repos[] = array('repo' => $merge_repo, 'branch' => $DEFAULT_BRANCH);
else if($merge_branch)
} else if ($merge_branch) {
$merge_repos[] = array('repo' => $merge_repo, 'branch' => $merge_branch);
}
}
} while(!empty($merge_repo));
} while (!empty($merge_repo));
}
if($branch == "RESTORE" && $g['platform'] == "pfSense") {
if(!file_exists("/root/cvssync_backup.tgz")) {
if ($branch == "RESTORE" && $g['platform'] == "pfSense") {
if (!file_exists("/root/cvssync_backup.tgz")) {
echo "Sorry, we could not find a previous CVSSync backup file.\n";
conf_mount_ro();
exit();
@ -247,7 +260,7 @@ if($branch == "RESTORE" && $g['platform'] == "pfSense") {
$nobackup = true; // do not backup embedded, livecd
}
if($nobackup == false) {
if ($nobackup == false) {
echo "===> Backing up current pfSense information...\n";
echo "===> Please wait... ";
exec("tar czPf /root/cvssync_backup.tgz --exclude /root --exclude /dev --exclude /tmp --exclude /var/run --exclude /var/empty /");
@ -259,7 +272,7 @@ if($nobackup == false) {
echo "===> Checking out $branch\n";
// Git commands for resetting to the specified branch
if($branch == "build_commit") {
if ($branch == "build_commit") {
$git_cmd = array(
"cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} branch " . escapeshellarg($branch) . " 2>/dev/null",
"cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} checkout -f " . escapeshellarg($branch) . " 2>/dev/null",
@ -274,28 +287,30 @@ if($branch == "build_commit") {
}
// Git 'er done!
if(is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) {
if (is_dir("$CODIR/pfSenseGITREPO/pfSenseGITREPO")) {
echo "===> Fetching updates...\n";
exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} config remote.origin.url " . escapeshellarg($GIT_REPO));
exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} fetch");
exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} clean -f -f -x -d");
run_cmds($git_cmd);
} else {
exec("mkdir -p $CODIR/pfSenseGITREPO");
echo "Executing cd $CODIR/pfSenseGITREPO && {$GIT_BIN} clone $GIT_REPO pfSenseGITREPO\n";
exec("mkdir -p $CODIR/pfSenseGITREPO");
echo "Executing cd $CODIR/pfSenseGITREPO && {$GIT_BIN} clone $GIT_REPO pfSenseGITREPO\n";
exec("cd $CODIR/pfSenseGITREPO && {$GIT_BIN} clone " . escapeshellarg($GIT_REPO) . " pfSenseGITREPO");
if(is_dir("$CODIR/pfSenseGITREPO/pfSense"))
if (is_dir("$CODIR/pfSenseGITREPO/pfSense")) {
exec("mv $CODIR/pfSenseGITREPO/pfSense $CODIR/pfSenseGITREPO/pfSenseGITREPO");
if(is_dir("$CODIR/pfSenseGITREPO/mainline"))
}
if (is_dir("$CODIR/pfSenseGITREPO/mainline")) {
exec("mv $CODIR/pfSenseGITREPO/mainline $CODIR/pfSenseGITREPO/pfSenseGITREPO");
}
run_cmds($git_cmd);
}
foreach($merge_repos as $merge_repo) {
foreach ($merge_repos as $merge_repo) {
echo "===> Merging branch {$merge_repo['branch']} from {$merge_repo['repo']}\n";
exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} pull " . escapeshellarg($merge_repo['repo']) . " " . escapeshellarg($merge_repo['branch']), $output_str, $ret);
unset($output_str);
if($ret <> 0) {
if ($ret <> 0) {
echo "\nMerge failed. Aborting sync.\n\n";
run_cmds($git_cmd);
conf_mount_ro();
@ -303,14 +318,16 @@ foreach($merge_repos as $merge_repo) {
}
}
if(isset($args["--minimal"])) {
if(file_exists("/etc/version.gitsync"))
if (isset($args["--minimal"])) {
if (file_exists("/etc/version.gitsync")) {
$old_revision = trim(file_get_contents("/etc/version.gitsync"));
else if(file_exists("/etc/version.lastcommit"))
} else if (file_exists("/etc/version.lastcommit")) {
$old_revision = trim(file_get_contents("/etc/version.lastcommit"));
}
$files_to_copy = strtr(shell_exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} diff --name-only " . escapeshellarg($old_revision)), "\n", " ");
} else
} else {
$files_to_copy = '--exclude .git .';
}
// Save new commit ID for later minimal file copies
exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} rev-parse -q --verify HEAD > /etc/version.gitsync");
@ -321,7 +338,7 @@ exec("mkdir -p /tmp/lighttpd/cache/compress/");
exec("cd ${CODIR}/pfSenseGITREPO/pfSenseGITREPO && find . -name CVS -exec rm -rf {} \; 2>/dev/null");
exec("cd ${CODIR}/pfSenseGITREPO/pfSenseGITREPO && find . -name pfSense.tgz -exec rm {} \; 2>/dev/null");
// Remove files that we do not want to overwrite the system with
// Remove files that we do not want to overwrite the system with
exec("rm ${CODIR}/pfSenseGITREPO/pfSenseGITREPO/etc/crontab 2>/dev/null");
exec("rm ${CODIR}/pfSenseGITREPO/pfSenseGITREPO/etc/master.passwd 2>/dev/null");
exec("rm ${CODIR}/pfSenseGITREPO/pfSenseGITREPO/etc/passwd 2>/dev/null");
@ -341,13 +358,15 @@ exec("rm -f ${CODIR}/pfSenseGITREPO/pfSenseGITREPO/etc/syslog.conf 2>/dev/null")
echo "===> Installing new files...\n";
if($g['platform'] == "pfSense")
if ($g['platform'] == "pfSense") {
$command = "cd $CODIR/pfSenseGITREPO/pfSenseGITREPO ; tar -cpf - {$files_to_copy} | (cd / ; tar -Uxpf -)";
else
} else {
$command = "cd $CODIR/pfSenseGITREPO/pfSenseGITREPO ; tar -cpf - {$files_to_copy} | (cd / ; tar -xpf -) 2>/dev/null";
if(!empty($files_to_copy))
}
if (!empty($files_to_copy)) {
exec($command);
else {
} else {
echo "Already up-to-date.\n";
$upgrading = true;
}
@ -357,19 +376,23 @@ exec("cd $CODIR/pfSenseGITREPO/pfSenseGITREPO && {$GIT_BIN} reset --hard >/dev/n
// Remove obsolete files
$files_to_remove = file("/etc/pfSense.obsoletedfiles");
foreach($files_to_remove as $file_to_remove)
if(file_exists($file_to_remove))
foreach ($files_to_remove as $file_to_remove) {
if (file_exists($file_to_remove)) {
exec("/bin/rm -f $file_to_remove");
}
}
if(!$upgrading)
if (!$upgrading) {
post_cvssync_commands();
}
echo "===> Checkout complete.\n";
echo "\n";
if(!$upgrading)
if (!$upgrading) {
echo "Your system is now sync'd and PHP and Lighty will be restarted in 5 seconds.\n\n";
else
} else {
echo "Your system is now sync'd.\n\n";
}
function post_cvssync_commands() {
echo "===> Removing FAST-CGI temporary files...\n";
@ -386,7 +409,7 @@ function post_cvssync_commands() {
exec("pfctl -f /tmp/rules.debug");
echo "\n";
if(file_exists("/etc/rc.php_ini_setup")) {
if (file_exists("/etc/rc.php_ini_setup")) {
echo "===> Running /etc/rc.php_ini_setup...";
exec("/etc/rc.php_ini_setup");
echo "\n";
@ -395,14 +418,15 @@ function post_cvssync_commands() {
/* lock down console if necessary */
echo "===> Locking down the console if needed...\n";
reload_ttys();
echo "===> Signaling PHP and Lighty restart...";
$fd = fopen("/tmp/restart_lighty", "w");
fwrite($fd, "#!/bin/sh\n");
fwrite($fd, "sleep 5\n");
fwrite($fd, "/usr/local/sbin/pfSctl -c 'service restart webgui'\n");
if(file_exists("/var/etc/lighty-CaptivePortal.conf"))
if (file_exists("/var/etc/lighty-CaptivePortal.conf")) {
fwrite($fd, "/usr/local/sbin/lighttpd -f /var/etc/lighty-CaptivePortal.conf\n");
}
fclose($fd);
mwexec_bg("sh /tmp/restart_lighty");
echo "\n";
@ -410,19 +434,23 @@ function post_cvssync_commands() {
}
function isUrl($url = "") {
if($url)
if(strstr($url, "rcs.pfsense.org") or
strstr($url, "mainline") or
strstr($url, ".git") or strstr($url, "git://"))
return true;
if ($url) {
if (strstr($url, "rcs.pfsense.org") or
strstr($url, "mainline") or
strstr($url, ".git") or
strstr($url, "git://")) {
return true;
}
}
return false;
}
function run_cmds($cmds) {
global $debug;
foreach($cmds as $cmd) {
if($debug)
foreach ($cmds as $cmd) {
if ($debug) {
echo "Running $cmd";
}
exec($cmd);
}
}

View File

@ -4,10 +4,11 @@ require_once("pkg-utils.inc");
global $g, $config, $argv, $command_split;
if(is_array($command_split))
if (is_array($command_split)) {
$args = array_slice($command_split, 2);
else
} else {
$args = array_slice($argv, 3);
}
$pkg_name = $args[0];
$install_type = empty($args[1]) ? "normal" : $args[1];
@ -27,13 +28,14 @@ if ($pkg_info) {
$static_output = "";
$pkg_interface = "console";
if (empty($pkg_info[$pkg_name]))
if (empty($pkg_info[$pkg_name])) {
echo "\nPackage not found.\n";
elseif ($install_type == "normal")
} elseif ($install_type == "normal") {
install_package($pkg_name, $pkg_info[$pkg_name], true);
elseif ($install_type == "xmlonly")
} elseif ($install_type == "xmlonly") {
install_package_xml($pkg_name);
else
} else {
echo "Invalid install type. Valid values are: normal, xmlonly.\n";
}
echo "\nDone.\n";

View File

@ -5,11 +5,12 @@ global $g, $config;
echo "Installed packages:\n";
foreach($config['installedpackages']['package'] as $package) {
foreach ($config['installedpackages']['package'] as $package) {
$name = str_pad("{$package['name']}-{$package['version']}", 30);
$descr = $package['descr'];
$line = "{$name} {$descr}";
if (strlen($line) > 80)
if (strlen($line) > 80) {
$line = substr($line, 0, 77) . "...";
}
echo "{$line}\n";
}

View File

@ -13,8 +13,9 @@ unset($queue);
unset($altq);
foreach ($config['filter']['rule'] as $key => $rule) {
if (isset($rule['wizard']) && $rule['wizard'] == "yes")
if (isset($rule['wizard']) && $rule['wizard'] == "yes") {
unset($config['filter']['rule'][$key]);
}
}
if (write_config()) {
echo gettext("Shaper Successfully Removed.\n");

View File

@ -2,4 +2,4 @@
require_once("config.inc");
require_once("ipsec.inc");
require_once("vpn.inc");
vpn_ipsec_configure();
vpn_ipsec_configure(true);

View File

@ -13,10 +13,11 @@ function usage() {
global $g, $config, $argv, $command_split;
if(is_array($command_split))
if (is_array($command_split)) {
$args = array_slice($command_split, 2);
else
} else {
$args = array_slice($argv, 3);
}
if (empty($args[0])) {
usage();

View File

@ -4,10 +4,11 @@ require_once("pkg-utils.inc");
global $g, $config, $argv, $command_split;
if(is_array($command_split))
if (is_array($command_split)) {
$args = array_slice($command_split, 2);
else
} else {
$args = array_slice($argv, 3);
}
$pkg_name = $args[0];
$remove_type = empty($args[1]) ? "normal" : $args[1];
@ -15,21 +16,23 @@ $pkg_info = array();
echo "Removing package \"{$pkg_name}\"...\n";
foreach($config['installedpackages']['package'] as $package) {
if ($pkg_name == $package['name'])
foreach ($config['installedpackages']['package'] as $package) {
if ($pkg_name == $package['name']) {
$pkg_info = $package;
}
}
$static_output = "";
$pkg_interface = "console";
if (empty($pkg_info))
if (empty($pkg_info)) {
echo "\nPackage not installed.\n";
elseif ($remove_type == "normal")
} elseif ($remove_type == "normal") {
uninstall_package($pkg_name);
elseif ($remove_type == "xmlonly")
} elseif ($remove_type == "xmlonly") {
delete_package_xml($pkg_name);
else
} else {
echo "Invalid removal type. Valid values are: normal, xmlonly.\n";
}
echo "\nDone.\n";

38
etc/rc
View File

@ -102,8 +102,8 @@ else
# If /conf is a directory, convert it to a symlink to /cf/conf
if [ -d "/conf" ]; then
# If item is not a symlink then rm and recreate
CONFPOINTSTO=`readlink /conf`
if ! test "x$CONFPOINTSTO" = "x/cf/conf"; then
CONFPOINTSTO=`readlink /conf`
if ! test "x$CONFPOINTSTO" = "x/cf/conf"; then
/bin/rm -rf /conf
/bin/ln -s /cf/conf /conf
fi
@ -225,8 +225,8 @@ if [ "$PLATFORM" = "cdrom" ] ; then
/bin/mkdir /tmp/unionfs/confdefault
/sbin/mount_unionfs /tmp/unionfs/usr /usr/
/sbin/mount_unionfs /tmp/unionfs/root /root/
/sbin/mount_unionfs /tmp/unionfs/bin /bin/
/sbin/mount_unionfs /tmp/unionfs/sbin /sbin/
/sbin/mount_unionfs /tmp/unionfs/bin /bin/
/sbin/mount_unionfs /tmp/unionfs/sbin /sbin/
/sbin/mount_unionfs /tmp/unionfs/boot /boot/
/sbin/mount_unionfs /tmp/unionfs/confdefault /conf.default/
echo "done."
@ -269,22 +269,22 @@ if [ ! -L /etc/hosts ]; then
fi
if [ ! -L /etc/resolv.conf ]; then
/bin/rm -rf /etc/resolv.conf
/bin/ln -s /var/etc/resolv.conf /etc/resolv.conf
/bin/rm -rf /etc/resolv.conf
/bin/ln -s /var/etc/resolv.conf /etc/resolv.conf
fi
if [ ! -L /etc/resolvconf.conf ]; then
/bin/rm -rf /etc/resolvconf.conf
/bin/ln -s /var/etc/resolvconf.conf /etc/resolvconf.conf
/bin/rm -rf /etc/resolvconf.conf
/bin/ln -s /var/etc/resolvconf.conf /etc/resolvconf.conf
fi
# Setup compatibility link for packages that
# have trouble overriding the PREFIX configure
# argument since we build our packages in a
# separated PREFIX area
# Only create if symlink does not exist.
# Only create if symlink does not exist.
if [ ! -h /tmp/tmp ]; then
/bin/ln -hfs / /tmp/tmp
/bin/ln -hfs / /tmp/tmp
fi
# Make sure our /tmp is 777 + Sticky
@ -296,13 +296,13 @@ fi
if [ ! "$PLATFORM" = "cdrom" ] ; then
# Malloc debugging check
if [ -L /etc/malloc.conf ]; then
#ln -s aj /etc/malloc.conf
#ln -s aj /etc/malloc.conf
/bin/rm /etc/malloc.conf
fi
fi
if [ ! -L /etc/dhclient.conf ]; then
/bin/rm -rf /etc/dhclient.conf
/bin/rm -rf /etc/dhclient.conf
fi
if [ ! -d /var/tmp ]; then
@ -310,7 +310,7 @@ if [ ! -d /var/tmp ]; then
fi
if [ ! -d /cf/conf/backup/ ]; then
/bin/mkdir -p /cf/conf/backup/
/bin/mkdir -p /cf/conf/backup/
fi
set -T
@ -334,18 +334,18 @@ if [ ! ${DEFAULT_LOG_FILE_SIZE} ]; then
fi
for logfile in $LOG_FILES; do
if [ "$DISABLESYSLOGCLOG" -gt "0" ]; then
if [ "$DISABLESYSLOGCLOG" -gt "0" ]; then
/usr/bin/touch /var/log/$logfile.log
else
else
if [ ! -f /var/log/$logfile.log ]; then
if [ "$ENABLEFIFOLOG" -gt "0" ]; then
# generate fifolog files
/usr/sbin/fifolog_create -s ${DEFAULT_LOG_FILE_SIZE} /var/log/$logfile.log
else
else
/usr/local/sbin/clog -i -s ${DEFAULT_LOG_FILE_SIZE} /var/log/$logfile.log
fi
fi
fi
fi
done
# change permissions on newly created fifolog files.
@ -368,7 +368,7 @@ echo -n "."
# Make sure /etc/rc.conf doesn't exist.
if [ -f /etc/rc.conf ]; then
/bin/rm -rf /etc/rc.conf
/bin/rm -rf /etc/rc.conf
fi
if [ ! "$PLATFORM" = "jail" ]; then
@ -429,7 +429,7 @@ if [ -f $varrunpath/booting ]; then
/bin/rm $varrunpath/booting
fi
# If a shell was selected from recovery
# If a shell was selected from recovery
# console then just drop to the shell now.
if [ -f "/tmp/donotbootup" ]; then
echo "Dropping to recovery shell."

View File

@ -7,7 +7,7 @@
if [ -d "${RRDDBPATH}" ]; then
[ -z "$NO_REMOUNT" ] && /etc/rc.conf_mount_rw
[ -f "${CF_CONF_PATH}/rrd.tgz" ] && /bin/rm -f "${CF_CONF_PATH}"/rrd.tgz
tgzlist=""
for rrdfile in "${RRDDBPATH}"/*.rrd ; do

View File

@ -42,50 +42,51 @@
$product = $g['product_name'];
$machine = trim(`uname -m`);
$hideplatform = $g['hideplatform'];
if(!$hideplatform)
if (!$hideplatform) {
$platformbanner = "-{$platform}";
}
print "*** Welcome to {$product} {$version}{$platformbanner} ({$machine}) on {$hostname} ***\n";
$iflist = get_configured_interface_with_descr(false, true);
foreach($iflist as $ifname => $friendly) {
foreach ($iflist as $ifname => $friendly) {
/* point to this interface's config */
$ifconf = $config['interfaces'][$ifname];
/* look for 'special cases' */
switch($ifconf['ipaddr']) {
case "dhcp":
$class = "/DHCP4";
break;
case "pppoe":
$class = "/PPPoE";
break;
case "pptp":
$class = "/PPTP";
break;
case "l2tp":
$class = "/L2TP";
break;
default:
$class = "";
break;
switch ($ifconf['ipaddr']) {
case "dhcp":
$class = "/DHCP4";
break;
case "pppoe":
$class = "/PPPoE";
break;
case "pptp":
$class = "/PPTP";
break;
case "l2tp":
$class = "/L2TP";
break;
default:
$class = "";
break;
}
switch($ifconf['ipaddrv6']) {
case "dhcp6":
$class6 = "/DHCP6";
break;
case "slaac":
$class6 = "/SLAAC";
break;
case "6rd":
$class6 = "/6RD";
break;
case "6to4":
$class6 = "/6to4";
break;
case "track6":
$class6 = "/t6";
break;
switch ($ifconf['ipaddrv6']) {
case "dhcp6":
$class6 = "/DHCP6";
break;
case "slaac":
$class6 = "/SLAAC";
break;
case "6rd":
$class6 = "/6RD";
break;
case "6to4":
$class6 = "/6to4";
break;
case "track6":
$class6 = "/t6";
break;
}
$ipaddr = get_interface_ip($ifname);
$subnet = get_interface_subnet($ifname);

View File

@ -38,7 +38,7 @@ function rescue_detect_keypress() {
// How long do you want the script to wait before moving on (in seconds)
$timeout=9;
echo "\n";
echo "[ Press R to enter recovery mode or ]\n";
echo "[ Press R to enter recovery mode or ]\n";
echo "[ press I to launch the installer ]\n\n";
echo "(R)ecovery mode can assist by rescuing config.xml\n";
echo "from a broken hard disk installation, etc.\n\n";
@ -48,30 +48,31 @@ function rescue_detect_keypress() {
echo "Timeout before auto boot continues (seconds): {$timeout}";
$key = null;
exec("/bin/stty erase " . chr(8));
while(!in_array($key, array("c", "C", "r","R", "i", "I", "~", "!"))) {
echo chr(8) . "{$timeout}";
`/bin/stty -icanon min 0 time 25`;
$key = trim(`KEY=\`dd count=1 2>/dev/null\`; echo \$KEY`);
`/bin/stty icanon`;
// Decrement our timeout value
$timeout--;
// If we have reached 0 exit and continue on
if ($timeout == 0)
break;
while (!in_array($key, array("c", "C", "r","R", "i", "I", "~", "!"))) {
echo chr(8) . "{$timeout}";
`/bin/stty -icanon min 0 time 25`;
$key = trim(`KEY=\`dd count=1 2>/dev/null\`; echo \$KEY`);
`/bin/stty icanon`;
// Decrement our timeout value
$timeout--;
// If we have reached 0 exit and continue on
if ($timeout == 0) {
break;
}
}
// If R or I was pressed do our logic here
if (in_array($key, array("r", "R"))) {
putenv("TERM=cons25");
echo "\n\nRecovery mode selected...\n";
passthru("/usr/bin/env TERM=cons25 /bin/tcsh -c /scripts/lua_installer_rescue");
putenv("TERM=cons25");
echo "\n\nRecovery mode selected...\n";
passthru("/usr/bin/env TERM=cons25 /bin/tcsh -c /scripts/lua_installer_rescue");
} elseif (in_array($key, array("i", "I"))) {
putenv("TERM=cons25");
echo "\n\nInstaller mode selected...\n";
passthru("/usr/bin/env TERM=cons25 /bin/tcsh -c /scripts/lua_installer");
if(file_exists("/tmp/install_complete")) {
passthru("/etc/rc.reboot");
exit;
}
putenv("TERM=cons25");
echo "\n\nInstaller mode selected...\n";
passthru("/usr/bin/env TERM=cons25 /bin/tcsh -c /scripts/lua_installer");
if (file_exists("/tmp/install_complete")) {
passthru("/etc/rc.reboot");
exit;
}
} elseif (in_array($key, array("!", "~"))) {
putenv("TERM=cons25");
echo "\n\nRecovery shell selected...\n";
@ -141,8 +142,9 @@ system_dmesg_save();
system_check_reset_button();
/* remove previous firmware upgrade if present */
if (file_exists("/root/firmware.tgz"))
if (file_exists("/root/firmware.tgz")) {
unlink("/root/firmware.tgz");
}
/* start devd (dhclient now uses it) */
echo "Starting device manager (devd)...";
@ -153,14 +155,15 @@ unmute_kernel_msgs();
echo "done.\n";
// Display rescue configuration option
if($g['platform'] == "cdrom")
rescue_detect_keypress();
if ($g['platform'] == "cdrom") {
rescue_detect_keypress();
}
echo "Loading configuration...";
parse_config_bootup();
echo "done.\n";
if($g['platform'] == "jail") {
if ($g['platform'] == "jail") {
/* We must determine what network settings have been configured for us */
$wanif = "lo0"; /* defaults, if the jail admin hasn't set us up */
$ipaddr = "127.0.0.1";
@ -181,28 +184,32 @@ if($g['platform'] == "jail") {
$config['interfaces']['wan']['ipaddr'] = $ipaddr;
$config['interfaces']['wan']['subnet'] = "32"; /* XXX right? */
$config['interfaces']['wan']['enable'] = true;
if($config['dhcpd']['lan'])
if ($config['dhcpd']['lan']) {
unset($config['dhcpd']['lan']['enable']);
}
unlink_if_exists('/conf/trigger_initial_wizard');
write_config();
} else {
/*
* Determine if we need to throw a interface exception
* and ask the user to reassign interfaces. This will
* avoid a reboot and thats a good thing.
* Determine if we need to throw a interface exception
* and ask the user to reassign interfaces. This will
* avoid a reboot and that is a good thing.
*/
while(is_interface_mismatch() == true) {
while (is_interface_mismatch() == true) {
led_assigninterfaces();
if (isset($config['revision'])) {
if (file_exists("{$g['tmp_path']}/missing_interfaces"))
if (file_exists("{$g['tmp_path']}/missing_interfaces")) {
echo "Warning: Configuration references interfaces that do not exist: " . file_get_contents("{$g['tmp_path']}/missing_interfaces") . "\n";
}
echo "\nNetwork interface mismatch -- Running interface assignment option.\n";
} else
} else {
echo "\nDefault interfaces not found -- Running interface assignment option.\n";
}
$ifaces = get_interface_list();
if (is_array($ifaces)) {
foreach($ifaces as $iface => $ifdata)
foreach ($ifaces as $iface => $ifdata) {
interfaces_bring_up($iface);
}
}
set_networking_interfaces_ports();
led_kitt();
@ -262,12 +269,14 @@ setup_microcode();
echo "done.\n";
/* set up interfaces */
if(!$debugging)
if (!$debugging) {
mute_kernel_msgs();
}
interfaces_configure();
interfaces_sync_setup();
if(!$debugging)
if (!$debugging) {
unmute_kernel_msgs();
}
/* re-make hosts file after configuring interfaces */
system_hosts_generate();
@ -297,7 +306,7 @@ echo "Synchronizing user settings...";
local_sync_accounts();
echo "done.\n";
if($realmem > 0 and $realmem < 65) {
if ($realmem > 0 and $realmem < 65) {
echo "System has less than 65 megabytes of ram {$realmem}. Delaying webConfigurator startup.\n";
/* start webConfigurator up on final pass */
mwexec("/usr/local/sbin/pfSctl -c 'service restart webgui'");
@ -339,7 +348,7 @@ system_console_configure();
/* start DHCP service */
services_dhcpd_configure();
/* start dhcpleases dhpcp hosts leases program */
/* start dhcpleases dhcp hosts leases program */
system_dhcpleases_configure();
/* start DHCP relay */
@ -385,12 +394,12 @@ enable_rrd_graphing();
enable_watchdog();
/* if <system><afterbootupshellcmd> exists, execute the command */
if($config['system']['afterbootupshellcmd'] <> "") {
if ($config['system']['afterbootupshellcmd'] <> "") {
echo "Running afterbootupshellcmd {$config['system']['afterbootupshellcmd']}\n";
mwexec($config['system']['afterbootupshellcmd']);
}
if($physmem < $g['minimum_ram_warning']) {
if ($physmem < $g['minimum_ram_warning']) {
require_once("/etc/inc/notices.inc");
file_notice("{$g['product_name']}MemoryRequirements", "{$g['product_name']} requires at least {$g['minimum_ram_warning_text']} of RAM. Expect unusual performance. This platform is not supported.", "Memory", "", 1);
set_sysctl(array(
@ -404,8 +413,9 @@ if($physmem < $g['minimum_ram_warning']) {
$kern_hz = get_single_sysctl('kern.clockrate');
$kern_hz = substr($kern_hz, strpos($kern_hz, "hz = ") + 5);
$kern_hz = substr($kern_hz, 0, strpos($kern_hz, ","));
if($kern_hz == "1000")
if ($kern_hz == "1000") {
set_single_sysctl("net.inet.tcp.rexmit_min" , "30");
}
/* start the igmpproxy daemon */
services_igmpproxy_configure();
@ -420,14 +430,15 @@ activate_powerd();
prefer_ipv4_or_ipv6();
/* Remove the old shutdown binary if we kept it. */
if (file_exists("/sbin/shutdown.old"))
if (file_exists("/sbin/shutdown.old")) {
@unlink("/sbin/shutdown.old");
}
/* Resync / Reinstall packages if need be */
if(file_exists('/conf/needs_package_sync')) {
if($config['installedpackages'] <> '' && is_array($config['installedpackages']['package'])) {
if (file_exists('/conf/needs_package_sync')) {
if ($config['installedpackages'] <> '' && is_array($config['installedpackages']['package'])) {
require_once("pkg-utils.inc");
if($g['platform'] == "pfSense" || $g['platform'] == "nanobsd") {
if ($g['platform'] == "pfSense" || $g['platform'] == "nanobsd") {
mark_subsystem_dirty('packagelock');
pkg_reinstall_all();
clear_subsystem_dirty('packagelock');
@ -447,6 +458,8 @@ unset($g['booting']);
/* If there are ipsec dynamic hosts try again to reload the tunnels as rc.newipsecdns does */
if ($ipsec_dynamic_hosts) {
vpn_ipsec_configure();
}
if ($ipsec_dynamic_hosts || !empty($filterdns)) {
filter_configure();
}

View File

@ -2,31 +2,31 @@
<?php
/* $Id$ */
/*
rc.captiveportal_configure
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
rc.captiveportal_configure
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require("config.inc");

View File

@ -1,31 +1,31 @@
#!/usr/local/bin/php -f
<?php
/*
rc.captiveportal_configure_mac
part of pfSense (https://www.pfsense.org)
Copyright (C) 2015 Ermal LUÇi
All rights reserved.
rc.captiveportal_configure_mac
part of pfSense (https://www.pfsense.org)
Copyright (C) 2015 Ermal LUÇi
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require("config.inc");

View File

@ -2,31 +2,31 @@
<?php
/* $Id$ */
/*
rc.carpbackup
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
rc.carpbackup
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require_once("functions.inc");
@ -35,12 +35,14 @@ require_once("notices.inc");
require_once("openvpn.inc");
require_once("interfaces.inc");
if (isset($_GET))
$argument = $_GET['interface'];
else
if (isset($_GET)) {
$argument = $_GET['interface'];
} else {
$argument = str_replace("\n", "", $argv[1]);
if (!strstr($argument, "@"))
log_error("Carp MASTER event triggered from wrong source {$argument}");
}
if (!strstr($argument, "@")) {
log_error("Carp MASTER event triggered from wrong source {$argument}");
}
list($vhid, $iface) = explode("@", $argument);
@ -73,15 +75,17 @@ if (is_array($config['openvpn']) && is_array($config['openvpn']['openvpn-client'
if (isset($config['dhcpdv6']) && is_array($config['dhcpdv6'])) {
$found = false;
foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
if ($dhcpv6ifconf['rainterface'] != $carp_iface)
if ($dhcpv6ifconf['rainterface'] != $carp_iface) {
continue;
}
$found = true;
break;
}
if ($found === true)
if ($found === true) {
services_radvd_configure();
}
}
$pluginparams = array();

View File

@ -2,31 +2,31 @@
<?php
/* $Id$ */
/*
rc.carpmaster
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
rc.carpmaster
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require_once("functions.inc");
@ -35,12 +35,14 @@ require_once("notices.inc");
require_once("openvpn.inc");
require_once("interfaces.inc");
if (isset($_GET))
if (isset($_GET)) {
$argument = $_GET['interface'];
else
} else {
$argument = str_replace("\n", "", $argv[1]);
if (!strstr($argument, "@"))
}
if (!strstr($argument, "@")) {
log_error("Carp MASTER event triggered from wrong source {$argument}");
}
list($vhid, $iface) = explode("@", $argument);
@ -81,15 +83,17 @@ if (is_array($config['openvpn']) && is_array($config['openvpn']['openvpn-server'
if (isset($config['dhcpdv6']) && is_array($config['dhcpdv6'])) {
$found = false;
foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
if ($dhcpv6ifconf['rainterface'] != $carp_iface)
if ($dhcpv6ifconf['rainterface'] != $carp_iface) {
continue;
}
$found = true;
break;
}
if ($found === true)
if ($found === true) {
services_radvd_configure();
}
}
$pluginparams = array();

View File

@ -12,9 +12,9 @@ partsize="6m"
export VARMFS_COPYDBPKG=yes
for i in tmp varmfs etcmfs; do
if [ -f /etc/rc.d/$i ]; then
sh /etc/rc.d/$i start
fi
if [ -f /etc/rc.d/$i ]; then
sh /etc/rc.d/$i start
fi
done
# Start PFI
@ -24,13 +24,13 @@ done
# a tiny mfs under /conf and populate with stock
# configuration.
if [ ! -f /conf/config.xml ]; then
echo -n "Generating a MFS /conf partition... "
device=$(mdconfig -a -t malloc -s ${partsize})
newfs /dev/${device} > /dev/null 2>&1
mount /dev/${device} /conf
cp /conf.default/* /conf
mount_nullfs /conf /cf/conf
echo "done."
echo -n "Generating a MFS /conf partition... "
device=$(mdconfig -a -t malloc -s ${partsize})
newfs /dev/${device} > /dev/null 2>&1
mount /dev/${device} /conf
cp /conf.default/* /conf
mount_nullfs /conf /cf/conf
echo "done."
fi
echo -n "Generating a MFS /home partition... "

View File

@ -2,31 +2,31 @@
<?php
/* $Id$ */
/*
rc.conf_mount_ro
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
rc.conf_mount_ro
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require_once("config.inc");

View File

@ -2,31 +2,31 @@
<?php
/* $Id$ */
/*
rc.conf_mount_rw
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
rc.conf_mount_rw
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require_once("config.inc");

View File

@ -2,31 +2,31 @@
<?php
/* $Id$ */
/*
rc.dhclient_cron
part of pfSense (https://www.pfsense.org)
Copyright (C) 2006 Scott Ullrich
All rights reserved.
rc.dhclient_cron
part of pfSense (https://www.pfsense.org)
Copyright (C) 2006 Scott Ullrich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require_once("config.inc");
@ -40,9 +40,9 @@ unlink_if_exists("/tmp/config.cache");
$iflist = get_configured_interface_with_descr();
foreach($iflist as $ifname => $interface) {
$real_interface = get_real_interface($ifname);
if($config['interfaces'][$ifname]['ipaddr'] == "dhcp") {
if ($config['interfaces'][$ifname]['ipaddr'] == "dhcp") {
$pid = find_dhclient_process($real_interface);
if($pid == 0 or !$pid) {
if ($pid == 0 or !$pid) {
/* dhclient is not running for interface, kick it */
log_error("DHCLIENT was not running for {$real_interface} ... Launching new instance.");
exec("/sbin/dhclient $real_interface");

View File

@ -2,31 +2,31 @@
<?php
/* $Id$ */
/*
rc.dyndns.update
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
rc.dyndns.update
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require_once("config.inc");
@ -37,18 +37,20 @@ require_once("shaper.inc");
/* Interface IP address has changed */
if (isset($_GET['dyndns']))
if (isset($_GET['dyndns'])) {
$argument = $_GET['dyndns'];
else
} else {
$argument = trim($argv[1], " \n");
}
if(empty($argument) || $argument == "all") {
if (empty($argument) || $argument == "all") {
services_dyndns_configure();
services_dnsupdate_process();
} else {
$interface = lookup_gateway_interface_by_name($argument);
if (empty($interface))
if (empty($interface)) {
$interface = $argument;
}
services_dyndns_configure($interface);
services_dnsupdate_process($interface);
}

View File

@ -4,20 +4,20 @@
/*
rc.expireaccounts
part of pfSense
Copyright (C) 2009 Shrew Soft Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
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
@ -39,16 +39,16 @@
$count = count($config['system']['user']);
$index = 0;
for(; $index < $count; $index++) {
for (; $index < $count; $index++) {
$user =& $config['system']['user'][$index];
if($user['scope'] == "system")
if ($user['scope'] == "system")
continue;
echo "1\n";
echo "User {$user['name']} expires {$user['expires']}\n";
if(!$user['expires'] || isset($user['disabled']))
if (!$user['expires'] || isset($user['disabled']))
continue;
echo "1\n";
if(strtotime("-1 day") > strtotime($user['expires'])) {
if (strtotime("-1 day") > strtotime($user['expires'])) {
echo "Disabling user {$user['name']} at index #{$index}\n";
//unset($config['system']['user'][$index]);
$user['disabled'] = true;
@ -58,8 +58,9 @@
}
}
if($removed > 0)
if ($removed > 0) {
write_config("Expired {$removed} user accounts");
}
//print_r($config);

View File

@ -2,31 +2,31 @@
<?php
/* $Id$ */
/*
rc.filter_configure
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
rc.filter_configure
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require_once("config.inc");

View File

@ -2,31 +2,31 @@
<?php
/* $Id$ */
/*
rc.filter_configure_sync
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
rc.filter_configure_sync
part of pfSense (https://www.pfsense.org)
Copyright (C) 2004 Scott Ullrich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require_once("config.inc");

View File

@ -1,37 +1,37 @@
#!/usr/local/bin/php -f
<?php
/*
rc.filter_configure_xmlrpc
Copyright (C) 2004-2006 Scott Ullrich
Copyright (C) 2005 Bill Marquette
Copyright (C) 2006 Peter Allgeyer
Copyright (C) 2008 Ermal Luci
All rights reserved.
rc.filter_configure_xmlrpc
Copyright (C) 2004-2006 Scott Ullrich
Copyright (C) 2005 Bill Marquette
Copyright (C) 2006 Peter Allgeyer
Copyright (C) 2008 Ermal Luci
All rights reserved.
originally part of m0n0wall (http://m0n0.ch/wall)
Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
All rights reserved.
originally part of m0n0wall (http://m0n0.ch/wall)
Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

View File

@ -3,9 +3,9 @@
/*
rc.filter_synchronize
Copyright (C) 2004-2006 Scott Ullrich
Copyright (C) 2005 Bill Marquette
Copyright (C) 2006 Peter Allgeyer
Copyright (C) 2008 Ermal Luci
Copyright (C) 2005 Bill Marquette
Copyright (C) 2006 Peter Allgeyer
Copyright (C) 2008 Ermal Luci
All rights reserved.
originally part of m0n0wall (http://m0n0.ch/wall)
@ -54,7 +54,7 @@ function backup_vip_config_section() {
return;
$temp = array();
$temp['vip'] = array();
foreach($config['virtualip']['vip'] as $section) {
foreach ($config['virtualip']['vip'] as $section) {
if (($section['mode'] == 'proxyarp' || $section['mode'] == 'ipalias') &&
(strpos($section['interface'], '_vip') === FALSE) &&
(strpos($section['interface'], 'lo0') === FALSE))
@ -62,14 +62,16 @@ function backup_vip_config_section() {
if ($section['advskew'] <> "") {
$section_val = intval($section['advskew']);
$section_val=$section_val+100;
if ($section_val > 254)
if ($section_val > 254) {
$section_val = 254;
}
$section['advskew'] = $section_val;
}
if ($section['advbase'] <> "") {
$section_val = intval($section['advbase']);
if ($section_val > 254)
if ($section_val > 254) {
$section_val = 254;
}
$section['advbase'] = $section_val;
}
$temp['vip'][] = $section;
@ -82,8 +84,9 @@ function remove_special_characters($string) {
preg_match_all("/[a-zA-Z0-9\_\-]+/",$string,$match_array);
$string = "";
foreach ($match_array[0] as $ma) {
if ($string <> "")
if ($string <> "") {
$string .= " ";
}
$string .= $ma;
}
return $string;
@ -92,7 +95,7 @@ function remove_special_characters($string) {
function carp_check_version($url, $username, $password, $port = 80, $method = 'pfsense.host_firmware_version') {
global $config, $g;
if(file_exists("{$g['varrun_path']}/booting") || platform_booting())
if (file_exists("{$g['varrun_path']}/booting") || platform_booting())
return;
$params = array(
@ -104,17 +107,18 @@ function carp_check_version($url, $username, $password, $port = 80, $method = 'p
$msg = new XML_RPC_Message($method, $params);
$cli = new XML_RPC_Client('/xmlrpc.php', $url, $port);
$cli->setCredentials($username, $password);
if($numberofruns > 0)
if ($numberofruns > 0) {
$cli->setDebug(1);
}
/* send our XMLRPC message and timeout after 240 seconds */
$resp = $cli->send($msg, "240");
if(!is_object($resp)) {
if (!is_object($resp)) {
$error = "A communications error occurred while attempting XMLRPC sync with username {$username} {$url}:{$port}.";
} elseif($resp->faultCode()) {
} elseif ($resp->faultCode()) {
$error = "An error code was received while attempting XMLRPC sync with username {$username} {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString();
} else {
$parsed_response = XML_RPC_decode($resp->value());
if(!is_array($parsed_response)) {
if (!is_array($parsed_response)) {
if (trim($parsed_response) == "Authentication failed") {
$error = "An authentication failure occurred while trying to access {$url}:{$port} ({$method}).";
log_error($error);
@ -127,8 +131,9 @@ function carp_check_version($url, $username, $password, $port = 80, $method = 'p
update_filter_reload_status("The other member is on older configuration version of {$g['product_name']}. Sync will not be done to prevent problems!");
log_error("The other member is on older configuration version of {$g['product_name']}. Sync will not be done to prevent problems!");
return false;
} else
} else {
return true;
}
}
}
log_error($error);
@ -142,7 +147,7 @@ function carp_check_version($url, $username, $password, $port = 80, $method = 'p
function carp_sync_xml($url, $username, $password, $sections, $port = 80, $method = 'pfsense.restore_config_section') {
global $config, $g;
if(file_exists("{$g['varrun_path']}/booting") || platform_booting())
if (file_exists("{$g['varrun_path']}/booting") || platform_booting())
return;
update_filter_reload_status("Syncing CARP data to {$url}");
@ -155,54 +160,60 @@ function carp_sync_xml($url, $username, $password, $sections, $port = 80, $metho
$rulescnt = count($config_copy['nat']['outbound']['rule']);
for ($x = 0; $x < $rulescnt; $x++) {
$config_copy['nat']['outbound']['rule'][$x]['descr'] = remove_special_characters($config_copy['nat']['outbound']['rule'][$x]['descr']);
if (isset ($config_copy['nat']['outbound']['rule'][$x]['nosync']))
if (isset ($config_copy['nat']['outbound']['rule'][$x]['nosync'])) {
unset ($config_copy['nat']['outbound']['rule'][$x]);
}
}
}
if (is_array($config_copy['nat']['rule'])) {
$natcnt = count($config_copy['nat']['rule']);
for ($x = 0; $x < $natcnt; $x++) {
$config_copy['nat']['rule'][$x]['descr'] = remove_special_characters($config_copy['nat']['rule'][$x]['descr']);
if (isset ($config_copy['nat']['rule'][$x]['nosync']))
if (isset ($config_copy['nat']['rule'][$x]['nosync'])) {
unset ($config_copy['nat']['rule'][$x]);
}
}
}
if (is_array($config_copy['filter']['rule'])) {
$filtercnt = count($config_copy['filter']['rule']);
for ($x = 0; $x < $filtercnt; $x++) {
$config_copy['filter']['rule'][$x]['descr'] = remove_special_characters($config_copy['filter']['rule'][$x]['descr']);
if (isset ($config_copy['filter']['rule'][$x]['nosync']))
if (isset ($config_copy['filter']['rule'][$x]['nosync'])) {
unset ($config_copy['filter']['rule'][$x]);
}
}
}
if (is_array($config_copy['aliases']['alias'])) {
$aliascnt = count($config_copy['aliases']['alias']);
for ($x = 0; $x < $aliascnt; $x++) {
$config_copy['aliases']['alias'][$x]['descr'] = remove_special_characters($config_copy['aliases']['alias'][$x]['descr']);
if (isset ($config_copy['aliases']['alias'][$x]['nosync']))
if (isset ($config_copy['aliases']['alias'][$x]['nosync'])) {
unset ($config_copy['aliases']['alias'][$x]);
}
}
}
if (is_array($config_copy['dnsmasq']['hosts'])) {
$dnscnt = count($config_copy['dnsmasq']['hosts']);
for ($x = 0; $x < $dnscnt; $x++) {
$config_copy['dnsmasq']['hosts'][$x]['descr'] = remove_special_characters($config_copy['dnsmasq']['hosts'][$x]['descr']);
if (isset ($config_copy['dnsmasq']['hosts'][$x]['nosync']))
if (isset ($config_copy['dnsmasq']['hosts'][$x]['nosync'])) {
unset ($config_copy['dnsmasq']['hosts'][$x]);
}
}
}
if (is_array($config_copy['ipsec']['tunnel'])) {
$ipseccnt = count($config_copy['ipsec']['tunnel']);
for ($x = 0; $x < $ipseccnt; $x++) {
$config_copy['ipsec']['tunnel'][$x]['descr'] = remove_special_characters($config_copy['ipsec']['tunnel'][$x]['descr']);
if (isset ($config_copy['ipsec']['tunnel'][$x]['nosync']))
if (isset ($config_copy['ipsec']['tunnel'][$x]['nosync'])) {
unset ($config_copy['ipsec']['tunnel'][$x]);
}
}
}
if (is_array($config_copy['dhcpd'])) {
foreach($config_copy['dhcpd'] as $dhcpif => $dhcpifconf) {
if($dhcpifconf['failover_peerip'] <> "") {
foreach ($config_copy['dhcpd'] as $dhcpif => $dhcpifconf) {
if ($dhcpifconf['failover_peerip'] <> "") {
$int = guess_interface_from_ip($dhcpifconf['failover_peerip']);
$intip = find_interface_ip($int);
$config_copy['dhcpd'][$dhcpif]['failover_peerip'] = $intip;
@ -244,21 +255,22 @@ function carp_sync_xml($url, $username, $password, $sections, $port = 80, $metho
$msg = new XML_RPC_Message($method, $params);
$cli = new XML_RPC_Client('/xmlrpc.php', $url, $port);
$cli->setCredentials($username, $password);
if($numberofruns > 0)
if ($numberofruns > 0) {
$cli->setDebug(1);
}
/* send our XMLRPC message and timeout after 240 seconds */
$resp = $cli->send($msg, "240");
if(!is_object($resp)) {
if (!is_object($resp)) {
$error = "A communications error occurred while attempting XMLRPC sync with username {$username} {$url}:{$port}.";
log_error($error);
file_notice("sync_settings", $error, "Settings Sync", "");
} elseif($resp->faultCode()) {
} elseif ($resp->faultCode()) {
$error = "An error code was received while attempting XMLRPC sync with username {$username} {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString();
log_error($error);
file_notice("sync_settings", $error, "Settings Sync", "");
} else {
$parsed_response = XML_RPC_decode($resp->value());
if(!is_array($parsed_response) && trim($parsed_response) == "Authentication failed") {
if (!is_array($parsed_response) && trim($parsed_response) == "Authentication failed") {
$error = "An authentication failure occurred while trying to access {$url}:{$port} ($method).";
log_error($error);
file_notice("sync_settings", $error, "Settings Sync", "");
@ -297,118 +309,144 @@ if (is_array($config['hasync'])) {
/* if port is empty lets rely on the protocol selection */
$port = $config['system']['webgui']['port'];
if (empty($port)) {
if ($config['system']['webgui']['protocol'] == "http")
if ($config['system']['webgui']['protocol'] == "http") {
$port = "80";
else
} else {
$port = "443";
}
}
if(is_ipaddrv6($hasync['synchronizetoip']))
if (is_ipaddrv6($hasync['synchronizetoip'])) {
$hasync['synchronizetoip'] = "[{$hasync['synchronizetoip']}]";
}
$synchronizetoip .= $hasync['synchronizetoip'];
if ($hasync['synchronizerules'] != "") {
if (!is_array($config['filter']))
if (!is_array($config['filter'])) {
$config['filter'] = array();
}
$sections[] = 'filter';
}
if ($hasync['synchronizenat'] != "") {
if (!is_array($config['nat']))
if (!is_array($config['nat'])) {
$config['nat'] = array();
}
$sections[] = 'nat';
}
if ($hasync['synchronizealiases'] != "") {
if (!is_array($config['aliases']))
if (!is_array($config['aliases'])) {
$config['aliases'] = array();
}
$sections[] = 'aliases';
}
if ($hasync['synchronizedhcpd'] != "" and is_array($config['dhcpd']))
if ($hasync['synchronizedhcpd'] != "" and is_array($config['dhcpd'])) {
$sections[] = 'dhcpd';
}
if ($hasync['synchronizewol'] != "") {
if (!is_array($config['wol']))
if (!is_array($config['wol'])) {
$config['wol'] = array();
}
$sections[] = 'wol';
}
if ($hasync['synchronizetrafficshaper'] != "" and is_array($config['shaper']))
if ($hasync['synchronizetrafficshaper'] != "" and is_array($config['shaper'])) {
$sections[] = 'shaper';
if ($hasync['synchronizetrafficshaperlimiter'] != "" and is_array($config['dnshaper']))
}
if ($hasync['synchronizetrafficshaperlimiter'] != "" and is_array($config['dnshaper'])) {
$sections[] = 'dnshaper';
if ($hasync['synchronizetrafficshaperlayer7'] != "" and is_array($config['l7shaper']))
}
if ($hasync['synchronizetrafficshaperlayer7'] != "" and is_array($config['l7shaper'])) {
$sections[] = 'l7shaper';
}
if ($hasync['synchronizestaticroutes'] != "") {
if (!is_array($config['staticroutes']))
if (!is_array($config['staticroutes'])) {
$config['staticroutes'] = array();
if (!is_array($config['staticroutes']['route']))
}
if (!is_array($config['staticroutes']['route'])) {
$config['staticroutes']['route'] = array();
}
$sections[] = 'staticroutes';
if (!is_array($config['gateways']))
if (!is_array($config['gateways'])) {
$config['gateways'] = array();
}
$sections[] = 'gateways';
}
if ($hasync['synchronizevirtualip'] != "") {
if (!is_array($config['virtualip']))
if (!is_array($config['virtualip'])) {
$config['virtualip'] = array();
}
$sections[] = 'virtualip';
}
if ($hasync['synchronizelb'] != "") {
if (!is_array($config['load_balancer']))
if (!is_array($config['load_balancer'])) {
$config['load_balancer'] = array();
}
$sections[] = 'load_balancer';
}
if ($hasync['synchronizeipsec'] != "") {
if (!is_array($config['ipsec']))
if (!is_array($config['ipsec'])) {
$config['ipsec'] = array();
}
$sections[] = 'ipsec';
}
if ($hasync['synchronizeopenvpn'] != "") {
if (!is_array($config['openvpn']))
if (!is_array($config['openvpn'])) {
$config['openvpn'] = array();
}
$sections[] = 'openvpn';
}
if ($hasync['synchronizecerts'] != "" || $hasync['synchronizeopenvpn'] != "") {
if (!is_array($config['cert']))
if (!is_array($config['cert'])) {
$config['cert'] = array();
}
$sections[] = 'cert';
if (!is_array($config['ca']))
if (!is_array($config['ca'])) {
$config['ca'] = array();
}
$sections[] = 'ca';
if (!is_array($config['crl']))
if (!is_array($config['crl'])) {
$config['crl'] = array();
}
$sections[] = 'crl';
}
if ($hasync['synchronizeusers'] != "") {
$sections[] = 'user';
$sections[] = 'group';
}
}
if ($hasync['synchronizeauthservers'] != "") {
$sections[] = 'authserver';
}
if ($hasync['synchronizednsforwarder'] != "") {
if (is_array($config['dnsmasq']))
if (is_array($config['dnsmasq'])) {
$sections[] = 'dnsmasq';
if (is_array($config['unbound']))
}
if (is_array($config['unbound'])) {
$sections[] = 'unbound';
}
}
if ($hasync['synchronizeschedules'] != "" || $hasync['synchronizerules'] != "") {
if (!is_array($config['schedules']))
if (!is_array($config['schedules'])) {
$config['schedules'] = array();
}
$sections[] = 'schedules';
}
if ($hasync['synchronizecaptiveportal'] != "" and is_array($config['captiveportal']))
if ($hasync['synchronizecaptiveportal'] != "" and is_array($config['captiveportal'])) {
$sections[] = 'captiveportal';
if ($hasync['synchronizecaptiveportal'] != "" and is_array($config['vouchers']))
}
if ($hasync['synchronizecaptiveportal'] != "" and is_array($config['vouchers'])) {
$sections[] = 'vouchers';
}
if (count($sections) <= 0) {
log_error("Nothing has been configured to be synched. Skipping....");
return;
}
if (empty($hasync['username']))
if (empty($hasync['username'])) {
$username = "admin";
else
} else {
$username = $hasync['username'];
}
if (!carp_check_version($synchronizetoip, $username, $hasync['password'], $port))
return;
@ -429,7 +467,7 @@ if (is_array($config['hasync'])) {
$error = "A communications error occurred while attempting Filter sync with username {$username} {$synchronizetoip}:{$port}.";
log_error($error);
file_notice("sync_settings", $error, "Settings Sync", "");
} elseif($resp->faultCode()) {
} elseif ($resp->faultCode()) {
$error = "An error code was received while attempting Filter sync with username {$username} {$synchronizetoip}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString();
log_error($error);
file_notice("sync_settings", $error, "Settings Sync", "");

View File

@ -29,7 +29,7 @@ fi
file_notice() {
/usr/local/bin/php -q -d auto_prepend_file=config.inc <<ENDOFF
<?php
require_once("globals.inc");
require_once("globals.inc");
require_once("functions.inc");
file_notice("$1", "$2", "$1", "");
?>
@ -39,7 +39,7 @@ ENDOFF
output_env_to_log() {
date >> /conf/upgrade_log.txt
echo "" >> /conf/upgrade_log.txt
ls -lah /dev/ >> /conf/upgrade_log.txt
echo "" >> /conf/upgrade_log.txt
@ -59,14 +59,14 @@ output_env_to_log() {
backup_chflags() {
TOPROCESS="bin lib libexec sbin usr"
for files in $TOPROCESS; do
/usr/sbin/mtree -Pcp /${files} | bzip2 -9 > /tmp/chflags.dist.${files}.bz2 2>> /conf/upgrade_log.txt
/usr/sbin/mtree -Pcp /${files} | bzip2 -9 > /tmp/chflags.dist.${files}.bz2 2>> /conf/upgrade_log.txt
done
}
restore_chflags() {
TOPROCESS="bin lib libexec sbin usr"
for files in $TOPROCESS; do
cd / && /usr/bin/bzcat /tmp/chflags.dist.${files}.bz2 | /usr/sbin/mtree -PU -p /${files} >> /conf/upgrade_log.txt 2>&1
cd / && /usr/bin/bzcat /tmp/chflags.dist.${files}.bz2 | /usr/sbin/mtree -P -p /${files} >> /conf/upgrade_log.txt 2>&1
done
}
@ -89,30 +89,30 @@ binary_update() {
remove_chflags
cd /tmp/patches
for i in `/usr/bin/tar tvzf $TGZ | egrep -v "(^d|_md5)" | nawk '{print $9;}'`;
do
FILE=`basename ${i}`
echo "Working on ${i}"
# Untar patch file and md5 files
/usr/bin/tar xzf ${TGZ} ${i} ${i}.old_file_md5 ${i}.new_patch_md5 ${i}.new_file_md5 2>>${ERR_F}
do
FILE=`basename ${i}`
echo "Working on ${i}"
# Untar patch file and md5 files
/usr/bin/tar xzf ${TGZ} ${i} ${i}.old_file_md5 ${i}.new_patch_md5 ${i}.new_file_md5 2>>${ERR_F}
# Apply patch - oldfile newfile patchfile
/usr/local/bin/bspatch /${i} /tmp/patched/${FILE} /tmp/patches/${i} 2>>${ERR_F}
# Apply patch - oldfile newfile patchfile
/usr/local/bin/bspatch /${i} /tmp/patched/${FILE} /tmp/patches/${i} 2>>${ERR_F}
OLD_FILE_MD5=`cat /tmp/patches/${i}.old_file_md5 2>/dev/null`
NEW_PATCH_MD5=`cat /tmp/patches/${i}.new_patch_md5 2>/dev/null`
NEW_FILE_MD5=`cat /tmp/patches/${i}.new_file_md5 2>/dev/null`
PATCHED_MD5=`/sbin/md5 -q /tmp/patched/${FILE} 2>/dev/null`
OLD_FILE_MD5=`cat /tmp/patches/${i}.old_file_md5 2>/dev/null`
NEW_PATCH_MD5=`cat /tmp/patches/${i}.new_patch_md5 2>/dev/null`
NEW_FILE_MD5=`cat /tmp/patches/${i}.new_file_md5 2>/dev/null`
PATCHED_MD5=`/sbin/md5 -q /tmp/patched/${FILE} 2>/dev/null`
if [ "$PATCHED_MD5" = "$NEW_PATCH_MD5" ]; then
/usr/bin/install -S /tmp/patched/${FILE} /${i}
else
#echo "${i} file does not match intended final md5."
echo "${i} file does not match intended final md5." >> ${ERR_F}
fi
if [ "$PATCHED_MD5" = "$NEW_PATCH_MD5" ]; then
/usr/bin/install -S /tmp/patched/${FILE} /${i}
else
#echo "${i} file does not match intended final md5."
echo "${i} file does not match intended final md5." >> ${ERR_F}
fi
/bin/rm /tmp/patched/${FILE} >> ${ERR_F}
/bin/rm /tmp/patches/${i} >> ${ERR_F}
/bin/rm /tmp/patches/${i}.* >> ${ERR_F}
/bin/rm /tmp/patched/${FILE} >> ${ERR_F}
/bin/rm /tmp/patches/${i} >> ${ERR_F}
/bin/rm /tmp/patches/${i}.* >> ${ERR_F}
done
/bin/rm -rf /tmp/patched /tmp/patches >> ${ERR_F}
restore_chflags
@ -123,7 +123,7 @@ enable)
touch /conf/upgrade_log.txt
echo "" >> /conf/upgrade_log.txt
echo "Enable" >> /conf/upgrade_log.txt
echo "" >> /conf/upgrade_log.txt
echo "" >> /conf/upgrade_log.txt
/etc/rc.conf_mount_ro
;;
auto)
@ -145,10 +145,10 @@ pfSenseNanoBSDupgrade)
# Prevent full upgrade file from being used to upgrade
if [ `echo $IMG | grep "full"` ]; then
echo "You cannot use a full file for upgrade. Please use a file labeled nanobsd upgrade."
file_notice "NanoBSDUpgradeFailure" "You have attemped to use a full NanoBSD installation file as an upgrade. Please use a NanoBSD file labeled 'upgrade' instead."
echo "You cannot use a full file for upgrade. Please use a file labelled nanobsd upgrade."
file_notice "NanoBSDUpgradeFailure" "You have attempted to use a full NanoBSD installation file as an upgrade. Please use a NanoBSD file labelled 'upgrade' instead."
rm -f $IMG
/etc/rc.conf_mount_ro
/etc/rc.conf_mount_ro
exit 1
fi
@ -157,7 +157,7 @@ pfSenseNanoBSDupgrade)
echo "NanoBSD Firmware upgrade in progress..." >> /conf/upgrade_log.txt 2>&1
echo "NanoBSD Firmware upgrade in progress..." | wall
/etc/rc.notify_message -e -g -m "NanoBSD Firmware upgrade in progress..."
# backup config
/bin/mkdir -p /tmp/configbak
cp -Rp /conf/* /tmp/configbak 2>/dev/null
@ -176,8 +176,8 @@ pfSenseNanoBSDupgrade)
REAL_BOOT_DEVICE=`/sbin/glabel list | /usr/bin/grep -B2 ufs/${BOOT_DEVICE} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`
# grab the boot device, example ad1, ad0
BOOT_DRIVE=`/sbin/glabel list | /usr/bin/grep -B2 ufs/pfsense | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' ' | /usr/bin/cut -d's' -f1`
# test the slice. if we are on slice 1 we need to flash 2 and vica versa
if [ `echo $REAL_BOOT_DEVICE | /usr/bin/grep "s1"` ]; then
# test the slice. if we are on slice 1 we need to flash 2 and vice versa
if [ `echo $REAL_BOOT_DEVICE | /usr/bin/grep "s1"` ]; then
SLICE="2"
OLDSLICE="1"
TOFLASH="${BOOT_DRIVE}s${SLICE}"
@ -187,7 +187,7 @@ pfSenseNanoBSDupgrade)
OLD_UFS_ID="0"
else
SLICE="1"
OLDSLICE="2"
OLDSLICE="2"
TOFLASH="${BOOT_DRIVE}s${SLICE}"
COMPLETE_PATH="${BOOT_DRIVE}s${SLICE}a"
GLABEL_SLICE="pfsense0"
@ -195,21 +195,21 @@ pfSenseNanoBSDupgrade)
OLD_UFS_ID="1"
fi
# Output specifc information that this script is using
# Output specific information that this script is using
echo "SLICE ${SLICE}" >> /conf/upgrade_log.txt
echo "OLDSLICE ${OLDSLICE}" >> /conf/upgrade_log.txt
echo "TOFLASH ${TOFLASH}" >> /conf/upgrade_log.txt
echo "COMPLETE_PATH ${COMPLETE_PATH}" >> /conf/upgrade_log.txt
echo "GLABEL_SLICE ${GLABEL_SLICE}" >> /conf/upgrade_log.txt
# First ensure the new file can fit inside the
# First ensure the new file can fit inside the
# slice that we are going to be operating on.
NEW_IMG_SIZE=`echo $((\`gzip -l ${IMG} | grep -v compressed | awk '{ print $2}'\` / 1024 / 1024))`
SIZE=`/sbin/fdisk ${COMPLETE_PATH} | /usr/bin/grep Meg | /usr/bin/awk '{ print $5 }' | /usr/bin/cut -d"(" -f2`
# USB slices are under-reported even more than CF slices when viewed
# directly, instead of when looking at the entire disk. Compensate
# by adding exactly 6MB. 4MB was consistently 2MB too few, and
# was resulting in failing upgrades on USB Flash based installs.
# directly, instead of when looking at the entire disk. Compensate
# by adding exactly 6MB. 4MB was consistently 2MB too few, and
# was resulting in failing upgrades on USB Flash based installs.
SIZE=`expr $SIZE + 6`
if [ "$SIZE" -lt "$NEW_IMG_SIZE" ]; then
file_notice "UpgradeFailure" "Upgrade failed due to the upgrade image being larger than the partition that is configured on disk. Halting. Size on disk: $SIZE < Size of new image: $NEW_IMG_SIZE"
@ -218,13 +218,13 @@ pfSenseNanoBSDupgrade)
rm -f /var/run/firmwarelock.dirty
rm -f /var/run/firmware.lock
rm -f ${IMG}
/etc/rc.conf_mount_ro
/etc/rc.conf_mount_ro
exit 1
fi
# Output environment information to log file
output_env_to_log
# Grab a before upgrade look at fdisk
echo "" >> /conf/fdisk_upgrade_log.txt
echo "Before upgrade fdisk/bsdlabel" >> /conf/fdisk_upgrade_log.txt
@ -234,7 +234,7 @@ pfSenseNanoBSDupgrade)
bsdlabel -A ${BOOT_DRIVE}s3 >> /conf/fdisk_upgrade_log.txt
echo "---------------------------------------------------------------" >> /conf/fdisk_upgrade_log.txt
echo "" >> /conf/fdisk_upgrade_log.txt
# Log that we are really doing a NanoBSD upgrade
echo "" >> /conf/upgrade_log.txt
echo "NanoBSD upgrade starting" >> /conf/upgrade_log.txt
@ -242,7 +242,7 @@ pfSenseNanoBSDupgrade)
# Remove TOFLASH and get ready for new flash image
echo "" >> /conf/upgrade_log.txt
echo "dd if=/dev/zero of=/dev/${TOFLASH} bs=1m count=1" >> /conf/upgrade_log.txt
echo "dd if=/dev/zero of=/dev/${TOFLASH} bs=1m count=1" >> /conf/upgrade_log.txt
dd if=/dev/zero of=/dev/${TOFLASH} bs=1m count=1 >> /conf/upgrade_log.txt 2>&1
# Stream gzipped image to dd and explode image to new area
@ -250,7 +250,7 @@ pfSenseNanoBSDupgrade)
echo "/usr/bin/gzip -dc $IMG | /bin/dd of=/dev/${TOFLASH} obs=64k" >> /conf/upgrade_log.txt
/usr/bin/gzip -dc $IMG | /bin/dd of=/dev/${TOFLASH} obs=64k >> /conf/upgrade_log.txt 2>&1
# Grab a after upgrade look at fdisk
# Grab an after upgrade look at fdisk
echo "" >> /conf/fdisk_upgrade_log.txt
echo "After upgrade fdisk/bsdlabel" >> /conf/upgrade_log.txt
fdisk $BOOT_DRIVE >> /conf/fdisk_upgrade_log.txt
@ -259,7 +259,7 @@ pfSenseNanoBSDupgrade)
bsdlabel -A ${BOOT_DRIVE}s3 >> /conf/fdisk_upgrade_log.txt
echo "---------------------------------------------------------------" >> /conf/fdisk_upgrade_log.txt
echo "" >> /conf/fdisk_upgrade_log.txt
# Ensure that our new system is sound and bail if it is not and file a notice
echo "" >> /conf/upgrade_log.txt
echo "/sbin/fsck_ufs -y /dev/${COMPLETE_PATH}" >> /conf/upgrade_log.txt
@ -269,7 +269,7 @@ pfSenseNanoBSDupgrade)
rm -f $IMG
rm -f /var/run/firmwarelock.dirty
rm -f /var/run/firmware.lock
/etc/rc.conf_mount_ro
/etc/rc.conf_mount_ro
exit 1
fi
@ -297,7 +297,7 @@ pfSenseNanoBSDupgrade)
cp /boot/loader.conf.local /tmp/$GLABEL_SLICE/boot/loader.conf.local
fi
# If /tmp/$GLABEL_SLICE/tmp/post_upgrade_command exists
# If /tmp/$GLABEL_SLICE/tmp/post_upgrade_command exists
# after update then execute the command.
echo "Checking for post_upgrade_command..." >> /conf/upgrade_log.txt
if [ -f /tmp/$GLABEL_SLICE/tmp/post_upgrade_command ]; then
@ -327,7 +327,7 @@ pfSenseNanoBSDupgrade)
# Unmount newly prepared slice
umount /tmp/$GLABEL_SLICE
sync
# Set active mount slice in fdisk
@ -364,7 +364,7 @@ pfSenseNanoBSDupgrade)
date >> /conf/upgrade_log.txt
echo "" >> /conf/upgrade_log.txt
# Trigger a package reinstallation on reobot
# Trigger a package reinstallation on reboot
touch /conf/needs_package_sync
# remount /cf ro
@ -391,7 +391,7 @@ pfSenseupgrade)
exit
fi
# wait 1 seconds before beginning
# wait 1 second before beginning
sleep 1
# Log that we are really doing a pfSense upgrade
@ -417,7 +417,7 @@ pfSenseupgrade)
remove_chflags
# Do we have a pre-upgrade hook in the update file?
if [ `tar tvzf $IMG | grep /tmp/pre_upgrade_command | wc -l` -gt 0 ]; then
if [ `tar tvzf $IMG | grep /tmp/pre_upgrade_command | wc -l` -gt 0 ]; then
tar xzvf $IMG -C / ./tmp/pre_upgrade_command >> /conf/upgrade_log.txt 2>&1
chmod a+rx /tmp/pre_upgrade_command >> /conf/upgrade_log.txt 2>&1
sh /tmp/pre_upgrade_command >> /conf/upgrade_log.txt 2>&1
@ -426,7 +426,7 @@ pfSenseupgrade)
echo "Firmware upgrade in progress..." >> /conf/upgrade_log.txt 2>&1
echo "Firmware upgrade in progress..." | wall
/etc/rc.notify_message -e -g -m "Firmware upgrade in progress..."
# backup config
[ -d /tmp/configbak ] && rm -rf /tmp/configbak
/bin/mkdir -p /tmp/configbak
@ -443,17 +443,17 @@ pfSenseupgrade)
/usr/local/sbin/check_reload_status
echo "Image installed $IMG." >> /conf/upgrade_log.txt 2>&1
# process custom image if its passed
if [ $# -eq 3 ]; then
if [ -f $CUSTOMIMG ]; then
echo "Custom image $CUSTOMIMG found." >> /conf/upgrade_log.txt 2>&1
echo "Custom image ($CUSTOMIMG) found." >> /conf/upgrade_log.txt 2>&1
PWD_DIR=`pwd`
cd / && /usr/bin/tar xzPUf $CUSTOMIMG >> /conf/upgrade_log.txt 2>&1
cd $PWD_DIR
echo "Custom image $CUSTOMIMG installed." >> /conf/upgrade_log.txt 2>&1
fi
fi
# process custom image if its passed
if [ $# -eq 3 ]; then
if [ -f $CUSTOMIMG ]; then
echo "Custom image $CUSTOMIMG found." >> /conf/upgrade_log.txt 2>&1
echo "Custom image ($CUSTOMIMG) found." >> /conf/upgrade_log.txt 2>&1
PWD_DIR=`pwd`
cd / && /usr/bin/tar xzPUf $CUSTOMIMG >> /conf/upgrade_log.txt 2>&1
cd $PWD_DIR
echo "Custom image $CUSTOMIMG installed." >> /conf/upgrade_log.txt 2>&1
fi
fi
# restore config
cp -Rp /tmp/configbak/* /conf 2>/dev/null

View File

@ -34,53 +34,53 @@ echo " Package MD5: ${PMD}" | logger -p daemon.info -i -t AutoUpgrade
echo "Downloaded MD5: ${MD}" | logger -p daemon.info -i -t AutoUpgrade
if [ "$PMD" = "" ]; then
echo "Package MD5 is null md5. Require proxy auth?" | logger -p daemon.info -i -t AutoUpgrade
exit 1
echo "Package MD5 is null md5. Require proxy auth?" | logger -p daemon.info -i -t AutoUpgrade
exit 1
fi
if [ "$MD" = "" ]; then
echo "Downloaded MD5 is null md5. Require proxy auth?" | logger -p daemon.info -i -t AutoUpgrade
exit 1
echo "Downloaded MD5 is null md5. Require proxy auth?" | logger -p daemon.info -i -t AutoUpgrade
exit 1
fi
if [ "$PMD" = "$MD" ]; then
echo "MD5's match." | logger -p daemon.info -i -t AutoUpgrade
echo "Beginning ${product} upgrade." | wall
if [ "$PLATFORM" = "net45xx" ]; then
/usr/local/bin/php /etc/rc.conf_mount_rw
fi
if [ "$PLATFORM" = "wrap" ]; then
/usr/local/bin/php /etc/rc.conf_mount_rw
fi
if [ "$PLATFORM" = "nanobsd" ]; then
/usr/local/bin/php /etc/rc.conf_mount_rw
fi
if [ -r "/tmp/custom.tgz" ]; then
sh /etc/rc.firmware pfSenseupgrade /tmp/latest.tgz /tmp/custom.tgz
else
if [ "$PLATFORM" = "nanobsd" ]; then
sh /etc/rc.firmware pfSenseNanoBSDupgrade /tmp/latest.tgz
else
sh /etc/rc.firmware pfSenseupgrade /tmp/latest.tgz
fi
fi
if [ "$PLATFORM" = "wrap" ]; then
/bin/sync
sleep 5
/usr/local/bin/php /etc/rc.conf_mount_ro
if [ -e /etc/init_bootloader.sh ]; then
sh /etc/init_bootloader.sh
fi
fi
if [ "$PLATFORM" = "net45xx" ]; then
/bin/sync
sleep 5
/usr/local/bin/php /etc/rc.conf_mount_ro
if [ -e /etc/init_bootloader.sh ]; then
sh /etc/init_bootloader.sh
fi
fi
exit 0
echo "MD5's match." | logger -p daemon.info -i -t AutoUpgrade
echo "Beginning ${product} upgrade." | wall
if [ "$PLATFORM" = "net45xx" ]; then
/usr/local/bin/php /etc/rc.conf_mount_rw
fi
if [ "$PLATFORM" = "wrap" ]; then
/usr/local/bin/php /etc/rc.conf_mount_rw
fi
if [ "$PLATFORM" = "nanobsd" ]; then
/usr/local/bin/php /etc/rc.conf_mount_rw
fi
if [ -r "/tmp/custom.tgz" ]; then
sh /etc/rc.firmware pfSenseupgrade /tmp/latest.tgz /tmp/custom.tgz
else
if [ "$PLATFORM" = "nanobsd" ]; then
sh /etc/rc.firmware pfSenseNanoBSDupgrade /tmp/latest.tgz
else
sh /etc/rc.firmware pfSenseupgrade /tmp/latest.tgz
fi
fi
if [ "$PLATFORM" = "wrap" ]; then
/bin/sync
sleep 5
/usr/local/bin/php /etc/rc.conf_mount_ro
if [ -e /etc/init_bootloader.sh ]; then
sh /etc/init_bootloader.sh
fi
fi
if [ "$PLATFORM" = "net45xx" ]; then
/bin/sync
sleep 5
/usr/local/bin/php /etc/rc.conf_mount_ro
if [ -e /etc/init_bootloader.sh ]; then
sh /etc/init_bootloader.sh
fi
fi
exit 0
fi
echo "MD5's do not match. Upgrade aborted." | logger -p daemon.info -i -t AutoUpgrade

View File

@ -69,14 +69,14 @@ else
fi
for i in /var/db/pfi/capable_*; do
if [ -f $i -a ! -L /cf/conf ]; then
option98="98) Move configuration file to removable device"
break
fi
if [ -f $i -a ! -L /cf/conf ]; then
option98="98) Move configuration file to removable device"
break
fi
done
if [ "$PLATFORM" = "cdrom" ]; then
option99="99) Install ${product} to a hard drive, etc."
option99="99) Install ${product} to a hard drive, etc."
fi
# display a cheap menu
@ -103,78 +103,78 @@ echo
# see what the user has chosen
case ${opmode} in
0)
exit && exit && logout
;;
exit && exit && logout
;;
1)
/etc/rc.initial.setports
;;
/etc/rc.initial.setports
;;
2)
/etc/rc.initial.setlanip
;;
/etc/rc.initial.setlanip
;;
3)
/etc/rc.initial.password
;;
/etc/rc.initial.password
;;
4)
/etc/rc.initial.defaults
;;
/etc/rc.initial.defaults
;;
5)
/etc/rc.initial.reboot
;;
/etc/rc.initial.reboot
;;
6)
/etc/rc.initial.halt
;;
/etc/rc.initial.halt
;;
7)
/etc/rc.initial.ping
;;
/etc/rc.initial.ping
;;
8)
/bin/tcsh
;;
/bin/tcsh
;;
9)
/usr/local/sbin/pftop
;;
/usr/local/sbin/pftop
;;
10)
/usr/local/sbin/clog -f /var/log/filter.log
;;
/usr/local/sbin/clog -f /var/log/filter.log
;;
11 | 111)
/etc/rc.restart_webgui
;;
/etc/rc.restart_webgui
;;
12)
/usr/local/sbin/pfSsh.php
;;
13)
php -f /etc/rc.initial.firmware_update
;;
14)
php -f /etc/rc.initial.toggle_sshd
;;
/usr/local/sbin/pfSsh.php
;;
13)
php -f /etc/rc.initial.firmware_update
;;
14)
php -f /etc/rc.initial.toggle_sshd
;;
15)
/etc/rc.restore_config_backup
;;
/etc/rc.restore_config_backup
;;
16)
/etc/rc.php-fpm_restart
;;
/etc/rc.php-fpm_restart
;;
98)
if [ ! -f /tmp/config_moved ]; then
/etc/rc.initial.store_config_to_removable_device
fi
;;
if [ ! -f /tmp/config_moved ]; then
/etc/rc.initial.store_config_to_removable_device
fi
;;
99)
if [ -e /dev/ukbd0 ]; then
env TERM=cons25 /scripts/lua_installer
else
/scripts/lua_installer
fi
;;
if [ -e /dev/ukbd0 ]; then
env TERM=cons25 /scripts/lua_installer
else
/scripts/lua_installer
fi
;;
100)
if grep "$WORD" "$CONFIG"; then
links "https://localhost"
else
links "http://localhost"
fi
;;
if grep "$WORD" "$CONFIG"; then
links "https://localhost"
else
links "http://localhost"
fi
;;
"")
kill $PPID ; exit
;;
kill $PPID ; exit
;;
esac
done

View File

@ -57,6 +57,6 @@ EOD;
system_reboot_sync();
}
fclose($fp);
?>

View File

@ -11,17 +11,19 @@ echo "Starting the {$g['product_name']} console firmware update system";
require("functions.inc");
echo ".";
if(isset($config['system']['firmware']['alturl']['enable']))
if(isset($config['system']['firmware']['alturl']['enable'])) {
$updater_url = "{$config['system']['firmware']['alturl']['firmwareurl']}";
else
} else {
$updater_url = $g['update_url'];
}
$nanosize = "";
if ($g['platform'] == "nanobsd") {
if (file_exists("/etc/nano_use_vga.txt"))
if (file_exists("/etc/nano_use_vga.txt")) {
$nanosize = "-nanobsd-vga-";
else
} else {
$nanosize = "-nanobsd-";
}
$nanosize .= strtolower(trim(file_get_contents("/etc/nanosize.txt")));
$update_filename = "latest{$nanosize}.img.gz";
@ -55,28 +57,28 @@ switch ($command) {
case "1":
echo "\nEnter the URL to the .tgz or .img.gz update file. \nType 'auto' to use {$autoupdateurl}\n> ";
$url = chop(fgets($fp));
if(!$url) {
if (!$url) {
fclose($fp);
die;
}
if($url == "auto") {
if ($url == "auto") {
$url = $autoupdateurl;
}
$status = does_url_exist($url);
if($status) {
if ($status) {
conf_mount_rw();
mark_subsystem_dirty('firmware');
unlink_if_exists("/root/firmware.tgz");
echo "\nFetching file... ";
download_file_with_progress_bar($url, '/root/firmware.tgz');
if(!file_exists("/root/firmware.tgz")) {
if (!file_exists("/root/firmware.tgz")) {
echo "Something went wrong during file transfer. Exiting.\n\n";
fclose($fp);
clear_subsystem_dirty('firmware');
die;
}
$status = does_url_exist("$url.sha256");
if($status) {
if ($status) {
echo "\nFetching sha256... ";
download_file_with_progress_bar($url . ".sha256", '/root/firmware.tgz.sha256');
echo "\n";
@ -92,12 +94,12 @@ switch ($command) {
die;
}
}
if(file_exists("/root/firmware.tgz.sha256")) {
if (file_exists("/root/firmware.tgz.sha256")) {
$source_sha256 = trim(`cat /root/firmware.tgz.sha256 | awk '{ print \$4 }'`,"\r");
$file_sha256 = trim(`sha256 /root/firmware.tgz | awk '{ print \$4 }'`,"\r");
echo "URL sha256: $source_sha256\n";
echo "Downloaded file sha256: $file_sha256\n";
if($source_sha256 <> $file_sha256) {
if ($source_sha256 <> $file_sha256) {
echo "\n\nsha256 checksum does not match. Cancelling upgrade.\n\n";
unlink_if_exists("/root/firmware.tgz.sha256");
fclose($fp);
@ -107,10 +109,10 @@ switch ($command) {
echo "\nsha256 checksum matches.\n";
unlink_if_exists("/root/firmware.tgz.sha256");
}
if(strstr($url,"bdiff")) {
if (strstr($url,"bdiff")) {
echo "Binary DIFF upgrade file detected...\n";
$type = "bdiff";
} elseif(strstr($url,"nanobsd")) {
} elseif (strstr($url,"nanobsd")) {
echo "NanoBSD upgrade file detected...\n";
$type = "nanobsd";
} else {
@ -123,15 +125,17 @@ switch ($command) {
case "2":
echo "\nEnter the complete path to the .tgz or .img.gz update file: ";
$path = chop(fgets($fp));
if(!$path) {
if (!$path) {
fclose($fp);
die;
}
if(stristr($path,"bdiff"))
if (stristr($path,"bdiff")) {
$type = "bdiff";
if(stristr($path,"nanobsd"))
$type = "nanobsd";
if(file_exists($path)) {
}
if (stristr($path,"nanobsd")) {
$type = "nanobsd";
}
if (file_exists($path)) {
mark_subsystem_dirty('firmware');
do_upgrade($path, $type);
clear_subsystem_dirty('firmware');
@ -144,15 +148,16 @@ switch ($command) {
function do_upgrade($path, $type) {
global $g, $fp;
$sigchk = verify_digital_signature($path);
if ($sigchk == 1)
if ($sigchk == 1) {
$sig_warning = "The digital signature on this image is invalid.";
else if ($sigchk == 2)
} elseif ($sigchk == 2) {
$sig_warning = "This image is not digitally signed.";
else if (($sigchk == 3) || ($sigchk == 4))
} elseif (($sigchk == 3) || ($sigchk == 4)) {
$sig_warning = "There has been an error verifying the signature on this image.";
if($sig_warning) {
}
if ($sig_warning) {
$sig_warning = "\nWARNING! ACHTUNG! DANGER!\n\n{$sig_warning}\n\n" .
"This means that the image you uploaded is not an official/supported image and\n" .
"may lead to unexpected behavior or security compromises.\n\n" .
@ -161,7 +166,7 @@ function do_upgrade($path, $type) {
"Do you want to install this image anyway at your own risk [n]?";
echo $sig_warning;
$command = strtoupper(chop(fgets($fp)));
if(strtoupper($command) == "Y" or strtoupper($command) == "Y" or strtoupper($command) == "YES") {
if (strtoupper($command) == "Y" or strtoupper($command) == "Y" or strtoupper($command) == "YES") {
echo "\nContinuing upgrade...";
} else {
echo "\nUpgrade cancelled.\n\n";
@ -170,14 +175,15 @@ function do_upgrade($path, $type) {
}
mark_subsystem_dirty('firmwarelock');
echo "\nOne moment please...\nInvoking firmware upgrade...";
if($type == "bdiff")
if ($type == "bdiff") {
mwexec_bg("/etc/rc.firmware delta_update $path");
elseif($type == "nanobsd")
} elseif ($type == "nanobsd") {
mwexec_bg("/etc/rc.firmware pfSenseNanoBSDupgrade $path");
else
} else {
mwexec_bg("/etc/rc.firmware pfSenseupgrade $path");
}
sleep(10);
while(is_subsystem_dirty('firmwarelock')) {
while (is_subsystem_dirty('firmwarelock')) {
sleep(1);
echo ".";
}

View File

@ -55,7 +55,7 @@ EOD;
system_halt();
}
fclose($fp);
?>

View File

@ -45,20 +45,22 @@ The webConfigurator admin password and privileges will be reset to the default (
if (strcasecmp(chop(fgets($fp)), "y") == 0) {
if (isset($config['system']['webgui']['authmode']) &&
$config['system']['webgui']['authmode'] != "Local Database") {
$config['system']['webgui']['authmode'] != "Local Database") {
echo "\n" . gettext('
The User manager authentication server is set to "' . $config['system']['webgui']['authmode'] . '".') . "\n" .
gettext('Do you want to set it back to Local Database [y|n]?');
if (strcasecmp(chop(fgets($fp)), "y") == 0)
if (strcasecmp(chop(fgets($fp)), "y") == 0) {
$config['system']['webgui']['authmode'] = "Local Database";
}
}
$admin_user =& getUserEntryByUID(0);
if (!$admin_user) {
echo "Failed to locate the admin user account! Attempting to restore access.\n";
$admin_user = array();
$admin_user['uid'] = 0;
if (!is_array($config['system']['user']))
if (!is_array($config['system']['user'])) {
$config['system']['user'] = array();
}
$config['system']['user'][] = $admin_user;
}
@ -66,8 +68,9 @@ The User manager authentication server is set to "' . $config['system']['webgui'
$admin_user['scope'] = "system";
$admin_user['priv'] = array("user-shell-access");
if (isset($admin_user['disabled']))
if (isset($admin_user['disabled'])) {
unset($admin_user['disabled']);
}
local_user_set_password($admin_user, strtolower($g['product_name']));
local_user_set($admin_user);

View File

@ -4,20 +4,20 @@
/*
rc.initial.ping
part of m0n0wall (http://m0n0.ch/wall)
Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
@ -33,9 +33,9 @@
/* parse the configuration and include all functions used below */
require_once("config.inc");
require_once("functions.inc");
$fp = fopen('php://stdin', 'r');
echo "\nEnter a host name or IP address: ";
$pinghost = chop(fgets($fp));
@ -50,6 +50,6 @@
echo "\nPress ENTER to continue.\n";
fgets($fp);
}
fclose($fp);
?>

View File

@ -55,7 +55,7 @@ EOD;
system_reboot_sync();
}
fclose($fp);
?>

View File

@ -30,8 +30,6 @@
POSSIBILITY OF SUCH DAMAGE.
*/
$options = getopt("hn", array("dry-run", "help"));
if (isset($options["h"]) || isset($options["help"])) {
@ -46,8 +44,6 @@ if ($dry_run) {
echo "DRY RUN MODE IS ON\n";
}
/* parse the configuration and include all functions used below */
require_once("config.inc");
require_once("functions.inc");
@ -93,9 +89,10 @@ function console_get_interface_from_ppp($realif) {
function prompt_for_enable_dhcp_server($version = 4) {
global $config, $fp, $interface;
if($interface == "wan") {
if($config['interfaces']['lan'])
if ($interface == "wan") {
if ($config['interfaces']['lan']) {
return false;
}
}
/* only allow DHCP server to be enabled when static IP is
configured on this interface */
@ -116,7 +113,9 @@ function prompt_for_enable_dhcp_server($version = 4) {
function get_interface_config_description($iface) {
global $config;
$c = $config['interfaces'][$iface];
if (!$c) { return null; }
if (!$c) {
return null;
}
$if = $c['if'];
$result = $if;
$result2 = array();
@ -143,28 +142,27 @@ $fp = fopen('php://stdin', 'r');
/* build an interface collection */
$ifdescrs = get_configured_interface_with_descr(false, true);
$count = count($ifdescrs);
/* grab interface that we will operate on, unless there is only one
interface */
/* grab interface that we will operate on, unless there is only one interface */
if ($count > 1) {
echo "Available interfaces:\n\n";
$x=1;
foreach($ifdescrs as $iface => $ifdescr) {
foreach ($ifdescrs as $iface => $ifdescr) {
$config_descr = get_interface_config_description($iface);
echo "{$x} - {$ifdescr} ({$config_descr})\n";
$x++;
}
echo "\nEnter the number of the interface you wish to configure: ";
$intnum = chop(fgets($fp));
$intnum = chop(fgets($fp));
} else {
$intnum = $count;
}
if($intnum < 1)
if ($intnum < 1)
return;
if($intnum > $count)
if ($intnum > $count)
return;
$index = 1;
foreach ($ifdescrs as $ifname => $ifdesc) {
if ($intnum == $index) {
@ -173,8 +171,8 @@ foreach ($ifdescrs as $ifname => $ifdesc) {
} else {
$index++;
}
}
if(!$interface) {
}
if (!$interface) {
echo "Invalid interface!\n";
return;
}
@ -185,7 +183,9 @@ function next_unused_gateway_name($interface) {
global $g, $config;
$new_name = "GW_" . strtoupper($interface);
if (!is_array($config['gateways']['gateway_item'])) { return $new_name; }
if (!is_array($config['gateways']['gateway_item'])) {
return $new_name;
}
$count = 1;
do {
$existing = false;
@ -216,10 +216,12 @@ function add_gateway_to_config($interface, $gatewayip, $inet_type) {
$is_default = true;
foreach ($a_gateways as $item) {
if ($item['ipprotocol'] === $inet_type) {
if (isset($item['defaultgw']))
if (isset($item['defaultgw'])) {
$is_default = false;
if (($item['interface'] === $interface) && ($item['gateway'] === $gatewayip))
}
if (($item['interface'] === $interface) && ($item['gateway'] === $gatewayip)) {
$new_name = $item['name'];
}
}
}
if ($new_name == '') {
@ -252,34 +254,36 @@ function console_configure_ip_address($version) {
$upperifname = strtoupper($interface);
if($interface == "wan") {
if ($interface == "wan") {
if (console_prompt_for_yn (sprintf(gettext("Configure %s address %s interface via %s?"), $label_IPvX, $upperifname, $label_DHCP))) {
$ifppp = console_get_interface_from_ppp(get_real_interface("wan"));
if (!empty($ifppp))
if (!empty($ifppp)) {
$ifaceassigned = $ifppp;
}
$intip = ($version === 6) ? "dhcp6" : "dhcp";
$intbits = "";
$isintdhcp = true;
$restart_dhcpd = true;
}
}
}
if($isintdhcp == false or $interface <> "wan") {
while(true) {
if ($isintdhcp == false or $interface <> "wan") {
while (true) {
do {
echo "\n" . sprintf(gettext("Enter the new %s %s address. Press <ENTER> for none:"),
$upperifname, $label_IPvX) . "\n> ";
$upperifname, $label_IPvX) . "\n> ";
$intip = chop(fgets($fp));
$is_ipaddr = ($version === 6) ? is_ipaddrv6($intip) : is_ipaddrv4($intip);
if ($is_ipaddr && is_ipaddr_configured($intip, $interface, true)) {
$ip_conflict = true;
echo gettext("This IP address conflicts with another interface or a VIP") . "\n";
} else
} else {
$ip_conflict = false;
}
} while (($ip_conflict === true) || !($is_ipaddr || $intip == ''));
if ($intip != '') {
echo "\n" . sprintf(gettext("Subnet masks are entered as bit counts (as in CIDR notation) in %s."),
$g['product_name']) . "\n";
$g['product_name']) . "\n";
if ($version === 6) {
echo "e.g. ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00 = 120\n";
echo " ffff:ffff:ffff:ffff:ffff:ffff:ffff:0 = 112\n";
@ -294,7 +298,7 @@ function console_configure_ip_address($version) {
do {
$upperifname = strtoupper($interface);
echo "\n" . sprintf(gettext("Enter the new %s %s subnet bit count (1 to %s):"),
$upperifname, $label_IPvX, $maxbits) . "\n> ";
$upperifname, $label_IPvX, $maxbits) . "\n> ";
$intbits = chop(fgets($fp));
$intbits_ok = is_numeric($intbits) && (($intbits >= 1) && ($intbits <= $maxbits));
$restart_dhcpd = true;
@ -338,8 +342,9 @@ function console_configure_ip_address($version) {
}
}
$ifppp = console_get_interface_from_ppp(get_real_interface($interface));
if (!empty($ifppp))
if (!empty($ifppp)) {
$ifaceassigned = $ifppp;
}
break;
}
}
@ -350,8 +355,9 @@ function console_configure_ip_address($version) {
list($intip, $intbits, $gwname) = console_configure_ip_address(4);
list($intip6, $intbits6, $gwname6) = console_configure_ip_address(6);
if (!empty($ifaceassigned))
if (!empty($ifaceassigned)) {
$config['interfaces'][$interface]['if'] = $ifaceassigned;
}
$config['interfaces'][$interface]['ipaddr'] = $intip;
$config['interfaces'][$interface]['subnet'] = $intbits;
$config['interfaces'][$interface]['gateway'] = $gwname;
@ -366,7 +372,7 @@ function console_configure_dhcpd($version = 4) {
$label_IPvX = ($version === 6) ? "IPv6" : "IPv4";
$dhcpd = ($version === 6) ? "dhcpdv6" : "dhcpd";
if($g['services_dhcp_server_enable'] && prompt_for_enable_dhcp_server($version)) {
if ($g['services_dhcp_server_enable'] && prompt_for_enable_dhcp_server($version)) {
$subnet_start = ($version === 6) ? gen_subnetv6($intip6, $intbits6) : gen_subnet($intip, $intbits);
$subnet_end = ($version === 6) ? gen_subnetv6_max($intip6, $intbits6) : gen_subnet_max($intip, $intbits);
do {
@ -379,8 +385,9 @@ function console_configure_dhcpd($version = 4) {
}
$is_ipaddr = ($version === 6) ? is_ipaddrv6($dhcpstartip) : is_ipaddrv4($dhcpstartip);
$is_inrange = is_inrange($dhcpstartip, $subnet_start, $subnet_end);
if (!$is_inrange)
if (!$is_inrange) {
echo gettext("This IP address must be in the interface's subnet") . "\n";
}
} while (!$is_ipaddr || !$is_inrange);
do {
@ -392,8 +399,9 @@ function console_configure_dhcpd($version = 4) {
}
$is_ipaddr = ($version === 6) ? is_ipaddrv6($dhcpendip) : is_ipaddrv4($dhcpendip);
$is_inrange = is_inrange($dhcpendip, $subnet_start, $subnet_end);
if (!$is_inrange)
if (!$is_inrange) {
echo gettext("This IP address must be in the interface's subnet") . "\n";
}
$not_inorder = ($version === 6) ? (inet_pton($dhcpendip) < inet_pton($dhcpstartip)) : ip_less_than($dhcpendip, $dhcpstartip);
if ($not_inorder) {
echo gettext("The end address of the DHCP range must be >= the start address") . "\n";
@ -405,7 +413,7 @@ function console_configure_dhcpd($version = 4) {
$config[$dhcpd][$interface]['range']['from'] = $dhcpstartip;
$config[$dhcpd][$interface]['range']['to'] = $dhcpendip;
} else {
if(isset($config[$dhcpd][$interface]['enable'])) {
if (isset($config[$dhcpd][$interface]['enable'])) {
unset($config[$dhcpd][$interface]['enable']);
printf(gettext("Disabling %s DHCPD..."), $label_IPvX);
$restart_dhcpd = true;
@ -418,7 +426,7 @@ if (console_configure_dhcpd(4) == 0)
return 0;
if (console_configure_dhcpd(6) == 0)
return 0;
//*****************************************************************************
if ($config['system']['webgui']['protocol'] == "https") {
@ -434,21 +442,27 @@ if (isset($config['system']['webgui']['noantilockout'])) {
unset($config['system']['webgui']['noantilockout']);
}
if($config['interfaces']['lan']) {
if($config['dhcpd'])
if($config['dhcpd']['wan'])
unset($config['dhcpd']['wan']);
if($config['dhcpdv6'])
if($config['dhcpdv6']['wan'])
if ($config['interfaces']['lan']) {
if ($config['dhcpd']) {
if ($config['dhcpd']['wan']) {
unset($config['dhcpd']['wan']);
}
}
if ($config['dhcpdv6']) {
if ($config['dhcpdv6']['wan']) {
unset($config['dhcpdv6']['wan']);
}
}
}
if(!$config['interfaces']['lan']) {
if (!$config['interfaces']['lan']) {
unset($config['interfaces']['lan']);
if($config['dhcpd']['lan'])
if ($config['dhcpd']['lan']) {
unset($config['dhcpd']['lan']);
if($config['dhcpdv6']['lan'])
}
if ($config['dhcpdv6']['lan']) {
unset($config['dhcpdv6']['lan']);
}
unset($config['shaper']);
unset($config['ezshaper']);
unset($config['nat']);
@ -467,32 +481,32 @@ if (!$dry_run) {
filter_configure_sync();
echo "\n Reloading routing configuration...";
system_routing_configure();
if($restart_dhcpd) {
echo "\n DHCPD...";
if ($restart_dhcpd) {
echo "\n DHCPD...";
services_dhcpd_configure();
}
if($restart_webgui) {
if ($restart_webgui) {
echo "\n Restarting webConfigurator... ";
mwexec("/etc/rc.restart_webgui");
}
}
if ($intip != '') {
if (is_ipaddr($intip)) {
echo "\n\n" . sprintf(gettext("The IPv4 %s address has been set to %s"),
$upperifname, "{$intip}/{$intbits}") . "\n";
$upperifname, "{$intip}/{$intbits}") . "\n";
} else {
echo "\n\n" . sprintf(gettext("The IPv4 %s address has been set to %s"),
$upperifname, $intip) . "\n";
$upperifname, $intip) . "\n";
}
}
if ($intip6 != '') {
if (is_ipaddr($intip6)) {
echo "\n\n" . sprintf(gettext("The IPv6 %s address has been set to %s"),
$upperifname, "${intip6}/${intbits6}") . "\n";
$upperifname, "${intip6}/${intbits6}") . "\n";
} else {
echo "\n\n" . sprintf(gettext("The IPv6 %s address has been set to %s"),
$upperifname, $intip6) . "\n";
$upperifname, $intip6) . "\n";
}
}
@ -503,7 +517,7 @@ if ($intip != '' || $intip6 != '') {
echo "interface is {$interface} \n";
}
echo gettext('You can now access the webConfigurator by opening the following URL in your web browser:') . "\n";
if(!empty($config['system']['webgui']['port'])) {
if (!empty($config['system']['webgui']['port'])) {
$webuiport = $config['system']['webgui']['port'];
if ($intip != '') {
echo " {$config['system']['webgui']['protocol']}://{$intip}:{$webuiport}/\n";
@ -534,5 +548,5 @@ echo "\n" . gettext('Press <ENTER> to continue.');
fgets($fp);
fclose($fp);
?>

View File

@ -44,8 +44,8 @@
set_networking_interfaces_ports();
reload_interfaces_sync();
/* reload graphing functions */
enable_rrd_graphing();
enable_rrd_graphing();
?>

Some files were not shown because too many files have changed in this diff Show More