Project

General

Profile

Download (61.4 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
	$ip = gethostbyname($g['product_website']);
732
	if($ip == $g['product_website'])
733
		return false;
734
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
735
		"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
736
		"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
737
		"platform" => trim(file_get_contents('/etc/platform'))
738
		);
739
	if($tocheck == "all") {
740
		$params = $rawparams;
741
	} else {
742
		foreach($tocheck as $check) {
743
			$params['check'] = $rawparams['check'];
744
			$params['platform'] = $rawparams['platform'];
745
		}
746
	}
747
	if($config['system']['firmware']['branch']) {
748
		$params['branch'] = $config['system']['firmware']['branch'];
749
	}
750
	if(!$versions = call_pfsense_method('pfsense.get_firmware_version', $params)) {
751
		return false;
752
	} else {
753
		$versions["current"] = $params;
754
	}
755
	return $versions;
756
}
757

    
758
function get_disk_info() {
759
	$diskout = "";
760
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $2, $3, $4, $5 }'", $diskout);
761
	return explode(' ', $diskout[0]);
762
	// $size, $used, $avail, $cap
763
}
764

    
765
/****f* pfsense-utils/strncpy
766
 * NAME
767
 *   strncpy - copy strings
768
 * INPUTS
769
 *   &$dst, $src, $length
770
 * RESULT
771
 *   none
772
 ******/
773
function strncpy(&$dst, $src, $length) {
774
	if (strlen($src) > $length) {
775
		$dst = substr($src, 0, $length);
776
	} else {
777
		$dst = $src;
778
	}
779
}
780

    
781
/****f* pfsense-utils/reload_interfaces_sync
782
 * NAME
783
 *   reload_interfaces - reload all interfaces
784
 * INPUTS
785
 *   none
786
 * RESULT
787
 *   none
788
 ******/
789
function reload_interfaces_sync() {
790
	global $config, $g;
791

    
792
	/* XXX: Use locks?! */
793
	if (file_exists("{$g['tmp_path']}/reloading_all")) {
794
		log_error("WARNING: Recursive call to interfaces sync!");
795
		return;
796
	}
797
	touch("{$g['tmp_path']}/reloading_all");
798

    
799
	if($g['debug'])
800
		log_error("reload_interfaces_sync() is starting.");
801

    
802
	/* parse config.xml again */
803
	$config = parse_config(true);
804

    
805
	/* enable routing */
806
	system_routing_enable();
807
	if($g['debug'])
808
		log_error("Enabling system routing");
809

    
810
	if($g['debug'])
811
		log_error("Cleaning up Interfaces");
812

    
813
	/* set up interfaces */
814
	interfaces_configure();
815

    
816
	/* remove reloading_all trigger */
817
	if($g['debug'])
818
		log_error("Removing {$g['tmp_path']}/reloading_all");
819

    
820
	/* start devd back up */
821
	mwexec("/bin/rm {$g['tmp_path']}/reload*");
822
}
823

    
824
/****f* pfsense-utils/reload_all
825
 * NAME
826
 *   reload_all - triggers a reload of all settings
827
 *   * INPUTS
828
 *   none
829
 * RESULT
830
 *   none
831
 ******/
832
function reload_all() {
833
	global $g;
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
	global $g;
847
	touch("{$g['tmp_path']}/reload_interfaces");
848
}
849

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

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

    
863
	/* XXX: Use locks?! */
864
        if (file_exists("{$g['tmp_path']}/reloading_all")) {
865
                log_error("WARNING: Recursive call to reload all sync!");
866
                return;
867
        }
868
	touch("{$g['tmp_path']}/reloading_all");
869

    
870
	/* parse config.xml again */
871
	$config = parse_config(true);
872

    
873
	/* set up our timezone */
874
	system_timezone_configure();
875

    
876
	/* set up our hostname */
877
	system_hostname_configure();
878

    
879
	/* make hosts file */
880
	system_hosts_generate();
881

    
882
	/* generate resolv.conf */
883
	system_resolvconf_generate();
884

    
885
	/* enable routing */
886
	system_routing_enable();
887

    
888
	/* set up interfaces */
889
	interfaces_configure();
890

    
891
	/* start dyndns service */
892
	services_dyndns_configure();
893

    
894
	/* configure cron service */
895
	configure_cron();
896

    
897
	/* start the NTP client */
