Projet

Général

Profil

Télécharger (83,4 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / etc / inc / pfsense-utils.inc @ 4665dbdd

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/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
		set_single_sysctl("kern.polling.idle_poll", "1");
269
	else
270
		set_single_sysctl("kern.polling.idle_poll", "0");
271

    
272
	if($config['system']['polling_each_burst'])
273
		set_single_sysctl("kern.polling.each_burst", $config['system']['polling_each_burst']);
274
	if($config['system']['polling_burst_max'])
275
		set_single_sysctl("kern.polling.burst_max", $config['system']['polling_burst_max']);
276
	if($config['system']['polling_user_frac'])
277
		set_single_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 = get_single_sysctl('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 = get_active_xml_rpc_base_url();
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 = get_active_xml_rpc_base_url();
722
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
723
	$ip = gethostbyname($xmlrpcfqdn);
724
	if($ip == $xmlrpcfqdn)
725
		return false;
726
	$version = php_uname('r');
727
	$version = explode('-', $version);
728
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
729
		"kernel"   => array("version" => $version[0]),
730
		"base"     => array("version" => $version[0]),
731
		"platform" => trim(file_get_contents('/etc/platform')),
732
		"config_version" => $config['version']
733
		);
734
	unset($version);
735

    
736
	if($tocheck == "all") {
737
		$params = $rawparams;
738
	} else {
739
		foreach($tocheck as $check) {
740
			$params['check'] = $rawparams['check'];
741
			$params['platform'] = $rawparams['platform'];
742
		}
743
	}
744
	if($config['system']['firmware']['branch'])
745
		$params['branch'] = $config['system']['firmware']['branch'];
746

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

    
754
	return $versions;
755
}
756

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

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

    
765
	return array(
766
		"firmware" => array("version" => trim(file_get_contents('/etc/version', " \n"))),
767
		"kernel"   => array("version" => $os_version),
768
		"base"     => array("version" => $os_version),
769
		"platform" => trim(file_get_contents('/etc/platform', " \n")),
770
		"config_version" => $config['version']
771
	);
772
}
773

    
774
function get_disk_info() {
775
	$diskout = "";
776
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $2, $3, $4, $5 }'", $diskout);
777
	return explode(' ', $diskout[0]);
778
}
779

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

    
796
/****f* pfsense-utils/reload_interfaces_sync
797
 * NAME
798
 *   reload_interfaces - reload all interfaces
799
 * INPUTS
800
 *   none
801
 * RESULT
802
 *   none
803
 ******/
804
function reload_interfaces_sync() {
805
	global $config, $g;
806

    
807
	if($g['debug'])
808
		log_error(gettext("reload_interfaces_sync() is starting."));
809

    
810
	/* parse config.xml again */
811
	$config = parse_config(true);
812

    
813
	/* enable routing */
814
	system_routing_enable();
815
	if($g['debug'])
816
		log_error(gettext("Enabling system routing"));
817

    
818
	if($g['debug'])
819
		log_error(gettext("Cleaning up Interfaces"));
820

    
821
	/* set up interfaces */
822
	interfaces_configure();
823
}
824

    
825
/****f* pfsense-utils/reload_all
826
 * NAME
827
 *   reload_all - triggers a reload of all settings
828
 *   * INPUTS
829
 *   none
830
 * RESULT
831
 *   none
832
 ******/
833
function reload_all() {
834
	send_event("service reload all");
835
}
836

    
837
/****f* pfsense-utils/reload_interfaces
838
 * NAME
839
 *   reload_interfaces - triggers a reload of all interfaces
840
 * INPUTS
841
 *   none
842
 * RESULT
843
 *   none
844
 ******/
845
function reload_interfaces() {
846
	send_event("interface all reload");
847
}
848

    
849
/****f* pfsense-utils/reload_all_sync
850
 * NAME
851
 *   reload_all - reload all settings
852
 *   * INPUTS
853
 *   none
854
 * RESULT
855
 *   none
856
 ******/
