pfsense-utils.inc 55.1 KB
Newer Older
Ad Schellevis's avatar
Ad Schellevis committed
1
<?php
2 3

/*
4
 * Copyright (C) 2004-2007 Scott Ullrich <sullrich@gmail.com>
Ad Schellevis's avatar
Ad Schellevis committed
5
 * All rights reserved.
6
 *
Ad Schellevis's avatar
Ad Schellevis committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 */

30
/****f* legacy/have_natpfruleint_access
Ad Schellevis's avatar
Ad Schellevis committed
31 32 33 34 35 36 37 38 39
 * NAME
 *   have_natpfruleint_access
 * INPUTS
 *	none
 * RESULT
 *   returns true if user has access to edit a specific firewall nat port forward interface
 ******/
function have_natpfruleint_access($if) {
	$security_url = "firewall_nat_edit.php?if=". strtolower($if);
40
	if(isAllowedPage($security_url))
Ad Schellevis's avatar
Ad Schellevis committed
41 42 43 44
		return true;
	return false;
}

45
/****f* legacy/have_ruleint_access
Ad Schellevis's avatar
Ad Schellevis committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
 * NAME
 *   have_ruleint_access
 * INPUTS
 *	none
 * RESULT
 *   returns true if user has access to edit a specific firewall interface
 ******/
function have_ruleint_access($if) {
	$security_url = "firewall_rules.php?if=". strtolower($if);
	if(isAllowedPage($security_url))
		return true;
	return false;
}


61
/****f* legacy/is_private_ip
Ad Schellevis's avatar
Ad Schellevis committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
 * NAME
 *   is_private_ip
 * INPUTS
 *	none
 * RESULT
 *   returns true if an ip address is in a private range
 ******/
function is_private_ip($iptocheck) {
	$isprivate = false;
	$ip_private_list=array(
		"10.0.0.0/8",
		"100.64.0.0/10",
		"172.16.0.0/12",
		"192.168.0.0/16",
	);
	foreach($ip_private_list as $private) {
		if(ip_in_subnet($iptocheck,$private)==true)
			$isprivate = true;
	}
	return $isprivate;
}

84
/****f* legacy/get_dns_servers
Ad Schellevis's avatar
Ad Schellevis committed
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
 * NAME
 *   get_dns_servres - get system dns servers
 * INPUTS
 *   $dns_servers - an array of the dns servers
 * RESULT
 *   null
 ******/
function get_dns_servers() {
	$dns_servers = array();
	$dns_s = file("/etc/resolv.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
	foreach($dns_s as $dns) {
		$matches = "";
		if (preg_match("/nameserver (.*)/", $dns, $matches))
			$dns_servers[] = $matches[1];
	}
	return array_unique($dns_servers);
}

103
/****f* legacy/enable_hardware_offloading
Ad Schellevis's avatar
Ad Schellevis committed
104 105 106 107 108 109 110 111 112
 * NAME
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
 * INPUTS
 *   $interface	- string containing the physical interface to work on.
 * RESULT
 *   null
 * NOTES
 *   This function only supports the fxp driver's loadable microcode.
 ******/
113 114 115
function enable_hardware_offloading($interface)
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
116

117
	if (isset($config['system']['do_not_use_nic_microcode'])) {
Ad Schellevis's avatar
Ad Schellevis committed
118
		return;
119
	}
Ad Schellevis's avatar
Ad Schellevis committed
120 121 122

	/* translate wan, lan, opt -> real interface if needed */
	$int = get_real_interface($interface);
123
	if (empty($int)) {
Ad Schellevis's avatar
Ad Schellevis committed
124
		return;
125 126
	}
	$int_family = preg_split('/[0-9]+/', $int);
Ad Schellevis's avatar
Ad Schellevis committed
127 128
	$supported_ints = array('fxp');
	if (in_array($int_family, $supported_ints)) {
129
		if (does_interface_exist($int)) {
130
			legacy_interface_flags($int, 'link0');
131
		}
Ad Schellevis's avatar
Ad Schellevis committed
132 133 134
	}
}

135
/****f* legacy/is_schedule_inuse
Ad Schellevis's avatar
Ad Schellevis committed
136 137 138 139 140 141 142 143 144
 * NAME
 *   checks to see if a schedule is currently in use by a rule
 * INPUTS
 *
 * RESULT
 *   true or false
 * NOTES
 *
 ******/
