Project

General

Profile

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

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

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

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

    
73
/****f* pfsense-utils/have_ruleint_access
74
 * NAME
75
 *   have_ruleint_access
76
 * INPUTS
77
 *	 none
78
 * RESULT
79
 *   returns true if user has access to edit a specific firewall interface
80
 ******/
81
function have_ruleint_access($if) {
82
	$security_url = "firewall_rules.php?if=". strtolower($if);
83
	if(isAllowedPage($security_url)) 
84
		return true;
85
	return false;
86
}
87

    
88
/****f* pfsense-utils/does_url_exist
89
 * NAME
90
 *   does_url_exist
91
 * INPUTS
92
 *	 none
93
 * RESULT
94
 *   returns true if a url is available
95
 ******/
96
function does_url_exist($url) {
97
	$fd = fopen("$url","r");
98
	if($fd) {
99
		fclose($fd);
100
   		return true;    
101
	} else {
102
        return false;
103
	}
104
}
105

    
106
/****f* pfsense-utils/is_private_ip
107
 * NAME
108
 *   is_private_ip
109
 * INPUTS
110
 *	 none
111
 * RESULT
112
 *   returns true if an ip address is in a private range
113
 ******/
114
function is_private_ip($iptocheck) {
115
        $isprivate = false;
116
        $ip_private_list=array(
117
               "10.0.0.0/8",
118
               "172.16.0.0/12",
119
               "192.168.0.0/16",
120
               "99.0.0.0/8"
121
        );
122
        foreach($ip_private_list as $private) {
123
                if(ip_in_subnet($iptocheck,$private)==true)
124
                        $isprivate = true;
125
        }
126
        return $isprivate;
127
}
128

    
129
/****f* pfsense-utils/get_tmp_file
130
 * NAME
131
 *   get_tmp_file
132
 * INPUTS
133
 *	 none
134
 * RESULT
135
 *   returns a temporary filename
136
 ******/
137
function get_tmp_file() {
138
	global $g;
139
	return "{$g['tmp_path']}/tmp-" . time();
140
}
141

    
142
/****f* pfsense-utils/get_dns_servers
143
 * NAME
144
 *   get_dns_servres - get system dns servers
145
 * INPUTS
146
 *   $dns_servers - an array of the dns servers
147
 * RESULT
148
 *   null
149
 ******/
