Project

General

Profile

Download (82.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/****h* pfSense/pfsense-utils
3
 * NAME
4
 *   pfsense-utils.inc - Utilities specific to pfSense
5
 * DESCRIPTION
6
 *   This include contains various pfSense specific functions.
7
 * HISTORY
8
 *   $Id$
9
 ******
10
 *
11
 * Copyright (C) 2004-2007 Scott Ullrich (sullrich@gmail.com)
12
 * All rights reserved.
13
 * Redistribution and use in source and binary forms, with or without
14
 * modification, are permitted provided that the following conditions are met:
15
 *
16
 * 1. Redistributions of source code must retain the above copyright notice,
17
 * this list of conditions and the following disclaimer.
18
 *
19
 * 2. Redistributions in binary form must reproduce the above copyright
20
 * notice, this list of conditions and the following disclaimer in the
21
 * documentation and/or other materials provided with the distribution.
22
 *
23
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
24
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
25
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
27
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31
 * RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 */
35

    
36
/*
37
	pfSense_BUILDER_BINARIES:	/sbin/sysctl	/sbin/ifconfig	/sbin/pfctl	/usr/local/bin/php /usr/bin/netstat
38
	pfSense_BUILDER_BINARIES:	/bin/df	/usr/bin/grep	/usr/bin/awk	/bin/rm	/usr/sbin/pwd_mkdb	/usr/bin/host
39
	pfSense_BUILDER_BINARIES:	/sbin/kldload
40
	pfSense_MODULE:	utils
41
*/
42

    
43
/****f* pfsense-utils/have_natpfruleint_access
44
 * NAME
45
 *   have_natpfruleint_access
46
 * INPUTS
47
 *	none
48
 * RESULT
49
 *   returns true if user has access to edit a specific firewall nat port forward interface
50
 ******/
51
function have_natpfruleint_access($if) {
52
	$security_url = "firewall_nat_edit.php?if=". strtolower($if);
53
	if(isAllowedPage($security_url, $allowed))
54
		return true;
55
	return false;
56
}
57

    
58
/****f* pfsense-utils/have_ruleint_access
59
 * NAME
60
 *   have_ruleint_access
61
 * INPUTS
62
 *	none
63
 * RESULT
64
 *   returns true if user has access to edit a specific firewall interface
65
 ******/
66
function have_ruleint_access($if) {
67
	$security_url = "firewall_rules.php?if=". strtolower($if);
68
	if(isAllowedPage($security_url))
69
		return true;
70
	return false;
71
}
72

    
73
/****f* pfsense-utils/does_url_exist
74
 * NAME
75
 *   does_url_exist
76
 * INPUTS
77
 *	none
78
 * RESULT
79
 *   returns true if a url is available
80
 ******/
81
function does_url_exist($url) {
82
	$fd = fopen("$url","r");
83
	if($fd) {
84
		fclose($fd);
85
		return true;
86
	} else {
87
		return false;
88
	}
89
}
90

    
91
/****f* pfsense-utils/is_private_ip
92
 * NAME
93
 *   is_private_ip
94
 * INPUTS
95
 *	none
96
 * RESULT
97
 *   returns true if an ip address is in a private range
98
 ******/
99
function is_private_ip($iptocheck) {
100
	$isprivate = false;
101
	$ip_private_list=array(
102
		"10.0.0.0/8",
103
		"100.64.0.0/10",
104
		"172.16.0.0/12",
105
		"192.168.0.0/16",
106
	);
107
	foreach($ip_private_list as $private) {
108
		if(ip_in_subnet($iptocheck,$private)==true)
109
			$isprivate = true;
110
	}
111
	return $isprivate;
112
}
113

    
114
/****f* pfsense-utils/get_tmp_file
115
 * NAME
116
 *   get_tmp_file
117
 * INPUTS
118
 *	none
119
 * RESULT
120
 *   returns a temporary filename
121
 ******/
122
function get_tmp_file() {
123
	global $g;
124
	return "{$g['tmp_path']}/tmp-" . time();
125
}
126

    
127
/****f* pfsense-utils/get_dns_servers
128
 * NAME
129
 *   get_dns_servres - get system dns servers
130
 * INPUTS
131
 *   $dns_servers - an array of the dns servers
132
 * RESULT
133
 *   null
134
 ******/
135
function get_dns_servers() {
136
	$dns_servers = array();
137
	$dns_s = file("/etc/resolv.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
138
	foreach($dns_s as $dns) {
139
		$matches = "";
140
		if (preg_match("/nameserver (.*)/", $dns, $matches))
141
			$dns_servers[] = $matches[1];
142
	}
143
	return array_unique($dns_servers);
144
}
145

    
146
/****f* pfsense-utils/enable_hardware_offloading
147
 * NAME
148
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
149
 * INPUTS
150
 *   $interface	- string containing the physical interface to work on.
151
 * RESULT
152
 *   null
153
 * NOTES
154
 *   This function only supports the fxp driver's loadable microcode.
155
 ******/
156
function enable_hardware_offloading($interface) {
157
	global $g, $config;
158

    
159
	if(isset($config['system']['do_not_use_nic_microcode']))
160
		return;
161

    
162
	/* translate wan, lan, opt -> real interface if needed */
163
	$int = get_real_interface($interface);
164
	if(empty($int))
165
		return;
166
	$int_family = preg_split("/[0-9]+/", $int);
167
	$supported_ints = array('fxp');
168
	if (in_array($int_family, $supported_ints)) {
169
		if(does_interface_exist($int))
170
			pfSense_interface_flags($int, IFF_LINK0);
171
	}
172

    
173
	return;
174
}
175

    
176
/****f* pfsense-utils/interface_supports_polling
177
 * NAME
178
 *   checks to see if an interface supports polling according to man polling
179
 * INPUTS
180
 *
181
 * RESULT
182
 *   true or false
183
 * NOTES
184
 *
185
 ******/
186
function interface_supports_polling($iface) {
187
	$opts = pfSense_get_interface_addresses($iface);
188
	if (is_array($opts) && isset($opts['caps']['polling']))
189
		return true;
190

    
191
	return false;
192
}
193

    
194
/****f* pfsense-utils/is_alias_inuse
195
 * NAME
196
 *   checks to see if an alias is currently in use by a rule
197
 * INPUTS
198
 *
199
 * RESULT
200
 *   true or false
201
 * NOTES
202
 *
203
 ******/
204
function is_alias_inuse($alias) {
205
	global $g, $config;
206

    
207
	if($alias == "") return false;
208
	/* loop through firewall rules looking for alias in use */
209
	if(is_array($config['filter']['rule']))
210
		foreach($config['filter']['rule'] as $rule) {
211
			if($rule['source']['address'])
212
				if($rule['source']['address'] == $alias)
213
					return true;
214
			if($rule['destination']['address'])
215
				if($rule['destination']['address'] == $alias)
216
					return true;
217
		}
218
	/* loop through nat rules looking for alias in use */
219
	if(is_array($config['nat']['rule']))
220
		foreach($config['nat']['rule'] as $rule) {
221
			if($rule['target'] && $rule['target'] == $alias)
222
				return true;
223
			if($rule['source']['address'] && $rule['source']['address'] == $alias)
224
				return true;
225
			if($rule['destination']['address'] && $rule['destination']['address'] == $alias)
226
				return true;
227
		}
228
	return false;
229
}
230

    
231
/****f* pfsense-utils/is_schedule_inuse
232
 * NAME
233
 *   checks to see if a schedule is currently in use by a rule
234
 * INPUTS
235
 *
236
 * RESULT
237
 *   true or false
238
 * NOTES
239
 *
240
 ******/
241
function is_schedule_inuse($schedule) {
242
	global $g, $config;
243

    
244
	if($schedule == "") return false;
245
	/* loop through firewall rules looking for schedule in use */
246
	if(is_array($config['filter']['rule']))
247
		foreach($config['filter']['rule'] as $rule) {
248
			if($rule['sched'] == $schedule)
249
				return true;
250
		}
251
	return false;
252
}
253

    
254
/****f* pfsense-utils/setup_polling
255
 * NAME
256
 *   sets up polling
257
 * INPUTS
258
 *
259
 * RESULT
260
 *   null
261
 * NOTES
262
 *
263
 ******/
264
function setup_polling() {
265
	global $g, $config;
266

    
267
	if (isset($config['system']['polling']))
268
		mwexec("/sbin/sysctl kern.polling.idle_poll=1");
269
	else
270
		mwexec("/sbin/sysctl kern.polling.idle_poll=0");
271

    
272
	if($config['system']['polling_each_burst'])
273
		mwexec("/sbin/sysctl kern.polling.each_burst={$config['system']['polling_each_burst']}");
274
	if($config['system']['polling_burst_max'])
275
		mwexec("/sbin/sysctl kern.polling.burst_max={$config['system']['polling_burst_max']}");
276
	if($config['system']['polling_user_frac'])
277
		mwexec("/sbin/sysctl kern.polling.user_frac={$config['system']['polling_user_frac']}");
278
}
279

    
280
/****f* pfsense-utils/setup_microcode
281
 * NAME
282
 *   enumerates all interfaces and calls enable_hardware_offloading which
283
 *   enables a NIC's supported hardware features.
284
 * INPUTS
285
 *
286
 * RESULT
287
 *   null
288
 * NOTES
289
 *   This function only supports the fxp driver's loadable microcode.
290
 ******/
291
function setup_microcode() {
292

    
293
	/* if list */
294
	$ifs = get_interface_arr();
295

    
296
	foreach($ifs as $if)
297
		enable_hardware_offloading($if);
298
}
299

    
300
/****f* pfsense-utils/get_carp_status
301
 * NAME
302
 *   get_carp_status - Return whether CARP is enabled or disabled.
303
 * RESULT
304
 *   boolean	- true if CARP is enabled, false if otherwise.
305
 ******/
306
function get_carp_status() {
307
	/* grab the current status of carp */
308
	$status = `/sbin/sysctl -n net.inet.carp.allow`;
309
	return (intval($status) > 0);
310
}
311

    
312
/*
313
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
314

    
315
 */
316
function convert_ip_to_network_format($ip, $subnet) {
317
	$ipsplit = explode('.', $ip);
318
	$string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
319
	return $string;
320
}
321

    
322
/*
323
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
324
 */
325
function get_carp_interface_status($carpinterface) {
326
	$carp_query = "";
327

    
328
	/* XXX: Need to fidn a better way for this! */
329
	list ($interface, $vhid) = explode("_vip", $carpinterface);
330
	$interface = get_real_interface($interface);
331
	exec("/sbin/ifconfig $interface | /usr/bin/grep -v grep | /usr/bin/grep carp: | /usr/bin/grep 'vhid {$vhid}'", $carp_query);
332
	foreach($carp_query as $int) {
333
		if(stristr($int, "MASTER"))
334
			return gettext("MASTER");
335
		if(stristr($int, "BACKUP"))
336
			return gettext("BACKUP");
337
		if(stristr($int, "INIT"))
338
			return gettext("INIT");
339
	}
340
	return;
341
}
342

    
343
/*
344
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
345
 */
346
function get_pfsync_interface_status($pfsyncinterface) {
347
	if (!does_interface_exist($pfsyncinterface))
348
		return;
349

    
350
	return exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'");
351
}
352

    
353
/*
354
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
355
 */
356
function add_rule_to_anchor($anchor, $rule, $label) {
357
	mwexec("echo " . escapeshellarg($rule) . " | /sbin/pfctl -a " . escapeshellarg($anchor) . ":" . escapeshellarg($label) . " -f -");
358
}
359

    
360
/*
361
 * remove_text_from_file
362
 * remove $text from file $file
363
 */
364
function remove_text_from_file($file, $text) {
365
	if(!file_exists($file) && !is_writable($file))
366
		return;
367
	$filecontents = file_get_contents($file);
368
	$text = str_replace($text, "", $filecontents);
369
	@file_put_contents($file, $text);
370
}
371

    
372
/*
373
 * add_text_to_file($file, $text): adds $text to $file.
374
 * replaces the text if it already exists.
375
 */
376
function add_text_to_file($file, $text, $replace = false) {
377
	if(file_exists($file) and is_writable($file)) {
378
		$filecontents = file($file);
379
		$filecontents = array_map('rtrim', $filecontents);
380
		array_push($filecontents, $text);
381
		if ($replace)
382
			$filecontents = array_unique($filecontents);
383

    
384
		$file_text = implode("\n", $filecontents);
385

    
386
		@file_put_contents($file, $file_text);
387
		return true;
388
	}
389
	return false;
390
}
391

    
392
/*
393
 *   after_sync_bump_adv_skew(): create skew values by 1S
394
 */
395
function after_sync_bump_adv_skew() {
396
	global $config, $g;
397
	$processed_skew = 1;
398
	$a_vip = &$config['virtualip']['vip'];
399
	foreach ($a_vip as $vipent) {
400
		if($vipent['advskew'] <> "") {
401
			$processed_skew = 1;
402
			$vipent['advskew'] = $vipent['advskew']+1;
403
		}
404
	}
405
	if($processed_skew == 1)
406
		write_config(gettext("After synch increase advertising skew"));
407
}
408

    
409
/*
410
 * get_filename_from_url($url): converts a url to its filename.
411
 */
412
function get_filename_from_url($url) {
413
	return basename($url);
414
}
415

    
416
/*
417
 *   get_dir: return an array of $dir
418
 */
419
function get_dir($dir) {
420
	$dir_array = array();
421
	$d = dir($dir);
422
	while (false !== ($entry = $d->read())) {
423
		array_push($dir_array, $entry);
424
	}
425
	$d->close();
426
	return $dir_array;
427
}
428

    
429
/****f* pfsense-utils/WakeOnLan
430
 * NAME
431
 *   WakeOnLan - Wake a machine up using the wake on lan format/protocol
432
 * RESULT
433
 *   true/false - true if the operation was successful
434
 ******/
435
function WakeOnLan($addr, $mac)
436
{
437
	$addr_byte = explode(':', $mac);
438
	$hw_addr = '';
439

    
440
	for ($a=0; $a < 6; $a++)
441
		$hw_addr .= chr(hexdec($addr_byte[$a]));
442

    
443
	$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
444

    
445
	for ($a = 1; $a <= 16; $a++)
446
		$msg .= $hw_addr;
447

    
448
	// send it to the broadcast address using UDP
449
	$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
450
	if ($s == false) {
451
		log_error(gettext("Error creating socket!"));
452
		log_error(sprintf(gettext("Error code is '%1\$s' - %2\$s"), socket_last_error($s), socket_strerror(socket_last_error($s))));
453
	} else {
454
		// setting a broadcast option to socket:
455
		$opt_ret =  socket_set_option($s, 1, 6, TRUE);
456
		if($opt_ret < 0)
457
			log_error(sprintf(gettext("setsockopt() failed, error: %s"), strerror($opt_ret)));
458
		$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
459
		socket_close($s);
460
		log_error(sprintf(gettext('Magic Packet sent (%1$s) to {%2$s} MAC=%3$s'), $e, $addr, $mac));
461
		return true;
462
	}
463

    
464
	return false;
465
}
466

    
467
/*
468
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
469
 *					 Useful for finding paths and stripping file extensions.
470
 */
471
function reverse_strrchr($haystack, $needle) {
472
	if (!is_string($haystack))
473
		return;
474
	return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
475
}
476

    
477
/*
478
 *  backup_config_section($section): returns as an xml file string of
479
 *                                   the configuration section
480
 */
481
function backup_config_section($section_name) {
482
	global $config;
483
	$new_section = &$config[$section_name];
484
	/* generate configuration XML */
485
	$xmlconfig = dump_xml_config($new_section, $section_name);
486
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
487
	return $xmlconfig;
488
}
489

    
490
/*
491
 *  restore_config_section($section_name, new_contents): restore a configuration section,
492
 *                                                  and write the configuration out
493
 *                                                  to disk/cf.
494
 */
495
function restore_config_section($section_name, $new_contents) {
496
	global $config, $g;
497
	conf_mount_rw();
498
	$fout = fopen("{$g['tmp_path']}/tmpxml","w");
499
	fwrite($fout, $new_contents);
500
	fclose($fout);
501

    
502
	$xml = parse_xml_config($g['tmp_path'] . "/tmpxml", null);
503
	if ($xml['pfsense']) {
504
		$xml = $xml['pfsense'];
505
	}
506
	else if ($xml['m0n0wall']) {
507
		$xml = $xml['m0n0wall'];
508
	}
509
	if ($xml[$section_name]) {
510
		$section_xml = $xml[$section_name];
511
	} else {
512
		$section_xml = -1;
513
	}
514

    
515
	@unlink($g['tmp_path'] . "/tmpxml");
516
	if ($section_xml === -1) {
517
		return false;
518
	}
519
	$config[$section_name] = &$section_xml;
520
	if(file_exists("{$g['tmp_path']}/config.cache"))
521
		unlink("{$g['tmp_path']}/config.cache");
522
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
523
	disable_security_checks();
524
	conf_mount_ro();
525
	return true;
526
}
527

    
528
/*
529
 *  merge_config_section($section_name, new_contents):   restore a configuration section,
530
 *                                                  and write the configuration out
531
 *                                                  to disk/cf.  But preserve the prior
532
 * 													structure if needed
533
 */
534
function merge_config_section($section_name, $new_contents) {
535
	global $config;
536
	conf_mount_rw();
537
	$fname = get_tmp_filename();
538
	$fout = fopen($fname, "w");
539
	fwrite($fout, $new_contents);
540
	fclose($fout);
541
	$section_xml = parse_xml_config($fname, $section_name);
542
	$config[$section_name] = $section_xml;
543
	unlink($fname);
544
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
545
	disable_security_checks();
546
	conf_mount_ro();
547
	return;
548
}
549

    
550
/*
551
 * http_post($server, $port, $url, $vars): does an http post to a web server
552
 *                                         posting the vars array.
553
 * written by nf@bigpond.net.au
554
 */
555
function http_post($server, $port, $url, $vars) {
556
	$user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
557
	$urlencoded = "";
558
	while (list($key,$value) = each($vars))
559
		$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
560
	$urlencoded = substr($urlencoded,0,-1);
561
	$content_length = strlen($urlencoded);
562
	$headers = "POST $url HTTP/1.1
563
Accept: */*
564
Accept-Language: en-au
565
Content-Type: application/x-www-form-urlencoded
566
User-Agent: $user_agent
567
Host: $server
568
Connection: Keep-Alive
569
Cache-Control: no-cache
570
Content-Length: $content_length
571

    
572
";
573

    
574
	$errno = "";
575
	$errstr = "";
576
	$fp = fsockopen($server, $port, $errno, $errstr);
577
	if (!$fp) {
578
		return false;
579
	}
580

    
581
	fputs($fp, $headers);
582
	fputs($fp, $urlencoded);
583

    
584
	$ret = "";
585
	while (!feof($fp))
586
		$ret.= fgets($fp, 1024);
587
	fclose($fp);
588

    
589
	return $ret;
590
}
591

    
592
/*
593
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
594
 */
595
if (!function_exists('php_check_syntax')){
596
	global $g;
597
	function php_check_syntax($code_to_check, &$errormessage){
598
		return false;
599
		$fout = fopen("{$g['tmp_path']}/codetocheck.php","w");
600
		$code = $_POST['content'];
601
		$code = str_replace("<?php", "", $code);
602
		$code = str_replace("?>", "", $code);
603
		fwrite($fout, "<?php\n\n");
604
		fwrite($fout, $code_to_check);
605
		fwrite($fout, "\n\n?>\n");
606
		fclose($fout);
607
		$command = "/usr/local/bin/php -l {$g['tmp_path']}/codetocheck.php";
608
		$output = exec_command($command);
609
		if (stristr($output, "Errors parsing") == false) {
610
			echo "false\n";
611
			$errormessage = '';
612
			return(false);
613
		} else {
614
			$errormessage = $output;
615
			return(true);
616
		}
617
	}
618
}
619

    
620
/*
621
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
622
 */
623
if (!function_exists('php_check_syntax')){
624
	function php_check_syntax($code_to_check, &$errormessage){
625
		return false;
626
		$command = "/usr/local/bin/php -l " . escapeshellarg($code_to_check);
627
		$output = exec_command($command);
628
		if (stristr($output, "Errors parsing") == false) {
629
			echo "false\n";
630
			$errormessage = '';
631
			return(false);
632
		} else {
633
			$errormessage = $output;
634
			return(true);
635
		}
636
	}
637
}
638

    
639
/*
640
 * rmdir_recursive($path,$follow_links=false)
641
 * Recursively remove a directory tree (rm -rf path)
642
 * This is for directories _only_
643
 */
644
function rmdir_recursive($path,$follow_links=false) {
645
	$to_do = glob($path);
646
	if(!is_array($to_do)) $to_do = array($to_do);
647
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
648
		if(file_exists($workingdir)) {
649
			if(is_dir($workingdir)) {
650
				$dir = opendir($workingdir);
651
				while ($entry = readdir($dir)) {
652
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
653
						unlink("$workingdir/$entry");
654
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
655
						rmdir_recursive("$workingdir/$entry");
656
				}
657
				closedir($dir);
658
				rmdir($workingdir);
659
			} elseif (is_file($workingdir)) {
660
				unlink($workingdir);
661
			}
662
		}
663
	}
664
	return;
665
}
666

    
667
/*
668
 * call_pfsense_method(): Call a method exposed by the pfsense.org XMLRPC server.
669
 */
670
function call_pfsense_method($method, $params, $timeout = 0) {
671
	global $g, $config;
672

    
673
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
674
	$xmlrpc_path = $g['xmlrpcpath'];
675
	
676
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
677
	$ip = gethostbyname($xmlrpcfqdn);
678
	if($ip == $xmlrpcfqdn)
679
		return false;
680

    
681
	$msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params)));