857
function reload_all_sync() {
858
	global $config, $g;
859

    
860
	$g['booting'] = false;
861

    
862
	/* parse config.xml again */
863
	$config = parse_config(true);
864

    
865
	/* set up our timezone */
866
	system_timezone_configure();
867

    
868
	/* set up our hostname */
869
	system_hostname_configure();
870

    
871
	/* make hosts file */
872
	system_hosts_generate();
873

    
874
	/* generate resolv.conf */
875
	system_resolvconf_generate();
876

    
877
	/* enable routing */
878
	system_routing_enable();
879

    
880
	/* set up interfaces */
881
	interfaces_configure();
882

    
883
	/* start dyndns service */
884
	services_dyndns_configure();
885

    
886
	/* configure cron service */
887
	configure_cron();
888

    
889
	/* start the NTP client */
890
	system_ntp_configure();
891

    
892
	/* sync pw database */
893
	conf_mount_rw();
894
	unlink_if_exists("/etc/spwd.db.tmp");
895
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
896
	conf_mount_ro();
897

    
898
	/* restart sshd */
899
	send_event("service restart sshd");
900

    
901
	/* restart webConfigurator if needed */
902
	send_event("service restart webgui");
903
}
904

    
905
function setup_serial_port($when="save", $path="") {
906
	global $g, $config;
907
	conf_mount_rw();
908
	$prefix = "";
909
	if (($when == "upgrade") && (!empty($path)) && is_dir($path.'/boot/'))
910
		$prefix = "/tmp/{$path}";
911
	$boot_config_file = "{$path}/boot.config";
912
	$loader_conf_file = "{$path}/boot/loader.conf";
913
	/* serial console - write out /boot.config */
914
	if(file_exists($boot_config_file))
915
		$boot_config = file_get_contents($boot_config_file);
916
	else
917
		$boot_config = "";
918

    
919
	$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "115200";
920
	if ($g['platform'] != "cdrom") {
921
		$boot_config_split = explode("\n", $boot_config);
922
		$fd = fopen($boot_config_file,"w");
923
		if($fd) {
924
			foreach($boot_config_split as $bcs) {
925
				if(stristr($bcs, "-D") || stristr($bcs, "-h")) {
926
					/* DONT WRITE OUT, WE'LL DO IT LATER */
927
				} else {
928
					if($bcs <> "")
929
						fwrite($fd, "{$bcs}\n");
930
				}
931
			}
932
			if (($g['platform'] == "nanobsd") && !file_exists("/etc/nano_use_vga.txt"))
933
				fwrite($fd, "-S{$serialspeed} -h");
934
			else if (is_serial_enabled())
935
				fwrite($fd, "-S{$serialspeed} -D");
936
			fclose($fd);
937
		}
938

    
939
		/* serial console - write out /boot/loader.conf */
940
		if ($when == "upgrade")
941
			system("echo \"Reading {$loader_conf_file}...\" >> /conf/upgrade_log.txt");
942
		$boot_config = file_get_contents($loader_conf_file);
943
		$boot_config_split = explode("\n", $boot_config);
944
		if(count($boot_config_split) > 0) {
945
			$new_boot_config = array();
946
			// Loop through and only add lines that are not empty, and which
947
			//  do not contain a console directive.
948
			foreach($boot_config_split as $bcs)
949
				if(!empty($bcs)
950
					&& (stripos($bcs, "console") === false)
951
					&& (stripos($bcs, "boot_multicons") === false)
952
					&& (stripos($bcs, "boot_serial") === false)
953
					&& (stripos($bcs, "hw.usb.no_pf") === false))
954
					$new_boot_config[] = $bcs;
955

    
956
			if (($g['platform'] == "nanobsd") && !file_exists("/etc/nano_use_vga.txt")) {
957
				$new_boot_config[] = 'boot_serial="YES"';
958
				$new_boot_config[] = 'console="comconsole"';
959
			} else if (is_serial_enabled()) {
960
				$new_boot_config[] = 'boot_multicons="YES"';
961
				$new_boot_config[] = 'boot_serial="YES"';
962
				$primaryconsole = isset($g['primaryconsole_force']) ? $g['primaryconsole_force'] : $config['system']['primaryconsole'];
963
				switch ($primaryconsole) {
964
					case "video":
965
						$new_boot_config[] = 'console="vidconsole,comconsole"';
966
						break;
967
					case "serial":
968
					default:
969
						$new_boot_config[] = 'console="comconsole,vidconsole"';
970
				}
971
			}
972
			$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
973
			$new_boot_config[] = 'hw.usb.no_pf="1"';
974

    
975
			file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n");
976
		}
977
	}
978
	$ttys = file_get_contents("/etc/ttys");
979
	$ttys_split = explode("\n", $ttys);
980
	$fd = fopen("/etc/ttys", "w");
981

    
982
	$on_off = (is_serial_enabled() ? 'on' : 'off');
983

    
984
	if (isset($config['system']['disableconsolemenu'])) {
985
		$console_type = 'Pc';
986
		$serial_type = 'std.' . $serialspeed;
987
	} else {
988
		$console_type = 'al.Pc';
989
		$serial_type = 'al.' . $serialspeed;
990
	}
991
	foreach($ttys_split as $tty) {
992
		if (stristr($tty, "ttyv0"))
993
			fwrite($fd, "ttyv0	\"/usr/libexec/getty {$console_type}\"	cons25	on	secure\n");
994
		else if (stristr($tty, "ttyu0"))
995
			fwrite($fd, "ttyu0	\"/usr/libexec/getty {$serial_type}\"	cons25	{$on_off}	secure\n");
996
		else
997
			fwrite($fd, $tty . "\n");
998
	}
999
	unset($on_off, $console_type, $serial_type);
1000
	fclose($fd);
1001
	reload_ttys();
1002

    
1003
	conf_mount_ro();
1004
	return;
1005
}
1006

    
1007
function is_serial_enabled() {
1008
	global $g, $config;
1009

    
1010
	if (!isset($g['enableserial_force']) &&
1011
	    !isset($config['system']['enableserial']) &&
1012
	    ($g['platform'] == "pfSense" || $g['platform'] == "cdrom" || file_exists("/etc/nano_use_vga.txt")))
1013
		return false;
1014

    
1015
	return true;
1016
}
1017

    
1018
function reload_ttys() {
1019
	// Send a HUP signal to init will make it reload /etc/ttys
1020
	posix_kill(1, SIGHUP);
1021
}
1022

    
1023
function print_value_list($list, $count = 10, $separator = ",") {
1024
	$list = implode($separator, array_slice($list, 0, $count));
1025
	if(count($list) < $count) {
1026
		$list .= ".";
1027
	} else {
1028
		$list .= "...";
1029
	}
1030
	return $list;
1031
}
1032

    
1033
/* DHCP enabled on any interfaces? */
1034
function is_dhcp_server_enabled() {
1035
	global $config;
1036

    
1037
	if (!is_array($config['dhcpd']))
1038
		return false;
1039

    
1040
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1041
		if (isset($dhcpifconf['enable']) && !empty($config['interfaces'][$dhcpif]))
1042
			return true;
1043
	}
1044

    
1045
	return false;
1046
}
1047

    
1048
/* DHCP enabled on any interfaces? */
1049
function is_dhcpv6_server_enabled() {
1050
	global $config;
1051

    
1052
	if (is_array($config['interfaces'])) {
1053
		foreach ($config['interfaces'] as $ifcfg) {
1054
			if (isset($ifcfg['enable']) && !empty($ifcfg['track6-interface']))
1055
				return true;
1056
		}
1057
	}
1058

    
1059
	if (!is_array($config['dhcpdv6']))
1060
		return false;
1061

    
1062
	foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1063
		if (isset($dhcpv6ifconf['enable']) && !empty($config['interfaces'][$dhcpv6if]))
1064
			return true;
1065
	}
1066

    
1067
	return false;
1068
}
1069

    
1070
/* radvd enabled on any interfaces? */
1071
function is_radvd_enabled() {
1072
	global $config;
1073

    
1074
	if (!is_array($config['dhcpdv6']))
1075
		$config['dhcpdv6'] = array();
1076

    
1077
	$dhcpdv6cfg = $config['dhcpdv6'];
1078
	$Iflist = get_configured_interface_list();
1079

    
1080
	/* handle manually configured DHCP6 server settings first */
1081
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1082
		if(!isset($config['interfaces'][$dhcpv6if]['enable']))
1083
			continue;
1084

    
1085
		if(!isset($dhcpv6ifconf['ramode']))
1086
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1087

    
1088
		if($dhcpv6ifconf['ramode'] == "disabled")
1089
			continue;
1090

    
1091
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1092
		if(!is_ipaddrv6($ifcfgipv6))
1093
			continue;
1094

    
1095
		return true;
1096
	}
1097

    
1098
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
1099
	foreach ($Iflist as $if => $ifdescr) {
1100
		if(!isset($config['interfaces'][$if]['track6-interface']))
1101
			continue;
1102
		if(!isset($config['interfaces'][$if]['enable']))
1103
			continue;
1104

    
1105
		$ifcfgipv6 = get_interface_ipv6($if);
1106
		if(!is_ipaddrv6($ifcfgipv6))
1107
			continue;
1108

    
1109
		$ifcfgsnv6 = get_interface_subnetv6($if);
1110
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1111

    
1112
		if(!is_ipaddrv6($subnetv6))
1113
			continue;
1114

    
1115
		return true;
1116
	}
1117

    
1118
	return false;
1119
}
1120

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

    
1125
	$pppoeenable = false;
1126

    
1127
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1128
		return false;
1129

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

    
1134
	return $pppoeenable;
