pfsense-utils.inc 26.7 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/is_private_ip
Ad Schellevis's avatar
Ad Schellevis committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
 * 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;
}

53
/****f* legacy/get_dns_servers
Ad Schellevis's avatar
Ad Schellevis committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
 * 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);
}

72
/****f* legacy/enable_hardware_offloading
Ad Schellevis's avatar
Ad Schellevis committed
73 74 75 76 77 78 79 80 81
 * 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.
 ******/
82 83 84
function enable_hardware_offloading($interface)
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
85

86
	if (isset($config['system']['do_not_use_nic_microcode'])) {
Ad Schellevis's avatar
Ad Schellevis committed
87
		return;
88
	}
Ad Schellevis's avatar
Ad Schellevis committed
89 90 91

	/* translate wan, lan, opt -> real interface if needed */
	$int = get_real_interface($interface);
92
	if (empty($int)) {
Ad Schellevis's avatar
Ad Schellevis committed
93
		return;
94 95
	}
	$int_family = preg_split('/[0-9]+/', $int);
Ad Schellevis's avatar
Ad Schellevis committed
96 97
	$supported_ints = array('fxp');
	if (in_array($int_family, $supported_ints)) {
98
		if (does_interface_exist($int)) {
99
			legacy_interface_flags($int, 'link0');
100
		}
Ad Schellevis's avatar
Ad Schellevis committed
101 102 103
	}
}

104
/****f* legacy/setup_polling
Ad Schellevis's avatar
Ad Schellevis committed
105 106 107 108 109 110 111 112 113
 * NAME
 *   sets up polling
 * INPUTS
 *
 * RESULT
 *   null
 * NOTES
 *
 ******/
114 115 116
function setup_polling()
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
117

118
	if (isset($config['system']['polling'])) {
Ad Schellevis's avatar
Ad Schellevis committed
119
		set_single_sysctl("kern.polling.idle_poll", "1");
120
	} else {
Ad Schellevis's avatar
Ad Schellevis committed
121
		set_single_sysctl("kern.polling.idle_poll", "0");
122
	}
Ad Schellevis's avatar
Ad Schellevis committed
123 124
}

125
/****f* legacy/setup_microcode
Ad Schellevis's avatar
Ad Schellevis committed
126 127 128 129 130 131 132 133 134 135 136 137 138
 * 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 */
139
	$ifs = legacy_interface_listget();
Ad Schellevis's avatar
Ad Schellevis committed
140

141
	foreach($ifs as $if) {
Ad Schellevis's avatar
Ad Schellevis committed
142
		enable_hardware_offloading($if);
143
	}
Ad Schellevis's avatar
Ad Schellevis committed
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
}

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

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

180
/* KEEP THIS: unbreaks syntax highlighting <?php */
181

Ad Schellevis's avatar
Ad Schellevis committed
182 183 184 185 186
/*
 *  restore_config_section($section_name, new_contents): restore a configuration section,
 *                                                  and write the configuration out
 *                                                  to disk/cf.
 */
187 188 189 190 191 192 193
function restore_config_section($section_name, $new_contents)
{
	global $config;

	$tmpxml = '/tmp/tmpxml';

	$fout = fopen($tmpxml, 'w');
Ad Schellevis's avatar
Ad Schellevis committed
194 195 196
	fwrite($fout, $new_contents);
	fclose($fout);

197
	$xml = parse_xml_config($tmpxml, null);
198
	if (isset($xml['pfsense'])) {
Ad Schellevis's avatar
Ad Schellevis committed
199
		$xml = $xml['pfsense'];
200
	} elseif (isset($xml['m0n0wall'])) {
Ad Schellevis's avatar
Ad Schellevis committed
201
		$xml = $xml['m0n0wall'];
202
	} elseif (isset($xml['opnsense'])) {
203
		$xml = $xml['opnsense'];
Ad Schellevis's avatar
Ad Schellevis committed
204
	}
205
	if (isset($xml[$section_name])) {
Ad Schellevis's avatar
Ad Schellevis committed
206 207 208 209 210
		$section_xml = $xml[$section_name];
	} else {
		$section_xml = -1;
	}

211 212
	@unlink($tmpxml);

Ad Schellevis's avatar
Ad Schellevis committed
213 214 215
	if ($section_xml === -1) {
		return false;
	}
216

Ad Schellevis's avatar
Ad Schellevis committed
217 218 219
	$config[$section_name] = &$section_xml;
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
	disable_security_checks();
220

Ad Schellevis's avatar
Ad Schellevis committed
221 222 223 224 225 226 227
	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
228
 *													structure if needed
Ad Schellevis's avatar
Ad Schellevis committed
229
 */
230 231
function merge_config_section($section_name, $new_contents)
{
Ad Schellevis's avatar
Ad Schellevis committed
232
	global $config;
233
	$fname = '/tmp/tmp-' . time();
Ad Schellevis's avatar
Ad Schellevis committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247
	$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;
}

/*
 * host_firmware_version(): Return the versions used in this install
 */
248
function host_firmware_version()
249 250
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
251 252

	return array(
253
		'firmware' => array('version' => file_get_contents('/usr/local/opnsense/version/opnsense')),
254 255
		'kernel' => array('version' => file_get_contents('/usr/local/opnsense/version/opnsense-update.kernel')),
		'base' => array('version' => file_get_contents('/usr/local/opnsense/version/opnsense-update.base')),
256
		'config_version' => $config['version']
Ad Schellevis's avatar
Ad Schellevis committed
257 258 259
	);
}