682
	$port = 0;
683
	$proxyurl = "";
684
	$proxyport = 0;
685
	$proxyuser = "";
686
	$proxypass = "";
687
	if (!empty($config['system']['proxyurl']))
688
		$proxyurl = $config['system']['proxyurl'];
689
	if (!empty($config['system']['proxyport']) && is_numeric($config['system']['proxyport']))
690
		$proxyport = $config['system']['proxyport'];
691
	if (!empty($config['system']['proxyuser']))
692
		$proxyuser = $config['system']['proxyuser'];
693
	if (!empty($config['system']['proxypass']))
694
		$proxypass = $config['system']['proxypass'];
695
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url, $port, $proxyurl, $proxyport, $proxyuser, $proxypass);
696
	// If the ALT PKG Repo has a username/password set, use it.
697
	if($config['system']['altpkgrepo']['username'] &&
698
	   $config['system']['altpkgrepo']['password']) {
699
		$username = $config['system']['altpkgrepo']['username'];
700
		$password = $config['system']['altpkgrepo']['password'];
701
		$cli->setCredentials($username, $password);
702
	}
703
	$resp = $cli->send($msg, $timeout);
704
	if(!is_object($resp)) {
705
		log_error(sprintf(gettext("XMLRPC communication error: %s"), $cli->errstr));
706
		return false;
707
	} elseif($resp->faultCode()) {
708
		log_error(sprintf(gettext('XMLRPC request failed with error %1$s: %2$s'), $resp->faultCode(), $resp->faultString()));
709
		return false;
710
	} else {
711
		return XML_RPC_Decode($resp->value());
712
	}
713
}
714

    
715
/*
716
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
717
 */
718
function check_firmware_version($tocheck = "all", $return_php = true) {
719
	global $g, $config;
720
	
721
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
722
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
723
	$ip = gethostbyname($xmlrpcfqdn);
724
	if($ip == $xmlrpcfqdn)
725
		return false;
726

    
727
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
728
		"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
729
		"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
730
		"platform" => trim(file_get_contents('/etc/platform')),
731
		"config_version" => $config['version']
732
		);
733
	if($tocheck == "all") {
734
		$params = $rawparams;
735
	} else {
736
		foreach($tocheck as $check) {
737
			$params['check'] = $rawparams['check'];
738
			$params['platform'] = $rawparams['platform'];
739
		}
740
	}
741
	if($config['system']['firmware']['branch'])
742
		$params['branch'] = $config['system']['firmware']['branch'];
743

    
744
	/* XXX: What is this method? */
745
	if(!($versions = call_pfsense_method('pfsense.get_firmware_version', $params))) {
746
		return false;
747
	} else {
748
		$versions["current"] = $params;
749
	}
750

    
751
	return $versions;
752
}
753

    
754
/*
755
 * host_firmware_version(): Return the versions used in this install
756
 */
757
function host_firmware_version($tocheck = "") {
758
	global $g, $config;
759

    
760
	return array(
761
		"firmware" => array("version" => trim(file_get_contents('/etc/version', " \n"))),
762
		"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel', " \n"))),
763
		"base"     => array("version" => trim(file_get_contents('/etc/version_base', " \n"))),
764
		"platform" => trim(file_get_contents('/etc/platform', " \n")),
765
		"config_version" => $config['version']
766
	);
767
}
768

    
769
function get_disk_info() {
770
	$diskout = "";
771
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $2, $3, $4, $5 }'", $diskout);
772
	return explode(' ', $diskout[0]);