145 146 147 148 149 150 151
function is_schedule_inuse($schedule)
{
	global $config;

	if ($schedule == '') {
		return false;
	}
Ad Schellevis's avatar
Ad Schellevis committed
152 153

	/* loop through firewall rules looking for schedule in use */
154 155 156
	if (isset($config['filter']['rule'])) {
		foreach ($config['filter']['rule'] as $rule) {
			if ($rule['sched'] == $schedule) {
Ad Schellevis's avatar
Ad Schellevis committed
157
				return true;
158
			}
Ad Schellevis's avatar
Ad Schellevis committed
159
		}
160 161
	}

Ad Schellevis's avatar
Ad Schellevis committed
162 163 164
	return false;
}

165
/****f* legacy/setup_polling
Ad Schellevis's avatar
Ad Schellevis committed
166 167 168 169 170 171 172 173 174
 * NAME
 *   sets up polling
 * INPUTS
 *
 * RESULT
 *   null
 * NOTES
 *
 ******/
175 176 177
function setup_polling()
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
178

179
	if (isset($config['system']['polling'])) {
Ad Schellevis's avatar
Ad Schellevis committed
180
		set_single_sysctl("kern.polling.idle_poll", "1");
181
	} else {
Ad Schellevis's avatar
Ad Schellevis committed
182
		set_single_sysctl("kern.polling.idle_poll", "0");
183
	}
Ad Schellevis's avatar
Ad Schellevis committed
184

185
	if ($config['system']['polling_each_burst']) {
Ad Schellevis's avatar
Ad Schellevis committed
186
		set_single_sysctl("kern.polling.each_burst", $config['system']['polling_each_burst']);
187 188 189
	}

	if ($config['system']['polling_burst_max']) {
Ad Schellevis's avatar
Ad Schellevis committed
190
		set_single_sysctl("kern.polling.burst_max", $config['system']['polling_burst_max']);
191 192 193
	}

	if ($config['system']['polling_user_frac']) {
Ad Schellevis's avatar
Ad Schellevis committed
194
		set_single_sysctl("kern.polling.user_frac", $config['system']['polling_user_frac']);
195
	}
Ad Schellevis's avatar
Ad Schellevis committed
196 197
}

198 199 200 201 202 203 204 205 206 207 208 209
function set_language($lang)
{
	$lang_encoding = $lang . '.UTF-8';
	$textdomain = 'OPNsense';

	putenv('LANG=' . $lang_encoding);
	setlocale(LC_ALL, $lang_encoding);
	textdomain($textdomain);
	bindtextdomain($textdomain, '/usr/local/share/locale');
	bind_textdomain_codeset($textdomain, $lang_encoding);
}

210
/****f* legacy/setup_microcode
Ad Schellevis's avatar
Ad Schellevis committed
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
 * 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);
}

230
/****f* legacy/get_carp_status
Ad Schellevis's avatar
Ad Schellevis committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
 * 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 -");
}


/*
 * 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
 */
314 315 316 317
function after_sync_bump_adv_skew()
{
	global $config;

Ad Schellevis's avatar
Ad Schellevis committed
318 319 320 321 322 323 324 325
	$processed_skew = 1;
	$a_vip = &$config['virtualip']['vip'];
	foreach ($a_vip as $vipent) {
		if($vipent['advskew'] <> "") {
			$processed_skew = 1;
			$vipent['advskew'] = $vipent['advskew']+1;
		}
	}
326 327

	if ($processed_skew == 1) {
Ad Schellevis's avatar
Ad Schellevis committed
328
		write_config(gettext("After synch increase advertising skew"));
329
	}
Ad Schellevis's avatar
Ad Schellevis committed
330 331 332 333 334 335 336 337 338 339
}

/*
 * get_filename_from_url($url): converts a url to its filename.
 */
function get_filename_from_url($url) {
	return basename($url);
}


340
/****f* legacy/WakeOnLan
Ad Schellevis's avatar
Ad Schellevis committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
 * 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("<?xml version=\"1.0\"?>", "", $xmlconfig);
	return $xmlconfig;
}

/*
 *  restore_config_section($section_name, new_contents): restore a configuration section,
 *                                                  and write the configuration out
 *                                                  to disk/cf.
 */