150
function get_dns_servers() {
151
	$dns_servers = array();
152
	$dns_s = file("/etc/resolv.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
153
	foreach($dns_s as $dns) {
154
		$matches = "";
155
		if (preg_match("/nameserver (.*)/", $dns, $matches))
156
			$dns_servers[] = $matches[1];
157
	}
158
	return array_unique($dns_servers);
159
}
160

    
161
/****f* pfsense-utils/enable_hardware_offloading
162
 * NAME
163
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
164
 * INPUTS
165
 *   $interface	- string containing the physical interface to work on.
166
 * RESULT
167
 *   null
168
 * NOTES
169
 *   This function only supports the fxp driver's loadable microcode.
170
 ******/
171
function enable_hardware_offloading($interface) {
172
	global $g, $config;
173

    
174
	if(isset($config['system']['do_not_use_nic_microcode']))
175
		return;
176

    
177
	/* translate wan, lan, opt -> real interface if needed */
178
	$int = get_real_interface($interface);
179
	if(empty($int)) 
180
		return;
181
	$int_family = preg_split("/[0-9]+/", $int);
182
	$supported_ints = array('fxp');
183
	if (in_array($int_family, $supported_ints)) {
184
		if(does_interface_exist($int)) 
185
			pfSense_interface_flags($int, IFF_LINK0);
186
	}
187

    
188
	return;
189
}
190

    
191
/****f* pfsense-utils/interface_supports_polling
192
 * NAME
193
 *   checks to see if an interface supports polling according to man polling
194
 * INPUTS
195
 *
196
 * RESULT
197
 *   true or false
198
 * NOTES
199
 *
200
 ******/
201
function interface_supports_polling($iface) {
202
	$opts = pfSense_get_interface_addresses($iface);
203
	if (is_array($opts) && isset($opts['caps']['polling']))
204
		return true;
205

    
206
	return false;
207
}
208

    
209
/****f* pfsense-utils/is_alias_inuse
210
 * NAME
211
 *   checks to see if an alias is currently in use by a rule
212
 * INPUTS
213
 *
214
 * RESULT
215
 *   true or false
216
 * NOTES
217
 *
218
 ******/
219
function is_alias_inuse($alias) {
220
	global $g, $config;
221

    
222
	if($alias == "") return false;
223
	/* loop through firewall rules looking for alias in use */
224
	if(is_array($config['filter']['rule']))
225
		foreach($config['filter']['rule'] as $rule) {
226
			if($rule['source']['address'])
227
				if($rule['source']['address'] == $alias)
228
					return true;
229
			if($rule['destination']['address'])
230
				if($rule['destination']['address'] == $alias)
231
					return true;
232
		}
233
	/* loop through nat rules looking for alias in use */
234
	if(is_array($config['nat']['rule']))
235
		foreach($config['nat']['rule'] as $rule) {
236
			if($rule['target'] && $rule['target'] == $alias)
237
				return true;
238
			if($rule['source']['address'] && $rule['source']['address'] == $alias)
239
				return true;
240
			if($rule['destination']['address'] && $rule['destination']['address'] == $alias)
241
				return true;
242
		}
243
	return false;
244
}
245

    
246
/****f* pfsense-utils/is_schedule_inuse
247
 * NAME
248
 *   checks to see if a schedule is currently in use by a rule
249
 * INPUTS
250
 *
251
 * RESULT
252
 *   true or false
253
 * NOTES
254
 *
255
 ******/
256
function is_schedule_inuse($schedule) {
257
	global $g, $config;
258

    
259
	if($schedule == "") return false;
260
	/* loop through firewall rules looking for schedule in use */
261
	if(is_array($config['filter']['rule']))
262
		foreach($config['filter']['rule'] as $rule) {
263
			if($rule['sched'] == $schedule)
264
				return true;
265
		}
266
	return false;
267
}
268

    
269
/****f* pfsense-utils/setup_polling
270
 * NAME
271
 *   sets up polling
272
 * INPUTS
273
 *
274
 * RESULT
275
 *   null
276
 * NOTES
277
 *
278
 ******/
279
function setup_polling() {
280
	global $g, $config;
281

    
282
	if (isset($config['system']['polling']))
283
		mwexec("/sbin/sysctl kern.polling.idle_poll=1");
284
	else
285
		mwexec("/sbin/sysctl kern.polling.idle_poll=0");
286

    
287
	if($config['system']['polling_each_burst'])
288
		mwexec("/sbin/sysctl kern.polling.each_burst={$config['system']['polling_each_burst']}");
289
	if($config['system']['polling_burst_max'])
290
		mwexec("/sbin/sysctl kern.polling.burst_max={$config['system']['polling_burst_max']}");
291
	if($config['system']['polling_user_frac'])
292
		mwexec("/sbin/sysctl kern.polling.user_frac={$config['system']['polling_user_frac']}");
293
}
294

    
295
/****f* pfsense-utils/setup_microcode
296
 * NAME
297
 *   enumerates all interfaces and calls enable_hardware_offloading which
298
 *   enables a NIC's supported hardware features.
299
 * INPUTS
300
 *
301
 * RESULT
302
 *   null
303
 * NOTES
304
 *   This function only supports the fxp driver's loadable microcode.
305
 ******/
306
function setup_microcode() {
307

    
308
	/* if list */
309
	$ifs = get_interface_arr();
310

    
311
	foreach($ifs as $if)
312
		enable_hardware_offloading($if);
313
}
314

    
315
/****f* pfsense-utils/get_carp_status
316
 * NAME
317
 *   get_carp_status - Return whether CARP is enabled or disabled.
318
 * RESULT
319
 *   boolean	- true if CARP is enabled, false if otherwise.
320
 ******/
321
function get_carp_status() {
322
    /* grab the current status of carp */
323
    $status = `/sbin/sysctl -n net.inet.carp.allow`;
324
    return (intval($status) > 0);
325
}
326

    
327
/*
328
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
329

    
330
 */
331
function convert_ip_to_network_format($ip, $subnet) {
332
	$ipsplit = split('[.]', $ip);
333
	$string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
334
	return $string;
335
}
336

    
337
/*
338
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
339
 */
340
function get_carp_interface_status($carpinterface) {
341
	$carp_query = "";
342
	exec("/sbin/ifconfig $carpinterface | /usr/bin/grep -v grep | /usr/bin/grep carp:", $carp_query);
343
	foreach($carp_query as $int) {
344
		if(stristr($int, "MASTER")) 
345
			return "MASTER";
346
		if(stristr($int, "BACKUP")) 
347
			return "BACKUP";
348
		if(stristr($int, "INIT")) 
349
			return "INIT";
350
	}
351
	return;
352
}
353

    
354
/*
355
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
356
 */
357
function get_pfsync_interface_status($pfsyncinterface) {
358
    $result = does_interface_exist($pfsyncinterface);
359
    if($result <> true) return;
360
    $status = exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'");
361
    return $status;
362
}
363

    
364
/*
365
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
366
 */
367
function add_rule_to_anchor($anchor, $rule, $label) {
368
	mwexec("echo " . $rule . " | /sbin/pfctl -a " . $anchor . ":" . $label . " -f -");
369
}
370

    
371
/*
372
 * remove_text_from_file
373
 * remove $text from file $file
374
 */
375
function remove_text_from_file($file, $text) {
376
	if(!file_exists($file) && !is_writable($file))
377
		return;
378
	$filecontents = file_get_contents($file);
379
	$text = str_replace($text, "", $filecontents);
380
	@file_put_contents($file, $text); 
381
}
382

    
383
/*
384
 * add_text_to_file($file, $text): adds $text to $file.
385
 * replaces the text if it already exists.
386
 */
387
function add_text_to_file($file, $text, $replace = false) {
388
	if(file_exists($file) and is_writable($file)) {
389
		$filecontents = file($file);
390
		$filecontents = array_map('rtrim', $filecontents);
391
		array_push($filecontents, $text);
392
		if ($replace)
393
			$filecontents = array_unique($filecontents);
394

    
395
		$file_text = implode("\n", $filecontents);
396

    
397
		@file_put_contents($file, $file_text); 
398
		return true;
399
	}
400
	return false;
401
}
402

    
403
/*
404
 *   after_sync_bump_adv_skew(): create skew values by 1S
405
 */
406
function after_sync_bump_adv_skew() {
407
	global $config, $g;
408
	$processed_skew = 1;
409
	$a_vip = &$config['virtualip']['vip'];
410
	foreach ($a_vip as $vipent) {
411
		if($vipent['advskew'] <> "") {
412
			$processed_skew = 1;
413
			$vipent['advskew'] = $vipent['advskew']+1;
414
		}
415
	}
416
	if($processed_skew == 1)
417
		write_config("After synch increase advertising skew");
418
}
419

    
420
/*
421
 * get_filename_from_url($url): converts a url to its filename.
422
 */
423
function get_filename_from_url($url) {
424
	return basename($url);
425
}
426

    
427
/*
428
 *   get_dir: return an array of $dir
429
 */
430
function get_dir($dir) {
431
	$dir_array = array();
432
	$d = dir($dir);
433
	while (false !== ($entry = $d->read())) {
434
		array_push($dir_array, $entry);
435
	}
436
	$d->close();
437
	return $dir_array;
438
}
439

    
440
/****f* pfsense-utils/WakeOnLan
441
 * NAME
442
 *   WakeOnLan - Wake a machine up using the wake on lan format/protocol
443
 * RESULT
444
 *   true/false - true if the operation was successful
445
 ******/
446
function WakeOnLan($addr, $mac)
447
{
448
	$addr_byte = explode(':', $mac);
449
	$hw_addr = '';
450

    
451
	for ($a=0; $a < 6; $a++)
452
		$hw_addr .= chr(hexdec($addr_byte[$a]));
453

    
454
	$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
455

    
456
	for ($a = 1; $a <= 16; $a++)
457
		$msg .= $hw_addr;
458

    
459
	// send it to the broadcast address using UDP
460
	$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
461
	if ($s == false) {
462
		log_error("Error creating socket!");
463
		log_error("Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s)));
464
	} else {
465
		// setting a broadcast option to socket:
466
		$opt_ret =  socket_set_option($s, 1, 6, TRUE);
467
		if($opt_ret < 0)
468
			log_error("setsockopt() failed, error: " . strerror($opt_ret));
469
		$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
470
		socket_close($s);
471
		log_error("Magic Packet sent ({$e}) to {$addr} MAC={$mac}");
472
		return true;
473
	}
474

    
475
	return false;
476
}
477

    
478
/*
479
 * gather_altq_queue_stats():  gather altq queue stats and return an array that
480
 *                             is queuename|qlength|measured_packets
481
 *                             NOTE: this command takes 5 seconds to run
482
 */
483
function gather_altq_queue_stats($dont_return_root_queues) {
484
	exec("/sbin/pfctl -vvsq", $stats_array);
485
	$queue_stats = array();
486
	foreach ($stats_array as $stats_line) {
487
		$match_array = "";
488
		if (preg_match_all("/queue\s+(\w+)\s+/",$stats_line,$match_array))
489
			$queue_name = $match_array[1][0];
490
		if (preg_match_all("/measured:\s+.*packets\/s\,\s(.*)\s+\]/",$stats_line,$match_array))
491
			$speed = $match_array[1][0];
492
		if (preg_match_all("/borrows:\s+(.*)/",$stats_line,$match_array))
493
			$borrows = $match_array[1][0];
494
		if (preg_match_all("/suspends:\s+(.*)/",$stats_line,$match_array))
495
			$suspends = $match_array[1][0];
496
		if (preg_match_all("/dropped pkts:\s+(.*)/",$stats_line,$match_array))
497
			$drops = $match_array[1][0];
498
		if (preg_match_all("/measured:\s+(.*)packets/",$stats_line,$match_array)) {
499
			$measured = $match_array[1][0];
500
			if($dont_return_root_queues == true)
501
				if(stristr($queue_name,"root_") == false)
502
					array_push($queue_stats, "{$queue_name}|{$speed}|{$measured}|{$borrows}|{$suspends}|{$drops}");
503
		}
504
	}
505
	return $queue_stats;
506
}
507

    
508
/*
509
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
510
 *					 Useful for finding paths and stripping file extensions.
511
 */
512
function reverse_strrchr($haystack, $needle) {
513
	if (!is_string($haystack))
514
		return;
515
	return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
516
}
517

    
518
/*
519
 *  backup_config_section($section): returns as an xml file string of
520
 *                                   the configuration section
521
 */
522
function backup_config_section($section) {
523
	global $config;
524
	$new_section = &$config[$section];
525
	/* generate configuration XML */
526
	$xmlconfig = dump_xml_config($new_section, $section);
527
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
528
	return $xmlconfig;
529
}
530

    
531
/*
532
 *  restore_config_section($section, new_contents): restore a configuration section,
533
 *                                                  and write the configuration out
534
 *                                                  to disk/cf.
535
 */
536
function restore_config_section($section, $new_contents) {
537
	global $config, $g;
538
	conf_mount_rw();
539
	$fout = fopen("{$g['tmp_path']}/tmpxml","w");
540
	fwrite($fout, $new_contents);
541
	fclose($fout);
542
	$section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
543
	if ($section_xml != -1)
544
		$config[$section] = &$section_xml;
545
	@unlink($g['tmp_path'] . "/tmpxml");
546
	if(file_exists("{$g['tmp_path']}/config.cache"))
547
		unlink("{$g['tmp_path']}/config.cache");
548
	write_config("Restored {$section} of config file (maybe from CARP partner)");
549
	disable_security_checks();
550
	conf_mount_ro();
551
	return;
552
}
553

    
554
/*
555
 *  merge_config_section($section, new_contents):   restore a configuration section,
556
 *                                                  and write the configuration out
557
 *                                                  to disk/cf.  But preserve the prior
558
 * 													structure if needed
559
 */
560
function merge_config_section($section, $new_contents) {
561
	global $config;
562
	conf_mount_rw();
563
	$fname = get_tmp_filename();
564
	$fout = fopen($fname, "w");
565
	fwrite($fout, $new_contents);
566
	fclose($fout);
567
	$section_xml = parse_xml_config($fname, $section);
568
	$config[$section] = $section_xml;
569
	unlink($fname);
570
	write_config("Restored {$section} of config file (maybe from CARP partner)");
571
	disable_security_checks();
572
	conf_mount_ro();
573
	return;
574
}
575

    
576
/*
577
 * http_post($server, $port, $url, $vars): does an http post to a web server
578
 *                                         posting the vars array.
579
 * written by nf@bigpond.net.au
580
 */
581
function http_post($server, $port, $url, $vars) {
582
	$user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
583
	$urlencoded = "";
584
	while (list($key,$value) = each($vars))
585
		$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
586
	$urlencoded = substr($urlencoded,0,-1);
587
	$content_length = strlen($urlencoded);
588
	$headers = "POST $url HTTP/1.1
589
Accept: */*
590
Accept-Language: en-au
591
Content-Type: application/x-www-form-urlencoded
592
User-Agent: $user_agent
593
Host: $server
594
Connection: Keep-Alive
595
Cache-Control: no-cache
596
Content-Length: $content_length
597

    
598
";
599

    
600
	$errno = "";
601
	$errstr = "";
602
	$fp = fsockopen($server, $port, $errno, $errstr);
603
	if (!$fp) {
604
		return false;
605
	}
606

    
607
	fputs($fp, $headers);
608
	fputs($fp, $urlencoded);
609

    
610
	$ret = "";
611
	while (!feof($fp))
612
		$ret.= fgets($fp, 1024);
613
	fclose($fp);
614

    
615
	return $ret;
616
}
617

    
618
/*
619
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
620
 */
621
if (!function_exists('php_check_syntax')){
622
	global $g;
623
	function php_check_syntax($code_to_check, &$errormessage){
624
		return false;
625
		$fout = fopen("{$g['tmp_path']}/codetocheck.php","w");
626
		$code = $_POST['content'];
627
		$code = str_replace("<?php", "", $code);
628
		$code = str_replace("?>", "", $code);
629
		fwrite($fout, "<?php\n\n");
630
		fwrite($fout, $code_to_check);
631
		fwrite($fout, "\n\n?>\n");
632
		fclose($fout);
633
		$command = "/usr/local/bin/php -l {$g['tmp_path']}/codetocheck.php";
634
		$output = exec_command($command);
635
		if (stristr($output, "Errors parsing") == false) {
636
			echo "false\n";
637
			$errormessage = '';
638
			return(false);
639
		} else {
640
			$errormessage = $output;
641
			return(true);
642
		}
643
	}
644
}
645

    
646
/*
647
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
648
 */
649
if (!function_exists('php_check_syntax')){
650
	function php_check_syntax($code_to_check, &$errormessage){
651
		return false;
652
		$command = "/usr/local/bin/php -l " . $code_to_check;
653
		$output = exec_command($command);
654
		if (stristr($output, "Errors parsing") == false) {
655
			echo "false\n";
656
			$errormessage = '';
657
			return(false);
658
		} else {
659
			$errormessage = $output;
660
			return(true);
661
		}
662
	}
663
}
664

    
665
/*
666
 * rmdir_recursive($path,$follow_links=false)
667
 * Recursively remove a directory tree (rm -rf path)
668
 * This is for directories _only_
669
 */
670
function rmdir_recursive($path,$follow_links=false) {
671
	$to_do = glob($path);
672
	if(!is_array($to_do)) $to_do = array($to_do);
673
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
674
		if(file_exists($workingdir)) {
675
			if(is_dir($workingdir)) {
676
				$dir = opendir($workingdir);
677
				while ($entry = readdir($dir)) {
678
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
679
						unlink("$workingdir/$entry");
680
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
681
						rmdir_recursive("$workingdir/$entry");
682
				}
683
				closedir($dir);
684
				rmdir($workingdir);
685
			} elseif (is_file($workingdir)) {
686
				unlink($workingdir);
687
			}
688
               	}
689
	}
690
	return;
691
}
692

    
693
/*
694
 * call_pfsense_method(): Call a method exposed by the pfsense.com XMLRPC server.
695
 */
696
function call_pfsense_method($method, $params, $timeout = 0) {
697
	global $g, $config;
698

    
699
	$ip = gethostbyname($g['product_website']);
700
	if($ip == $g['product_website'])
701
		return false;
702

    
703
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
704
	$xmlrpc_path = $g['xmlrpcpath'];
705
	$msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params)));