773
}
774

    
775
/****f* pfsense-utils/strncpy
776
 * NAME
777
 *   strncpy - copy strings
778
 * INPUTS
779
 *   &$dst, $src, $length
780
 * RESULT
781
 *   none
782
 ******/
783
function strncpy(&$dst, $src, $length) {
784
	if (strlen($src) > $length) {
785
		$dst = substr($src, 0, $length);
786
	} else {
787
		$dst = $src;
788
	}
789
}
790

    
791
/****f* pfsense-utils/reload_interfaces_sync
792
 * NAME
793
 *   reload_interfaces - reload all interfaces
794
 * INPUTS
795
 *   none
796
 * RESULT
797
 *   none
798
 ******/
799
function reload_interfaces_sync() {
800
	global $config, $g;
801

    
802
	if($g['debug'])
803
		log_error(gettext("reload_interfaces_sync() is starting."));
804

    
805
	/* parse config.xml again */
806
	$config = parse_config(true);
807

    
808
	/* enable routing */
809
	system_routing_enable();
810
	if($g['debug'])
811
		log_error(gettext("Enabling system routing"));
812

    
813
	if($g['debug'])
814
		log_error(gettext("Cleaning up Interfaces"));
815

    
816
	/* set up interfaces */
817
	interfaces_configure();
818
}
819

    
820
/****f* pfsense-utils/reload_all
821
 * NAME
822
 *   reload_all - triggers a reload of all settings
823
 *   * INPUTS
824
 *   none
825
 * RESULT
826
 *   none
827
 ******/
828
function reload_all() {
829
	send_event("service reload all");
830
}
831

    
832
/****f* pfsense-utils/reload_interfaces
833
 * NAME
834
 *   reload_interfaces - triggers a reload of all interfaces
835
 * INPUTS
836
 *   none
837
 * RESULT
838
 *   none
839
 ******/
840
function reload_interfaces() {
841
	send_event("interface all reload");
842
}
843

    
844
/****f* pfsense-utils/reload_all_sync
845
 * NAME
846
 *   reload_all - reload all settings
847
 *   * INPUTS
848
 *   none
849
 * RESULT
850
 *   none
851
 ******/
852
function reload_all_sync() {
853
	global $config, $g;
854

    
855
	$g['booting'] = false;
856

    
857
	/* parse config.xml again */
858
	$config = parse_config(true);
859

    
860
	/* set up our timezone */
861
	system_timezone_configure();
862

    
863
	/* set up our hostname */
864
	system_hostname_configure();
865

    
866
	/* make hosts file */
867
	system_hosts_generate();
868

    
869
	/* generate resolv.conf */
870
	system_resolvconf_generate();
871

    
872
	/* enable routing */
873
	system_routing_enable();
874

    
875
	/* set up interfaces */
876
	interfaces_configure();
877

    
878
	/* start dyndns service */
879
	services_dyndns_configure();
880

    
881
	/* configure cron service */
882
	configure_cron();
883

    
884
	/* start the NTP client */
885
	system_ntp_configure();
886

    
887
	/* sync pw database */
888
	conf_mount_rw();
889
	unlink_if_exists("/etc/spwd.db.tmp");
890
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
891
	conf_mount_ro();
892

    
893
	/* restart sshd */
894
	send_event("service restart sshd");
895

    
896
	/* restart webConfigurator if needed */
897
	send_event("service restart webgui");
898
}
899

    
900
function auto_login() {
901
	global $config;
902

    
903
	if(isset($config['system']['disableconsolemenu']))
904
		$status = false;
905
	else
906
		$status = true;
907

    
908
	$gettytab = file_get_contents("/etc/gettytab");
909
	$getty_split = explode("\n", $gettytab);
910
	$getty_update_needed = false;
911
	$getty_search_str = ":ht:np:sp#115200";
912
	$getty_al_str = ":al=root:";
913
	$getty_al_search_str = $getty_search_str . $getty_al_str;
914
	/* Check if gettytab is already OK, if so then do not rewrite it. */
915
	foreach($getty_split as $gs) {
916
		if(stristr($gs, $getty_search_str)) {
917
			if($status == true) {
918
				if(!stristr($gs, $getty_al_search_str)) {
919
					$getty_update_needed = true;
920
				}
921
			} else {
922
				if(stristr($gs, $getty_al_search_str)) {
923
					$getty_update_needed = true;
924
				}
925
			}
926
		}
927
	}
928

    
929
	if (!$getty_update_needed) {
930
		return;
931
	}
932

    
933
	conf_mount_rw();
934
	$fd = false;
935
	$tries = 0;
936
	while (!$fd && $tries < 100) {
937
		$fd = fopen("/etc/gettytab", "w");
938
		$tries++;
939

    
940
	}
941
	if (!$fd) {
942
		conf_mount_ro();
943
		if ($status) {
944
			log_error(gettext("Enabling auto login was not possible."));
945
		} else {
946
			log_error(gettext("Disabling auto login was not possible."));
947
		}
948
		return;
949
	}
950
	foreach($getty_split as $gs) {
951
		if(stristr($gs, $getty_search_str)) {
952
			if($status == true) {
953
				fwrite($fd, "	".$getty_al_search_str."\n");
954
			} else {
955
				fwrite($fd, "	".$getty_search_str."\n");
956
			}
957
		} else {
958
			fwrite($fd, "{$gs}\n");
959
		}
960
	}
961
	fclose($fd);
962

    
963
	if ($status) {
964
		log_error(gettext("Enabled console auto login, console menu is NOT password protected."));
965
	} else {
966
		log_error(gettext("Disabled console auto login, console menu is password protected."));
967
	}
968

    
969
	conf_mount_ro();
970
}
971

    
972
function setup_serial_port($when="save", $path="") {
973
	global $g, $config;
974
	conf_mount_rw();
975
	$prefix = "";
976
	if (($when == "upgrade") && (!empty($path)) && is_dir($path.'/boot/'))
977
		$prefix = "/tmp/{$path}";
978
	$boot_config_file = "{$path}/boot.config";
979
	$loader_conf_file = "{$path}/boot/loader.conf";
980
	/* serial console - write out /boot.config */
981
	if(file_exists($boot_config_file))
982
		$boot_config = file_get_contents($boot_config_file);
983
	else
984
		$boot_config = "";
985

    
986
	if(($g['platform'] != "cdrom") && ($g['platform'] != "nanobsd")) {
987
		$boot_config_split = explode("\n", $boot_config);
988
		$fd = fopen($boot_config_file,"w");
989
		if($fd) {
990
			foreach($boot_config_split as $bcs) {
991
				if(stristr($bcs, "-D")) {
992
					/* DONT WRITE OUT, WE'LL DO IT LATER */
993
				} else {
994
					if($bcs <> "")
995
						fwrite($fd, "{$bcs}\n");
996
				}
997
			}
998
			if(isset($config['system']['enableserial']) || $g['enableserial_force']) {
999
				fwrite($fd, "-D");
1000
			}
1001
			fclose($fd);
1002
		}
1003
	}
1004
	if($g['platform'] != "cdrom") {
1005
		/* serial console - write out /boot/loader.conf */
1006
		if ($when == "upgrade")
1007
			system("echo \"Reading {$loader_conf_file}...\" >> /conf/upgrade_log.txt");
1008
		$boot_config = file_get_contents($loader_conf_file);
1009
		$boot_config_split = explode("\n", $boot_config);
1010
		if(count($boot_config_split) > 0) {
1011
			$new_boot_config = array();
1012
			// Loop through and only add lines that are not empty, and which
1013
			//  do not contain a console directive.
1014
			foreach($boot_config_split as $bcs)
1015
				if(!empty($bcs)
1016
					&& (stripos($bcs, "console") === false)
1017
					&& (stripos($bcs, "boot_multicons") === false)
1018
					&& (stripos($bcs, "boot_serial") === false)
1019
					&& (stripos($bcs, "hw.usb.no_pf") === false))
1020
					$new_boot_config[] = $bcs;
1021

    
1022
			$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "9600";
1023
			if(isset($config['system']['enableserial']) || $g['enableserial_force']) {
1024
				$new_boot_config[] = 'boot_multicons="YES"';
1025
				$new_boot_config[] = 'boot_serial="YES"';
1026
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1027
				$primaryconsole = isset($g['primaryconsole_force']) ? $g['primaryconsole_force'] : $config['system']['primaryconsole'];
1028
				switch ($primaryconsole) {
1029
					case "video":
1030
						$new_boot_config[] = 'console="vidconsole,comconsole"';
1031
						break;
1032
					case "serial":
1033
					default:
1034
						$new_boot_config[] = 'console="comconsole,vidconsole"';
1035
				}
1036
			} elseif ($g['platform'] == "nanobsd") {
1037
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1038
			}
1039

    
1040
			$new_boot_config[] = 'hw.usb.no_pf="1"';
1041

    
1042
			file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n");
1043
		}
1044
	}
1045
	$ttys = file_get_contents("/etc/ttys");
1046
	$ttys_split = explode("\n", $ttys);
1047
	$fd = fopen("/etc/ttys", "w");
1048
	foreach($ttys_split as $tty) {
1049
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
1050
			if(isset($config['system']['enableserial']) || $g['enableserial_force']) {
1051
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
1052
			} else {
1053
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
1054
			}
1055
		} else {
1056
			fwrite($fd, $tty . "\n");
1057
		}
1058
	}
1059
	fclose($fd);
1060
	auto_login();
1061

    
1062
	conf_mount_ro();
1063
	return;
1064
}
1065

    
1066
function print_value_list($list, $count = 10, $separator = ",") {
1067
	$list = implode($separator, array_slice($list, 0, $count));
1068
	if(count($list) < $count) {
1069
		$list .= ".";
1070
	} else {
1071
		$list .= "...";
1072
	}
1073
	return $list;
1074
}
1075

    
1076
/* DHCP enabled on any interfaces? */
1077
function is_dhcp_server_enabled() {
1078
	global $config;
1079

    
1080
	if (!is_array($config['dhcpd']))
1081
		return false;
1082

    
1083
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1084
		if (isset($dhcpifconf['enable']) && !empty($config['interfaces'][$dhcpif]))
1085
			return true;
1086
	}
1087

    
1088
	return false;
1089
}
1090

    
1091
/* DHCP enabled on any interfaces? */
1092
function is_dhcpv6_server_enabled() {
1093
	global $config;
1094

    
1095
	if (is_array($config['interfaces'])) {
1096
		foreach ($config['interfaces'] as $ifcfg) {
1097
			if (isset($ifcfg['enable']) && !empty($ifcfg['track6-interface']))
1098
				return true;
1099
		}
1100
	}
1101

    
1102
	if (!is_array($config['dhcpdv6']))
1103
		return false;
1104

    
1105
	foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1106
		if (isset($dhcpv6ifconf['enable']) && !empty($config['interfaces'][$dhcpv6if]))
1107
			return true;
1108
	}
1109

    
1110
	return false;
1111
}
1112

    
1113
/* radvd enabled on any interfaces? */
1114
function is_radvd_enabled() {
1115
	global $config;
1116

    
1117
	if (!is_array($config['dhcpdv6']))
1118
		$config['dhcpdv6'] = array();
1119

    
1120
	$dhcpdv6cfg = $config['dhcpdv6'];
1121
	$Iflist = get_configured_interface_list();
1122

    
1123
	/* handle manually configured DHCP6 server settings first */
1124
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1125
		if(!isset($config['interfaces'][$dhcpv6if]['enable']))
1126
			continue;
1127

    
1128
		if(!isset($dhcpv6ifconf['ramode']))
1129
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1130

    
1131
		if($dhcpv6ifconf['ramode'] == "disabled")
1132
			continue;
1133

    
1134
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1135
		if(!is_ipaddrv6($ifcfgipv6))
1136
			continue;
1137

    
1138
		return true;
1139
	}
1140

    
1141
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
1142
	foreach ($Iflist as $if => $ifdescr) {
1143
		if(!isset($config['interfaces'][$if]['track6-interface']))
1144
			continue;
1145
		if(!isset($config['interfaces'][$if]['enable']))
1146
			continue;
1147

    
1148
		$ifcfgipv6 = get_interface_ipv6($if);
1149
		if(!is_ipaddrv6($ifcfgipv6))
1150
			continue;
1151

    
1152
		$ifcfgsnv6 = get_interface_subnetv6($if);
1153
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1154

    
1155
		if(!is_ipaddrv6($subnetv6))
1156
			continue;
1157

    
1158
		return true;
1159
	}