260 261
function reload_all()
{
262
	configd_run('service reload all', true);
Ad Schellevis's avatar
Ad Schellevis committed
263 264
}

265 266
function reload_interfaces()
{
267
	configd_run('interface reload');
Ad Schellevis's avatar
Ad Schellevis committed
268 269
}

270
function setup_serial_port($sync = true)
271
{
272
	global $config;
273

274
	$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : '115200';
275 276
	$serial_enabled = isset($config['system']['enableserial']);

277 278
	$loader_conf_file = '/boot/loader.conf';
	$boot_config_file = '/boot.config';
Ad Schellevis's avatar
Ad Schellevis committed
279

280
	if (!is_install_media()) {
281 282 283 284 285 286 287
		/* serial console - write out /boot.config */
		if (file_exists($boot_config_file)) {
			$boot_config = file_get_contents($boot_config_file);
		} else {
			$boot_config = '';
		}

Ad Schellevis's avatar
Ad Schellevis committed
288 289 290 291 292 293 294 295 296 297 298
		$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");
				}
			}
299
			if ($serial_enabled) {
300
				fwrite($fd, "-S{$serialspeed} -D\n");
Ad Schellevis's avatar
Ad Schellevis committed
301
			}
Ad Schellevis's avatar
Ad Schellevis committed
302 303 304
			fclose($fd);
		}

305
		$boot_config = @file_get_contents($loader_conf_file);
Ad Schellevis's avatar
Ad Schellevis committed
306 307 308 309 310 311 312 313 314 315
		$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)
316 317
					&& (stripos($bcs, "hw.usb.no_pf") === false)
					&& (stripos($bcs, "autoboot_delay") === false))
Ad Schellevis's avatar
Ad Schellevis committed
318 319
					$new_boot_config[] = $bcs;

320
			if ($serial_enabled) {
Ad Schellevis's avatar
Ad Schellevis committed
321 322
				$new_boot_config[] = 'boot_multicons="YES"';
				$new_boot_config[] = 'boot_serial="YES"';
323
				$primaryconsole = $config['system']['primaryconsole'];
Ad Schellevis's avatar
Ad Schellevis committed
324 325 326 327 328 329 330 331 332 333 334
				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
335
			$new_boot_config[] = 'autoboot_delay="3"';
Ad Schellevis's avatar
Ad Schellevis committed
336 337 338 339

			file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n");
		}
	}
340

Ad Schellevis's avatar
Ad Schellevis committed
341 342 343 344
	$ttys = file_get_contents("/etc/ttys");
	$ttys_split = explode("\n", $ttys);
	$fd = fopen("/etc/ttys", "w");

345
	$on_off = $serial_enabled ? 'on' : 'off';
Ad Schellevis's avatar
Ad Schellevis committed
346 347 348 349 350 351 352 353

	if (isset($config['system']['disableconsolemenu'])) {
		$console_type = 'Pc';
		$serial_type = 'std.' . $serialspeed;
	} else {
		$console_type = 'al.Pc';
		$serial_type = 'al.' . $serialspeed;
	}
354

Ad Schellevis's avatar
Ad Schellevis committed
355 356 357 358 359 360 361 362
	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");
	}
363

Ad Schellevis's avatar
Ad Schellevis committed
364 365
	unset($on_off, $console_type, $serial_type);
	fclose($fd);
366 367 368 369

	if ($sync) {
		reload_ttys();
	}
Ad Schellevis's avatar
Ad Schellevis committed
370 371
}

372 373
function reload_ttys()
{
374 375
	/* force init(8) to reload /etc/ttys */
	exec('/bin/kill -HUP 1');
Ad Schellevis's avatar
Ad Schellevis committed
376 377 378 379 380 381 382 383 384
}


/* Any PPPoE servers enabled? */
function is_pppoe_server_enabled() {
	global $config;

	$pppoeenable = false;

385
	if (!isset($config['pppoes']['pppoe']) || !is_array($config['pppoes']['pppoe']))
Ad Schellevis's avatar
Ad Schellevis committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
		return false;

	foreach ($config['pppoes']['pppoe'] as $pppoes)
		if ($pppoes['mode'] == 'server')
			$pppoeenable = true;

	return $pppoeenable;
}

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