706
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url);
707
	// If the ALT PKG Repo has a username/password set, use it.
708
	if($config['system']['altpkgrepo']['username'] && 
709
	   $config['system']['altpkgrepo']['password']) {
710
		$username = $config['system']['altpkgrepo']['username'];
711
		$password = $config['system']['altpkgrepo']['password'];
712
		$cli->setCredentials($username, $password);
713
	}
714
	$resp = $cli->send($msg, $timeout);
715
	if(!is_object($resp)) {
716
		log_error("XMLRPC communication error: " . $cli->errstr);
717
		return false;
718
	} elseif($resp->faultCode()) {
719
		log_error("XMLRPC request failed with error " . $resp->faultCode() . ": " . $resp->faultString());
720
		return false;
721
	} else {
722
		return XML_RPC_Decode($resp->value());
723
	}
724
}
725

    
726
/*
727
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
728
 */
729
function check_firmware_version($tocheck = "all", $return_php = true) {
730
	global $g, $config;
731

    
732
	$ip = gethostbyname($g['product_website']);
733
	if($ip == $g['product_website'])
734
		return false;
735

    
736
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
737
		"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
738
		"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
739
		"platform" => trim(file_get_contents('/etc/platform')),
740
		"config_version" => $config['version']
741
		);
742
	if($tocheck == "all") {
743
		$params = $rawparams;
744
	} else {
745
		foreach($tocheck as $check) {
746
			$params['check'] = $rawparams['check'];
747
			$params['platform'] = $rawparams['platform'];
748
		}
749
	}
750
	if($config['system']['firmware']['branch'])
751
		$params['branch'] = $config['system']['firmware']['branch'];
752

    
753
	/* XXX: What is this method? */
754
	if(!($versions = call_pfsense_method('pfsense.get_firmware_version', $params))) {
755
		return false;
756
	} else {
757
		$versions["current"] = $params;
758
	}
759

    
760
	return $versions;
761
}
762

    
763
/*
764
 * host_firmware_version(): Return the versions used in this install
765
 */
766
function host_firmware_version($tocheck = "") {
767
        global $g, $config;
768

    
769
        return array(
770
		"firmware" => array("version" => trim(file_get_contents('/etc/version', " \n"))),
771
                "kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel', " \n"))),
772
                "base"     => array("version" => trim(file_get_contents('/etc/version_base', " \n"))),
773
                "platform" => trim(file_get_contents('/etc/platform', " \n")),
774
                "config_version" => $config['version']
775
                );
776
}
777

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

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

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

    
811
	if($g['debug'])
812
		log_error("reload_interfaces_sync() is starting.");
813

    
814
	/* parse config.xml again */
815
	$config = parse_config(true);
816

    
817
	/* enable routing */
818
	system_routing_enable();
819
	if($g['debug'])
820
		log_error("Enabling system routing");
821

    
822
	if($g['debug'])
823
		log_error("Cleaning up Interfaces");
824

    
825
	/* set up interfaces */
826
	interfaces_configure();
827
}
828

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

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

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

    
864
	$g['booting'] = false;
865

    
866
	/* parse config.xml again */
867
	$config = parse_config(true);
868

    
869
	/* set up our timezone */
870
	system_timezone_configure();
871

    
872
	/* set up our hostname */
873
	system_hostname_configure();
874

    
875
	/* make hosts file */
876
	system_hosts_generate();
877

    
878
	/* generate resolv.conf */
879
	system_resolvconf_generate();
880

    
881
	/* enable routing */
882
	system_routing_enable();
883

    
884
	/* set up interfaces */
885
	interfaces_configure();
886

    
887
	/* start dyndns service */
888
	services_dyndns_configure();
889

    
890
	/* configure cron service */
891
	configure_cron();
892

    
893
	/* start the NTP client */
894
	system_ntp_configure();
895

    
896
	/* sync pw database */
897
	conf_mount_rw();
898
	unlink_if_exists("/etc/spwd.db.tmp");
899
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
900
	conf_mount_ro();
901

    
902
	/* restart sshd */
903
	send_event("service restart sshd");
904

    
905
	/* restart webConfigurator if needed */
906
	send_event("service restart webgui");