1160

    
1161
	return false;
1162
}
1163

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

    
1168
	$pppoeenable = false;
1169

    
1170
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1171
		return false;
1172

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

    
1177
	return $pppoeenable;
1178
}
1179

    
1180
function convert_seconds_to_hms($sec){
1181
	$min=$hrs=0;
1182
	if ($sec != 0){
1183
		$min = floor($sec/60);
1184
		$sec %= 60;
1185
	}
1186
	if ($min != 0){
1187
		$hrs = floor($min/60);
1188
		$min %= 60;
1189
	}
1190
	if ($sec < 10)
1191
		$sec = "0".$sec;
1192
	if ($min < 10)
1193
		$min = "0".$min;
1194
	if ($hrs < 10)
1195
		$hrs = "0".$hrs;
1196
	$result = $hrs.":".$min.":".$sec;
1197
	return $result;
1198
}
1199

    
1200
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1201

    
1202
function get_ppp_uptime($port){
1203
	if (file_exists("/conf/{$port}.log")){
1204
		$saved_time = file_get_contents("/conf/{$port}.log");
1205
		$uptime_data = explode("\n",$saved_time);
1206
		$sec=0;
1207
		foreach($uptime_data as $upt) {
1208
			$sec += substr($upt, 1 + strpos($upt, " "));
1209
		}
1210
		return convert_seconds_to_hms($sec);
1211
	} else {
1212
		$total_time = gettext("No history data found!");
1213
		return $total_time;
1214
	}
1215
}
1216

    
1217
//returns interface information
1218
function get_interface_info($ifdescr) {
1219
	global $config, $g;
1220

    
1221
	$ifinfo = array();
1222
	if (empty($config['interfaces'][$ifdescr]))
1223
		return;
1224
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1225
	$ifinfo['if'] = get_real_interface($ifdescr);
1226

    
1227
	$chkif = $ifinfo['if'];
1228
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1229
	$ifinfo['status'] = $ifinfotmp['status'];
1230
	if (empty($ifinfo['status']))
1231
		$ifinfo['status'] = "down";
1232
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1233
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1234
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1235
	$ifinfo['linklocal'] = get_interface_linklocal($ifdescr);
1236
	$ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr);
1237
	$ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr);
1238
	if (isset($ifinfotmp['link0']))
1239
		$link0 = "down";
1240
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1241
	// $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1242
	// $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1243
	$ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1244
	$ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1245
	$ifinfo['collisions'] = $ifinfotmp['collisions'];
1246

    
1247
	/* Use pfctl for non wrapping 64 bit counters */
1248
	/* Pass */
1249
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1250
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1251
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1252
	$pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]);
1253
	$pf_out6_pass = preg_split("/ +/", $pfctlstats[9]);
1254
	$in4_pass = $pf_in4_pass[5];
1255
	$out4_pass = $pf_out4_pass[5];
1256
	$in4_pass_packets = $pf_in4_pass[3];
1257
	$out4_pass_packets = $pf_out4_pass[3];
1258
	$in6_pass = $pf_in6_pass[5];
1259
	$out6_pass = $pf_out6_pass[5];
1260
	$in6_pass_packets = $pf_in6_pass[3];
1261
	$out6_pass_packets = $pf_out6_pass[3];
1262
	$ifinfo['inbytespass'] = $in4_pass + $in6_pass;
1263
	$ifinfo['outbytespass'] = $out4_pass + $out6_pass;
1264
	$ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets;
1265
	$ifinfo['outpktspass'] = $out4_pass_packets + $out6_pass_packets;
1266

    
1267
	/* Block */
1268
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1269
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1270
	$pf_in6_block = preg_split("/ +/", $pfctlstats[8]);
1271
	$pf_out6_block = preg_split("/ +/", $pfctlstats[10]);
1272
	$in4_block = $pf_in4_block[5];
1273
	$out4_block = $pf_out4_block[5];
1274
	$in4_block_packets = $pf_in4_block[3];
1275
	$out4_block_packets = $pf_out4_block[3];
1276
	$in6_block = $pf_in6_block[5];
1277
	$out6_block = $pf_out6_block[5];
1278
	$in6_block_packets = $pf_in6_block[3];
1279
	$out6_block_packets = $pf_out6_block[3];
1280
	$ifinfo['inbytesblock'] = $in4_block + $in6_block;
1281
	$ifinfo['outbytesblock'] = $out4_block + $out6_block;
1282
	$ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets;
1283
	$ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets;
1284

    
1285
	$ifinfo['inbytes'] = $in4_pass + $in6_pass;
1286
	$ifinfo['outbytes'] = $out4_pass + $out6_pass;
1287
	$ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets;
1288
	$ifinfo['outpkts'] = $out4_pass_packets + $out6_pass_packets;
1289

    
1290
	$ifconfiginfo = "";
1291
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1292
	switch ($link_type) {
1293
	/* DHCP? -> see if dhclient is up */
1294
	case "dhcp":
1295
		/* see if dhclient is up */
1296
		if (find_dhclient_process($ifinfo['if']) <> "")
1297
			$ifinfo['dhcplink'] = "up";
1298
		else
1299
			$ifinfo['dhcplink'] = "down";
1300

    
1301
		break;
1302
	/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1303
	case "pppoe":
1304
	case "pptp":
1305
	case "l2tp":
1306
		if ($ifinfo['status'] == "up" && !isset($link0))
1307
			/* get PPPoE link status for dial on demand */
1308
			$ifinfo["{$link_type}link"] = "up";
1309
		else
1310
			$ifinfo["{$link_type}link"] = "down";
1311

    
1312
		break;
1313
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1314
	case "ppp":
1315
		if ($ifinfo['status'] == "up")
1316
			$ifinfo['ppplink'] = "up";
1317
		else
1318
			$ifinfo['ppplink'] = "down" ;
1319

    
1320
		if (empty($ifinfo['status']))
1321
			$ifinfo['status'] = "down";
1322

    
1323
		if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1324
			foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1325
				if ($config['interfaces'][$ifdescr]['if'] == $ppp['if'])
1326
					break;
1327
			}
1328
		}
1329
		$dev = $ppp['ports'];
1330
		if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev))
1331
			break;
1332
		if (!file_exists($dev)) {
1333
			$ifinfo['nodevice'] = 1;
1334
			$ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?");
1335
		}
1336

    
1337
		$usbmodemoutput = array();
1338
		exec("usbconfig", $usbmodemoutput);
1339
		$mondev = "{$g['tmp_path']}/3gstats.{$ifdescr}";
1340
		if(file_exists($mondev)) {
1341
			$cellstats = file($mondev);
1342
			/* skip header */
1343
			$a_cellstats = explode(",", $cellstats[1]);
1344
			if(preg_match("/huawei/i", implode("\n", $usbmodemoutput))) {
1345
				$ifinfo['cell_rssi'] = huawei_rssi_to_string($a_cellstats[1]);
1346
				$ifinfo['cell_mode'] = huawei_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1347
				$ifinfo['cell_simstate'] = huawei_simstate_to_string($a_cellstats[10]);
1348
				$ifinfo['cell_service'] = huawei_service_to_string(trim($a_cellstats[11]));
1349
			}
1350
			if(preg_match("/zte/i", implode("\n", $usbmodemoutput))) {
1351
				$ifinfo['cell_rssi'] = zte_rssi_to_string($a_cellstats[1]);
1352
				$ifinfo['cell_mode'] = zte_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1353
				$ifinfo['cell_simstate'] = zte_simstate_to_string($a_cellstats[10]);
1354
				$ifinfo['cell_service'] = zte_service_to_string(trim($a_cellstats[11]));
1355
			}
1356
			$ifinfo['cell_upstream'] = $a_cellstats[4];
1357
			$ifinfo['cell_downstream'] = trim($a_cellstats[5]);
1358
			$ifinfo['cell_sent'] = $a_cellstats[6];
1359
			$ifinfo['cell_received'] = trim($a_cellstats[7]);
1360
			$ifinfo['cell_bwupstream'] = $a_cellstats[8];
1361
			$ifinfo['cell_bwdownstream'] = trim($a_cellstats[9]);
1362
		}
1363
		// Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over!
1364
		if (isset($ppp['uptime']))
1365
			$ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")";
1366
		break;
1367
	default:
1368
		break;
1369
	}
1370

    
1371
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1372
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1373
		$ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec);
1374
	}
1375

    
1376
	if ($ifinfo['status'] == "up") {
1377
		/* try to determine media with ifconfig */
1378
		unset($ifconfiginfo);
1379
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1380
		$wifconfiginfo = array();
1381
		if(is_interface_wireless($ifdescr)) {
1382
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1383
			array_shift($wifconfiginfo);
1384
		}
1385
		$matches = "";
1386
		foreach ($ifconfiginfo as $ici) {
1387

    
1388
			/* don't list media/speed for wireless cards, as it always
1389
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1390
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1391
				$ifinfo['media'] = $matches[1];
1392
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1393
				$ifinfo['media'] = $matches[1];
1394
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1395
				$ifinfo['media'] = $matches[1];
1396
			}
1397

    
1398
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1399
				if ($matches[1] != "active")
1400
					$ifinfo['status'] = $matches[1];
1401
				if($ifinfo['status'] == gettext("running"))
1402
					$ifinfo['status'] = gettext("up");
1403
			}
1404
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1405
				$ifinfo['channel'] = $matches[1];
1406
			}
1407
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1408
				if ($matches[1][0] == '"')
1409
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1410
				else
1411
					$ifinfo['ssid'] = $matches[1];
1412
			}
1413
			if (preg_match("/laggproto (.*)$/", $ici, $matches)) {
1414
				$ifinfo['laggproto'] = $matches[1];
1415
			}
1416
			if (preg_match("/laggport: (.*)$/", $ici, $matches)) {
1417
				$ifinfo['laggport'][] = $matches[1];
1418
			}
1419
		}
1420
		foreach($wifconfiginfo as $ici) {
1421
			$elements = preg_split("/[ ]+/i", $ici);
1422
			if ($elements[0] != "") {
1423
				$ifinfo['bssid'] = $elements[0];
1424
			}
1425
			if ($elements[3] != "") {
1426
				$ifinfo['rate'] = $elements[3];
1427
			}
1428
			if ($elements[4] != "") {
1429
				$ifinfo['rssi'] = $elements[4];
1430
			}
1431

    
1432
		}
1433
		/* lookup the gateway */
1434
		if (interface_has_gateway($ifdescr)) {
1435
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1436
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1437
		}
1438
	}
1439

    
1440
	$bridge = "";
1441
	$bridge = link_interface_to_bridge($ifdescr);
1442
	if($bridge) {
1443
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1444
		if(stristr($bridge_text, "blocking") <> false) {
1445
			$ifinfo['bridge'] = "<b><font color='red'>" . gettext("blocking") . "</font></b> - " . gettext("check for ethernet loops");
1446
			$ifinfo['bridgeint'] = $bridge;
1447
		} else if(stristr($bridge_text, "learning") <> false) {
1448
			$ifinfo['bridge'] = gettext("learning");
1449
			$ifinfo['bridgeint'] = $bridge;
1450
		} else if(stristr($bridge_text, "forwarding") <> false) {
1451
			$ifinfo['bridge'] = gettext("forwarding");
1452
			$ifinfo['bridgeint'] = $bridge;
1453
		}
1454
	}
1455

    
1456
	return $ifinfo;
1457
}
1458

    
1459
//returns cpu speed of processor. Good for determining capabilities of machine
1460
function get_cpu_speed() {
1461
	return exec("/sbin/sysctl -n hw.clockrate");
1462
}
1463

    
1464
function get_uptime_sec() {
1465
	$boottime = "";
1466
	$matches = "";
1467
	exec("/sbin/sysctl -n kern.boottime", $boottime);
1468
	preg_match("/sec = (\d+)/", $boottime[0], $matches);
1469
	$boottime = $matches[1];
1470
	if(intval($boottime) == 0)
1471
		return 0;
1472

    
1473
	$uptime = time() - $boottime;
1474
	return $uptime;
1475
}
1476

    
1477
function add_hostname_to_watch($hostname) {
1478
	if(!is_dir("/var/db/dnscache")) {
1479
		mkdir("/var/db/dnscache");
1480
	}
1481
	$result = array();
1482
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1483
		$domrecords = array();
1484
		$domips = array();
1485
		exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1486
		if($rethost == 0) {
1487
			foreach($domrecords as $domr) {
1488
				$doml = explode(" ", $domr);
1489
				$domip = $doml[3];
1490
				/* fill array with domain ip addresses */
1491
				if(is_ipaddr($domip)) {
1492
					$domips[] = $domip;
1493
				}
1494
			}
1495
		}
1496
		sort($domips);
1497
		$contents = "";
1498
		if(! empty($domips)) {
1499
			foreach($domips as $ip) {
1500
				$contents .= "$ip\n";
1501
			}
1502
		}
1503
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1504
		/* Remove empty elements */
1505
		$result = array_filter(explode("\n", $contents), 'strlen');
1506
	}