898
	system_ntp_configure();
899

    
900
	/* sync pw database */
901
	conf_mount_rw();
902
	unlink_if_exists("/etc/spwd.db.tmp");
903
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
904
	conf_mount_ro();
905

    
906
	/* restart sshd */
907
	send_event("service restart sshd");
908

    
909
	/* restart webConfigurator if needed */
910
	send_event("service restart webgui");
911

    
912
	mwexec("/bin/rm {$g['tmp_path']}/reload*");
913
}
914

    
915
function auto_login() {
916
	global $config;
917

    
918
	if(isset($config['system']['disableconsolemenu']))
919
		$status = false;
920
	else
921
		$status = true;
922

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

    
953
function setup_serial_port() {
954
	global $g, $config;
955
	conf_mount_rw();
956
	/* serial console - write out /boot.config */
957
	if(file_exists("/boot.config"))
958
		$boot_config = file_get_contents("/boot.config");
959
	else
960
		$boot_config = "";
961

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

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

    
1012
	conf_mount_ro();
1013
	return;
1014
}
1015

    
1016
function print_value_list($list, $count = 10, $separator = ",") {
1017
	$list = implode($separator, array_slice($list, 0, $count));
1018
	if(count($list) < $count) {
1019
		$list .= ".";
1020
	} else {
1021
		$list .= "...";
1022
	}
1023
	return $list;
1024
}
1025

    
1026
/* DHCP enabled on any interfaces? */
1027
function is_dhcp_server_enabled() 
1028
{
1029
	global $config;
1030

    
1031
	$dhcpdenable = false;
1032
	
1033
	if (!is_array($config['dhcpd']))
1034
		return false;
1035

    
1036
	$Iflist = get_configured_interface_list();
1037

    
1038
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1039
		if (isset($dhcpifconf['enable']) && isset($Iflist[$dhcpif])) {
1040
			$dhcpdenable = true;
1041
			break;
1042
		}
1043
	}
1044

    
1045
	return $dhcpdenable;
1046
}
1047

    
1048
function convert_seconds_to_hms($sec){
1049
	$min=$hrs=0;
1050
	if ($sec != 0){
1051
		$min = floor($sec/60);
1052
		$sec %= 60;
1053
	}
1054
	if ($min != 0){
1055
		$hrs = floor($min/60);
1056
		$min %= 60;
1057
	}
1058
	if ($sec < 10)
1059
		$sec = "0".$sec;
1060
	if ($min < 10)
1061
		$min = "0".$min;
1062
	if ($hrs < 10)
1063
		$hrs = "0".$hrs;
1064
	$result = $hrs.":".$min.":".$sec;
1065
	return $result;
1066
}
1067

    
1068
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1069

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

    
1085
//returns interface information
1086
function get_interface_info($ifdescr) {
1087
	global $config, $g;
1088

    
1089
	$ifinfo = array();
1090
	if (empty($config['interfaces'][$ifdescr]))
1091
		return;
1092
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1093
	$ifinfo['if'] = get_real_interface($ifdescr);
1094

    
1095
	$chkif = $ifinfo['if'];
1096
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1097
	$ifinfo['status'] = $ifinfotmp['status'];
1098
	if (empty($ifinfo['status']))
1099
                $ifinfo['status'] = "down";
1100
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1101
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1102
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1103
	if (isset($ifinfotmp['link0']))
1104
		$link0 = "down";
1105
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1106
        $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1107
        $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1108
        $ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1109
        $ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1110
        $ifinfo['collisions'] = $ifinfotmp['collisions'];
1111

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

    
1126
	/* Block */
1127
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1128
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1129
	$in4_block = $pf_in4_block[5];
1130
	$out4_block = $pf_out4_block[5];
1131
	$in4_block_packets = $pf_in4_block[3];
1132
	$out4_block_packets = $pf_out4_block[3];
1133
	$ifinfo['inbytesblock'] = $in4_block;
1134
	$ifinfo['outbytesblock'] = $out4_block;
1135
	$ifinfo['inpktsblock'] = $in4_block_packets;
1136
	$ifinfo['outpktsblock'] = $out4_block_packets;
1137

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

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

    
1166
		break;
1167
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1168
	case "ppp":
1169
		if ($ifinfo['status'] == "up")
1170
			$ifinfo['ppplink'] = "up";
1171
		else
1172
			$ifinfo['ppplink'] = "down" ;
1173

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

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

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

    
1253
		}