907
}
908

    
909
function auto_login() {
910
	global $config;
911

    
912
	if(isset($config['system']['disableconsolemenu']))
913
		$status = false;
914
	else
915
		$status = true;
916

    
917
	$gettytab = file_get_contents("/etc/gettytab");
918
	$getty_split = split("\n", $gettytab);
919
	conf_mount_rw();
920
	$fd = false;
921
	$tries = 0;
922
	while (!$fd && $tries < 100) {
923
		$fd = fopen("/etc/gettytab", "w");
924
		$tries++;
925
		
926
	}
927
	if (!$fd) {
928
		conf_mount_ro();
929
		log_error("Enabling auto login was not possible.");
930
		return;
931
	}
932
	foreach($getty_split as $gs) {
933
		if(stristr($gs, ":ht:np:sp#115200") ) {
934
			if($status == true) {
935
				fwrite($fd, "	:ht:np:sp#115200:al=root:\n");
936
			} else {
937
				fwrite($fd, "	:ht:np:sp#115200:\n");
938
			}
939
		} else {
940
			fwrite($fd, "{$gs}\n");
941
		}
942
	}
943
	fclose($fd);
944
	conf_mount_ro();
945
}
946

    
947
function setup_serial_port() {
948
	global $g, $config;
949
	conf_mount_rw();
950
	/* serial console - write out /boot.config */
951
	if(file_exists("/boot.config"))
952
		$boot_config = file_get_contents("/boot.config");
953
	else
954
		$boot_config = "";
955

    
956
	if($g['platform'] <> "cdrom") {
957
		$boot_config_split = split("\n", $boot_config);
958
		$fd = fopen("/boot.config","w");
959
		if($fd) {
960
			foreach($boot_config_split as $bcs) {
961
				if(stristr($bcs, "-D")) {
962
					/* DONT WRITE OUT, WE'LL DO IT LATER */
963
				} else {
964
					if($bcs <> "")
965
						fwrite($fd, "{$bcs}\n");
966
				}
967
			}
968
			if(isset($config['system']['enableserial'])) {
969
				fwrite($fd, "-D");
970
			}
971
			fclose($fd);
972
		}
973
		/* serial console - write out /boot/loader.conf */
974
		$boot_config = file_get_contents("/boot/loader.conf");
975
		$boot_config_split = explode("\n", $boot_config);
976
		if(count($boot_config_split) > 0) {
977
			$new_boot_config = array();
978
			// Loop through and only add lines that are not empty, and which
979
			//  do not contain a console directive.
980
			foreach($boot_config_split as $bcs)
981
				if(!empty($bcs) && (stripos($bcs, "console") === false))
982
					$new_boot_config[] = $bcs;
983

    
984
			if(isset($config['system']['enableserial']))
985
				$new_boot_config[] = 'console="comconsole"';
986
			file_put_contents("/boot/loader.conf", implode("\n", $new_boot_config));
987
		}
988
	}
989
	$ttys = file_get_contents("/etc/ttys");
990
	$ttys_split = split("\n", $ttys);
991
	$fd = fopen("/etc/ttys", "w");
992
	foreach($ttys_split as $tty) {
993
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
994
			if(isset($config['system']['enableserial'])) {
995
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
996
			} else {
997
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
998
			}
999
		} else {
1000
			fwrite($fd, $tty . "\n");
1001
		}
1002
	}
1003
	fclose($fd);
1004
	auto_login();
1005

    
1006
	conf_mount_ro();
1007
	return;
1008
}
1009

    
1010
function print_value_list($list, $count = 10, $separator = ",") {
1011
	$list = implode($separator, array_slice($list, 0, $count));
1012
	if(count($list) < $count) {
1013
		$list .= ".";
1014
	} else {
1015
		$list .= "...";
1016
	}
1017
	return $list;
1018
}
1019

    
1020
/* DHCP enabled on any interfaces? */
1021
function is_dhcp_server_enabled() 
1022
{
1023
	global $config;
1024

    
1025
	$dhcpdenable = false;
1026
	
1027
	if (!is_array($config['dhcpd']))
1028
		return false;
1029

    
1030
	$Iflist = get_configured_interface_list();
1031

    
1032
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1033
		if (isset($dhcpifconf['enable']) && isset($Iflist[$dhcpif])) {
1034
			$dhcpdenable = true;
1035
			break;
1036
		}
1037
	}
1038

    
1039
	return $dhcpdenable;
1040
}
1041

    
1042
function convert_seconds_to_hms($sec){
1043
	$min=$hrs=0;
1044
	if ($sec != 0){
1045
		$min = floor($sec/60);
1046
		$sec %= 60;
1047
	}
1048
	if ($min != 0){
1049
		$hrs = floor($min/60);
1050
		$min %= 60;
1051
	}
1052
	if ($sec < 10)
1053
		$sec = "0".$sec;
1054
	if ($min < 10)
1055
		$min = "0".$min;
1056
	if ($hrs < 10)
1057
		$hrs = "0".$hrs;
1058
	$result = $hrs.":".$min.":".$sec;
1059
	return $result;
1060
}
1061

    
1062
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1063

    
1064
function get_ppp_uptime($port){
1065
	if (file_exists("/conf/{$port}.log")){
1066
    	$saved_time = file_get_contents("/conf/{$port}.log");
1067
    	$uptime_data = explode("\n",$saved_time);
1068
		$sec=0;
1069
		foreach($uptime_data as $upt) {
1070
			$sec += substr($upt, 1 + strpos($upt, " "));
1071
 		}
1072
		return convert_seconds_to_hms($sec);
1073
	} else {
1074
		$total_time = "No history data found!";
1075
		return $total_time;
1076
	}
1077
}
1078

    
1079
//returns interface information
1080
function get_interface_info($ifdescr) {
1081
	global $config, $g;
1082

    
1083
	$ifinfo = array();
1084
	if (empty($config['interfaces'][$ifdescr]))
1085
		return;
1086
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1087
	$ifinfo['if'] = get_real_interface($ifdescr);
1088

    
1089
	$chkif = $ifinfo['if'];
1090
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1091
	$ifinfo['status'] = $ifinfotmp['status'];
1092
	if (empty($ifinfo['status']))
1093
                $ifinfo['status'] = "down";
1094
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1095
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1096
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1097
	if (isset($ifinfotmp['link0']))
1098
		$link0 = "down";
1099
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1100
        $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1101
        $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1102
        $ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1103
        $ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1104
        $ifinfo['collisions'] = $ifinfotmp['collisions'];
1105

    
1106
	/* Use pfctl for non wrapping 64 bit counters */
1107
	/* Pass */
1108
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1109
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1110
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1111
	$in4_pass = $pf_in4_pass[5];
1112
	$out4_pass = $pf_out4_pass[5];
1113
	$in4_pass_packets = $pf_in4_pass[3];
1114
	$out4_pass_packets = $pf_out4_pass[3];
1115
	$ifinfo['inbytespass'] = $in4_pass;
1116
	$ifinfo['outbytespass'] = $out4_pass;
1117
	$ifinfo['inpktspass'] = $in4_pass_packets;
1118
	$ifinfo['outpktspass'] = $out4_pass_packets;
1119

    
1120
	/* Block */
1121
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1122
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1123
	$in4_block = $pf_in4_block[5];
1124
	$out4_block = $pf_out4_block[5];
1125
	$in4_block_packets = $pf_in4_block[3];
1126
	$out4_block_packets = $pf_out4_block[3];
1127
	$ifinfo['inbytesblock'] = $in4_block;
1128
	$ifinfo['outbytesblock'] = $out4_block;
1129
	$ifinfo['inpktsblock'] = $in4_block_packets;
1130
	$ifinfo['outpktsblock'] = $out4_block_packets;
1131

    
1132
	$ifinfo['inbytes'] = $in4_pass + $in4_block;
1133
	$ifinfo['outbytes'] = $out4_pass + $out4_block;
1134
	$ifinfo['inpkts'] = $in4_pass_packets + $in4_block_packets;
1135
	$ifinfo['outpkts'] = $in4_pass_packets + $out4_block_packets;
1136
		
1137
	$ifconfiginfo = "";
1138
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1139
	switch ($link_type) {
1140
	 /* DHCP? -> see if dhclient is up */
1141
	case "dhcp":
1142
	case "carpdev-dhcp":
1143
		/* see if dhclient is up */
1144
		if (find_dhclient_process($ifinfo['if']) <> "")
1145
			$ifinfo['dhcplink'] = "up";
1146
		else
1147
			$ifinfo['dhcplink'] = "down";
1148

    
1149
		break;
1150
	/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1151
	case "pppoe":
1152
	case "pptp":
1153
	case "l2tp":
1154
		if ($ifinfo['status'] == "up" && !isset($link0))
1155
			/* get PPPoE link status for dial on demand */
1156
			$ifinfo["{$link_type}link"] = "up";
1157
		else
1158
			$ifinfo["{$link_type}link"] = "down";
1159

    
1160
		break;
1161
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1162
	case "ppp":
1163
		if ($ifinfo['status'] == "up")
1164
			$ifinfo['ppplink'] = "up";
1165
		else
1166
			$ifinfo['ppplink'] = "down" ;
1167

    
1168
		if (empty($ifinfo['status']))
1169
			$ifinfo['status'] = "down";
1170
			
1171
		if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1172
			foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1173
				if ($config['interfaces'][$ifdescr]['if'] == $ppp['if'])
1174
					break;
1175
			}
1176
		}