1135
}
1136

    
1137
function convert_seconds_to_hms($sec){
1138
	$min=$hrs=0;
1139
	if ($sec != 0){
1140
		$min = floor($sec/60);
1141
		$sec %= 60;
1142
	}
1143
	if ($min != 0){
1144
		$hrs = floor($min/60);
1145
		$min %= 60;
1146
	}
1147
	if ($sec < 10)
1148
		$sec = "0".$sec;
1149
	if ($min < 10)
1150
		$min = "0".$min;
1151
	if ($hrs < 10)
1152
		$hrs = "0".$hrs;
1153
	$result = $hrs.":".$min.":".$sec;
1154
	return $result;
1155
}
1156

    
1157
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1158

    
1159
function get_ppp_uptime($port){
1160
	if (file_exists("/conf/{$port}.log")){
1161
		$saved_time = file_get_contents("/conf/{$port}.log");
1162
		$uptime_data = explode("\n",$saved_time);
1163
		$sec=0;
1164
		foreach($uptime_data as $upt) {
1165
			$sec += substr($upt, 1 + strpos($upt, " "));
1166
		}
1167
		return convert_seconds_to_hms($sec);
1168
	} else {
1169
		$total_time = gettext("No history data found!");
1170
		return $total_time;
1171
	}
1172
}
1173

    
1174
//returns interface information
1175
function get_interface_info($ifdescr) {
1176
	global $config, $g;
1177

    
1178
	$ifinfo = array();
1179
	if (empty($config['interfaces'][$ifdescr]))
1180
		return;
1181
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1182
	$ifinfo['if'] = get_real_interface($ifdescr);
1183

    
1184
	$chkif = $ifinfo['if'];
1185
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1186
	$ifinfo['status'] = $ifinfotmp['status'];
1187
	if (empty($ifinfo['status']))
1188
		$ifinfo['status'] = "down";
1189
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1190
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1191
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1192
	$ifinfo['linklocal'] = get_interface_linklocal($ifdescr);
1193
	$ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr);
1194
	$ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr);
1195
	if (isset($ifinfotmp['link0']))
1196
		$link0 = "down";
1197
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1198
	// $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1199
	// $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1200
	$ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1201
	$ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1202
	$ifinfo['collisions'] = $ifinfotmp['collisions'];
1203

    
1204
	/* Use pfctl for non wrapping 64 bit counters */
1205
	/* Pass */
1206
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1207
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1208
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1209
	$pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]);
1210
	$pf_out6_pass = preg_split("/ +/", $pfctlstats[9]);
1211
	$in4_pass = $pf_in4_pass[5];
1212
	$out4_pass = $pf_out4_pass[5];
1213
	$in4_pass_packets = $pf_in4_pass[3];
1214
	$out4_pass_packets = $pf_out4_pass[3];
1215
	$in6_pass = $pf_in6_pass[5];
1216
	$out6_pass = $pf_out6_pass[5];
1217
	$in6_pass_packets = $pf_in6_pass[3];
1218
	$out6_pass_packets = $pf_out6_pass[3];
1219
	$ifinfo['inbytespass'] = $in4_pass + $in6_pass;
1220
	$ifinfo['outbytespass'] = $out4_pass + $out6_pass;
1221
	$ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets;
1222
	$ifinfo['outpktspass'] = $out4_pass_packets + $out6_pass_packets;
1223

    
1224
	/* Block */
1225
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1226
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1227
	$pf_in6_block = preg_split("/ +/", $pfctlstats[8]);
1228
	$pf_out6_block = preg_split("/ +/", $pfctlstats[10]);
1229
	$in4_block = $pf_in4_block[5];
1230
	$out4_block = $pf_out4_block[5];
1231
	$in4_block_packets = $pf_in4_block[3];
1232
	$out4_block_packets = $pf_out4_block[3];
1233
	$in6_block = $pf_in6_block[5];
1234
	$out6_block = $pf_out6_block[5];
1235
	$in6_block_packets = $pf_in6_block[3];
1236
	$out6_block_packets = $pf_out6_block[3];
1237
	$ifinfo['inbytesblock'] = $in4_block + $in6_block;
1238
	$ifinfo['outbytesblock'] = $out4_block + $out6_block;
1239
	$ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets;
1240
	$ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets;
1241

    
1242
	$ifinfo['inbytes'] = $in4_pass + $in6_pass;
1243
	$ifinfo['outbytes'] = $out4_pass + $out6_pass;
1244
	$ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets;
1245
	$ifinfo['outpkts'] = $out4_pass_packets + $out6_pass_packets;
1246

    
1247
	$ifconfiginfo = "";
1248
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1249
	switch ($link_type) {
1250
	/* DHCP? -> see if dhclient is up */
1251
	case "dhcp":
1252
		/* see if dhclient is up */
1253
		if (find_dhclient_process($ifinfo['if']) != 0)
1254
			$ifinfo['dhcplink'] = "up";
1255
		else
1256
			$ifinfo['dhcplink'] = "down";
1257

    
1258
		break;
1259
	/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1260
	case "pppoe":
1261
	case "pptp":
1262
	case "l2tp":
1263
		if ($ifinfo['status'] == "up" && !isset($link0))
1264
			/* get PPPoE link status for dial on demand */
1265
			$ifinfo["{$link_type}link"] = "up";
1266
		else
1267
			$ifinfo["{$link_type}link"] = "down";
1268

    
1269
		break;
1270
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1271
	case "ppp":
1272
		if ($ifinfo['status'] == "up")
1273
			$ifinfo['ppplink'] = "up";
1274
		else
1275
			$ifinfo['ppplink'] = "down" ;
1276

    
1277
		if (empty($ifinfo['status']))
1278
			$ifinfo['status'] = "down";
1279

    
1280
		if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1281
			foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1282
				if ($config['interfaces'][$ifdescr]['if'] == $ppp['if'])
1283
					break;
1284
			}
1285
		}
1286
		$dev = $ppp['ports'];
1287
		if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev))
1288
			break;
1289
		if (!file_exists($dev)) {
1290
			$ifinfo['nodevice'] = 1;
1291
			$ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?");
1292
		}
1293

    
1294
		$usbmodemoutput = array();
1295
		exec("usbconfig", $usbmodemoutput);
1296
		$mondev = "{$g['tmp_path']}/3gstats.{$ifdescr}";
1297
		if(file_exists($mondev)) {
1298
			$cellstats = file($mondev);
1299
			/* skip header */
1300
			$a_cellstats = explode(",", $cellstats[1]);
1301
			if(preg_match("/huawei/i", implode("\n", $usbmodemoutput))) {
1302
				$ifinfo['cell_rssi'] = huawei_rssi_to_string($a_cellstats[1]);
1303
				$ifinfo['cell_mode'] = huawei_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1304
				$ifinfo['cell_simstate'] = huawei_simstate_to_string($a_cellstats[10]);
1305
				$ifinfo['cell_service'] = huawei_service_to_string(trim($a_cellstats[11]));
1306
			}
1307
			if(preg_match("/zte/i", implode("\n", $usbmodemoutput))) {
1308
				$ifinfo['cell_rssi'] = zte_rssi_to_string($a_cellstats[1]);
1309
				$ifinfo['cell_mode'] = zte_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1310
				$ifinfo['cell_simstate'] = zte_simstate_to_string($a_cellstats[10]);
1311
				$ifinfo['cell_service'] = zte_service_to_string(trim($a_cellstats[11]));
1312
			}
1313
			$ifinfo['cell_upstream'] = $a_cellstats[4];
1314
			$ifinfo['cell_downstream'] = trim($a_cellstats[5]);
1315
			$ifinfo['cell_sent'] = $a_cellstats[6];
1316
			$ifinfo['cell_received'] = trim($a_cellstats[7]);
1317
			$ifinfo['cell_bwupstream'] = $a_cellstats[8];
1318
			$ifinfo['cell_bwdownstream'] = trim($a_cellstats[9]);
1319
		}