1254
		/* lookup the gateway */
1255
		if (interface_has_gateway($ifdescr)) 
1256
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1257
	}
1258

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

    
1275
	return $ifinfo;
1276
}
1277

    
1278
//returns cpu speed of processor. Good for determining capabilities of machine
1279
function get_cpu_speed() {
1280
	 return exec("sysctl hw.clockrate | awk '{ print $2 }'");
1281
}
1282

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

    
1312
function is_fqdn($fqdn) {
1313
	$hostname = false;
1314
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1315
		$hostname = true;
1316
	}
1317
	if(preg_match("/\.\./", $fqdn)) {
1318
		$hostname = false;
1319
	}
1320
	if(preg_match("/^\./i", $fqdn)) { 
1321
		$hostname = false;
1322
	}
1323
	if(preg_match("/\//i", $fqdn)) {
1324
		$hostname = false;
1325
	}
1326
	return($hostname);
1327
}
1328

    
1329
function pfsense_default_state_size() {
1330
  /* get system memory amount */
1331
  $memory = get_memory();
1332
  $avail = $memory[0];
1333
  /* Be cautious and only allocate 10% of system memory to the state table */
1334
  $max_states = (int) ($avail/10)*1000;
1335
  return $max_states;
1336
}
1337

    
1338
function pfsense_default_table_entries_size() {
1339
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1340
	return $current;
1341
}
1342

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

    
1379
	if(trim($oldcontents) != trim($contents)) {
1380
		if($g['debug']) {
1381
			log_error("DNSCACHE: Found old IP {$oldcontents} and new IP {$contents}");
1382
		}
1383
		return ($oldcontents);
1384
	} else {
1385
		return false;
1386
	}
1387
}
1388

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

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

    
1417
function get_freebsd_version() {
1418
	$version = php_uname("r");
1419
	return $version[0];
1420
}
1421

    
1422
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body') {
1423
        global $ch, $fout, $file_size, $downloaded;
1424
        $file_size  = 1;
1425
        $downloaded = 1;
1426
        /* open destination file */
1427
        $fout = fopen($destination_file, "wb");
1428

    
1429
        /*
1430
         *      Originally by Author: Keyvan Minoukadeh
1431
         *      Modified by Scott Ullrich to return Content-Length size
1432
         */
1433

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

    
1445
        curl_exec($ch);
1446
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1447
        if($fout)
1448
                fclose($fout);
1449
        curl_close($ch);
1450
        return ($http_code == 200) ? true : $http_code;
1451
}
1452

    
1453
function read_header($ch, $string) {
1454
        global $file_size, $fout;
1455
        $length = strlen($string);
1456
        $regs = "";
1457
        ereg("(Content-Length:) (.*)", $string, $regs);
1458
        if($regs[2] <> "") {
1459
                $file_size = intval($regs[2]);
1460
        }
1461
        ob_flush();
1462
        return $length;
1463
}
1464

    
1465
function read_body($ch, $string) {
1466
        global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen;
1467
        $length = strlen($string);
1468
        $downloaded += intval($length);
1469
        $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1470
        $downloadProgress = 100 - $downloadProgress;
1471
        if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1472
                if($sendto == "status") {
1473
                        $tostatus = $static_status . $downloadProgress . "%";
1474
                        update_status($tostatus);
1475
                } else {
1476
                        $tooutput = $static_output . $downloadProgress . "%";
1477
                        update_output_window($tooutput);
1478
                }
1479
                update_progress_bar($downloadProgress);
1480
                $lastseen = $downloadProgress;
1481
        }
1482
        if($fout)
1483
                fwrite($fout, $string);
1484
        ob_flush();
1485
        return $length;
1486
}
1487

    
1488
/*
1489
 *   update_output_window: update bottom textarea dynamically.
1490
 */
1491
function update_output_window($text) {
1492
        global $pkg_interface;
1493
        $log = ereg_replace("\n", "\\n", $text);
1494
        if($pkg_interface != "console") {
1495
                echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"" . $log . "\";</script>";
1496
        }
1497
        /* ensure that contents are written out */
1498
        ob_flush();
1499
}
1500

    
1501
/*
1502
 *   update_output_window: update top textarea dynamically.
1503
 */
