diff --git a/usr/local/www/includes/authgui.inc b/usr/local/www/includes/authgui.inc deleted file mode 100644 index fe2c05fcc..000000000 --- a/usr/local/www/includes/authgui.inc +++ /dev/null @@ -1,317 +0,0 @@ - - All rights reserved. - - Copyright (C) 2005-2006 Bill Marquette - All rights reserved. - - Copyright (C) 2006 Paul Taylor . - All rights reserved. - - Copyright (C) 2003-2006 Manuel Kasper . - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - 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: authgui -*/ -include_once("auth.inc"); -include_once("priv.inc"); - -/* Authenticate user - exit if failed */ -if (!session_auth()) { - display_login_form(); - exit; -} - -/* - * Once here, the user has authenticated with the web server. - * We give them access only to the appropriate pages based on - * the user or group privileges. - */ -$allowedpages = getAllowedPages($_SESSION['Username']); - -/* - * redirect to first allowed page if requesting a wrong url - */ -if (!isAllowedPage($_SERVER['REQUEST_URI'])) { - if (count($allowedpages) > 0) { - $page = str_replace('*', '', $allowedpages[0]); - $_SESSION['Post_Login'] = true; - require_once("functions.inc"); - pfSenseHeader("/{$page}"); - - $username = empty($_SESSION["Username"]) ? "(system)" : $_SESSION['Username']; - 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; - } else { - display_error_form("201", gettext("No page assigned to this user! Click here to logout.")); - exit; - } -} else - $_SESSION['Post_Login'] = true; - - /* - * redirect browsers post-login to avoid pages - * taking action in reponse to a POST request - */ - if (!$_SESSION['Post_Login']) { - $_SESSION['Post_Login'] = true; - require_once("functions.inc"); - pfSenseHeader($_SERVER['REQUEST_URI']); - exit; - } - - /* - * Close session data to allow other scripts from same host to come in. - * A session can be reactivated from calling session_start again - */ - session_commit(); - - /* - * determine if the user is allowed access to the requested page - */ - function display_error_form($http_code, $desc) { - global $config, $g; - $g['theme'] = get_current_theme(); - if(isAjax()) { - printf(gettext('Error: %1$s Description: %2$s'), $http_code, $desc); - return; - } - - ?> - - - - - - - - - - - - - - - - - <?=$http_code?> - - - - - - - - - - - - - "True") { - isset($_SESSION['Login_Error']) ? $login_error = $_SESSION['Login_Error'] : $login_error = gettext("unknown reason"); - printf("showajaxmessage('" . gettext("Invalid login (%s).") . "')", $login_error); - } - if (file_exists("{$g['tmp_path']}/webconfigurator.lock")) { - // TODO: add the IP from the user who did lock the device - $whom = file_get_contents("{$g['tmp_path']}/webconfigurator.lock"); - printf("showajaxmessage('" . gettext("This device is currently being maintained by: %s.") . "');", $whom); - } - } - exit; - } - - /* Check against locally configured IP addresses, which will catch when someone - port forwards WebGUI access from WAN to an internal IP on the router. */ - global $FilterIflist, $nifty_background; - $local_ip = false; - if(strstr($_SERVER['HTTP_HOST'], ":")) { - $http_host_port = explode(":", $_SERVER['HTTP_HOST']); - $http_host = $http_host_port[0]; - } else { - $http_host = $_SERVER['HTTP_HOST']; - } - if (empty($FilterIflist)) { - require_once('filter.inc'); - require_once('shaper.inc'); - filter_generate_optcfg_array(); - } - foreach ($FilterIflist as $iflist) { - if($iflist['ip'] == $http_host) - $local_ip = true; - if($iflist['ipv6'] == $http_host) - $local_ip = true; - } - unset($FilterIflist); - - if($config['virtualip']) { - if($config['virtualip']['vip']) { - foreach($config['virtualip']['vip'] as $vip) { - if($vip['subnet'] == $http_host) - $local_ip = true; - } - } - } - if (is_array($config['openvpn']['openvpn-server'])) { - foreach ($config['openvpn']['openvpn-server'] as $ovpns) { - if (is_ipaddrv4($http_host) && !empty($ovpns['tunnel_network']) && ip_in_subnet($http_host, $ovpns['tunnel_network'])) { - $local_ip = true; - break; - } - - if (is_ipaddrv6($http_host) && !empty($ovpns['tunnel_networkv6']) && ip_in_subnet($http_host, $ovpns['tunnel_networkv6'])) { - $local_ip = true; - break; - } - } - } - setcookie("cookie_test", time() + 3600); - $have_cookies = isset($_COOKIE["cookie_test"]); - - ?> - - - - - - - - - - - - - - - - - <?=gettext("Login"); ?> - - - - - - - - - - - - - - - - - - - - - diff --git a/usr/local/www/includes/functions.inc b/usr/local/www/includes/functions.inc deleted file mode 100644 index 509c16e90..000000000 --- a/usr/local/www/includes/functions.inc +++ /dev/null @@ -1,152 +0,0 @@ -. - 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. - - pfSense_MODULE: utils - -*/ - -/* BEGIN compatibility goo with HEAD */ -if(!function_exists("gettext")) { - function gettext($text) { - return $text; - } -} - -if(!function_exists("pfSenseHeader")) { - /****f* pfsense-utils/pfSenseHeader - * NAME - * pfSenseHeader - * INPUTS - * none - * RESULT - * Javascript header change or browser Location: - ******/ - function pfSenseHeader($text) { - global $_SERVER; - if (isAjax()) { - if ($_SERVER['HTTPS'] == "on") - $protocol = "https"; - else - $protocol = "http"; - - $port = ":{$_SERVER['SERVER_PORT']}"; - if ($_SERVER['SERVER_PORT'] == "80" && $protocol == "http") - $port = ""; - if ($_SERVER['SERVER_PORT'] == "443" && $protocol == "https") - $port = ""; - $complete_url = "{$protocol}://{$_SERVER['SERVER_NAME']}{$port}/{$text}"; - echo "\ndocument.location.href = '{$complete_url}';\n"; - } else { - header("Location: $text"); - } - } -} -/* END compatibility goo with HEAD */ - -/*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 = "
    "; - - $notice_msgs .= "
  • ".gettext("Acknowledge All Notices")."
  • "; - - 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}'); jQuery(this).parent().parent().remove();\""; - $notice_msgs .= "
  • {$date} [ ".htmlspecialchars($noticemsg)."]
  • "; - } - $notice_msgs .="
"; - - - $menu_messages = ''; - - 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.="{$msg} {$notice_msgs}\n"; - - } - } - else { - $menu_messages=''; - $menu_messages.= "".$config['system']['hostname'] . "." . $config['system']['domain'].""; - $menu_messages.=''; - } - return ($menu_messages); - } -} - -if(!function_exists("dom_title")) { - function dom_title($title_msg,$width=NULL){ - $width=preg_replace("/\D+/","",$width); - if (!empty($width)){ - $width=",'width',$width"; - } - if (!empty($title_msg)){ - $title_msg=preg_replace("/\s+/"," ",$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"); -require_once("services.inc"); -require_once("pfsense-utils.inc"); -require_once("certs.inc"); -require_once("system.inc"); -require_once("vslb.inc"); - -?> diff --git a/usr/local/www/includes/globals.inc b/usr/local/www/includes/globals.inc deleted file mode 100644 index 9b6dc4d45..000000000 --- a/usr/local/www/includes/globals.inc +++ /dev/null @@ -1,164 +0,0 @@ -. - 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. - - pfSense_MODULE: utils - -*/ - -global $g; -$g = array( - "base_packages" => "siproxd", - "event_address" => "unix:///var/run/check_reload_status", - "factory_shipped_username" => "admin", - "factory_shipped_password" => "opnsense", - "upload_path" => "/root", - "dhcpd_chroot_path" => "/var/dhcpd", - "unbound_chroot_path" => "/var/unbound", - "varrun_path" => "/var/run", - "varetc_path" => "/var/etc", - "vardb_path" => "/var/db", - "varlog_path" => "/var/log", - "etc_path" => "/etc", - "tmp_path" => "/tmp", - "conf_path" => "/conf", - "ftmp_path" => "/ftmp", - "conf_default_path" => "/conf.default", - "cf_path" => "/cf", - "cf_conf_path" => "/cf/conf", - "www_path" => "/usr/local/www", - "xml_rootobj" => "pfsense", - "admin_group" => "admins", - "product_name" => "OPNsense", - "product_copyright" => "Deciso B.V.", - "product_copyright_url" => "http://www.deciso.com", - "product_copyright_years" => "2014 - ".date("Y"), - "product_website" => "www.opnsense.org", - "product_website_footer" => "https://www.opnsense.org/?gui22", - "product_email" => "coreteam@opnsense.org", - "hideplatform" => false, - "hidedownloadbackup" => false, - "hidebackupbeforeupgrade" => false, - "disablethemeselection" => false, - "disablehelpmenu" => false, - "disablehelpicon" => false, - "disablecrashreporter" => false, - "crashreporterurl" => "https://crashreporter.opnsense.org/crash_reporter.php", - "debug" => false, - "latest_config" => "11.1", - "nopkg_platforms" => array("cdrom"), - "minimum_ram_warning" => "101", - "minimum_ram_warning_text" => "128 MB", - "wan_interface_name" => "wan", - "nopccard_platforms" => array("wrap", "net48xx"), - "xmlrpcbaseurl" => "https://packages.pfsense.org", - "captiveportal_path" => "/usr/local/captiveportal", - "captiveportal_element_path" => "/var/db/cpelements", - "captiveportal_element_sizelimit" => 1048576, - "xmlrpcpath" => "/xmlrpc.php", - "embeddedbootupslice" => "/dev/ad0a", - "services_dhcp_server_enable" => true, - "wireless_regex" => "/^(ndis|wi|ath|an|ral|ural|iwi|wlan|rum|run|bwn|zyd|mwl|bwi|ipw|iwn|malo|uath|upgt|urtw|wpi)/", - "help_base_url" => "/help.php" -); - -/* IP TOS flags */ -$iptos = array("lowdelay", "throughput", "reliability"); - -/* TCP flags */ -$tcpflags = array("syn", "ack", "fin", "rst", "psh", "urg", "ece", "cwr"); - -if(file_exists("/etc/platform")) { - $arch = php_uname("m"); - /* Do not remove this, it is not needed for the snapshots URL but is needed later for the -RELEASE/stable URLs */ - //$arch = ($arch == "i386") ? "" : '/' . $arch; - - /* Full installs and NanoBSD use the same update directory and manifest in 2.x */ - $g['update_url']="https://snapshots.opnsense.org/FreeBSD_releng/10.1/{$arch}/pfSense_HEAD/.updaters/"; - $g['update_manifest']="https://updates.opnsense.org/manifest"; - - $g['platform'] = trim(file_get_contents("/etc/platform")); - if($g['platform'] == "nanobsd") { - $g['firmware_update_text']="OPNsense-*.img.gz"; - $g['hidedownloadbackup'] = true; - $g['hidebackupbeforeupgrade'] = true; - - } else { - $g['firmware_update_text']="pfSense-*.tgz"; - } -} - -/* Default sysctls */ -$sysctls = array("net.inet.ip.portrange.first" => "1024", - "net.inet.tcp.blackhole" => "2", - "net.inet.udp.blackhole" => "1", - "net.inet.ip.random_id" => "1", - "net.inet.tcp.drop_synfin" => "1", - "net.inet.ip.redirect" => "1", - "net.inet6.ip6.redirect" => "1", - "net.inet6.ip6.use_tempaddr" => "0", - "net.inet6.ip6.prefer_tempaddr" => "0", - "net.inet.tcp.syncookies" => "1", - "net.inet.tcp.recvspace" => "65228", - "net.inet.tcp.sendspace" => "65228", - "net.inet.ip.fastforwarding" => "0", - "net.inet.tcp.delayed_ack" => "0", - "net.inet.udp.maxdgram" => "57344", - "net.link.bridge.pfil_onlyip" => "0", - "net.link.bridge.pfil_member" => "1", - "net.link.bridge.pfil_bridge" => "0", - "net.link.tap.user_open" => "1", - "kern.randompid" => "347", - "net.inet.ip.intr_queue_maxlen" => "1000", - "hw.syscons.kbd_reboot" => "0", - "net.inet.tcp.log_debug" => "0", - "net.inet.tcp.tso" => "1", - "net.inet.icmp.icmplim" => "0", - "vfs.read_max" => "32", - "kern.ipc.maxsockbuf" => "4262144", - "debug.pfftpproxy" => "0", - "net.inet.ip.process_options" => 0, - "kern.random.sys.harvest.interrupt" => 0, - "kern.random.sys.harvest.point_to_point" => 0, - "kern.random.sys.harvest.ethernet" => 0, - "net.route.netisr_maxqlen" => 1024, - "net.inet.udp.checksum" => 1, - "net.bpf.zerocopy_enable" => 1, - "net.inet.icmp.reply_from_interface" => 1 -); - -/* 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")) - @include("globals_override.inc"); - -$config_parsed = false; - -?> diff --git a/usr/local/www/includes/pfsense-utils.inc b/usr/local/www/includes/pfsense-utils.inc deleted file mode 100644 index 776260b6b..000000000 --- a/usr/local/www/includes/pfsense-utils.inc +++ /dev/null @@ -1,2911 +0,0 @@ - real interface if needed */ - $int = get_real_interface($interface); - if(empty($int)) - return; - $int_family = preg_split("/[0-9]+/", $int); - $supported_ints = array('fxp'); - if (in_array($int_family, $supported_ints)) { - if(does_interface_exist($int)) - pfSense_interface_flags($int, IFF_LINK0); - } - - return; -} - -/****f* pfsense-utils/interface_supports_polling - * NAME - * checks to see if an interface supports polling according to man polling - * INPUTS - * - * RESULT - * true or false - * NOTES - * - ******/ -function interface_supports_polling($iface) { - $opts = pfSense_get_interface_addresses($iface); - if (is_array($opts) && isset($opts['caps']['polling'])) - return true; - - return false; -} - -/****f* pfsense-utils/is_alias_inuse - * NAME - * checks to see if an alias is currently in use by a rule - * INPUTS - * - * RESULT - * true or false - * NOTES - * - ******/ -function is_alias_inuse($alias) { - global $g, $config; - - if($alias == "") return false; - /* loop through firewall rules looking for alias in use */ - if(is_array($config['filter']['rule'])) - foreach($config['filter']['rule'] as $rule) { - if($rule['source']['address']) - if($rule['source']['address'] == $alias) - return true; - if($rule['destination']['address']) - if($rule['destination']['address'] == $alias) - return true; - } - /* loop through nat rules looking for alias in use */ - if(is_array($config['nat']['rule'])) - foreach($config['nat']['rule'] as $rule) { - if($rule['target'] && $rule['target'] == $alias) - return true; - if($rule['source']['address'] && $rule['source']['address'] == $alias) - return true; - if($rule['destination']['address'] && $rule['destination']['address'] == $alias) - return true; - } - return false; -} - -/****f* pfsense-utils/is_schedule_inuse - * NAME - * checks to see if a schedule is currently in use by a rule - * INPUTS - * - * RESULT - * true or false - * NOTES - * - ******/ -function is_schedule_inuse($schedule) { - global $g, $config; - - if($schedule == "") return false; - /* loop through firewall rules looking for schedule in use */ - if(is_array($config['filter']['rule'])) - foreach($config['filter']['rule'] as $rule) { - if($rule['sched'] == $schedule) - return true; - } - return false; -} - -/****f* pfsense-utils/setup_polling - * NAME - * sets up polling - * INPUTS - * - * RESULT - * null - * NOTES - * - ******/ -function setup_polling() { - global $g, $config; - - if (isset($config['system']['polling'])) - set_single_sysctl("kern.polling.idle_poll", "1"); - else - set_single_sysctl("kern.polling.idle_poll", "0"); - - if($config['system']['polling_each_burst']) - set_single_sysctl("kern.polling.each_burst", $config['system']['polling_each_burst']); - if($config['system']['polling_burst_max']) - set_single_sysctl("kern.polling.burst_max", $config['system']['polling_burst_max']); - if($config['system']['polling_user_frac']) - set_single_sysctl("kern.polling.user_frac", $config['system']['polling_user_frac']); -} - -/****f* pfsense-utils/setup_microcode - * NAME - * enumerates all interfaces and calls enable_hardware_offloading which - * enables a NIC's supported hardware features. - * INPUTS - * - * RESULT - * null - * NOTES - * This function only supports the fxp driver's loadable microcode. - ******/ -function setup_microcode() { - - /* if list */ - $ifs = get_interface_arr(); - - foreach($ifs as $if) - enable_hardware_offloading($if); -} - -/****f* pfsense-utils/get_carp_status - * NAME - * get_carp_status - Return whether CARP is enabled or disabled. - * RESULT - * boolean - true if CARP is enabled, false if otherwise. - ******/ -function get_carp_status() { - /* grab the current status of carp */ - $status = get_single_sysctl('net.inet.carp.allow'); - return (intval($status) > 0); -} - -/* - * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form - - */ -function convert_ip_to_network_format($ip, $subnet) { - $ipsplit = explode('.', $ip); - $string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet; - return $string; -} - -/* - * get_carp_interface_status($carpinterface): returns the status of a carp ip - */ -function get_carp_interface_status($carpinterface) { - $carp_query = ""; - - /* XXX: Need to fidn a better way for this! */ - list ($interface, $vhid) = explode("_vip", $carpinterface); - $interface = get_real_interface($interface); - exec("/sbin/ifconfig $interface | /usr/bin/grep -v grep | /usr/bin/grep carp: | /usr/bin/grep 'vhid {$vhid}'", $carp_query); - foreach($carp_query as $int) { - if(stristr($int, "MASTER")) - return gettext("MASTER"); - if(stristr($int, "BACKUP")) - return gettext("BACKUP"); - if(stristr($int, "INIT")) - return gettext("INIT"); - } - return; -} - -/* - * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync - */ -function get_pfsync_interface_status($pfsyncinterface) { - if (!does_interface_exist($pfsyncinterface)) - return; - - return exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'"); -} - -/* - * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor - */ -function add_rule_to_anchor($anchor, $rule, $label) { - mwexec("echo " . escapeshellarg($rule) . " | /sbin/pfctl -a " . escapeshellarg($anchor) . ":" . escapeshellarg($label) . " -f -"); -} - -/* - * remove_text_from_file - * remove $text from file $file - */ -function remove_text_from_file($file, $text) { - if(!file_exists($file) && !is_writable($file)) - return; - $filecontents = file_get_contents($file); - $text = str_replace($text, "", $filecontents); - @file_put_contents($file, $text); -} - -/* - * add_text_to_file($file, $text): adds $text to $file. - * replaces the text if it already exists. - */ -function add_text_to_file($file, $text, $replace = false) { - if(file_exists($file) and is_writable($file)) { - $filecontents = file($file); - $filecontents = array_map('rtrim', $filecontents); - array_push($filecontents, $text); - if ($replace) - $filecontents = array_unique($filecontents); - - $file_text = implode("\n", $filecontents); - - @file_put_contents($file, $file_text); - return true; - } - return false; -} - -/* - * after_sync_bump_adv_skew(): create skew values by 1S - */ -function after_sync_bump_adv_skew() { - global $config, $g; - $processed_skew = 1; - $a_vip = &$config['virtualip']['vip']; - foreach ($a_vip as $vipent) { - if($vipent['advskew'] <> "") { - $processed_skew = 1; - $vipent['advskew'] = $vipent['advskew']+1; - } - } - if($processed_skew == 1) - write_config(gettext("After synch increase advertising skew")); -} - -/* - * get_filename_from_url($url): converts a url to its filename. - */ -function get_filename_from_url($url) { - return basename($url); -} - -/* - * get_dir: return an array of $dir - */ -function get_dir($dir) { - $dir_array = array(); - $d = dir($dir); - while (false !== ($entry = $d->read())) { - array_push($dir_array, $entry); - } - $d->close(); - return $dir_array; -} - -/****f* pfsense-utils/WakeOnLan - * NAME - * WakeOnLan - Wake a machine up using the wake on lan format/protocol - * RESULT - * true/false - true if the operation was successful - ******/ -function WakeOnLan($addr, $mac) -{ - $addr_byte = explode(':', $mac); - $hw_addr = ''; - - for ($a=0; $a < 6; $a++) - $hw_addr .= chr(hexdec($addr_byte[$a])); - - $msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255); - - for ($a = 1; $a <= 16; $a++) - $msg .= $hw_addr; - - // send it to the broadcast address using UDP - $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); - if ($s == false) { - log_error(gettext("Error creating socket!")); - log_error(sprintf(gettext("Error code is '%1\$s' - %2\$s"), socket_last_error($s), socket_strerror(socket_last_error($s)))); - } else { - // setting a broadcast option to socket: - $opt_ret = socket_set_option($s, 1, 6, TRUE); - if($opt_ret < 0) - log_error(sprintf(gettext("setsockopt() failed, error: %s"), strerror($opt_ret))); - $e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050); - socket_close($s); - log_error(sprintf(gettext('Magic Packet sent (%1$s) to {%2$s} MAC=%3$s'), $e, $addr, $mac)); - return true; - } - - return false; -} - -/* - * reverse_strrchr($haystack, $needle): Return everything in $haystack up to the *last* instance of $needle. - * Useful for finding paths and stripping file extensions. - */ -function reverse_strrchr($haystack, $needle) { - if (!is_string($haystack)) - return; - return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false; -} - -/* - * backup_config_section($section): returns as an xml file string of - * the configuration section - */ -function backup_config_section($section_name) { - global $config; - $new_section = &$config[$section_name]; - /* generate configuration XML */ - $xmlconfig = dump_xml_config($new_section, $section_name); - $xmlconfig = str_replace("", "", $xmlconfig); - return $xmlconfig; -} - -/* - * restore_config_section($section_name, new_contents): restore a configuration section, - * and write the configuration out - * to disk/cf. - */ -function restore_config_section($section_name, $new_contents) { - global $config, $g; - conf_mount_rw(); - $fout = fopen("{$g['tmp_path']}/tmpxml","w"); - fwrite($fout, $new_contents); - fclose($fout); - - $xml = parse_xml_config($g['tmp_path'] . "/tmpxml", null); - if ($xml['pfsense']) { - $xml = $xml['pfsense']; - } - else if ($xml['m0n0wall']) { - $xml = $xml['m0n0wall']; - } - if ($xml[$section_name]) { - $section_xml = $xml[$section_name]; - } else { - $section_xml = -1; - } - - @unlink($g['tmp_path'] . "/tmpxml"); - if ($section_xml === -1) { - return false; - } - $config[$section_name] = &$section_xml; - if(file_exists("{$g['tmp_path']}/config.cache")) - unlink("{$g['tmp_path']}/config.cache"); - write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name)); - disable_security_checks(); - conf_mount_ro(); - return true; -} - -/* - * merge_config_section($section_name, new_contents): restore a configuration section, - * and write the configuration out - * to disk/cf. But preserve the prior - * structure if needed - */ -function merge_config_section($section_name, $new_contents) { - global $config; - conf_mount_rw(); - $fname = get_tmp_filename(); - $fout = fopen($fname, "w"); - fwrite($fout, $new_contents); - fclose($fout); - $section_xml = parse_xml_config($fname, $section_name); - $config[$section_name] = $section_xml; - unlink($fname); - write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name)); - disable_security_checks(); - conf_mount_ro(); - return; -} - -/* - * http_post($server, $port, $url, $vars): does an http post to a web server - * posting the vars array. - * written by nf@bigpond.net.au - */ -function http_post($server, $port, $url, $vars) { - $user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)"; - $urlencoded = ""; - while (list($key,$value) = each($vars)) - $urlencoded.= urlencode($key) . "=" . urlencode($value) . "&"; - $urlencoded = substr($urlencoded,0,-1); - $content_length = strlen($urlencoded); - $headers = "POST $url HTTP/1.1 -Accept: */* -Accept-Language: en-au -Content-Type: application/x-www-form-urlencoded -User-Agent: $user_agent -Host: $server -Connection: Keep-Alive -Cache-Control: no-cache -Content-Length: $content_length - -"; - - $errno = ""; - $errstr = ""; - $fp = fsockopen($server, $port, $errno, $errstr); - if (!$fp) { - return false; - } - - fputs($fp, $headers); - fputs($fp, $urlencoded); - - $ret = ""; - while (!feof($fp)) - $ret.= fgets($fp, 1024); - fclose($fp); - - return $ret; -} - -/* - * php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors - */ -if (!function_exists('php_check_syntax')){ - global $g; - function php_check_syntax($code_to_check, &$errormessage){ - return false; - $fout = fopen("{$g['tmp_path']}/codetocheck.php","w"); - $code = $_POST['content']; - $code = str_replace("", "", $code); - fwrite($fout, "\n"); - fclose($fout); - $command = "/usr/local/bin/php -l {$g['tmp_path']}/codetocheck.php"; - $output = exec_command($command); - if (stristr($output, "Errors parsing") == false) { - echo "false\n"; - $errormessage = ''; - return(false); - } else { - $errormessage = $output; - return(true); - } - } -} - -/* - * php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors - */ -if (!function_exists('php_check_syntax')){ - function php_check_syntax($code_to_check, &$errormessage){ - return false; - $command = "/usr/local/bin/php -l " . escapeshellarg($code_to_check); - $output = exec_command($command); - if (stristr($output, "Errors parsing") == false) { - echo "false\n"; - $errormessage = ''; - return(false); - } else { - $errormessage = $output; - return(true); - } - } -} - -/* - * rmdir_recursive($path,$follow_links=false) - * Recursively remove a directory tree (rm -rf path) - * This is for directories _only_ - */ -function rmdir_recursive($path,$follow_links=false) { - $to_do = glob($path); - if(!is_array($to_do)) $to_do = array($to_do); - foreach($to_do as $workingdir) { // Handle wildcards by foreaching. - if(file_exists($workingdir)) { - if(is_dir($workingdir)) { - $dir = opendir($workingdir); - while ($entry = readdir($dir)) { - if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry"))) - unlink("$workingdir/$entry"); - elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..') - rmdir_recursive("$workingdir/$entry"); - } - closedir($dir); - rmdir($workingdir); - } elseif (is_file($workingdir)) { - unlink($workingdir); - } - } - } - return; -} - -/* - * call_pfsense_method(): Call a method exposed by the pfsense.org XMLRPC server. - */ -function call_pfsense_method($method, $params, $timeout = 0) { - global $g, $config; - - $xmlrpc_base_url = get_active_xml_rpc_base_url(); - $xmlrpc_path = $g['xmlrpcpath']; - - $xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url); - $ip = gethostbyname($xmlrpcfqdn); - if($ip == $xmlrpcfqdn) - return false; - - $msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params))); - $port = 0; - $proxyurl = ""; - $proxyport = 0; - $proxyuser = ""; - $proxypass = ""; - if (!empty($config['system']['proxyurl'])) - $proxyurl = $config['system']['proxyurl']; - if (!empty($config['system']['proxyport']) && is_numeric($config['system']['proxyport'])) - $proxyport = $config['system']['proxyport']; - if (!empty($config['system']['proxyuser'])) - $proxyuser = $config['system']['proxyuser']; - if (!empty($config['system']['proxypass'])) - $proxypass = $config['system']['proxypass']; - $cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url, $port, $proxyurl, $proxyport, $proxyuser, $proxypass); - // If the ALT PKG Repo has a username/password set, use it. - if($config['system']['altpkgrepo']['username'] && - $config['system']['altpkgrepo']['password']) { - $username = $config['system']['altpkgrepo']['username']; - $password = $config['system']['altpkgrepo']['password']; - $cli->setCredentials($username, $password); - } - $resp = $cli->send($msg, $timeout); - if(!is_object($resp)) { - log_error(sprintf(gettext("XMLRPC communication error: %s"), $cli->errstr)); - return false; - } elseif($resp->faultCode()) { - log_error(sprintf(gettext('XMLRPC request failed with error %1$s: %2$s'), $resp->faultCode(), $resp->faultString())); - return false; - } else { - return XML_RPC_Decode($resp->value()); - } -} - -/* - * check_firmware_version(): Check whether the current firmware installed is the most recently released. - */ -function check_firmware_version($tocheck = "all", $return_php = true) { - global $g, $config; - - $xmlrpc_base_url = get_active_xml_rpc_base_url(); - $xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url); - $ip = gethostbyname($xmlrpcfqdn); - if($ip == $xmlrpcfqdn) - return false; - $version = php_uname('r'); - $version = explode('-', $version); - $rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))), - "kernel" => array("version" => $version[0]), - "base" => array("version" => $version[0]), - "platform" => trim(file_get_contents('/etc/platform')), - "config_version" => $config['version'] - ); - unset($version); - - if($tocheck == "all") { - $params = $rawparams; - } else { - foreach($tocheck as $check) { - $params['check'] = $rawparams['check']; - $params['platform'] = $rawparams['platform']; - } - } - if($config['system']['firmware']['branch']) - $params['branch'] = $config['system']['firmware']['branch']; - - /* XXX: What is this method? */ - if(!($versions = call_pfsense_method('pfsense.get_firmware_version', $params))) { - return false; - } else { - $versions["current"] = $params; - } - - return $versions; -} - -/* - * host_firmware_version(): Return the versions used in this install - */ -function host_firmware_version($tocheck = "") { - global $g, $config; - - $os_version = trim(substr(php_uname("r"), 0, strpos(php_uname("r"), '-'))); - - return array( - "firmware" => array("version" => trim(file_get_contents('/etc/version', " \n"))), - "kernel" => array("version" => $os_version), - "base" => array("version" => $os_version), - "platform" => trim(file_get_contents('/etc/platform', " \n")), - "config_version" => $config['version'] - ); -} - -function get_disk_info() { - $diskout = ""; - exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $2, $3, $4, $5 }'", $diskout); - return explode(' ', $diskout[0]); -} - -/****f* pfsense-utils/strncpy - * NAME - * strncpy - copy strings - * INPUTS - * &$dst, $src, $length - * RESULT - * none - ******/ -function strncpy(&$dst, $src, $length) { - if (strlen($src) > $length) { - $dst = substr($src, 0, $length); - } else { - $dst = $src; - } -} - -/****f* pfsense-utils/reload_interfaces_sync - * NAME - * reload_interfaces - reload all interfaces - * INPUTS - * none - * RESULT - * none - ******/ -function reload_interfaces_sync() { - global $config, $g; - - if($g['debug']) - log_error(gettext("reload_interfaces_sync() is starting.")); - - /* parse config.xml again */ - $config = parse_config(true); - - /* enable routing */ - system_routing_enable(); - if($g['debug']) - log_error(gettext("Enabling system routing")); - - if($g['debug']) - log_error(gettext("Cleaning up Interfaces")); - - /* set up interfaces */ - interfaces_configure(); -} - -/****f* pfsense-utils/reload_all - * NAME - * reload_all - triggers a reload of all settings - * * INPUTS - * none - * RESULT - * none - ******/ -function reload_all() { - send_event("service reload all"); -} - -/****f* pfsense-utils/reload_interfaces - * NAME - * reload_interfaces - triggers a reload of all interfaces - * INPUTS - * none - * RESULT - * none - ******/ -function reload_interfaces() { - send_event("interface all reload"); -} - -/****f* pfsense-utils/reload_all_sync - * NAME - * reload_all - reload all settings - * * INPUTS - * none - * RESULT - * none - ******/ -function reload_all_sync() { - global $config, $g; - - $g['booting'] = false; - - /* parse config.xml again */ - $config = parse_config(true); - - /* set up our timezone */ - system_timezone_configure(); - - /* set up our hostname */ - system_hostname_configure(); - - /* make hosts file */ - system_hosts_generate(); - - /* generate resolv.conf */ - system_resolvconf_generate(); - - /* enable routing */ - system_routing_enable(); - - /* set up interfaces */ - interfaces_configure(); - - /* start dyndns service */ - services_dyndns_configure(); - - /* configure cron service */ - configure_cron(); - - /* start the NTP client */ - system_ntp_configure(); - - /* sync pw database */ - conf_mount_rw(); - unlink_if_exists("/etc/spwd.db.tmp"); - mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd"); - conf_mount_ro(); - - /* restart sshd */ - send_event("service restart sshd"); - - /* restart webConfigurator if needed */ - send_event("service restart webgui"); -} - -function setup_serial_port($when="save", $path="") { - global $g, $config; - conf_mount_rw(); - $prefix = ""; - if (($when == "upgrade") && (!empty($path)) && is_dir($path.'/boot/')) - $prefix = "/tmp/{$path}"; - $boot_config_file = "{$path}/boot.config"; - $loader_conf_file = "{$path}/boot/loader.conf"; - /* serial console - write out /boot.config */ - if(file_exists($boot_config_file)) - $boot_config = file_get_contents($boot_config_file); - else - $boot_config = ""; - - $serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "115200"; - if ($g['platform'] != "cdrom") { - $boot_config_split = explode("\n", $boot_config); - $fd = fopen($boot_config_file,"w"); - if($fd) { - foreach($boot_config_split as $bcs) { - if(stristr($bcs, "-D") || stristr($bcs, "-h")) { - /* DONT WRITE OUT, WE'LL DO IT LATER */ - } else { - if($bcs <> "") - fwrite($fd, "{$bcs}\n"); - } - } - if (($g['platform'] == "nanobsd") && !file_exists("/etc/nano_use_vga.txt")) - fwrite($fd, "-S{$serialspeed} -h"); - else if (is_serial_enabled()) - fwrite($fd, "-S{$serialspeed} -D"); - fclose($fd); - } - - /* serial console - write out /boot/loader.conf */ - if ($when == "upgrade") - system("echo \"Reading {$loader_conf_file}...\" >> /conf/upgrade_log.txt"); - $boot_config = file_get_contents($loader_conf_file); - $boot_config_split = explode("\n", $boot_config); - if(count($boot_config_split) > 0) { - $new_boot_config = array(); - // Loop through and only add lines that are not empty, and which - // do not contain a console directive. - foreach($boot_config_split as $bcs) - if(!empty($bcs) - && (stripos($bcs, "console") === false) - && (stripos($bcs, "boot_multicons") === false) - && (stripos($bcs, "boot_serial") === false) - && (stripos($bcs, "hw.usb.no_pf") === false)) - $new_boot_config[] = $bcs; - - if (($g['platform'] == "nanobsd") && !file_exists("/etc/nano_use_vga.txt")) { - $new_boot_config[] = 'boot_serial="YES"'; - $new_boot_config[] = 'console="comconsole"'; - } else if (is_serial_enabled()) { - $new_boot_config[] = 'boot_multicons="YES"'; - $new_boot_config[] = 'boot_serial="YES"'; - $primaryconsole = isset($g['primaryconsole_force']) ? $g['primaryconsole_force'] : $config['system']['primaryconsole']; - switch ($primaryconsole) { - case "video": - $new_boot_config[] = 'console="vidconsole,comconsole"'; - break; - case "serial": - default: - $new_boot_config[] = 'console="comconsole,vidconsole"'; - } - } - $new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"'; - $new_boot_config[] = 'hw.usb.no_pf="1"'; - - file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n"); - } - } - $ttys = file_get_contents("/etc/ttys"); - $ttys_split = explode("\n", $ttys); - $fd = fopen("/etc/ttys", "w"); - - $on_off = (is_serial_enabled() ? 'on' : 'off'); - - if (isset($config['system']['disableconsolemenu'])) { - $console_type = 'Pc'; - $serial_type = 'std.' . $serialspeed; - } else { - $console_type = 'al.Pc'; - $serial_type = 'al.' . $serialspeed; - } - foreach($ttys_split as $tty) { - if (stristr($tty, "ttyv0")) - fwrite($fd, "ttyv0 \"/usr/libexec/getty {$console_type}\" cons25 on secure\n"); - else if (stristr($tty, "ttyu0")) - fwrite($fd, "ttyu0 \"/usr/libexec/getty {$serial_type}\" cons25 {$on_off} secure\n"); - else - fwrite($fd, $tty . "\n"); - } - unset($on_off, $console_type, $serial_type); - fclose($fd); - reload_ttys(); - - conf_mount_ro(); - return; -} - -function is_serial_enabled() { - global $g, $config; - - if (!isset($g['enableserial_force']) && - !isset($config['system']['enableserial']) && - ($g['platform'] == "pfSense" || $g['platform'] == "cdrom" || file_exists("/etc/nano_use_vga.txt"))) - return false; - - return true; -} - -function reload_ttys() { - // Send a HUP signal to init will make it reload /etc/ttys - posix_kill(1, SIGHUP); -} - -function print_value_list($list, $count = 10, $separator = ",") { - $list = implode($separator, array_slice($list, 0, $count)); - if(count($list) < $count) { - $list .= "."; - } else { - $list .= "..."; - } - return $list; -} - -/* DHCP enabled on any interfaces? */ -function is_dhcp_server_enabled() { - global $config; - - if (!is_array($config['dhcpd'])) - return false; - - foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) { - if (isset($dhcpifconf['enable']) && !empty($config['interfaces'][$dhcpif])) - return true; - } - - return false; -} - -/* DHCP enabled on any interfaces? */ -function is_dhcpv6_server_enabled() { - global $config; - - if (is_array($config['interfaces'])) { - foreach ($config['interfaces'] as $ifcfg) { - if (isset($ifcfg['enable']) && !empty($ifcfg['track6-interface'])) - return true; - } - } - - if (!is_array($config['dhcpdv6'])) - return false; - - foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) { - if (isset($dhcpv6ifconf['enable']) && !empty($config['interfaces'][$dhcpv6if])) - return true; - } - - return false; -} - -/* radvd enabled on any interfaces? */ -function is_radvd_enabled() { - global $config; - - if (!is_array($config['dhcpdv6'])) - $config['dhcpdv6'] = array(); - - $dhcpdv6cfg = $config['dhcpdv6']; - $Iflist = get_configured_interface_list(); - - /* handle manually configured DHCP6 server settings first */ - foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) { - if(!isset($config['interfaces'][$dhcpv6if]['enable'])) - continue; - - if(!isset($dhcpv6ifconf['ramode'])) - $dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode']; - - if($dhcpv6ifconf['ramode'] == "disabled") - continue; - - $ifcfgipv6 = get_interface_ipv6($dhcpv6if); - if(!is_ipaddrv6($ifcfgipv6)) - continue; - - return true; - } - - /* handle DHCP-PD prefixes and 6RD dynamic interfaces */ - foreach ($Iflist as $if => $ifdescr) { - if(!isset($config['interfaces'][$if]['track6-interface'])) - continue; - if(!isset($config['interfaces'][$if]['enable'])) - continue; - - $ifcfgipv6 = get_interface_ipv6($if); - if(!is_ipaddrv6($ifcfgipv6)) - continue; - - $ifcfgsnv6 = get_interface_subnetv6($if); - $subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6); - - if(!is_ipaddrv6($subnetv6)) - continue; - - return true; - } - - return false; -} - -/* Any PPPoE servers enabled? */ -function is_pppoe_server_enabled() { - global $config; - - $pppoeenable = false; - - if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe'])) - return false; - - foreach ($config['pppoes']['pppoe'] as $pppoes) - if ($pppoes['mode'] == 'server') - $pppoeenable = true; - - return $pppoeenable; -} - -function convert_seconds_to_hms($sec){ - $min=$hrs=0; - if ($sec != 0){ - $min = floor($sec/60); - $sec %= 60; - } - if ($min != 0){ - $hrs = floor($min/60); - $min %= 60; - } - if ($sec < 10) - $sec = "0".$sec; - if ($min < 10) - $min = "0".$min; - if ($hrs < 10) - $hrs = "0".$hrs; - $result = $hrs.":".$min.":".$sec; - return $result; -} - -/* Compute the total uptime from the ppp uptime log file in the conf directory */ - -function get_ppp_uptime($port){ - if (file_exists("/conf/{$port}.log")){ - $saved_time = file_get_contents("/conf/{$port}.log"); - $uptime_data = explode("\n",$saved_time); - $sec=0; - foreach($uptime_data as $upt) { - $sec += substr($upt, 1 + strpos($upt, " ")); - } - return convert_seconds_to_hms($sec); - } else { - $total_time = gettext("No history data found!"); - return $total_time; - } -} - -//returns interface information -function get_interface_info($ifdescr) { - global $config, $g; - - $ifinfo = array(); - if (empty($config['interfaces'][$ifdescr])) - return; - $ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if']; - $ifinfo['if'] = get_real_interface($ifdescr); - - $chkif = $ifinfo['if']; - $ifinfotmp = pfSense_get_interface_addresses($chkif); - $ifinfo['status'] = $ifinfotmp['status']; - if (empty($ifinfo['status'])) - $ifinfo['status'] = "down"; - $ifinfo['macaddr'] = $ifinfotmp['macaddr']; - $ifinfo['ipaddr'] = $ifinfotmp['ipaddr']; - $ifinfo['subnet'] = $ifinfotmp['subnet']; - $ifinfo['linklocal'] = get_interface_linklocal($ifdescr); - $ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr); - $ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr); - if (isset($ifinfotmp['link0'])) - $link0 = "down"; - $ifinfotmp = pfSense_get_interface_stats($chkif); - // $ifinfo['inpkts'] = $ifinfotmp['inpkts']; - // $ifinfo['outpkts'] = $ifinfotmp['outpkts']; - $ifinfo['inerrs'] = $ifinfotmp['inerrs']; - $ifinfo['outerrs'] = $ifinfotmp['outerrs']; - $ifinfo['collisions'] = $ifinfotmp['collisions']; - - /* Use pfctl for non wrapping 64 bit counters */ - /* Pass */ - exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats); - $pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]); - $pf_out4_pass = preg_split("/ +/", $pfctlstats[5]); - $pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]); - $pf_out6_pass = preg_split("/ +/", $pfctlstats[9]); - $in4_pass = $pf_in4_pass[5]; - $out4_pass = $pf_out4_pass[5]; - $in4_pass_packets = $pf_in4_pass[3]; - $out4_pass_packets = $pf_out4_pass[3]; - $in6_pass = $pf_in6_pass[5]; - $out6_pass = $pf_out6_pass[5]; - $in6_pass_packets = $pf_in6_pass[3]; - $out6_pass_packets = $pf_out6_pass[3]; - $ifinfo['inbytespass'] = $in4_pass + $in6_pass; - $ifinfo['outbytespass'] = $out4_pass + $out6_pass; - $ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets; - $ifinfo['outpktspass'] = $out4_pass_packets + $out6_pass_packets; - - /* Block */ - $pf_in4_block = preg_split("/ +/", $pfctlstats[4]); - $pf_out4_block = preg_split("/ +/", $pfctlstats[6]); - $pf_in6_block = preg_split("/ +/", $pfctlstats[8]); - $pf_out6_block = preg_split("/ +/", $pfctlstats[10]); - $in4_block = $pf_in4_block[5]; - $out4_block = $pf_out4_block[5]; - $in4_block_packets = $pf_in4_block[3]; - $out4_block_packets = $pf_out4_block[3]; - $in6_block = $pf_in6_block[5]; - $out6_block = $pf_out6_block[5]; - $in6_block_packets = $pf_in6_block[3]; - $out6_block_packets = $pf_out6_block[3]; - $ifinfo['inbytesblock'] = $in4_block + $in6_block; - $ifinfo['outbytesblock'] = $out4_block + $out6_block; - $ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets; - $ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets; - - $ifinfo['inbytes'] = $in4_pass + $in6_pass; - $ifinfo['outbytes'] = $out4_pass + $out6_pass; - $ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets; - $ifinfo['outpkts'] = $out4_pass_packets + $out6_pass_packets; - - $ifconfiginfo = ""; - $link_type = $config['interfaces'][$ifdescr]['ipaddr']; - switch ($link_type) { - /* DHCP? -> see if dhclient is up */ - case "dhcp": - /* see if dhclient is up */ - if (find_dhclient_process($ifinfo['if']) != 0) - $ifinfo['dhcplink'] = "up"; - else - $ifinfo['dhcplink'] = "down"; - - break; - /* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */ - case "pppoe": - case "pptp": - case "l2tp": - if ($ifinfo['status'] == "up" && !isset($link0)) - /* get PPPoE link status for dial on demand */ - $ifinfo["{$link_type}link"] = "up"; - else - $ifinfo["{$link_type}link"] = "down"; - - break; - /* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */ - case "ppp": - if ($ifinfo['status'] == "up") - $ifinfo['ppplink'] = "up"; - else - $ifinfo['ppplink'] = "down" ; - - if (empty($ifinfo['status'])) - $ifinfo['status'] = "down"; - - if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) { - foreach ($config['ppps']['ppp'] as $pppid => $ppp) { - if ($config['interfaces'][$ifdescr]['if'] == $ppp['if']) - break; - } - } - $dev = $ppp['ports']; - if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev)) - break; - if (!file_exists($dev)) { - $ifinfo['nodevice'] = 1; - $ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?"); - } - - $usbmodemoutput = array(); - exec("usbconfig", $usbmodemoutput); - $mondev = "{$g['tmp_path']}/3gstats.{$ifdescr}"; - if(file_exists($mondev)) { - $cellstats = file($mondev); - /* skip header */ - $a_cellstats = explode(",", $cellstats[1]); - if(preg_match("/huawei/i", implode("\n", $usbmodemoutput))) { - $ifinfo['cell_rssi'] = huawei_rssi_to_string($a_cellstats[1]); - $ifinfo['cell_mode'] = huawei_mode_to_string($a_cellstats[2], $a_cellstats[3]); - $ifinfo['cell_simstate'] = huawei_simstate_to_string($a_cellstats[10]); - $ifinfo['cell_service'] = huawei_service_to_string(trim($a_cellstats[11])); - } - if(preg_match("/zte/i", implode("\n", $usbmodemoutput))) { - $ifinfo['cell_rssi'] = zte_rssi_to_string($a_cellstats[1]); - $ifinfo['cell_mode'] = zte_mode_to_string($a_cellstats[2], $a_cellstats[3]); - $ifinfo['cell_simstate'] = zte_simstate_to_string($a_cellstats[10]); - $ifinfo['cell_service'] = zte_service_to_string(trim($a_cellstats[11])); - } - $ifinfo['cell_upstream'] = $a_cellstats[4]; - $ifinfo['cell_downstream'] = trim($a_cellstats[5]); - $ifinfo['cell_sent'] = $a_cellstats[6]; - $ifinfo['cell_received'] = trim($a_cellstats[7]); - $ifinfo['cell_bwupstream'] = $a_cellstats[8]; - $ifinfo['cell_bwdownstream'] = trim($a_cellstats[9]); - } - // Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over! - if (isset($ppp['uptime'])) - $ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")"; - break; - default: - break; - } - - if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) { - $sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`); - $ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec); - } - - if ($ifinfo['status'] == "up") { - /* try to determine media with ifconfig */ - unset($ifconfiginfo); - exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo); - $wifconfiginfo = array(); - if(is_interface_wireless($ifdescr)) { - exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo); - array_shift($wifconfiginfo); - } - $matches = ""; - foreach ($ifconfiginfo as $ici) { - - /* don't list media/speed for wireless cards, as it always - displays 2 Mbps even though clients can connect at 11 Mbps */ - if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) { - $ifinfo['media'] = $matches[1]; - } else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) { - $ifinfo['media'] = $matches[1]; - } else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) { - $ifinfo['media'] = $matches[1]; - } - - if (preg_match("/status: (.*)$/", $ici, $matches)) { - if ($matches[1] != "active") - $ifinfo['status'] = $matches[1]; - if($ifinfo['status'] == gettext("running")) - $ifinfo['status'] = gettext("up"); - } - if (preg_match("/channel (\S*)/", $ici, $matches)) { - $ifinfo['channel'] = $matches[1]; - } - if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) { - if ($matches[1][0] == '"') - $ifinfo['ssid'] = substr($matches[1], 1, -1); - else - $ifinfo['ssid'] = $matches[1]; - } - if (preg_match("/laggproto (.*)$/", $ici, $matches)) { - $ifinfo['laggproto'] = $matches[1]; - } - if (preg_match("/laggport: (.*)$/", $ici, $matches)) { - $ifinfo['laggport'][] = $matches[1]; - } - } - foreach($wifconfiginfo as $ici) { - $elements = preg_split("/[ ]+/i", $ici); - if ($elements[0] != "") { - $ifinfo['bssid'] = $elements[0]; - } - if ($elements[3] != "") { - $ifinfo['rate'] = $elements[3]; - } - if ($elements[4] != "") { - $ifinfo['rssi'] = $elements[4]; - } - - } - /* lookup the gateway */ - if (interface_has_gateway($ifdescr)) { - $ifinfo['gateway'] = get_interface_gateway($ifdescr); - $ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr); - } - } - - $bridge = ""; - $bridge = link_interface_to_bridge($ifdescr); - if($bridge) { - $bridge_text = `/sbin/ifconfig {$bridge}`; - if(stristr($bridge_text, "blocking") <> false) { - $ifinfo['bridge'] = "" . gettext("blocking") . " - " . gettext("check for ethernet loops"); - $ifinfo['bridgeint'] = $bridge; - } else if(stristr($bridge_text, "learning") <> false) { - $ifinfo['bridge'] = gettext("learning"); - $ifinfo['bridgeint'] = $bridge; - } else if(stristr($bridge_text, "forwarding") <> false) { - $ifinfo['bridge'] = gettext("forwarding"); - $ifinfo['bridgeint'] = $bridge; - } - } - - return $ifinfo; -} - -//returns cpu speed of processor. Good for determining capabilities of machine -function get_cpu_speed() { - return get_single_sysctl("hw.clockrate"); -} - -function get_uptime_sec() { - $boottime = ""; - $matches = ""; - $boottime = get_single_sysctl("kern.boottime"); - preg_match("/sec = (\d+)/", $boottime, $matches); - $boottime = $matches[1]; - if(intval($boottime) == 0) - return 0; - - $uptime = time() - $boottime; - return $uptime; -} - -function add_hostname_to_watch($hostname) { - if(!is_dir("/var/db/dnscache")) { - mkdir("/var/db/dnscache"); - } - $result = array(); - if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) { - $domrecords = array(); - $domips = array(); - exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost); - if($rethost == 0) { - foreach($domrecords as $domr) { - $doml = explode(" ", $domr); - $domip = $doml[3]; - /* fill array with domain ip addresses */ - if(is_ipaddr($domip)) { - $domips[] = $domip; - } - } - } - sort($domips); - $contents = ""; - if(! empty($domips)) { - foreach($domips as $ip) { - $contents .= "$ip\n"; - } - } - file_put_contents("/var/db/dnscache/$hostname", $contents); - /* Remove empty elements */ - $result = array_filter(explode("\n", $contents), 'strlen'); - } - return $result; -} - -function is_fqdn($fqdn) { - $hostname = false; - if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) { - $hostname = true; - } - if(preg_match("/\.\./", $fqdn)) { - $hostname = false; - } - if(preg_match("/^\./i", $fqdn)) { - $hostname = false; - } - if(preg_match("/\//i", $fqdn)) { - $hostname = false; - } - return($hostname); -} - -function pfsense_default_state_size() { - /* get system memory amount */ - $memory = get_memory(); - $physmem = $memory[0]; - /* Be cautious and only allocate 10% of system memory to the state table */ - $max_states = (int) ($physmem/10)*1000; - return $max_states; -} - -function pfsense_default_tables_size() { - $current = `pfctl -sm | grep ^tables | awk '{print $4};'`; - return $current; -} - -function pfsense_default_table_entries_size() { - $current = `pfctl -sm | grep table-entries | awk '{print $4};'`; - return $current; -} - -/* Compare the current hostname DNS to the DNS cache we made - * if it has changed we return the old records - * if no change we return false */ -function compare_hostname_to_dnscache($hostname) { - if(!is_dir("/var/db/dnscache")) { - mkdir("/var/db/dnscache"); - } - $hostname = trim($hostname); - if(is_readable("/var/db/dnscache/{$hostname}")) { - $oldcontents = file_get_contents("/var/db/dnscache/{$hostname}"); - } else { - $oldcontents = ""; - } - if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) { - $domrecords = array(); - $domips = array(); - exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost); - if($rethost == 0) { - foreach($domrecords as $domr) { - $doml = explode(" ", $domr); - $domip = $doml[3]; - /* fill array with domain ip addresses */ - if(is_ipaddr($domip)) { - $domips[] = $domip; - } - } - } - sort($domips); - $contents = ""; - if(! empty($domips)) { - foreach($domips as $ip) { - $contents .= "$ip\n"; - } - } - } - - if(trim($oldcontents) != trim($contents)) { - if($g['debug']) { - log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents)); - } - return ($oldcontents); - } else { - return false; - } -} - -/* - * load_crypto() - Load crypto modules if enabled in config. - */ -function load_crypto() { - global $config, $g; - $crypto_modules = array('glxsb', 'aesni'); - - if (!in_array($config['system']['crypto_hardware'], $crypto_modules)) - return false; - - if (!empty($config['system']['crypto_hardware']) && !is_module_loaded($config['system']['crypto_hardware'])) { - log_error("Loading {$config['system']['crypto_hardware']} cryptographic accelerator module."); - mwexec("/sbin/kldload {$config['system']['crypto_hardware']}"); - } -} - -/* - * load_thermal_hardware() - Load temperature monitor kernel module - */ -function load_thermal_hardware() { - global $config, $g; - $thermal_hardware_modules = array('coretemp', 'amdtemp'); - - if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules)) - return false; - - if (!empty($config['system']['thermal_hardware']) && !is_module_loaded($config['system']['thermal_hardware'])) { - log_error("Loading {$config['system']['thermal_hardware']} thermal monitor module."); - mwexec("/sbin/kldload {$config['system']['thermal_hardware']}"); - } -} - -/****f* pfsense-utils/isvm - * NAME - * isvm - * INPUTS - * none - * RESULT - * returns true if machine is running under a virtual environment - ******/ -function isvm() { - $virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86"); - $bios_product = trim(`/bin/kenv smbios.system.product`); - foreach ($virtualenvs as $virtualenv) - if (stripos($bios_product, $virtualenv) !== false) - return true; - - return false; -} - -function get_freebsd_version() { - $version = explode(".", php_uname("r")); - return $version[0]; -} - -function download_file($url, $destination, $verify_ssl = false, $connect_timeout = 60, $timeout = 0) { - global $config, $g; - - $fp = fopen($destination, "wb"); - - if (!$fp) - return false; - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_ssl); - curl_setopt($ch, CURLOPT_FILE, $fp); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout); - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); - curl_setopt($ch, CURLOPT_HEADER, false); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version"))); - - if (!empty($config['system']['proxyurl'])) { - curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']); - if (!empty($config['system']['proxyport'])) - curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']); - if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) { - @curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE); - curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}"); - } - } - - @curl_exec($ch); - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - fclose($fp); - curl_close($ch); - return ($http_code == 200) ? true : $http_code; -} - -function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) { - global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update; - $file_size = 1; - $downloaded = 1; - $first_progress_update = TRUE; - /* open destination file */ - $fout = fopen($destination_file, "wb"); - - /* - * Originally by Author: Keyvan Minoukadeh - * Modified by Scott Ullrich to return Content-Length size - */ - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url_file); - curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header'); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); - /* Don't verify SSL peers since we don't have the certificates to do so. */ - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody); - curl_setopt($ch, CURLOPT_NOPROGRESS, '1'); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout); - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); - curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version"))); - - if (!empty($config['system']['proxyurl'])) { - curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']); - if (!empty($config['system']['proxyport'])) - curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']); - if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) { - @curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE); - curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}"); - } - } - - @curl_exec($ch); - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - if($fout) - fclose($fout); - curl_close($ch); - return ($http_code == 200) ? true : $http_code; -} - -function read_header($ch, $string) { - global $file_size, $fout; - $length = strlen($string); - $regs = ""; - preg_match("/(Content-Length:) (.*)/", $string, $regs); - if($regs[2] <> "") { - $file_size = intval($regs[2]); - } - ob_flush(); - return $length; -} - -function read_body($ch, $string) { - global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $first_progress_update; - global $pkg_interface; - $length = strlen($string); - $downloaded += intval($length); - if($file_size > 0) { - $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0); - $downloadProgress = 100 - $downloadProgress; - } else - $downloadProgress = 0; - if($lastseen <> $downloadProgress and $downloadProgress < 101) { - if($sendto == "status") { - if($pkg_interface == "console") { - if(($downloadProgress % 10) == 0 || $downloadProgress < 10) { - $tostatus = $static_status . $downloadProgress . "%"; - if ($downloadProgress == 100) { - $tostatus = $tostatus . "\r"; - } - update_status($tostatus); - } - } else { - $tostatus = $static_status . $downloadProgress . "%"; - update_status($tostatus); - } - } else { - if($pkg_interface == "console") { - if(($downloadProgress % 10) == 0 || $downloadProgress < 10) { - $tooutput = $static_output . $downloadProgress . "%"; - if ($downloadProgress == 100) { - $tooutput = $tooutput . "\r"; - } - update_output_window($tooutput); - } - } else { - $tooutput = $static_output . $downloadProgress . "%"; - update_output_window($tooutput); - } - } - if(($pkg_interface != "console") || (($downloadProgress % 10) == 0) || ($downloadProgress < 10)) { - update_progress_bar($downloadProgress, $first_progress_update); - $first_progress_update = FALSE; - } - $lastseen = $downloadProgress; - } - if($fout) - fwrite($fout, $string); - ob_flush(); - return $length; -} - -/* - * update_output_window: update bottom textarea dynamically. - */ -function update_output_window($text) { - global $pkg_interface; - $log = preg_replace("/\n/", "\\n", $text); - if($pkg_interface != "console") { - echo "\n"; - } - /* ensure that contents are written out */ - ob_flush(); -} - -/* - * update_status: update top textarea dynamically. - */ -function update_status($status) { - global $pkg_interface; - if($pkg_interface == "console") { - echo "\r{$status}"; - } else { - echo "\n"; - } - /* ensure that contents are written out */ - ob_flush(); -} - -/* - * update_progress_bar($percent, $first_time): updates the javascript driven progress bar. - */ -function update_progress_bar($percent, $first_time) { - global $pkg_interface; - if($percent > 100) $percent = 1; - if($pkg_interface <> "console") { - echo "\n"; - } else { - if(!($first_time)) - echo "\x08\x08\x08\x08\x08"; - echo sprintf("%4d%%", $percent); - } -} - -/* Split() is being DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged. */ -if(!function_exists("split")) { - function split($separator, $haystack, $limit = null) { - log_error("deprecated split() call with separator '{$separator}'"); - return preg_split($separator, $haystack, $limit); - } -} - -function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) { - global $g, $config, $pconfig, $debug; - if(!$origname) - return; - - $sectionref = &$config; - foreach($section as $sectionname) { - if(is_array($sectionref) && isset($sectionref[$sectionname])) - $sectionref = &$sectionref[$sectionname]; - else - return; - } - - if($debug) $fd = fopen("{$g['tmp_path']}/print_r", "a"); - if($debug) fwrite($fd, print_r($pconfig, true)); - - if(is_array($sectionref)) { - foreach($sectionref as $itemkey => $item) { - if($debug) fwrite($fd, "$itemkey\n"); - - $fieldfound = true; - $fieldref = &$sectionref[$itemkey]; - foreach($field as $fieldname) { - if(is_array($fieldref) && isset($fieldref[$fieldname])) - $fieldref = &$fieldref[$fieldname]; - else { - $fieldfound = false; - break; - } - } - if($fieldfound && $fieldref == $origname) { - if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n"); - $fieldref = $new_alias_name; - } - } - } - - if($debug) fclose($fd); - -} - -function update_alias_url_data() { - global $config, $g; - - $updated = false; - - /* item is a url type */ - $lockkey = lock('aliasurl'); - if (is_array($config['aliases']['alias'])) { - foreach ($config['aliases']['alias'] as $x => $alias) { - if (empty($alias['aliasurl'])) - continue; - - $address = ""; - $isfirst = 0; - foreach ($alias['aliasurl'] as $alias_url) { - /* fetch down and add in */ - $temp_filename = tempnam("{$g['tmp_path']}/", "alias_import"); - unlink($temp_filename); - $verify_ssl = isset($config['system']['checkaliasesurlcert']); - mkdir($temp_filename); - download_file($alias_url, $temp_filename . "/aliases", $verify_ssl); - - /* if the item is tar gzipped then extract */ - if (stripos($alias_url, '.tgz')) { - if (!process_alias_tgz($temp_filename)) - continue; - } else if (stripos($alias_url, '.zip')) { - if (!process_alias_unzip($temp_filename)) - continue; - } - if (file_exists("{$temp_filename}/aliases")) { - $fd = @fopen("{$temp_filename}/aliases", 'r'); - if (!$fd) { - log_error(gettext("Could not process aliases from alias: {$alias_url}")); - continue; - } - /* NOTE: fgetss() is not a typo RTFM before being smart */ - while (($fc = fgetss($fd)) !== FALSE) { - $tmp = trim($fc, " \t\n\r"); - if (empty($tmp)) - continue; - $tmp_str = strstr($tmp, '#', true); - if (!empty($tmp_str)) - $tmp = $tmp_str; - if ($isfirst == 1) - $address .= ' '; - $address .= $tmp; - $isfirst = 1; - } - fclose($fd); - mwexec("/bin/rm -rf {$temp_filename}"); - } - } - if (!empty($address)) { - $config['aliases']['alias'][$x]['address'] = $address; - $updated = true; - } - } - } - unlock($lockkey); - - /* Report status to callers as well */ - return $updated; -} - -function process_alias_unzip($temp_filename) { - if(!file_exists("/usr/local/bin/unzip")) { - log_error(gettext("Alias archive is a .zip file which cannot be decompressed because utility is missing!")); - return false; - } - rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.zip"); - mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/"); - unlink("{$temp_filename}/aliases.zip"); - $files_to_process = return_dir_as_array("{$temp_filename}/"); - /* foreach through all extracted files and build up aliases file */ - $fd = @fopen("{$temp_filename}/aliases", "w"); - if (!$fd) { - log_error(gettext("Could not open {$temp_filename}/aliases for writing!")); - return false; - } - foreach($files_to_process as $f2p) { - $tmpfd = @fopen($f2p, 'r'); - if (!$tmpfd) { - log_error(gettext("The following file could not be read {$f2p} from {$temp_filename}")); - continue; - } - while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE) - fwrite($fd, $tmpbuf); - fclose($tmpfd); - unlink($f2p); - } - fclose($fd); - unset($tmpbuf); - - return true; -} - -function process_alias_tgz($temp_filename) { - if(!file_exists('/usr/bin/tar')) { - log_error(gettext("Alias archive is a .tar/tgz file which cannot be decompressed because utility is missing!")); - return false; - } - rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.tgz"); - mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/"); - unlink("{$temp_filename}/aliases.tgz"); - $files_to_process = return_dir_as_array("{$temp_filename}/"); - /* foreach through all extracted files and build up aliases file */ - $fd = @fopen("{$temp_filename}/aliases", "w"); - if (!$fd) { - log_error(gettext("Could not open {$temp_filename}/aliases for writing!")); - return false; - } - foreach($files_to_process as $f2p) { - $tmpfd = @fopen($f2p, 'r'); - if (!$tmpfd) { - log_error(gettext("The following file could not be read {$f2p} from {$temp_filename}")); - continue; - } - while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE) - fwrite($fd, $tmpbuf); - fclose($tmpfd); - unlink($f2p); - } - fclose($fd); - unset($tmpbuf); - - return true; -} - -function version_compare_dates($a, $b) { - $a_time = strtotime($a); - $b_time = strtotime($b); - - if ((!$a_time) || (!$b_time)) { - return FALSE; - } else { - if ($a_time < $b_time) - return -1; - elseif ($a_time == $b_time) - return 0; - else - return 1; - } -} -function version_get_string_value($a) { - $strs = array( - 0 => "ALPHA-ALPHA", - 2 => "ALPHA", - 3 => "BETA", - 4 => "B", - 5 => "C", - 6 => "D", - 7 => "RC", - 8 => "RELEASE", - 9 => "*" // Matches all release levels - ); - $major = 0; - $minor = 0; - foreach ($strs as $num => $str) { - if (substr($a, 0, strlen($str)) == $str) { - $major = $num; - $n = substr($a, strlen($str)); - if (is_numeric($n)) - $minor = $n; - break; - } - } - return "{$major}.{$minor}"; -} -function version_compare_string($a, $b) { - // Only compare string parts if both versions give a specific release - // (If either version lacks a string part, assume intended to match all release levels) - if (isset($a) && isset($b)) - return version_compare_numeric(version_get_string_value($a), version_get_string_value($b)); - else - return 0; -} -function version_compare_numeric($a, $b) { - $a_arr = explode('.', rtrim($a, '.0')); - $b_arr = explode('.', rtrim($b, '.0')); - - foreach ($a_arr as $n => $val) { - if (array_key_exists($n, $b_arr)) { - // So far so good, both have values at this minor version level. Compare. - if ($val > $b_arr[$n]) - return 1; - elseif ($val < $b_arr[$n]) - return -1; - } else { - // a is greater, since b doesn't have any minor version here. - return 1; - } - } - if (count($b_arr) > count($a_arr)) { - // b is longer than a, so it must be greater. - return -1; - } else { - // Both a and b are of equal length and value. - return 0; - } -} -function pfs_version_compare($cur_time, $cur_text, $remote) { - // First try date compare - $v = version_compare_dates($cur_time, $remote); - if ($v === FALSE) { - // If that fails, try to compare by string - // Before anything else, simply test if the strings are equal - if (($cur_text == $remote) || ($cur_time == $remote)) - return 0; - list($cur_num, $cur_str) = explode('-', $cur_text); - list($rem_num, $rem_str) = explode('-', $remote); - - // First try to compare the numeric parts of the version string. - $v = version_compare_numeric($cur_num, $rem_num); - - // If the numeric parts are the same, compare the string parts. - if ($v == 0) - return version_compare_string($cur_str, $rem_str); - } - return $v; -} -function process_alias_urltable($name, $url, $freq, $forceupdate=false) { - global $config; - - $urltable_prefix = "/var/db/aliastables/"; - $urltable_filename = $urltable_prefix . $name . ".txt"; - - // Make the aliases directory if it doesn't exist - if (!file_exists($urltable_prefix)) { - mkdir($urltable_prefix); - } elseif (!is_dir($urltable_prefix)) { - unlink($urltable_prefix); - mkdir($urltable_prefix); - } - - // If the file doesn't exist or is older than update_freq days, fetch a new copy. - if (!file_exists($urltable_filename) - || ((time() - filemtime($urltable_filename)) > ($freq * 86400 - 90)) - || $forceupdate) { - - // Try to fetch the URL supplied - conf_mount_rw(); - unlink_if_exists($urltable_filename . ".tmp"); - $verify_ssl = isset($config['system']['checkaliasesurlcert']); - if (download_file($url, $urltable_filename . ".tmp", $verify_ssl)) { - mwexec("/usr/bin/sed -E 's/\;.*//g; /^[[:space:]]*($|#)/d' ". escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename)); - if (alias_get_type($name) == "urltable_ports") { - $ports = explode("\n", file_get_contents($urltable_filename)); - $ports = group_ports($ports); - file_put_contents($urltable_filename, implode("\n", $ports)); - } - unlink_if_exists($urltable_filename . ".tmp"); - } else - touch($urltable_filename); - conf_mount_ro(); - return true; - } else { - // File exists, and it doesn't need updated. - return -1; - } -} -function get_real_slice_from_glabel($label) { - $label = escapeshellarg($label); - return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`); -} -function nanobsd_get_boot_slice() { - return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`); -} -function nanobsd_get_boot_drive() { - return trim(`/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`); -} -function nanobsd_get_active_slice() { - $boot_drive = nanobsd_get_boot_drive(); - $active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`); - - return "{$boot_drive}s{$active}"; -} -function nanobsd_get_size() { - return strtoupper(file_get_contents("/etc/nanosize.txt")); -} -function nanobsd_switch_boot_slice() { - global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH; - global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH; - global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE; - nanobsd_detect_slice_info(); - - if ($BOOTFLASH == $ACTIVE_SLICE) { - $slice = $TOFLASH; - } else { - $slice = $BOOTFLASH; - } - - for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); } - ob_implicit_flush(1); - if(strstr($slice, "s2")) { - $ASLICE="2"; - $AOLDSLICE="1"; - $AGLABEL_SLICE="pfsense1"; - $AUFS_ID="1"; - $AOLD_UFS_ID="0"; - } else { - $ASLICE="1"; - $AOLDSLICE="2"; - $AGLABEL_SLICE="pfsense0"; - $AUFS_ID="0"; - $AOLD_UFS_ID="1"; - } - $ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}"; - $ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a"; - $ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}"; - conf_mount_rw(); - set_single_sysctl("kern.geom.debugflags", "16"); - exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}"); - exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}"); - // We can't update these if they are mounted now. - if ($BOOTFLASH != $slice) { - exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH"); - nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID); - } - set_single_sysctl("kern.geom.debugflags", "0"); - conf_mount_ro(); -} -function nanobsd_clone_slice() { - global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH; - global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH; - global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE; - nanobsd_detect_slice_info(); - - for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); } - ob_implicit_flush(1); - set_single_sysctl("kern.geom.debugflags", "16"); - exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1"); - exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k"); - exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}"); - $status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID); - set_single_sysctl("kern.geom.debugflags", "0"); - if($status) { - return false; - } else { - return true; - } -} -function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) { - $tmppath = "/tmp/{$gslice}"; - $fstabpath = "/tmp/{$gslice}/etc/fstab"; - - mkdir($tmppath); - exec("/sbin/fsck_ufs -y /dev/{$complete_path}"); - exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}"); - copy("/etc/fstab", $fstabpath); - - if (!file_exists($fstabpath)) { - $fstab = << $val) - { - if ($priority == 'tag') - $attributes_data[$attr] = $val; - else - $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' - } - } - if ($type == "open") - { - $parent[$level -1] = & $current; - if (!is_array($current) or (!in_array($tag, array_keys($current)))) - { - $current[$tag] = $result; - if ($attributes_data) - $current[$tag . '_attr'] = $attributes_data; - $repeated_tag_index[$tag . '_' . $level] = 1; - $current = & $current[$tag]; - } - else - { - if (isset ($current[$tag][0])) - { - $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result; - $repeated_tag_index[$tag . '_' . $level]++; - } - else - { - $current[$tag] = array ( - $current[$tag], - $result - ); - $repeated_tag_index[$tag . '_' . $level] = 2; - if (isset ($current[$tag . '_attr'])) - { - $current[$tag]['0_attr'] = $current[$tag . '_attr']; - unset ($current[$tag . '_attr']); - } - } - $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1; - $current = & $current[$tag][$last_item_index]; - } - } - elseif ($type == "complete") - { - if (!isset ($current[$tag])) - { - $current[$tag] = $result; - $repeated_tag_index[$tag . '_' . $level] = 1; - if ($priority == 'tag' and $attributes_data) - $current[$tag . '_attr'] = $attributes_data; - } - else - { - if (isset ($current[$tag][0]) and is_array($current[$tag])) - { - $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result; - if ($priority == 'tag' and $get_attributes and $attributes_data) - { - $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data; - } - $repeated_tag_index[$tag . '_' . $level]++; - } - else - { - $current[$tag] = array ( - $current[$tag], - $result - ); - $repeated_tag_index[$tag . '_' . $level] = 1; - if ($priority == 'tag' and $get_attributes) - { - if (isset ($current[$tag . '_attr'])) - { - $current[$tag]['0_attr'] = $current[$tag . '_attr']; - unset ($current[$tag . '_attr']); - } - if ($attributes_data) - { - $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data; - } - } - $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken - } - } - } - elseif ($type == 'close') - { - $current = & $parent[$level -1]; - } - } - return ($xml_array); -} - -function get_country_name($country_code) { - if ($country_code != "ALL" && strlen($country_code) != 2) - return ""; - - $country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml"; - $country_names_contents = file_get_contents($country_names_xml); - $country_names = xml2array($country_names_contents); - - if($country_code == "ALL") { - $country_list = array(); - foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) { - $country_list[] = array("code" => $country['ISO_3166-1_Alpha-2_Code_element'], - "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) ); - } - return $country_list; - } - - foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) { - if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) { - return ucwords(strtolower($country['ISO_3166-1_Country_name'])); - } - } - return ""; -} - -/* sort by interface only, retain the original order of rules that apply to - the same interface */ -function filter_rules_sort() { - global $config; - - /* mark each rule with the sequence number (to retain the order while sorting) */ - for ($i = 0; isset($config['filter']['rule'][$i]); $i++) - $config['filter']['rule'][$i]['seq'] = $i; - - usort($config['filter']['rule'], "filter_rules_compare"); - - /* strip the sequence numbers again */ - for ($i = 0; isset($config['filter']['rule'][$i]); $i++) - unset($config['filter']['rule'][$i]['seq']); -} -function filter_rules_compare($a, $b) { - if (isset($a['floating']) && isset($b['floating'])) - return $a['seq'] - $b['seq']; - else if (isset($a['floating'])) - return -1; - else if (isset($b['floating'])) - return 1; - else if ($a['interface'] == $b['interface']) - return $a['seq'] - $b['seq']; - else - return compare_interface_friendly_names($a['interface'], $b['interface']); -} - -function generate_ipv6_from_mac($mac) { - $elements = explode(":", $mac); - if(count($elements) <> 6) - return false; - - $i = 0; - $ipv6 = "fe80::"; - foreach($elements as $byte) { - if($i == 0) { - $hexadecimal = substr($byte, 1, 2); - $bitmap = base_convert($hexadecimal, 16, 2); - $bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT); - $bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4); - $byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16); - } - $ipv6 .= $byte; - if($i == 1) { - $ipv6 .= ":"; - } - if($i == 3) { - $ipv6 .= ":"; - } - if($i == 2) { - $ipv6 .= "ff:fe"; - } - - $i++; - } - return $ipv6; -} - -/****f* pfsense-utils/load_mac_manufacturer_table - * NAME - * load_mac_manufacturer_table - * INPUTS - * none - * RESULT - * returns associative array with MAC-Manufacturer pairs - ******/ -function load_mac_manufacturer_table() { - /* load MAC-Manufacture data from the file */ - $macs = false; - if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes")) - $macs=file("/usr/local/share/nmap/nmap-mac-prefixes"); - if ($macs){ - foreach ($macs as $line){ - if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){ - /* store values like this $mac_man['000C29']='VMware' */ - $mac_man["$matches[1]"]=$matches[2]; - } - } - return $mac_man; - } else - return -1; - -} - -/****f* pfsense-utils/is_ipaddr_configured - * NAME - * is_ipaddr_configured - * INPUTS - * IP Address to check. - * RESULT - * returns true if the IP Address is - * configured and present on this device. -*/ -function is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, $check_subnets = false) { - global $config; - - $isipv6 = is_ipaddrv6($ipaddr); - - if ($check_subnets) { - $iflist = get_configured_interface_list(); - foreach ($iflist as $if => $ifname) { - if ($ignore_if == $if) - continue; - - if ($isipv6 === true) { - $bitmask = get_interface_subnetv6($if); - $subnet = gen_subnetv6(get_interface_ipv6($if), $bitmask); - } else { - $bitmask = get_interface_subnet($if); - $subnet = gen_subnet(get_interface_ip($if), $bitmask); - } - - if (ip_in_subnet($ipaddr, $subnet . '/' . $bitmask)) - return true; - } - } else { - if ($isipv6 === true) - $interface_list_ips = get_configured_ipv6_addresses(); - else - $interface_list_ips = get_configured_ip_addresses(); - - foreach($interface_list_ips as $if => $ilips) { - /* Also ignore CARP interfaces, it'll be checked below */ - if ($ignore_if == $if || strstr($ignore_if, "_vip")) - continue; - if (strcasecmp($ipaddr, $ilips) == 0) - return true; - } - } - - $interface_list_vips = get_configured_vips_list(true); - foreach ($interface_list_vips as $id => $vip) { - if ($ignore_if == $vip['if']) - continue; - if (strcasecmp($ipaddr, $vip['ipaddr']) == 0) - return true; - } - - if ($check_localip) { - if (is_array($config['pptpd']) && !empty($config['pptpd']['localip']) && (strcasecmp($ipaddr, $config['pptpd']['localip']) == 0)) - return true; - - if (!is_array($config['l2tp']) && !empty($config['l2tp']['localip']) && (strcasecmp($ipaddr, $config['l2tp']['localip']) == 0)) - return true; - } - - return false; -} - -/****f* pfsense-utils/pfSense_handle_custom_code - * NAME - * pfSense_handle_custom_code - * INPUTS - * directory name to process - * RESULT - * globs the directory and includes the files - */ -function pfSense_handle_custom_code($src_dir) { - // Allow extending of the nat edit page and include custom input validation - if(is_dir("$src_dir")) { - $cf = glob($src_dir . "/*.inc"); - foreach($cf as $nf) { - if($nf == "." || $nf == "..") - continue; - // Include the extra handler - include("$nf"); - } - } -} - -function set_language($lang = 'en_US', $encoding = "UTF-8") { - putenv("LANG={$lang}.{$encoding}"); - setlocale(LC_ALL, "{$lang}.{$encoding}"); - textdomain("pfSense"); - bindtextdomain("pfSense","/usr/local/share/locale"); - bind_textdomain_codeset("pfSense","{$lang}.{$encoding}"); -} - -function get_locale_list() { - $locales = array( - "en_US" => gettext("English"), - "pt_BR" => gettext("Portuguese (Brazil)"), - "tr" => gettext("Turkish"), - ); - asort($locales); - return $locales; -} - -function system_get_language_code() { - global $config, $g_languages; - - // a language code, as per [RFC3066] - $language = $config['system']['language']; - //$code = $g_languages[$language]['code']; - $code = str_replace("_", "-", $language); - - if (empty($code)) - $code = "en-US"; // Set default code. - - return $code; -} - -function system_get_language_codeset() { - global $config, $g_languages; - - $language = $config['system']['language']; - $codeset = $g_languages[$language]['codeset']; - - if (empty($codeset)) - $codeset = "UTF-8"; // Set default codeset. - - return $codeset; -} - -/* Available languages/locales */ -$g_languages = array ( - "sq" => array("codeset" => "UTF-8", "desc" => gettext("Albanian")), - "bg" => array("codeset" => "UTF-8", "desc" => gettext("Bulgarian")), - "zh_CN" => array("codeset" => "UTF-8", "desc" => gettext("Chinese (Simplified)")), - "zh_TW" => array("codeset" => "UTF-8", "desc" => gettext("Chinese (Traditional)")), - "nl" => array("codeset" => "UTF-8", "desc" => gettext("Dutch")), - "da" => array("codeset" => "UTF-8", "desc" => gettext("Danish")), - "en_US" => array("codeset" => "UTF-8", "desc" => gettext("English")), - "fi" => array("codeset" => "UTF-8", "desc" => gettext("Finnish")), - "fr" => array("codeset" => "UTF-8", "desc" => gettext("French")), - "de" => array("codeset" => "UTF-8", "desc" => gettext("German")), - "el" => array("codeset" => "UTF-8", "desc" => gettext("Greek")), - "hu" => array("codeset" => "UTF-8", "desc" => gettext("Hungarian")), - "it" => array("codeset" => "UTF-8", "desc" => gettext("Italian")), - "ja" => array("codeset" => "UTF-8", "desc" => gettext("Japanese")), - "ko" => array("codeset" => "UTF-8", "desc" => gettext("Korean")), - "lv" => array("codeset" => "UTF-8", "desc" => gettext("Latvian")), - "nb" => array("codeset" => "UTF-8", "desc" => gettext("Norwegian (Bokmal)")), - "pl" => array("codeset" => "UTF-8", "desc" => gettext("Polish")), - "pt_BR" => array("codeset" => "ISO-8859-1", "desc" => gettext("Portuguese (Brazil)")), - "pt" => array("codeset" => "UTF-8", "desc" => gettext("Portuguese (Portugal)")), - "ro" => array("codeset" => "UTF-8", "desc" => gettext("Romanian")), - "ru" => array("codeset" => "UTF-8", "desc" => gettext("Russian")), - "sl" => array("codeset" => "UTF-8", "desc" => gettext("Slovenian")), - "tr" => array("codeset" => "UTF-8", "desc" => gettext("Turkish")), - "es" => array("codeset" => "UTF-8", "desc" => gettext("Spanish")), - "sv" => array("codeset" => "UTF-8", "desc" => gettext("Swedish")), - "sk" => array("codeset" => "UTF-8", "desc" => gettext("Slovak")), - "cs" => array("codeset" => "UTF-8", "desc" => gettext("Czech")) -); - -function return_hex_ipv4($ipv4) { - if(!is_ipaddrv4($ipv4)) - return(false); - - /* we need the hex form of the interface IPv4 address */ - $ip4arr = explode(".", $ipv4); - return (sprintf("%02x%02x%02x%02x", $ip4arr[0], $ip4arr[1], $ip4arr[2], $ip4arr[3])); -} - -function convert_ipv6_to_128bit($ipv6) { - if(!is_ipaddrv6($ipv6)) - return(false); - - $ip6arr = array(); - $ip6prefix = Net_IPv6::uncompress($ipv6); - $ip6arr = explode(":", $ip6prefix); - /* binary presentation of the prefix for all 128 bits. */ - $ip6prefixbin = ""; - foreach($ip6arr as $element) { - $ip6prefixbin .= sprintf("%016b", hexdec($element)); - } - return($ip6prefixbin); -} - -function convert_128bit_to_ipv6($ip6bin) { - if(strlen($ip6bin) <> 128) - return(false); - - $ip6arr = array(); - $ip6binarr = array(); - $ip6binarr = str_split($ip6bin, 16); - foreach($ip6binarr as $binpart) - $ip6arr[] = dechex(bindec($binpart)); - $ip6addr = Net_IPv6::compress(implode(":", $ip6arr)); - - return($ip6addr); -} - - -/* Returns the calculated bit length of the prefix delegation from the WAN interface */ -/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */ -/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */ -/* 6to4 is 16 bits, e.g. 65535 */ -function calculate_ipv6_delegation_length($if) { - global $config; - - if(!is_array($config['interfaces'][$if])) - return false; - - switch($config['interfaces'][$if]['ipaddrv6']) { - case "6to4": - $pdlen = 16; - break; - case "6rd": - $rd6cfg = $config['interfaces'][$if]; - $rd6plen = explode("/", $rd6cfg['prefix-6rd']); - $pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen']))); - break; - case "dhcp6": - $dhcp6cfg = $config['interfaces'][$if]; - $pdlen = $dhcp6cfg['dhcp6-ia-pd-len']; - break; - default: - $pdlen = 0; - break; - } - return($pdlen); -} - -function huawei_rssi_to_string($rssi) { - $dbm = array(); - $i = 0; - $dbstart = -113; - while($i < 32) { - $dbm[$i] = $dbstart + ($i * 2); - $i++; - } - $percent = round(($rssi / 31) * 100); - $string = "rssi:{$rssi} level:{$dbm[$rssi]}dBm percent:{$percent}%"; - return $string; -} - -function huawei_mode_to_string($mode, $submode) { - $modes[0] = "None"; - $modes[1] = "AMPS"; - $modes[2] = "CDMA"; - $modes[3] = "GSM/GPRS"; - $modes[4] = "HDR"; - $modes[5] = "WCDMA"; - $modes[6] = "GPS"; - - $submodes[0] = "No Service"; - $submodes[1] = "GSM"; - $submodes[2] = "GPRS"; - $submodes[3] = "EDGE"; - $submodes[4] = "WCDMA"; - $submodes[5] = "HSDPA"; - $submodes[6] = "HSUPA"; - $submodes[7] = "HSDPA+HSUPA"; - $submodes[8] = "TD-SCDMA"; - $submodes[9] = "HSPA+"; - $string = "{$modes[$mode]}, {$submodes[$submode]} Mode"; - return $string; -} - -function huawei_service_to_string($state) { - $modes[0] = "No"; - $modes[1] = "Restricted"; - $modes[2] = "Valid"; - $modes[3] = "Restricted Regional"; - $modes[4] = "Powersaving"; - $string = "{$modes[$state]} Service"; - return $string; -} - -function huawei_simstate_to_string($state) { - $modes[0] = "Invalid SIM/locked"; - $modes[1] = "Valid SIM"; - $modes[2] = "Invalid SIM CS"; - $modes[3] = "Invalid SIM PS"; - $modes[4] = "Invalid SIM CS/PS"; - $modes[255] = "Missing SIM"; - $string = "{$modes[$state]} State"; - return $string; -} - -function zte_rssi_to_string($rssi) { - return huawei_rssi_to_string($rssi); -} - -function zte_mode_to_string($mode, $submode) { - $modes[0] = "No Service"; - $modes[1] = "Limited Service"; - $modes[2] = "GPRS"; - $modes[3] = "GSM"; - $modes[4] = "UMTS"; - $modes[5] = "EDGE"; - $modes[6] = "HSDPA"; - - $submodes[0] = "CS_ONLY"; - $submodes[1] = "PS_ONLY"; - $submodes[2] = "CS_PS"; - $submodes[3] = "CAMPED"; - $string = "{$modes[$mode]}, {$submodes[$submode]} Mode"; - return $string; -} - -function zte_service_to_string($state) { - $modes[0] = "Initializing"; - $modes[1] = "Network Lock error"; - $modes[2] = "Network Locked"; - $modes[3] = "Unlocked or correct MCC/MNC"; - $string = "{$modes[$state]} Service"; - return $string; -} - -function zte_simstate_to_string($state) { - $modes[0] = "No action"; - $modes[1] = "Network lock"; - $modes[2] = "(U)SIM card lock"; - $modes[3] = "Network Lock and (U)SIM card Lock"; - $string = "{$modes[$state]} State"; - return $string; -} - -function get_configured_pppoe_server_interfaces() { - global $config; - $iflist = array(); - if (is_array($config['pppoes']['pppoe'])) { - foreach($config['pppoes']['pppoe'] as $pppoe) { - if ($pppoe['mode'] == "server") { - $int = "poes". $pppoe['pppoeid']; - $iflist[$int] = strtoupper($int); - } - } - } - return $iflist; -} - -function get_pppoes_child_interfaces($ifpattern) { - $if_arr = array(); - if($ifpattern == "") - return; - - exec("ifconfig", $out, $ret); - foreach($out as $line) { - if(preg_match("/^({$ifpattern}[0-9]+):/i", $line, $match)) { - $if_arr[] = $match[1]; - } - } - return $if_arr; - -} - -/****f* pfsense-utils/pkg_call_plugins - * NAME - * pkg_call_plugins - * INPUTS - * $plugin_type value used to search in package configuration if the plugin is used, also used to create the function name - * $plugin_params parameters to pass to the plugin function for passing multiple parameters a array can be used. - * RESULT - * returns associative array results from the plugin calls for each package - * NOTES - * This generic function can be used to notify or retrieve results from functions that are defined in packages. - ******/ -function pkg_call_plugins($plugin_type, $plugin_params) { - global $g, $config; - $results = array(); - if (!is_array($config['installedpackages']['package'])) - return $results; - foreach ($config['installedpackages']['package'] as $package) { - if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) - continue; - $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], 'packagegui'); - $pkgname = substr(reverse_strrchr($package['configurationfile'], "."),0,-1); - if (is_array($pkg_config['plugins']['item'])) - foreach ($pkg_config['plugins']['item'] as $plugin) { - if ($plugin['type'] == $plugin_type) { - if (file_exists($pkg_config['include_file'])) - require_once($pkg_config['include_file']); - else - continue; - $plugin_function = $pkgname . '_'. $plugin_type; - $results[$pkgname] = @eval($plugin_function($plugin_params)); - } - } - } - return $results; -} - -/* Function to find and return the active XML RPC base URL to avoid code duplication */ -function get_active_xml_rpc_base_url() { - global $config, $g; - /* If the user has activated the option to enable an alternate xmlrpcbaseurl, and it's not empty, then use it */ - if (isset($config['system']['altpkgrepo']['enable']) && !empty($config['system']['altpkgrepo']['xmlrpcbaseurl'])) { - return $config['system']['altpkgrepo']['xmlrpcbaseurl']; - } else { - return $g['xmlrpcbaseurl']; - } -} - -?> diff --git a/usr/local/www/includes/pkg-utils.inc b/usr/local/www/includes/pkg-utils.inc deleted file mode 100644 index 2c9a4882e..000000000 --- a/usr/local/www/includes/pkg-utils.inc +++ /dev/null @@ -1,1546 +0,0 @@ ->/tmp/pbi_delete_errors.txt"); -} - -/****f* pkg-utils/is_package_installed - * NAME - * is_package_installed - Check whether a package is installed. - * INPUTS - * $packagename - name of the package to check - * RESULT - * boolean - true if the package is installed, false otherwise - * NOTES - * This function is deprecated - get_pkg_id() can already check for installation. - ******/ -function is_package_installed($packagename) { - $pkg = get_pkg_id($packagename); - if($pkg == -1) - return false; - return true; -} - -/****f* pkg-utils/get_pkg_id - * NAME - * get_pkg_id - Find a package's numeric ID. - * INPUTS - * $pkg_name - name of the package to check - * RESULT - * integer - -1 if package is not found, >-1 otherwise - ******/ -function get_pkg_id($pkg_name) { - global $config; - - if (is_array($config['installedpackages']['package'])) { - foreach($config['installedpackages']['package'] as $idx => $pkg) { - if($pkg['name'] == $pkg_name) - return $idx; - } - } - return -1; -} - -/****f* pkg-utils/get_pkg_internal_name - * NAME - * get_pkg_internal_name - Find a package's internal name (e.g. squid3 internal name is squid) - * INPUTS - * $package - array of package data from config - * RESULT - * string - internal name (if defined) or default to package name - ******/ -function get_pkg_internal_name($package) { - if (isset($package['internal_name']) && ($package['internal_name'] != "")) { - /* e.g. name is Ipguard-dev, internal name is ipguard */ - $pkg_internal_name = $package['internal_name']; - } else { - $pkg_internal_name = $package['name']; - } - return $pkg_internal_name; -} - -/****f* pkg-utils/get_pkg_info - * NAME - * get_pkg_info - Retrieve package information from package server. - * INPUTS - * $pkgs - 'all' to retrieve all packages, an array containing package names otherwise - * $info - 'all' to retrieve all information, an array containing keys otherwise - * RESULT - * $raw_versions - Array containing retrieved information, indexed by package name. - ******/ -function get_pkg_info($pkgs = 'all', $info = 'all') { - global $g; - - $freebsd_machine = php_uname("m"); - $params = array( - "pkg" => $pkgs, - "info" => $info, - "freebsd_version" => get_freebsd_version(), - "freebsd_machine" => $freebsd_machine - ); - $resp = call_pfsense_method('pfsense.get_pkgs', $params, 10); - return $resp ? $resp : array(); -} - -function get_pkg_sizes($pkgs = 'all') { - global $config, $g; - - $freebsd_machine = php_uname("m"); - $params = array( - "pkg" => $pkgs, - "freebsd_version" => get_freebsd_version(), - "freebsd_machine" => $freebsd_machine - ); - $msg = new XML_RPC_Message('pfsense.get_pkg_sizes', array(php_value_to_xmlrpc($params))); - $xmlrpc_base_url = get_active_xml_rpc_base_url(); - $cli = new XML_RPC_Client($g['xmlrpcpath'], $xmlrpc_base_url); - $resp = $cli->send($msg, 10); - if(!is_object($resp)) - log_error("Could not get response from XMLRPC server!"); - else if (!$resp->faultCode()) { - $raw_versions = $resp->value(); - return xmlrpc_value_to_php($raw_versions); - } - - return array(); -} - -/* - * resync_all_package_configs() Force packages to setup their configuration and rc.d files. - * This function may also print output to the terminal indicating progress. - */ -function resync_all_package_configs($show_message = false) { - global $config, $pkg_interface, $g; - - log_error(gettext("Resyncing configuration for all packages.")); - - if (!is_array($config['installedpackages']['package'])) - return; - - if($show_message == true) - echo "Syncing packages:"; - - conf_mount_rw(); - - foreach($config['installedpackages']['package'] as $idx => $package) { - if (empty($package['name'])) - continue; - if($show_message == true) - echo " " . $package['name']; - get_pkg_depends($package['name'], "all"); - if($g['booting'] != true) - stop_service(get_pkg_internal_name($package)); - sync_package($idx, true, true); - if($pkg_interface == "console") - echo "\n" . gettext("Syncing packages:"); - } - - if($show_message == true) - echo " done.\n"; - - @unlink("/conf/needs_package_sync"); - conf_mount_ro(); -} - -/* - * is_freebsd_pkg_installed() - Check /var/db/pkg to determine whether or not a FreeBSD - * package is installed. - */ -function is_freebsd_pkg_installed($pkg) { - if(!$pkg) - return; - $output = ""; - $_gb = exec("/usr/local/sbin/pbi_info " . escapeshellarg($pkg) . ' 2>/dev/null', $output, $retval); - - return (intval($retval) == 0); -} - -/* - * get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", return_nosync = 1): Return a package's dependencies. - * - * $filetype = "all" || ".xml", ".tgz", etc. - * $format = "files" (full filenames) || "names" (stripped / parsed depend names) - * $return_nosync = 1 (return depends that have nosync set) | 0 (ignore packages with nosync) - * - */ -function get_pkg_depends($pkg_name, $filetype = ".xml", $format = "files", $return_nosync = 1) { - global $config; - - $pkg_id = get_pkg_id($pkg_name); - if($pkg_id == -1) - return -1; // This package doesn't really exist - exit the function. - else if (!isset($config['installedpackages']['package'][$pkg_id])) - return; // No package belongs to the pkg_id passed to this function. - - $package =& $config['installedpackages']['package'][$pkg_id]; - if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) { - log_error(sprintf(gettext('The %1$s package is missing required dependencies and must be reinstalled. %2$s'), $package['name'], $package['configurationfile'])); - uninstall_package($package['name']); - if (install_package($package['name']) < 0) { - log_error("Failed reinstalling package {$package['name']}."); - return false; - } - } - $pkg_xml = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui"); - if (!empty($pkg_xml['additional_files_needed'])) { - foreach($pkg_xml['additional_files_needed'] as $item) { - if ($return_nosync == 0 && isset($item['nosync'])) - continue; // Do not return depends with nosync set if not required. - $depend_file = substr(strrchr($item['item']['0'], '/'),1); // Strip URLs down to filenames. - $depend_name = substr(substr($depend_file,0,strpos($depend_file,".")+1),0,-1); // Strip filename down to dependency name. - if (($filetype != "all") && (!preg_match("/{$filetype}/i", $depend_file))) - if (($filetype != "all") && (strtolower(substr($depend_file, -strlen($filetype))) != strtolower($filetype))) - continue; - if ($item['prefix'] != "") - $prefix = $item['prefix']; - else - $prefix = "/usr/local/pkg/"; - // Ensure that the prefix exists to avoid installation errors. - if(!is_dir($prefix)) - exec("/bin/mkdir -p {$prefix}"); - if(!file_exists($prefix . $depend_file)) - log_error(sprintf(gettext("The %s package is missing required dependencies and must be reinstalled."), $package['name'])); - switch ($format) { - case "files": - $depends[] = $prefix . $depend_file; - break; - case "names": - switch ($filetype) { - case "all": - if(preg_match("/\.xml/i", $depend_file)) { - $depend_xml = parse_xml_config_pkg("/usr/local/pkg/{$depend_file}", "packagegui"); - if (!empty($depend_xml)) - $depends[] = $depend_xml['name']; - } else - $depends[] = $depend_name; // If this dependency isn't package XML, use the stripped filename. - break; - case ".xml": - $depend_xml = parse_xml_config_pkg("/usr/local/pkg/" . $depend_file, "packagegui"); - if (!empty($depend_xml)) - $depends[] = $depend_xml['name']; - break; - default: - $depends[] = $depend_name; // If we aren't looking for XML, use the stripped filename (it's all we have). - break; - } - } - } - return $depends; - } -} - -function uninstall_package($pkg_name) { - global $config, $static_output; - global $builder_package_install; - - $id = get_pkg_id($pkg_name); - if ($id >= 0) { - stop_service(get_pkg_internal_name($config['installedpackages']['package'][$id])); - $pkg_depends =& $config['installedpackages']['package'][$id]['depends_on_package_pbi']; - $static_output .= "Removing package...\n"; - update_output_window($static_output); - if (is_array($pkg_depends)) { - foreach ($pkg_depends as $pkg_depend) - delete_package($pkg_depend); - } else { - // The packages (1 or more) are all in one long string. - // We need to pass them 1 at a time to delete_package. - // Compress any multiple whitespace (sp, tab, cr, lf...) into a single space char. - $pkg_dep_str = preg_replace("'\s+'", ' ', $pkg_depends); - // Get rid of any leading or trailing space. - $pkg_dep_str = trim($pkg_dep_str); - // Now we have a space-separated string. Make it into an array and process it. - $pkg_dep_array = explode(" ", $pkg_dep_str); - foreach ($pkg_dep_array as $pkg_depend) { - delete_package($pkg_depend); - } - } - } - delete_package_xml($pkg_name); - - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); -} - -function force_remove_package($pkg_name) { - delete_package_xml($pkg_name); -} - -/* - * sync_package($pkg_name, $sync_depends = true, $show_message = false) Force a package to setup its configuration and rc.d files. - */ -function sync_package($pkg_name, $sync_depends = true, $show_message = false) { - global $config, $config_parsed; - global $builder_package_install; - - // If this code is being called by pfspkg_installer - // which the builder system uses then return (ignore). - if($builder_package_install) - return; - - if(empty($config['installedpackages']['package'])) - return; - if(!is_numeric($pkg_name)) { - $pkg_id = get_pkg_id($pkg_name); - if($pkg_id == -1) - return -1; // This package doesn't really exist - exit the function. - } else { - $pkg_id = $pkg_name; - if(empty($config['installedpackages']['package'][$pkg_id])) - return; // No package belongs to the pkg_id passed to this function. - } - if (is_array($config['installedpackages']['package'][$pkg_id])) - $package =& $config['installedpackages']['package'][$pkg_id]; - else - return; /* empty package tag */ - if(!file_exists("/usr/local/pkg/" . $package['configurationfile'])) { - log_error(sprintf(gettext("The %s package is missing its configuration file and must be reinstalled."), $package['name'])); - force_remove_package($package['name']); - return -1; - } - $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], "packagegui"); - if(isset($pkg_config['nosync'])) - return; - /* Bring in package include files */ - if (!empty($pkg_config['include_file'])) { - $include_file = $pkg_config['include_file']; - if (file_exists($include_file)) - require_once($include_file); - else { - /* XXX: What the heck is this?! */ - log_error("Reinstalling package {$package['name']} because its include file({$include_file}) is missing!"); - uninstall_package($package['name']); - if (install_package($package['name']) < 0) { - log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!"); - return -1; - } - } - } - - if(!empty($pkg_config['custom_php_global_functions'])) - eval($pkg_config['custom_php_global_functions']); - if(!empty($pkg_config['custom_php_resync_config_command'])) - eval($pkg_config['custom_php_resync_config_command']); - if($sync_depends == true) { - $depends = get_pkg_depends($pkg_name, ".xml", "files", 1); // Call dependency handler and do a little more error checking. - if(is_array($depends)) { - foreach($depends as $item) { - if(!file_exists($item)) { - require_once("notices.inc"); - file_notice($package['name'], sprintf(gettext("The %s package is missing required dependencies and must be reinstalled."), $package['name']), "Packages", "/pkg_mgr_install.php?mode=reinstallpkg&pkg={$package['name']}", 1); - log_error("Could not find {$item}. Reinstalling package."); - uninstall_package($pkg_name); - if (install_package($pkg_name) < 0) { - log_error("Reinstalling package {$package['name']} failed. Take appropriate measures!!!"); - return -1; - } - } else { - $item_config = parse_xml_config_pkg($item, "packagegui"); - if (empty($item_config)) - continue; - if(isset($item_config['nosync'])) - continue; - if (!empty($item_config['include_file'])) { - if (file_exists($item_config['include_file'])) - require_once($item_config['include_file']); - else { - log_error("Not calling package sync code for dependency {$item_config['name']} of {$package['name']} because some include files are missing."); - continue; - } - } - if($item_config['custom_php_global_functions'] <> "") - eval($item_config['custom_php_global_functions']); - if($item_config['custom_php_resync_config_command'] <> "") - eval($item_config['custom_php_resync_config_command']); - if($show_message == true) - print " " . $item_config['name']; - } - } - } - } -} - -/* - * pkg_fetch_recursive: Download and install a FreeBSD PBI package. This function provides output to - * a progress bar and output window. - */ -function pkg_fetch_recursive($pkgname, $filename, $dependlevel = 0, $base_url = "") { - global $static_output, $g, $config; - - // Clean up incoming filenames - $filename = str_replace(" ", " ", $filename); - $filename = str_replace("\n", " ", $filename); - $filename = str_replace(" ", " ", $filename); - - $pkgs = explode(" ", $filename); - foreach($pkgs as $filename) { - $filename = trim($filename); - if ($g['platform'] == "nanobsd") { - $pkgtmpdir = "/usr/bin/env PKG_TMPDIR=/root/ "; - $pkgstagingdir = "/root/tmp"; - if (!is_dir($pkgstagingdir)) - mkdir($pkgstagingdir); - $pkgstaging = "-o {$pkgstagingdir}/instmp.XXXXXX"; - $fetchdir = $pkgstagingdir; - } else { - $fetchdir = $g['tmp_path']; - } - - /* FreeBSD has no PBI's hosted, so fall back to our own URL for now. (Maybe fail to PC-BSD?) */ - $rel = get_freebsd_version(); - $priv_url = "https://files.pfsense.org/packages/{$rel}/All/"; - if (empty($base_url)) - $base_url = $priv_url; - if (substr($base_url, -1) == "/") - $base_url = substr($base_url, 0, -1); - $fetchto = "{$fetchdir}/apkg_{$filename}"; - $static_output .= "\n" . str_repeat(" ", $dependlevel * 2 + 1) . "Downloading {$base_url}/{$filename} ... "; - if (download_file_with_progress_bar("{$base_url}/{$filename}", $fetchto) !== true) { - if ($base_url != $priv_url && download_file_with_progress_bar("{$priv_url}/{$filename}", $fetchto) !== true) { - $static_output .= " could not download from there or {$priv_url}/{$filename}.\n"; - update_output_window($static_output); - return false; - } else if ($base_url == $priv_url) { - $static_output .= " failed to download.\n"; - update_output_window($static_output); - return false; - } else { - $static_output .= " [{$osname} repository]\n"; - update_output_window($static_output); - } - } - $static_output .= " (extracting)\n"; - update_output_window($static_output); - - $pkgaddout = ""; - - $no_checksig = ""; - if (isset($config['system']['pkg_nochecksig'])) - $no_checksig = "--no-checksig"; - - $result = exec("/usr/local/sbin/pbi_add " . $pkgstaging . " -f -v {$no_checksig} " . escapeshellarg($fetchto) . " 2>&1", $pkgaddout, $rc); - pkg_debug($pkgname . " " . print_r($pkgaddout, true) . "\n"); - if ($rc == 0) { - $pbi_name = preg_replace('/\.pbi$/','',$filename); - - $gb = exec("/usr/local/sbin/pbi_info {$pbi_name} | /usr/bin/awk '/Prefix/ {print $2}'", $pbi_prefix); - $pbi_prefix = $pbi_prefix[0]; - - $links = get_pbi_binaries(escapeshellarg($pbi_name)); - foreach($links as $link) { - @unlink("/usr/local/{$link['link_name']}"); - @symlink("{$link['target']}","/usr/local/{$link['link_name']}"); - } - - $extra_links = array( - array("target" => "bin", "link_name" => "sbin"), - array("target" => "local/lib", "link_name" => "lib"), - array("target" => "local/libexec", "link_name" => "libexec"), - array("target" => "local/share", "link_name" => "share"), - array("target" => "local/www", "link_name" => "www"), - array("target" => "local/etc", "link_name" => "etc") - ); - - foreach ($extra_links as $link) { - if (!file_exists($pbi_prefix . "/" . $link['target'])) - continue; - @rmdir("{$pbi_prefix}/{$link['link_name']}"); - unlink_if_exists("{$pbi_prefix}/{$link['link_name']}"); - @symlink("{$pbi_prefix}/{$link['target']}", "{$pbi_prefix}/{$link['link_name']}"); - } - pkg_debug("pbi_add successfully completed.\n"); - } else { - if (is_array($pkgaddout)) - foreach ($pkgaddout as $line) - $static_output .= " " . $line .= "\n"; - - update_output_window($static_output); - pkg_debug("pbi_add failed.\n"); - return false; - } - } - return true; -} - -function get_pbi_binaries($pbi) { - $result = array(); - - if (empty($pbi)) - return $result; - - $gb = exec("/usr/local/sbin/pbi_info {$pbi} | /usr/bin/awk '/Prefix/ {print $2}'", $pbi_prefix); - $pbi_prefix = $pbi_prefix[0]; - - if (empty($pbi_prefix)) - return $result; - - foreach(array('bin', 'sbin') as $dir) { - if(!is_dir("{$pbi_prefix}/{$dir}")) - continue; - - $files = glob("{$pbi_prefix}/{$dir}/*.pbiopt"); - foreach($files as $f) { - $pbiopts = file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - foreach($pbiopts as $pbiopt) { - if (!preg_match('/^TARGET:\s+(.*)$/', $pbiopt, $matches)) - continue; - - $result[] = array( - 'target' => preg_replace('/\.pbiopt$/', '', $f), - 'link_name' => $matches[1]); - } - } - } - - return $result; -} - - -function install_package($package, $pkg_info = "", $force_install = false) { - global $g, $config, $static_output, $pkg_interface; - - /* safe side. Write config below will send to ro again. */ - conf_mount_rw(); - - if($pkg_interface == "console") - echo "\n"; - /* fetch package information if needed */ - if(empty($pkg_info) or !is_array($pkg_info[$package])) { - $pkg_info = get_pkg_info(array($package)); - $pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array. - if (empty($pkg_info)) { - conf_mount_ro(); - return -1; - } - } - if (!$force_install) { - $compatible = true; - $version = rtrim(file_get_contents("/etc/version")); - - if (isset($pkg_info['required_version'])) - $compatible = (pfs_version_compare("", $version, $pkg_info['required_version']) >= 0); - if (isset($pkg_info['maximum_version'])) - $compatible = $compatible && (pfs_version_compare("", $version, $pkg_info['maximum_version']) <= 0); - - if (!$compatible) { - log_error(sprintf(gettext('Package %s is not supported on this version.'), $pkg_info['name'])); - $static_output .= sprintf(gettext("Package %s is not supported on this version."), $pkg_info['name']); - update_status($static_output); - - conf_mount_ro(); - return -1; - } - } - pkg_debug(gettext("Beginning package installation.") . "\n"); - log_error(sprintf(gettext('Beginning package installation for %s .'), $pkg_info['name'])); - $static_output .= sprintf(gettext("Beginning package installation for %s ."), $pkg_info['name']); - update_status($static_output); - - /* fetch the package's configuration file */ - pkg_fetch_config_file($package, $pkg_info); - - /* add package information to config.xml */ - $pkgid = get_pkg_id($pkg_info['name']); - $static_output .= gettext("Saving updated package information...") . " "; - update_output_window($static_output); - if($pkgid == -1) { - $config['installedpackages']['package'][] = $pkg_info; - $changedesc = sprintf(gettext("Installed %s package."),$pkg_info['name']); - $to_output = gettext("done.") . "\n"; - } else { - $config['installedpackages']['package'][$pkgid] = $pkg_info; - $changedesc = sprintf(gettext("Overwrote previous installation of %s."), $pkg_info['name']); - $to_output = gettext("overwrite!") . "\n"; - } - if(file_exists('/conf/needs_package_sync')) - @unlink('/conf/needs_package_sync'); - conf_mount_ro(); - write_config("Intermediate config write during package install for {$pkg_info['name']}."); - $static_output .= $to_output; - update_output_window($static_output); - /* install other package components */ - if (!install_package_xml($package)) { - uninstall_package($package); - write_config($changedesc); - $static_output .= gettext("Failed to install package.") . "\n"; - update_output_window($static_output); - return -1; - } else { - $static_output .= gettext("Writing configuration... "); - update_output_window($static_output); - write_config($changedesc); - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - if($pkg_info['after_install_info']) - update_output_window($pkg_info['after_install_info']); - } -} - -function get_after_install_info($package) { - global $pkg_info; - /* fetch package information if needed */ - if(!$pkg_info or !is_array($pkg_info[$package])) { - $pkg_info = get_pkg_info(array($package)); - $pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array. - } - if($pkg_info['after_install_info']) - return $pkg_info['after_install_info']; -} - -function eval_once($toeval) { - global $evaled; - if(!$evaled) $evaled = array(); - $evalmd5 = md5($toeval); - if(!in_array($evalmd5, $evaled)) { - @eval($toeval); - $evaled[] = $evalmd5; - } - return; -} - -function install_package_xml($pkg) { - global $g, $config, $static_output, $pkg_interface, $config_parsed; - - if(($pkgid = get_pkg_id($pkg)) == -1) { - $static_output .= sprintf(gettext("The %s package is not installed.%sInstallation aborted."), $pkg, "\n\n"); - update_output_window($static_output); - if($pkg_interface <> "console") { - echo "\n"; - echo "\n"; - } - sleep(1); - return false; - } else - $pkg_info = $config['installedpackages']['package'][$pkgid]; - - /* pkg_add the package and its dependencies */ - if($pkg_info['depends_on_package_base_url'] != "") { - if($pkg_interface == "console") - echo "\n"; - update_status(gettext("Installing") . " " . $pkg_info['name'] . " " . gettext("and its dependencies.")); - $static_output .= gettext("Downloading") . " " . $pkg_info['name'] . " " . gettext("and its dependencies... "); - $static_orig = $static_output; - $static_output .= "\n"; - update_output_window($static_output); - foreach((array) $pkg_info['depends_on_package_pbi'] as $pkgdep) { - $pkg_name = substr(reverse_strrchr($pkgdep, "."), 0, -1); - $static_output = $static_orig . "\nChecking for package installation... "; - update_output_window($static_output); - if (!is_freebsd_pkg_installed($pkg_name)) { - if (!pkg_fetch_recursive($pkg_name, $pkgdep, 0, $pkg_info['depends_on_package_base_url'])) { - $static_output .= "of {$pkg_name} failed!\n\nInstallation aborted."; - update_output_window($static_output); - pkg_debug(gettext("Package WAS NOT installed properly.") . "\n"); - if($pkg_interface <> "console") { - echo "\n"; - echo "\n"; - } - sleep(1); - return false; - } - } - } - } - - $configfile = substr(strrchr($pkg_info['config_file'], '/'), 1); - if(file_exists("/usr/local/pkg/" . $configfile)) { - $static_output .= gettext("Loading package configuration... "); - update_output_window($static_output); - $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui"); - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - $static_output .= gettext("Configuring package components...\n"); - if (!empty($pkg_config['filter_rules_needed'])) - $config['installedpackages']['package'][$pkgid]['filter_rule_function'] = $pkg_config['filter_rules_needed']; - update_output_window($static_output); - /* modify system files */ - if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) { - $static_output .= gettext("System files... "); - update_output_window($static_output); - foreach($pkg_config['modify_system']['item'] as $ms) { - if($ms['textneeded']) { - add_text_to_file($ms['modifyfilename'], $ms['textneeded']); - } - } - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - - pkg_fetch_additional_files($pkg, $pkg_info); - - /* if a require exists, include it. this will - * show us where an error exists in a package - * instead of making us blindly guess - */ - $missing_include = false; - if($pkg_config['include_file'] <> "") { - $static_output .= gettext("Loading package instructions...") . "\n"; - update_output_window($static_output); - pkg_debug("require_once('{$pkg_config['include_file']}')\n"); - if (file_exists($pkg_config['include_file'])) - require_once($pkg_config['include_file']); - else { - $missing_include = true; - $static_output .= "Include " . basename($pkg_config['include_file']) . " is missing!\n"; - update_output_window($static_output); - /* XXX: Should undo the steps before this?! */ - return false; - } - } - - /* custom commands */ - $static_output .= gettext("Custom commands...") . "\n"; - update_output_window($static_output); - if ($missing_include == false) { - if($pkg_config['custom_php_global_functions'] <> "") { - $static_output .= gettext("Executing custom_php_global_functions()..."); - update_output_window($static_output); - eval_once($pkg_config['custom_php_global_functions']); - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - if($pkg_config['custom_php_install_command']) { - $static_output .= gettext("Executing custom_php_install_command()..."); - update_output_window($static_output); - /* XXX: create symlinks for conf files into the PBI directories. - * change packages to store configs at /usr/pbi/pkg/etc and remove this - */ - eval_once($pkg_config['custom_php_install_command']); - // Note: pkg may be mixed-case, e.g. "squidGuard" but the PBI names are lowercase. - // e.g. "squidguard-1.4_4-i386" so feed lowercase to pbi_info below. - // Also add the "-" so that examples like "squid-" do not match "squidguard-". - $pkg_name_for_pbi_match = strtolower($pkg) . "-"; - exec("/usr/local/sbin/pbi_info | grep '^{$pkg_name_for_pbi_match}' | xargs /usr/local/sbin/pbi_info | awk '/Prefix/ {print $2}'",$pbidirarray); - $pbidir0 = $pbidirarray[0]; - exec("find /usr/local/etc/ -name *.conf | grep " . escapeshellarg($pkg),$files); - foreach($files as $f) { - $pbiconf = str_replace('/usr/local',$pbidir0,$f); - if(is_file($pbiconf) || is_link($pbiconf)) { - unlink($pbiconf); - } - if(is_dir(dirname($pbiconf))) { - symlink($f,$pbiconf); - } else { - log_error("The dir for {$pbiconf} does not exist. Cannot add symlink to {$f}."); - } - } - eval_once($pkg_config['custom_php_install_command']); - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - if($pkg_config['custom_php_resync_config_command'] <> "") { - $static_output .= gettext("Executing custom_php_resync_config_command()..."); - update_output_window($static_output); - eval_once($pkg_config['custom_php_resync_config_command']); - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - } - /* sidebar items */ - if(is_array($pkg_config['menu'])) { - $static_output .= gettext("Menu items... "); - update_output_window($static_output); - foreach($pkg_config['menu'] as $menu) { - if(is_array($config['installedpackages']['menu'])) { - foreach($config['installedpackages']['menu'] as $amenu) - if($amenu['name'] == $menu['name']) - continue 2; - } else - $config['installedpackages']['menu'] = array(); - $config['installedpackages']['menu'][] = $menu; - } - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - /* integrated tab items */ - if(is_array($pkg_config['tabs']['tab'])) { - $static_output .= gettext("Integrated Tab items... "); - update_output_window($static_output); - foreach($pkg_config['tabs']['tab'] as $tab) { - if(is_array($config['installedpackages']['tab'])) { - foreach($config['installedpackages']['tab'] as $atab) - if($atab['name'] == $tab['name']) - continue 2; - } else - $config['installedpackages']['tab'] = array(); - $config['installedpackages']['tab'][] = $tab; - } - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - /* services */ - if(is_array($pkg_config['service'])) { - $static_output .= gettext("Services... "); - update_output_window($static_output); - foreach($pkg_config['service'] as $service) { - if(is_array($config['installedpackages']['service'])) { - foreach($config['installedpackages']['service'] as $aservice) - if($aservice['name'] == $service['name']) - continue 2; - } else - $config['installedpackages']['service'] = array(); - $config['installedpackages']['service'][] = $service; - } - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - } else { - $static_output .= gettext("Loading package configuration... failed!") . "\n\n" . gettext("Installation aborted."); - update_output_window($static_output); - pkg_debug(gettext("Unable to load package configuration. Installation aborted.") ."\n"); - if($pkg_interface <> "console") { - echo "\n"; - echo "\n"; - } - sleep(1); - return false; - } - - /* set up package logging streams */ - if($pkg_info['logging']) { - mwexec("/usr/sbin/fifolog_create -s 32768 {$g['varlog_path']}/{$pkg_info['logging']['logfilename']}"); - @chmod($g['varlog_path'] . '/' . $pkg_info['logging']['logfilename'], 0600); - add_text_to_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']); - pkg_debug("Adding text to file /etc/syslog.conf\n"); - system_syslogd_start(); - } - - return true; -} - -function does_package_depend($pkg) { - // Should not happen, but just in case. - if(!$pkg) - return; - $pkg_var_db_dir = glob("/var/db/pkg/{$pkg}*"); - // If this package has dependency then return true - foreach($pkg_var_db_dir as $pvdd) { - if (file_exists("{$vardb}/{$pvdd}/+REQUIRED_BY") && count(file("{$vardb}/{$pvdd}/+REQUIRED_BY")) > 0) - return true; - } - // Did not find a record of dependencies, so return false. - return false; -} - -function delete_package($pkg) { - global $config, $g, $static_output, $vardb; - - if(!$pkg) - return; - - // Note: $pkg has the full PBI package name followed by ".pbi". Strip off ".pbi". - $pkg = substr(reverse_strrchr($pkg, "."), 0, -1); - - if($pkg) - $static_output .= sprintf(gettext("Starting package deletion for %s..."),$pkg); - update_output_window($static_output); - - remove_freebsd_package($pkg); - $static_output .= "done.\n"; - update_output_window($static_output); - - /* Rescan directories for what has been left and avoid fooling other programs. */ - mwexec("/sbin/ldconfig"); - - return; -} - -function delete_package_xml($pkg) { - global $g, $config, $static_output, $pkg_interface; - - conf_mount_rw(); - - $pkgid = get_pkg_id($pkg); - if ($pkgid == -1) { - $static_output .= sprintf(gettext("The %s package is not installed.%sDeletion aborted."), $pkg, "\n\n"); - update_output_window($static_output); - if($pkg_interface <> "console") { - echo "\n"; - echo "\n"; - } - ob_flush(); - sleep(1); - conf_mount_ro(); - return; - } - pkg_debug(sprintf(gettext("Removing %s package... "),$pkg)); - $static_output .= sprintf(gettext("Removing %s components..."),$pkg) . "\n"; - update_output_window($static_output); - /* parse package configuration */ - $packages = &$config['installedpackages']['package']; - $tabs =& $config['installedpackages']['tab']; - $menus =& $config['installedpackages']['menu']; - $services = &$config['installedpackages']['service']; - $pkg_info =& $packages[$pkgid]; - if(file_exists("/usr/local/pkg/" . $pkg_info['configurationfile'])) { - $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $packages[$pkgid]['configurationfile'], "packagegui"); - /* remove tab items */ - if(is_array($pkg_config['tabs'])) { - $static_output .= gettext("Tabs items... "); - update_output_window($static_output); - if(is_array($pkg_config['tabs']['tab']) && is_array($tabs)) { - foreach($pkg_config['tabs']['tab'] as $tab) { - foreach($tabs as $key => $insttab) { - if($insttab['name'] == $tab['name']) { - unset($tabs[$key]); - break; - } - } - } - } - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - /* remove menu items */ - if(is_array($pkg_config['menu'])) { - $static_output .= gettext("Menu items... "); - update_output_window($static_output); - if (is_array($pkg_config['menu']) && is_array($menus)) { - foreach($pkg_config['menu'] as $menu) { - foreach($menus as $key => $instmenu) { - if($instmenu['name'] == $menu['name']) { - unset($menus[$key]); - break; - } - } - } - } - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - /* remove services */ - if(is_array($pkg_config['service'])) { - $static_output .= gettext("Services... "); - update_output_window($static_output); - if (is_array($pkg_config['service']) && is_array($services)) { - foreach($pkg_config['service'] as $service) { - foreach($services as $key => $instservice) { - if($instservice['name'] == $service['name']) { - if($g['booting'] != true) - stop_service($service['name']); - if($service['rcfile']) { - $prefix = RCFILEPREFIX; - if (!empty($service['prefix'])) - $prefix = $service['prefix']; - if (file_exists("{$prefix}{$service['rcfile']}")) - @unlink("{$prefix}{$service['rcfile']}"); - } - unset($services[$key]); - } - } - } - } - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - /* - * XXX: Otherwise inclusion of config.inc again invalidates actions taken. - * Same is done during installation. - */ - write_config("Intermediate config write during package removal for {$pkg}."); - - /* - * If a require exists, include it. this will - * show us where an error exists in a package - * instead of making us blindly guess - */ - $missing_include = false; - if($pkg_config['include_file'] <> "") { - $static_output .= gettext("Loading package instructions...") . "\n"; - update_output_window($static_output); - pkg_debug("require_once(\"{$pkg_config['include_file']}\")\n"); - if (file_exists($pkg_config['include_file'])) - require_once($pkg_config['include_file']); - else { - $missing_include = true; - update_output_window($static_output); - $static_output .= "Include file " . basename($pkg_config['include_file']) . " could not be found for inclusion.\n"; - } - } - /* ermal - * NOTE: It is not possible to handle parse errors on eval. - * So we prevent it from being run at all to not interrupt all the other code. - */ - if ($missing_include == false) { - /* evalate this package's global functions and pre deinstall commands */ - if($pkg_config['custom_php_global_functions'] <> "") - eval_once($pkg_config['custom_php_global_functions']); - if($pkg_config['custom_php_pre_deinstall_command'] <> "") - eval_once($pkg_config['custom_php_pre_deinstall_command']); - } - /* system files */ - if(is_array($pkg_config['modify_system']) && is_array($pkg_config['modify_system']['item'])) { - $static_output .= gettext("System files... "); - update_output_window($static_output); - foreach($pkg_config['modify_system']['item'] as $ms) - if($ms['textneeded']) remove_text_from_file($ms['modifyfilename'], $ms['textneeded']); - - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - /* deinstall commands */ - if($pkg_config['custom_php_deinstall_command'] <> "") { - $static_output .= gettext("Deinstall commands... "); - update_output_window($static_output); - if ($missing_include == false) { - eval_once($pkg_config['custom_php_deinstall_command']); - $static_output .= gettext("done.") . "\n"; - } else - $static_output .= "\nNot executing custom deinstall hook because an include is missing.\n"; - update_output_window($static_output); - } - if($pkg_config['include_file'] <> "") { - $static_output .= gettext("Removing package instructions..."); - update_output_window($static_output); - pkg_debug(sprintf(gettext("Remove '%s'"), $pkg_config['include_file']) . "\n"); - unlink_if_exists("/usr/local/pkg/" . $pkg_config['include_file']); - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - /* remove all additional files */ - if(is_array($pkg_config['additional_files_needed'])) { - $static_output .= gettext("Auxiliary files... "); - update_output_window($static_output); - foreach($pkg_config['additional_files_needed'] as $afn) { - $filename = get_filename_from_url($afn['item'][0]); - if($afn['prefix'] <> "") - $prefix = $afn['prefix']; - else - $prefix = "/usr/local/pkg/"; - unlink_if_exists($prefix . $filename); - } - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - /* package XML file */ - $static_output .= gettext("Package XML... "); - update_output_window($static_output); - unlink_if_exists("/usr/local/pkg/" . $packages[$pkgid]['configurationfile']); - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - /* syslog */ - if(is_array($pkg_info['logging']) && $pkg_info['logging']['logfile_name'] <> "") { - $static_output .= "Syslog entries... "; - update_output_window($static_output); - remove_text_from_file("/etc/syslog.conf", $pkg_info['logging']['facilityname'] . "\t\t\t\t" . $pkg_info['logging']['logfilename']); - system_syslogd_start(); - @unlink("{$g['varlog_path']}/{$pkg_info['logging']['logfilename']}"); - $static_output .= "done.\n"; - update_output_window($static_output); - } - - conf_mount_ro(); - /* remove config.xml entries */ - $static_output .= gettext("Configuration... "); - update_output_window($static_output); - unset($config['installedpackages']['package'][$pkgid]); - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - write_config("Removed {$pkg} package.\n"); -} - -function expand_to_bytes($size) { - $conv = array( - "G" => "3", - "M" => "2", - "K" => "1", - "B" => "0" - ); - $suffix = substr($size, -1); - if(!in_array($suffix, array_keys($conv))) return $size; - $size = substr($size, 0, -1); - for($i = 0; $i < $conv[$suffix]; $i++) { - $size *= 1024; - } - return $size; -} - -function get_pkg_db() { - global $g; - return return_dir_as_array($g['vardb_path'] . '/pkg'); -} - -function walk_depend($depend, $pkgdb = "", $alreadyseen = "") { - if(!$pkgdb) - $pkgdb = get_pkg_db(); - if(!is_array($alreadyseen)) - $alreadyseen = array(); - if (!is_array($depend)) - $depend = array(); - foreach($depend as $adepend) { - $pkgname = reverse_strrchr($adepend['name'], '.'); - if(in_array($pkgname, $alreadyseen)) { - continue; - } elseif(!in_array($pkgname, $pkgdb)) { - $size += expand_to_bytes($adepend['size']); - $alreadyseen[] = $pkgname; - if(is_array($adepend['depend'])) $size += walk_depend($adepend['depend'], $pkgdb, $alreadyseen); - } - } - return $size; -} - -function get_package_install_size($pkg = 'all', $pkg_info = "") { - global $config, $g; - if((!is_array($pkg)) and ($pkg != 'all')) - $pkg = array($pkg); - $pkgdb = get_pkg_db(); - if(!$pkg_info) - $pkg_info = get_pkg_sizes($pkg); - foreach($pkg as $apkg) { - if(!$pkg_info[$apkg]) - continue; - $toreturn[$apkg] = expand_to_bytes(walk_depend(array($pkg_info[$apkg]), $pkgdb)); - } - return $toreturn; -} - -function squash_from_bytes($size, $round = "") { - $conv = array(1 => "B", "K", "M", "G"); - foreach($conv as $div => $suffix) { - $sizeorig = $size; - if(($size /= 1024) < 1) { - if($round) { - $sizeorig = round($sizeorig, $round); - } - return $sizeorig . $suffix; - } - } - return; -} - -function pkg_reinstall_all() { - global $g, $config; - - @unlink('/conf/needs_package_sync'); - if (is_array($config['installedpackages']['package'])) { - echo gettext("One moment please, reinstalling packages...\n"); - echo gettext(" >>> Trying to fetch package info..."); - log_error(gettext("Attempting to reinstall all packages")); - $pkg_info = get_pkg_info(); - if ($pkg_info) { - echo " Done.\n"; - } else { - $xmlrpc_base_url = get_active_xml_rpc_base_url(); - $error = sprintf(gettext(' >>> Unable to communicate with %1$s. Please verify DNS and interface configuration, and that %2$s has functional Internet connectivity.'), $xmlrpc_base_url, $g['product_name']); - echo "\n{$error}\n"; - log_error(gettext("Cannot reinstall packages: ") . $error); - return; - } - $todo = array(); - $all_names = array(); - foreach($config['installedpackages']['package'] as $package) { - $todo[] = array('name' => $package['name'], 'version' => $package['version']); - $all_names[] = $package['name']; - } - $package_name_list = gettext("List of packages to reinstall: ") . implode(", ", $all_names); - echo " >>> {$package_name_list}\n"; - log_error($package_name_list); - - foreach($todo as $pkgtodo) { - $static_output = ""; - if($pkgtodo['name']) { - log_error(gettext("Uninstalling package") . " {$pkgtodo['name']}"); - uninstall_package($pkgtodo['name']); - log_error(gettext("Finished uninstalling package") . " {$pkgtodo['name']}"); - log_error(gettext("Reinstalling package") . " {$pkgtodo['name']}"); - install_package($pkgtodo['name']); - log_error(gettext("Finished installing package") . " {$pkgtodo['name']}"); - } - } - log_error(gettext("Finished reinstalling all packages.")); - } else - echo "No packages are installed."; -} - -function stop_packages() { - require_once("config.inc"); - require_once("functions.inc"); - require_once("filter.inc"); - require_once("shaper.inc"); - require_once("captiveportal.inc"); - require_once("pkg-utils.inc"); - require_once("pfsense-utils.inc"); - require_once("service-utils.inc"); - - global $config, $g; - - log_error("Stopping all packages."); - - $rcfiles = glob(RCFILEPREFIX . "*.sh"); - if (!$rcfiles) - $rcfiles = array(); - else { - $rcfiles = array_flip($rcfiles); - if (!$rcfiles) - $rcfiles = array(); - } - - if (is_array($config['installedpackages']['package'])) { - foreach($config['installedpackages']['package'] as $package) { - echo " Stopping package {$package['name']}..."; - $internal_name = get_pkg_internal_name($package); - stop_service($internal_name); - unset($rcfiles[RCFILEPREFIX . strtolower($internal_name) . ".sh"]); - echo "done.\n"; - } - } - - foreach ($rcfiles as $rcfile => $number) { - $shell = @popen("/bin/sh", "w"); - if ($shell) { - echo " Stopping {$rcfile}..."; - if (!@fwrite($shell, "{$rcfile} stop >>/tmp/bootup_messages 2>&1")) { - if ($shell) - pclose($shell); - $shell = @popen("/bin/sh", "w"); - } - echo "done.\n"; - pclose($shell); - } - } -} - -function package_skip_tests($index,$requested_version){ - global $config, $g; - - /* Get pfsense version*/ - $version = rtrim(file_get_contents("/etc/version")); - - if($g['platform'] == "nanobsd") - if($index['noembedded']) - return true; - - /* If we are on not on HEAD, and the package wants it, skip */ - if ($version <> "HEAD" && $index['required_version'] == "HEAD" && $requested_version <> "other") - return true; - - /* If there is no required version, and the requested package version is not 'none', then skip */ - if (empty($index['required_version']) && $requested_version <> "none") - return true; - - /* If the requested version is not 'other', and the required version is newer than what we have, skip. */ - if($requested_version <> "other" && (pfs_version_compare("", $version, $index['required_version']) < 0)) - return true; - - /* If the requestion version is 'other' and we are on the version requested, skip. */ - if($requested_version == "other" && (pfs_version_compare("", $version, $index['required_version']) == 0)) - return true; - - /* Package is only for an older version, lets skip */ - if($index['maximum_version'] && (pfs_version_compare("", $version, $index['maximum_version']) > 0)) - return true; - - /* Do not skip package list */ - return false; -} - -function get_pkg_interfaces_select_source($include_localhost=false) { - $interfaces = get_configured_interface_with_descr(); - $ssifs = array(); - foreach ($interfaces as $iface => $ifacename) { - $tmp["name"] = $ifacename; - $tmp["value"] = $iface; - $ssifs[] = $tmp; - } - if ($include_localhost) { - $tmp["name"] = "Localhost"; - $tmp["value"] = "lo0"; - $ssifs[] = $tmp; - } - return $ssifs; -} - -function verify_all_package_servers() { - return verify_package_server(get_active_xml_rpc_base_url()); -} - -/* Check if the active package server is a valid default or if it has been - altered. */ -function verify_package_server($server) { - /* Define the expected default package server domains. Include - preceding "." to prevent matching from being too liberal. */ - $default_package_domains = array('.pfsense.org', '.pfsense.com', '.netgate.com'); - - /* For this test we only need to check the hostname. */ - $xmlrpcbase = parse_url($server, PHP_URL_HOST); - - foreach ($default_package_domains as $dom) { - if (substr($xmlrpcbase, -(strlen($dom))) == $dom) { - return true; - } - } - return false; -} - -/* Test the package server certificate to ensure that it validates properly */ -function check_package_server_ssl() { - global $g; - $xmlrpcurl = get_active_xml_rpc_base_url() . $g['xmlrpcpath']; - - /* If the package server is using HTTP, we can't verify SSL */ - if (substr($xmlrpcurl, 0, 5) == "http:") { - return "http"; - } - - /* Setup a basic cURL connection. We do not care about the content of - the result, only the SSL verification. */ - $ch = curl_init($xmlrpcurl); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, '30'); - curl_setopt($ch, CURLOPT_TIMEOUT, 60); - curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version"))); - $result_page = curl_exec($ch); - $verifyfail = curl_getinfo($ch, CURLINFO_SSL_VERIFYRESULT); - curl_close($ch); - - /* The result from curl is 1 on failure, 0 on success. */ - if ($verifyfail == 0) - return true; - else - return false; -} - -/* Keep this message centrally since it will be used several times on pages - in the GUI. */ -function package_server_ssl_failure_message() { - $msg = "The package server's SSL certificate could not be verified. " - . "The SSL certificate itself may be invalid, its chain of trust may " - . "have failed validation, or the server may have been impersonated. " - . "Downloaded packages may come from an untrusted source. " - . "Proceed with caution."; - - return sprintf(gettext($msg), htmlspecialchars(get_active_xml_rpc_base_url())); -} - -/* Keep this message centrally since it will be used several times on pages - in the GUI. */ -function package_server_mismatch_message() { - $msg = "The package server currently configured on " - . "this firewall (%s) is NOT an official package server. The contents " - . "of such servers cannot be verified and may contain malicious files. " - . "Return the package server settings to their default values to " - . "ensure that verifiable and trusted packages are received."; - - return sprintf(gettext($msg), htmlspecialchars(get_active_xml_rpc_base_url())) . '

' - . '' . gettext("Package Manager Settings") . ''; -} - - -function pkg_fetch_config_file($package, $pkg_info = "") { - global $g, $config, $static_output, $pkg_interface; - conf_mount_rw(); - - if(empty($pkg_info) or !is_array($pkg_info[$package])) { - $pkg_info = get_pkg_info(array($package)); - $pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array. - if (empty($pkg_info)) { - conf_mount_ro(); - return -1; - } - } - - /* fetch the package's configuration file */ - if($pkg_info['config_file'] != "") { - $static_output .= "\n" . gettext("Downloading package configuration file... "); - update_output_window($static_output); - pkg_debug(gettext("Downloading package configuration file...") . "\n"); - $fetchto = substr(strrchr($pkg_info['config_file'], '/'), 1); - download_file_with_progress_bar($pkg_info['config_file'], '/usr/local/pkg/' . $fetchto); - if(!file_exists('/usr/local/pkg/' . $fetchto)) { - pkg_debug(gettext("ERROR! Unable to fetch package configuration file. Aborting installation.") . "\n"); - if($pkg_interface == "console") - print "\n" . gettext("ERROR! Unable to fetch package configuration file. Aborting package installation.") . "\n"; - else { - $static_output .= gettext("failed!\n\nInstallation aborted.\n"); - update_output_window($static_output); - echo "
Show install log"; - } - conf_mount_ro(); - return -1; - } - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - conf_mount_ro(); - return true; -} - - -function pkg_fetch_additional_files($package, $pkg_info = "") { - global $g, $config, $static_output, $pkg_interface; - conf_mount_rw(); - - if(empty($pkg_info) or !is_array($pkg_info[$package])) { - $pkg_info = get_pkg_info(array($package)); - $pkg_info = $pkg_info[$package]; // We're only dealing with one package, so we can strip away the extra array. - if (empty($pkg_info)) { - conf_mount_ro(); - return -1; - } - } - - $configfile = substr(strrchr($pkg_info['config_file'], '/'), 1); - if(file_exists("/usr/local/pkg/" . $configfile)) { - $static_output .= gettext("Loading package configuration... "); - update_output_window($static_output); - $pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $configfile, "packagegui"); - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - /* download additional files */ - if(is_array($pkg_config['additional_files_needed'])) { - $static_output .= gettext("Additional files... "); - $static_orig = $static_output; - update_output_window($static_output); - foreach($pkg_config['additional_files_needed'] as $afn) { - $filename = get_filename_from_url($afn['item'][0]); - if($afn['chmod'] <> "") - $pkg_chmod = $afn['chmod']; - else - $pkg_chmod = ""; - - if($afn['prefix'] <> "") - $prefix = $afn['prefix']; - else - $prefix = "/usr/local/pkg/"; - - if(!is_dir($prefix)) - safe_mkdir($prefix); - $static_output .= $filename . " "; - update_output_window($static_output); - if (download_file_with_progress_bar($afn['item'][0], $prefix . $filename) !== true) { - $static_output .= "failed.\n"; - @unlink($prefix . $filename); - update_output_window($static_output); - return false; - } - if(stristr($filename, ".tgz") <> "") { - pkg_debug(gettext("Extracting tarball to -C for ") . $filename . "...\n"); - $tarout = ""; - exec("/usr/bin/tar xvzf " . escapeshellarg($prefix . $filename) . " -C / 2>&1", $tarout); - pkg_debug(print_r($tarout, true) . "\n"); - } - if($pkg_chmod <> "") { - pkg_debug(sprintf(gettext('Changing file mode to %1$s for %2$s%3$s%4$s'), $pkg_chmod, $prefix, $filename, "\n")); - @chmod($prefix . $filename, $pkg_chmod); - system("/bin/chmod {$pkg_chmod} {$prefix}{$filename}"); - } - $static_output = $static_orig; - update_output_window($static_output); - } - $static_output .= gettext("done.") . "\n"; - update_output_window($static_output); - } - conf_mount_ro(); - return true; - } -} - -?> diff --git a/usr/local/www/includes/service-utils.inc b/usr/local/www/includes/service-utils.inc deleted file mode 100644 index 58e9fe6e8..000000000 --- a/usr/local/www/includes/service-utils.inc +++ /dev/null @@ -1,825 +0,0 @@ - "") { - eval("\$rc={$aservice['custom_php_service_status_command']};"); - return $rc; - } - if(empty($aservice['executable'])) - return false; - if (is_process_running($aservice['executable'])) - return true; - - return false; - } - } - } - - if (is_process_running($service)) - return true; - - return false; - } - -} - -if (!function_exists('get_services')) { - - function get_services() { - global $config; - if (is_array($config['installedpackages']['service'])) - $services = $config['installedpackages']['service']; - else - $services = array(); - - /* Add services that are in the base. - * - */ - if (is_radvd_enabled()) { - $pconfig = array(); - $pconfig['name'] = "radvd"; - $pconfig['description'] = gettext("Router Advertisement Daemon"); - $services[] = $pconfig; - } - - if (isset($config['dnsmasq']['enable'])) { - $pconfig = array(); - $pconfig['name'] = "dnsmasq"; - $pconfig['description'] = gettext("DNS Forwarder"); - $services[] = $pconfig; - } - - if (isset($config['unbound']['enable'])) { - $pconfig = array(); - $pconfig['name'] = "unbound"; - $pconfig['description'] = gettext("Unbound DNS Forwarder"); - $services[] = $pconfig; - } - - $pconfig = array(); - $pconfig['name'] = "ntpd"; - $pconfig['description'] = gettext("NTP clock sync"); - $services[] = $pconfig; - - if (is_array($config['captiveportal'])) { - foreach ($config['captiveportal'] as $zone => $setting) { - if (isset($setting['enable'])) { - $pconfig = array(); - $pconfig['name'] = "captiveportal"; - $pconfig['zone'] = $zone; - $pconfig['description'] = gettext("Captive Portal") . ": ".htmlspecialchars($setting['zone']); - $services[] = $pconfig; - } - } - } - - $iflist = array(); - $ifdescrs = get_configured_interface_list(); - foreach ($ifdescrs as $if) { - $oc = $config['interfaces'][$if]; - if ($oc['if'] && (!link_interface_to_bridge($if))) - $iflist[$if] = $if; - } - - if (isset($config['dhcrelay']['enable'])) { - $pconfig = array(); - $pconfig['name'] = "dhcrelay"; - $pconfig['description'] = gettext("DHCP Relay"); - $services[] = $pconfig; - } - - if (isset($config['dhcrelay6']['enable'])) { - $pconfig = array(); - $pconfig['name'] = "dhcrelay6"; - $pconfig['description'] = gettext("DHCPv6 Relay"); - $services[] = $pconfig; - } - - if (is_dhcp_server_enabled()) { - $pconfig = array(); - $pconfig['name'] = "dhcpd"; - $pconfig['description'] = gettext("DHCP Service"); - $services[] = $pconfig; - } - - $gateways_arr = return_gateways_array(); - if (is_array($gateways_arr)) { - $pconfig = array(); - $pconfig['name'] = "apinger"; - $pconfig['description'] = gettext("Gateway Monitoring Daemon"); - $services[] = $pconfig; - } - - if (isset($config['snmpd']['enable'])) { - $pconfig = array(); - $pconfig['name'] = "bsnmpd"; - $pconfig['description'] = gettext("SNMP Service"); - $services[] = $pconfig; - } - - if (is_array($config['igmpproxy']['igmpentry']) && (count($config['igmpproxy']['igmpentry']) > 0)) { - $pconfig = array(); - $pconfig['name'] = "igmpproxy"; - $pconfig['description'] = gettext("IGMP proxy"); - $services[] = $pconfig; - } - - if (isset($config['installedpackages']['miniupnpd']) && $config['installedpackages']['miniupnpd']['config'][0]['enable']) { - $pconfig = array(); - $pconfig['name'] = "miniupnpd"; - $pconfig['description'] = gettext("UPnP Service"); - $services[] = $pconfig; - } - - if (isset($config['installedpackages']['routed']) && $config['installedpackages']['routed']['config'][0]['enable']) { - $pconfig = array(); - $pconfig['name'] = "routed"; - $pconfig['description'] = gettext("RIP Daemon"); - $services[] = $pconfig; - } - - if (isset($config['ipsec']['enable'])) { - $pconfig = array(); - $pconfig['name'] = "ipsec"; - $pconfig['description'] = gettext("IPsec VPN"); - $services[] = $pconfig; - } - - if (isset($config['system']['enablesshd'])) { - $pconfig = array(); - $pconfig['name'] = "sshd"; - $pconfig['description'] = gettext("Secure Shell Daemon"); - $services[] = $pconfig; - } - - foreach (array('server', 'client') as $mode) { - if (is_array($config['openvpn']["openvpn-{$mode}"])) { - foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) { - if (!isset($setting['disable'])) { - $pconfig = array(); - $pconfig['name'] = "openvpn"; - $pconfig['mode'] = $mode; - $pconfig['id'] = $id; - $pconfig['vpnid'] = $setting['vpnid']; - $pconfig['description'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']); - $services[] = $pconfig; - } - } - } - } - - if (count($config['load_balancer']['virtual_server']) && count($config['load_balancer']['lbpool'])) { - $pconfig = array(); - $pconfig['name'] = "relayd"; - $pconfig['description'] = gettext("Server load balancing daemon"); - $services[] = $pconfig; - } - return $services; - } - -} - -if (!function_exists('find_service_by_name')) { - - function find_service_by_name($name) { - $services = get_services(); - foreach ($services as $service) - if ($service["name"] == $name) - return $service; - return array(); - } - -} - -if (!function_exists('find_service_by_openvpn_vpnid')) { - - function find_service_by_openvpn_vpnid($vpnid) { - $services = get_services(); - foreach ($services as $service) - if (($service["name"] == "openvpn") && isset($service["vpnid"]) && ($service["vpnid"] == $vpnid)) - return $service; - return array(); - } - - -} - -if (!function_exists('find_service_by_cp_zone')) { - - - function find_service_by_cp_zone($zone) { - $services = get_services(); - foreach ($services as $service) - if (($service["name"] == "captiveportal") && isset($service["zone"]) && ($service["zone"] == $zone)) - return $service; - return array(); - } - - -} - -if (!function_exists('service_name_compare')) { - - - function service_name_compare($a, $b) { - if (strtolower($a['name']) == strtolower($b['name'])) - return 0; - return (strtolower($a['name']) < strtolower($b['name'])) ? -1 : 1; - } - - -} - -if (!function_exists('get_pkg_descr')) { - - - 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) - return $pkg['descr']; - } - } - return gettext("Not available."); - } - - -} - -if (!function_exists('get_service_status')) { - - - function get_service_status($service) { - global $g; - switch ($service['name']) { - case "openvpn": - $running = is_pid_running("{$g['varrun_path']}/openvpn_{$service['mode']}{$service['vpnid']}.pid"); - break; - case "captiveportal": - $running = is_pid_running("{$g['varrun_path']}/lighty-{$service['zone']}-CaptivePortal.pid"); - 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"); - break; - case "dhcrelay6": - $running = is_pid_running("{$g['varrun_path']}/dhcrelay6.pid"); - break; - case 'ipsec': - $running = is_pid_running("{$g['varrun_path']}/charon.pid"); - break; - default: - $running = is_service_running($service['name']); - } - return $running; - } - - -} - -if (!function_exists('get_service_status_icon')) { - - - function get_service_status_icon($service, $withtext = true, $smallicon = false) { - global $g; - $output = ""; - if(get_service_status($service)) { - $statustext = gettext("Running"); - - $output .= ' '; - - /* - $output .= "\"status\" "; - if ($withtext) - $output .= " " . $statustext; - */ - } - - - else { - $service_enabled = is_service_enabled($service['name']); - $statustext = ($service_enabled) ? gettext("Stopped") : gettext("Disabled"); - - $output .= ' '; - /* - - $output .= "\"status\" "; - if ($withtext) - $output .= " {$statustext}"; - */ - - } - return $output; - } - - -} - -if (!function_exists('get_service_control_links')) { - - - function get_service_control_links($service, $addname = false) { - global $g; - $output = ""; - $stitle = ($addname) ? $service['name'] . " " : ""; - if(get_service_status($service)) { - switch ($service['name']) { - case "openvpn": - $output .= ""; - break; - case "captiveportal": - $output .= ""; - break; - default: - $output .= ""; - } - $output .= "\n"; - switch ($service['name']) { - case "openvpn": - $output .= ""; - break; - case "captiveportal": - $output .= ""; - break; - default: - $output .= ""; - } - $output .= ""; - $output .= ""; - } else { - $service_enabled = is_service_enabled($service['name']); - switch ($service['name']) { - case "openvpn": - $output .= ""; - break; - case "captiveportal": - $output .= ""; - break; - default: - if ($service_enabled) - $output .= ""; - } - if ($service_enabled) - $output .= "\n"; - } - return $output; - } - - -} - -if (!function_exists('service_control_start')) { - - - function service_control_start($name, $extras) { - global $g; - switch($name) { - case 'radvd': - services_radvd_configure(); - break; - case 'captiveportal': - $zone = htmlspecialchars($extras['zone']); - captiveportal_init_webgui_zonename($zone); - break; - case 'ntpd': - case 'openntpd': - system_ntp_configure(); - break; - case 'apinger': - setup_gateways_monitor(); - break; - case 'bsnmpd': - services_snmpd_configure(); - break; - case 'dhcrelay': - services_dhcrelay_configure(); - break; - case 'dhcrelay6': - services_dhcrelay6_configure(); - break; - case 'dnsmasq': - services_dnsmasq_configure(); - break; - case 'dhcpd': - services_dhcpd_configure(); - break; - case 'igmpproxy': - services_igmpproxy_configure(); - break; - case 'miniupnpd': - upnp_action('start'); - break; - case 'ipsec': - vpn_ipsec_force_reload(); - break; - case 'sshd': - send_event("service restart sshd"); - break; - case 'openvpn': - $vpnmode = isset($extras['vpnmode']) ? htmlspecialchars($extras['vpnmode']) : htmlspecialchars($extras['mode']); - 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)) - openvpn_restart_by_vpnid($vpnmode, $id); - } - break; - case 'relayd': - relayd_configure(); - break; - default: - start_service($name); - break; - } - return sprintf(gettext("%s has been started."),htmlspecialchars($name)); - } - -} - -if (!function_exists('service_control_stop')) { - - - function service_control_stop($name, $extras) { - global $g; - switch($name) { - case 'radvd': - killbypid("{$g['varrun_path']}/radvd.pid"); - break; - case 'captiveportal': - $zone = htmlspecialchars($extras['zone']); - killbypid("{$g['varrun_path']}/lighty-{$zone}-CaptivePortal.pid"); - killbypid("{$g['varrun_path']}/lighty-{$zone}-CaptivePortal-SSL.pid"); - break; - case 'ntpd': - killbyname("ntpd"); - break; - case 'openntpd': - killbyname("openntpd"); - break; - case 'apinger': - killbypid("{$g['varrun_path']}/apinger.pid"); - break; - case 'bsnmpd': - killbypid("{$g['varrun_path']}/snmpd.pid"); - break; - case 'choparp': - killbyname("choparp"); - break; - case 'dhcpd': - killbyname("dhcpd"); - break; - case 'dhcrelay': - killbypid("{$g['varrun_path']}/dhcrelay.pid"); - break; - case 'dhcrelay6': - killbypid("{$g['varrun_path']}/dhcrelay6.pid"); - break; - case 'dnsmasq': - killbypid("{$g['varrun_path']}/dnsmasq.pid"); - break; - case 'unbound': - killbypid("{$g['varrun_path']}/unbound.pid"); - break; - case 'igmpproxy': - killbyname("igmpproxy"); - break; - case 'miniupnpd': - upnp_action('stop'); - break; - case 'sshd': - killbyname("sshd"); - break; - case 'ipsec': - exec("/usr/local/sbin/ipsec stop"); - break; - case 'openvpn': - $vpnmode = htmlspecialchars($extras['vpnmode']); - if (($vpnmode == "server") or ($vpnmode == "client")) { - $id = htmlspecialchars($extras['id']); - $pidfile = "{$g['varrun_path']}/openvpn_{$vpnmode}{$id}.pid"; - killbypid($pidfile); - } - break; - case 'relayd': - mwexec('pkill relayd'); - break; - default: - stop_service($name); - break; - } - return sprintf(gettext("%s has been stopped."), htmlspecialchars($name)); - } - - -} - -if (!function_exists('service_control_restart')) { - - - function service_control_restart($name, $extras) { - global $g; - switch($name) { - case 'radvd': - services_radvd_configure(); - break; - case 'captiveportal': - $zone = htmlspecialchars($extras['zone']); - killbypid("{$g['varrun_path']}/lighty-{$zone}-CaptivePortal.pid"); - killbypid("{$g['varrun_path']}/lighty-{$zone}-CaptivePortal-SSL.pid"); - captiveportal_init_webgui_zonename($zone); - break; - case 'ntpd': - case 'openntpd': - system_ntp_configure(); - break; - case 'apinger': - killbypid("{$g['varrun_path']}/apinger.pid"); - setup_gateways_monitor(); - break; - case 'bsnmpd': - services_snmpd_configure(); - break; - case 'dhcrelay': - services_dhcrelay_configure(); - break; - case 'dhcrelay6': - services_dhcrelay6_configure(); - break; - case 'dnsmasq': - services_dnsmasq_configure(); - break; - case 'unbound': - services_unbound_configure(); - break; - case 'dhcpd': - services_dhcpd_configure(); - break; - case 'igmpproxy': - services_igmpproxy_configure(); - break; - case 'miniupnpd': - upnp_action('restart'); - break; - case 'ipsec': - vpn_ipsec_force_reload(); - break; - case 'sshd': - send_event("service restart sshd"); - break; - case 'openvpn': - $vpnmode = htmlspecialchars($extras['vpnmode']); - if ($vpnmode == "server" || $vpnmode == "client") { - $id = htmlspecialchars($extras['id']); - $configfile = "{$g['varetc_path']}/openvpn/{$vpnmode}{$id}.conf"; - if (file_exists($configfile)) - openvpn_restart_by_vpnid($vpnmode, $id); - } - break; - case 'relayd': - relayd_configure(true); - break; - default: - restart_service($name); - break; - } - return sprintf(gettext("%s has been restarted."),htmlspecialchars($name)); - } -} - -?> diff --git a/usr/local/www/includes/shaper.inc b/usr/local/www/includes/shaper.inc deleted file mode 100644 index 8e811c89c..000000000 --- a/usr/local/www/includes/shaper.inc +++ /dev/null @@ -1,4525 +0,0 @@ -GetInterface(); - $altq =& $altq_list_queues[$int]; - if ($altq) { - $bw_3 = $altq->GetBandwidth(); - $bw_3 = $bw_3 * get_bandwidthtype_scale($altq->GetBwscale()); - return floatval($bw_3); - } else - return 0; -} - -/* - * This is duplicated here since we cannot include guiconfig.inc. - * Including it makes all stuff break. - */ -function shaper_do_input_validation($postdata, $reqdfields, $reqdfieldsn, $input_errors) -{ - - /* check for bad control characters */ - foreach ($postdata as $pn => $pd) { - if (is_string($pd) && preg_match("/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f]/", $pd)) { - $input_errors[] = sprintf(gettext("The field '%s' contains invalid characters."), $pn); - } - } - - for ($i = 0; $i < count($reqdfields); $i++) { - if ($postdata[$reqdfields[$i]] == "") { - $input_errors[] = sprintf(gettext("The field '%s' is required."), $reqdfieldsn[$i]); - } - } -} - -function cleanup_queue_from_rules($queue) -{ - global $config; - - foreach ($config['filter']['rule'] as $rule) { - if ($rule['defaultqueue'] == $queue) - unset($rule['defaultqueue']); - if ($rule['ackqueue'] == $queue) - unset($rule['ackqueue']); - } -} - -function cleanup_dnqueue_from_rules($queue) -{ - global $config; - - foreach ($config['filter']['rule'] as $rule) { - if ($rule['dnpipe'] == $queue) - unset($rule['dnpipe']); - if ($rule['pdnpipe'] == $queue) - unset($rule['pdnpipe']); - } -} - -class altq_root_queue { - var $interface; - var $tbrconfig ; - var $bandwidth; - var $bandwidthtype; /* b, Kb, Mb */ - var $scheduler; - var $qlimit; - var $queues = array(); - var $qenabled = false; - var $link; - var $available_bw; /* in b/s */ - - /* Accesor functions */ - function GetAvailableBandwidth() { - return $this->available_bw; - } - function SetAvailableBandwidth($bw) { - $this->available_bw = $bw; - } - function GetDefaultQueuePresent() { - if (!empty($this->queues)) { - foreach ($this->queues as $q) { - if ($q->GetDefault()) - return true; - } - } - - return false; - } - function SetLink($link) { - $this->link = $link; - } - function GetLink() { - return $this->link; - } - function GetEnabled() { - return $this->qenabled; - } - function SetEnabled($value) { - $this->qenabled = $value; - } - function CanHaveChildren() { - if ($this->GetScheduler() == "CODELQ") - return false; - else - return true; - } - function CanBeDeleted() { - return false; - } - function GetQname() { - return $this->interface; - } - function SetQname($name) { - $this->interface = trim($name); - } - function GetInterface() { - return $this->interface; - } - function SetInterface($name) { - $this->interface = trim($name); - } - function GetTbrConfig() { - return $this->tbrconfig; - } - function SetTbrConfig($tbrconfig) { - $this->tbrconfig = $tbrconfig; - } - function GetBandwidth() { - return $this->bandwidth; - } - function SetBandwidth($bw) { - $this->bandwidth = $bw; - } - function GetBwscale() { - return $this->bandwidthtype; - } - function SetBwscale($bwscale) { - $this->bandwidthtype = $bwscale; - } - function GetScheduler() { - return $this->scheduler; - } - function SetScheduler($scheduler) { - $this->scheduler = trim($scheduler); - } - function GetQlimit() { - return $this->qlimit; - } - function SetQlimit($limit) { - $this->qlimit = $limit; - } - - function validate_input($data, &$input_errors) { - - $reqdfields[] = "bandwidth"; - $reqdfieldsn[] = gettext("Bandwidth"); - $reqdfields[] = "bandwidthtype"; - $reqdfieldsn[] = gettext("Bandwidthtype"); - - shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - - if ($data['bandwidth'] && (!is_numeric($data['bandwidth']))) - $input_errors[] = gettext("Bandwidth must be an integer."); - if ($data['bandwidth'] < 0) - $input_errors[] = gettext("Bandwidth cannot be negative."); - if ($data['qlimit'] && (!is_numeric($data['qlimit']))) - $input_errors[] = gettext("Qlimit must be an integer."); - if ($data['qlimit'] < 0) - $input_errors[] = gettext("Qlimit must be positive."); - if ($data['tbrconfig'] && (!is_numeric($data['tbrconfig']))) - $input_errors[] = gettext("Tbrsize must be an integer."); - if ($data['tbrconfig'] < 0) - $input_errors[] = gettext("Tbrsize must be positive."); - } - - /* Implement this to shorten some code on the frontend page */ - function ReadConfig(&$conf) { - if (isset($conf['tbrconfig'])) - $this->SetTbrConfig($conf['tbrconfig']); - else - $this->SetTbrConfig($conf['tbrconfig']); - $this->SetBandwidth($conf['bandwidth']); - if ($conf['bandwidthtype'] <> "") - $this->SetBwscale($conf['bandwidthtype']); - if (isset($conf['scheduler'])) { - if ($this->GetScheduler() != $conf['scheduler']) { - foreach ($this->queues as $q) { - clean_child_queues($conf['scheduler'], $this->GetLink()); - $q->clean_queue($conf['scheduler']); - } - } - $this->SetScheduler($conf['scheduler']); - } - if (isset($conf['qlimit']) && $conf['qlimit'] <> "") - $this->SetQlimit($conf['qlimit']); - else - $this->SetQlimit(""); - if (isset($conf['name'])) - $this->SetQname($conf['name']); - if (!empty($conf['enabled'])) - $this->SetEnabled($conf['enabled']); - else - $this->SetEnabled(""); - } - - function copy_queue($interface, &$cflink) { - $cflink['interface'] = $interface; - $cflink['name'] = $interface; - $cflink['scheduler'] = $this->GetScheduler(); - $cflink['bandwidth'] = $this->GetBandwidth(); - $cflink['bandwidthtype'] = $this->GetBwscale(); - $cflink['qlimit'] = $this->GetQlimit(); - $cflink['tbrconfig'] = $this->GetTbrConfig(); - $cflink['enabled'] = $this->GetEnabled(); - if (is_array($this->queues)) { - $cflink['queue'] = array(); - foreach ($this->queues as $q) { - $cflink['queue'][$q->GetQname()] = array(); - $q->copy_queue($interface, $cflink['queue'][$q->GetQname()]); - } - } - } - - function &get_queue_list(&$q = null) { - $qlist = array(); - - //$qlist[$this->GetQname()] = & $this; - if (is_array($this->queues)) { - foreach ($this->queues as $queue) - $queue->get_queue_list($qlist); - } - return $qlist; - } - - function &add_queue($interface, &$queue, &$path, &$input_errors) { - - if (!is_array($this->queues)) - $this->queues = array(); - - switch ($this->GetScheduler()) { - case "PRIQ": - $q =& new priq_queue(); - break; - case "HFSC": - $q =& new hfsc_queue(); - break; - case "CBQ": - $q =& new cbq_queue(); - break; - case "FAIRQ": - $q =& new fairq_queue(); - break; - default: - /* XXX: but should not happen anyway */ - return; - break; - } - $q->SetLink($path); - $q->SetInterface($this->GetInterface()); - $q->SetEnabled("on"); - $q->SetParent($this); - $q->ReadConfig($queue); - $q->validate_input($queue, $input_errors); - if (count($input_errors)) { - log_error("SHAPER: could not create queue " . $q->GetQname() . " on interface {$interface} because: " . print_r($input_errors, true)); - return $q; - } - - if (isset($queue['bandwidth'])) { - switch ($queue['bandwidthtype']) { - case "%": - $myBw = $this->GetAvailableBandwidth() * $queue['bandwidth'] / 100; - break; - default: - $myBw = $queue['bandwidth'] * get_bandwidthtype_scale($queue['bandwdithtype']); - break; - } - } - $q->SetAvailableBandwidth($myBw); - $this->SetAvailableBandwidth($this->GetAvailableBandwidth() - $myBw); - $this->queues[$q->GetQname()] = &$q; - ref_on_altq_queue_list($this->GetQname(), $q->GetQname()); - if (is_array($queue['queue'])) { - foreach ($queue['queue'] as $key1 => $que) { - array_push($path, $key1); - $q->add_queue($q->GetInterface(), $que, $path, $input_errors); - array_pop($path); - } - } - - return $q; - } - - /* interface here might be optional */ - function &find_queue($interface, $qname) { - if ($qname == $this->GetQname()) { - return $this; - } - foreach ($this->queues as $q) { - $result =& $q->find_queue("", $qname); - if ($result) - return $result; - } - } - - function &find_parentqueue($interface, $qname) { - if ($qname == $interface) { - $result = NULL; - } else if ($this->queues[$qname]) { - $result = $this; - } else if ($this->GetScheduler() <> "PRIQ") { - foreach ($this->queues as $q) { - $result = $q->find_parentqueue("", $qname); - if ($result) - return $result; - } - } - } - - function build_tree() { - global $shaperIFlist; - - $tree = "
  • GetInterface()."&queue=". $this->GetInterface()."&action=show"; - $tree .= "\">" . $shaperIFlist[$this->GetInterface()] . ""; - if (is_array($this->queues)) { - $tree .= "
      "; - foreach ($this->queues as $q) { - $tree .= $q->build_tree(); - } - $tree .= "
    "; - } - $tree .= "
  • "; - return $tree; - } - - function delete_queue() { - foreach ($this->queues as $q) { - $this->SetAvailableBandwidth($this->GetAvailableBandwidth() + $q->GetAvailableBandwidth()); - $q->delete_queue(); - } - unset_object_by_reference($this->GetLink()); - } - - function delete_all() { - if (count($this->queues)) { - foreach ($this->queues as $q) { - $q->delete_all(); - unset_object_by_reference($q->GetLink()); - unset($q); - } - unset($this->queues); - } - } - - /* - * First it spits: - * altq on $interface .............. - * then it goes like - * foreach ($queues as $qkey => $queue) - * this->queues[$qkey]->build_rule(); - */ - function build_rules(&$default = false) { - if (count($this->queues) > 0 && $this->GetEnabled() == "on") { - $default = false; - $rules = " altq on " . get_real_interface($this->GetInterface()); - if ($this->GetScheduler()) - $rules .= " ".strtolower($this->GetScheduler()); - if ($this->GetQlimit() > 0) - $rules .= " qlimit " . $this->GetQlimit() . " "; - if ($this->GetBandwidth()) { - $rules .= " bandwidth ".trim($this->GetBandwidth()); - if ($this->GetBwscale()) - $rules .= $this->GetBwscale(); - } - if ($this->GetTbrConfig()) - $rules .= " tbrsize ".$this->GetTbrConfig(); - if (count($this->queues)) { - $i = count($this->queues); - $rules .= " queue { "; - foreach ($this->queues as $qkey => $qnone) { - if ($i > 1) { - $i--; - $rules .= " {$qkey}, "; - } else - $rules .= " {$qkey} "; - } - $rules .= " } \n"; - foreach ($this->queues as $q) { - $rules .= $q->build_rules($default); - } - } - - if ($default == false) { - $error = "SHAPER: no default queue specified for interface ". $this->GetInterface() . ". The interface queue will be enforced as default."; - file_notice("Shaper", $error, "Error occurred", ""); - unset($error); - return "\n"; - } - $frule .= $rules; - } else if ($this->GetEnabled() == "on" && $this->GetScheduler() == "CODELQ") { - $rules = " altq on " . get_real_interface($this->GetInterface()); - if ($this->GetScheduler()) - $rules .= " ".strtolower($this->GetScheduler()); - if ($this->GetQlimit() > 0) - $rules .= " ( qlimit " . $this->GetQlimit() . " ) "; - if ($this->GetBandwidth()) { - $rules .= " bandwidth ".trim($this->GetBandwidth()); - if ($this->GetBwscale()) - $rules .= $this->GetBwscale(); - } - if ($this->GetTbrConfig()) - $rules .= " tbrsize ".$this->GetTbrConfig(); - - $rules .= " queue"; - } - - $rules .= " \n"; - return $rules; - } - - function build_javascript() { - $javascript = ""; - - return $javascript; - } - - function build_shortform() { - global $g; - - $altq =& $this; - if ($altq) - $scheduler = ": " . $altq->GetScheduler(); - $form = ""; - $form .= "GetInterface() . "&queue=". $this->GetInterface()."&action=show\">". $shaperIFlist[$this->GetInterface()] .": ".$scheduler.""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= "Bandwidth: " . $this->GetBandwidth().$this->GetBwscale(); - $form .= ""; - $form .= ""; - $form .= "GetInterface() . "&queue="; - $form .= $this->GetQname() . "&action=delete\" class=\"btn btn-default btn-xs\""; - - $form .= " title=\"Disable shaper on interface\">"; - $form .= ""; - - return $form; - - } - /* - * For requesting the parameters of the root queues - * to the user like the traffic wizard does. - */ - function build_form() { - $form = "
    "; - $form .= gettext("Enable/Disable"); - $form .= "
    "; - $form .= " GetEnabled() == "on") - $form .= " checked=\"checked\""; - $form .= " /> " . gettext("Enable/disable discipline and its children") . ""; - $form .= ""; - $form .= "
    " . gettext("Name") . ""; - $form .= ""; - $form .= "".$this->GetQname().""; - $form .= ""; - $form .= "" . gettext("Scheduler Type "); - $form .= ""; - $form .= ""; - $form .= ""; - $form .= "
    "; - $form .= gettext("NOTE: Changing this changes all child queues!"); - $form .= gettext(" Beware you can lose information."); - $form .= ""; - $form .= ""; - $form .= "" . gettext("Bandwidth"); - $form .= ""; - $form .= "GetBandwidth() . "\" />"; - $form .= ""; - $form .= ""; - $form .= "Queue Limit"; - $form .= ""; - $form .= "GetQlimit(); - $form .= "\" />"; - $form .= ""; - $form .= "TBR Size"; - $form .= ""; - $form .= "
    GetTbrConfig(); - $form .= "\" />"; - $form .= "
    "; - $form .= gettext("Adjusts the size, in bytes, of the token bucket regulator. " - . "If not specified, heuristics based on the interface " - . "bandwidth are used to determine the size."); - $form .= ""; - $form .= "GetInterface() . "\" />"; - $form .= "GetQname()."\" />"; - - - return $form; - } - - function update_altq_queue_data(&$data) { - $this->ReadConfig($data); - } - - /* - * Should call on each of it queues and subqueues - * the same function much like build_rules(); - */ - function wconfig() { - $cflink = &get_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) - $cflink = array(); - $cflink['interface'] = $this->GetInterface(); - $cflink['name'] = $this->GetQname(); - $cflink['scheduler'] = $this->GetScheduler(); - $cflink['bandwidth'] = $this->GetBandwidth(); - $cflink['bandwidthtype'] = $this->GetBwscale(); - $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) - unset($cflink['qlimit']); - $cflink['tbrconfig'] = trim($this->GetTbrConfig()); - if (empty($cflink['tbrconfig'])) - unset($cflink['tbrconfig']); - $cflink['enabled'] = $this->GetEnabled(); - if (empty($cflink['enabled'])) - unset($cflink['enabled']); - } - -} - -class priq_queue { - var $qname; - var $qinterface; - var $qlimit; - var $qpriority; - var $description; - var $isparent; - var $qbandwidth; - var $qbandwidthtype; - var $qdefault = ""; - var $qrio = ""; - var $qred = ""; - var $qcodel = ""; - var $qecn = ""; - var $qack; - var $qenabled = ""; - var $qparent; - var $link; - var $available_bw; /* in b/s */ - - /* This is here to help with form building and building rules/lists */ - var $subqueues = array(); - - /* Accesor functions */ - function GetAvailableBandwidth() { - return $this->available_bw; - } - function SetAvailableBandwidth($bw) { - $this->available_bw = $bw; - } - function SetLink($link) { - $this->link = $link; - } - function GetLink() { - return $this->link; - } - function &GetParent() { - return $this->qparent; - } - function SetParent(&$parent) { - $this->qparent = &$parent; - } - function GetEnabled() { - return $this->qenabled; - } - function SetEnabled($value) { - $this->qenabled = $value; - } - function CanHaveChildren() { - return false; - } - function CanBeDeleted() { - return true; - } - function GetQname() { - return $this->qname; - } - function SetQname($name) { - $this->qname = trim($name); - } - function GetBandwidth() { - return $this->qbandwidth; - } - function SetBandwidth($bandwidth) { - $this->qbandwidth = $bandwidth; - } - function GetInterface() { - return $this->qinterface; - } - function SetInterface($name) { - $this->qinterface = trim($name); - } - function GetQlimit() { - return $this->qlimit; - } - function SetQlimit($limit) { - $this->qlimit = $limit; - } - function GetQpriority() { - return $this->qpriority; - } - function SetQpriority($priority) { - $this->qpriority = $priority; - } - function GetDescription() { - return $this->description; - } - function SetDescription($str) { - $this->description = trim($str); - } - function GetFirstime() { - return $this->firsttime; - } - function SetFirsttime($number) { - $this->firsttime = $number; - } - function GetBwscale() { - return $this->qbandwidthtype; - } - function SetBwscale($scale) { - $this->qbandwidthtype = $scale; - } - function GetDefaultQueuePresent() { - if ($this->GetDefault()) - return true; - if (!empty($this->subqueues)) { - foreach ($this->subqueues as $q) { - if ($q->GetDefault()) - return true; - } - } - - return false; - } - function GetDefault() { - return $this->qdefault; - } - function SetDefault($value = false) { - $this->qdefault = $value; - } - function GetCodel() { - return $this->codel; - } - function SetCodel($codel = false) { - $this->codel = $codel; - } - function GetRed() { - return $this->qred; - } - function SetRed($red = false) { - $this->qred = $red; - } - function GetRio() { - return $this->qrio; - } - function SetRio($rio = false) { - $this->qrio = $rio; - } - function GetEcn() { - return $this->qecn; - } - function SetEcn($ecn = false) { - $this->qecn = $ecn; - } - function GetAck() { - return $this->qack; - } - function SetAck($ack = false) { - $this->qack = $ack; - } - - function build_javascript() { - $javascript = ""; - - return $javascript; - } - - function &add_queue($interface, &$qname, &$path, &$input_errors) { return; } - - /* - * Currently this will not be called unless we decide to clone a whole - * queue tree on the 'By Queues' view or support drag&drop on the tree/list - */ - function copy_queue($interface, &$cflink) { - - $cflink['name'] = $this->GetQname(); - $cflink['interface'] = $interface; - $cflink['qlimit'] = $this->GetQlimit(); - $cflink['priority'] = $this->GetQpriority(); - $cflink['description'] = $this->GetDescription(); - $cflink['enabled'] = $this->GetEnabled(); - $cflink['default'] = $this->GetDefault(); - $cflink['red'] = $this->GetRed(); - $cflink['codel'] = $this->GetCodel(); - $cflink['rio'] = $this->GetRio(); - $cflink['ecn'] = $this->GetEcn(); - - if (is_array($this->subqueues)) { - $cflinkp['queue'] = array(); - foreach ($this->subqueues as $q) { - $cflink['queue'][$q->GetQname()] = array(); - $q->copy_queue($interface, $cflink['queue'][$q->GetQname()]); - } - } - - } - - function clean_queue($sched) { - clean_child_queues($sched, $this->GetLink()); - if (is_array($this->subqueues)) { - foreach ($this->subqueues as $q) - $q->clean_queue($sched); - } - } - - function &get_queue_list(&$qlist) { - - $qlist[$this->GetQname()] = & $this; - if (is_array($this->subqueues)) { - foreach ($this->subqueues as $queue) - $queue->get_queue_list($qlist); - } - } - - function delete_queue() { - unref_on_altq_queue_list($this->GetQname()); - cleanup_queue_from_rules($this->GetQname()); - unset_object_by_reference($this->GetLink()); - } - - function delete_all() { - if (count($this->subqueues)) { - foreach ($this->subqueues as $q) { - $q->delete_all(); - unset_object_by_reference($q->GetLink()); - unset($q); - } - unset($this->subqueues); - } - } - - function &find_queue($interface, $qname) { - if ($qname == $this->GetQname()) - return $this; - } - - function find_parentqueue($interface, $qname) { return; } - - function validate_input($data, &$input_errors) { - - $reqdfields[] = "name"; - $reqdfieldsn[] = gettext("Name"); - shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - - if ($data['bandwidth'] && (!is_numeric($data['bandwidth']))) - $input_errors[] = "Bandwidth must be an integer."; - if ($data['bandwidth'] < 0) - $input_errors[] = "Bandwidth cannot be negative."; - if ($data['priority'] && (!is_numeric($data['priority']) - || ($data['priority'] < 1) || ($data['priority'] > 15))) { - $input_errors[] = gettext("The priority must be an integer between 1 and 15."); - } - if ($data['qlimit'] && (!is_numeric($data['qlimit']))) - $input_errors[] = gettext("Queue limit must be an integer"); - if ($data['qlimit'] < 0) - $input_errors[] = gettext("Queue limit must be positive"); - if (!empty($data['newname']) && !preg_match("/^[a-zA-Z0-9_-]*$/", $data['newname'])) - $input_errors[] = gettext("Queue names must be alphanumeric and _ or - only."); - if (!empty($data['name']) && !preg_match("/^[a-zA-Z0-9_-]*$/", $data['name'])) - $input_errors[] = gettext("Queue names must be alphanumeric and _ or - only."); - $default = $this->GetDefault(); - if (!empty($data['default']) && altq_get_default_queue($data['interface']) && empty($default)) - $input_errors[] = gettext("Only one default queue per interface is allowed."); - } - - function ReadConfig(&$q) { - if (!empty($q['name']) && !empty($q['newname']) && $q['name'] != $q['newname']) { - $this->SetQname($q['newname']); - } else if (!empty($q['newname'])) { - $this->SetQname($q['newname']); - } else if (isset($q['name'])) - $this->SetQname($q['name']); - if (isset($q['interface'])) - $this->SetInterface($q['interface']); - $this->SetBandwidth($q['bandwidth']); - if ($q['bandwidthtype'] <> "") - $this->SetBwscale($q['bandwidthtype']); - if (!empty($q['qlimit'])) - $this->SetQlimit($q['qlimit']); - else - $this->SetQlimit(""); // Default - if (!empty($q['priority'])) - $this->SetQPriority($q['priority']); - else - $this->SetQpriority(""); - if (!empty($q['description'])) - $this->SetDescription($q['description']); - else - $this->SetDescription(""); - if (!empty($q['red'])) - $this->SetRed($q['red']); - else - $this->SetRed(); - if (!empty($q['codel'])) - $this->SetCodel($q['codel']); - else - $this->SetCodel(); - if (!empty($q['rio'])) - $this->SetRio($q['rio']); - else - $this->SetRio(); - if (!empty($q['ecn'])) - $this->SetEcn($q['ecn']); - else - $this->SetEcn(); - if (!empty($q['default'])) - $this->SetDefault($q['default']); - else - $this->SetDefault(); - if (!empty($q['enabled'])) - $this->SetEnabled($q['enabled']); - else - $this->SetEnabled(""); - - } - - function build_tree() { - $tree = "
  • GetInterface()."&queue=". $this->GetQname()."&action=show"; - $tree .= "\" "; - $tmpvalue = $this->GetDefault(); - if (!empty($tmpvalue)) - $tree .= " class=\"navlnk\""; - $tree .= " >" . $this->GetQname() . ""; - /* - * Not needed here! - * if (is_array($queues) { - * $tree .= "
      "; - * foreach ($q as $queues) - * $tree .= $queues['$q->GetName()']->build_tree(); - * endforeach - * $tree .= "
    "; - * } - */ - - $tree .= "
  • "; - - return $tree; - } - - /* Should return something like: - * queue $qname on $qinterface bandwidth .... - */ - function build_rules(&$default = false) { - $pfq_rule = " queue ". $this->qname; - if ($this->GetInterface()) - $pfq_rule .= " on ".get_real_interface($this->GetInterface()); - $tmpvalue = $this->GetQpriority(); - if (!empty($tmpvalue)) - $pfq_rule .= " priority ".$this->GetQpriority(); - $tmpvalue = $this->GetQlimit(); - if (!empty($tmpvalue)) - $pfq_rule .= " qlimit " . $this->GetQlimit(); - if ($this->GetRed() || $this->GetRio() || $this->GetEcn() || $this->GetDefault() || $this->GetCodel()) { - $pfq_rule .= " priq ( "; - $tmpvalue = $this->GetRed(); - if (!empty($tmpvalue)) { - $comma = 1; - $pfq_rule .= " red "; - } - $tmpvalue = $this->GetRio(); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " rio "; - } - $tmpvalue = $this->GetEcn(); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " ecn "; - } - $tmpvalue = $this->GetCodel(); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " codel "; - } - $tmpvalue = $this->GetDefault(); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $pfq_rule .= " default "; - $default = true; - } - $pfq_rule .= " ) "; - } - - $pfq_rule .= " \n"; - - return $pfq_rule; - } - - /* - * To return the html form to show to user - * for getting the parameters. - * Should do even for first time when the - * object is created and later when we may - * need to update it. - */ - function build_form() { - $form = "
    "; - $form .= gettext("Enable/Disable"); - $form .= "
    "; - $form .= " GetEnabled() == "on") - $form .= " checked=\"checked\""; - $form .= " /> " . gettext("Enable/Disable queue and its children") . ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= gettext("Queue Name") . ""; - $form .= "GetQname()); - $form .= "\" />"; - $form .= "GetQname()); - $form .= "\" />"; - $form .= "
    " . gettext("Enter the name of the queue here. Do not use spaces and limit the size to 15 characters."); - $form .= "
    "; - $form .= ""; - $form .= "" . gettext("Priority") . ""; - $form .= " GetQpriority()); - $form .= "\" />"; - $form .= "
    " . gettext("For hfsc, the range is 0 to 7. The default is 1. Hfsc queues with a higher priority are preferred in the case of overload.") . ""; - $form .= ""; - $form .= ""; - $form .= "" . gettext("Queue limit") . ""; - $form .= " GetQlimit()); - $form .= "\" />"; - $form .= "
    " . gettext("Queue limit in packets."); - $form .= ""; - $form .= ""; - $form .= "" . gettext("Scheduler options") . ""; - $form .= ""; - if (empty($this->subqueues)) { - if ($this->GetDefault()) { - $form .= ""; - } else { - $form .= ""; - } - } - $form .= "GetRed(); - if(!empty($tmpvalue)) - $form .= " checked=\"checked\""; - $form .= " /> " . gettext("Random Early Detection") . "
    "; - $form .= "GetRio(); - if(!empty($tmpvalue)) - $form .= " checked=\"checked\""; - $form .= " /> " . gettext("Random Early Detection In and Out") . "
    "; - $form .= "GetEcn(); - if(!empty($tmpvalue)) - $form .= " checked=\"checked\""; - $form .= " /> " . gettext("Explicit Congestion Notification") . "
    "; - $form .= "GetCodel(); - if(!empty($tmpvalue)) - $form .= " checked=\"checked\""; - $form .= " /> " . gettext("Codel Active Queue") . "
    "; - $form .= "
    " . gettext("Select options for this queue"); - $form .= "
    "; - $form .= "" . gettext("Description") . ""; - $form .= ""; - $form .= "GetDescription() . "\" />"; - $form .= ""; - $form .= "GetInterface()."\" />"; - - return $form; - } - - function build_shortform() { - /* XXX: Hacks in site. Mostly layer violations! */ - global $g, $altq_list_queues; - global $shaperIFlist; - - $altq =& $altq_list_queues[$this->GetInterface()]; - if ($altq) - $scheduler = ": " . $altq->GetScheduler(); - $form = ""; - $form .= "GetInterface() . "&queue=" . $this->GetQname()."&action=show\">". $shaperIFlist[$this->GetInterface()] .$scheduler.""; - $form .= ""; - /* - * XXX: Hack in sight maybe fix with a class that wraps all - * of this layer violations - */ - $form .= ""; - $form .= ""; - $form .= gettext("Bandwidth:") . " " . $this->GetBandwidth().$this->GetBwscale(); - $form .= ""; - $tmpvalue = $this->GetQpriority(); - if (!empty($tmpvalue)) - $form .= "" .gettext("Priority: on") . " "; - $tmpvalue = $this->GetDefault(); - if (!empty($tmpvalue)) - $form .= "" . gettext("Default: on") . " "; - $form .= ""; - $form .= "GetInterface() . "&queue="; - $form .= $this->GetQname() . "&action=delete\" class=\"btn btn-default btn-xs\""; - - $form .= " title=\"" . gettext("Delete queue from interface") . "\" >"; - $form .= ""; - - return $form; - - } - - function update_altq_queue_data(&$q) { - $this->ReadConfig($q); - } - - function wconfig() { - $cflink =& get_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) - $cflink = array(); - $cflink['name'] = $this->GetQname(); - $cflink['interface'] = $this->GetInterface(); - $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) - unset($cflink['qlimit']); - $cflink['priority'] = trim($this->GetQpriority()); - if (empty($cflink['priority'])) - unset($cflink['priority']); - $cflink['description'] = trim($this->GetDescription()); - if (empty($cflink['description'])) - unset($cflink['description']); - $cflink['enabled'] = trim($this->GetEnabled()); - if (empty($cflink['enabled'])) - unset($cflink['enabled']); - $cflink['default'] = trim($this->GetDefault()); - if (empty($cflink['default'])) - unset($cflink['default']); - $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) - unset($cflink['red']); - $cflink['codel'] = trim($this->GetCodel()); - if (empty($cflink['codel'])) - unset($cflink['codel']); - $cflink['rio'] = trim($this->GetRio()); - if (empty($cflink['rio'])) - unset($cflink['rio']); - $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) - unset($cflink['ecn']); - } -} - -class hfsc_queue extends priq_queue { - /* realtime */ - var $realtime; - var $r_m1; - var $r_d; - var $r_m2; - /* linkshare */ - var $linkshare; - var $l_m1; - var $l_d; - var $l_m2; - /* upperlimit */ - var $upperlimit; - var $u_m1; - var $u_d; - var $u_m2; - - /* - * HFSC can have nested queues. - */ - function CanHaveChildren() { - return true; - } - function GetRealtime() { - return $this->realtime; - } - function GetR_m1() { - return $this->r_m1; - } - function GetR_d() { - return $this->r_d; - } - function GetR_m2() { - return $this->r_m2; - } - function SetRealtime() { - $this->realtime = "on"; - } - function DisableRealtime() { - $this->realtime = ""; - } - function SetR_m1($value) { - $this->r_m1 = $value; - } - function SetR_d($value) { - $this->r_d = $value; - } - function SetR_m2($value) { - $this->r_m2 = $value; - } - function GetLinkshare() { - return $this->linkshare; - } - function DisableLinkshare() { - $this->linkshare = ""; - } - function GetL_m1() { - return $this->l_m1; - } - function GetL_d() { - return $this->l_d; - } - function GetL_m2() { - return $this->l_m2; - } - function SetLinkshare() { - $this->linkshare = "on"; - } - function SetL_m1($value) { - $this->l_m1 = $value; - } - function SetL_d($value) { - $this->l_d = $value; - } - function SetL_m2($value) { - $this->l_m2 = $value; - } - function GetUpperlimit() { - return $this->upperlimit; - } - function GetU_m1() { - return $this->u_m1; - } - function GetU_d() { - return $this->u_d; - } - function GetU_m2() { - return $this->u_m2; - } - function SetUpperlimit() { - $this->upperlimit = "on"; - } - function DisableUpperlimit() { - $this->upperlimit = ""; - } - function SetU_m1($value) { - $this->u_m1 = $value; - } - function SetU_d($value) { - $this->u_d = $value; - } - function SetU_m2($value) { - $this->u_m2 = $value; - } - - function &add_queue($interface, &$qname, &$path, &$input_errors) { - - if (!is_array($this->subqueues)) - $this->subqueues = array(); - $q =& new hfsc_queue(); - $q->SetInterface($this->GetInterface()); - $q->SetParent($this); - $q->ReadConfig($qname); - $q->validate_input($qname, $input_errors); - if (count($input_errors)) { - log_error("SHAPER: could not create queue " . $q->GetQname() . " on interface {$interface} because: " . print_r($input_errors, true)); - return $q; - } - - $q->SetEnabled("on"); - $q->SetLink($path); - switch ($q->GetBwscale()) { - case "%": - $myBw = $this->GetAvailableBandwidth() * $qname['bandwidth'] / 100; - break; - default: - $myBw = $qname['bandwidth'] * get_bandwidthtype_scale($q->GetBwscale()); - break; - } - $q->SetAvailableBandwidth($myBw); - $this->SetAvailableBandwidth($this->GetAvailableBandwidth() - $myBw); - - $this->subqueues[$q->GetQname()] =& $q; //new hfsc_queue() - ref_on_altq_queue_list($this->GetQname(), $q->GetQname()); - if (is_array($qname['queue'])) { - foreach ($qname['queue'] as $key1 => $que) { - array_push($path, $key1); - $q->add_queue($q->GetInterface(), $que, $path, $input_errors); - array_pop($path); - } - } - - return $q; - } - - function copy_queue($interface, &$cflink) { - - $cflink['name'] = $this->GetQname(); - $cflink['interface'] = $interface; - $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) - unset($cflink['qlimit']); - $cflink['priority'] = trim($this->GetQpriority()); - if (empty($cflink['priority'])) - unset($cflink['priority']); - $cflink['description'] = trim($this->GetDescription()); - if (empty($cflink['description'])) - unset($cflink['description']); - $cflink['bandwidth'] = $this->GetBandwidth(); - $cflink['bandwidthtype'] = $this->GetBwscale(); - $cflink['enabled'] = trim($this->GetEnabled()); - if (empty($cflink['enabled'])) - unset($cflink['enabled']); - $cflink['default'] = trim($this->GetDefault()); - if (empty($cflink['default'])) - unset($cflink['default']); - $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) - unset($cflink['red']); - $cflink['rio'] = trim($this->GetRio()); - if (empty($cflink['rio'])) - unset($cflink['rio']); - $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) - unset($cflink['ecn']); - if ($this->GetLinkshare() <> "") { - if ($this->GetL_m1() <> "") { - $cflink['linkshare1'] = $this->GetL_m1(); - $cflink['linkshare2'] = $this->GetL_d(); - $cflink['linkshare'] = "on"; - } else { - unset($cflink['linkshare1']); - unset($cflink['linkshare2']); - unset($cflink['linkshare']); - } - if ($this->GetL_m2() <> "") { - $cflink['linkshare3'] = $this->GetL_m2(); - $cflink['linkshare'] = "on"; - } else { - unset($cflink['linkshare3']); - unset($cflink['linkshare']); - } - } - if ($this->GetRealtime() <> "") { - if ($this->GetR_m1() <> "") { - $cflink['realtime1'] = $this->GetR_m1(); - $cflink['realtime2'] = $this->GetR_d(); - $cflink['realtime'] = "on"; - } else { - unset($cflink['realtime1']); - unset($cflink['realtime2']); - unset($cflink['realtime']); - } - if ($this->GetR_m2() <> "") { - $cflink['realtime3'] = $this->GetR_m2(); - $cflink['realtime'] = "on"; - } else { - unset($cflink['realtime3']); - unset($cflink['realtime']); - } - } - if ($this->GetUpperlimit() <> "") { - if ($this->GetU_m1() <> "") { - $cflink['upperlimit1'] = $this->GetU_m1(); - $cflink['upperlimit2'] = $this->GetU_d(); - $cflink['upperlimit'] = "on"; - } else { - unset($cflink['upperlimit']); - unset($cflink['upperlimit1']); - unset($cflink['upperlimit2']); - } - if ($this->GetU_m2() <> "") { - $cflink['upperlimit3'] = $this->GetU_m2(); - $cflink['upperlimit'] = "on"; - } else { - unset($cflink['upperlimit3']); - unset($cflink['upperlimit']); - } - } - - if (is_array($this->subqueues)) { - $cflinkp['queue'] = array(); - foreach ($this->subqueues as $q) { - $cflink['queue'][$q->GetQname()] = array(); - $q->copy_queue($interface, $cflink['queue'][$q->GetQname()]); - } - } - } - - function delete_queue() { - unref_on_altq_queue_list($this->GetQname()); - cleanup_queue_from_rules($this->GetQname()); - $parent =& $this->GetParent(); - foreach ($this->subqueues as $q) { - $this->SetAvailableBandwidth($this->GetAvailableBandwidth() + $q->GetAvailableBandwidth()); - $q->delete_queue(); - } - unset_object_by_reference($this->GetLink()); - } - - /* - * Should search even its children - */ - function &find_queue($interface, $qname) { - if ($qname == $this->GetQname()) - return $this; - - foreach ($this->subqueues as $q) { - $result =& $q->find_queue("", $qname); - if ($result) - return $result; - } - } - - function &find_parentqueue($interface, $qname) { - if ($this->subqueues[$qname]) - return $this; - foreach ($this->subqueues as $q) { - $result = $q->find_parentqueue("", $qname); - if ($result) - return $result; - } - } - - function validate_input($data, &$input_errors) { - parent::validate_input($data, $input_errors); - - $reqdfields[] = "bandwidth"; - $reqdfieldsn[] = gettext("Bandwidth"); - $reqdfields[] = "bandwidthtype"; - $reqdfieldsn[] = gettext("Bandwidthtype"); - - shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - - if (isset($data['linkshare3']) && $data['linkshare3'] <> "") { - if ($data['bandwidth'] && (!is_numeric($data['bandwidth']))) - $input_errors[] = gettext("Bandwidth must be an integer."); - - if ($data['bandwidth'] < 0) - $input_errors[] = gettext("Bandwidth cannot be negative."); - - if ($data['bandwidthtype'] == "%") { - if ($data['bandwidth'] > 100 || $data['bandwidth'] < 0) - $input_errors[] = gettext("Bandwidth in percentage should be between 1 and 100 bounds."); - } - /* - $parent =& $this->GetParent(); - switch ($data['bandwidthtype']) { - case "%": - $myBw = $parent->GetAvailableBandwidth() * floatval($data['bandwidth']) / 100; - default: - $mybw = floatval($data['bandwidth']) * get_bandwidthtype_scale($data['bandwidthtype']); - break; - } - if ($parent->GetAvailableBandwidth() < $myBw) - $input_errors[] = "The sum of children bandwidth exceeds that of the parent."; - */ - } - - if ($data['upperlimit1'] <> "" && $data['upperlimit2'] == "") - $input_errors[] = gettext("upperlimit service curve defined but missing (d) value"); - if ($data['upperlimit2'] <> "" && $data['upperlimit1'] == "") - $input_errors[] = gettext("upperlimit service curve defined but missing initial bandwidth (m1) value"); - if ($data['upperlimit1'] <> "" && !is_valid_shaperbw($data['upperlimit1'])) - $input_errors[] = gettext("upperlimit m1 value needs to be Kb, Mb, Gb, or %"); - if ($data['upperlimit2'] <> "" && !is_numeric($data['upperlimit2'])) - $input_errors[] = gettext("upperlimit d value needs to be numeric"); - if ($data['upperlimit3'] <> "" && !is_valid_shaperbw($data['upperlimit3'])) - $input_errors[] = gettext("upperlimit m2 value needs to be Kb, Mb, Gb, or %"); - - /* - if (isset($data['upperlimit']) && $data['upperlimit3'] <> "" && $data['upperlimit1'] <> "") { - $bw_1 = get_hfsc_bandwidth($this, $data['upperlimit1']); - $bw_2 = get_hfsc_bandwidth($this, $data['upperlimit3']); - if (floatval($bw_1) < floatval($bw_2)) - $input_errors[] = ("upperlimit m1 cannot be smaller than m2"); - - if (get_interface_bandwidth($this) < (0.8 * (floatval($bw_1) + floatval($bw_2)))) - $input_errors[] = ("upperlimit specification exceeds 80% of allowable allocation."); - } - */ - if ($data['linkshare1'] <> "" && $data['linkshare2'] == "") - $input_errors[] = gettext("linkshare service curve defined but missing (d) value"); - if ($data['linkshare2'] <> "" && $data['linkshare1'] == "") - $input_errors[] = gettext("linkshare service curve defined but missing initial bandwidth (m1) value"); - if ($data['linkshare1'] <> "" && !is_valid_shaperbw($data['linkshare1'])) - $input_errors[] = gettext("linkshare m1 value needs to be Kb, Mb, Gb, or %"); - if ($data['linkshare2'] <> "" && !is_numeric($data['linkshare2'])) - $input_errors[] = gettext("linkshare d value needs to be numeric"); - if ($data['linkshare3'] <> "" && !is_valid_shaperbw($data['linkshare3'])) - $input_errors[] = gettext("linkshare m2 value needs to be Kb, Mb, Gb, or %"); - if ($data['realtime1'] <> "" && $data['realtime2'] == "") - $input_errors[] = gettext("realtime service curve defined but missing (d) value"); - if ($data['realtime2'] <> "" && $data['realtime1'] == "") - $input_errors[] = gettext("realtime service curve defined but missing initial bandwidth (m1) value"); - - /* - if (isset($data['linkshare']) && $data['linkshare3'] <> "" && $data['linkshare1'] <> "" && 0) { - $bw_1 = get_hfsc_bandwidth($this, $data['linkshare1']); - $bw_2 = get_hfsc_bandwidth($this, $data['linkshare3']); - if (floatval($bw_1) < floatval($bw_2)) - $input_errors[] = ("linkshare m1 cannot be smaller than m2"); - - if (get_interface_bandwidth($this) < (0.8 * (floatval($bw_1) + floatval($bw_2)))) - $input_errors[] = ("linkshare specification exceeds 80% of allowable allocation."); - } - */ - - if ($data['realtime1'] <> "" && !is_valid_shaperbw($data['realtime1'])) - $input_errors[] = gettext("realtime m1 value needs to be Kb, Mb, Gb, or %"); - if ($data['realtime2'] <> "" && !is_numeric($data['realtime2'])) - $input_errors[] = gettext("realtime d value needs to be numeric"); - if ($data['realtime3'] <> "" && !is_valid_shaperbw($data['realtime3'])) - $input_errors[] = gettext("realtime m2 value needs to be Kb, Mb, Gb, or %"); - - /* - if (isset($data['realtime']) && $data['realtime3'] <> "" && $data['realtime1'] <> "" && 0) { - $bw_1 = get_hfsc_bandwidth($this, $data['realtime1']); - $bw_2 = get_hfsc_bandwidth($this, $data['realtime3']); - if (floatval($bw_1) < floatval($bw_2)) - $input_errors[] = ("realtime m1 cannot be smaller than m2"); - - if (get_interface_bandwidth($this) < (0.8 * (floatval($bw_1) + floatval($bw_2)))) - $input_errors[] = ("realtime specification exceeds 80% of allowable allocation."); - } - */ - } - - function ReadConfig(&$cflink) { - if (!empty($cflink['linkshare'])) { - if (!empty($cflink['linkshare1'])) { - $this->SetL_m1($cflink['linkshare1']); - $this->SetL_d($cflink['linkshare2']); - $this->SetLinkshare(); - } else { - $this->SetL_m1(""); - $this->SetL_d(""); - $this->DisableLinkshare(); - } - if (!empty($cflink['linkshare3'])) { - $this->SetL_m2($cflink['linkshare3']); - $this->SetLinkshare(); - } - } else - $this->DisableLinkshare(); - if (!empty($cflink['realtime'])) { - if (!empty($cflink['realtime1'])) { - $this->SetR_m1($cflink['realtime1']); - $this->SetR_d($cflink['realtime2']); - $this->SetRealtime(); - } else { - $this->SetR_m1(""); - $this->SetR_d(""); - $this->DisableRealtime(); - } - if (!empty($cflink['realtime3'])) { - $this->SetR_m2($cflink['realtime3']); - $this->SetRealtime(); - } - } else - $this->DisableRealtime(); - if (!empty($cflink['upperlimit'])) { - if (!empty($cflink['upperlimit1'])) { - $this->SetU_m1($cflink['upperlimit1']); - $this->SetU_d($cflink['upperlimit2']); - $this->SetUpperlimit(); - } else { - $this->SetU_m1(""); - $this->SetU_d(""); - $this->DisableUpperlimit(); - } - if (!empty($cflink['upperlimit3'])) { - $this->SetU_m2($cflink['upperlimit3']); - $this->SetUpperlimit(); - } - } else - $this->DisableUpperlimit(); - parent::ReadConfig($cflink); - } - - function build_tree() { - $tree = "
  • GetInterface() ."&queue=" . $this->GetQname()."&action=show"; - $tree .= "\" "; - $tmpvalue = $this->GetDefault(); - if (!empty($tmpvalue)) - $tree .= " class=\"navlnk\""; - $tree .= " >" . $this->GetQname() . ""; - if (is_array($this->subqueues)) { - $tree .= "
      "; - foreach ($this->subqueues as $q) { - $tree .= $q->build_tree(); - } - $tree .= "
    "; - } - $tree .= "
  • "; - return $tree; - } - - /* Even this should take children into consideration */ - function build_rules(&$default = false) { - - $pfq_rule = " queue ". $this->qname; - if ($this->GetInterface()) - $pfq_rule .= " on ".get_real_interface($this->GetInterface()); - if ($this->GetBandwidth() && $this->GetBwscale()) - $pfq_rule .= " bandwidth ".trim($this->GetBandwidth()).$this->GetBwscale(); - - $tmpvalue = $this->GetQlimit(); - if (!empty($tmpvalue)) - $pfq_rule .= " qlimit " . $this->GetQlimit(); - if ($this->GetDefault() || $this->GetRed() || $this->GetRio() || $this->GetEcn() || $this->GetCodel() || $this->GetRealtime() <> "" || $this->GetLinkshare() <> "" || $this->GetUpperlimit() <> "") { - $pfq_rule .= " hfsc ( "; - $tmpvalue = $this->GetRed(); - if (!empty($tmpvalue)) { - $comma = 1; - $pfq_rule .= " red "; - } - - $tmpvalue = $this->GetRio(); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " rio "; - } - $tmpvalue = $this->GetEcn(); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " ecn "; - } - $tmpvalue = $this->GetCodel(); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " codel "; - } - $tmpvalue = $this->GetDefault(); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " default "; - $default = true; - } - - if ($this->GetRealtime() <> "") { - if ($comma) - $pfq_rule .= " , "; - if ($this->GetR_m1() <> "" && $this->GetR_d() <> "" && $this->GetR_m2() <> "") - $pfq_rule .= " realtime (".$this->GetR_m1() . ", " . $this->GetR_d().", ". $this->GetR_m2() .") "; - else if ($this->GetR_m2() <> "") - $pfq_rule .= " realtime " . $this->GetR_m2(); - $comma = 1; - } - if ($this->GetLinkshare() <> "") { - if ($comma) - $pfq_rule .= " ,"; - if ($this->GetL_m1() <> "" && $this->GetL_d() <> "" && $this->GetL_m2() <> "") - $pfq_rule .= " linkshare (".$this->GetL_m1(). ", ". $this->GetL_d(). ", ". $this->GetL_m2(). ") "; - else if ($this->GetL_m2() <> "") - $pfq_rule .= " linkshare " . $this->GetL_m2() . " "; - $comma = 1; - } - if ($this->GetUpperlimit() <> "") { - if ($comma) - $pfq_rule .= " ,"; - if ($this->GetU_m1() <> "" && $this->GetU_d() <> "" && $this->GetU_m2() <> "") - $pfq_rule .= " upperlimit (".$this->GetU_m1().", ". $this->GetU_d().", ". $this->GetU_m2(). ") "; - else if ($this->GetU_m2() <> "") - $pfq_rule .= " upperlimit " . $this->GetU_m2() . " "; - } - $pfq_rule .= " ) "; - } - if (count($this->subqueues)) { - $i = count($this->subqueues); - $pfq_rule .= " { "; - foreach ($this->subqueues as $qkey => $qnone) { - if ($i > 1) { - $i--; - $pfq_rule .= " {$qkey}, "; - } else - $pfq_rule .= " {$qkey} "; - } - $pfq_rule .= " } \n"; - foreach ($this->subqueues as $q) - $pfq_rule .= $q->build_rules($default); - } - - $pfq_rule .= " \n"; - - return $pfq_rule; - } - - function build_javascript() { - $javascript = parent::build_javascript(); - $javascript .= ""; - - return $javascript; - } - - function build_form() { - $form = parent::build_form(); - $form .= ""; - $form .= "" . gettext("Bandwidth") . ""; - $form .= " GetBandwidth()); - $form .= "\" />"; - $form .= "
    "; - $form .= "" . gettext("Choose the amount of bandwidth for this queue"); - $form .= ""; - $form .= ""; - $form .= "" . gettext("Service Curve (sc)") . ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= "
     
    m1
    d
    m2
    GetUpperlimit()<> "") - $form .= " checked=\"checked\" "; - $form .= "onchange=\"enable_upperlimit()\" /> " . gettext("Upperlimit:") . "GetU_m1()); - $form .= "\" id=\"upperlimit1\" name=\"upperlimit1\" "; - if ($this->GetUpperlimit() == "") - $form .= " disabled=\"disabled\""; - $form .= " />GetU_d()); - $form .= "\" id=\"upperlimi2\" name=\"upperlimit2\" "; - if ($this->GetUpperlimit() == "") - $form .= " disabled=\"disabled\""; - $form .= " />GetU_m2()); - $form .= "\" id=\"upperlimit3\" name=\"upperlimit3\" "; - if ($this->GetUpperlimit() == "") - $form .= " disabled=\"disabled\""; - $form .= " />" . gettext("The maximum allowed bandwidth for the queue.") . "
    GetRealtime() <> "") - $form .= " checked=\"checked\" "; - $form .= "onchange=\"enable_realtime()\" /> " . gettext("Real time:") . "GetR_m1()); - $form .= "\" id=\"realtime1\" name=\"realtime1\" "; - if ($this->GetRealtime() == "") - $form .= " disabled=\"disabled\""; - $form .= " />GetR_d()); - $form .= "\" id=\"realtime2\" name=\"realtime2\" "; - if ($this->GetRealtime() == "") - $form .= " disabled=\"disabled\""; - $form .= " />GetR_m2()); - $form .= "\" id=\"realtime3\" name=\"realtime3\" "; - if ($this->GetRealtime() == "") - $form .= " disabled=\"disabled\""; - $form .= " />" . gettext("The minimum required bandwidth for the queue.") . "
    GetLinkshare() <> "") - $form .= " checked=\"checked\" "; - $form .= "onchange=\"enable_linkshare()\" /> " . gettext("Link share:") . "GetL_m1()); - $form .= "\" id=\"linkshare1\" name=\"linkshare1\" "; - if ($this->GetLinkshare() == "") - $form .= " disabled=\"disabled\""; - $form .= " />GetL_d()); - $form .= "\" id=\"linkshare2\" name=\"linkshare2\" "; - if ($this->GetLinkshare() == "") - $form .= " disabled=\"disabled\""; - $form .= " />GetL_m2()); - $form .= "\" id=\"linkshare3\" name=\"linkshare3\" "; - if ($this->GetLinkshare() == "") - $form .= " disabled=\"disabled\""; - $form .= " />" . gettext("The bandwidth share of a backlogged queue - this overrides priority.") . "

    "; - $form .= gettext("The format for service curve specifications is (m1, d, m2). m2 controls " - . "the bandwidth assigned to the queue. m1 and d are optional and can be " - . "used to control the initial bandwidth assignment. For the first d milliseconds the queue gets the bandwidth given as m1, afterwards the value " - . "given in m2."); - $form .= ""; - $form .= ""; - - return $form; - } - - function update_altq_queue_data(&$data) { - $this->ReadConfig($data); - } - - function wconfig() { - $cflink =& get_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) - $cflink = array(); - $cflink['name'] = $this->GetQname(); - $cflink['interface'] = $this->GetInterface(); - $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) - unset($cflink['qlimit']); - $cflink['priority'] = $this->GetQpriority(); - if (empty($cflink['priority'])) - unset($cflink['priority']); - $cflink['description'] = $this->GetDescription(); - if (empty($cflink['description'])) - unset($cflink['description']); - $cflink['bandwidth'] = $this->GetBandwidth(); - $cflink['bandwidthtype'] = $this->GetBwscale(); - $cflink['enabled'] = $this->GetEnabled(); - if (empty($cflink['enabled'])) - unset($cflink['enabled']); - $cflink['default'] = $this->GetDefault(); - if (empty($cflink['default'])) - unset($cflink['default']); - $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) - unset($cflink['red']); - $cflink['rio'] = $this->GetRio(); - if (empty($cflink['rio'])) - unset($cflink['rio']); - $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) - unset($cflink['ecn']); - $cflink['codel'] = trim($this->GetCodel()); - if (empty($cflink['codel'])) - unset($cflink['codel']); - if ($this->GetLinkshare() <> "") { - if ($this->GetL_m1() <> "") { - $cflink['linkshare1'] = $this->GetL_m1(); - $cflink['linkshare2'] = $this->GetL_d(); - $cflink['linkshare'] = "on"; - } else { - unset($cflink['linkshare']); - unset($cflink['linkshare1']); - unset($cflink['linkshare2']); - } - if ($this->GetL_m2() <> "") { - $cflink['linkshare3'] = $this->GetL_m2(); - $cflink['linkshare'] = "on"; - } else { - unset($cflink['linkshare']); - unset($cflink['linkshare3']); - } - } else { - unset($cflink['linkshare']); - unset($cflink['linkshare1']); - unset($cflink['linkshare2']); - unset($cflink['linkshare3']); - } - if ($this->GetRealtime() <> "") { - if ($this->GetR_m1() <> "") { - $cflink['realtime1'] = $this->GetR_m1(); - $cflink['realtime2'] = $this->GetR_d(); - $cflink['realtime'] = "on"; - } else { - unset($cflink['realtime']); - unset($cflink['realtime1']); - unset($cflink['realtime2']); - } - if ($this->GetR_m2() <> "") { - $cflink['realtime3'] = $this->GetR_m2(); - $cflink['realtime'] = "on"; - } else { - unset($cflink['realtime']); - unset($cflink['realtime3']); - } - } else { - unset($cflink['realtime']); - unset($cflink['realtime1']); - unset($cflink['realtime2']); - unset($cflink['realtime3']); - } - if ($this->GetUpperlimit() <> "") { - if ($this->GetU_m1() <> "") { - $cflink['upperlimit1'] = $this->GetU_m1(); - $cflink['upperlimit2'] = $this->GetU_d(); - $cflink['upperlimit'] = "on"; - } else { - unset($cflink['upperlimit']); - unset($cflink['upperlimit1']); - unset($cflink['upperlimit2']); - } - if ($this->GetU_m2() <> "") { - $cflink['upperlimit3'] = $this->GetU_m2(); - $cflink['upperlimit'] = "on"; - } else { - unset($cflink['upperlimit']); - unset($cflink['upperlimit3']); - } - } else { - unset($cflink['upperlimit']); - unset($cflink['upperlimit1']); - unset($cflink['upperlimit2']); - unset($cflink['upperlimit3']); - } - } -} - -class cbq_queue extends priq_queue { - var $qborrow = ""; - - function GetBorrow() { - return $this->qborrow; - } - function SetBorrow($borrow) { - $this->qborrow = $borrow; - } - function CanHaveChildren() { - return true; - } - - function &add_queue($interface, &$qname, &$path, &$input_errors) { - - if (!is_array($this->subqueues)) - $this->subqueues = array(); - $q =& new cbq_queue(); - $q->SetInterface($this->GetInterface()); - $q->SetParent($this); - $q->ReadConfig($qname); - $q->validate_input($qname, $input_errors); - if (count($input_errors)) { - log_error("SHAPER: could not create queue " . $q->GetQname() . " on interface {$interface} because: " . print_r($input_errors, true)); - return $q; - } - switch ($q->GetBwscale()) { - case "%": - $myBw = $this->GetAvailableBandwidth() * $qname['bandwidth'] / 100; - break; - default: - $myBw = $qname['bandwidth'] * get_bandwidthtype_scale($q->GetBwscale()); - break; - } - $q->SetAvailableBandwidth($myBw); - $this->SetAvailableBandwidth($this->GetAvailableBandwidth() - $myBw); - - $q->SetEnabled("on"); - $q->SetLink($path); - $this->subqueues[$q->GetQName()] = &$q; - ref_on_altq_queue_list($this->GetQname(), $q->GetQname()); - if (is_array($qname['queue'])) { - foreach ($qname['queue'] as $key1 => $que) { - array_push($path, $key1); - $q->add_queue($q->GetInterface(), $que, $path, $input_errors); - array_pop($path); - } - } - - return $q; - } - - function copy_queue($interface, &$cflink) { - - $cflink['interface'] = $interface; - $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($clink['qlimit'])) - unset($cflink['qlimit']); - $cflink['priority'] = trim($this->GetQpriority()); - if (empty($cflink['priority'])) - unset($cflink['priority']); - $cflink['name'] = $this->GetQname(); - $cflink['description'] = trim($this->GetDescription()); - if (empty($cflink['description'])) - unset($cflink['description']); - $cflink['bandwidth'] = $this->GetBandwidth(); - $cflink['bandwidthtype'] = $this->GetBwscale(); - $cflink['enabled'] = trim($this->GetEnabled()); - if (empty($cflink['enabled'])) - unset($cflink['enabled']); - $cflink['default'] = trim($this->GetDefault()); - if (empty($cflink['default'])) - unset($cflink['default']); - $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) - unset($cflink['red']); - $cflink['rio'] = trim($this->GetRio()); - if (empty($cflink['rio'])) - unset($cflink['rio']); - $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) - unset($cflink['ecn']); - $cflink['borrow'] = trim($this->GetBorrow()); - if (empty($cflink['borrow'])) - unset($cflink['borrow']); - if (is_array($this->queues)) { - $cflinkp['queue'] = array(); - foreach ($this->subqueues as $q) { - $cflink['queue'][$q->GetQname()] = array(); - $q->copy_queue($interface, $cflink['queue'][$q->GetQname()]); - } - } - } - - /* - * Should search even its children - */ - function &find_queue($interface, $qname) { - if ($qname == $this->GetQname()) - return $this; - foreach ($this->subqueues as $q) { - $result =& $q->find_queue("", $qname); - if ($result) - return $result; - } - } - - function &find_parentqueue($interface, $qname) { - if ($this->subqueues[$qname]) - return $this; - foreach ($this->subqueues as $q) { - $result = $q->find_parentqueue("", $qname); - if ($result) - return $result; - } - } - - function delete_queue() { - unref_on_altq_queue_list($this->GetQname()); - cleanup_queue_from_rules($this->GetQname()); - foreach ($this->subqueues as $q) { - $this->SetAvailableBandwidth($this->GetAvailableBandwidth() + $q->GetAvailableBandwidth()); - $q->delete_queue(); - } - unset_object_by_reference($this->GetLink()); - } - - function validate_input($data, &$input_errors) { - parent::validate_input($data, $input_errors); - - if ($data['priority'] > 7) - $input_errors[] = gettext("Priority must be an integer between 1 and 7."); - $reqdfields[] = "bandwidth"; - $reqdfieldsn[] = gettext("Bandwidth"); - $reqdfields[] = "bandwidthtype"; - $reqdfieldsn[] = gettext("Bandwidthtype"); - - shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - - if ($data['bandwidth'] && !is_numeric($data['bandwidth'])) - $input_errors[] = gettext("Bandwidth must be an integer."); - - - if ($data['bandwidth'] < 0) - $input_errors[] = gettext("Bandwidth cannot be negative."); - - if ($data['bandwidthtype'] == "%") { - if ($data['bandwidth'] > 100 || $data['bandwidth'] < 0) - $input_errors[] = gettext("Bandwidth in percentage should be between 1 and 100 bounds."); - } - -/* - $parent =& $this->GetParent(); - switch ($data['bandwidthtype']) { - case "%": - $myBw = $parent->GetAvailableBandwidth() * floatval($data['bandwidth']) / 100; - break; - default: - $mybw = floatval($data['bandwidth']) * get_bandwidthtype_scale($data['bandwidthtype']); - break; - } - if ($parent->GetAvailableBandwidth() < floatval($myBw)) - $input_errors[] = "The sum of the children bandwidth exceeds that of the parent."; - */ - } - - function ReadConfig(&$q) { - parent::ReadConfig($q); - if (!empty($q['borrow'])) - $this->SetBorrow("on"); - else - $this->SetBorrow(""); - } - - function build_javascript() { - return parent::build_javascript(); - } - - function build_tree() { - $tree = "
  • GetInterface()."&queue=" . $this->GetQname()."&action=show"; - $tree .= "\" "; - $tmpvalue = trim($this->GetDefault()); - if (!empty($tmpvalue)) - $tree .= " class=\"navlnk\""; - $tree .= " >" . $this->GetQname() . ""; - if (is_array($this->subqueues)) { - $tree .= "
      "; - foreach ($this->subqueues as $q) { - $tree .= $q->build_tree(); - } - $tree .= "
    "; - } - $tree .= "
  • "; - return $tree; - } - - /* Even this should take children into consideration */ - function build_rules(&$default = false) { - $pfq_rule = "queue ". $this->qname; - if ($this->GetInterface()) - $pfq_rule .= " on ".get_real_interface($this->GetInterface()); - if ($this->GetBandwidth() && $this->GetBwscale()) - $pfq_rule .= " bandwidth ".trim($this->GetBandwidth()).$this->GetBwscale(); - $tmpvalue = $this->GetQpriority(); - if (!empty($tmpvalue)) - $pfq_rule .= " priority " . $this->GetQpriority(); - $tmpvalue = trim($this->GetQlimit()); - if (!empty($tmpvalue)) - $pfq_rule .= " qlimit " . $this->GetQlimit(); - if ($this->GetDefault() || $this->GetRed() || $this->GetRio() || $this->GetEcn() || $this->GetBorrow() || $this->GetCodel()) { - $pfq_rule .= " cbq ( "; - $tmpvalue = trim($this->GetRed()); - if (!empty($tmpvalue)) { - $comma = 1; - $pfq_rule .= " red "; - } - $tmpvalue = trim($this->GetCodel()); - if (!empty($tmpvalue)) { - $comma = 1; - $pfq_rule .= " codel "; - } - $tmpvalue = trim($this->GetRio()); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " rio "; - } - $tmpvalue = trim($this->GetEcn()); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " ecn "; - } - $tmpvalue = trim($this->GetDefault()); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " default "; - $default = true; - } - $tmpvalue = trim($this->GetBorrow()); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= ", "; - $pfq_rule .= " borrow "; - } - $pfq_rule .= " ) "; - } - if (count($this->subqueues)) { - $i = count($this->subqueues); - $pfq_rule .= " { "; - foreach ($this->subqueues as $qkey => $qnone) { - if ($i > 1) { - $i--; - $pfq_rule .= " {$qkey}, "; - } else - $pfq_rule .= " {$qkey} "; - } - $pfq_rule .= " } \n"; - foreach ($this->subqueues as $q) - $pfq_rule .= $q->build_rules($default); - } - - $pfq_rule .= " \n"; - return $pfq_rule; - } - - function build_form() { - $form = parent::build_form(); - $form .= ""; - $form .= "" . gettext("Bandwidth") . ""; - $form .= " GetBandwidth() > 0) - $form .= htmlspecialchars($this->GetBandwidth()); - $form .= "\" />"; - $form .= "
    "; - $form .= "" . gettext("Choose the amount of bandwidth for this queue"); - $form .= ""; - $form .= "" . gettext("Scheduler specific options") . ""; - $form .= "GetBorrow() == "on") - $form .= " checked=\"checked\" "; - $form .= " /> " . gettext("Borrow from other queues when available") . "
    "; - - return $form; - } - - function update_altq_queue_data(&$data) { - $this->ReadConfig($data); - } - - function wconfig() { - $cflink =& get_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) - $cflink = array(); - $cflink['interface'] = $this->GetInterface(); - $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) - unset($cflink['qlimit']); - $cflink['priority'] = $this->GetQpriority(); - if (empty($cflink['priority'])) - unset($cflink['priority']); - $cflink['name'] = $this->GetQname(); - $cflink['description'] = $this->GetDescription(); - if (empty($cflink['description'])) - unset($cflink['description']); - $cflink['bandwidth'] = $this->GetBandwidth(); - $cflink['bandwidthtype'] = $this->GetBwscale(); - $cflink['enabled'] = trim($this->GetEnabled()); - if (empty($cflink['enabled'])) - unset($cflink['enabled']); - $cflink['default'] = trim($this->GetDefault()); - if (empty($cflink['default'])) - unset($cflink['default']); - $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) - unset($cflink['red']); - $cflink['rio'] = trim($this->GetRio()); - if (empty($cflink['rio'])) - unset($cflink['rio']); - $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) - unset($cflink['ecn']); - $cflink['codel'] = trim($this->GetCodel()); - if (empty($cflink['codel'])) - unset($cflink['codel']); - $cflink['borrow'] = trim($this->GetBorrow()); - if (empty($cflink['borrow'])) - unset($cflink['borrow']); - } -} - -class fairq_queue extends priq_queue { - var $hogs; - var $buckets; - - function GetBuckets() { - return $this->buckets; - } - function SetBuckets($buckets) { - $this->buckets = $buckets; - } - function GetHogs() { - return $this->hogs; - } - function SetHogs($hogs) { - $this->hogs = $hogs; - } - function CanHaveChildren() { - return false; - } - - - function copy_queue($interface, &$cflink) { - $cflink['interface'] = $interface; - $cflink['qlimit'] = $this->GetQlimit(); - $cflink['priority'] = $this->GetQpriority(); - $cflink['name'] = $this->GetQname(); - $cflink['description'] = $this->GetDescription(); - $cflink['bandwidth'] = $this->GetBandwidth(); - $cflink['bandwidthtype'] = $this->GetBwscale(); - $cflink['enabled'] = $this->GetEnabled(); - $cflink['default'] = $this->GetDefault(); - $cflink['red'] = $this->GetRed(); - $cflink['rio'] = $this->GetRio(); - $cflink['ecn'] = $this->GetEcn(); - $cflink['buckets'] = $this->GetBuckets(); - $cflink['hogs'] = $this->GetHogs(); - } - - /* - * Should search even its children - */ - function &find_queue($interface, $qname) { - if ($qname == $this->GetQname()) - return $this; - } - - function find_parentqueue($interface, $qname) { return; } - - function delete_queue() { - unref_on_altq_queue_list($this->GetQname()); - cleanup_queue_from_rules($this->GetQname()); - unset_object_by_reference($this->GetLink()); - } - - function validate_input($data, &$input_errors) { - parent::validate_input($data, $input_errors); - - if ($data['priority'] > 255) - $input_errors[] = gettext("Priority must be an integer between 1 and 255."); - $reqdfields[] = "bandwidth"; - $reqdfieldsn[] = gettext("Bandwidth"); - $reqdfields[] = "bandwidthtype"; - $reqdfieldsn[] = gettext("Bandwidthtype"); - - shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - - if ($data['bandwidth'] && !is_numeric($data['bandwidth'])) - $input_errors[] = gettext("Bandwidth must be an integer."); - - - if ($data['bandwidth'] < 0) - $input_errors[] = gettext("Bandwidth cannot be negative."); - - - if ($data['bandwidthtype'] == "%") { - if ($data['bandwidth'] > 100 || $data['bandwidth'] < 0) - $input_errors[] = gettext("Bandwidth in percentage should be between 1 and 100 bounds."); - } - -/* - $parent =& $this->GetParent(); - switch ($data['bandwidthtype']) { - case "%": - $myBw = $parent->GetAvailableBandwidth() * floatval($data['bandwidth']) / 100; - default: - $mybw = floatval($data['bandwidth']) * get_bandwidthtype_scale($data['bandwidthtype']); - break; - } - if ($parent->GetAvailableBandwidth() < floatval($myBw)) - $input_errors[] = "The sum of children bandwidth exceeds that of the parent."; -*/ - } - - function ReadConfig(&$q) { - parent::ReadConfig($q); - if (!empty($q['buckets'])) - $this->SetBuckets($q['buckets']); - else - $this->SetBuckets(""); - if (!empty($q['hogs']) && is_valid_shaperbw($q['hogs'])) - $this->SetHogs($q['hogs']); - else - $this->SetHogs(""); - } - - function build_javascript() { - return parent::build_javascript(); - } - - function build_tree() { - $tree = "
  • GetInterface()."&queue=" . $this->GetQname()."&action=show"; - $tree .= "\" "; - $tmpvalue = trim($this->GetDefault()); - if (!empty($tmpvalue)) - $tree .= " class=\"navlnk\""; - $tree .= " >" . $this->GetQname() . ""; - $tree .= "
  • "; - return $tree; - } - - /* Even this should take children into consideration */ - function build_rules(&$default = false) { - $pfq_rule = "queue ". $this->qname; - if ($this->GetInterface()) - $pfq_rule .= " on ".get_real_interface($this->GetInterface()); - if ($this->GetBandwidth() && $this->GetBwscale()) - $pfq_rule .= " bandwidth ".trim($this->GetBandwidth()).$this->GetBwscale(); - $tmpvalue = trim($this->GetQpriority()); - if (!empty($tmpvalue)) - $pfq_rule .= " priority " . $this->GetQpriority(); - $tmpvalue = trim($this->GetQlimit()); - if (!empty($tmpvalue)) - $pfq_rule .= " qlimit " . $this->GetQlimit(); - if ($this->GetDefault() || $this->GetRed() || $this->GetRio() - || $this->GetEcn() || $this->GetBuckets() || $this->GetHogs() || $this->GetCodel()) { - $pfq_rule .= " fairq ( "; - $tmpvalue = trim($this->GetRed()); - if (!empty($tmpvalue)) { - $comma = 1; - $pfq_rule .= " red "; - } - $tmpvalue = trim($this->GetCodel()); - if (!empty($tmpvalue)) { - $comma = 1; - $pfq_rule .= " codel "; - } - $tmpvalue = trim($this->GetRio()); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " rio "; - } - $tmpvalue = trim($this->GetEcn()); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " ecn "; - } - $tmpvalue = trim($this->GetDefault()); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= " ,"; - $comma = 1; - $pfq_rule .= " default "; - $default = true; - } - $tmpvalue = trim($this->GetBuckets()); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= ", "; - $pfq_rule .= " buckets " . $this->GetBuckets() . " "; - } - $tmpvalue = trim($this->GetHogs()); - if (!empty($tmpvalue)) { - if ($comma) - $pfq_rule .= ", "; - $pfq_rule .= " hogs " . $this->GetHogs() . " "; - } - $pfq_rule .= " ) "; - } - - $pfq_rule .= " \n"; - return $pfq_rule; - } - - function build_form() { - $form = parent::build_form(); - $form .= ""; - $form .= "" . gettext("Bandwidth") . ""; - $form .= " GetBandwidth() > 0) - $form .= htmlspecialchars($this->GetBandwidth()); - $form .= "\" />"; - $form .= "
    "; - $form .= "" . gettext("Choose the amount of bandwidth for this queue"); - $form .= ""; - $form .= "" . gettext("Scheduler specific options") . ""; - $form .= ""; - $form .= ""; - $form .= "
    "; - $form .= "GetBuckets()); - if(!empty($tmpvalue)) - $form .= $this->GetBuckets(); - $form .= "\" /> " . gettext("Number of buckets available.") . "
    GetHogs()); - if(!empty($tmpvalue)) - $form .= $this->GetHogs(); - $form .= "\" /> " . gettext("Bandwidth limit for hosts to not saturate link.") . "
    "; - return $form; - } - - function update_altq_queue_data(&$data) { - $this->ReadConfig($data); - } - - function wconfig() { - $cflink =& get_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) - $cflink = array(); - $cflink['interface'] = $this->GetInterface(); - $cflink['qlimit'] = trim($this->GetQlimit()); - if (empty($cflink['qlimit'])) - unset($cflink['qlimit']); - $cflink['priority'] = trim($this->GetQpriority()); - if (empty($cflink['priority'])) - unset($cflink['priority']); - $cflink['name'] = $this->GetQname(); - $cflink['description'] = trim($this->GetDescription()); - if (empty($cflink['description'])) - unset($cflink['description']); - $cflink['bandwidth'] = $this->GetBandwidth(); - $cflink['bandwidthtype'] = $this->GetBwscale(); - $cflink['enabled'] = $this->GetEnabled(); - if (empty($cflink['enabled'])) - unset($cflink['enabled']); - $cflink['default'] = trim($this->GetDefault()); - if (empty($cflink['default'])) - unset($cflink['default']); - $cflink['red'] = trim($this->GetRed()); - if (empty($cflink['red'])) - unset($cflink['red']); - $cflink['rio'] = trim($this->GetRio()); - if (empty($cflink['rio'])) - unset($cflink['rio']); - $cflink['ecn'] = trim($this->GetEcn()); - if (empty($cflink['ecn'])) - unset($cflink['ecn']); - $cflink['codel'] = trim($this->GetCodel()); - if (empty($cflink['codel'])) - unset($cflink['codel']); - $cflink['buckets'] = trim($this->GetBuckets()); - if (empty($cflink['buckets'])) - unset($cflink['buckets']); - $cflink['hogs'] = trim($this->GetHogs()); - if (empty($cflink['hogs'])) - unset($cflink['hogs']); - } -} - - -/* - * dummynet(4) wrappers. - */ - - -/* - * List of respective objects! - */ -$dummynet_pipe_list = array(); - -class dummynet_class { - var $qname; - var $qnumber; /* dummynet(4) uses numbers instead of names; maybe integrate with pf the same as altq does?! */ - var $qlimit; - var $description; - var $qenabled; - var $link; - var $qparent; /* link to upper class so we do things easily on WF2Q+ rule creation */ - var $plr; - - var $buckets; - /* mask parameters */ - var $mask; - var $noerror; - - /* Accessor functions */ - function SetLink($link) { - $this->link = $link; - } - function GetLink() { - return $this->link; - } - function GetMask() { - if (!isset($this->mask["type"])) - $this->mask["type"] = "none"; - return $this->mask; - } - function SetMask($mask) { - $this->mask = $mask; - } - function &GetParent() { - return $this->qparent; - } - function SetParent(&$parent) { - $this->qparent = &$parent; - } - function GetEnabled() { - return $this->qenabled; - } - function SetEnabled($value) { - $this->qenabled = $value; - } - function CanHaveChildren() { - return false; - } - function CanBeDeleted() { - return true; - } - function GetQname() { - return $this->qname; - } - function SetQname($name) { - $this->qname = trim($name); - } - function GetQlimit() { - return $this->qlimit; - } - function SetQlimit($limit) { - $this->qlimit = $limit; - } - function GetDescription() { - return $this->description; - } - function SetDescription($str) { - $this->description = trim($str); - } - function GetFirstime() { - return $this->firsttime; - } - function SetFirsttime($number) { - $this->firsttime = $number; - } - function GetBuckets() { - return $this->buckets; - } - function SetBuckets($buckets) { - $this->buckets = $buckets; - } - function SetNumber($number) { - $this->qnumber = $number; - } - function GetNumber() { - return $this->qnumber; - } - function GetPlr() { - return $this->plr; - } - function SetPlr($plr) { - $this->plr = $plr; - } - - function build_javascript() { - $javascript .= "\n"; - return $javascript; - } - - function validate_input($data, &$input_errors) { - $reqdfields[] = "bandwidth"; - $reqdfieldsn[] = gettext("Bandwidth"); - $reqdfields[] = "burst"; - $reqdfieldsn[] = gettext("Burst"); - $reqdfields[] = "bandwidthtype"; - $reqdfieldsn[] = gettext("Bandwidthtype"); - $reqdfields[] = "newname"; - $reqdfieldsn[] = gettext("Name"); - - shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - - if ($data['plr'] && (!is_numeric($data['plr']) || - ($data['plr'] < 0) || ($data['plr'] > 1))) - $input_errors[] = gettext("Plr must be a value between 0 and 1."); - if ($data['buckets'] && (!is_numeric($data['buckets']) || - ($data['buckets'] < 16) || ($data['buckets'] > 65535))) - $input_errors[] = gettext("Buckets must be an integer between 16 and 65535."); - if ($data['qlimit'] && (!is_numeric($data['qlimit']))) - $input_errors[] = gettext("Queue limit must be an integer"); - if (!empty($data['newname']) && !preg_match("/^[a-zA-Z0-9_-]+$/", $data['newname'])) - $input_errors[] = gettext("Queue names must be alphanumeric and _ or - only."); - if (!empty($data['name']) && !preg_match("/^[a-zA-Z0-9_-]+$/", $data['name'])) - $input_errors[] = gettext("Queue names must be alphanumeric and _ or - only."); - if (isset($data['maskbits']) && ($data['maskbits'] <> "")) - if ((!is_numeric($data['maskbits'])) || ($data['maskbits'] <= 0) || ($data['maskbits'] > 32)) - $input_errors[] = gettext("IPV4 bit mask must be blank or numeric value between 1 and 32."); - if (isset($data['maskbitsv6']) && ($data['maskbitsv6'] <> "")) - if ((!is_numeric($data['maskbitsv6'])) || ($data['maskbitsv6'] <= 0) || ($data['maskbitsv6'] > 128)) - $input_errors[] = gettext("IPV6 bit mask must be blank or numeric value between 1 and 128."); - } - - function build_mask_rules(&$pfq_rule) { - $mask = $this->GetMask(); - if (!empty($mask['type'])) { - if ($mask['type'] <> 'none') - $pfq_rule .= " mask"; - switch ($mask['type']) { - case 'srcaddress': - if (!empty($mask['bitsv6']) && ($mask['bitsv6'] <> "")) - $pfq_rule .= " src-ip6 /" . $mask['bitsv6']; - else - $pfq_rule .= " src-ip6 /128"; - if (!empty($mask['bits']) && ($mask['bits'] <> "")) - $pfq_rule .= sprintf(" src-ip 0x%x", gen_subnet_mask_long($mask['bits'])); - else - $pfq_rule .= " src-ip 0xffffffff"; - break; - case 'dstaddress': - if (!empty($mask['bitsv6']) && ($mask['bitsv6'] <> "")) - $pfq_rule .= " dst-ip6 /" . $mask['bitsv6']; - else - $pfq_rule .= " dst-ip6 /128"; - if (!empty($mask['bits']) && ($mask['bits'] <> "")) - $pfq_rule .= sprintf(" dst-ip 0x%x", gen_subnet_mask_long($mask['bits'])); - else - $pfq_rule .= " dst-ip 0xffffffff"; - break; - default: - break; - } - } - } - -} - -class dnpipe_class extends dummynet_class { - var $delay; - var $qbandwidth = array(); - var $qbandwidthtype; - - /* This is here to help on form building and building rules/lists */ - var $subqueues = array(); - - function CanHaveChildren() { - return true; - } - function SetDelay($delay) { - $this->delay = $delay; - } - function GetDelay() { - return $this->delay; - } - function delete_queue() { - cleanup_dnqueue_from_rules($this->GetQname()); - foreach ($this->subqueues as $q) - $q->delete_queue(); - unset_dn_object_by_reference($this->GetLink()); - @pfSense_pipe_action("pipe delete " . $this->GetNumber()); - } - function GetBandwidth() { - return $this->qbandwidth; - } - function SetBandwidth($bandwidth) { - $this->qbandwidth = $bandwidth; - } - function GetBurst() { - return $this->qburst; - } - function SetBurst($burst) { - $this->qburst = $burst; - } - - function &add_queue($interface, &$queue, &$path, &$input_errors) { - - if (!is_array($this->subqueues)) - $this->subqueues = array(); - - $q =& new dnqueue_class(); - $q->SetLink($path); - $q->SetEnabled("on"); - $q->SetPipe($this->GetQname()); - $q->SetParent($this); - $q->ReadConfig($queue); - $q->validate_input($queue, $input_errors); - if (count($input_errors)) { - log_error("SHAPER: could not create queue " . $q->GetQname() . " on interface {$interface} because: " . print_r($input_errors, true)); - return $q; - } - $number = dnqueue_find_nextnumber(); - $q->SetNumber($number); - $this->subqueues[$q->GetQname()] = &$q; - - return $q; - } - - function &get_queue_list(&$q = null) { - $qlist = array(); - - $qlist[$this->GetQname()] = $this->GetNumber(); - if (is_array($this->subqueues)) { - foreach ($this->subqueues as $queue) - $queue->get_queue_list($qlist); - } - return $qlist; - } - - /* - * Should search even its children - */ - function &find_queue($pipe, $qname) { - if ($qname == $this->GetQname()) - return $this; - foreach ($this->subqueues as $q) { - $result =& $q->find_queue("", $qname); - if ($result) - return $result; - } - } - - function &find_parentqueue($pipe, $qname) { - return NULL; - } - - function validate_input($data, &$input_errors) { - parent::validate_input($data, $input_errors); - - $schedule = 0; - $schedulenone = 0; - $entries = 0; - for ($i = 0; $i < 30; $i++) { - if (!empty($data["bwsched{$i}"])) { - if ($data["bwsched{$i}"] != "none") - $schedule++; - else - $schedulenone++; - } - if (!empty($data["bandwidth{$i}"])) { - if (!is_numeric($data["bandwidth{$i}"])) - $input_errors[] = sprintf(gettext("Bandwidth for schedule %s must be an integer."), $data["bwsched{$i}"]); - else if (($data["burst{$i}"] != "") && (!is_numeric($data["burst{$i}"]))) - $input_errors[] = sprintf(gettext("Burst for schedule %s must be an integer."), $data["bwsched{$i}"]); - else - $entries++; - } - } - if ($schedule == 0 && $entries > 1) - $input_errors[] = gettext("You need to specify a schedule for every additional entry"); - if ($schedulenone > 0 && $entries > 1) - $input_errors[] = gettext("If more than one bandwidth configured all schedules need to be selected"); - if ($entries == 0) - $input_errors[] = gettext("At least one bw specification is necessary"); - if ($data['delay'] && (!is_numeric($data['delay']))) - $input_errors[] = gettext("Delay must be an integer."); - } - - function ReadConfig(&$q) { - if (!empty($q['name']) && !empty($q['newname']) && $q['name'] != $q['newname']) { - $this->SetQname($q['newname']); - } else if (!empty($q['newname'])) { - $this->SetQname($q['newname']); - } else { - $this->SetQname($q['name']); - } - $this->SetNumber($q['number']); - - if (!empty($_POST)) { - $bandwidth = array(); - for ($i = 0; $i < 30; $i++) { - if (isset($q["bandwidth{$i}"]) && $q["bandwidth{$i}"] <> "") { - $bw = array(); - $bw['bw'] = $q["bandwidth{$i}"]; - $bw['burst'] = $q["burst{$i}"]; - if (isset($q["bwtype{$i}"]) && $q["bwtype{$i}"]) - $bw['bwscale'] = $q["bwtype{$i}"]; - if (isset($q["bwsched{$i}"]) && $q["bwsched{$i}"]) - $bw['bwsched'] = $q["bwsched{$i}"]; - $bandwidth[] = $bw; - } - } - $this->SetBandwidth($bandwidth); - } - - if (is_array($q['bandwidth']) && is_array($q['bandwidth']['item'])) { - $this->SetBandwidth($q['bandwidth']['item']); - $this->SetBurst($q['burst']['item']); - } - - if (isset($q['qlimit']) && $q['qlimit'] <> "") - $this->SetQlimit($q['qlimit']); - else - $this->SetQlimit(""); - if (isset($q['mask']) && $q['mask'] <> "") - $masktype = $q['mask']; - else - $masktype = ""; - if (isset($q['maskbits']) && $q['maskbits'] <> "") - $maskbits = $q['maskbits']; - else - $maskbits = ""; - if (isset($q['maskbitsv6']) && $q['maskbitsv6'] <> "") - $maskbitsv6 = $q['maskbitsv6']; - else - $maskbitsv6 = ""; - $this->SetMask(array("type" => $masktype, "bits" => $maskbits, "bitsv6" => $maskbitsv6)); - if (isset($q['buckets']) && $q['buckets'] <> "") - $this->SetBuckets($q['buckets']); - else - $this->SetBuckets(""); - if (isset($q['plr']) && $q['plr'] <> "") - $this->SetPlr($q['plr']); - else - $this->SetPlr(""); - if (isset($q['delay']) && $q['delay'] <> "") - $this->SetDelay($q['delay']); - else - $this->SetDelay(0); - if (isset($q['description']) && $q['description'] <> "") - $this->SetDescription($q['description']); - else - $this->SetDescription(""); - $this->SetEnabled($q['enabled']); - - } - - function build_tree() { - $tree = "
  • GetQname() ."&queue=".$this->GetQname() ."&action=show\">"; - $tree .= $this->GetQname() . ""; - if (is_array($this->subqueues)) { - $tree .= "
      "; - foreach ($this->subqueues as $q) { - $tree .= $q->build_tree(); - } - $tree .= "
    "; - } - $tree .= "
  • "; - - return $tree; - } - - function build_rules() { - global $config, $time_based_rules; - - if ($this->GetEnabled() == "") - return; - - $pfq_rule = "\npipe ". $this->GetNumber() . " config "; - $found = false; - $bandwidth = $this->GetBandwidth(); - if (is_array($bandwidth)) { - foreach ($bandwidth as $bw) { - if ($bw['bwsched'] != "none") { - $time_based_rules = true; - if (is_array($config['schedules']) && is_array($config['schedules']['schedule'])) { - foreach ($config['schedules']['schedule'] as $schedule) { - if ($bw['bwsched'] == $schedule['name']) { - if (filter_get_time_based_rule_status($schedule)) { - $pfq_rule .= " bw ".trim($bw['bw']).$bw['bwscale']; - if (is_numeric($bw['burst']) && ($bw['burst'] > 0)) - $pfq_rule .= " burst ".trim($bw['burst']); - $found = true; - break; - } - } - } - } else { - $pfq_rule .= " bw 0"; - $found = true; - break; - } - } else { - $pfq_rule .= " bw ".trim($bw['bw']).$bw['bwscale']; - if (is_numeric($bw['burst']) && ($bw['burst'] > 0)) - $pfq_rule .= " burst ".trim($bw['burst']); - $found = true; - break; - } - } - if ($found == false) - $pfq_rule .= " bw 0"; - } else - $pfq_rule .= " bw 0"; - - if ($this->GetQlimit()) - $pfq_rule .= " queue " . $this->GetQlimit(); - if ($this->GetPlr()) - $pfq_rule .= " plr " . $this->GetPlr(); - if ($this->GetBuckets()) - $pfq_rule .= " buckets " . $this->GetBuckets(); - if ($this->GetDelay()) - $pfq_rule .= " delay " . $this->GetDelay(); - $this->build_mask_rules($pfq_rule); - - $pfq_rule .= "\n"; - - if (!empty($this->subqueues) && count($this->subqueues) > 0) { - foreach ($this->subqueues as $q) - $pfq_rule .= $q->build_rules(); - } - $pfq_rule .= " \n"; - - return $pfq_rule; - } - - function update_dn_data(&$data) { - $this->ReadConfig($data); - } - - function build_javascript() { - global $g, $config; - - $javasr = parent::build_javascript(); - - //build list of schedules - $schedules = ""; - if (is_array($config['schedules']) && is_array($config['schedules']['schedule'])) { - foreach ($config['schedules']['schedule'] as $schedule) { - if ($schedule['name'] <> "") - $schedules .= ""; - } - } - $bwopt = ""; - foreach (array("Kb" => "Kbit/s", "Mb" => "Mbit/s", "Gb" => "Gbit/s", "b" => "Bit/s") as $bwidx => $bw) - $bwopt .= ""; - - $javasr .= << -//"; - tr.appendChild(td); - td = d.createElement("td"); - td.innerHTML=""; - tr.appendChild(td); - td = d.createElement("td"); - td.innerHTML=""; - tr.appendChild(td); - td = d.createElement("td"); - td.innerHTML=""; - tr.appendChild(td); - td = d.createElement("td"); - td.rowSpan = "1"; - td.innerHTML = ''; - tr.appendChild(td); - tbody.appendChild(tr); - totalrows++; - }); -})(); - -function removeBwRow(el) { - var cel; - while (el && el.nodeName.toLowerCase() != "tr") - el = el.parentNode; - if (el && el.parentNode) { - cel = el.getElementsByTagName("td").item(0); - el.parentNode.removeChild(el); - } -} -//]]> - - -EOD; - - return $javasr; - } - - function build_form() { - global $g, $config; - - //build list of schedules - $schedules = array(); - $schedules[] = "none";//leave none to leave rule enabled all the time - if (is_array($config['schedules']) && is_array($config['schedules']['schedule'])) { - foreach ($config['schedules']['schedule'] as $schedule) { - if ($schedule['name'] <> "") - $schedules[] = $schedule['name']; - } - } - - $form = "
    "; - $form .= gettext("Enable"); - $form .= ""; - $form .= " GetEnabled() == "on") - $form .= " checked=\"checked\""; - $form .= " /> " . gettext("Enable limiter and its children") . ""; - $form .= ""; - $form .= "
    " . gettext("Name") . ""; - $form .= ""; - $form .= "GetQname()."\" />"; - $form .= "GetQname()."\" />"; - if ($this->GetNumber() > 0) { - $form .= "GetNumber()."\" />"; - } - $form .= ""; - $form .= "" . gettext("Bandwidth"); - $bandwidth = $this->GetBandwidth(); - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - if (is_array($bandwidth)) { - foreach ($bandwidth as $bwidx => $bw) { - $form .= "\n"; - } - } - $form .= "
    Bandwidth
    Burst
    Bw type
    Schedule
    "; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= "
    "; - $form .= ""; - $form .= ""; - $form .= "
    " . gettext("Bandwidth is a rate (e.g. Mbit/s), burst is a total amount of data that will be transferred at full speed after an idle period.") . "
    "; - $form .= ""; - $form .= "" . gettext("Mask") . ""; - $form .= ""; - $form .= ""; - $form .= " 
    "; - $form .= "" . gettext("If 'source' or 'destination' slots is chosen, \n" - . "a dynamic pipe with the bandwidth, delay, packet loss and queue size given above will \n" - . "be created for each source/destination IP address encountered, \n" - . "respectively. This makes it possible to easily specify bandwidth \n" - . "limits per host.") . "
    "; - $form .= "255.255.255.255/  "none") - $form .= $mask['bits']; - $form .= "\""; - if ($mask['type'] == "none") - $form .= " disabled"; - $form .= " />"; - $form .= "  IPV4 mask bits (1-32)
    "; - $form .= "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/  "none") - $form .= $mask['bitsv6']; - $form .= "\""; - if ($mask['type'] == "none") - $form .= " disabled"; - $form .= " />"; - $form .= "  IPV6 mask bits (1-128)
    "; - $form .= "" . gettext("If 'source' or 'destination' slots is chosen, \n" - . "leaving the mask bits blank will create one pipe per host. Otherwise specify \n" - . "the number of 'one' bits in the subnet mask used to group multiple hosts \n" - . "per pipe.") . ""; - $form .= ""; - $form .= "" . gettext("Description") . ""; - $form .= ""; - $form .= "GetDescription(); - $form .= "\" />"; - $form .= "
    "; - $form .= gettext("You may enter a description here for your reference (not parsed).") . ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= "
    "; - $form .= "

    "; - $form .= "

    "; - $form .= ""; - - $form .= "" . gettext("Delay") . ""; - $form .= ""; - $form .= "GetDelay() . "\" />"; - $form .= " ms
    " . gettext("Hint: in most cases, you " - . "should specify 0 here (or leave the field empty)") . "
    "; - $form .= ""; - $form .= ""; - $form .= "" . gettext("Packet loss rate") . ""; - $form .= ""; - $form .= "GetPlr() . "\" />"; - $form .= " 
    " . gettext("Hint: in most cases, you " - . "should specify 0 here (or leave the field empty). " - . "A value of 0.001 means one packet in 1000 gets dropped") . ""; - $form .= ""; - $form .= ""; - $form .= "" . gettext("Queue Size") . ""; - $form .= ""; - $form .= "GetQlimit() . "\" />"; - $form .= " slots
    "; - $form .= "" . gettext("Hint: in most cases, you " - . "should leave the field empty. All packets in this pipe are placed into a fixed-size queue first, " - . "then they are delayed by value specified in the Delay field, and then they " - . "are delivered to their destination.") . ""; - $form .= ""; - $form .= ""; - $form .= "" . gettext("Bucket Size") . ""; - $form .= ""; - $form .= "GetBuckets() . "\" />"; - $form .= " slots
    "; - $form .= "" . gettext("Hint: in most cases, you " - . "should leave the field empty. It increases the hash size set."); - $form .= ""; - - return $form; - - } - - function wconfig() { - $cflink =& get_dn_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) - $cflink = array(); - $cflink['name'] = $this->GetQname(); - $cflink['number'] = $this->GetNumber(); - $cflink['qlimit'] = $this->GetQlimit(); - $cflink['plr'] = $this->GetPlr(); - $cflink['description'] = $this->GetDescription(); - - $bandwidth = $this->GetBandwidth(); - if (is_array($bandwidth)) { - $cflink['bandwidth'] = array(); - $cflink['bandwidth']['item'] = array(); - foreach ($bandwidth as $bwidx => $bw) - $cflink['bandwidth']['item'][] = $bw; - } - - $cflink['enabled'] = $this->GetEnabled(); - $cflink['buckets'] = $this->GetBuckets(); - $mask = $this->GetMask(); - $cflink['mask'] = $mask['type']; - $cflink['maskbits'] = $mask['bits']; - $cflink['maskbitsv6'] = $mask['bitsv6']; - $cflink['delay'] = $this->GetDelay(); - } - -} - -class dnqueue_class extends dummynet_class { - var $pipeparent; - var $weight; - - function GetWeight() { - return $this->weight; - } - function SetWeight($weight) { - $this->weight = $weight; - } - function GetPipe() { - return $this->pipeparent; - } - function SetPipe($pipe) { - $this->pipeparent = $pipe; - } - - /* Just a stub in case we ever try to call this from the frontend. */ - function &add_queue($interface, &$queue, &$path, &$input_errors) { return; } - - function delete_queue() { - cleanup_dnqueue_from_rules($this->GetQname()); - unset_dn_object_by_reference($this->GetLink()); - @pfSense_pipe_action("queue delete " . $this->GetNumber()); - } - - function validate_input($data, &$input_errors) { - parent::validate_input($data, $input_errors); - - if ($data['weight'] && ((!is_numeric($data['weight'])) || - ($data['weight'] < 1 && $data['weight'] > 100))) - $input_errors[] = gettext("Weight must be an integer between 1 and 100."); - } - - /* - * Should search even its children - */ - function &find_queue($pipe, $qname) { - if ($qname == $this->GetQname()) - return $this; - else - return NULL; - } - - function &find_parentqueue($pipe, $qname) { - return $this->qparent; - } - - function &get_queue_list(&$qlist) { - if ($this->GetEnabled() == "") - return; - $qlist[$this->GetQname()] = "?" .$this->GetNumber(); - } - - function ReadConfig(&$q) { - if (!empty($q['name']) && !empty($q['newname']) && $q['name'] != $q['newname']) { - $this->SetQname($q['newname']); - } else if (!empty($q['newname'])) { - $this->SetQname($q['newname']); - } else { - $this->SetQname($q['name']); - } - $this->SetNumber($q['number']); - if (isset($q['qlimit']) && $q['qlimit'] <> "") - $this->SetQlimit($q['qlimit']); - else - $this->SetQlimit(""); - if (isset($q['mask']) && $q['mask'] <> "") - $masktype = $q['mask']; - else - $masktype = ""; - if (isset($q['maskbits']) && $q['maskbits'] <> "") - $maskbits = $q['maskbits']; - else - $maskbits = ""; - if (isset($q['maskbitsv6']) && $q['maskbitsv6'] <> "") - $maskbitsv6 = $q['maskbitsv6']; - else - $maskbitsv6 = ""; - $this->SetMask(array("type" => $masktype, "bits" => $maskbits, "bitsv6" => $maskbitsv6)); - if (isset($q['buckets']) && $q['buckets'] <> "") - $this->SetBuckets($q['buckets']); - else - $this->SetBuckets(""); - if (isset($q['plr']) && $q['plr'] <> "") - $this->SetPlr($q['plr']); - else - $this->SetPlr(""); - if (isset($q['weight']) && $q['weight'] <> "") - $this->SetWeight($q['weight']); - else - $this->SetWeight(""); - if (isset($q['description']) && $q['description'] <> "") - $this->SetDescription($q['description']); - else - $this->SetDescription(""); - $this->SetEnabled($q['enabled']); - } - - function build_tree() { - $parent =& $this->GetParent(); - $tree = "
  • GetQname() ."&queue=" . $this->GetQname() ."&action=show\">"; - $tree .= $this->GetQname() . ""; - $tree .= "
  • "; - - return $tree; - } - - function build_rules() { - if ($this->GetEnabled() == "") - return; - - $parent =& $this->GetParent(); - $pfq_rule = "queue ". $this->GetNumber() . " config pipe " . $parent->GetNumber(); - if ($this->GetQlimit()) - $pfq_rule .= " queue " . $this->GetQlimit(); - if ($this->GetWeight()) - $pfq_rule .= " weight " . $this->GetWeight(); - if ($this->GetBuckets()) - $pfq_rule .= " buckets " . $this->GetBuckets(); - $this->build_mask_rules($pfq_rule); - $pfq_rule .= "\n"; - - return $pfq_rule; - } - - function build_javascript() { - return parent::build_javascript(); - } - - - function build_form() { - $form = "
    "; - $form .= gettext("Enable/Disable"); - $form .= ""; - $form .= " GetEnabled() == "on") - $form .= " checked=\"checked\""; - $form .= " /> " . gettext("Enable/Disable queue") . ""; - $form .= ""; - $form .= "
    " . gettext("Name") . ""; - $form .= ""; - $form .= "GetQname()."\" />"; - $form .= "GetQname()."\" />"; - if ($this->GetNumber() > 0) { - $form .= "GetNumber()."\" />"; - } - $form .= ""; - $form .= "" . gettext("Mask") . ""; - $form .= ""; - $form .= ""; - $form .= " slots
    "; - $form .= "" . gettext("If 'source' or 'destination' slots is chosen, \n" - . "a dynamic pipe with the bandwidth, delay, packet loss and queue size given above will \n" - . "be created for each source/destination IP address encountered, \n" - . "respectively. This makes it possible to easily specify bandwidth \n" - . "limits per host.") . "
    "; - $form .= "255.255.255.255/  "none") - $form .= $mask['bits']; - $form .= "\""; - if ($mask['type'] == "none") - $form .= " disabled"; - $form .= " />"; - $form .= "  IPV4 mask bits (1-32)
    "; - $form .= "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/  "none") - $form .= $mask['bitsv6']; - $form .= "\""; - if ($mask['type'] == "none") - $form .= " disabled"; - $form .= " />"; - $form .= "  IPV6 mask bits (1-128)
    "; - $form .= "" . gettext("If 'source' or 'destination' slots is chosen, \n" - . "leaving the mask bits blank will create one pipe per host. Otherwise specify \n" - . "the number of 'one' bits in the subnet mask used to group multiple hosts \n" - . "per queue.") . ""; - $form .= ""; - $form .= "" . gettext("Description") . ""; - $form .= ""; - $form .= "GetDescription(); - $form .= "\" />"; - $form .= "
    "; - $form .= gettext("You may enter a description here for your reference (not parsed).") . ""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= "
    "; - $form .= "

    "; - $form .= "

    "; - $form .= ""; - $form .= "" . gettext("Weight") . ""; - $form .= ""; - $form .= "GetWeight() . "\" />"; - $form .= " 
    " . gettext("Hint: For queues under the same parent " - . "this specifies the share that a queue gets(values range from 1 to 100, you can leave it blank otherwise)") . ""; - $form .= ""; - $form .= ""; - $form .= "" . gettext("Packet loss rate") . ""; - $form .= ""; - $form .= "GetPlr() . "\" />"; - $form .= " 
    " . gettext("Hint: in most cases, you " - . "should specify 0 here (or leave the field empty). " - . "A value of 0.001 means one packet in 1000 gets dropped") . ""; - $form .= ""; - $form .= ""; - $form .= "" . gettext("Queue Size") . ""; - $form .= ""; - $form .= "GetQlimit() . "\" />"; - $form .= " slots
    "; - $form .= "" . gettext("Hint: in most cases, you " - . "should leave the field empty. All packets in this pipe are placed into a fixed-size queue first, " - . "then they are delayed by value specified in the Delay field, and then they " - . "are delivered to their destination.") . ""; - $form .= ""; - $form .= ""; - $form .= "" . gettext("Bucket Size") . ""; - $form .= ""; - $form .= "GetBuckets() . "\" />"; - $form .= " " . gettext("slots") . "
    "; - $form .= "" . gettext("Hint: in most cases, you " - . "should leave the field empty. It increases the hash size set."); - $form .= ""; - - $form .= "GetPipe() . "\" />"; - - return $form; - - } - - function update_dn_data(&$data) { - $this->ReadConfig($data); - } - - function wconfig() { - $cflink =& get_dn_reference_to_me_in_config($this->GetLink()); - if (!is_array($cflink)) - $cflink = array(); - $cflink['name'] = $this->GetQname(); - $cflink['number'] = $this->GetNumber(); - $cflink['qlimit'] = $this->GetQlimit(); - $cflink['description'] = $this->GetDescription(); - $cflink['weight'] = $this->GetWeight(); - $cflink['enabled'] = $this->GetEnabled(); - $cflink['buckets'] = $this->GetBuckets(); - $mask = $this->GetMask(); - $cflink['mask'] = $mask['type']; - $cflink['maskbits'] = $mask['bits']; - $cflink['maskbitsv6'] = $mask['bitsv6']; - } -} - -// List of layer7 objects -$layer7_rules_list = array(); - -class layer7 { - - var $rname; //alias - var $rdescription; //alias description - var $rport; //divert port - var $renabled; //rule enabled - var $rsets = array(); //array of l7 associations - - // Auxiliary functions - - function GetRName() { - return $this->rname; - } - function SetRName($rname) { - $this->rname = $rname; - } - function GetRDescription() { - return $this->rdescription; - } - function SetRDescription($rdescription) { - $this->rdescription = $rdescription; - } - function GetRPort() { - return $this->rport; - } - function SetRPort($rport) { - $this->rport = $rport; - } - function GetREnabled() { - return $this->renabled; - } - function SetREnabled($value) { - $this->renabled = $value; - } - function GetRl7() { - return $this->rsets; - } - function SetRl7($rsets) { - $this->rsets = $rsets; - } - - //Add a tuple (rule,sctructure,element) to the $rsets - - function add_rule($l7set) { - $this->rsets[] = $l7set; - } - - // Build the layer7 rules - function build_l7_rules() { - if($this->GetREnabled() == "") { - return; - } - //$l7rules = "#" . $this->rdescription . "\n"; - foreach ($this->rsets as $rl7) { - $l7rules .= $rl7->build_rules(); - } - return $l7rules; - } - - // Read the config from array - function ReadConfig(&$qname, &$q) { - $this->SetRName($qname); - $this->SetREnabled($q['enabled']); - $this->SetRPort($q['divert_port']); - if(isset($q['description']) && $q['description'] <> "") - $this->SetRDescription($q['description']); - $rsets = $q['l7rules']; - //Put individual rules in the array - if(is_array($rsets)) { - $this->rsets = array(); // XXX: ugly hack - foreach($rsets as $l7r) { - $l7obj = new l7rule(); - $l7obj->SetRProtocol($l7r['protocol']); - $l7obj->SetRStructure($l7r['structure']); - $l7obj->SetRBehaviour($l7r['behaviour']); - $this->add_rule($l7obj); - } - } - } - - //Generate a random port for the divert socket - function gen_divert_port() { - $dports = get_divert_ports(); //array of used ports - $divert_port = 1; // Initialize - while (($divert_port % 2) != 0 || in_array($divert_port, $dports)) { - $divert_port = rand(40000, 60000); - } - return $divert_port; - } - - //Helps building the left tree - function build_tree() { - $tree = "
  • GetRName() ."&action=show\">"; - $tree .= $this->GetRName() . ""; - $tree .= "
  • "; - - return $tree; - } - - function build_form() { - $form = "
    "; - $form .= gettext("Enable/Disable"); - $form .= ""; - $form .= " GetREnabled() == "on") { - $form .= "checked=\"checked\""; - } - $form .= " /> " . gettext("Enable/Disable layer7 Container") . ""; - $form .= ""; - $form .= "
    " . gettext("Name") . ""; - $form .= ""; - $form .= "GetRName()."\" />"; - $form .= ""; - $form .= "" . gettext("Description") . ""; - $form .= ""; - $form .= "GetRDescription(); - $form .= "\" />"; - $form .= "
    "; - $form .= gettext("You may enter a description here for your reference (not parsed).") . ""; - $form .= ""; - - return $form; - } - - //Write the setting to the $config array - function wconfig() { - global $config; - - if(!is_array($config['l7shaper']['container'])) { - $config['l7shaper']['container'] = array(); - } - // - $cflink =& get_l7c_reference_to_me_in_config($this->GetRName()); - // Test if this rule does exists already - if(!$cflink) { - $cflink =& $config['l7shaper']['container'][]; - } - $cflink['name'] = $this->GetRName(); - $cflink['enabled'] = $this->GetREnabled(); - $cflink['description'] = $this->GetRDescription(); - $cflink['divert_port'] = $this->GetRPort(); - - //Destroy previously existent rules - if(is_array($cflink['rules'])) { - unset($cflink['l7rules']); - } - - $cflink['l7rules'] = array(); - - $i = 0; - foreach($this->rsets as $rulel7) { - $cflink['l7rules'][$i]['protocol'] = $rulel7->GetRProtocol(); - $cflink['l7rules'][$i]['structure'] = $rulel7->GetRStructure(); - $cflink['l7rules'][$i]['behaviour'] = $rulel7->GetRBehaviour(); - $i++; - } - } - - //This function is necessary to help producing the overload options for keep state - function get_unique_structures() { - - $unique_structures = array("action" => false, "dummynet" => false, "altq" => false); - foreach($this->rsets as $l7rule) { - if($l7rule->GetRStructure() == "action") - $unique_structures['action'] = true; - else if($l7rule->GetRStructure() == "limiter") - $unique_structures['dummynet'] = true; - else - $unique_structures['altq'] = true; - } - //Delete non used structures so we don't have to check this in filter.inc - foreach($unique_structures as $key => $value) - if(!$value) - unset($unique_structures[$key]); - return $unique_structures; - } - - function validate_input($data, &$input_errors) { - $reqdfields[] = "container"; - $reqdfieldsn[] = gettext("Name"); - - shaper_do_input_validation($data, $reqdfields, $reqdfieldsn, $input_errors); - - if (!preg_match("/^[a-zA-Z0-9_-]+$/", $data['container'])) - $input_errors[] = gettext("Queue names must be alphanumeric and _ or - only."); - } - - function delete_l7c() { - mwexec("/bin/pkill -f 'ipfw-classifyd .* -p ". $this->GetRPort() . "'", true); - unset_l7_object_by_reference($this->GetRName()); - cleanup_l7_from_rules($this->GetRName()); - } -} - -class l7rule { - - var $rprotocol; //protocol - var $rstructure; //action, limiter, queue - var $rbehaviour; //allow, block, queue_name, pipe_number ... - - //Auxiliary Functions - - function GetRProtocol() { - return $this->rprotocol; - } - function SetRProtocol($rprotocol) { - $this->rprotocol = $rprotocol; - } - function GetRStructure() { - return $this->rstructure; - } - function SetRStructure($rstructure) { - $this->rstructure = $rstructure; - } - function GetRBehaviour() { - return $this->rbehaviour; - } - function SetRBehaviour($rbehaviour) { - $this->rbehaviour = $rbehaviour; - } - - //XXX Do we need to test any particularity for AltQ queues? - function build_rules() { - global $dummynet_pipe_list; - switch ($this->GetRStructure()) { - case "limiter": - read_dummynet_config(); - $dn_list =& get_unique_dnqueue_list(); - $found = false; - if(is_array($dn_list)) { - foreach($dn_list as $key => $value) { - if($key == $this->GetRBehaviour()) { - if($value[0] == "?") - $l7rule = $this->GetRProtocol() . " = dnqueue " . substr($value, 1) . "\n"; - else - $l7rule = $this->GetRProtocol() . " = dnpipe " . $value . "\n"; - $found = true; - } - if($found) - break; - } - } - break; - default: //This is for action and for altq - $l7rule = $this->GetRProtocol() . " = " . $this->GetRStructure() . " " . $this->GetRBehaviour() . "\n"; - break; - } - return $l7rule; - } -} - -/* - * This function allows to return an array with all the used divert socket ports - */ -function get_divert_ports() { - global $layer7_rules_list; - $dports = array(); - - foreach($layer7_rules_list as $l7r) - $dports[] = $l7r->GetRPort(); - - return $dports; -} - -function &get_l7c_reference_to_me_in_config(&$name) { - global $config; - - $ptr = NULL; - - if(is_array($config['l7shaper']['container'])) { - foreach($config['l7shaper']['container'] as $key => $value) { - if($value['name'] == $name) - $ptr =& $config['l7shaper']['container'][$key]; - } - } - return $ptr; - // $ptr can be null. has to be checked later -} - -function unset_l7_object_by_reference(&$name) { - global $config; - - if(is_array($config['l7shaper']['container'])) { - foreach($config['l7shaper']['container'] as $key => $value) { - if($value['name'] == $name) { - unset($config['l7shaper']['container'][$key]['l7rules']); - unset($config['l7shaper']['container'][$key]); - break; - } - } - } -} - -function read_layer7_config() { - global $layer7_rules_list, $config; - - if (!is_array($config['l7shaper']['container']) || !count($config['l7shaper']['container'])) { - $layer7_rules_list = array(); - return; - } - - $l7cs = &$config['l7shaper']['container']; - - $layer7_rules_list = array(); - - foreach ($l7cs as $conf) { - if (empty($conf['name'])) - continue; /* XXX: grrrrrr at php */ - $root =& new layer7(); - $root->ReadConfig($conf['name'],$conf); - $layer7_rules_list[$root->GetRName()] = &$root; - } -} - -function update_layer7_custom_patterns() { - global $config; - - if (!is_array($config['l7shaper']['custom_pat'])) - return; - - foreach ($config['l7shaper']['custom_pat'] as $filename => $filecontent) - if (!file_exists("/usr/local/share/protocols/" . $filename)) - @file_put_contents("/usr/local/share/protocols/" . $filename, base64_decode($filecontent)); -} - -function generate_layer7_files() { - global $layer7_rules_list, $g; - - read_layer7_config(); - - if (!empty($layer7_rules_list)) { - if (!is_module_loaded("ipdivert.ko")) - mwexec("/sbin/kldload ipdivert.ko"); - - array_map('unlink', glob("{$g['tmp_path']}/*.l7")); - } - - update_layer7_custom_patterns(); - - foreach($layer7_rules_list as $l7rules) { - if($l7rules->GetREnabled()) { - $filename = $l7rules->GetRName() . ".l7"; - $path = "{$g['tmp_path']}/" . $filename; - - $rules = $l7rules->build_l7_rules(); - - $fp = fopen($path,'w'); - fwrite($fp,$rules); - fclose($fp); - } - } -} - -function layer7_start_l7daemon() { - global $layer7_rules_list, $g; - - /* - * XXX: ermal - Needed ?! - * read_layer7_config(); - */ - - foreach($layer7_rules_list as $l7rules) { - if($l7rules->GetREnabled()) { - $filename = $l7rules->GetRName() . ".l7"; - $path = "{$g['tmp_path']}/" . $filename; - - unset($l7pid); - /* Only reread the configuration rather than restart to avoid losing information. */ - exec("/bin/pgrep -f 'ipfw-classifyd .* -p ". $l7rules->GetRPort() . "'", $l7pid); - if (count($l7pid) > 0) { - log_error(sprintf(gettext("Sending HUP signal to %s"), $l7pid[0])); - mwexec("/bin/kill -HUP {$l7pid[0]}"); - } else { - // XXX: Hardcoded number of packets to garbage collect and queue length.. - $ipfw_classifyd_init = "/usr/local/sbin/ipfw-classifyd -n 8 -q 700 -c {$path} -p " . $l7rules->GetRPort() . " -P /usr/local/share/protocols"; - mwexec_bg($ipfw_classifyd_init); - } - } - } -} - -// This function uses /usr/local/share/protocols as a default directory for searching .pat files -function generate_protocols_array() { - - update_layer7_custom_patterns(); - - $protocols = return_dir_as_array("/usr/local/share/protocols"); - $protocols_new = array(); - if(is_array($protocols)) { - foreach($protocols as $key => $proto) { - if (strstr($proto, ".pat")) - $protocols_new[$key] =& str_replace(".pat", "", $proto); - } - sort($protocols_new); - } - return $protocols_new; -} - -function get_l7_unique_list() { - global $layer7_rules_list; - - $l7list = array(); - if(is_array($layer7_rules_list)) - foreach($layer7_rules_list as $l7c) - if($l7c->GetREnabled()) - $l7list[] = $l7c->GetRName(); - - return $l7list; -} - -// Disable a removed l7 container from the filter -function cleanup_l7_from_rules(&$name) { - global $config; - - if(is_array($config['filter']['rule'])) - foreach ($config['filter']['rule'] as $key => $rule) { - if ($rule['l7container'] == $name) - unset($config['filter']['rule'][$key]['l7container']); - } -} - -function get_dummynet_name_list() { - - $dn_name_list =& get_unique_dnqueue_list(); - $dn_name = array(); - if(is_array($dn_name_list)) - foreach($dn_name_list as $key => $value) - $dn_name[] = $key; - - return $dn_name; - -} - -function get_altq_name_list() { - $altq_name_list =& get_unique_queue_list(); - $altq_name = array(); - if(is_array($altq_name_list)) - foreach($altq_name_list as $key => $aqobj) - $altq_name[] = $key; - - return $altq_name; -} - -/* - * XXX: TODO Make a class shaper to hide all these function - * from the global namespace. - */ - -/* - * This is a layer violation but for now there is no way - * i can find to properly do this with PHP. - */ -function altq_get_default_queue($interface) { - global $altq_list_queues; - - $altq_tmp = $altq_list_queues[$interface]; - if ($altq_tmp) - return $altq_tmp->GetDefaultQueuePresent(); - else - return false; -} - -function altq_check_default_queues() { - global $altq_list_queues; - - $count = 0; - if (is_array($altq_list_queues)) { - foreach($altq_list_queues as $altq) { - if ($altq->GetDefaultQueuePresent()) - $count++; - } - } - else $count++; - - return 0; -} - -function &get_unique_queue_list() { - global $altq_list_queues; - - $qlist = array(); - if (is_array($altq_list_queues)) { - foreach ($altq_list_queues as $altq) { - if ($altq->GetEnabled() == "") - continue; - $tmplist =& $altq->get_queue_list(); - foreach ($tmplist as $qname => $link) { - if ($link->GetEnabled() <> "") - $qlist[$qname] = $link; - } - } - } - return $qlist; -} - -function &get_unique_dnqueue_list() { - global $dummynet_pipe_list; - - $qlist = array(); - if (is_array($dummynet_pipe_list)) { - foreach ($dummynet_pipe_list as $dn) { - if ($dn->GetEnabled() == "") - continue; - $tmplist =& $dn->get_queue_list(); - foreach ($tmplist as $qname => $link) { - $qlist[$qname] = $link; - } - } - } - return $qlist; -} - -function ref_on_altq_queue_list($parent, $qname) { - if (isset($GLOBALS['queue_list'][$qname])) - $GLOBALS['queue_list'][$qname]++; - else - $GLOBALS['queue_list'][$qname] = 1; - - unref_on_altq_queue_list($parent); -} - -function unref_on_altq_queue_list($qname) { - $GLOBALS['queue_list'][$qname]--; - if ($GLOBALS['queue_list'][$qname] <= 1) - unset($GLOBALS['queue_list'][$qname]); -} - -function read_altq_config() { - global $altq_list_queues, $config; - $path = array(); - - if (!is_array($config['shaper'])) - $config['shaper'] = array(); - if (!is_array($config['shaper']['queue'])) - $config['shaper']['queue'] = array(); - $a_int = &$config['shaper']['queue']; - - $altq_list_queues = array(); - - if (!is_array($config['shaper']['queue'])) - return; - - foreach ($a_int as $key => $conf) { - $int = $conf['interface']; - $root =& new altq_root_queue(); - $root->SetInterface($int); - $altq_list_queues[$root->GetInterface()] = &$root; - $root->ReadConfig($conf); - array_push($path, $key); - $root->SetLink($path); - if (is_array($conf['queue'])) { - foreach ($conf['queue'] as $key1 => $q) { - array_push($path, $key1); - /* - * XXX: we completely ignore errors here but anyway we must have - * checked them before so no harm should be come from this. - */ - $root->add_queue($root->GetInterface(), $q, $path, $input_errors); - array_pop($path); - } - } - array_pop($path); - } -} - -function read_dummynet_config() { - global $dummynet_pipe_list, $config; - $path = array(); - - if (!is_array($config['dnshaper'])) - $config['dnshaper'] = array(); - if (!is_array($config['dnshaper']['queue'])) - $config['dnshaper']['queue'] = array(); - $a_int = &$config['dnshaper']['queue']; - - $dummynet_pipe_list = array(); - - if (!is_array($config['dnshaper']['queue']) - || !count($config['dnshaper']['queue'])) - return; - - foreach ($a_int as $key => $conf) { - if (empty($conf['name'])) - continue; /* XXX: grrrrrr at php */ - $root =& new dnpipe_class(); - $root->ReadConfig($conf); - $dummynet_pipe_list[$root->GetQname()] = &$root; - array_push($path, $key); - $root->SetLink($path); - if (is_array($conf['queue'])) { - foreach ($conf['queue'] as $key1 => $q) { - array_push($path, $key1); - /* - * XXX: we completely ignore errors here but anyway we must have - * checked them before so no harm should be come from this. - */ - $root->add_queue($root->GetQname(), $q, $path, $input_errors); - array_pop($path); - } - } - array_pop($path); - } -} - -function get_interface_list_to_show() { - global $altq_list_queues, $config; - global $shaperIFlist; - - $tree = ""; - foreach ($shaperIFlist as $shif => $shDescr) { - if ($altq_list_queues[$shif]) { - continue; - } else { - if (!is_altq_capable(get_real_interface($shif))) - continue; - $tree .= "
  • ".$shDescr."
  • "; - } - } - - return $tree; -} - -function filter_generate_altq_queues() { - global $altq_list_queues; - - read_altq_config(); - - $altq_rules = ""; - foreach ($altq_list_queues as $altq) - $altq_rules .= $altq->build_rules(); - - return $altq_rules; -} - -function dnqueue_find_nextnumber() { - global $dummynet_pipe_list; - - $dnused = array(); - if (is_array($dummynet_pipe_list)) { - foreach ($dummynet_pipe_list as $dn) { - $tmplist =& $dn->get_queue_list(); - foreach ($tmplist as $qname => $link) { - if ($link[0] == "?") - $dnused[$qname] = substr($link, 1); - } - } - } - - sort($dnused, SORT_NUMERIC); - $dnnumber = 0; - $found = false; - foreach ($dnused as $dnnum) { - if (($dnnum - $dnnumber) > 1) { - $dnnumber = $dnnum + 1; - $found = true; - break; - } else - $dnnumber = $dnnum; - } - - if ($found == false) - $dnnumber++; - - unset($dnused, $dnnum, $found); - return $dnnumber; -} - -function dnpipe_find_nextnumber() { - global $dummynet_pipe_list; - - $dnused = array(); - foreach ($dummynet_pipe_list as $dn) - $dnused[] = $dn->GetNumber(); - - sort($dnused, SORT_NUMERIC); - $dnnumber = 0; - $found = false; - foreach ($dnused as $dnnum) { - if (($dnnum - $dnnumber) > 1) { - $dnnumber = $dnnum + 1; - $found = true; - break; - } else - $dnnumber = $dnnum; - } - - if ($found == false) - $dnnumber++; - - unset($dnused, $dnnum, $found); - return $dnnumber; -} - -function filter_generate_dummynet_rules() { - global $g, $dummynet_pipe_list; - - read_dummynet_config(); - - $dn_rules = ""; - foreach ($dummynet_pipe_list as $dn) - $dn_rules .= $dn->build_rules(); - - if (!empty($dn_rules)) { - if (!is_module_loaded("dummynet.ko")) { - mwexec("/sbin/kldload dummynet"); - set_sysctl(array( - "net.inet.ip.dummynet.io_fast" => "1", - "net.inet.ip.dummynet.hash_size" => "256" - )); - } - file_put_contents("{$g['tmp_path']}/rules.limiter", $dn_rules); - mwexec("/sbin/ipfw {$g['tmp_path']}/rules.limiter"); - } -} - -function build_iface_without_this_queue($iface, $qname) { - global $g, $altq_list_queues; - global $shaperIFlist; - - $altq =& $altq_list_queues[$iface]; - if ($altq) - $scheduler = ": " . $altq->GetScheduler(); - $form = ""; - $form .= "". $shaperIFlist[$iface] . $scheduler.""; - $form .= ""; - $form .= ""; - $form .= ""; - $form .= " "; - //$form .= gettext(" Clone shaper/queue on this interface") . ""; - - return $form; - -} - - -$default_shaper_msg = ""; -$default_shaper_msg .= "" . sprintf(gettext("Welcome to the %s Traffic Shaper."), $g['product_name']) . "
    "; -$default_shaper_msg .= gettext("The tree on the left helps you navigate through the queues
    " - . "buttons at the bottom represent queue actions and are activated accordingly."); -$default_shaper_msg .= "
    "; -$default_shaper_msg .= ""; - -$dn_default_shaper_msg = ""; -$dn_default_shaper_msg .= "" . sprintf(gettext("Welcome to the %s Traffic Shaper."), $g['product_name']) . "
    "; -$dn_default_shaper_msg .= gettext("The tree on the left helps you navigate through the queues
    " - . "buttons at the bottom represent queue actions and are activated accordingly."); -$dn_default_shaper_msg .= "
    "; -$dn_default_shaper_msg .= ""; - -?>