1320
		// Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over!
1321
		if (isset($ppp['uptime']))
1322
			$ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")";
1323
		break;
1324
	default:
1325
		break;
1326
	}
1327

    
1328
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1329
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1330
		$ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec);
1331
	}
1332

    
1333
	if ($ifinfo['status'] == "up") {
1334
		/* try to determine media with ifconfig */
1335
		unset($ifconfiginfo);
1336
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1337
		$wifconfiginfo = array();
1338
		if(is_interface_wireless($ifdescr)) {
1339
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1340
			array_shift($wifconfiginfo);
1341
		}
1342
		$matches = "";
1343
		foreach ($ifconfiginfo as $ici) {
1344

    
1345
			/* don't list media/speed for wireless cards, as it always
1346
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1347
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1348
				$ifinfo['media'] = $matches[1];
1349
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1350
				$ifinfo['media'] = $matches[1];
1351
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1352
				$ifinfo['media'] = $matches[1];
1353
			}
1354

    
1355
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1356
				if ($matches[1] != "active")
1357
					$ifinfo['status'] = $matches[1];
1358
				if($ifinfo['status'] == gettext("running"))
1359
					$ifinfo['status'] = gettext("up");
1360
			}
1361
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1362
				$ifinfo['channel'] = $matches[1];
1363
			}
1364
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1365
				if ($matches[1][0] == '"')
1366
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1367
				else
1368
					$ifinfo['ssid'] = $matches[1];
1369
			}
1370
			if (preg_match("/laggproto (.*)$/", $ici, $matches)) {
1371
				$ifinfo['laggproto'] = $matches[1];
1372
			}
1373
			if (preg_match("/laggport: (.*)$/", $ici, $matches)) {
1374
				$ifinfo['laggport'][] = $matches[1];
1375
			}
1376
		}
1377
		foreach($wifconfiginfo as $ici) {
1378
			$elements = preg_split("/[ ]+/i", $ici);
1379
			if ($elements[0] != "") {
1380
				$ifinfo['bssid'] = $elements[0];
1381
			}
1382
			if ($elements[3] != "") {
1383
				$ifinfo['rate'] = $elements[3];
1384
			}
1385
			if ($elements[4] != "") {
1386
				$ifinfo['rssi'] = $elements[4];
1387
			}
1388

    
1389
		}
1390
		/* lookup the gateway */
1391
		if (interface_has_gateway($ifdescr)) {
1392
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1393
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1394
		}
1395
	}
1396

    
1397
	$bridge = "";
1398
	$bridge = link_interface_to_bridge($ifdescr);
1399
	if($bridge) {
1400
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1401
		if(stristr($bridge_text, "blocking") <> false) {
1402
			$ifinfo['bridge'] = "<b><font color='red'>" . gettext("blocking") . "</font></b> - " . gettext("check for ethernet loops");
1403
			$ifinfo['bridgeint'] = $bridge;
1404
		} else if(stristr($bridge_text, "learning") <> false) {
1405
			$ifinfo['bridge'] = gettext("learning");
1406
			$ifinfo['bridgeint'] = $bridge;
1407
		} else if(stristr($bridge_text, "forwarding") <> false) {
1408
			$ifinfo['bridge'] = gettext("forwarding");
1409
			$ifinfo['bridgeint'] = $bridge;
1410
		}
1411
	}
1412

    
1413
	return $ifinfo;
1414
}
1415

    
1416
//returns cpu speed of processor. Good for determining capabilities of machine
1417
function get_cpu_speed() {
1418
	return get_single_sysctl("hw.clockrate");
1419
}
1420

    
1421
function get_uptime_sec() {
1422
	$boottime = "";
1423
	$matches = "";
1424
	$boottime = get_single_sysctl("kern.boottime");
1425
	preg_match("/sec = (\d+)/", $boottime, $matches);
1426
	$boottime = $matches[1];
1427
	if(intval($boottime) == 0)
1428
		return 0;
1429

    
1430
	$uptime = time() - $boottime;
1431
	return $uptime;
1432
}
1433

    
1434
function add_hostname_to_watch($hostname) {
1435
	if(!is_dir("/var/db/dnscache")) {
1436
		mkdir("/var/db/dnscache");
1437
	}
1438
	$result = array();
1439
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1440
		$domrecords = array();
1441
		$domips = array();
1442
		exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1443
		if($rethost == 0) {
1444
			foreach($domrecords as $domr) {
1445
				$doml = explode(" ", $domr);
1446
				$domip = $doml[3];
1447
				/* fill array with domain ip addresses */
1448
				if(is_ipaddr($domip)) {
1449
					$domips[] = $domip;
1450
				}
1451
			}
1452
		}
1453
		sort($domips);
1454
		$contents = "";
1455
		if(! empty($domips)) {
1456
			foreach($domips as $ip) {
1457
				$contents .= "$ip\n";
1458
			}
1459
		}
1460
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1461
		/* Remove empty elements */
1462
		$result = array_filter(explode("\n", $contents), 'strlen');
1463
	}
1464
	return $result;
1465
}
1466

    
1467
function is_fqdn($fqdn) {
1468
	$hostname = false;
1469
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1470
		$hostname = true;
1471
	}
1472
	if(preg_match("/\.\./", $fqdn)) {
1473
		$hostname = false;
1474
	}
1475
	if(preg_match("/^\./i", $fqdn)) {
1476
		$hostname = false;
1477
	}
1478
	if(preg_match("/\//i", $fqdn)) {
1479
		$hostname = false;
1480
	}
1481
	return($hostname);
1482
}
1483

    
1484
function pfsense_default_state_size() {
1485
	/* get system memory amount */
1486
	$memory = get_memory();
1487
	$physmem = $memory[0];
1488
	/* Be cautious and only allocate 10% of system memory to the state table */
1489
	$max_states = (int) ($physmem/10)*1000;
1490
	return $max_states;
1491
}
1492

    
1493
function pfsense_default_tables_size() {
1494
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1495
	return $current;
1496
}
1497

    
1498
function pfsense_default_table_entries_size() {
1499
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1500
	return $current;
1501
}
1502

    
1503
/* Compare the current hostname DNS to the DNS cache we made
1504
 * if it has changed we return the old records
1505
 * if no change we return false */
1506
function compare_hostname_to_dnscache($hostname) {
1507
	if(!is_dir("/var/db/dnscache")) {
1508
		mkdir("/var/db/dnscache");
1509
	}
1510
	$hostname = trim($hostname);
1511
	if(is_readable("/var/db/dnscache/{$hostname}")) {
1512
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1513
	} else {
1514
		$oldcontents = "";
1515
	}
1516
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1517
		$domrecords = array();
1518
		$domips = array();
1519
		exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1520
		if($rethost == 0) {
1521
			foreach($domrecords as $domr) {
1522
				$doml = explode(" ", $domr);
1523
				$domip = $doml[3];
1524
				/* fill array with domain ip addresses */
1525
				if(is_ipaddr($domip)) {
1526
					$domips[] = $domip;
1527
				}
1528
			}
1529
		}
1530
		sort($domips);
1531
		$contents = "";
1532
		if(! empty($domips)) {
1533
			foreach($domips as $ip) {
1534
				$contents .= "$ip\n";
1535
			}
1536
		}
1537
	}