1177
		$dev = $ppp['ports'];
1178
		if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev))
1179
			break;
1180
		if (!file_exists($dev)) {
1181
			$ifinfo['nodevice'] = 1;
1182
			$ifinfo['pppinfo'] = $dev . " device not present! Is the modem attached to the system?";	
1183
		}
1184
		// Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over!
1185
		if (isset($ppp['uptime']))
1186
			$ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")";
1187
		break;
1188
	default:
1189
		break;
1190
	}
1191
	
1192
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1193
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1194
		$ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec);
1195
	}
1196
	
1197
	if ($ifinfo['status'] == "up") {
1198
		/* try to determine media with ifconfig */
1199
		unset($ifconfiginfo);
1200
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1201
		$wifconfiginfo = array();
1202
		if(is_interface_wireless($ifdescr)) {
1203
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1204
			array_shift($wifconfiginfo);
1205
		}
1206
		$matches = "";
1207
		foreach ($ifconfiginfo as $ici) {
1208

    
1209
			/* don't list media/speed for wireless cards, as it always
1210
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1211
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1212
				$ifinfo['media'] = $matches[1];
1213
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1214
				$ifinfo['media'] = $matches[1];
1215
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1216
				$ifinfo['media'] = $matches[1];
1217
			}
1218

    
1219
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1220
				if ($matches[1] != "active")
1221
					$ifinfo['status'] = $matches[1];
1222
				if($ifinfo['status'] == "running")
1223
					$ifinfo['status'] = "up";
1224
			}
1225
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1226
				$ifinfo['channel'] = $matches[1];
1227
			}
1228
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1229
				if ($matches[1][0] == '"')
1230
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1231
				else
1232
					$ifinfo['ssid'] = $matches[1];
1233
			}
1234
		}
1235
		foreach($wifconfiginfo as $ici) {
1236
			$elements = preg_split("/[ ]+/i", $ici);
1237
			if ($elements[0] != "") {
1238
				$ifinfo['bssid'] = $elements[0];
1239
			}
1240
			if ($elements[3] != "") {
1241
				$ifinfo['rate'] = $elements[3];
1242
			}
1243
			if ($elements[4] != "") {
1244
				$ifinfo['rssi'] = $elements[4];
1245
			}
1246

    
1247
		}
1248
		/* lookup the gateway */
1249
		if (interface_has_gateway($ifdescr)) 
1250
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1251
	}
1252

    
1253
	$bridge = "";
1254
	$bridge = link_interface_to_bridge($ifdescr);
1255
	if($bridge) {
1256
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1257
		if(stristr($bridge_text, "blocking") <> false) {
1258
			$ifinfo['bridge'] = "<b><font color='red'>blocking</font></b> - check for ethernet loops";
1259
			$ifinfo['bridgeint'] = $bridge;
1260
		} else if(stristr($bridge_text, "learning") <> false) {
1261
			$ifinfo['bridge'] = "learning";
1262
			$ifinfo['bridgeint'] = $bridge;
1263
		} else if(stristr($bridge_text, "forwarding") <> false) {
1264
			$ifinfo['bridge'] = "forwarding";
1265
			$ifinfo['bridgeint'] = $bridge;
1266
		}
1267
	}
1268

    
1269
	return $ifinfo;
1270
}
1271

    
1272
//returns cpu speed of processor. Good for determining capabilities of machine
1273
function get_cpu_speed() {
1274
	 return exec("sysctl hw.clockrate | awk '{ print $2 }'");
1275
}
1276

    
1277
function add_hostname_to_watch($hostname) {
1278
	if(!is_dir("/var/db/dnscache")) {
1279
		mkdir("/var/db/dnscache");
1280
	}
1281
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1282
		$domrecords = array();
1283
		$domips = array();
1284
		exec("host -t A $hostname", $domrecords, $rethost);
1285
		if($rethost == 0) {
1286
			foreach($domrecords as $domr) {
1287
				$doml = explode(" ", $domr);
1288
				$domip = $doml[3];
1289
				/* fill array with domain ip addresses */
1290
				if(is_ipaddr($domip)) {
1291
					$domips[] = $domip;
1292
				}
1293
			}
1294
		}
1295
		sort($domips);
1296
		$contents = "";
1297
		if(! empty($domips)) {
1298
			foreach($domips as $ip) {
1299
				$contents .= "$ip\n";
1300
			}
1301
		}
1302
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1303
	}
1304
}
1305

    
1306
function is_fqdn($fqdn) {
1307
	$hostname = false;
1308
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1309
		$hostname = true;
1310
	}
1311
	if(preg_match("/\.\./", $fqdn)) {
1312
		$hostname = false;
1313
	}
1314
	if(preg_match("/^\./i", $fqdn)) { 
1315
		$hostname = false;
1316
	}
1317
	if(preg_match("/\//i", $fqdn)) {
1318
		$hostname = false;
1319
	}
1320
	return($hostname);
1321
}
1322

    
1323
function pfsense_default_state_size() {
1324
  /* get system memory amount */
1325
  $memory = get_memory();
1326
  $avail = $memory[0];
1327
  /* Be cautious and only allocate 10% of system memory to the state table */
1328
  $max_states = (int) ($avail/10)*1000;
1329
  return $max_states;
1330
}
1331

    
1332
function pfsense_default_table_entries_size() {
1333
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1334
	return $current;
1335
}
1336

    
1337
/* Compare the current hostname DNS to the DNS cache we made
1338
 * if it has changed we return the old records
1339
 * if no change we return true */
1340
function compare_hostname_to_dnscache($hostname) {
1341
	if(!is_dir("/var/db/dnscache")) {
1342
		mkdir("/var/db/dnscache");
1343
	}
1344
	$hostname = trim($hostname);
1345
	if(is_readable("/var/db/dnscache/{$hostname}")) {
1346
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1347
	} else {
1348
		$oldcontents = "";
1349
	}
1350
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1351
		$domrecords = array();
1352
		$domips = array();
1353
		exec("host -t A $hostname", $domrecords, $rethost);
1354
		if($rethost == 0) {
1355
			foreach($domrecords as $domr) {
1356
				$doml = explode(" ", $domr);
1357
				$domip = $doml[3];
1358
				/* fill array with domain ip addresses */
1359
				if(is_ipaddr($domip)) {
1360
					$domips[] = $domip;
1361
				}
1362
			}
1363
		}
1364
		sort($domips);
1365
		$contents = "";
1366
		if(! empty($domips)) {
1367
			foreach($domips as $ip) {
1368
				$contents .= "$ip\n";
1369
			}
1370
		}
1371
	}
1372

    
1373
	if(trim($oldcontents) != trim($contents)) {
1374
		if($g['debug']) {
1375
			log_error("DNSCACHE: Found old IP {$oldcontents} and new IP {$contents}");
1376
		}
1377
		return ($oldcontents);
1378
	} else {
1379
		return false;
1380
	}
1381
}
1382

    
1383
/*
1384
 * load_glxsb() - Load the glxsb crypto module if enabled in config.
1385
 */
1386
function load_glxsb() {
1387
	global $config, $g;
1388
	$is_loaded = `/sbin/kldstat | /usr/bin/grep -c glxsb`;
1389
	if (isset($config['system']['glxsb_enable']) && ($is_loaded == 0)) {
1390
		mwexec("/sbin/kldload glxsb");
1391
	}
1392
}
1393

    
1394
/****f* pfsense-utils/isvm
1395
 * NAME
1396
 *   isvm
1397
 * INPUTS
1398
 *	 none
1399
 * RESULT
1400
 *   returns true if machine is running under a virtual environment
1401
 ******/