1507
	return $result;
1508
}
1509

    
1510
function is_fqdn($fqdn) {
1511
	$hostname = false;
1512
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1513
		$hostname = true;
1514
	}
1515
	if(preg_match("/\.\./", $fqdn)) {
1516
		$hostname = false;
1517
	}
1518
	if(preg_match("/^\./i", $fqdn)) {
1519
		$hostname = false;
1520
	}
1521
	if(preg_match("/\//i", $fqdn)) {
1522
		$hostname = false;
1523
	}
1524
	return($hostname);
1525
}
1526

    
1527
function pfsense_default_state_size() {
1528
	/* get system memory amount */
1529
	$memory = get_memory();
1530
	$physmem = $memory[0];
1531
	/* Be cautious and only allocate 10% of system memory to the state table */
1532
	$max_states = (int) ($physmem/10)*1000;
1533
	return $max_states;
1534
}
1535

    
1536
function pfsense_default_tables_size() {
1537
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1538
	return $current;
1539
}
1540

    
1541
function pfsense_default_table_entries_size() {
1542
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1543
	return $current;
1544
}
1545

    
1546
/* Compare the current hostname DNS to the DNS cache we made
1547
 * if it has changed we return the old records
1548
 * if no change we return false */
1549
function compare_hostname_to_dnscache($hostname) {
1550
	if(!is_dir("/var/db/dnscache")) {
1551
		mkdir("/var/db/dnscache");
1552
	}
1553
	$hostname = trim($hostname);
1554
	if(is_readable("/var/db/dnscache/{$hostname}")) {
1555
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1556
	} else {
1557
		$oldcontents = "";
1558
	}
1559
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1560
		$domrecords = array();
1561
		$domips = array();
1562
		exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1563
		if($rethost == 0) {
1564
			foreach($domrecords as $domr) {
1565
				$doml = explode(" ", $domr);
1566
				$domip = $doml[3];
1567
				/* fill array with domain ip addresses */
1568
				if(is_ipaddr($domip)) {
1569
					$domips[] = $domip;
1570
				}
1571
			}
1572
		}
1573
		sort($domips);
1574
		$contents = "";
1575
		if(! empty($domips)) {
1576
			foreach($domips as $ip) {
1577
				$contents .= "$ip\n";
1578
			}
1579
		}
1580
	}
1581

    
1582
	if(trim($oldcontents) != trim($contents)) {
1583
		if($g['debug']) {
1584
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1585
		}
1586
		return ($oldcontents);
1587
	} else {
1588
		return false;
1589
	}
1590
}
1591

    
1592
/*
1593
 * load_crypto() - Load crypto modules if enabled in config.
1594
 */
1595
function load_crypto() {
1596
	global $config, $g;
1597
	$crypto_modules = array('glxsb', 'aesni');
1598

    
1599
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules))
1600
		return false;
1601

    
1602
	if (!empty($config['system']['crypto_hardware']) && !is_module_loaded($config['system']['crypto_hardware'])) {
1603
		log_error("Loading {$config['system']['crypto_hardware']} cryptographic accelerator module.");
1604
		mwexec("/sbin/kldload {$config['system']['crypto_hardware']}");
1605
	}
1606
}
1607

    
1608
/*
1609
 * load_thermal_hardware() - Load temperature monitor kernel module
1610
 */
1611
function load_thermal_hardware() {
1612
	global $config, $g;
1613
	$thermal_hardware_modules = array('coretemp', 'amdtemp');
1614

    
1615
	if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules))
1616
		return false;
1617

    
1618
	if (!empty($config['system']['thermal_hardware']) && !is_module_loaded($config['system']['thermal_hardware'])) {
1619
		log_error("Loading {$config['system']['thermal_hardware']} thermal monitor module.");
1620
		mwexec("/sbin/kldload {$config['system']['thermal_hardware']}");
1621
	}
1622
}
1623

    
1624
/****f* pfsense-utils/isvm
1625
 * NAME
1626
 *   isvm
1627
 * INPUTS
1628
 *	none
1629
 * RESULT
1630
 *   returns true if machine is running under a virtual environment
1631
 ******/
1632
function isvm() {
1633
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1634
	$bios_product = trim(`/bin/kenv | /usr/bin/awk -F= '/smbios.system.product/ {print $2}'`);
1635
	foreach ($virtualenvs as $virtualenv)
1636
		if (stripos($bios_product, $virtualenv) !== false)
1637
			return true;
1638

    
1639
	return false;
1640
}
1641

    
1642
function get_freebsd_version() {
1643
	$version = explode(".", php_uname("r"));
1644
	return $version[0];
1645
}
1646

    
1647
function download_file($url, $destination, $verify_ssl = false, $connect_timeout = 60, $timeout = 0) {
1648
	global $config, $g;
1649

    
1650
	$fp = fopen($destination, "wb");
1651

    
1652
	if (!$fp)
1653
		return false;
1654

    
1655
	$ch = curl_init();
1656
	curl_setopt($ch, CURLOPT_URL, $url);
1657
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_ssl);
1658
	curl_setopt($ch, CURLOPT_FILE, $fp);
1659
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1660
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1661
	curl_setopt($ch, CURLOPT_HEADER, false);
1662
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1663
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version")));
1664

    
1665
	if (!empty($config['system']['proxyurl'])) {
1666
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1667
		if (!empty($config['system']['proxyport']))
1668
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1669
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1670
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1671
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1672
		}
1673
	}
1674

    
1675
	@curl_exec($ch);
1676
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1677
	fclose($fp);
1678
	curl_close($ch);
1679
	return ($http_code == 200) ? true : $http_code;
1680
}
1681

    
1682
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1683
	global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update;
1684
	$file_size  = 1;
1685
	$downloaded = 1;
1686
	$first_progress_update = TRUE;
1687
	/* open destination file */
1688
	$fout = fopen($destination_file, "wb");
1689

    
1690
	/*
1691
	 *      Originally by Author: Keyvan Minoukadeh
1692
	 *      Modified by Scott Ullrich to return Content-Length size
1693
	 */
1694

    
1695
	$ch = curl_init();
1696
	curl_setopt($ch, CURLOPT_URL, $url_file);
1697
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1698
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1699
	/* Don't verify SSL peers since we don't have the certificates to do so. */
1700
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1701
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1702
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1703
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1704
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1705

    
1706
	if (!empty($config['system']['proxyurl'])) {
1707
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1708
		if (!empty($config['system']['proxyport']))
1709
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1710
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1711
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1712
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1713
		}
1714
	}
1715

    
1716
	@curl_exec($ch);
1717
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1718
	if($fout)
1719
		fclose($fout);
1720
	curl_close($ch);
1721
	return ($http_code == 200) ? true : $http_code;
1722
}
1723

    
1724
function read_header($ch, $string) {
1725
	global $file_size, $fout;
1726
	$length = strlen($string);
1727
	$regs = "";
1728
	preg_match("/(Content-Length:) (.*)/", $string, $regs);
1729
	if($regs[2] <> "") {
1730
		$file_size = intval($regs[2]);
1731
	}
1732
	ob_flush();
1733
	return $length;
1734
}
1735

    
1736
function read_body($ch, $string) {
1737
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $first_progress_update;
1738
	global $pkg_interface;
1739
	$length = strlen($string);
1740
	$downloaded += intval($length);
1741
	if($file_size > 0) {
1742
		$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1743
		$downloadProgress = 100 - $downloadProgress;
1744
	} else
1745
		$downloadProgress = 0;
1746
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1747
		if($sendto == "status") {
1748
			if($pkg_interface == "console") {
1749
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1750
					$tostatus = $static_status . $downloadProgress . "%";
1751
					if ($downloadProgress == 100) {
1752
						$tostatus = $tostatus . "\r";
1753
					}
1754
					update_status($tostatus);
1755
				}
1756
			} else {
1757
				$tostatus = $static_status . $downloadProgress . "%";
1758
				update_status($tostatus);
1759
			}
1760
		} else {
1761
			if($pkg_interface == "console") {
1762
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1763
					$tooutput = $static_output . $downloadProgress . "%";
1764
					if ($downloadProgress == 100) {
1765
						$tooutput = $tooutput . "\r";
1766
					}
1767
					update_output_window($tooutput);
1768
				}
1769
			} else {
1770
				$tooutput = $static_output . $downloadProgress . "%";
1771
				update_output_window($tooutput);
1772
			}
1773
		}
1774
				if(($pkg_interface != "console") || (($downloadProgress % 10) == 0) || ($downloadProgress < 10)) {
1775
					update_progress_bar($downloadProgress, $first_progress_update);
1776
					$first_progress_update = FALSE;
1777
				}
1778
		$lastseen = $downloadProgress;
1779
	}
1780
	if($fout)
1781
		fwrite($fout, $string);
1782
	ob_flush();
1783
	return $length;
1784
}
1785

    
1786
/*
1787
 *   update_output_window: update bottom textarea dynamically.
1788
 */
1789
function update_output_window($text) {
1790
	global $pkg_interface;
1791
	$log = preg_replace("/\n/", "\\n", $text);
1792
	if($pkg_interface != "console") {
1793
		echo "\n<script type=\"text/javascript\">";
1794
		echo "\n//<![CDATA[";
1795
		echo "\nthis.document.forms[0].output.value = \"" . $log . "\";";
1796
		echo "\nthis.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;";
1797
		echo "\n//]]>";
1798
		echo "\n</script>";
1799
	}
1800
	/* ensure that contents are written out */
1801
	ob_flush();
1802
}
1803

    
1804
/*
1805
 *   update_status: update top textarea dynamically.
1806
 */
1807
function update_status($status) {
1808
	global $pkg_interface;
1809
	if($pkg_interface == "console") {
1810
		echo "\r{$status}";
1811
	} else {
1812
		echo "\n<script type=\"text/javascript\">";
1813
		echo "\n//<![CDATA[";
1814
		echo "\nthis.document.forms[0].status.value=\"" . $status . "\";";
1815
		echo "\n//]]>";
1816
		echo "\n</script>";
1817
	}
1818
	/* ensure that contents are written out */
1819
	ob_flush();
1820
}
1821

    
1822
/*
1823
 * update_progress_bar($percent, $first_time): updates the javascript driven progress bar.
1824
 */
1825
function update_progress_bar($percent, $first_time) {
1826
	global $pkg_interface;
1827
	if($percent > 100) $percent = 1;
1828
	if($pkg_interface <> "console") {
1829
		echo "\n<script type=\"text/javascript\">";
1830
		echo "\n//<![CDATA[";
1831
		echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1832
		echo "\n//]]>";
1833
		echo "\n</script>";
1834
	} else {
1835
		if(!($first_time))
1836
			echo "\x08\x08\x08\x08\x08";
1837
		echo sprintf("%4d%%", $percent);
1838
	}
1839
}
1840

    
1841
/* 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. */
1842
if(!function_exists("split")) {
1843
	function split($separator, $haystack, $limit = null) {
1844
		log_error("deprecated split() call with separator '{$separator}'");
1845
		return preg_split($separator, $haystack, $limit);
1846
	}
1847
}
1848

    
1849
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1850
	global $g, $config, $pconfig, $debug;
1851
	if(!$origname)
1852
		return;
1853

    
1854
	$sectionref = &$config;
1855
	foreach($section as $sectionname) {
1856
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1857
			$sectionref = &$sectionref[$sectionname];
1858
		else
1859
			return;
1860
	}
1861

    
1862
	if($debug) $fd = fopen("{$g['tmp_path']}/print_r", "a");
1863
	if($debug) fwrite($fd, print_r($pconfig, true));