1538

    
1539
	if(trim($oldcontents) != trim($contents)) {
1540
		if($g['debug']) {
1541
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1542
		}
1543
		return ($oldcontents);
1544
	} else {
1545
		return false;
1546
	}
1547
}
1548

    
1549
/*
1550
 * load_crypto() - Load crypto modules if enabled in config.
1551
 */
1552
function load_crypto() {
1553
	global $config, $g;
1554
	$crypto_modules = array('glxsb', 'aesni');
1555

    
1556
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules))
1557
		return false;
1558

    
1559
	if (!empty($config['system']['crypto_hardware']) && !is_module_loaded($config['system']['crypto_hardware'])) {
1560
		log_error("Loading {$config['system']['crypto_hardware']} cryptographic accelerator module.");
1561
		mwexec("/sbin/kldload {$config['system']['crypto_hardware']}");
1562
	}
1563
}
1564

    
1565
/*
1566
 * load_thermal_hardware() - Load temperature monitor kernel module
1567
 */
1568
function load_thermal_hardware() {
1569
	global $config, $g;
1570
	$thermal_hardware_modules = array('coretemp', 'amdtemp');
1571

    
1572
	if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules))
1573
		return false;
1574

    
1575
	if (!empty($config['system']['thermal_hardware']) && !is_module_loaded($config['system']['thermal_hardware'])) {
1576
		log_error("Loading {$config['system']['thermal_hardware']} thermal monitor module.");
1577
		mwexec("/sbin/kldload {$config['system']['thermal_hardware']}");
1578
	}
1579
}
1580

    
1581
/****f* pfsense-utils/isvm
1582
 * NAME
1583
 *   isvm
1584
 * INPUTS
1585
 *	none
1586
 * RESULT
1587
 *   returns true if machine is running under a virtual environment
1588
 ******/
1589
function isvm() {
1590
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1591
	$bios_product = trim(`/bin/kenv smbios.system.product`);
1592
	foreach ($virtualenvs as $virtualenv)
1593
		if (stripos($bios_product, $virtualenv) !== false)
1594
			return true;
1595

    
1596
	return false;
1597
}
1598

    
1599
function get_freebsd_version() {
1600
	$version = explode(".", php_uname("r"));
1601
	return $version[0];
1602
}
1603

    
1604
function download_file($url, $destination, $verify_ssl = false, $connect_timeout = 60, $timeout = 0) {
1605
	global $config, $g;
1606

    
1607
	$fp = fopen($destination, "wb");
1608

    
1609
	if (!$fp)
1610
		return false;
1611

    
1612
	$ch = curl_init();
1613
	curl_setopt($ch, CURLOPT_URL, $url);
1614
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_ssl);
1615
	curl_setopt($ch, CURLOPT_FILE, $fp);
1616
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1617
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1618
	curl_setopt($ch, CURLOPT_HEADER, false);
1619
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1620
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version")));
1621

    
1622
	if (!empty($config['system']['proxyurl'])) {
1623
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1624
		if (!empty($config['system']['proxyport']))
1625
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1626
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1627
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1628
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1629
		}
1630
	}
1631

    
1632
	@curl_exec($ch);
1633
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1634
	fclose($fp);
1635
	curl_close($ch);
1636
	return ($http_code == 200) ? true : $http_code;
1637
}
1638

    
1639
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1640
	global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update;
1641
	$file_size  = 1;
1642
	$downloaded = 1;
1643
	$first_progress_update = TRUE;
1644
	/* open destination file */
1645
	$fout = fopen($destination_file, "wb");
1646

    
1647
	/*
1648
	 *      Originally by Author: Keyvan Minoukadeh
1649
	 *      Modified by Scott Ullrich to return Content-Length size
1650
	 */
1651

    
1652
	$ch = curl_init();
1653
	curl_setopt($ch, CURLOPT_URL, $url_file);
1654
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1655
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1656
	/* Don't verify SSL peers since we don't have the certificates to do so. */
1657
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1658
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1659
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1660
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1661
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1662
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version")));
1663

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

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

    
1682
function read_header($ch, $string) {
1683
	global $file_size, $fout;
1684
	$length = strlen($string);
1685
	$regs = "";
1686
	preg_match("/(Content-Length:) (.*)/", $string, $regs);
1687
	if($regs[2] <> "") {
1688
		$file_size = intval($regs[2]);
1689
	}
1690
	ob_flush();
1691
	return $length;
1692
}
1693

    
1694
function read_body($ch, $string) {
1695
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $first_progress_update;
1696
	global $pkg_interface;
1697
	$length = strlen($string);
1698
	$downloaded += intval($length);
1699
	if($file_size > 0) {
1700
		$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1701
		$downloadProgress = 100 - $downloadProgress;
1702
	} else
1703
		$downloadProgress = 0;
1704
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1705
		if($sendto == "status") {
1706
			if($pkg_interface == "console") {
1707
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1708
					$tostatus = $static_status . $downloadProgress . "%";
1709
					if ($downloadProgress == 100) {
1710
						$tostatus = $tostatus . "\r";
1711
					}
1712
					update_status($tostatus);
1713
				}
1714
			} else {
1715
				$tostatus = $static_status . $downloadProgress . "%";
1716
				update_status($tostatus);
1717
			}
1718
		} else {
1719
			if($pkg_interface == "console") {
1720
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1721
					$tooutput = $static_output . $downloadProgress . "%";
1722
					if ($downloadProgress == 100) {
1723
						$tooutput = $tooutput . "\r";
1724
					}
1725
					update_output_window($tooutput);
1726
				}
1727
			} else {
1728
				$tooutput = $static_output . $downloadProgress . "%";
1729
				update_output_window($tooutput);
1730
			}
1731
		}
1732
				if(($pkg_interface != "console") || (($downloadProgress % 10) == 0) || ($downloadProgress < 10)) {
1733
					update_progress_bar($downloadProgress, $first_progress_update);
1734
					$first_progress_update = FALSE;
1735
				}
1736
		$lastseen = $downloadProgress;
1737
	}
1738
	if($fout)
1739
		fwrite($fout, $string);
1740
	ob_flush();
1741
	return $length;
1742
}
1743

    
1744
/*
1745
 *   update_output_window: update bottom textarea dynamically.
1746
 */
1747
function update_output_window($text) {
1748
	global $pkg_interface;
1749
	$log = preg_replace("/\n/", "\\n", $text);
1750
	if($pkg_interface != "console") {
1751
		echo "\n<script type=\"text/javascript\">";
1752
		echo "\n//<![CDATA[";
1753
		echo "\nthis.document.forms[0].output.value = \"" . $log . "\";";
1754
		echo "\nthis.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;";
1755
		echo "\n//]]>";
1756
		echo "\n</script>";
1757
	}
1758
	/* ensure that contents are written out */
1759
	ob_flush();
1760
}
1761

    
1762
/*
1763
 *   update_status: update top textarea dynamically.
1764
 */