1402
function isvm() {
1403
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1404
	$bios_vendor = strtolower(`/bin/kenv | /usr/bin/awk -F= '/smbios.bios.vendor/ {print $2}'`);
1405
	if(in_array($bios_vendor, $virtualenvs)) 
1406
		return true;
1407
	else
1408
		return false;
1409
}
1410

    
1411
function get_freebsd_version() {
1412
	$version = php_uname("r");
1413
	return $version[0];
1414
}
1415

    
1416
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body') {
1417
        global $ch, $fout, $file_size, $downloaded;
1418
        $file_size  = 1;
1419
        $downloaded = 1;
1420
        /* open destination file */
1421
        $fout = fopen($destination_file, "wb");
1422

    
1423
        /*
1424
         *      Originally by Author: Keyvan Minoukadeh
1425
         *      Modified by Scott Ullrich to return Content-Length size
1426
         */
1427

    
1428
        $ch = curl_init();
1429
        curl_setopt($ch, CURLOPT_URL, $url_file);
1430
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1431
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1432
        /* Don't verify SSL peers since we don't have the certificates to do so. */
1433
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1434
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1435
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1436
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, '60');
1437
        curl_setopt($ch, CURLOPT_TIMEOUT, 0);
1438

    
1439
        curl_exec($ch);
1440
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1441
        if($fout)
1442
                fclose($fout);
1443
        curl_close($ch);
1444
        return ($http_code == 200) ? true : $http_code;
1445
}
1446

    
1447
function read_header($ch, $string) {
1448
        global $file_size, $fout;
1449
        $length = strlen($string);
1450
        $regs = "";
1451
        ereg("(Content-Length:) (.*)", $string, $regs);
1452
        if($regs[2] <> "") {
1453
                $file_size = intval($regs[2]);
1454
        }
1455
        ob_flush();
1456
        return $length;
1457
}
1458

    
1459
function read_body($ch, $string) {
1460
        global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen;
1461
		global $pkg_interface;
1462
        $length = strlen($string);
1463
        $downloaded += intval($length);
1464
        if($file_size > 0) {
1465
                $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1466
                $downloadProgress = 100 - $downloadProgress;
1467
        } else
1468
                $downloadProgress = 0;
1469
        if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1470
                if($sendto == "status") {
1471
					if($pkg_interface == "console") {
1472
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1473
                        	$tostatus = $static_status . $downloadProgress . "%";
1474
                        	update_status($tostatus);
1475
						}
1476
					} else {
1477
                        $tostatus = $static_status . $downloadProgress . "%";
1478
                        update_status($tostatus);						
1479
					}
1480
                } else {
1481
					if($pkg_interface == "console") {
1482
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1483
                        	$tooutput = $static_output . $downloadProgress . "%";
1484
                        	update_output_window($tooutput);
1485
						}
1486
					} else {
1487
                        $tooutput = $static_output . $downloadProgress . "%";
1488
                        update_output_window($tooutput);
1489
					}
1490
                }
1491
                update_progress_bar($downloadProgress);
1492
                $lastseen = $downloadProgress;
1493
        }
1494
        if($fout)
1495
                fwrite($fout, $string);
1496
        ob_flush();
1497
        return $length;
1498
}
1499

    
1500
/*
1501
 *   update_output_window: update bottom textarea dynamically.
1502
 */
1503
function update_output_window($text) {
1504
        global $pkg_interface;
1505
        $log = ereg_replace("\n", "\\n", $text);
1506
        if($pkg_interface != "console") {
1507
                echo "\n<script language=\"JavaScript\">\nthis.document.forms[0].output.value = \"" . $log . "\";\n";
1508
				echo "this.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;\n";	
1509
				echo "</script>";
1510
        }
1511
        /* ensure that contents are written out */
1512
        ob_flush();
1513
}
1514

    
1515
/*
1516
 *   update_output_window: update top textarea dynamically.
1517
 */
1518
function update_status($status) {
1519
        global $pkg_interface;
1520
        if($pkg_interface == "console") {
1521
                echo $status . "\n";
1522
        } else {
1523
                echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
1524
        }
1525
        /* ensure that contents are written out */
1526
        ob_flush();
1527
}
1528

    
1529
/*
1530
 * update_progress_bar($percent): updates the javascript driven progress bar.
1531
 */