/*
 * load_crypto() - Load crypto modules if enabled in config.
 */
448 449 450 451
function load_crypto()
{
	global $config;

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

454
	if (!isset($config['system']['crypto_hardware']) || !in_array($config['system']['crypto_hardware'], $crypto_modules)) {
Ad Schellevis's avatar
Ad Schellevis committed
455
		return false;
456
	}
Ad Schellevis's avatar
Ad Schellevis committed
457 458 459 460 461 462 463 464 465 466

	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
 */
467 468 469 470
function load_thermal_hardware()
{
	global $config;

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

473
	if (!isset($config['system']['thermal_hardware']) || !in_array($config['system']['thermal_hardware'], $thermal_hardware_modules)) {
Ad Schellevis's avatar
Ad Schellevis committed
474
		return false;
475
	}
Ad Schellevis's avatar
Ad Schellevis committed
476 477 478 479 480 481 482

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

483 484
function download_file($url, $destination, $verify_ssl = false, $connect_timeout = 60, $timeout = 0)
{
Ad Schellevis's avatar
Ad Schellevis committed
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
	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);
500
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/usr/local/opnsense/version/opnsense")));
Ad Schellevis's avatar
Ad Schellevis committed
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

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

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

527 528
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname)
{
529 530 531
	global $config, $pconfig;

	if (!$origname) {
Ad Schellevis's avatar
Ad Schellevis committed
532
		return;
533
	}
Ad Schellevis's avatar
Ad Schellevis committed
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574

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


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) {
575
		log_error(sprintf(gettext('Could not open %s/aliases for writing!'), $temp_filename));
Ad Schellevis's avatar
Ad Schellevis committed
576 577 578 579 580
		return false;
	}
	foreach($files_to_process as $f2p) {
		$tmpfd = @fopen($f2p, 'r');
		if (!$tmpfd) {
581
			log_error(sprintf(gettext('The following file could not be read %s from %s'), $f2p, $temp_filename));
Ad Schellevis's avatar
Ad Schellevis committed
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
			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) {
607
		log_error(sprintf(gettext('Could not open %s/aliases for writing!'), $temp_filename));
Ad Schellevis's avatar
Ad Schellevis committed
608 609 610 611 612
		return false;
	}
	foreach($files_to_process as $f2p) {
		$tmpfd = @fopen($f2p, 'r');
		if (!$tmpfd) {
613
			log_error(sprintf(gettext('The following file could not be read %s from %s'), $f2p, $temp_filename));
Ad Schellevis's avatar
Ad Schellevis committed
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
			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
647
		@unlink("{$urltable_filename}.tmp");
Ad Schellevis's avatar
Ad Schellevis committed
648
		$verify_ssl = isset($config['system']['checkaliasesurlcert']);
649
		if (download_file($url, "{$urltable_filename}.tmp", $verify_ssl)) {
Ad Schellevis's avatar
Ad Schellevis committed
650 651 652 653 654 655
			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));
			}
656 657
			@unlink("{$urltable_filename}.tmp");
		} else {
Ad Schellevis's avatar
Ad Schellevis committed
658
			touch($urltable_filename);
659
		}
Ad Schellevis's avatar
Ad Schellevis committed
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 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 759 760 761 762 763 764 765 766 767 768 769 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 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
		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']);
}


832
/****f* legacy/load_mac_manufacturer_table
Ad Schellevis's avatar
Ad Schellevis committed
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
 * 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;

}

858
/****f* legacy/is_ipaddr_configured
Ad Schellevis's avatar
Ad Schellevis committed
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
 * 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) {
896 897
			/* Also ignore CARP interfaces, it'll be checked below */
			if ($ignore_if == $if || strstr($ignore_if, "_vip"))
Ad Schellevis's avatar
Ad Schellevis committed
898 899 900 901 902 903 904 905
				continue;
			if (strcasecmp($ipaddr, $ilips) == 0)
				return true;
		}
	}

	$interface_list_vips = get_configured_vips_list(true);
	foreach ($interface_list_vips as $id => $vip) {
906
		if ($ignore_if == $vip['if'])
Ad Schellevis's avatar
Ad Schellevis committed
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
			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;

932
	if(!isset($config['interfaces'][$if]) || !is_array($config['interfaces'][$if])) {
Ad Schellevis's avatar
Ad Schellevis committed
933
		return false;
934 935
	} elseif (!isset($config['interfaces'][$if]['ipaddrv6'])) {
		return (0);
936
	}
Ad Schellevis's avatar
Ad Schellevis committed
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956

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