1765
function update_status($status) {
1766
	global $pkg_interface;
1767
	if($pkg_interface == "console") {
1768
		echo "\r{$status}";
1769
	} else {
1770
		echo "\n<script type=\"text/javascript\">";
1771
		echo "\n//<![CDATA[";
1772
		echo "\nthis.document.forms[0].status.value=\"" . $status . "\";";
1773
		echo "\n//]]>";
1774
		echo "\n</script>";
1775
	}
1776
	/* ensure that contents are written out */
1777
	ob_flush();
1778
}
1779

    
1780
/*
1781
 * update_progress_bar($percent, $first_time): updates the javascript driven progress bar.
1782
 */
1783
function update_progress_bar($percent, $first_time) {
1784
	global $pkg_interface;
1785
	if($percent > 100) $percent = 1;
1786
	if($pkg_interface <> "console") {
1787
		echo "\n<script type=\"text/javascript\">";
1788
		echo "\n//<![CDATA[";
1789
		echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1790
		echo "\n//]]>";
1791
		echo "\n</script>";
1792
	} else {
1793
		if(!($first_time))
1794
			echo "\x08\x08\x08\x08\x08";
1795
		echo sprintf("%4d%%", $percent);
1796
	}
1797
}
1798

    
1799
/* 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. */
1800
if(!function_exists("split")) {
1801
	function split($separator, $haystack, $limit = null) {
1802
		log_error("deprecated split() call with separator '{$separator}'");
1803
		return preg_split($separator, $haystack, $limit);
1804
	}
1805
}
1806

    
1807
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1808
	global $g, $config, $pconfig, $debug;
1809
	if(!$origname)
1810
		return;
1811

    
1812
	$sectionref = &$config;
1813
	foreach($section as $sectionname) {
1814
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1815
			$sectionref = &$sectionref[$sectionname];
1816
		else
1817
			return;
1818
	}
1819

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

    
1823
	if(is_array($sectionref)) {
1824
		foreach($sectionref as $itemkey => $item) {
1825
			if($debug) fwrite($fd, "$itemkey\n");
1826

    
1827
			$fieldfound = true;
1828
			$fieldref = &$sectionref[$itemkey];
1829
			foreach($field as $fieldname) {
1830
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1831
					$fieldref = &$fieldref[$fieldname];
1832
				else {
1833
					$fieldfound = false;
1834
					break;
1835
				}
1836
			}
1837
			if($fieldfound && $fieldref == $origname) {
1838
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1839
				$fieldref = $new_alias_name;
1840
			}
1841
		}
1842
	}
1843

    
1844
	if($debug) fclose($fd);
1845

    
1846
}
1847

    
1848
function update_alias_url_data() {
1849
	global $config, $g;
1850

    
1851
	$updated = false;
1852

    
1853
	/* item is a url type */
1854
	$lockkey = lock('aliasurl');
1855
	if (is_array($config['aliases']['alias'])) {
1856
		foreach ($config['aliases']['alias'] as $x => $alias) {
1857
			if (empty($alias['aliasurl']))
1858
				continue;
1859

    
1860
			$address = "";
1861
			$isfirst = 0;
1862
			foreach ($alias['aliasurl'] as $alias_url) {
1863
				/* fetch down and add in */
1864
				$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1865
				unlink($temp_filename);
1866
				$verify_ssl = isset($config['system']['checkaliasesurlcert']);
1867
				mkdir($temp_filename);
1868
				download_file($alias_url, $temp_filename . "/aliases", $verify_ssl);
1869

    
1870
				/* if the item is tar gzipped then extract */
1871
				if (stripos($alias_url, '.tgz')) {
1872
					if (!process_alias_tgz($temp_filename))
1873
						continue;
1874
				} else if (stripos($alias_url, '.zip')) {
1875
					if (!process_alias_unzip($temp_filename))
1876
						continue;
1877
				}
1878
				if (file_exists("{$temp_filename}/aliases")) {
1879
					$fd = @fopen("{$temp_filename}/aliases", 'r');
1880
					if (!$fd) {
1881
						log_error(gettext("Could not process aliases from alias: {$alias_url}"));
1882
						continue;
1883
					}
1884
					/* NOTE: fgetss() is not a typo RTFM before being smart */
1885
					while (($fc = fgetss($fd)) !== FALSE) {
1886
						$tmp = trim($fc, " \t\n\r");
1887
						if (empty($tmp))
1888
							continue;
1889
						$tmp_str = strstr($tmp, '#', true);
1890
						if (!empty($tmp_str))
1891
							$tmp = $tmp_str;
1892
						if ($isfirst == 1)
1893
							$address .= ' ';
1894
						$address .= $tmp;
1895
						$isfirst = 1;
1896
					}
1897
					fclose($fd);
1898
					mwexec("/bin/rm -rf {$temp_filename}");
1899
				}
1900
			}
1901
			if (!empty($address)) {
1902
				$config['aliases']['alias'][$x]['address'] = $address;
1903
				$updated = true;
1904
			}
1905
		}
1906
	}
1907
	unlock($lockkey);
1908

    
1909
	/* Report status to callers as well */
1910
	return $updated;
1911
}
1912

    
1913
function process_alias_unzip($temp_filename) {
1914
	if(!file_exists("/usr/local/bin/unzip")) {
1915
		log_error(gettext("Alias archive is a .zip file which cannot be decompressed because utility is missing!"));
1916
		return false;
1917
	}
1918
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.zip");
1919
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1920
	unlink("{$temp_filename}/aliases.zip");
1921
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1922
	/* foreach through all extracted files and build up aliases file */
1923
	$fd = @fopen("{$temp_filename}/aliases", "w");
1924
	if (!$fd) {
1925
		log_error(gettext("Could not open {$temp_filename}/aliases for writing!"));
1926
		return false;
1927
	}
1928
	foreach($files_to_process as $f2p) {
1929
		$tmpfd = @fopen($f2p, 'r');
1930
		if (!$tmpfd) {
1931
			log_error(gettext("The following file could not be read {$f2p} from {$temp_filename}"));
1932
			continue;
1933
		}
1934
		while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE)
1935
			fwrite($fd, $tmpbuf);
1936
		fclose($tmpfd);
1937
		unlink($f2p);
1938
	}
1939
	fclose($fd);
1940
	unset($tmpbuf);
1941

    
1942
	return true;
1943
}
1944

    
1945
function process_alias_tgz($temp_filename) {
1946
	if(!file_exists('/usr/bin/tar')) {
1947
		log_error(gettext("Alias archive is a .tar/tgz file which cannot be decompressed because utility is missing!"));
1948
		return false;
1949
	}
1950
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.tgz");
1951
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1952
	unlink("{$temp_filename}/aliases.tgz");
1953
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1954
	/* foreach through all extracted files and build up aliases file */
1955
	$fd = @fopen("{$temp_filename}/aliases", "w");
1956
	if (!$fd) {
1957
		log_error(gettext("Could not open {$temp_filename}/aliases for writing!"));
1958
		return false;
1959
	}
1960
	foreach($files_to_process as $f2p) {
1961
		$tmpfd = @fopen($f2p, 'r');
1962
		if (!$tmpfd) {
1963
			log_error(gettext("The following file could not be read {$f2p} from {$temp_filename}"));
1964
			continue;
1965
		}
1966
		while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE)
1967
			fwrite($fd, $tmpbuf);
1968
		fclose($tmpfd);
1969
		unlink($f2p);
1970
	}