1864

    
1865
	if(is_array($sectionref)) {
1866
		foreach($sectionref as $itemkey => $item) {
1867
			if($debug) fwrite($fd, "$itemkey\n");
1868

    
1869
			$fieldfound = true;
1870
			$fieldref = &$sectionref[$itemkey];
1871
			foreach($field as $fieldname) {
1872
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1873
					$fieldref = &$fieldref[$fieldname];
1874
				else {
1875
					$fieldfound = false;
1876
					break;
1877
				}
1878
			}
1879
			if($fieldfound && $fieldref == $origname) {
1880
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1881
				$fieldref = $new_alias_name;
1882
			}
1883
		}
1884
	}
1885

    
1886
	if($debug) fclose($fd);
1887

    
1888
}
1889

    
1890
function update_alias_url_data() {
1891
	global $config, $g;
1892

    
1893
	/* item is a url type */
1894
	$lockkey = lock('config');
1895
	if (is_array($config['aliases']['alias'])) {
1896
		foreach ($config['aliases']['alias'] as $x => $alias) {
1897
			if (empty($alias['aliasurl']))
1898
				continue;
1899

    
1900
			$address = "";
1901
			$isfirst = 0;
1902
			foreach ($alias['aliasurl'] as $alias_url) {
1903
				/* fetch down and add in */
1904
				$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1905
				unlink($temp_filename);
1906
				$verify_ssl = isset($config['system']['checkaliasesurlcert']);
1907
				mkdir($temp_filename);
1908
				download_file($alias_url, $temp_filename . "/aliases", $verify_ssl);
1909

    
1910
				/* if the item is tar gzipped then extract */
1911
				if (stristr($alias_url, ".tgz"))
1912
					process_alias_tgz($temp_filename);
1913
				else if (stristr($alias_url, ".zip"))
1914
					process_alias_unzip($temp_filename);
1915
				if (file_exists("{$temp_filename}/aliases")) {
1916
					$file_contents = file_get_contents("{$temp_filename}/aliases");
1917
					$file_contents = str_replace("#", "\n#", $file_contents);
1918
					$file_contents_split = explode("\n", $file_contents);
1919
					foreach ($file_contents_split as $fc) {
1920
						$tmp = trim($fc);
1921
						if (stristr($fc, "#")) {
1922
							$tmp_split = explode("#", $tmp);
1923
							$tmp = trim($tmp_split[0]);
1924
						}
1925
						if (trim($tmp) <> "") {
1926
							if ($isfirst == 1)
1927
								$address .= " ";
1928
							$address .= $tmp;
1929
							$isfirst = 1;
1930
						}
1931
					}
1932
					mwexec("/bin/rm -rf {$temp_filename}");
1933
				}
1934
			}
1935
			if($isfirst > 0) {
1936
				$config['aliases']['alias'][$x]['address'] = $address;
1937
				$updated = true;
1938
			}
1939
		}
1940
	}
1941
	if ($updated)
1942
		write_config();
1943
	unlock($lockkey);
1944
}
1945

    
1946
function process_alias_unzip($temp_filename) {
1947
	if(!file_exists("/usr/local/bin/unzip"))
1948
		return;
1949
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.zip");
1950
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1951
	unlink("{$temp_filename}/aliases.zip");
1952
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1953
	/* foreach through all extracted files and build up aliases file */
1954
	$fd = fopen("{$temp_filename}/aliases", "w");
1955
	foreach($files_to_process as $f2p) {
1956
		$file_contents = file_get_contents($f2p);
1957
		fwrite($fd, $file_contents);
1958
		unlink($f2p);
1959
	}
1960
	fclose($fd);
1961
}
1962

    
1963
function process_alias_tgz($temp_filename) {
1964
	if(!file_exists("/usr/bin/tar"))
1965
		return;
1966
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.tgz");
1967
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1968
	unlink("{$temp_filename}/aliases.tgz");
1969
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1970
	/* foreach through all extracted files and build up aliases file */
1971
	$fd = fopen("{$temp_filename}/aliases", "w");
1972
	foreach($files_to_process as $f2p) {
1973
		$file_contents = file_get_contents($f2p);
1974
		fwrite($fd, $file_contents);
1975
		unlink($f2p);
1976
	}
1977
	fclose($fd);
1978
}
1979

    
1980
function version_compare_dates($a, $b) {
1981
	$a_time = strtotime($a);
1982
	$b_time = strtotime($b);
1983

    
1984
	if ((!$a_time) || (!$b_time)) {
1985
		return FALSE;
1986
	} else {
1987
		if ($a_time < $b_time)
1988
			return -1;
1989
		elseif ($a_time == $b_time)
1990
			return 0;
1991
		else
1992
			return 1;
1993
	}
1994
}
1995
function version_get_string_value($a) {
1996
	$strs = array(
1997
		0 => "ALPHA-ALPHA",
1998
		2 => "ALPHA",
1999
		3 => "BETA",
2000
		4 => "B",
2001
		5 => "C",
2002
		6 => "D",
2003
		7 => "RC",
2004
		8 => "RELEASE",
2005
		9 => "*"			// Matches all release levels
2006
	);
2007
	$major = 0;
2008
	$minor = 0;
2009
	foreach ($strs as $num => $str) {
2010
		if (substr($a, 0, strlen($str)) == $str) {
2011
			$major = $num;
2012
			$n = substr($a, strlen($str));
2013
			if (is_numeric($n))
2014
				$minor = $n;
2015
			break;
2016
		}
2017
	}
2018
	return "{$major}.{$minor}";
2019
}
2020
function version_compare_string($a, $b) {
2021
	// Only compare string parts if both versions give a specific release
2022
	// (If either version lacks a string part, assume intended to match all release levels)
2023
	if (isset($a) && isset($b))
2024
		return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
2025
	else
2026
		return 0;
2027
}
2028
function version_compare_numeric($a, $b) {
2029
	$a_arr = explode('.', rtrim($a, '.0'));
2030
	$b_arr = explode('.', rtrim($b, '.0'));
2031

    
2032
	foreach ($a_arr as $n => $val) {
2033
		if (array_key_exists($n, $b_arr)) {
2034
			// So far so good, both have values at this minor version level. Compare.
2035
			if ($val > $b_arr[$n])
2036
				return 1;
2037
			elseif ($val < $b_arr[$n])
2038
				return -1;
2039
		} else {
2040
			// a is greater, since b doesn't have any minor version here.
2041
			return 1;
2042
		}
2043
	}
2044
	if (count($b_arr) > count($a_arr)) {
2045
		// b is longer than a, so it must be greater.
2046
		return -1;
2047
	} else {
2048
		// Both a and b are of equal length and value.
2049
		return 0;
2050
	}
2051
}
2052
function pfs_version_compare($cur_time, $cur_text, $remote) {
2053
	// First try date compare
2054
	$v = version_compare_dates($cur_time, $remote);
2055
	if ($v === FALSE) {
2056
		// If that fails, try to compare by string
2057
		// Before anything else, simply test if the strings are equal
2058
		if (($cur_text == $remote) || ($cur_time == $remote))
2059
			return 0;
2060
		list($cur_num, $cur_str) = explode('-', $cur_text);
2061
		list($rem_num, $rem_str) = explode('-', $remote);
2062

    
2063
		// First try to compare the numeric parts of the version string.
2064
		$v = version_compare_numeric($cur_num, $rem_num);
2065

    
2066
		// If the numeric parts are the same, compare the string parts.
2067
		if ($v == 0)
2068
			return version_compare_string($cur_str, $rem_str);
2069
	}
2070
	return $v;
2071
}
2072
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
2073
	global $config;
2074

    
2075
	$urltable_prefix = "/var/db/aliastables/";
2076
	$urltable_filename = $urltable_prefix . $name . ".txt";
2077

    
2078
	// Make the aliases directory if it doesn't exist
2079
	if (!file_exists($urltable_prefix)) {
2080
		mkdir($urltable_prefix);
2081
	} elseif (!is_dir($urltable_prefix)) {
2082
		unlink($urltable_prefix);
2083
		mkdir($urltable_prefix);
2084
	}