406 407 408 409 410 411 412
function restore_config_section($section_name, $new_contents)
{
	global $config;

	$tmpxml = '/tmp/tmpxml';

	$fout = fopen($tmpxml, 'w');
Ad Schellevis's avatar
Ad Schellevis committed
413 414 415
	fwrite($fout, $new_contents);
	fclose($fout);

416
	$xml = parse_xml_config($tmpxml, null);
Ad Schellevis's avatar
Ad Schellevis committed
417 418
	if ($xml['pfsense']) {
		$xml = $xml['pfsense'];
419
	} elseif ($xml['m0n0wall']) {
Ad Schellevis's avatar
Ad Schellevis committed
420
		$xml = $xml['m0n0wall'];
421 422
	} elseif ($xml['opnsense']) {
		$xml = $xml['opnsense'];
Ad Schellevis's avatar
Ad Schellevis committed
423 424 425 426 427 428 429
	}
	if ($xml[$section_name]) {
		$section_xml = $xml[$section_name];
	} else {
		$section_xml = -1;
	}

430 431
	@unlink($tmpxml);

Ad Schellevis's avatar
Ad Schellevis committed
432 433 434
	if ($section_xml === -1) {
		return false;
	}
435

Ad Schellevis's avatar
Ad Schellevis committed
436 437 438
	$config[$section_name] = &$section_xml;
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
	disable_security_checks();
439

Ad Schellevis's avatar
Ad Schellevis committed
440 441 442 443 444 445 446
	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
447
 *													structure if needed
Ad Schellevis's avatar
Ad Schellevis committed
448
 */
449 450
function merge_config_section($section_name, $new_contents)
{
Ad Schellevis's avatar
Ad Schellevis committed
451
	global $config;
452
	$fname = '/tmp/tmp-' . time();
Ad Schellevis's avatar
Ad Schellevis committed
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
	$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();
	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;
}

/*
 * 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;
}

/*
 * host_firmware_version(): Return the versions used in this install
 */
537 538 539
function host_firmware_version($tocheck = "")
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
540 541 542 543

	$os_version = trim(substr(php_uname("r"), 0, strpos(php_uname("r"), '-')));

	return array(
544
		"firmware" => array("version" => trim(file_get_contents('/usr/local/opnsense/version/opnsense', " \n"))),
Ad Schellevis's avatar
Ad Schellevis committed
545 546 547 548 549 550 551
		"kernel"   => array("version" => $os_version),
		"base"     => array("version" => $os_version),
		"config_version" => $config['version']
	);
}


552
/****f* legacy/strncpy
Ad Schellevis's avatar
Ad Schellevis committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
 * 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;
	}
}

568
/****f* legacy/reload_interfaces_sync
Ad Schellevis's avatar
Ad Schellevis committed
569 570 571 572 573 574 575
 * NAME
 *   reload_interfaces - reload all interfaces
 * INPUTS
 *   none
 * RESULT
 *   none
 ******/
576 577 578
function reload_interfaces_sync()
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
579 580

	/* parse config.xml again */
581
	$config = parse_config();
Ad Schellevis's avatar
Ad Schellevis committed
582 583 584 585 586 587 588 589

	/* enable routing */
	system_routing_enable();

	/* set up interfaces */
	interfaces_configure();
}

590
/****f* legacy/reload_all
Ad Schellevis's avatar
Ad Schellevis committed
591 592 593 594 595 596 597 598
 * NAME
 *   reload_all - triggers a reload of all settings
 *   * INPUTS
 *   none
 * RESULT
 *   none
 ******/
function reload_all() {
Ad Schellevis's avatar
Ad Schellevis committed
599
	configd_run("service reload all", true);
Ad Schellevis's avatar
Ad Schellevis committed
600 601
}

602
/****f* legacy/reload_interfaces
Ad Schellevis's avatar
Ad Schellevis committed
603 604 605 606 607 608 609 610
 * NAME
 *   reload_interfaces - triggers a reload of all interfaces
 * INPUTS
 *   none
 * RESULT
 *   none
 ******/
function reload_interfaces() {
611
	configd_run("interface reload");
Ad Schellevis's avatar
Ad Schellevis committed
612 613
}

614
/****f* legacy/reload_all_sync
Ad Schellevis's avatar
Ad Schellevis committed
615 616 617 618 619 620 621 622
 * NAME
 *   reload_all - reload all settings
 *   * INPUTS
 *   none
 * RESULT
 *   none
 ******/
function reload_all_sync() {
623
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
624 625

	/* parse config.xml again */
626
	$config = parse_config();
Ad Schellevis's avatar
Ad Schellevis committed
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655

	/* 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();

	/* restart sshd */
656
	mwexec_bg('/usr/local/etc/rc.sshd');
Ad Schellevis's avatar
Ad Schellevis committed
657 658

	/* restart webConfigurator if needed */
659
	mwexec_bg('/usr/local/etc/rc.restart_webgui');
Ad Schellevis's avatar
Ad Schellevis committed
660 661
}