1971
	fclose($fd);
1972
	unset($tmpbuf);
1973

    
1974
	return true;
1975
}
1976

    
1977
function version_compare_dates($a, $b) {
1978
	$a_time = strtotime($a);
1979
	$b_time = strtotime($b);
1980

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

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

    
2060
		// First try to compare the numeric parts of the version string.
2061
		$v = version_compare_numeric($cur_num, $rem_num);
2062

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

    
2072
	$urltable_prefix = "/var/db/aliastables/";
2073
	$urltable_filename = $urltable_prefix . $name . ".txt";
2074

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

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

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

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

    
2134
	if ($BOOTFLASH == $ACTIVE_SLICE) {
2135
		$slice = $TOFLASH;
2136
	} else {
2137
		$slice = $BOOTFLASH;
2138
	}
2139

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

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

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

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

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

    
2221
	$BOOT_DEVICE=nanobsd_get_boot_slice();
2222
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
2223
	$BOOT_DRIVE=nanobsd_get_boot_drive();
2224
	$ACTIVE_SLICE=nanobsd_get_active_slice();
2225

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

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

    
2247
function nanobsd_friendly_slice_name($slicename) {
2248
	global $g;
2249
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2250
}
2251

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

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

    
2398
function get_country_name($country_code) {
2399
	if ($country_code != "ALL" && strlen($country_code) != 2)
2400
		return "";
2401

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

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

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

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

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

    
2432
	usort($config['filter']['rule'], "filter_rules_compare");
2433

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

    
2451
function generate_ipv6_from_mac($mac) {
2452
	$elements = explode(":", $mac);
2453
	if(count($elements) <> 6)
2454
		return false;
2455

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

    
2477
		$i++;
2478
	}
2479
	return $ipv6;
2480
}
2481

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

    
2506
}
2507

    
2508
/****f* pfsense-utils/is_ipaddr_configured
2509
 * NAME
2510
 *   is_ipaddr_configured
2511
 * INPUTS
2512
 *   IP Address to check.
2513
 *   If ignore_if is a VIP (not carp), vip array index is passed after string _virtualip
2514
 * RESULT
2515
 *   returns true if the IP Address is
2516
 *   configured and present on this device.
2517
*/
2518
function is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, $check_subnets = false) {
2519
	global $config;
2520

    
2521
	$pos = strpos($ignore_if, '_virtualip');
2522
	if ($pos !== false) {
2523
		$ignore_vip_id = substr($ignore_if, $pos+10);
2524
		$ignore_vip_if = substr($ignore_if, 0, $pos);
2525
	} else {
2526
		$ignore_vip_id = -1;
2527
		$ignore_vip_if = $ignore_if;
2528
	}
2529

    
2530
	$isipv6 = is_ipaddrv6($ipaddr);
2531

    
2532
	if ($check_subnets) {
2533
		$iflist = get_configured_interface_list();
2534
		foreach ($iflist as $if => $ifname) {
2535
			if ($ignore_if == $if)
2536
				continue;
2537

    
2538
			if ($isipv6 === true) {
2539
				$bitmask = get_interface_subnetv6($if);
2540
				$subnet = gen_subnetv6(get_interface_ipv6($if), $bitmask);
2541
			} else {
2542
				$bitmask = get_interface_subnet($if);
2543
				$subnet = gen_subnet(get_interface_ip($if), $bitmask);
2544
			}
2545

    
2546
			if (ip_in_subnet($ipaddr, $subnet . '/' . $bitmask))
2547
				return true;
2548
		}
2549
	} else {
2550
		if ($isipv6 === true)
2551
			$interface_list_ips = get_configured_ipv6_addresses();
2552
		else
2553
			$interface_list_ips = get_configured_ip_addresses();
2554

    
2555
		foreach($interface_list_ips as $if => $ilips) {
2556
			if ($ignore_if == $if)
2557
				continue;
2558
			if (strcasecmp($ipaddr, $ilips) == 0)
2559
				return true;
2560
		}
2561
	}
2562

    
2563
	$interface_list_vips = get_configured_vips_list(true);
2564
	foreach ($interface_list_vips as $id => $vip) {
2565
		/* Skip CARP interfaces here since they were already checked above */
2566
		if ($id == $ignore_vip_id || (strstr($ignore_if, '_vip') && $ignore_vip_if == $vip['if']))
2567
			continue;
2568
		if (strcasecmp($ipaddr, $vip['ipaddr']) == 0)
2569
			return true;
2570
	}
2571

    
2572
	if ($check_localip) {
2573
		if (is_array($config['pptpd']) && !empty($config['pptpd']['localip']) && (strcasecmp($ipaddr, $config['pptpd']['localip']) == 0))
2574
			return true;
2575

    
2576
		if (!is_array($config['l2tp']) && !empty($config['l2tp']['localip']) && (strcasecmp($ipaddr, $config['l2tp']['localip']) == 0))
2577
			return true;
2578
	}
2579

    
2580
	return false;
2581
}
2582

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

    
2604
function set_language($lang = 'en_US', $encoding = "UTF-8") {
2605
	putenv("LANG={$lang}.{$encoding}");
2606
	setlocale(LC_ALL, "{$lang}.{$encoding}");
2607
	textdomain("pfSense");
2608
	bindtextdomain("pfSense","/usr/local/share/locale");
2609
	bind_textdomain_codeset("pfSense","{$lang}.{$encoding}");
2610
}
2611

    
2612
function get_locale_list() {
2613
	$locales = array(
2614
		"en_US" => gettext("English"),
2615
		"pt_BR" => gettext("Portuguese (Brazil)"),
2616
		"tr" => gettext("Turkish"),
2617
	);
2618
	asort($locales);
2619
	return $locales;
2620
}
2621

    
2622
function system_get_language_code() {
2623
	global $config, $g_languages;
2624

    
2625
	// a language code, as per [RFC3066]
2626
	$language = $config['system']['language'];
2627
	//$code = $g_languages[$language]['code'];
2628
	$code = str_replace("_", "-", $language);
2629

    
2630
	if (empty($code))
2631
		$code = "en-US"; // Set default code.
2632

    
2633
	return $code;
2634
}
2635

    
2636
function system_get_language_codeset() {
2637
	global $config, $g_languages;
2638

    
2639
	$language = $config['system']['language'];
2640
	$codeset = $g_languages[$language]['codeset'];
2641

    
2642
	if (empty($codeset))
2643
		$codeset = "UTF-8"; // Set default codeset.
2644

    
2645
	return $codeset;
2646
}
2647

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

    
2680
function return_hex_ipv4($ipv4) {
2681
	if(!is_ipaddrv4($ipv4))
2682
		return(false);
2683

    
2684
	/* we need the hex form of the interface IPv4 address */
2685
	$ip4arr = explode(".", $ipv4);
2686
	return (sprintf("%02x%02x%02x%02x", $ip4arr[0], $ip4arr[1], $ip4arr[2], $ip4arr[3]));
2687
}
2688

    
2689
function convert_ipv6_to_128bit($ipv6) {
2690
	if(!is_ipaddrv6($ipv6))
2691
		return(false);
2692

    
2693
	$ip6arr = array();
2694
	$ip6prefix = Net_IPv6::uncompress($ipv6);
2695
	$ip6arr = explode(":", $ip6prefix);
2696
	/* binary presentation of the prefix for all 128 bits. */
2697
	$ip6prefixbin = "";
2698
	foreach($ip6arr as $element) {
2699
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
2700
	}
2701
	return($ip6prefixbin);
2702
}
2703

    
2704
function convert_128bit_to_ipv6($ip6bin) {
2705
	if(strlen($ip6bin) <> 128)
2706
		return(false);
2707

    
2708
	$ip6arr = array();
2709
	$ip6binarr = array();
2710
	$ip6binarr = str_split($ip6bin, 16);
2711
	foreach($ip6binarr as $binpart)
2712
		$ip6arr[] = dechex(bindec($binpart));
2713
	$ip6addr = Net_IPv6::compress(implode(":", $ip6arr));
2714

    
2715
	return($ip6addr);
2716
}
2717

    
2718

    
2719
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
2720
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
2721
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
2722
/* 6to4 is 16 bits, e.g. 65535 */
2723
function calculate_ipv6_delegation_length($if) {
2724
	global $config;
2725

    
2726
	if(!is_array($config['interfaces'][$if]))
2727
		return false;
2728

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

    
2749
function huawei_rssi_to_string($rssi) {
2750
	$dbm = array();
2751
	$i = 0;
2752
	$dbstart = -113;
2753
	while($i < 32) {
2754
		$dbm[$i] = $dbstart + ($i * 2);
2755
		$i++;
2756
	}
2757
	$percent = round(($rssi / 31) * 100);
2758
	$string = "rssi:{$rssi} level:{$dbm[$rssi]}dBm percent:{$percent}%";
2759
	return $string;
2760
}
2761

    
2762
function huawei_mode_to_string($mode, $submode) {
2763
	$modes[0] = "None";
2764
	$modes[1] = "AMPS";
2765
	$modes[2] = "CDMA";
2766
	$modes[3] = "GSM/GPRS";
2767
	$modes[4] = "HDR";
2768
	$modes[5] = "WCDMA";
2769
	$modes[6] = "GPS";
2770

    
2771
	$submodes[0] = "No Service";
2772
	$submodes[1] = "GSM";
2773
	$submodes[2] = "GPRS";
2774
	$submodes[3] = "EDGE";
2775
	$submodes[4] = "WCDMA";
2776
	$submodes[5] = "HSDPA";
2777
	$submodes[6] = "HSUPA";
2778
	$submodes[7] = "HSDPA+HSUPA";
2779
	$submodes[8] = "TD-SCDMA";
2780
	$submodes[9] = "HSPA+";
2781
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2782
	return $string;
2783
}
2784

    
2785
function huawei_service_to_string($state) {
2786
	$modes[0] = "No";
2787
	$modes[1] = "Restricted";
2788
	$modes[2] = "Valid";
2789
	$modes[3] = "Restricted Regional";
2790
	$modes[4] = "Powersaving";
2791
	$string = "{$modes[$state]} Service";
2792
	return $string;
2793
}
2794

    
2795
function huawei_simstate_to_string($state) {
2796
	$modes[0] = "Invalid SIM/locked";
2797
	$modes[1] = "Valid SIM";
2798
	$modes[2] = "Invalid SIM CS";
2799
	$modes[3] = "Invalid SIM PS";
2800
	$modes[4] = "Invalid SIM CS/PS";
2801
	$modes[255] = "Missing SIM";
2802
	$string = "{$modes[$state]} State";
2803
	return $string;
2804
}
2805

    
2806
function zte_rssi_to_string($rssi) {
2807
	return huawei_rssi_to_string($rssi);
2808
}
2809

    
2810
function zte_mode_to_string($mode, $submode) {
2811
	$modes[0] = "No Service";
2812
	$modes[1] = "Limited Service";
2813
	$modes[2] = "GPRS";
2814
	$modes[3] = "GSM";
2815
	$modes[4] = "UMTS";
2816
	$modes[5] = "EDGE";
2817
	$modes[6] = "HSDPA";
2818

    
2819
	$submodes[0] = "CS_ONLY";
2820
	$submodes[1] = "PS_ONLY";
2821
	$submodes[2] = "CS_PS";
2822
	$submodes[3] = "CAMPED";
2823
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2824
	return $string;
2825
}
2826

    
2827
function zte_service_to_string($state) {
2828
	$modes[0] = "Initializing";
2829
	$modes[1] = "Network Lock error";
2830
	$modes[2] = "Network Locked";
2831
	$modes[3] = "Unlocked or correct MCC/MNC";
2832
	$string = "{$modes[$state]} Service";
2833
	return $string;
2834
}
2835

    
2836
function zte_simstate_to_string($state) {
2837
	$modes[0] = "No action";
2838
	$modes[1] = "Network lock";
2839
	$modes[2] = "(U)SIM card lock";
2840
	$modes[3] = "Network Lock and (U)SIM card Lock";
2841
	$string = "{$modes[$state]} State";
2842
	return $string;
2843
}
2844

    
2845
function get_configured_pppoe_server_interfaces() {
2846
	global $config;
2847
	$iflist = array();
2848
	if (is_array($config['pppoes']['pppoe'])) {
2849
		foreach($config['pppoes']['pppoe'] as $pppoe) {
2850
			if ($pppoe['mode'] == "server") {
2851
				$int = "poes". $pppoe['pppoeid'];
2852
				$iflist[$int] = strtoupper($int);
2853
			}
2854
		}
2855
	}
2856
	return $iflist;
2857
}
2858

    
2859
function get_pppoes_child_interfaces($ifpattern) {
2860
	$if_arr = array();
2861
	if($ifpattern == "")
2862
		return;
2863

    
2864
	exec("ifconfig", $out, $ret);
2865
	foreach($out as $line) {
2866
		if(preg_match("/^({$ifpattern}[0-9]+):/i", $line, $match)) {
2867
			$if_arr[] = $match[1];
2868
		}
2869
	}
2870
	return $if_arr;
2871

    
2872
}
2873

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

    
2910
/* Function to find and return the active XML RPC base URL to avoid code duplication */
2911
function get_active_xml_rpc_base_url() {
2912
	global $config, $g;
2913
	/* If the user has activated the option to enable an alternate xmlrpcbaseurl, and it's not empty, then use it */
2914
	if (isset($config['system']['altpkgrepo']['enable']) && !empty($config['system']['altpkgrepo']['xmlrpcbaseurl'])) {
2915
		return $config['system']['altpkgrepo']['xmlrpcbaseurl'];
2916
	} else {
2917
		return $g['xmlrpcbaseurl'];
2918
	}
2919
}
2920

    
2921
?>
(40-40/68)