\n";
foreach ($tab_array as $ta) {
if ($ta[1] == true) {
echo "
\n";
} else {
echo "
\n";
}
$tabscounter++;
}
echo "
\n";
echo "
\n";
echo "";
}
/****f* pfsense-utils/display_topbar
* NAME
* display_topbar - top a table off with rounded edges
* INPUTS
* $text - (optional) Text to include in bar
* RESULT
* null
******/
function display_topbar($text = "", $bg_color="#990000", $replace_color="#FFFFFF", $rounding_style="smooth") {
echo "
\n";
echo "
\n";
echo "
";
echo "
\n";
echo "
\n";
echo "
\n";
if ($text != "")
echo "
{$text}
\n";
else
echo "
\n";
echo "
\n";
echo "
";
echo "";
}
/****f* pfsense-utils/generate_random_mac_address
* NAME
* generate_random_mac - generates a random mac address
* INPUTS
* none
* RESULT
* $mac - a random mac address
******/
function generate_random_mac_address() {
$mac = "02";
for($x=0; $x<5; $x++)
$mac .= ":" . dechex(rand(16, 255));
return $mac;
}
/****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, $debug;
$shutdown_webgui_needed = false;
touch("{$g['tmp_path']}/reloading_all");
if($debug)
log_error("reload_interfaces_sync() is starting.");
if(file_exists("{$g['tmp_path']}/config.cache"))
unlink("{$g['tmp_path']}/config.cache");
/* parse config.xml again */
$config = parse_config(true);
$wan_if = $config['interfaces']['wan']['if'];
$lan_if = $config['interfaces']['lan']['if'];
if($debug)
log_error("Cleaning up Interfaces");
/* if list */
$iflist = get_configured_interface_list(true);
foreach ($iflist as $ifent => $ifname) {
$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
if(stristr($ifname, "lo0") == true)
continue;
/* do not process wan interface, its mandatory */
if(stristr($ifname, "$wan_if") == true)
continue;
/* do not process lan interface, its mandatory */
if(stristr($ifname, "$lan_if") == true)
continue;
if($debug)
log_error("Downing and deleting $ifname_real - $ifname");
mwexec("/sbin/ifconfig {$ifname_real} down");
mwexec("/sbin/ifconfig {$ifname_real} delete");
}
/* set up interfaces */
interfaces_configure();
/* set up static routes */
if($debug)
log_error("Configuring system Routing");
system_routing_configure();
/* enable routing */
if($debug)
log_error("Enabling system routing");
system_routing_enable();
/* setup captive portal if needed */
if($debug)
log_error("Configuring Captive portal");
captiveportal_configure();
/* bring up carp interfaces */
if($debug)
log_error("Configuring CARP");
interfaces_carp_configure();
/* restart webConfigurator if needed */
if($shutdown_webgui_needed == true)
touch("/tmp/restart_webgui");
/* start devd back up */
mwexec("/bin/rm /tmp/reload*");
/* remove reloading_all trigger */
if($debug)
log_error("Removing {$g['tmp_path']}/reloading_all");
unlink_if_exists("{$g['tmp_path']}/reloading_all");
}
/****f* pfsense-utils/reload_all
* NAME
* reload_all - triggers a reload of all settings
* * INPUTS
* none
* RESULT
* none
******/
function reload_all() {
touch("/tmp/reload_all");
}
/****f* pfsense-utils/reload_interfaces
* NAME
* reload_interfaces - triggers a reload of all interfaces
* INPUTS
* none
* RESULT
* none
******/
function reload_interfaces() {
touch("/tmp/reload_interfaces");
}
/****f* pfsense-utils/sync_webgui_passwords
* NAME
* sync_webgui_passwords - syncs webgui and ssh passwords
* INPUTS
* none
* RESULT
* none
******/
function sync_webgui_passwords() {
global $config, $g, $groupindex, $userindex;
conf_mount_rw();
$fd = fopen("{$g['varrun_path']}/htpasswd", "w");
if (!$fd) {
log_error("Error: cannot open htpasswd in sync_webgui_passwords().\n");
return 1;
}
/* loop through custom users and add "virtual" entries */
if ($config['system']['user']) {
foreach ($config['system']['user'] as $user)
fwrite($fd, "{$user['name']}:{$user['password']}\n");
}
fclose($fd);
chmod("{$g['varrun_path']}/htpasswd", 0600);
$root =& getUNIXRoot();
$crypted_pw = &$root['password'];
if (!$crypted_pw) {
log_error("Error: cannot determine root pwd in sync_webgui_passwords().\nRoot user struct follows:\n");
if(!$root)
log_error("Unable to determine root user" . print_r($root, true));
log_error("Testing whether your system has the necessary users... ");
empty($config['system']['user']) ? log_error("users are missing.\n") : log_error("users found.\n");
return 1;
}
if(file_exists("/etc/pwd.db.tmp"))
unlink("/etc/pwd.db.tmp");
mwexec("/usr/sbin/pwd_mkdb -d /etc -p /etc/master.passwd");
mwexec("/usr/sbin/pwd_mkdb -p /etc/master.passwd");
/* sync root */
$fd = popen("/usr/sbin/pw usermod -n root -H 0", "w");
fwrite($fd, $crypted_pw);
pclose($fd);
mwexec("/usr/sbin/pw usermod -n root -s /bin/sh");
/* and again for shell users */
/* only users with hasShellAccess() == true should be synced */
if($config['system']['user']) {
$home_base = $g['platform'] == "pfSense" ? "/home" : "/var/home";
if(! is_dir($home_base))
mkdir($home_base, 0755);
foreach($config['system']['user'] as $user) {
if (hasShellAccess($user['name']) || isAllowedToCopyFiles($user['name'])) {
$home = hasShellAccess($user['name']) ? "{$home_base}/{$user['name']}" : "{$home_base}/scponly";
$shell = isAllowedToCopyFiles($user['name']) ? "/usr/local/bin/scponly" : "/etc/rc.initial";
if (isAllowedToCopyFiles($user['name']))
$user['groupname'] = "scponly";
$fd = popen("/usr/sbin/pw groupshow -n {$user['groupname']} 2>&1", "r");
$pwread = fgets($fd, 4096);
pclose($fd);
if (strpos($pwread, "unknown group") !== false) {
$groupname = $user['groupname'];
$group = $config['system']['group'][$groupindex[$groupname]];
if (isset($group) && is_array($group)) {
log_error("Running: /usr/sbin/pw groupadd -g {$group['gid']} -n {$group['name']}");
$fd = popen("/usr/sbin/pw groupadd -g {$group['gid']} -n {$group['name']}", "r");
pclose($fd);
} elseif (isAllowedToCopyFiles($user['name'])) {
log_error("Running: /usr/sbin/pw groupadd -g 100 -n scponly");
$fd = popen("/usr/sbin/pw groupadd -g 100 -n scponly", "r");
pclose($fd);
}
}
$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
$pwread = fgets($fd, 4096);
pclose($fd);
isSystemAdmin($user['name']) ? $group = "wheel" : $group = "staff";
if (strpos($pwread, "no such user") === false) {
log_error("Running: /usr/sbin/pw usermod -n {$user['name']} -g {$user['groupname']} -G {$group} -H 0");
$fd = popen("/usr/sbin/pw usermod -n {$user['name']} -g {$user['groupname']} -G {$group} -H 0", "w");
fwrite($fd, $user['password']);
pclose($fd);
} else {
log_error("Running: /usr/sbin/pw useradd -u {$user['uid']} -n {$user['name']} -c '" . escapeshellarg($user['fullname']) . " -g {$user['groupname']} -G {$group} -H 0");
$fd = popen("/usr/sbin/pw useradd -u {$user['uid']} -n {$user['name']} -c " . escapeshellarg($user['fullname']) . " -g {$user['groupname']} -G {$group} -H 0", "w");
fwrite($fd, $user['password']);
pclose($fd);
}
/* common user related operations */
mwexec("/usr/sbin/pw usermod -n {$user['name']} -s {$shell}");
if(! is_dir($home)) mkdir($home, 0755);
mwexec("/usr/sbin/pw usermod -n {$user['name']} -d {$home} -m");
if (isAllowedToCopyFiles($user['name'])) {
mwexec("/usr/sbin/pw usermod -n {$user['name']} -g scponly");
}
if (file_exists("{$home_base}/scponly"))
mwexec("chmod 0660 {$home_base}/scponly");
if(isset($config['system']['ssh']['sshdkeyonly']) && ! isAllowedToCopyFiles($user['name'])) {
create_authorized_keys($user['name'], $home);
}
}
}
}
mwexec("/usr/sbin/pwd_mkdb -d /etc -p /etc/master.passwd");
mwexec("/usr/sbin/pwd_mkdb -p /etc/master.passwd");
conf_mount_ro();
}
/****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;
touch("{$g['tmp_path']}/reloading_all");
$shutdown_webgui_needed = false;
if(file_exists("{$g['tmp_path']}/config.cache"))
unlink("{$g['tmp_path']}/config.cache");
/* 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();
/* Set up our loopback interface */
interfaces_loopback_configure();
/* delete all old interface information */
$iflist = split(" ", str_replace("\n", "", `/sbin/ifconfig -l`));
$wan_if = $config['interfaces']['wan']['if'];
$lan_if = $config['interfaces']['lan']['if'];
/* if list */
$iflist = get_configured_interface_list();
foreach ($iflist as $ifent => $ifname) {
$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
if(stristr($ifname, "lo0") == true)
continue;
/* do not process wan interface, its mandatory */
if($wan_if == $ifname_real)
continue;
/* do not process lan interface, its mandatory */
if($lan_if == $ifname_real)
continue;
mwexec("/sbin/ifconfig {$ifname_real} down");
mwexec("/sbin/ifconfig {$ifname_real} delete");
}
/* set up interfaces */
interfaces_configure();
/* bring up carp interfaces */
interfaces_carp_configure();
/* set up static routes */
system_routing_configure();
/* enable routing */
system_routing_enable();
/* ensure passwords are sync'd */
system_password_configure();
/* start dnsmasq service */
services_dnsmasq_configure();
/* start dyndns service */
services_dyndns_configure();
/* start DHCP service */
services_dhcpd_configure();
/* configure cron service */
configure_cron();
/* start the NTP client */
system_ntp_configure();
/* start ftp proxy helpers if they are enabled */
system_start_ftp_helpers();
/* start the captive portal */
captiveportal_configure();
/* reload the filter */
filter_configure_sync();
/* sync pw database */
conf_mount_rw();
mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
conf_mount_ro();
/* restart sshd */
touch("/tmp/start_sshd");
/* restart webConfigurator if needed */
if($shutdown_webgui_needed == true)
touch("/tmp/restart_webgui");
mwexec("/bin/rm /tmp/reload*");
unlink_if_exists("{$g['tmp_path']}/reloading_all");
}
function auto_login($status) {
$gettytab = file_get_contents("/etc/gettytab");
$getty_split = split("\n", $gettytab);
conf_mount_rw();
$fd = fopen("/etc/gettytab", "w");
foreach($getty_split as $gs) {
if(stristr($gs, ":ht:np:sp#115200") ) {
if($status == true) {
fwrite($fd, " :ht:np:sp#115200:al=root:\n");
} else {
fwrite($fd, " :ht:np:sp#115200:\n");
}
} else {
fwrite($fd, "{$gs}\n");
}
}
fclose($fd);
conf_mount_ro();
}
function setup_serial_port() {
global $g, $config;
conf_mount_rw();
/* serial console - write out /boot.config */
if(file_exists("/boot.config"))
$boot_config = file_get_contents("/boot.config");
else
$boot_config = "";
if($g['platform'] <> "cdrom") {
$boot_config_split = split("\n", $boot_config);
$fd = fopen("/boot.config","w");
if($fd) {
foreach($boot_config_split as $bcs) {
if(stristr($bcs, "-D")) {
/* DONT WRITE OUT, WE'LL DO IT LATER */
} else {
if($bcs <> "")
fwrite($fd, "{$bcs}\n");
}
}
if(isset($config['system']['enableserial'])) {
fwrite($fd, "-D");
}
fclose($fd);
}
/* serial console - write out /boot/loader.conf */
$boot_config = file_get_contents("/boot/loader.conf");
$boot_config_split = split("\n", $boot_config);
$fd = fopen("/boot/loader.conf","w");
if($fd) {
foreach($boot_config_split as $bcs) {
if(stristr($bcs, "console")) {
/* DONT WRITE OUT, WE'LL DO IT LATER */
} else {
if($bcs <> "")
fwrite($fd, "{$bcs}\n");
}
}
if(isset($config['system']['enableserial'])) {
fwrite($fd, "console=\"comconsole\"\n");
}
fclose($fd);
}
}
$ttys = file_get_contents("/etc/ttys");
$ttys_split = split("\n", $ttys);
$fd = fopen("/etc/ttys", "w");
foreach($ttys_split as $tty) {
if(stristr($tty, "ttyd0")) {
if(isset($config['system']['enableserial'])) {
fwrite($fd, "ttyd0 \"/usr/libexec/getty bootupcli\" dialup on secure\n");
} else {
fwrite($fd, "ttyd0 \"/usr/libexec/getty bootupcli\" dialup off secure\n");
}
} else {
fwrite($fd, $tty . "\n");
}
}
fclose($fd);
if(isset($config['system']['disableconsolemenu'])) {
auto_login(false);
} else {
auto_login(true);
}
conf_mount_ro();
return;
}
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;
}
function enable_rrd_graphing() {
global $config, $g, $altq_list_queues;
if($g['booting'])
echo "Generating RRD graphs...";
$rrddbpath = "/var/db/rrd/";
$rrdgraphpath = "/usr/local/www/rrd";
$traffic = "-traffic.rrd";
$packets = "-packets.rrd";
$states = "-states.rrd";
$quality = "-quality.rrd";
$wireless = "-wireless.rrd";
$queues = "-queues.rrd";
$queuesdrop = "-queuedrops.rrd";
$spamd = "-spamd.rrd";
$proc = "-processor.rrd";
$mem = "-memory.rrd";
$rrdtool = "/usr/local/bin/rrdtool";
$netstat = "/usr/bin/netstat";
$awk = "/usr/bin/awk";
$tar = "/usr/bin/tar";
$pfctl = "/sbin/pfctl";
$sysctl = "/sbin/sysctl";
$php = "/usr/local/bin/php";
$top = "/usr/bin/top";
$spamd_gather = "/usr/local/bin/spamd_gather_stats.php";
$ifconfig = "/sbin/ifconfig";
$rrdtrafficinterval = 60;
$rrdqualityinterval = 60;
$rrdwirelessinterval = 60;
$rrdqueuesinterval = 60;
$rrdqueuesdropinterval = 60;
$rrdpacketsinterval = 60;
$rrdstatesinterval = 60;
$rrdspamdinterval = 60;
$rrdlbpoolinterval = 60;
$rrdprocinterval = 60;
$rrdmeminterval = 60;
$trafficvalid = $rrdtrafficinterval * 2;
$qualityvalid = $rrdqualityinterval * 2;
$wirelessvalid = $rrdwirelessinterval * 2;
$queuesvalid = $rrdqueuesinterval * 2;
$queuesdropvalid = $rrdqueuesdropinterval * 2;
$packetsvalid = $rrdpacketsinterval * 2;
$statesvalid = $rrdstatesinterval*2;
$spamdvalid = $rrdspamdinterval * 2;
$lbpoolvalid = $rrdlbpoolinterval * 2;
$procvalid = $rrdlbpoolinterval * 2;
$memvalid = $rrdmeminterval * 2;
/* Asume GigE for now */
$downstream = 125000000;
$upstream = 125000000;
/* read the shaper config */
read_altq_config();
$rrdrestore = "";
$rrdreturn = "";
if (isset ($config['rrd']['enable'])) {
/* create directory if needed */
if (!is_dir("$rrddbpath")) {
mkdir("$rrddbpath", 0755);
}
if ($g['booting']) {
if ($g['platform'] != "pfSense") {
/* restore the databases, if we have one */
if (file_exists("{$g['cf_conf_path']}/rrd.tgz")) {
exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/rrd.tgz", $rrdrestore, $rrdreturn);
if((int)$rrdrestore <> 0) {
log_error("RRD restore failed exited with $rrdreturn, the error is: $rrdrestore[0]\n");
}
}
}
}
/* db update script */
$rrdupdatesh = "#!/bin/sh\n";
$rrdupdatesh .= "\n";
$rrdupdatesh .= "counter=1\n";
$rrdupdatesh .= "while [ \"\$counter\" -ne 0 ]\n";
$rrdupdatesh .= "do\n";
$rrdupdatesh .= "";
$i = 0;
$vfaces = array (
"vlan.?*",
"enc.?*"
);
$ifdescrs = get_interface_list(true, true, $vfaces);
$ifdescrs['enc0']['friendly'] = "ipsec";
$ifdescrs['enc0']['descr'] = "IPsec";
$ifdescrs['enc0']['up'] = true;
foreach ($ifdescrs as $realif => $ifdescr) {
$ifname = $ifdescr['friendly'];
$state = $ifdescr['up'];
/* skip interfaces that do not have a friendly name */
if ("$ifname" == "") {
continue;
}
/* or are down */
if (!$state) {
continue;
}
/* TRAFFIC, set up the rrd file */
if (!file_exists("$rrddbpath$ifname$traffic")) {
/* create rrd file if it does not exist */
log_error("Create RRD database $rrddbpath$ifname$traffic");
$rrdcreate = "$rrdtool create $rrddbpath$ifname$traffic --step $rrdtrafficinterval ";
$rrdcreate .= "DS:in:COUNTER:$trafficvalid:0:$downstream ";
$rrdcreate .= "DS:out:COUNTER:$trafficvalid:0:$upstream ";
$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1440:1500 ";
$rrdcreateoutput = array();
$rrdcreatereturn = "";
$rrdcreatel = exec("$rrdcreate 2>&1", $rrdcreateoutput, $rrdcreatereturn);
if ($rrdcreatereturn != 0) {
log_error("RRD create failed exited with $rrdcreatereturn, the
error is: $rrdcreateoutput[0]\n");
}
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if($g['booting']) {
exec("$rrdtool update $rrddbpath$ifname$traffic N:U:U");
}
$rrdupdatesh .= "\n";
$rrdupdatesh .= "# polling traffic for interface $ifname $realif \n";
$rrdupdatesh .= "$rrdtool update $rrddbpath$ifname$traffic N:\\\n";
if(! is_macaddr(get_interface_mac($realif))) {
$rrdupdatesh .= "`$netstat -nbf link -I {$realif} | $awk '{getline 2;print \$6 \":\" \$9}'`\n";
} else {
$rrdupdatesh .= "`$netstat -nbf link -I {$realif} | $awk '{getline 2;print \$7 \":\" \$10}'`\n";
}
/* PACKETS, set up the rrd file */
if (!file_exists("$rrddbpath$ifname$packets")) {
/* create rrd file if it does not exist */
log_error("Create RRD database $rrddbpath$ifname$packets");
$rrdcreate = "$rrdtool create $rrddbpath$ifname$packets --step $rrdpacketsinterval ";
$rrdcreate .= "DS:in:COUNTER:$packetsvalid:0:$downstream ";
$rrdcreate .= "DS:out:COUNTER:$packetsvalid:0:$upstream ";
$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1440:1500 ";
$rrdcreatel = exec("$rrdcreate 2>&1", $rrdcreateoutput, $rrdcreatereturn);
if ($rrdcreatereturn != 0) {
log_error("RRD create failed exited with $rrdcreatereturn, the
error is: $rrdcreateoutput[0]\n");
}
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if($g['booting']) {
exec("$rrdtool update $rrddbpath$ifname$packets N:U:U");
}
$rrdupdatesh .= "\n";
$rrdupdatesh .= "# polling packets for interface $ifname $realif \n";
$rrdupdatesh .= "$rrdtool update $rrddbpath$ifname$packets N:\\\n";
if(! is_macaddr(get_interface_mac($realif))) {
$rrdupdatesh .= "`$netstat -nbf link -I {$realif} | $awk '{getline 2;print \$4 \":\" \$7}'`\n";
} else {
$rrdupdatesh .= "`$netstat -nbf link -I {$realif} | $awk '{getline 2;print \$5 \":\" \$8}'`\n";
}
/* QUALITY, create link quality database */
/* if the interface has a gateway defined, use it */
if(interface_has_gateway($ifname)) {
if (!file_exists("$rrddbpath$ifname$quality")) {
/* create rrd file if it does not exist */
log_error("Create RRD database $rrddbpath$ifname$quality");
$rrdcreate = "$rrdtool create $rrddbpath$ifname$quality --step $rrdqualityinterval ";
$rrdcreate .= "DS:loss:GAUGE:$qualityvalid:0:100 ";
$rrdcreate .= "DS:roundtrip:GAUGE:$qualityvalid:0:10000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1440:1500 ";
$rrdcreatel = exec("$rrdcreate 2>&1", $rrdcreateoutput, $rrdcreatereturn);
if ($rrdcreatereturn != 0) {
log_error("RRD create failed exited with $rrdcreatereturn, the error is: $rrdcreateoutput[0]\n");
}
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if($g['booting']) {
exec("$rrdtool update $rrddbpath$ifname$quality N:U:U");
}
$numpings = 5;
$monitorip = lookup_gateway_monitor_ip_by_name($config['interfaces'][$ifname]['gateway']);
/* the ping test function. We call this on the last line */
$rrdupdatesh .= "# Quality collector for {$ifname}\n";
$rrdupdatesh .= "get_quality_stats_{$ifname} () {\n";
$rrdupdatesh .= " packetloss_{$ifname}=100\n";
$rrdupdatesh .= " roundtrip_{$ifname}=0\n";
$rrdupdatesh .= " local out_{$ifname}\n";
$rrdupdatesh .= " out_{$ifname}=`ping -c $numpings -q $monitorip`\n";
$rrdupdatesh .= " if [ $? -eq 0 ]; then\n";
$rrdupdatesh .= " packetloss_{$ifname}=`echo \$out_{$ifname} | cut -f18 -d' ' | cut -c -1`\n";
$rrdupdatesh .= " roundtrip_{$ifname}=`echo \$out_{$ifname} | cut -f24 -d' ' | cut -f2 -d'/'`\n";
$rrdupdatesh .= " fi\n";
$rrdupdatesh .= " $rrdtool update $rrddbpath$ifname$quality N:\$packetloss_{$ifname}:\$roundtrip_{$ifname}\n";
$rrdupdatesh .= "}\n\n";
$rrdupdatesh .= "get_quality_stats_{$ifname} &\n\n";
}
/* WIRELESS, set up the rrd file */
if($config['interfaces'][$ifname]['wireless']['mode'] == "bss") {
if (!file_exists("$rrddbpath$ifname$wireless")) {
/* create rrd file if it does not exist */
log_error("Create RRD database $rrddbpath$ifname$wireless");
$rrdcreate = "$rrdtool create $rrddbpath$ifname$wireless --step $rrdwirelessinterval ";
$rrdcreate .= "DS:snr:GAUGE:$wirelessvalid:0:1000 ";
$rrdcreate .= "DS:rate:GAUGE:$wirelessvalid:0:1000 ";
$rrdcreate .= "DS:channel:GAUGE:$wirelessvalid:0:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1440:1500 ";
$rrdcreateoutput = array();
$rrdcreatereturn = "";
$rrdcreatel = exec("$rrdcreate 2>&1", $rrdcreateoutput, $rrdcreatereturn);
if ($rrdcreatereturn != 0) {
log_error("RRD create failed exited with $rrdcreatereturn, the
error is: $rrdcreateoutput[0]\n");
}
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if($g['booting']) {
exec("$rrdtool update $rrddbpath$ifname$wireless N:U:U:U");
}
$rrdupdatesh .= "\n";
$rrdupdatesh .= "# polling wireless for interface $ifname $realif \n";
$rrdupdatesh .= "$rrdtool update $rrddbpath$ifname$wireless N:\\\n";
$rrdupdatesh .= "`$ifconfig {$realif} list ap| $awk 'gsub(\"M\", \"\") {getline 2;print substr(\$5, 0, length(\$5)-2) \":\" $4 \":\" $3}'`\n";
}
/* QUEUES, set up the queues databases */
if ($altq_list_queues[$ifname]) {
$altq =& $altq_list_queues[$ifname];
/* NOTE: Is it worth as its own function?! */
switch ($altq->GetBwscale()) {
case "Gb":
$factor = 1000 * 1000 * 1000;
break;
case "Mb":
$factor = 1000 * 1000;
break;
case "Kb":
$factor = 1000;
break;
case "b":
default:
$factor = 1;
break;
}
$qbandwidth = $altq->GetBandwidth() * $factor;
if ($qbandwidth <=0)
$qbandwidth = 100 * 1000 * 1000; /* 100Mbit */
$qlist =& $altq->get_queue_list($notused);
if (!file_exists("$rrddbpath$ifname$queues")) {
/* create rrd file if it does not exist */
log_error("Create RRD database $rrddbpath$ifname$queues");
$rrdcreate = "$rrdtool create $rrddbpath$ifname$queues --step $rrdqueuesinterval ";
/* loop list of shaper queues */
$q = 0;
foreach ($qlist as $qname => $q) {
$rrdcreate .= "DS:$qname:COUNTER:$queuesvalid:0:$qbandwidth ";
}
$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1440:1500 ";
$rrdcreatel = exec("$rrdcreate 2>&1", $rrdcreateoutput, $rrdcreatereturn);
if ($rrdcreatereturn != 0) {
log_error("RRD create failed exited with $rrdcreatereturn, the
error is: $rrdcreateoutput[0]\n");
}
}
if (!file_exists("$rrddbpath$ifname$queuesdrop")) {
/* create rrd file if it does not exist */
log_error("Create RRD database $rrddbpath$ifname$queuesdrop");
$rrdcreate = "$rrdtool create $rrddbpath$ifname$queuesdrop --step $rrdqueuesdropinterval ";
/* loop list of shaper queues */
$q = 0;
foreach ($qlist as $qname => $q) {
$rrdcreate .= "DS:$qname:COUNTER:$queuesdropvalid:0:$qbandwidth ";
}
$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1440:1500 ";
$rrdcreatel = exec("$rrdcreate 2>&1", $rrdcreateoutput, $rrdcreatereturn);
if ($rrdcreatereturn != 0) {
log_error("RRD create failed exited with $rrdcreatereturn, the error is: $rrdcreateoutput[0]\n");
}
}
if($g['booting']) {
$rrdqcommand = "-t ";
$rrducommand = "N";
$q = 0;
foreach ($qlist as $qname => $q) {
if($q == 0) {
$rrdqcommand .= "{$qname}";
} else {
$rrdqcommand .= ":{$qname}";
}
$q++;
$rrducommand .= ":U";
}
exec("$rrdtool update $rrddbpath$ifname$queues $rrdqcommand $rrducommand");
exec("$rrdtool update $rrddbpath$ifname$queuesdrop $rrdqcommand $rrducommand");
}
/* awk function to gather shaper data */
/* yes, it's special */
$rrdupdatesh .= "` pfctl -vsq -i {$realif} | awk 'BEGIN {printf \"$rrdtool update $rrddbpath$ifname$queues \" } ";
$rrdupdatesh .= "{ ";
$rrdupdatesh .= "if ((\$1 == \"queue\") && ( \$2 ~ /^q/ )) { ";
$rrdupdatesh .= "dsname = dsname \":\" \$2 ; ";
$rrdupdatesh .= "q=1; ";
$rrdupdatesh .= "} ";
$rrdupdatesh .= "else if ((\$4 == \"bytes:\") && ( q == 1 ) ) { ";
$rrdupdatesh .= "dsdata = dsdata \":\" \$5 ; ";
$rrdupdatesh .= "q=0; ";
$rrdupdatesh .= "} ";
$rrdupdatesh .= "} END { ";
$rrdupdatesh .= "dsname = substr(dsname,2); ";
$rrdupdatesh .= "dsdata = substr(dsdata,2); ";
$rrdupdatesh .= "printf \"-t \" dsname \" N:\" dsdata }' ";
$rrdupdatesh .= "dsname=\"\" dsdata=\"\"`\n\n";
$rrdupdatesh .= "` pfctl -vsq -i {$realif} | awk 'BEGIN {printf \"$rrdtool update $rrddbpath$ifname$queuesdrop \" } ";
$rrdupdatesh .= "{ ";
$rrdupdatesh .= "if ((\$1 == \"queue\") && ( \$2 ~ /^q/ )) { ";
$rrdupdatesh .= "dsname = dsname \":\" \$2 ; ";
$rrdupdatesh .= "q=1; ";
$rrdupdatesh .= "} ";
$rrdupdatesh .= "else if ((\$4 == \"bytes:\") && ( q == 1 ) ) { ";
$rrdupdatesh .= "dsdata = dsdata \":\" \$8 ; ";
$rrdupdatesh .= "q=0; ";
$rrdupdatesh .= "} ";
$rrdupdatesh .= "} END { ";
$rrdupdatesh .= "dsname = substr(dsname,2); ";
$rrdupdatesh .= "dsdata = substr(dsdata,2); ";
$rrdupdatesh .= "printf \"-t \" dsname \" N:\" dsdata }' ";
$rrdupdatesh .= "dsname=\"\" dsdata=\"\"`\n\n";
}
}
$i++;
/* System only statistics */
$ifname = "system";
/* STATES, create pf states database */
if(! file_exists("$rrddbpath$ifname$states")) {
/* create rrd file if it does not exist */
log_error("Create RRD database $rrddbpath$ifname$states");
$rrdcreate = "$rrdtool create $rrddbpath$ifname$states --step $rrdstatesinterval ";
$rrdcreate .= "DS:pfrate:GAUGE:$statesvalid:0:10000000 ";
$rrdcreate .= "DS:pfstates:GAUGE:$statesvalid:0:10000000 ";
$rrdcreate .= "DS:pfnat:GAUGE:$statesvalid:0:10000000 ";
$rrdcreate .= "DS:srcip:GAUGE:$statesvalid:0:10000000 ";
$rrdcreate .= "DS:dstip:GAUGE:$statesvalid:0:10000000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1440:1500 ";
$rrdcreatel = exec("$rrdcreate 2>&1", $rrdcreateoutput, $rrdcreatereturn);
if($rrdcreatereturn != 0) {
log_error("RRD create failed exited with $rrdcreatereturn, the
error is: $rrdcreateoutput[0]\n");
}
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if($g['booting']) {
exec("$rrdtool update $rrddbpath$ifname$states N:U:U:U:U:U");
}
/* the pf states gathering function. */
$rrdupdatesh .= "\n";
$rrdupdatesh .= "pfctl_si_out=\"` $pfctl -si > /tmp/pfctl_si_out `\"\n";
$rrdupdatesh .= "pfctl_ss_out=\"` $pfctl -ss > /tmp/pfctl_ss_out`\"\n";
$rrdupdatesh .= "pfrate=\"` cat /tmp/pfctl_si_out | egrep \"inserts|removals\" | awk '{ pfrate = \$3 + pfrate } {print pfrate}'|tail -1 `\"\n";
$rrdupdatesh .= "pfstates=\"` cat /tmp/pfctl_ss_out | egrep -v \"<\\-.*?<\\-|\\->.*?\\->\" | wc -l|sed 's/ //g'`\"\n";
$rrdupdatesh .= "pfnat=\"` cat /tmp/pfctl_ss_out | egrep '<\\-.*?<\\-|\\->.*?\\->' | wc -l|sed 's/ //g' `\"\n";
$rrdupdatesh .= "srcip=\"` cat /tmp/pfctl_ss_out | egrep -v '<\\-.*?<\\-|\\->.*?\\->' | grep '\\->' | awk '{print \$3}' | awk -F: '{print \$1}' | sort -u|wc -l|sed 's/ //g' `\"\n";
$rrdupdatesh .= "dstip=\"` cat /tmp/pfctl_ss_out | egrep -v '<\\-.*?<\\-|\\->.*?\\->' | grep '<\\-' | awk '{print \$3}' | awk -F: '{print \$1}' | sort -u|wc -l|sed 's/ //g' `\"\n";
$rrdupdatesh .= "$rrdtool update $rrddbpath$ifname$states N:\$pfrate:\$pfstates:\$pfnat:\$srcip:\$dstip\n\n";
/* End pf states statistics */
/* CPU, create CPU statistics database */
if(! file_exists("$rrddbpath$ifname$proc")) {
/* create rrd file if it does not exist */
log_error("Create RRD database $rrddbpath$ifname$proc");
$rrdcreate = "$rrdtool create $rrddbpath$ifname$proc --step $rrdprocinterval ";
$rrdcreate .= "DS:user:GAUGE:$procvalid:0:10000000 ";
$rrdcreate .= "DS:nice:GAUGE:$procvalid:0:10000000 ";
$rrdcreate .= "DS:system:GAUGE:$procvalid:0:10000000 ";
$rrdcreate .= "DS:interrupt:GAUGE:$procvalid:0:10000000 ";
$rrdcreate .= "DS:processes:GAUGE:$procvalid:0:10000000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1440:1500 ";
$rrdcreatel = exec("$rrdcreate 2>&1", $rrdcreateoutput, $rrdcreatereturn);
if($rrdcreatereturn != 0) {
log_error("RRD create failed exited with $rrdcreatereturn, the
error is: $rrdcreateoutput[0]\n");
}
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if($g['booting']) {
exec("$rrdtool update $rrddbpath$ifname$proc N:U:U:U:U:U");
}
/* the CPU stats gathering function. */
$rrdupdatesh .= "`$top -d 2 -s 1 0 | $awk '{gsub(/%/, \"\")} BEGIN { ";
$rrdupdatesh .= "printf \"$rrdtool update $rrddbpath$ifname$proc \" } ";
$rrdupdatesh .= "{ if ( \$2 == \"processes:\" ) { ";
$rrdupdatesh .= "processes = \$1; ";
$rrdupdatesh .= "} ";
$rrdupdatesh .= "else if ( \$1 == \"CPU\" ) { ";
$rrdupdatesh .= "user = \$3; ";
$rrdupdatesh .= "nice = \$5; ";
$rrdupdatesh .= "sys = \$7; ";
$rrdupdatesh .= "interrupt = \$9; ";
$rrdupdatesh .= "} ";
$rrdupdatesh .= "} END { ";
$rrdupdatesh .= "printf \"N:\"user\":\"nice\":\"sys\":\"interrupt\":\"processes ";
$rrdupdatesh .= "}'`\n\n";
/* End CPU statistics */
/* Memory, create Memory statistics database */
if(! file_exists("$rrddbpath$ifname$mem")) {
/* create rrd file if it does not exist */
log_error("Create RRD database $rrddbpath$ifname$mem");
$rrdcreate = "$rrdtool create $rrddbpath$ifname$mem --step $rrdmeminterval ";
$rrdcreate .= "DS:active:GAUGE:$memvalid:0:10000000 ";
$rrdcreate .= "DS:inactive:GAUGE:$memvalid:0:10000000 ";
$rrdcreate .= "DS:free:GAUGE:$memvalid:0:10000000 ";
$rrdcreate .= "DS:cache:GAUGE:$memvalid:0:10000000 ";
$rrdcreate .= "DS:wire:GAUGE:$memvalid:0:10000000 ";
$rrdcreate .= "RRA:MIN:0.5:1:1000 ";
$rrdcreate .= "RRA:MIN:0.5:5:1000 ";
$rrdcreate .= "RRA:MIN:0.5:60:1000 ";
$rrdcreate .= "RRA:MIN:0.5:720:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
$rrdcreate .= "RRA:MAX:0.5:1:1000 ";
$rrdcreate .= "RRA:MAX:0.5:5:1000 ";
$rrdcreate .= "RRA:MAX:0.5:60:1000 ";
$rrdcreate .= "RRA:MAX:0.5:720:1000";
$rrdcreatel = exec("$rrdcreate 2>&1", $rrdcreateoutput, $rrdcreatereturn);
if($rrdcreatereturn != 0) {
log_error("RRD create failed exited with $rrdcreatereturn, the
error is: $rrdcreateoutput[0]\n");
}
}
/* enter UNKNOWN values in the RRD so it knows we rebooted. */
if($g['booting']) {
exec("$rrdtool update $rrddbpath$ifname$mem N:U:U:U:U:U");
}
/* the Memory stats gathering function. */
$rrdupdatesh .= "`$sysctl -n vm.stats.vm.v_page_count vm.stats.vm.v_active_count vm.stats.vm.v_inactive_count vm.stats.vm.v_free_count vm.stats.vm.v_cache_count vm.stats.vm.v_wire_count | ";
$rrdupdatesh .= " $awk '{getline active;getline inactive;getline free;getline cache;getline wire;printf \"$rrdtool update $rrddbpath$ifname$mem N:\"";
$rrdupdatesh .= "((active/$0) * 100)\":\"((inactive/$0) * 100)\":\"((free/$0) * 100)\":\"((cache/$0) * 100)\":\"(wire/$0 * 100)}'`\n\n";
/* End Memory statistics */
/* SPAMD, set up the spamd rrd file */
if (isset($config['installedpackages']['spamdsettings']) &&
isset ($config['installedpackages']['spamdsettings']['config'][0]['enablerrd'])) {
/* set up the spamd rrd file */
if (!file_exists("$rrddbpath$ifname$spamd")) {
/* create rrd file if it does not exist */
log_error("Create RRD database $rrddbpath$ifname$spamd");
$rrdcreate = "$rrdtool create $rrddbpath$ifname$spamd --step $rrdspamdinterval ";
$rrdcreate .= "DS:conn:GAUGE:$spamdvalid:0:10000 ";
$rrdcreate .= "DS:time:GAUGE:$spamdvalid:0:86400 ";
$rrdcreate .= "RRA:MIN:0.5:1:1000 ";
$rrdcreate .= "RRA:MIN:0.5:5:1000 ";
$rrdcreate .= "RRA:MIN:0.5:60:1000 ";
$rrdcreate .= "RRA:MIN:0.5:720:1000 ";
$rrdcreate .= "RRA:MIN:0.5:1440:1500 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:5:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:60:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:720:1000 ";
$rrdcreate .= "RRA:AVERAGE:0.5:1440:1500 ";
$rrdcreate .= "RRA:MAX:0.5:1:1000 ";
$rrdcreate .= "RRA:MAX:0.5:5:1000 ";
$rrdcreate .= "RRA:MAX:0.5:60:1000 ";
$rrdcreate .= "RRA:MAX:0.5:720:1000 ";
$rrdcreate .= "RRA:MAX:0.5:1440:1500 ";
$rrdcreatel = exec("$rrdcreate 2>&1", $rrdcreateoutput, $rrdcreatereturn);
if ($rrdcreatereturn != 0) {
log_error("RRD create failed exited with $rrdcreatereturn, the
error is: $rrdcreateoutput[0]\n");
}
}
$rrdupdatesh .= "\n";
$rrdupdatesh .= "# polling spamd for connections and tarpitness \n";
$rrdupdatesh .= "$rrdtool update $rrddbpath$ifname$spamd \\\n";
$rrdupdatesh .= "`$php -q $spamd_gather`\n";
}
/* End System statistics */
$rrdupdatesh .= "sleep 60\n";
$rrdupdatesh .= "done\n";
log_error("Creating rrd update script");
/* write the rrd update script */
$updaterrdscript = "{$g['vardb_path']}/rrd/updaterrd.sh";
$fd = fopen("$updaterrdscript", "w");
fwrite($fd, "$rrdupdatesh");
fclose($fd);
/* kill off traffic collectors */
kill_traffic_collector();
/* start traffic collector */
mwexec_bg("/usr/bin/nice -n20 /bin/sh $updaterrdscript");
} else {
/* kill off traffic collectors */
kill_traffic_collector();
}
if($g['booting'])
echo "done.\n";
}
function kill_traffic_collector() {
mwexec("ps awwwux | grep '/[u]pdaterrd.sh' | awk '{print $2}' | xargs kill");
}
function update_filter_reload_status($text) {
global $g;
config_lock();
$fd = fopen("{$g['varrun_path']}/filter_reload_status", "w");
fwrite($fd, $text);
fclose($fd);
config_unlock();
}
function get_interface_gateway($interface) {
global $config;
/* if wan is requested, return it */
if($interface == "wan")
return str_replace("\n", "", `route -n get default | grep gateway | awk '{ print $2 }'`);
$iflist = get_configured_interface_with_descr();
/*
* XXX: This is silly at first, but we may be called with the interface
* descr for no apparent reason!!!
*/
foreach ($iflist as $ifent => $ifdesc) {
if ($ifent == $interface || $ifdesc == $interface) {
$interface = $ifent;
break;
}
}
$gw = NULL;
$gwcfg = $config['interfaces'][$interface];
if (is_ipaddr($gwcfg['gateway']))
$gw = $gwcfg['gateway'];
else if ($gwcfg['gateway'] <> "") {
if (is_array($config['gateways']['gateway_item']))
foreach($config['gateways']['gateway_item'] as $gateway) {
if($gateway['name'] == $gwcfg['gateway']) {
$gw = $gateway['gateway'];
break;
}
}
}
// for dynamic interfaces we handle them through the $if_router file.
if (!is_ipaddr($gw)) {
$realif = get_real_wan_interface($if);
if (file_exists("{$g['tmp_path']}/{$realif}_router")) {
$gw = file_get_contents("{$g['tmp_path']}/{$realif}_router");
$gw = rtrim($gw);
}
}
/* return gateway */
return $gw;
}
function is_dhcp_server_enabled() {
/* DHCP enabled on any interfaces? */
global $config, $g;
$dhcpdcfg = $config['dhcpd'];
$dhcpdenable = false;
foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
if (isset ($dhcpifconf['enable']) && (($dhcpif == "lan") || (isset ($config['interfaces'][$dhcpif]['enable']) && $config['interfaces'][$dhcpif]['if'] && (!$config['interfaces'][$dhcpif]['bridge']))))
$dhcpdenable = true;
if (isset ($dhcpifconf['enable']) && (($dhcpif == "wan") || (isset ($config['interfaces'][$dhcpif]['enable']) && $config['interfaces'][$dhcpif]['if'] && (!$config['interfaces'][$dhcpif]['bridge']))))
$dhcpdenable = true;
}
return $dhcpdenable;
}
/* return outside interfaces with a gateway */
function get_interfaces_with_gateway() {
global $config;
$ints = array();
$vfaces = array(
'bridge.?*',
'ppp.?*',
'sl.?*',
'gif.?*',
'faith.?*',
'lo.?*',
'ng.?*',
'vlan.?*',
'pflog.?*',
'pfsync.?*',
'enc.?*',
'tun.?*',
'carp.?*'
);
$ifdescrs = get_interface_list("active","physical",$vfaces);
/* loop interfaces, check config for outbound */
foreach ($ifdescrs as $ifdescr => $ifname) {
$friendly = $ifname['friendly'];
switch ($config['interfaces'][$friendly]['ipaddr']) {
case "dhcp":
case "carpdev-dhcp":
case "pppoe":
case "pptp":
$ints[] = $friendly;
break;
default:
if ($config['interfaces'][$friendly]['pointtopoint'])
$ints[] = $friendly;
else if ($config['interfaces'][$friendly]['gateway'] <> "")
$ints[] = $friendly;
break;
}
}
return $ints;
}
/* return true if interface has a gateway */
function interface_has_gateway($friendly) {
$friendly = strtolower($friendly);
if(in_array($friendly, get_interfaces_with_gateway())) {
return true;
} else {
/* extra check for real interface names if it falls through */
$friendly = convert_real_interface_to_friendly_interface_name($friendly);
return(in_array($friendly, get_interfaces_with_gateway()));
}
}
/****f* pfsense-utils/isAjax
* NAME
* isAjax - reports if the request is driven from prototype
* INPUTS
* none
* RESULT
* true/false
******/
function isAjax() {
return isset ($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
//returns interface information
function get_interface_info($ifdescr) {
global $config, $linkinfo, $netstatrninfo;
$ifinfo = array();
/* if list */
$iflist = get_configured_interface_with_descr(false,true);
$found = false;
foreach ($iflist as $if => $ifname) {
if ($ifdescr == $if || $ifdescr == $ifname) {
$ifinfo['hwif'] = $config['interfaces'][$if]['if'];
$ifinfo['if'] = get_real_wan_interface($if);
$found = true;
break;
}
}
if ($found == false)
return;
/* run netstat to determine link info */
unset($linkinfo);
exec("/usr/bin/netstat -I " . $ifinfo['hwif'] . " -nWb -f link", $linkinfo);
$linkinfo = preg_split("/\s+/", $linkinfo[1]);
if (preg_match("/\*$/", $linkinfo[0])) {
$ifinfo['status'] = "down";
} else {
$ifinfo['status'] = "up";
}
if (!strstr($ifinfo['if'],'ovpn')) {
$ifinfo['macaddr'] = $linkinfo[3];
$ifinfo['inpkts'] = $linkinfo[4];
$ifinfo['inerrs'] = $linkinfo[5];
$ifinfo['inbytes'] = $linkinfo[6];
$ifinfo['outpkts'] = $linkinfo[7];
$ifinfo['outerrs'] = $linkinfo[8];
$ifinfo['outbytes'] = $linkinfo[9];
$ifinfo['collisions'] = $linkinfo[10];
} else {
$ifinfo['inpkts'] = $linkinfo[3];
$ifinfo['inbytes'] = $linkinfo[5];
$ifinfo['outpkts'] = $linkinfo[6];
$ifinfo['outbytes'] = $linkinfo[8];
}
$ifconfiginfo = "";
unset($ifconfiginfo);
exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
foreach ($ifconfiginfo as $ici) {
if (preg_match("/inet (\S+)/", $ici, $matches))
$ifinfo['ipaddr'] = $matches[1];
if (preg_match("/netmask (\S+)/", $ici, $matches))
if (preg_match("/^0x/", $matches[1]))
$ifinfo['subnet'] = long2ip(hexdec($matches[1]));
}
switch ($config['interfaces'][$if]['ipaddr']) {
/* DHCP? -> see if dhclient is up */
case "dhcp":
case "carpdev-dhcp":
/* see if dhclient is up */
if (is_dhcp_running($ifinfo['if']) == true)
$ifinfo['dhcplink'] = "up";
else
$ifinfo['dhcplink'] = "down";
break;
/* PPPoE interface? -> get status from virtual interface */
case "pppoe":
unset($linkinfo);
exec("/usr/bin/netstat -I " . $ifinfo['if'] . " -nWb -f link", $linkinfo);
$linkinfo = preg_split("/\s+/", $linkinfo[1]);
if (preg_match("/\*$/", $linkinfo[0])) {
$ifinfo['pppoelink'] = "down";
} else {
/* get PPPoE link status for dial on demand */
$ifinfo['pppoelink'] = "up";
foreach ($ifconfiginfo as $ici) {
if (strpos($ici, 'LINK0') !== false)
$ifinfo['pppoelink'] = "down";
}
}
break;
/* PPTP interface? -> get status from virtual interface */
case "pptp":
unset($linkinfo);
exec("/usr/bin/netstat -I " . $ifinfo['if'] . " -nWb -f link", $linkinfo);
$linkinfo = preg_split("/\s+/", $linkinfo[1]);
if (preg_match("/\*$/", $linkinfo[0])) {
$ifinfo['pptplink'] = "down";
} else {
/* get PPTP link status for dial on demand */
$ifinfo['pptplink'] = "up";
foreach ($ifconfiginfo as $ici) {
if (strpos($ici, 'LINK0') !== false)
$ifinfo['pptplink'] = "down";
}
}
break;
default:
break;
}
if ($ifinfo['status'] == "up") {
/* try to determine media with ifconfig */
unset($ifconfiginfo);
exec("/sbin/ifconfig " . $ifinfo['hwif'], $ifconfiginfo);
$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 (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];
}
}
/* lookup the gateway */
if (interface_has_gateway($if))
$ifinfo['gateway'] = get_interface_gateway($if);
}
$bridge = "";
$bridge = link_int_to_bridge_interface($ifinfo['if']);
if($bridge) {
$bridge_text = `/sbin/ifconfig {$bridge}`;
if(stristr($bridge_text, "blocking") <> false) {
$ifinfo['bridge'] = "blocking - check for ethernet loops";
$ifinfo['bridgeint'] = $bridge;
} else if(stristr($bridge_text, "learning") <> false) {
$ifinfo['bridge'] = "learning";
$ifinfo['bridgeint'] = $bridge;
} else if(stristr($bridge_text, "forwarding") <> false) {
$ifinfo['bridge'] = "forwarding";
$ifinfo['bridgeint'] = $bridge;
}
}
return $ifinfo;
}
//returns cpu speed of processor. Good for determining capabilities of machine
function get_cpu_speed() {
return exec("sysctl hw.clockrate | awk '{ print $2 }'");
}
/* check if the wan interface is up
* Wait for a maximum of 10 seconds
* If the interface is up before then continue
*/
function is_wan_interface_up($interface) {
global $g;
global $config;
$i = 0;
while($i < 10) {
if(get_interface_gateway($interface)) {
return true;
} else {
sleep(1);
}
$i++;
}
return false;
}
function add_hostname_to_watch($hostname) {
if(!is_dir("/var/db/dnscache")) {
mkdir("/var/db/dnscache");
}
if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
$domrecords = array();
$domips = array();
exec("host -t A $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);
}
}
function find_dns_aliases() {
global $config, $g;
foreach((array) $config['aliases']['alias'] as $alias) {
$alias_value = $alias['address'];
$alias_name = $alias['name'];
if(stristr($alias_value, " ")) {
$alias_split = split(" ", $alias_value);
foreach($alias_split as $as) {
if(is_fqdn($as))
add_hostname_to_watch($as);
}
} else {
if(is_fqdn($alias_value))
add_hostname_to_watch($alias_value);
}
}
}
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();
$avail = $memory[0];
/* Be cautious and only allocate 10% of system memory to the state table */
$max_states = (int) ($avail/10)*1000;
return $max_states;
}
function lookup_gateway_ip_by_name($name) {
global $config;
if(is_array($config['gateways'])) {
foreach($config['gateways']['gateway_item'] as $gateway) {
if($gateway['name'] == $name) {
$gatewayip = $gateway['gateway'];
$interfacegw = $gateway['interface'];
return($gatewayip);
}
}
} else {
return(false);
}
}
function lookup_gateway_monitor_ip_by_name($name) {
global $config;
if(is_array($config['gateways'])) {
foreach($config['gateways']['gateway_item'] as $gateway) {
if($gateway['name'] == "$name") {
$monitorip = $gateway['monitor'];
if($monitorip == "")
$monitorip = $gateway['gateway'];
return($monitorip);
}
}
} else {
return(false);
}
}
function lookup_gateway_interface_by_name($name) {
global $config;
if(is_array($config['gateways'])) {
foreach($config['gateways']['gateway_item'] as $gateway) {
if($gateway['name'] == "$name") {
$gatewayip = $gateway['gateway'];
$interfacegw = $gateway['interface'];
return($interfacegw);
}
}
} else {
return(false);
}
}
/****f* pfsense-utils/safe_write_file
* NAME
* safe_write_file - Write a file out atomically
* DESCRIPTION
* safe_write_file() Writes a file out atomically by first writing to a
* temporary file of the same name but ending with the pid of the current
* process, them renaming the temporary file over the original.
* INPUTS
* $filename - string containing the filename of the file to write
* $content - string containing the file content to write to file
* $force_binary - boolean denoting whether we should force binary
* mode writing.
* RESULT
* boolean - true if successful, false if not
******/
function safe_write_file($file, $content, $force_binary) {
$tmp_file = $file . "." . getmypid();
$write_mode = $force_binary ? "wb" : "w";
$fd = fopen($tmp_file, $write_mode);
if (!$fd) {
// Unable to open temporary file for writing
return false;
}
if (!fwrite($fd, $content)) {
// Unable to write to temporary file
fclose($fd);
return false;
}
fclose($fd);
if (!rename($tmp_file, $file)) {
// Unable to move temporary file to original
unlink($tmp_file);
return false;
}
return true;
}
function rule_popup($src,$srcport,$dst,$dstport){
global $config;
$aliases_array = array();
if($config['aliases']['alias'] <> "" and is_array($config['aliases']['alias']))
{
$span_begin = "";
$alias_src_span_begin = "";
$alias_src_span_end = "";
$alias_src_port_span_begin = "";
$alias_src_port_span_end = "";
$alias_dst_span_begin = "";
$alias_dst_span_end = "";
$alias_dst_port_span_begin = "";
$alias_dst_port_span_end = "";
$alias_content_text = "";
foreach($config['aliases']['alias'] as $alias_name)
{
$alias_addresses = explode (" ", $alias_name['address']);
$alias_details = explode ("||", $alias_name['detail']);
$alias_objects_with_details = "";
$counter = 0;
foreach($alias_addresses as $alias_ports_address)
{
$alias_objects_with_details .= $alias_addresses[$counter];
$alias_detail_default = strpos ($alias_details[$counter],"Entry added");
if ($alias_details[$counter] != "" && $alias_detail_default === False){
$alias_objects_with_details .=" - " . $alias_details[$counter];
}
$alias_objects_with_details .= " ";
$counter++;
}
//max character length for caption field
$maxlength = 60;
$alias_descr_substr = $alias_name['descr'];
$alias_content_text = htmlspecialchars($alias_objects_with_details);
$alias_caption = htmlspecialchars($alias_descr_substr . ":");
$strlength = strlen ($alias_caption);
if ($strlength >= $maxlength)
$alias_caption = substr($alias_caption, 0, $maxlength) . "...";
$span_begin = "$alias_caption