662 663
function setup_serial_port($when = 'save', $path = '')
{
664
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
665 666 667 668 669 670 671 672 673 674 675
	$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 = "";

676
	$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : '115200';
677
	if (!is_install_media()) {
Ad Schellevis's avatar
Ad Schellevis committed
678 679 680 681 682 683 684 685 686 687 688
		$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");
				}
			}
Ad Schellevis's avatar
Ad Schellevis committed
689
			if (is_serial_enabled()) {
690
				fwrite($fd, "-S{$serialspeed} -D\n");
Ad Schellevis's avatar
Ad Schellevis committed
691
			}
Ad Schellevis's avatar
Ad Schellevis committed
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
			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)
709 710
					&& (stripos($bcs, "hw.usb.no_pf") === false)
					&& (stripos($bcs, "autoboot_delay") === false))
Ad Schellevis's avatar
Ad Schellevis committed
711 712
					$new_boot_config[] = $bcs;

Ad Schellevis's avatar
Ad Schellevis committed
713
			if (is_serial_enabled()) {
Ad Schellevis's avatar
Ad Schellevis committed
714 715
				$new_boot_config[] = 'boot_multicons="YES"';
				$new_boot_config[] = 'boot_serial="YES"';
716
				$primaryconsole = $config['system']['primaryconsole'];
Ad Schellevis's avatar
Ad Schellevis committed
717 718 719 720 721 722 723 724 725 726 727
				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"';
Frank Wall's avatar
Frank Wall committed
728
			$new_boot_config[] = 'autoboot_delay="3"';
Ad Schellevis's avatar
Ad Schellevis committed
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758

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

759 760
function is_serial_enabled()
{
761
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
762

763
	return isset($config['system']['enableserial']);
Ad Schellevis's avatar
Ad Schellevis committed
764 765
}

766 767
function reload_ttys()
{
768 769
	/* force init(8) to reload /etc/ttys */
	exec('/bin/kill -HUP 1');
Ad Schellevis's avatar
Ad Schellevis committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
}

/* 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;

813
	if (!isset($config['dhcpdv6']) || !is_array($config['dhcpdv6'])) {
Ad Schellevis's avatar
Ad Schellevis committed
814
		$config['dhcpdv6'] = array();
815
	}
Ad Schellevis's avatar
Ad Schellevis committed
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914

	$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
915 916 917
function get_interface_info($ifdescr)
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
918 919 920 921 922 923 924 925 926 927

	$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'];
928 929 930
	if (empty($ifinfo['status'])) {
		$ifinfo['status'] = 'down';
	}
Ad Schellevis's avatar
Ad Schellevis committed
931 932 933 934 935 936
	$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);
937 938 939 940 941 942
	if (isset($ifinfotmp['link0'])) {
		$link0 = 'down';
	}
	$ifinfotmp = legacy_interface_stats($chkif);
	$ifinfo['inerrs'] = $ifinfotmp['input errors'];
	$ifinfo['outerrs'] = $ifinfotmp['output errors'];
Ad Schellevis's avatar
Ad Schellevis committed
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
	$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);
1037
		$mondev = "/tmp/3gstats.{$ifdescr}";
Ad Schellevis's avatar
Ad Schellevis committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
		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;
	}

1069
	if (file_exists("/var/run/{$link_type}_{$ifdescr}.pid")) {
Ad Schellevis's avatar
Ad Schellevis committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
		$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'] = "<b><font color='red'>" . gettext("blocking") . "</font></b> - " . 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;
}

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

1220 1221
function default_state_size()
{
Ad Schellevis's avatar
Ad Schellevis committed
1222 1223 1224
	/* get system memory amount */
	$memory = get_memory();
	$physmem = $memory[0];
1225

Ad Schellevis's avatar
Ad Schellevis committed
1226 1227
	/* Be cautious and only allocate 10% of system memory to the state table */
	$max_states = (int) ($physmem/10)*1000;
1228

Ad Schellevis's avatar
Ad Schellevis committed
1229 1230 1231
	return $max_states;
}

1232 1233
function default_table_entries_size()
{
Ad Schellevis's avatar
Ad Schellevis committed
1234
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1235

Ad Schellevis's avatar
Ad Schellevis committed
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
	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)) {
1276
		log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
Ad Schellevis's avatar
Ad Schellevis committed
1277 1278 1279 1280 1281 1282 1283 1284 1285
		return ($oldcontents);
	} else {
		return false;
	}
}