1532
function update_progress_bar($percent) {
1533
        global $pkg_interface;
1534
        if($percent > 100) $percent = 1;
1535
        if($pkg_interface <> "console") {
1536
                echo "\n<script type=\"text/javascript\" language=\"javascript\">";
1537
                echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1538
                echo "\n</script>";
1539
        } else {
1540
                echo " {$percent}%";
1541
        }
1542
}
1543

    
1544
/* 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. */
1545
if(!function_exists("split")) {
1546
	function split($seperator, $haystack, $limit = null) {
1547
		return preg_split($seperator, $haystack, $limit);
1548
	}
1549
}
1550

    
1551
function update_alias_names_upon_change($section, $subsection, $fielda, $fieldb, $new_alias_name, $origname) {
1552
	global $g, $config, $pconfig, $debug;
1553
	if(!$origname) 
1554
		return;
1555

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

    
1559
	if($fieldb) {
1560
		if($debug) fwrite($fd, "fieldb exists\n");
1561
		for ($i = 0; isset($config["$section"]["$subsection"][$i]["$fielda"]); $i++) {
1562
			if($debug) fwrite($fd, "$i\n");
1563
			if($config["$section"]["$subsection"][$i]["$fielda"]["$fieldb"] == $origname) {
1564
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1565
				$config["$section"]["$subsection"][$i]["$fielda"]["$fieldb"] = $new_alias_name;
1566
			}
1567
		}	
1568
	} else {
1569
		if($debug) fwrite($fd, "fieldb does not exist\n");
1570
		for ($i = 0; isset($config["$section"]["$subsection"][$i]["$fielda"]); $i++) {
1571
			if($config["$section"]["$subsection"][$i]["$fielda"] == $origname) {
1572
				$config["$section"]["$subsection"][$i]["$fielda"] = $new_alias_name;
1573
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1574
			}
1575
		}
1576
	}
1577

    
1578
	if($debug) fclose($fd);
1579

    
1580
}
1581

    
1582
function update_alias_url_data() {
1583
	global $config, $g;
1584

    
1585
	/* item is a url type */
1586
	$lockkey = lock('config');
1587
	if (is_array($config['aliases']['alias'])) {
1588
		foreach ($config['aliases']['alias'] as $x => $alias) {
1589
			if (empty($alias['aliasurl']))
1590
				continue;
1591

    
1592
			/* fetch down and add in */
1593
			$isfirst = 0;
1594
			$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1595
			unlink($temp_filename);
1596
			$fda = fopen("{$g['tmp_path']}/tmpfetch","w");
1597
			fwrite($fda, "/usr/bin/fetch -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1598
			fclose($fda);
1599
			mwexec("/bin/mkdir -p {$temp_filename}");
1600
			mwexec("/usr/bin/fetch -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1601
			/* if the item is tar gzipped then extract */
1602
			if(stristr($alias['aliasurl'], ".tgz"))
1603
				process_alias_tgz($temp_filename);
1604
			else if(stristr($alias['aliasurl'], ".zip"))
1605
				process_alias_unzip($temp_filename);
1606
			if(file_exists("{$temp_filename}/aliases")) {
1607
				$file_contents = file_get_contents("{$temp_filename}/aliases");
1608
				$file_contents = str_replace("#", "\n#", $file_contents);
1609
				$file_contents_split = split("\n", $file_contents);
1610
				foreach($file_contents_split as $fc) {
1611
					$tmp = trim($fc);
1612
					if(stristr($fc, "#")) {
1613
						$tmp_split = split("#", $tmp);
1614
						$tmp = trim($tmp_split[0]);
1615
					}
1616
					if(trim($tmp) <> "") {
1617
						if($isfirst == 1)
1618
							$address .= " ";
1619
						$address .= $tmp;
1620
						$isfirst = 1;
1621
					}
1622
				}
1623
				if($isfirst > 0) {
1624
					$config['aliases']['alias'][$x]['address'] = $address;
1625
					$updated = true;
1626
				}
1627
				mwexec("/bin/rm -rf {$temp_filename}");
1628
			}
1629
		}
1630
	}
1631
	if($updated)
1632
		write_config();
1633
	unlock($lockkey);
1634
}
1635

    
1636
function process_alias_unzip($temp_filename) {
1637
	if(!file_exists("/usr/local/bin/unzip"))
1638
		return;
1639
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.zip");
1640
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1641
	unlink("{$temp_filename}/aliases.zip");
1642
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1643
	/* foreach through all extracted files and build up aliases file */
1644
	$fd = fopen("{$temp_filename}/aliases", "w");
1645
	foreach($files_to_process as $f2p) {
1646
		$file_contents = file_get_contents($f2p);
1647
		fwrite($fd, $file_contents);
1648
		unlink($f2p);
1649
	}
1650
	fclose($fd);
1651
}
1652

    
1653
function process_alias_tgz($temp_filename) {
1654
	if(!file_exists("/usr/bin/tar"))
1655
		return;
1656
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.tgz");
1657
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1658
	unlink("{$temp_filename}/aliases.tgz");
1659
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1660
	/* foreach through all extracted files and build up aliases file */
1661
	$fd = fopen("{$temp_filename}/aliases", "w");
1662
	foreach($files_to_process as $f2p) {
1663
		$file_contents = file_get_contents($f2p);
1664
		fwrite($fd, $file_contents);
1665
		unlink($f2p);
1666
	}
1667
	fclose($fd);
1668
}
1669

    
1670
function version_compare_dates($a, $b) {
1671
	$a_time = strtotime($a);
1672
	$b_time = strtotime($b);
1673

    
1674
	if ((!$a_time) || (!$b_time)) {
1675
		return FALSE;
1676
	} else {
1677
		if ($a_time < $b_time)
1678
			return -1;
1679
		elseif ($$a_time == $b_time)
1680
			return 0;
1681
		else
1682
			return 1;
1683
	}
1684
}
1685
function version_get_string_value($a) {
1686
	$strs = array(
1687
		0 => "ALPHA-ALPHA",
1688
		2 => "ALPHA",
1689
		3 => "BETA",
1690
		4 => "B",
1691
		5 => "C",
1692
		6 => "D",
1693
		7 => "RC",
1694
		8 => "RELEASE"
1695
	);
1696
	$major = 0;
1697
	$minor = 0;
1698
	foreach ($strs as $num => $str) {
1699
		if (substr($a, 0, strlen($str)) == $str) {
1700
			$major = $num;
1701
			$n = substr($a, strlen($str));
1702
			if (is_numeric($n))
1703
				$minor = $n;
1704
			break;
1705
		}
1706
	}
1707
	return "{$major}.{$minor}";
1708
}
1709
function version_compare_string($a, $b) {
1710
	return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
1711
}
1712
function version_compare_numeric($a, $b) {
1713
	$a_arr = explode('.', rtrim($a, '.0'));
1714
	$b_arr = explode('.', rtrim($b, '.0'));
1715

    
1716
	foreach ($a_arr as $n => $val) {
1717
		if (array_key_exists($n, $b_arr)) {
1718
			// So far so good, both have values at this minor version level. Compare.
1719
			if ($val > $b_arr[$n])
1720
				return 1;
1721
			elseif ($val < $b_arr[$n])
1722
				return -1;
1723
		} else {
1724
			// a is greater, since b doesn't have any minor version here.
1725
			return 1;
1726
		}
1727
	}
1728
	if (count($b_arr) > count($a_arr)) {
1729
		// b is longer than a, so it must be greater.
1730
		return -1;
1731
	} else {
1732
		// Both a and b are of equal length and value.
1733
		return 0;
1734
	}
1735
}
1736
function pfs_version_compare($cur_time, $cur_text, $remote) {
1737
	// First try date compare
1738
	$v = version_compare_dates($cur_time, $remote);
1739
	if ($v === FALSE) {
1740
		// If that fails, try to compare by string
1741
		// Before anything else, simply test if the strings are equal
1742
		if (($cur_text == $remote) || ($cur_time == $remote))
1743
			return 0;
1744
		list($cur_num, $cur_str) = explode('-', $cur_text);
1745
		list($rem_num, $rem_str) = explode('-', $remote);
1746

    
1747
		// First try to compare the numeric parts of the version string.
1748
		$v = version_compare_numeric($cur_num, $rem_num);
1749

    
1750
		// If the numeric parts are the same, compare the string parts.
1751
		if ($v == 0)
1752
			return version_compare_string($cur_str, $rem_str);
1753
	}
1754
	return $v;
1755
}
1756
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
1757
	$urltable_prefix = "/var/db/aliastables/";
1758
	$urltable_filename = $urltable_prefix . $name . ".txt";
1759

    
1760
	// Make the aliases directory if it doesn't exist
1761
	if (!file_exists($urltable_prefix)) {
1762
		mkdir($urltable_prefix);
1763
	} elseif (!is_dir($urltable_prefix)) {
1764
		unlink($urltable_prefix);
1765
		mkdir($urltable_prefix);
1766
	}
1767

    
1768
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
1769
	if (!file_exists($urltable_filename)
1770
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400))
1771
		|| $forceupdate) {
1772

    
1773
		// Try to fetch the URL supplied
1774
		conf_mount_rw();
1775
		unlink_if_exists($urltable_filename . ".tmp");
1776
		// Use fetch to grab data since these may be large files, we don't want to process them through PHP if we can help it.
1777
		mwexec("/usr/bin/fetch -q -o " . escapeshellarg($urltable_filename . ".tmp") . " " . escapeshellarg($url));
1778
		// Remove comments. Might need some grep-fu to only allow lines that look like IPs/subnets
1779
		mwexec("/usr/bin/grep -v '^#' " . escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
1780
		unlink_if_exists($urltable_filename . ".tmp");
1781
		conf_mount_ro();
1782
		if (filesize($urltable_filename)) {
1783
			return true;
1784
		} else {
1785
			// If it's unfetchable or an empty file, bail
1786
			return false;
1787
		}
1788
	} else {
1789
		// File exists, and it doesn't need updated.
1790
		return -1;
1791
	}
1792
}
1793
function get_real_slice_from_glabel($label) {
1794
	$label = escapeshellarg($label);
1795
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
1796
}
1797
function nanobsd_get_boot_slice() {
1798
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
1799
}
1800
function nanobsd_get_boot_drive() {
1801
	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`);
1802
}
1803
function nanobsd_get_active_slice() {
1804
	$boot_drive = nanobsd_get_boot_drive();
1805
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
1806

    
1807
	return "{$boot_drive}s{$active}";
1808
}
1809
function nanobsd_get_size() {
1810
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
1811
}
1812
function nanobsd_switch_boot_slice() {
1813
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1814
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1815
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1816
	nanobsd_detect_slice_info();
1817

    
1818
	if ($BOOTFLASH == $ACTIVE_SLICE) {
1819
		$slice = $TOFLASH;
1820
	} else {
1821
		$slice = $BOOTFLASH;
1822
	}
1823

    
1824
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
1825
	ob_implicit_flush(1);
1826
	if(strstr($slice, "s2")) {
1827
		$ASLICE="2";
1828
		$AOLDSLICE="1";
1829
		$AGLABEL_SLICE="pfsense1";
1830
		$AUFS_ID="1";
1831
		$AOLD_UFS_ID="0";
1832
	} else {
1833
		$ASLICE="1";
1834
		$AOLDSLICE="2";
1835
		$AGLABEL_SLICE="pfsense0";
1836
		$AUFS_ID="0";
1837
		$AOLD_UFS_ID="1";
1838
	}
1839
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
1840
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
1841
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
1842
	conf_mount_rw();
1843
	exec("sysctl kern.geom.debugflags=16");
1844
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
1845
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
1846
	// We can't update these if they are mounted now.
1847
	if ($BOOTFLASH != $slice) {
1848
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
1849
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
1850
	}
1851
	exec("/sbin/sysctl kern.geom.debugflags=0");
1852
	conf_mount_ro();
1853
}
1854
function nanobsd_clone_slice() {
1855
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1856
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1857
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1858
	nanobsd_detect_slice_info();
1859

    
1860
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
1861
	ob_implicit_flush(1);
1862
	exec("/sbin/sysctl kern.geom.debugflags=16");
1863
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
1864
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
1865
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
1866
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
1867
	exec("/sbin/sysctl kern.geom.debugflags=0");
1868
	if($status) {
1869
		return false;
1870
	} else {
1871
		return true;
1872
	}
1873
}
1874
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
1875
	$tmppath = "/tmp/{$gslice}";
1876
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
1877

    
1878
	exec("/bin/mkdir {$tmppath}");
1879
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
1880
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
1881
	exec("/bin/cp /etc/fstab {$fstabpath}");
1882

    
1883
	if (!file_exists($fstabpath)) {
1884
		$fstab = <<<EOF
1885
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
1886
/dev/ufs/cf /cf ufs ro,noatime 1 1
1887
EOF;
1888
		if (file_put_contents($fstabpath, $fstab))
1889
			$status = true;
1890
		else
1891
			$status = false;
1892
	} else {
1893
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
1894
	}
1895
	exec("/sbin/umount {$tmppath}");
1896
	exec("/bin/rmdir {$tmppath}");
1897

    
1898
	return $status;
1899
}
1900
function nanobsd_detect_slice_info() {
1901
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1902
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1903
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1904

    
1905
	$BOOT_DEVICE=nanobsd_get_boot_slice();
1906
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
1907
	$BOOT_DRIVE=nanobsd_get_boot_drive();
1908
	$ACTIVE_SLICE=nanobsd_get_active_slice();
1909

    
1910
	// Detect which slice is active and set information.
1911
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
1912
		$SLICE="2";
1913
		$OLDSLICE="1";
1914
		$GLABEL_SLICE="pfsense1";
1915
		$UFS_ID="1";
1916
		$OLD_UFS_ID="0";
1917

    
1918
	} else {
1919
		$SLICE="1";
1920
		$OLDSLICE="2";
1921
		$GLABEL_SLICE="pfsense0";
1922
		$UFS_ID="0";
1923
		$OLD_UFS_ID="1";
1924
	}
1925
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
1926
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
1927
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
1928
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
1929
}
1930

    
1931
function nanobsd_friendly_slice_name($slicename) {
1932
	global $g;
1933
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
1934
}
1935

    
1936
function get_include_contents($filename) {
1937
    if (is_file($filename)) {
1938
        ob_start();
1939
        include $filename;
1940
        $contents = ob_get_contents();
1941
        ob_end_clean();
1942
        return $contents;
1943
    }
1944
    return false;
1945
}
1946

    
1947
/* This xml 2 array function is courtesy of the php.net comment section on xml_parse.
1948
 * it is roughly 4 times faster then our existing pfSense parser but due to the large
1949
 * size of the RRD xml dumps this is required.
1950
 * The reason we do not use it for pfSense is that it does not know about array fields
1951
 * which causes it to fail on array fields with single items. Possible Todo?
1952
 */
1953
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
1954
{
1955
    if (!function_exists('xml_parser_create'))
1956
    {
1957
        return array ();
1958
    }
1959
    $parser = xml_parser_create('');
1960
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
1961
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1962
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
1963
    xml_parse_into_struct($parser, trim($contents), $xml_values);
1964
    xml_parser_free($parser);
1965
    if (!$xml_values)
1966
        return; //Hmm...
1967
    $xml_array = array ();
1968
    $parents = array ();
1969
    $opened_tags = array ();
1970
    $arr = array ();
1971
    $current = & $xml_array;
1972
    $repeated_tag_index = array ();
1973
    foreach ($xml_values as $data)
1974
    {
1975
        unset ($attributes, $value);
1976
        extract($data);
1977
        $result = array ();
1978
        $attributes_data = array ();
1979
        if (isset ($value))
1980
        {
1981
            if ($priority == 'tag')
1982
                $result = $value;
1983
            else
1984
                $result['value'] = $value;
1985
        }
1986
        if (isset ($attributes) and $get_attributes)
1987
        {
1988
            foreach ($attributes as $attr => $val)
1989
            {
1990
                if ($priority == 'tag')
1991
                    $attributes_data[$attr] = $val;
1992
                else
1993
                    $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
1994
            }
1995
        }
1996
        if ($type == "open")
1997
        {
1998
            $parent[$level -1] = & $current;
1999
            if (!is_array($current) or (!in_array($tag, array_keys($current))))
2000
            {
2001
                $current[$tag] = $result;
2002
                if ($attributes_data)
2003
                    $current[$tag . '_attr'] = $attributes_data;
2004
                $repeated_tag_index[$tag . '_' . $level] = 1;
2005
                $current = & $current[$tag];
2006
            }
2007
            else
2008
            {
2009
                if (isset ($current[$tag][0]))
2010
                {
2011
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2012
                    $repeated_tag_index[$tag . '_' . $level]++;
2013
                }
2014
                else
2015
                {
2016
                    $current[$tag] = array (
2017
                        $current[$tag],
2018
                        $result
2019
                    );
2020
                    $repeated_tag_index[$tag . '_' . $level] = 2;
2021
                    if (isset ($current[$tag . '_attr']))
2022
                    {
2023
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
2024
                        unset ($current[$tag . '_attr']);
2025
                    }
2026
                }
2027
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
2028
                $current = & $current[$tag][$last_item_index];
2029
            }
2030
        }
2031
        elseif ($type == "complete")
2032
        {
2033
            if (!isset ($current[$tag]))
2034
            {
2035
                $current[$tag] = $result;
2036
                $repeated_tag_index[$tag . '_' . $level] = 1;
2037
                if ($priority == 'tag' and $attributes_data)
2038
                    $current[$tag . '_attr'] = $attributes_data;
2039
            }
2040
            else
2041
            {
2042
                if (isset ($current[$tag][0]) and is_array($current[$tag]))
2043
                {
2044
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2045
                    if ($priority == 'tag' and $get_attributes and $attributes_data)
2046
                    {
2047
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2048
                    }
2049
                    $repeated_tag_index[$tag . '_' . $level]++;
2050
                }
2051
                else
2052
                {
2053
                    $current[$tag] = array (
2054
                        $current[$tag],
2055
                        $result
2056
                    );
2057
                    $repeated_tag_index[$tag . '_' . $level] = 1;
2058
                    if ($priority == 'tag' and $get_attributes)
2059
                    {
2060
                        if (isset ($current[$tag . '_attr']))
2061
                        {
2062
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
2063
                            unset ($current[$tag . '_attr']);
2064
                        }
2065
                        if ($attributes_data)
2066
                        {
2067
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2068
                        }
2069
                    }
2070
                    $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
2071
                }
2072
            }
2073
        }
2074
        elseif ($type == 'close')
2075
        {
2076
            $current = & $parent[$level -1];
2077
        }
2078
    }
2079
    return ($xml_array);
2080
}
2081

    
2082
function get_country_name($country_code) {
2083
	if ($country_code != "ALL" && strlen($country_code) != 2)
2084
		return "";
2085

    
2086
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2087
	$country_names_contents = file_get_contents($country_names_xml);
2088
	$country_names = xml2array($country_names_contents);
2089

    
2090
	if($country_code == "ALL") {
2091
		$country_list = array();
2092
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2093
			$country_list[] = array( "code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2094
						 "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2095
		}
2096
		return $country_list;
2097
	}
2098

    
2099
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2100
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2101
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2102
		}
2103
	}
2104
	return "";
2105
}
2106

    
2107
/* sort by interface only, retain the original order of rules that apply to
2108
   the same interface */
2109
function filter_rules_sort() {
2110
	global $config;
2111

    
2112
	/* mark each rule with the sequence number (to retain the order while sorting) */
2113
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2114
		$config['filter']['rule'][$i]['seq'] = $i;
2115

    
2116
	usort($config['filter']['rule'], "filter_rules_compare");
2117

    
2118
	/* strip the sequence numbers again */
2119
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2120
		unset($config['filter']['rule'][$i]['seq']);
2121
}
2122
function filter_rules_compare($a, $b) {
2123
	if (isset($a['floating']) && isset($b['floating']))
2124
		return $a['seq'] - $b['seq'];
2125
	else if (isset($a['floating']))
2126
		return -1;
2127
	else if (isset($b['floating']))
2128
		return 1;
2129
	else if ($a['interface'] == $b['interface'])
2130
		return $a['seq'] - $b['seq'];
2131
	else
2132
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2133
}
2134

    
2135
?>
(35-35/61)