2085

    
2086
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
2087
	if (!file_exists($urltable_filename)
2088
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400 - 90))
2089
		|| $forceupdate) {
2090

    
2091
		// Try to fetch the URL supplied
2092
		conf_mount_rw();
2093
		unlink_if_exists($urltable_filename . ".tmp");
2094
		$verify_ssl = isset($config['system']['checkaliasesurlcert']);
2095
		if (download_file($url, $urltable_filename . ".tmp", $verify_ssl)) {
2096
			mwexec("/usr/bin/sed -E 's/\;.*//g; /^[[:space:]]*($|#)/d' ". escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
2097
			if (alias_get_type($name) == "urltable_ports") {
2098
				$ports = explode("\n", file_get_contents($urltable_filename));
2099
				$ports = group_ports($ports);
2100
				file_put_contents($urltable_filename, implode("\n", $ports));
2101
			}
2102
			unlink_if_exists($urltable_filename . ".tmp");
2103
		} else
2104
			touch($urltable_filename);
2105
		conf_mount_ro();
2106
		return true;
2107
	} else {
2108
		// File exists, and it doesn't need updated.
2109
		return -1;
2110
	}
2111
}
2112
function get_real_slice_from_glabel($label) {
2113
	$label = escapeshellarg($label);
2114
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
2115
}
2116
function nanobsd_get_boot_slice() {
2117
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
2118
}
2119
function nanobsd_get_boot_drive() {
2120
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/pfsense | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' ' | /usr/bin/cut -d's' -f1`);
2121
}
2122
function nanobsd_get_active_slice() {
2123
	$boot_drive = nanobsd_get_boot_drive();
2124
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
2125

    
2126
	return "{$boot_drive}s{$active}";
2127
}
2128
function nanobsd_get_size() {
2129
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
2130
}
2131
function nanobsd_switch_boot_slice() {
2132
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2133
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2134
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2135
	nanobsd_detect_slice_info();
2136

    
2137
	if ($BOOTFLASH == $ACTIVE_SLICE) {
2138
		$slice = $TOFLASH;
2139
	} else {
2140
		$slice = $BOOTFLASH;
2141
	}
2142

    
2143
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2144
	ob_implicit_flush(1);
2145
	if(strstr($slice, "s2")) {
2146
		$ASLICE="2";
2147
		$AOLDSLICE="1";
2148
		$AGLABEL_SLICE="pfsense1";
2149
		$AUFS_ID="1";
2150
		$AOLD_UFS_ID="0";
2151
	} else {
2152
		$ASLICE="1";
2153
		$AOLDSLICE="2";
2154
		$AGLABEL_SLICE="pfsense0";
2155
		$AUFS_ID="0";
2156
		$AOLD_UFS_ID="1";
2157
	}
2158
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
2159
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
2160
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
2161
	conf_mount_rw();
2162
	exec("sysctl kern.geom.debugflags=16");
2163
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
2164
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
2165
	// We can't update these if they are mounted now.
2166
	if ($BOOTFLASH != $slice) {
2167
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
2168
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
2169
	}
2170
	exec("/sbin/sysctl kern.geom.debugflags=0");
2171
	conf_mount_ro();
2172
}
2173
function nanobsd_clone_slice() {
2174
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2175
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2176
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2177
	nanobsd_detect_slice_info();
2178

    
2179
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2180
	ob_implicit_flush(1);
2181
	exec("/sbin/sysctl kern.geom.debugflags=16");
2182
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
2183
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
2184
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
2185
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
2186
	exec("/sbin/sysctl kern.geom.debugflags=0");
2187
	if($status) {
2188
		return false;
2189
	} else {
2190
		return true;
2191
	}
2192
}
2193
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
2194
	$tmppath = "/tmp/{$gslice}";
2195
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
2196

    
2197
	mkdir($tmppath);
2198
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
2199
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
2200
	copy("/etc/fstab", $fstabpath);
2201

    
2202
	if (!file_exists($fstabpath)) {
2203
		$fstab = <<<EOF
2204
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
2205
/dev/ufs/cf /cf ufs ro,noatime 1 1
2206
EOF;
2207
		if (file_put_contents($fstabpath, $fstab))
2208
			$status = true;
2209
		else
2210
			$status = false;
2211
	} else {
2212
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
2213
	}
2214
	exec("/sbin/umount {$tmppath}");
2215
	rmdir($tmppath);
2216

    
2217
	return $status;
2218
}
2219
function nanobsd_detect_slice_info() {
2220
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2221
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2222
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2223

    
2224
	$BOOT_DEVICE=nanobsd_get_boot_slice();
2225
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
2226
	$BOOT_DRIVE=nanobsd_get_boot_drive();
2227
	$ACTIVE_SLICE=nanobsd_get_active_slice();
2228

    
2229
	// Detect which slice is active and set information.
2230
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
2231
		$SLICE="2";
2232
		$OLDSLICE="1";
2233
		$GLABEL_SLICE="pfsense1";
2234
		$UFS_ID="1";
2235
		$OLD_UFS_ID="0";
2236

    
2237
	} else {
2238
		$SLICE="1";
2239
		$OLDSLICE="2";
2240
		$GLABEL_SLICE="pfsense0";
2241
		$UFS_ID="0";
2242
		$OLD_UFS_ID="1";
2243
	}
2244
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
2245
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
2246
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
2247
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
2248
}
2249

    
2250
function nanobsd_friendly_slice_name($slicename) {
2251
	global $g;
2252
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2253
}
2254

    
2255
function get_include_contents($filename) {
2256
	if (is_file($filename)) {
2257
		ob_start();
2258
		include $filename;
2259
		$contents = ob_get_contents();
2260
		ob_end_clean();
2261
		return $contents;
2262
	}
2263
	return false;
2264
}
2265

    
2266
/* This xml 2 array function is courtesy of the php.net comment section on xml_parse.
2267
 * it is roughly 4 times faster then our existing pfSense parser but due to the large
2268
 * size of the RRD xml dumps this is required.
2269
 * The reason we do not use it for pfSense is that it does not know about array fields
2270
 * which causes it to fail on array fields with single items. Possible Todo?
2271
 */
2272
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
2273
{
2274
	if (!function_exists('xml_parser_create'))
2275
	{
2276
		return array ();
2277
	}
2278
	$parser = xml_parser_create('');
2279
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
2280
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2281
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
2282
	xml_parse_into_struct($parser, trim($contents), $xml_values);
2283
	xml_parser_free($parser);
2284
	if (!$xml_values)
2285
		return; //Hmm...
2286
	$xml_array = array ();
2287
	$parents = array ();
2288
	$opened_tags = array ();
2289
	$arr = array ();
2290
	$current = & $xml_array;
2291
	$repeated_tag_index = array ();
2292
	foreach ($xml_values as $data)
2293
	{
2294
		unset ($attributes, $value);
2295
		extract($data);
2296
		$result = array ();
2297
		$attributes_data = array ();
2298
		if (isset ($value))
2299
		{
2300
			if ($priority == 'tag')
2301
				$result = $value;
2302
			else
2303
				$result['value'] = $value;
2304
		}
2305
		if (isset ($attributes) and $get_attributes)
2306
		{
2307
			foreach ($attributes as $attr => $val)
2308
			{
2309
				if ($priority == 'tag')
2310
					$attributes_data[$attr] = $val;
2311
				else
2312
					$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
2313
			}
2314
		}
2315
		if ($type == "open")
2316
		{
2317
			$parent[$level -1] = & $current;
2318
			if (!is_array($current) or (!in_array($tag, array_keys($current))))
2319
			{
2320
				$current[$tag] = $result;
2321
				if ($attributes_data)
2322
					$current[$tag . '_attr'] = $attributes_data;
2323
				$repeated_tag_index[$tag . '_' . $level] = 1;
2324
				$current = & $current[$tag];
2325
			}
2326
			else
2327
			{
2328
				if (isset ($current[$tag][0]))
2329
				{
2330
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2331
					$repeated_tag_index[$tag . '_' . $level]++;
2332
				}
2333
				else
2334
				{
2335
					$current[$tag] = array (
2336
						$current[$tag],
2337
						$result
2338
						);
2339
					$repeated_tag_index[$tag . '_' . $level] = 2;
2340
					if (isset ($current[$tag . '_attr']))
2341
					{
2342
						$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2343
						unset ($current[$tag . '_attr']);
2344
					}
2345
				}
2346
				$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
2347
				$current = & $current[$tag][$last_item_index];
2348
			}
2349
		}
2350
		elseif ($type == "complete")
2351
		{
2352
			if (!isset ($current[$tag]))
2353
			{
2354
				$current[$tag] = $result;
2355
				$repeated_tag_index[$tag . '_' . $level] = 1;
2356
				if ($priority == 'tag' and $attributes_data)
2357
					$current[$tag . '_attr'] = $attributes_data;
2358
			}
2359
			else
2360
			{
2361
				if (isset ($current[$tag][0]) and is_array($current[$tag]))
2362
				{
2363
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2364
					if ($priority == 'tag' and $get_attributes and $attributes_data)
2365
					{
2366
						$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2367
					}
2368
					$repeated_tag_index[$tag . '_' . $level]++;
2369
				}
2370
				else
2371
				{
2372
					$current[$tag] = array (
2373
						$current[$tag],
2374
						$result
2375
						);
2376
					$repeated_tag_index[$tag . '_' . $level] = 1;
2377
					if ($priority == 'tag' and $get_attributes)
2378
					{
2379
						if (isset ($current[$tag . '_attr']))
2380
						{
2381
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2382
							unset ($current[$tag . '_attr']);
2383
						}
2384
						if ($attributes_data)
2385
						{
2386
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2387
						}
2388
					}
2389
					$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
2390
				}
2391
			}
2392
		}
2393
		elseif ($type == 'close')
2394
		{
2395
			$current = & $parent[$level -1];
2396
		}
2397
	}
2398
	return ($xml_array);
2399
}
2400

    
2401
function get_country_name($country_code) {
2402
	if ($country_code != "ALL" && strlen($country_code) != 2)
2403
		return "";
2404

    
2405
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2406
	$country_names_contents = file_get_contents($country_names_xml);
2407
	$country_names = xml2array($country_names_contents);
2408

    
2409
	if($country_code == "ALL") {
2410
		$country_list = array();
2411
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2412
			$country_list[] = array("code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2413
						"name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2414
		}
2415
		return $country_list;
2416
	}
2417

    
2418
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2419
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2420
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2421
		}
2422
	}
2423
	return "";
2424
}
2425

    
2426
/* sort by interface only, retain the original order of rules that apply to
2427
   the same interface */
2428
function filter_rules_sort() {
2429
	global $config;
2430

    
2431
	/* mark each rule with the sequence number (to retain the order while sorting) */
2432
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2433
		$config['filter']['rule'][$i]['seq'] = $i;
2434

    
2435
	usort($config['filter']['rule'], "filter_rules_compare");
2436

    
2437
	/* strip the sequence numbers again */
2438
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2439
		unset($config['filter']['rule'][$i]['seq']);
2440
}
2441
function filter_rules_compare($a, $b) {
2442
	if (isset($a['floating']) && isset($b['floating']))
2443
		return $a['seq'] - $b['seq'];
2444
	else if (isset($a['floating']))
2445
		return -1;
2446
	else if (isset($b['floating']))
2447
		return 1;
2448
	else if ($a['interface'] == $b['interface'])
2449
		return $a['seq'] - $b['seq'];
2450
	else
2451
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2452
}
2453

    
2454
function generate_ipv6_from_mac($mac) {
2455
	$elements = explode(":", $mac);
2456
	if(count($elements) <> 6)
2457
		return false;
2458

    
2459
	$i = 0;
2460
	$ipv6 = "fe80::";
2461
	foreach($elements as $byte) {
2462
		if($i == 0) {
2463
			$hexadecimal =  substr($byte, 1, 2);
2464
			$bitmap = base_convert($hexadecimal, 16, 2);
2465
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2466
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4);
2467
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2468
		}
2469
		$ipv6 .= $byte;
2470
		if($i == 1) {
2471
			$ipv6 .= ":";
2472
		}
2473
		if($i == 3) {
2474
			$ipv6 .= ":";
2475
		}
2476
		if($i == 2) {
2477
			$ipv6 .= "ff:fe";
2478
		}
2479

    
2480
		$i++;
2481
	}
2482
	return $ipv6;
2483
}
2484

    
2485
/****f* pfsense-utils/load_mac_manufacturer_table
2486
 * NAME
2487
 *   load_mac_manufacturer_table
2488
 * INPUTS
2489
 *   none
2490
 * RESULT
2491
 *   returns associative array with MAC-Manufacturer pairs
2492
 ******/
2493
function load_mac_manufacturer_table() {
2494
	/* load MAC-Manufacture data from the file */
2495
	$macs = false;
2496
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2497
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2498
	if ($macs){
2499
		foreach ($macs as $line){
2500
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2501
				/* store values like this $mac_man['000C29']='VMware' */
2502
				$mac_man["$matches[1]"]=$matches[2];
2503
			}
2504
		}
2505
		return $mac_man;
2506
	} else
2507
		return -1;
2508

    
2509
}
2510

    
2511
/****f* pfsense-utils/is_ipaddr_configured
2512
 * NAME
2513
 *   is_ipaddr_configured
2514
 * INPUTS
2515
 *   IP Address to check.
2516
 * RESULT
2517
 *   returns true if the IP Address is
2518
 *   configured and present on this device.
2519
*/
2520
function is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, $check_subnets = false) {
2521
	global $config;
2522

    
2523
	$isipv6 = is_ipaddrv6($ipaddr);
2524

    
2525
	if ($check_subnets) {
2526
		$iflist = get_configured_interface_list();
2527
		foreach ($iflist as $if => $ifname) {
2528
			if ($ignore_if == $if)
2529
				continue;
2530

    
2531
			if ($isipv6 === true) {
2532
				$bitmask = get_interface_subnetv6($if);
2533
				$subnet = gen_subnetv6(get_interface_ipv6($if), $bitmask);
2534
			} else {
2535
				$bitmask = get_interface_subnet($if);
2536
				$subnet = gen_subnet(get_interface_ip($if), $bitmask);
2537
			}
2538

    
2539
			if (ip_in_subnet($ipaddr, $subnet . '/' . $bitmask))
2540
				return true;
2541
		}
2542
	} else {
2543
		if ($isipv6 === true)
2544
			$interface_list_ips = get_configured_ipv6_addresses();
2545
		else
2546
			$interface_list_ips = get_configured_ip_addresses();
2547

    
2548
		foreach($interface_list_ips as $if => $ilips) {
2549
			/* Also ignore CARP interfaces, it'll be checked below */
2550
			if ($ignore_if == $if || strstr($ignore_if, "_vip"))
2551
				continue;
2552
			if (strcasecmp($ipaddr, $ilips) == 0)
2553
				return true;
2554
		}
2555
	}
2556

    
2557
	$interface_list_vips = get_configured_vips_list(true);
2558
	foreach ($interface_list_vips as $id => $vip) {
2559
		if ($ignore_if == $vip['if'])
2560
			continue;
2561
		if (strcasecmp($ipaddr, $vip['ipaddr']) == 0)
2562
			return true;
2563
	}
2564

    
2565
	if ($check_localip) {
2566
		if (is_array($config['pptpd']) && !empty($config['pptpd']['localip']) && (strcasecmp($ipaddr, $config['pptpd']['localip']) == 0))
2567
			return true;
2568

    
2569
		if (!is_array($config['l2tp']) && !empty($config['l2tp']['localip']) && (strcasecmp($ipaddr, $config['l2tp']['localip']) == 0))
2570
			return true;
2571
	}
2572

    
2573
	return false;
2574
}
2575

    
2576
/****f* pfsense-utils/pfSense_handle_custom_code
2577
 * NAME
2578
 *   pfSense_handle_custom_code
2579
 * INPUTS
2580
 *   directory name to process
2581
 * RESULT
2582
 *   globs the directory and includes the files
2583
 */
2584
function pfSense_handle_custom_code($src_dir) {
2585
	// Allow extending of the nat edit page and include custom input validation
2586
	if(is_dir("$src_dir")) {
2587
		$cf = glob($src_dir . "/*.inc");
2588
		foreach($cf as $nf) {
2589
			if($nf == "." || $nf == "..")
2590
				continue;
2591
			// Include the extra handler
2592
			include("$nf");
2593
		}
2594
	}
2595
}
2596

    
2597
function set_language($lang = 'en_US', $encoding = "ISO8859-1") {
2598
	putenv("LANG={$lang}.{$encoding}");
2599
	setlocale(LC_ALL, "{$lang}.{$encoding}");
2600
	textdomain("pfSense");
2601
	bindtextdomain("pfSense","/usr/local/share/locale");
2602
	bind_textdomain_codeset("pfSense","{$lang}.{$encoding}");
2603
}
2604

    
2605
function get_locale_list() {
2606
	$locales = array(
2607
		"en_US" => gettext("English"),
2608
		"pt_BR" => gettext("Portuguese (Brazil)"),
2609
		"tr" => gettext("Turkish"),
2610
	);
2611
	asort($locales);
2612
	return $locales;
2613
}
2614

    
2615
function system_get_language_code() {
2616
	global $config, $g_languages;
2617

    
2618
	// a language code, as per [RFC3066]
2619
	$language = $config['system']['language'];
2620
	//$code = $g_languages[$language]['code'];
2621
	$code = str_replace("_", "-", $language);
2622

    
2623
	if (empty($code))
2624
		$code = "en-US"; // Set default code.
2625

    
2626
	return $code;
2627
}
2628

    
2629
function system_get_language_codeset() {
2630
	global $config, $g_languages;
2631

    
2632
	$language = $config['system']['language'];
2633
	$codeset = $g_languages[$language]['codeset'];
2634

    
2635
	if (empty($codeset))
2636
		$codeset = "UTF-8"; // Set default codeset.
2637

    
2638
	return $codeset;
2639
}
2640

    
2641
/* Available languages/locales */
2642
$g_languages = array (
2643
	"sq"    => array("codeset" => "UTF-8", "desc" => gettext("Albanian")),
2644
	"bg"    => array("codeset" => "UTF-8", "desc" => gettext("Bulgarian")),
2645
	"zh_CN" => array("codeset" => "UTF-8", "desc" => gettext("Chinese (Simplified)")),
2646
	"zh_TW" => array("codeset" => "UTF-8", "desc" => gettext("Chinese (Traditional)")),
2647
	"nl"    => array("codeset" => "UTF-8", "desc" => gettext("Dutch")),
2648
	"da"    => array("codeset" => "UTF-8", "desc" => gettext("Danish")),
2649
	"en_US" => array("codeset" => "ISO-8859-1", "desc" => gettext("English")),
2650
	"fi"    => array("codeset" => "UTF-8", "desc" => gettext("Finnish")),
2651
	"fr"    => array("codeset" => "UTF-8", "desc" => gettext("French")),
2652
	"de"    => array("codeset" => "UTF-8", "desc" => gettext("German")),
2653
	"el"    => array("codeset" => "UTF-8", "desc" => gettext("Greek")),
2654
	"hu"    => array("codeset" => "UTF-8", "desc" => gettext("Hungarian")),
2655
	"it"    => array("codeset" => "UTF-8", "desc" => gettext("Italian")),
2656
	"ja"    => array("codeset" => "UTF-8", "desc" => gettext("Japanese")),
2657
	"ko"    => array("codeset" => "UTF-8", "desc" => gettext("Korean")),
2658
	"lv"    => array("codeset" => "UTF-8", "desc" => gettext("Latvian")),
2659
	"nb"    => array("codeset" => "UTF-8", "desc" => gettext("Norwegian (Bokmal)")),
2660
	"pl"    => array("codeset" => "UTF-8", "desc" => gettext("Polish")),
2661
	"pt_BR" => array("codeset" => "ISO-8859-1", "desc" => gettext("Portuguese (Brazil)")),
2662
	"pt"    => array("codeset" => "UTF-8", "desc" => gettext("Portuguese (Portugal)")),
2663
	"ro"    => array("codeset" => "UTF-8", "desc" => gettext("Romanian")),
2664
	"ru"    => array("codeset" => "UTF-8", "desc" => gettext("Russian")),
2665
	"sl"    => array("codeset" => "UTF-8", "desc" => gettext("Slovenian")),
2666
	"tr"    => array("codeset" => "UTF-8", "desc" => gettext("Turkish")),
2667
	"es"    => array("codeset" => "UTF-8", "desc" => gettext("Spanish")),
2668
	"sv"    => array("codeset" => "UTF-8", "desc" => gettext("Swedish")),
2669
	"sk"    => array("codeset" => "UTF-8", "desc" => gettext("Slovak")),
2670
	"cs"    => array("codeset" => "UTF-8", "desc" => gettext("Czech"))
2671
);
2672

    
2673
function return_hex_ipv4($ipv4) {
2674
	if(!is_ipaddrv4($ipv4))
2675
		return(false);
2676

    
2677
	/* we need the hex form of the interface IPv4 address */
2678
	$ip4arr = explode(".", $ipv4);
2679
	return (sprintf("%02x%02x%02x%02x", $ip4arr[0], $ip4arr[1], $ip4arr[2], $ip4arr[3]));
2680
}
2681

    
2682
function convert_ipv6_to_128bit($ipv6) {
2683
	if(!is_ipaddrv6($ipv6))
2684
		return(false);
2685

    
2686
	$ip6arr = array();
2687
	$ip6prefix = Net_IPv6::uncompress($ipv6);
2688
	$ip6arr = explode(":", $ip6prefix);
2689
	/* binary presentation of the prefix for all 128 bits. */
2690
	$ip6prefixbin = "";
2691
	foreach($ip6arr as $element) {
2692
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
2693
	}
2694
	return($ip6prefixbin);
2695
}
2696

    
2697
function convert_128bit_to_ipv6($ip6bin) {
2698
	if(strlen($ip6bin) <> 128)
2699
		return(false);
2700

    
2701
	$ip6arr = array();
2702
	$ip6binarr = array();
2703
	$ip6binarr = str_split($ip6bin, 16);
2704
	foreach($ip6binarr as $binpart)
2705
		$ip6arr[] = dechex(bindec($binpart));
2706
	$ip6addr = Net_IPv6::compress(implode(":", $ip6arr));
2707

    
2708
	return($ip6addr);
2709
}
2710

    
2711

    
2712
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
2713
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
2714
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
2715
/* 6to4 is 16 bits, e.g. 65535 */
2716
function calculate_ipv6_delegation_length($if) {
2717
	global $config;
2718

    
2719
	if(!is_array($config['interfaces'][$if]))
2720
		return false;
2721

    
2722
	switch($config['interfaces'][$if]['ipaddrv6']) {
2723
		case "6to4":
2724
			$pdlen = 16;
2725
			break;
2726
		case "6rd":
2727
			$rd6cfg = $config['interfaces'][$if];
2728
			$rd6plen = explode("/", $rd6cfg['prefix-6rd']);
2729
			$pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen'])));
2730
			break;
2731
		case "dhcp6":
2732
			$dhcp6cfg = $config['interfaces'][$if];
2733
			$pdlen = $dhcp6cfg['dhcp6-ia-pd-len'];
2734
			break;
2735
		default:
2736
			$pdlen = 0;
2737
			break;
2738
	}
2739
	return($pdlen);
2740
}
2741

    
2742
function huawei_rssi_to_string($rssi) {
2743
	$dbm = array();
2744
	$i = 0;
2745
	$dbstart = -113;
2746
	while($i < 32) {
2747
		$dbm[$i] = $dbstart + ($i * 2);
2748
		$i++;
2749
	}
2750
	$percent = round(($rssi / 31) * 100);
2751
	$string = "rssi:{$rssi} level:{$dbm[$rssi]}dBm percent:{$percent}%";
2752
	return $string;
2753
}
2754

    
2755
function huawei_mode_to_string($mode, $submode) {
2756
	$modes[0] = "None";
2757
	$modes[1] = "AMPS";
2758
	$modes[2] = "CDMA";
2759
	$modes[3] = "GSM/GPRS";
2760
	$modes[4] = "HDR";
2761
	$modes[5] = "WCDMA";
2762
	$modes[6] = "GPS";
2763

    
2764
	$submodes[0] = "No Service";
2765
	$submodes[1] = "GSM";
2766
	$submodes[2] = "GPRS";
2767
	$submodes[3] = "EDGE";
2768
	$submodes[4] = "WCDMA";
2769
	$submodes[5] = "HSDPA";
2770
	$submodes[6] = "HSUPA";
2771
	$submodes[7] = "HSDPA+HSUPA";
2772
	$submodes[8] = "TD-SCDMA";
2773
	$submodes[9] = "HSPA+";
2774
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2775
	return $string;
2776
}
2777

    
2778
function huawei_service_to_string($state) {
2779
	$modes[0] = "No";
2780
	$modes[1] = "Restricted";
2781
	$modes[2] = "Valid";
2782
	$modes[3] = "Restricted Regional";
2783
	$modes[4] = "Powersaving";
2784
	$string = "{$modes[$state]} Service";
2785
	return $string;
2786
}
2787

    
2788
function huawei_simstate_to_string($state) {
2789
	$modes[0] = "Invalid SIM/locked";
2790
	$modes[1] = "Valid SIM";
2791
	$modes[2] = "Invalid SIM CS";
2792
	$modes[3] = "Invalid SIM PS";
2793
	$modes[4] = "Invalid SIM CS/PS";
2794
	$modes[255] = "Missing SIM";
2795
	$string = "{$modes[$state]} State";
2796
	return $string;
2797
}
2798

    
2799
function zte_rssi_to_string($rssi) {
2800
	return huawei_rssi_to_string($rssi);
2801
}
2802

    
2803
function zte_mode_to_string($mode, $submode) {
2804
	$modes[0] = "No Service";
2805
	$modes[1] = "Limited Service";
2806
	$modes[2] = "GPRS";
2807
	$modes[3] = "GSM";
2808
	$modes[4] = "UMTS";
2809
	$modes[5] = "EDGE";
2810
	$modes[6] = "HSDPA";
2811

    
2812
	$submodes[0] = "CS_ONLY";
2813
	$submodes[1] = "PS_ONLY";
2814
	$submodes[2] = "CS_PS";
2815
	$submodes[3] = "CAMPED";
2816
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2817
	return $string;
2818
}
2819

    
2820
function zte_service_to_string($state) {
2821
	$modes[0] = "Initializing";
2822
	$modes[1] = "Network Lock error";
2823
	$modes[2] = "Network Locked";
2824
	$modes[3] = "Unlocked or correct MCC/MNC";
2825
	$string = "{$modes[$state]} Service";
2826
	return $string;
2827
}
2828

    
2829
function zte_simstate_to_string($state) {
2830
	$modes[0] = "No action";
2831
	$modes[1] = "Network lock";
2832
	$modes[2] = "(U)SIM card lock";
2833
	$modes[3] = "Network Lock and (U)SIM card Lock";
2834
	$string = "{$modes[$state]} State";
2835
	return $string;
2836
}
2837

    
2838
function get_configured_pppoe_server_interfaces() {
2839
	global $config;
2840
	$iflist = array();
2841
	if (is_array($config['pppoes']['pppoe'])) {
2842
		foreach($config['pppoes']['pppoe'] as $pppoe) {
2843
			if ($pppoe['mode'] == "server") {
2844
				$int = "poes". $pppoe['pppoeid'];
2845
				$iflist[$int] = strtoupper($int);
2846
			}
2847
		}
2848
	}
2849
	return $iflist;
2850
}
2851

    
2852
function get_pppoes_child_interfaces($ifpattern) {
2853
	$if_arr = array();
2854
	if($ifpattern == "")
2855
		return;
2856

    
2857
	exec("ifconfig", $out, $ret);
2858
	foreach($out as $line) {
2859
		if(preg_match("/^({$ifpattern}[0-9]+):/i", $line, $match)) {
2860
			$if_arr[] = $match[1];
2861
		}
2862
	}
2863
	return $if_arr;
2864

    
2865
}
2866

    
2867
/****f* pfsense-utils/pkg_call_plugins
2868
 * NAME
2869
 *   pkg_call_plugins
2870
 * INPUTS
2871
 *   $plugin_type value used to search in package configuration if the plugin is used, also used to create the function name
2872
 *   $plugin_params parameters to pass to the plugin function for passing multiple parameters a array can be used.
2873
 * RESULT
2874
 *   returns associative array results from the plugin calls for each package
2875
 * NOTES
2876
 *   This generic function can be used to notify or retrieve results from functions that are defined in packages.
2877
 ******/
2878
function pkg_call_plugins($plugin_type, $plugin_params) {
2879
	global $g, $config;
2880
	$results = array();
2881
	if (!is_array($config['installedpackages']['package']))
2882
		return $results;
2883
	foreach ($config['installedpackages']['package'] as $package) {
2884
		if(!file_exists("/usr/local/pkg/" . $package['configurationfile']))
2885
			continue;
2886
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], 'packagegui');
2887
		$pkgname = substr(reverse_strrchr($package['configurationfile'], "."),0,-1);
2888
		if (is_array($pkg_config['plugins']['item']))
2889
			foreach ($pkg_config['plugins']['item'] as $plugin) {
2890
				if ($plugin['type'] == $plugin_type) {
2891
					if (file_exists($pkg_config['include_file']))
2892
						require_once($pkg_config['include_file']);
2893
					else
2894
						continue;
2895
					$plugin_function = $pkgname . '_'. $plugin_type;
2896
					$results[$pkgname] = @eval($plugin_function($plugin_params));
2897
				}
2898
			}
2899
	}
2900
	return $results;
2901
}
2902

    
2903
?>
(39-39/67)