/*
 * load_crypto() - Load crypto modules if enabled in config.
 */
1286 1287 1288 1289
function load_crypto()
{
	global $config;

Ad Schellevis's avatar
Ad Schellevis committed
1290 1291
	$crypto_modules = array('glxsb', 'aesni');

1292
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules)) {
Ad Schellevis's avatar
Ad Schellevis committed
1293
		return false;
1294
	}
Ad Schellevis's avatar
Ad Schellevis committed
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304

	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
 */
1305 1306 1307 1308
function load_thermal_hardware()
{
	global $config;

Ad Schellevis's avatar
Ad Schellevis committed
1309 1310
	$thermal_hardware_modules = array('coretemp', 'amdtemp');

1311
	if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules)) {
Ad Schellevis's avatar
Ad Schellevis committed
1312
		return false;
1313
	}
Ad Schellevis's avatar
Ad Schellevis committed
1314 1315 1316 1317 1318 1319 1320 1321

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


1322 1323
function get_freebsd_version()
{
Ad Schellevis's avatar
Ad Schellevis committed
1324 1325 1326 1327
	$version = explode(".", php_uname("r"));
	return $version[0];
}

1328 1329
function download_file($url, $destination, $verify_ssl = false, $connect_timeout = 60, $timeout = 0)
{
Ad Schellevis's avatar
Ad Schellevis committed
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
	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);
1345
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/usr/local/opnsense/version/opnsense")));
Ad Schellevis's avatar
Ad Schellevis committed
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384

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

/*
 *   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<script type=\"text/javascript\">";
		echo "\n//<![CDATA[";
1385 1386
		echo "\nthis.document.iform.output.value = \"" . $log . "\";";
		echo "\nthis.document.iform.output.scrollTop = this.document.iform.output.scrollHeight;";
Ad Schellevis's avatar
Ad Schellevis committed
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
		echo "\n//]]>";
		echo "\n</script>";
	}
	/* 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<script type=\"text/javascript\">";
		echo "\n//<![CDATA[";
1404
		echo "\nthis.document.iform.status.value=\"" . $status . "\";";
Ad Schellevis's avatar
Ad Schellevis committed
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
		echo "\n//]]>";
		echo "\n</script>";
	}
	/* 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<script type=\"text/javascript\">";
		echo "\n//<![CDATA[";
1421
		echo "\n$('.progress-bar').css('width', '" . $percent . "%');";
Ad Schellevis's avatar
Ad Schellevis committed
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
		echo "\n//]]>";
		echo "\n</script>";
	} 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);
	}
}

1439 1440
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname)
{
1441 1442 1443
	global $config, $pconfig;

	if (!$origname) {
Ad Schellevis's avatar
Ad Schellevis committed
1444
		return;
1445
	}
Ad Schellevis's avatar
Ad Schellevis committed
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473

	$sectionref = &$config;
	foreach($section as $sectionname) {
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
			$sectionref = &$sectionref[$sectionname];
		else
			return;
	}

	if(is_array($sectionref)) {
		foreach($sectionref as $itemkey => $item) {
			$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) {
				$fieldref = $new_alias_name;
			}
		}
	}
}

1474 1475 1476
function update_alias_url_data()
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490

	$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 */
1491
				$temp_filename = tempnam('/tmp/', 'alias_import');
Ad Schellevis's avatar
Ad Schellevis committed
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
				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) {
Franco Fichtner's avatar
Franco Fichtner committed
1508
						log_error(sprintf(_('Could not process aliases from alias: %s'), $alias_url));
Ad Schellevis's avatar
Ad Schellevis committed
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
						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) {
Franco Fichtner's avatar
Franco Fichtner committed
1552
		log_error(sprintf(_('Could not open %s/aliases for writing!'), $temp_filename));
Ad Schellevis's avatar
Ad Schellevis committed
1553 1554 1555 1556 1557
		return false;
	}
	foreach($files_to_process as $f2p) {
		$tmpfd = @fopen($f2p, 'r');
		if (!$tmpfd) {
Franco Fichtner's avatar
Franco Fichtner committed
1558
			log_error(sprintf(_('The following file could not be read %s from %s'), $f2p, $temp_filename));
Ad Schellevis's avatar
Ad Schellevis committed
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
			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) {
Franco Fichtner's avatar
Franco Fichtner committed
1584
		log_error(sprintf(_('Could not open %s/aliases for writing!'), $temp_filename));
Ad Schellevis's avatar
Ad Schellevis committed
1585 1586 1587 1588 1589
		return false;
	}
	foreach($files_to_process as $f2p) {
		$tmpfd = @fopen($f2p, 'r');
		if (!$tmpfd) {
Franco Fichtner's avatar
Franco Fichtner committed
1590
			log_error(sprintf(_('The following file could not be read %s from %s'), $f2p, $temp_filename));
Ad Schellevis's avatar
Ad Schellevis committed
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
			continue;
		}
		while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE)
			fwrite($fd, $tmpbuf);
		fclose($tmpfd);
		unlink($f2p);
	}
	fclose($fd);
	unset($tmpbuf);

	return true;
}

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
1624
		@unlink("{$urltable_filename}.tmp");