1504
function update_status($status) {
1505
        global $pkg_interface;
1506
        if($pkg_interface == "console") {
1507
                echo $status . "\n";
1508
        } else {
1509
                echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
1510
        }
1511
        /* ensure that contents are written out */
1512
        ob_flush();
1513
}
1514

    
1515
/*
1516
 * update_progress_bar($percent): updates the javascript driven progress bar.
1517
 */
1518
function update_progress_bar($percent) {
1519
        global $pkg_interface;
1520
        if($percent > 100) $percent = 1;
1521
        if($pkg_interface <> "console") {
1522
                echo "\n<script type=\"text/javascript\" language=\"javascript\">";
1523
                echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1524
                echo "\n</script>";
1525
        } else {
1526
                echo " {$percent}%";
1527
        }
1528
}
1529

    
1530
/* 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. */
1531
if(!function_exists("split")) {
1532
	function split($seperator, $haystack, $limit = null) {
1533
		return preg_split($seperator, $haystack, $limit);
1534
	}
1535
}
1536

    
1537
function update_alias_names_upon_change($section, $subsection, $fielda, $fieldb, $new_alias_name, $origname) {
1538
	global $g, $config, $pconfig, $debug;
1539
	if(!$origname) 
1540
		return;
1541

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

    
1545
	if($fieldb) {
1546
		if($debug) fwrite($fd, "fieldb exists\n");
1547
		for ($i = 0; isset($config["$section"]["$subsection"][$i]["$fielda"]); $i++) {
1548
			if($debug) fwrite($fd, "$i\n");
1549
			if($config["$section"]["$subsection"][$i]["$fielda"]["$fieldb"] == $origname) {
1550
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1551
				$config["$section"]["$subsection"][$i]["$fielda"]["$fieldb"] = $new_alias_name;
1552
			}
1553
		}	
1554
	} else {
1555
		if($debug) fwrite($fd, "fieldb does not exist\n");
1556
		for ($i = 0; isset($config["$section"]["$subsection"][$i]["$fielda"]); $i++) {
1557
			if($config["$section"]["$subsection"][$i]["$fielda"] == $origname) {
1558
				$config["$section"]["$subsection"][$i]["$fielda"] = $new_alias_name;
1559
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1560
			}
1561
		}
1562
	}
1563

    
1564
	if($debug) fclose($fd);
1565

    
1566
}
1567

    
1568
function update_alias_url_data() {
1569
	global $config, $g;
1570

    
1571
	/* item is a url type */
1572
	$lockkey = lock('config');
1573
	if (is_array($config['aliases']['alias'])) {
1574
		foreach ($config['aliases']['alias'] as $x => $alias) {
1575
			if (empty($alias['aliasurl']))
1576
				continue;
1577

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

    
1622
function process_alias_unzip($temp_filename) {
1623
	if(!file_exists("/usr/local/bin/unzip"))
1624
		return;
1625
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.zip");
1626
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1627
	unlink("{$temp_filename}/aliases.zip");
1628
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1629
	/* foreach through all extracted files and build up aliases file */
1630
	$fd = fopen("{$temp_filename}/aliases", "w");
1631
	foreach($files_to_process as $f2p) {
1632
		$file_contents = file_get_contents($f2p);
1633
		fwrite($fd, $file_contents);
1634
		unlink($f2p);
1635
	}
1636
	fclose($fd);
1637
}
1638

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

    
1656
function version_compare_dates($a, $b) {
1657
	$a_time = strtotime($a);
1658
	$b_time = strtotime($b);
1659

    
1660
	if ((!$a_time) || (!$b_time)) {
1661
		return FALSE;
1662
	} else {
1663
		if ($a < $b)
1664
			return -1;
1665
		elseif ($a == $b)
1666
			return 0;
1667
		else
1668
			return 1;
1669
	}
1670
}
1671
function version_get_string_value($a) {
1672
	$strs = array(
1673
		0 => "ALPHA-ALPHA",
1674
		2 => "ALPHA",
1675
		3 => "BETA",
1676
		4 => "B",
1677
		5 => "C",
1678
		6 => "D",
1679
		7 => "RC",
1680
		8 => "RELEASE"
1681
	);
1682
	$major = 0;
1683
	$minor = 0;
1684
	foreach ($strs as $num => $str) {
1685
		if (substr($a, 0, strlen($str)) == $str) {
1686
			$major = $num;
1687
			$n = substr($a, strlen($str));
1688
			if (is_numeric($n))
1689
				$minor = $n;
1690
			break;
1691
		}
1692
	}
1693
	return "{$major}.{$minor}";
1694
}
1695
function version_compare_string($a, $b) {
1696
	return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
1697
}
1698
function version_compare_numeric($a, $b) {
1699
	$a_arr = explode('.', rtrim($a, '.0'));
1700
	$b_arr = explode('.', rtrim($b, '.0'));
1701

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

    
1733
		// First try to compare the numeric parts of the version string.
1734
		$v = version_compare_numeric($cur_num, $rem_num);
1735

    
1736
		// If the numeric parts are the same, compare the string parts.
1737
		if ($v == 0)
1738
			return version_compare_string($cur_str, $rem_str);
1739
	}
1740
	return $v;
1741
}
1742
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
1743
	$urltable_prefix = "/var/db/aliastables/";
1744
	$urltable_filename = $urltable_prefix . $name . ".txt";
1745

    
1746
	// Make the aliases directory if it doesn't exist
1747
	if (!file_exists($urltable_prefix)) {
1748
		mkdir($urltable_prefix);
1749
	} elseif (!is_dir($urltable_prefix)) {
1750
		unlink($urltable_prefix);
1751
		mkdir($urltable_prefix);
1752
	}
1753

    
1754
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
1755
	if (!file_exists($urltable_filename)
1756
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400))
1757
		|| $forceupdate) {
1758

    
1759
		// Try to fetch the URL supplied
1760
		conf_mount_rw();
1761
		unlink_if_exists($urltable_filename . ".tmp");
1762
		// 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.
1763
		mwexec("/usr/bin/fetch -q -o " . escapeshellarg($urltable_filename . ".tmp") . " " . escapeshellarg($url));
1764
		// Remove comments. Might need some grep-fu to only allow lines that look like IPs/subnets
1765
		mwexec("/usr/bin/grep -v '^#' " . escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
1766
		unlink_if_exists($urltable_filename . ".tmp");
1767
		conf_mount_ro();
1768
		if (filesize($urltable_filename)) {
1769
			return true;
1770
		} else {
1771
			// If it's unfetchable or an empty file, bail
1772
			return false;
1773
		}
1774
	} else {
1775
		// File exists, and it doesn't need updated.
1776
		return -1;
1777
	}
1778
}
1779
function get_real_slice_from_glabel($label) {
1780
	$label = escapeshellarg($label);
1781
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
1782
}
1783
function nanobsd_get_boot_slice() {
1784
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
1785
}
1786
function nanobsd_get_boot_drive() {
1787
	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`);
1788
}
1789
function nanobsd_get_active_slice() {
1790
	$boot_drive = nanobsd_get_boot_drive();
1791
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
1792

    
1793
	return "{$boot_drive}s{$active}";
1794
}
1795
function nanobsd_get_size() {
1796
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
1797
}
1798
function nanobsd_switch_boot_slice() {
1799
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1800
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1801
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1802
	nanobsd_detect_slice_info();
1803

    
1804
	if ($BOOTFLASH == $ACTIVE_SLICE) {
1805
		$slice = $TOFLASH;
1806
	} else {
1807
		$slice = $BOOTFLASH;
1808
	}
1809

    
1810
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
1811
	ob_implicit_flush(1);
1812
	if(strstr($slice, "s2")) {
1813
		$ASLICE="2";
1814
		$AOLDSLICE="1";
1815
		$AGLABEL_SLICE="pfsense1";
1816
		$AUFS_ID="1";
1817
		$AOLD_UFS_ID="0";
1818
	} else {
1819
		$ASLICE="1";
1820
		$AOLDSLICE="2";
1821
		$AGLABEL_SLICE="pfsense0";
1822
		$AUFS_ID="0";
1823
		$AOLD_UFS_ID="1";
1824
	}
1825
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
1826
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
1827
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
1828
	conf_mount_rw();
1829
	exec("sysctl kern.geom.debugflags=16");
1830
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
1831
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
1832
	// We can't update these if they are mounted now.
1833
	if ($BOOTFLASH != $slice) {
1834
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
1835
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
1836
	}
1837
	exec("/sbin/sysctl kern.geom.debugflags=0");
1838
	conf_mount_ro();
1839
}
1840
function nanobsd_clone_slice() {
1841
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1842
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1843
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1844
	nanobsd_detect_slice_info();
1845

    
1846
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
1847
	ob_implicit_flush(1);
1848
	exec("/sbin/sysctl kern.geom.debugflags=16");
1849
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
1850
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
1851
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
1852
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
1853
	exec("/sbin/sysctl kern.geom.debugflags=0");
1854
	if($status) {
1855
		return false;
1856
	} else {
1857
		return true;
1858
	}
1859
}
1860
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
1861
	$tmppath = "/tmp/{$gslice}";
1862
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
1863

    
1864
	exec("/bin/mkdir {$tmppath}");
1865
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
1866
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
1867
	exec("/bin/cp /etc/fstab {$fstabpath}");
1868

    
1869
	if (!file_exists($fstabpath)) {
1870
		$fstab = <<<EOF
1871
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
1872
/dev/ufs/cf /cf ufs ro,noatime 1 1
1873
EOF;
1874
		if (file_put_contents($fstabpath, $fstab))
1875
			$status = true;
1876
		else
1877
			$status = false;
1878
	} else {
1879
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
1880
	}
1881
	exec("/sbin/umount {$tmppath}");
1882
	exec("/bin/rmdir {$tmppath}");
1883

    
1884
	return $status;
1885
}
1886
function nanobsd_detect_slice_info() {
1887
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1888
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1889
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1890

    
1891
	$BOOT_DEVICE=nanobsd_get_boot_slice();
1892
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
1893
	$BOOT_DRIVE=nanobsd_get_boot_drive();
1894
	$ACTIVE_SLICE=nanobsd_get_active_slice();
1895

    
1896
	// Detect which slice is active and set information.
1897
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
1898
		$SLICE="2";
1899
		$OLDSLICE="1";
1900
		$GLABEL_SLICE="pfsense1";
1901
		$UFS_ID="1";
1902
		$OLD_UFS_ID="0";
1903

    
1904
	} else {
1905
		$SLICE="1";
1906
		$OLDSLICE="2";
1907
		$GLABEL_SLICE="pfsense0";
1908
		$UFS_ID="0";
1909
		$OLD_UFS_ID="1";
1910
	}
1911
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
1912
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
1913
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
1914
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
1915
}
1916

    
1917
function nanobsd_friendly_slice_name($slicename) {
1918
	global $g;
1919
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
1920
}
1921

    
1922
function get_include_contents($filename) {
1923
    if (is_file($filename)) {
1924
        ob_start();
1925
        include $filename;
1926
        $contents = ob_get_contents();
1927
        ob_end_clean();
1928
        return $contents;
1929
    }
1930
    return false;
1931
}
1932

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

    
2068
function get_country_name($country_code) {
2069
	if ($country_code != "ALL" && strlen($country_code) != 2)
2070
		return "";
2071

    
2072
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2073
	$country_names_contents = file_get_contents($country_names_xml);
2074
	$country_names = xml2array($country_names_contents);
2075

    
2076
	if($country_code == "ALL") {
2077
		$country_list = array();
2078
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2079
			$country_list[] = array( "code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2080
						 "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2081
		}
2082
		return $country_list;
2083
	}
2084

    
2085
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2086
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2087
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2088
		}
2089
	}
2090
	return "";
2091
}
2092

    
2093
/* sort by interface only, retain the original order of rules that apply to
2094
   the same interface */
2095
function filter_rules_sort() {
2096
	global $config;
2097

    
2098
	/* mark each rule with the sequence number (to retain the order while sorting) */
2099
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2100
		$config['filter']['rule'][$i]['seq'] = $i;
2101

    
2102
	usort($config['filter']['rule'], "filter_rules_compare");
2103

    
2104
	/* strip the sequence numbers again */
2105
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2106
		unset($config['filter']['rule'][$i]['seq']);
2107
}
2108
function filter_rules_compare($a, $b) {
2109
	if (isset($a['floating']) && isset($b['floating']))
2110
		return $a['seq'] - $b['seq'];
2111
	else if (isset($a['floating']))
2112
		return -1;
2113
	else if (isset($b['floating']))
2114
		return 1;
2115
	else if ($a['interface'] == $b['interface'])
2116
		return $a['seq'] - $b['seq'];
2117
	else
2118
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2119
}
2120

    
2121
?>
(30-30/54)