Ad Schellevis's avatar
Ad Schellevis committed
1625
		$verify_ssl = isset($config['system']['checkaliasesurlcert']);
1626
		if (download_file($url, "{$urltable_filename}.tmp", $verify_ssl)) {
Ad Schellevis's avatar
Ad Schellevis committed
1627 1628 1629 1630 1631 1632
			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));
			}
1633 1634
			@unlink("{$urltable_filename}.tmp");
		} else {
Ad Schellevis's avatar
Ad Schellevis committed
1635
			touch($urltable_filename);
1636
		}
Ad Schellevis's avatar
Ad Schellevis committed
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
		return true;
	} else {
		// File exists, and it doesn't need updated.
		return -1;
	}
}


/* This xml 2 array function is courtesy of the php.net comment section on xml_parse.
 * it is roughly 4 times faster then our existing pfSense parser but due to the large
 * size of the RRD xml dumps this is required.
 * The reason we do not use it for pfSense is that it does not know about array fields
 * which causes it to fail on array fields with single items. Possible Todo?
 */
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
{
	if (!function_exists('xml_parser_create'))
	{
		return array ();
	}
	$parser = xml_parser_create('');
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
	xml_parse_into_struct($parser, trim($contents), $xml_values);
	xml_parser_free($parser);
	if (!$xml_values)
		return; //Hmm...
	$xml_array = array ();
	$parents = array ();
	$opened_tags = array ();
	$arr = array ();
	$current = & $xml_array;
	$repeated_tag_index = array ();
	foreach ($xml_values as $data)
	{
		unset ($attributes, $value);
		extract($data);
		$result = array ();
		$attributes_data = array ();
		if (isset ($value))
		{
			if ($priority == 'tag')
				$result = $value;
			else
				$result['value'] = $value;
		}
		if (isset ($attributes) and $get_attributes)
		{
			foreach ($attributes as $attr => $val)
			{
				if ($priority == 'tag')
					$attributes_data[$attr] = $val;
				else
					$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
			}
		}
		if ($type == "open")
		{
			$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);
}

/* 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']);
}


1809
/****f* legacy/load_mac_manufacturer_table
Ad Schellevis's avatar
Ad Schellevis committed
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
 * 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;

}

1835
/****f* legacy/is_ipaddr_configured
Ad Schellevis's avatar
Ad Schellevis committed
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
 * 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) {
1873 1874
			/* Also ignore CARP interfaces, it'll be checked below */
			if ($ignore_if == $if || strstr($ignore_if, "_vip"))
Ad Schellevis's avatar
Ad Schellevis committed
1875 1876 1877 1878 1879 1880 1881 1882
				continue;
			if (strcasecmp($ipaddr, $ilips) == 0)
				return true;
		}
	}

	$interface_list_vips = get_configured_vips_list(true);
	foreach ($interface_list_vips as $id => $vip) {
1883
		if ($ignore_if == $vip['if'])
Ad Schellevis's avatar
Ad Schellevis committed
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
			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;
}



/* 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;

1909
	if(!isset($config['interfaces'][$if]) || !is_array($config['interfaces'][$if])) {
Ad Schellevis's avatar
Ad Schellevis committed
1910
		return false;
1911
	}
Ad Schellevis's avatar
Ad Schellevis committed
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031

	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();
2032
	if (isset($config['pppoes']['pppoe']) && is_array($config['pppoes']['pppoe'])) {
Ad Schellevis's avatar
Ad Schellevis committed
2033 2034 2035 2036 2037 2038 2039 2040 2041
		foreach($config['pppoes']['pppoe'] as $pppoe) {
			if ($pppoe['mode'] == "server") {
				$int = "poes". $pppoe['pppoeid'];
				$iflist[$int] = strtoupper($int);
			}
		}
	}
	return $iflist;
}