Project

General

Profile

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

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

    
43
/****f* pfsense-utils/have_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
	$port = 0;
707
	$proxyurl = "";
708
	$proxyport = 0;
709
	$proxyuser = "";
710
	$proxypass = "";
711
	if (!empty($config['system']['proxyurl']))
712
		$proxyurl = $config['system']['proxyurl'];
713
	if (!empty($config['system']['proxyport']) && is_numeric($config['system']['proxyport']))
714
		$proxyport = $config['system']['proxyport'];
715
	if (!empty($config['system']['proxyuser']))
716
		$proxyuser = $config['system']['proxyuser'];
717
	if (!empty($config['system']['proxypass']))
718
		$proxypass = $config['system']['proxypass'];
719
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url, $port, $proxyurl, $proxyport, $proxyuser, $proxypass);
720
	// If the ALT PKG Repo has a username/password set, use it.
721
	if($config['system']['altpkgrepo']['username'] && 
722
	   $config['system']['altpkgrepo']['password']) {
723
		$username = $config['system']['altpkgrepo']['username'];
724
		$password = $config['system']['altpkgrepo']['password'];
725
		$cli->setCredentials($username, $password);
726
	}
727
	elseif($g['xmlrpcauthuser'] && $g['xmlrpcauthpass']) {
728
		$username = $g['xmlrpcauthuser'];
729
		$password = $g['xmlrpcauthpass'];
730
		$cli->setCredentials($username, $password);
731
	}
732
	$resp = $cli->send($msg, $timeout);
733
	if(!is_object($resp)) {
734
		log_error("XMLRPC communication error: " . $cli->errstr);
735
		return false;
736
	} elseif($resp->faultCode()) {
737
		log_error("XMLRPC request failed with error " . $resp->faultCode() . ": " . $resp->faultString());
738
		return false;
739
	} else {
740
		return XML_RPC_Decode($resp->value());
741
	}
742
}
743

    
744
/*
745
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
746
 */
747
function check_firmware_version($tocheck = "all", $return_php = true) {
748
	global $g, $config;
749

    
750
	$ip = gethostbyname($g['product_website']);
751
	if($ip == $g['product_website'])
752
		return false;
753

    
754
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
755
		"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
756
		"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
757
		"platform" => trim(file_get_contents('/etc/platform')),
758
		"config_version" => $config['version']
759
		);
760
	if($tocheck == "all") {
761
		$params = $rawparams;
762
	} else {
763
		foreach($tocheck as $check) {
764
			$params['check'] = $rawparams['check'];
765
			$params['platform'] = $rawparams['platform'];
766
		}
767
	}
768
	if($config['system']['firmware']['branch'])
769
		$params['branch'] = $config['system']['firmware']['branch'];
770

    
771
	/* XXX: What is this method? */
772
	if(!($versions = call_pfsense_method('pfsense.get_firmware_version', $params))) {
773
		return false;
774
	} else {
775
		$versions["current"] = $params;
776
	}
777

    
778
	return $versions;
779
}
780

    
781
/*
782
 * host_firmware_version(): Return the versions used in this install
783
 */
784
function host_firmware_version($tocheck = "") {
785
        global $g, $config;
786

    
787
        return array(
788
		"firmware" => array("version" => trim(file_get_contents('/etc/version', " \n"))),
789
                "kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel', " \n"))),
790
                "base"     => array("version" => trim(file_get_contents('/etc/version_base', " \n"))),
791
                "platform" => trim(file_get_contents('/etc/platform', " \n")),
792
                "config_version" => $config['version']
793
                );
794
}
795

    
796
function get_disk_info() {
797
	$diskout = "";
798
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $2, $3, $4, $5 }'", $diskout);
799
	return explode(' ', $diskout[0]);
800
}
801

    
802
/****f* pfsense-utils/strncpy
803
 * NAME
804
 *   strncpy - copy strings
805
 * INPUTS
806
 *   &$dst, $src, $length
807
 * RESULT
808
 *   none
809
 ******/
810
function strncpy(&$dst, $src, $length) {
811
	if (strlen($src) > $length) {
812
		$dst = substr($src, 0, $length);
813
	} else {
814
		$dst = $src;
815
	}
816
}
817

    
818
/****f* pfsense-utils/reload_interfaces_sync
819
 * NAME
820
 *   reload_interfaces - reload all interfaces
821
 * INPUTS
822
 *   none
823
 * RESULT
824
 *   none
825
 ******/
826
function reload_interfaces_sync() {
827
	global $config, $g;
828

    
829
	if($g['debug'])
830
		log_error("reload_interfaces_sync() is starting.");
831

    
832
	/* parse config.xml again */
833
	$config = parse_config(true);
834

    
835
	/* enable routing */
836
	system_routing_enable();
837
	if($g['debug'])
838
		log_error("Enabling system routing");
839

    
840
	if($g['debug'])
841
		log_error("Cleaning up Interfaces");
842

    
843
	/* set up interfaces */
844
	interfaces_configure();
845
}
846

    
847
/****f* pfsense-utils/reload_all
848
 * NAME
849
 *   reload_all - triggers a reload of all settings
850
 *   * INPUTS
851
 *   none
852
 * RESULT
853
 *   none
854
 ******/
855
function reload_all() {
856
	send_event("service reload all");
857
}
858

    
859
/****f* pfsense-utils/reload_interfaces
860
 * NAME
861
 *   reload_interfaces - triggers a reload of all interfaces
862
 * INPUTS
863
 *   none
864
 * RESULT
865
 *   none
866
 ******/
867
function reload_interfaces() {
868
	send_event("interface all reload");
869
}
870

    
871
/****f* pfsense-utils/reload_all_sync
872
 * NAME
873
 *   reload_all - reload all settings
874
 *   * INPUTS
875
 *   none
876
 * RESULT
877
 *   none
878
 ******/
879
function reload_all_sync() {
880
	global $config, $g;
881

    
882
	$g['booting'] = false;
883

    
884
	/* parse config.xml again */
885
	$config = parse_config(true);
886

    
887
	/* set up our timezone */
888
	system_timezone_configure();
889

    
890
	/* set up our hostname */
891
	system_hostname_configure();
892

    
893
	/* make hosts file */
894
	system_hosts_generate();
895

    
896
	/* generate resolv.conf */
897
	system_resolvconf_generate();
898

    
899
	/* enable routing */
900
	system_routing_enable();
901

    
902
	/* set up interfaces */
903
	interfaces_configure();
904

    
905
	/* start dyndns service */
906
	services_dyndns_configure();
907

    
908
	/* configure cron service */
909
	configure_cron();
910

    
911
	/* start the NTP client */
912
	system_ntp_configure();
913

    
914
	/* sync pw database */
915
	conf_mount_rw();
916
	unlink_if_exists("/etc/spwd.db.tmp");
917
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
918
	conf_mount_ro();
919

    
920
	/* restart sshd */
921
	send_event("service restart sshd");
922

    
923
	/* restart webConfigurator if needed */
924
	send_event("service restart webgui");
925
}
926

    
927
function auto_login() {
928
	global $config;
929

    
930
	if(isset($config['system']['disableconsolemenu']))
931
		$status = false;
932
	else
933
		$status = true;
934

    
935
	$gettytab = file_get_contents("/etc/gettytab");
936
	$getty_split = split("\n", $gettytab);
937
	conf_mount_rw();
938
	$fd = false;
939
	$tries = 0;
940
	while (!$fd && $tries < 100) {
941
		$fd = fopen("/etc/gettytab", "w");
942
		$tries++;
943
		
944
	}
945
	if (!$fd) {
946
		conf_mount_ro();
947
		log_error("Enabling auto login was not possible.");
948
		return;
949
	}
950
	foreach($getty_split as $gs) {
951
		if(stristr($gs, ":ht:np:sp#115200") ) {
952
			if($status == true) {
953
				fwrite($fd, "	:ht:np:sp#115200:al=root:\n");
954
			} else {
955
				fwrite($fd, "	:ht:np:sp#115200:\n");
956
			}
957
		} else {
958
			fwrite($fd, "{$gs}\n");
959
		}
960
	}
961
	fclose($fd);
962
	conf_mount_ro();
963
}
964

    
965
function setup_serial_port() {
966
	global $g, $config;
967
	conf_mount_rw();
968
	/* serial console - write out /boot.config */
969
	if(file_exists("/boot.config"))
970
		$boot_config = file_get_contents("/boot.config");
971
	else
972
		$boot_config = "";
973

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

    
1002
			if(isset($config['system']['enableserial']))
1003
				$new_boot_config[] = 'console="comconsole"';
1004
			file_put_contents("/boot/loader.conf", implode("\n", $new_boot_config));
1005
		}
1006
	}
1007
	$ttys = file_get_contents("/etc/ttys");
1008
	$ttys_split = split("\n", $ttys);
1009
	$fd = fopen("/etc/ttys", "w");
1010
	foreach($ttys_split as $tty) {
1011
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
1012
			if(isset($config['system']['enableserial'])) {
1013
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
1014
			} else {
1015
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
1016
			}
1017
		} else {
1018
			fwrite($fd, $tty . "\n");
1019
		}
1020
	}
1021
	fclose($fd);
1022
	auto_login();
1023

    
1024
	conf_mount_ro();
1025
	return;
1026
}
1027

    
1028
function print_value_list($list, $count = 10, $separator = ",") {
1029
	$list = implode($separator, array_slice($list, 0, $count));
1030
	if(count($list) < $count) {
1031
		$list .= ".";
1032
	} else {
1033
		$list .= "...";
1034
	}
1035
	return $list;
1036
}
1037

    
1038
/* DHCP enabled on any interfaces? */
1039
function is_dhcp_server_enabled() 
1040
{
1041
	global $config;
1042

    
1043
	$dhcpdenable = false;
1044
	
1045
	if (!is_array($config['dhcpd']))
1046
		return false;
1047

    
1048
	$Iflist = get_configured_interface_list();
1049

    
1050
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1051
		if (isset($dhcpifconf['enable']) && isset($Iflist[$dhcpif])) {
1052
			$dhcpdenable = true;
1053
			break;
1054
		}
1055
	}
1056

    
1057
	return $dhcpdenable;
1058
}
1059

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

    
1064
	$pppoeenable = false;
1065

    
1066
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1067
		return false;
1068

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

    
1073
	return $pppoeenable;
1074
}
1075

    
1076
function convert_seconds_to_hms($sec){
1077
	$min=$hrs=0;
1078
	if ($sec != 0){
1079
		$min = floor($sec/60);
1080
		$sec %= 60;
1081
	}
1082
	if ($min != 0){
1083
		$hrs = floor($min/60);
1084
		$min %= 60;
1085
	}
1086
	if ($sec < 10)
1087
		$sec = "0".$sec;
1088
	if ($min < 10)
1089
		$min = "0".$min;
1090
	if ($hrs < 10)
1091
		$hrs = "0".$hrs;
1092
	$result = $hrs.":".$min.":".$sec;
1093
	return $result;
1094
}
1095

    
1096
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1097

    
1098
function get_ppp_uptime($port){
1099
	if (file_exists("/conf/{$port}.log")){
1100
    	$saved_time = file_get_contents("/conf/{$port}.log");
1101
    	$uptime_data = explode("\n",$saved_time);
1102
		$sec=0;
1103
		foreach($uptime_data as $upt) {
1104
			$sec += substr($upt, 1 + strpos($upt, " "));
1105
 		}
1106
		return convert_seconds_to_hms($sec);
1107
	} else {
1108
		$total_time = "No history data found!";
1109
		return $total_time;
1110
	}
1111
}
1112

    
1113
//returns interface information
1114
function get_interface_info($ifdescr) {
1115
	global $config, $g;
1116

    
1117
	$ifinfo = array();
1118
	if (empty($config['interfaces'][$ifdescr]))
1119
		return;
1120
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1121
	$ifinfo['if'] = get_real_interface($ifdescr);
1122

    
1123
	$chkif = $ifinfo['if'];
1124
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1125
	$ifinfo['status'] = $ifinfotmp['status'];
1126
	if (empty($ifinfo['status']))
1127
                $ifinfo['status'] = "down";
1128
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1129
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1130
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1131
	if (isset($ifinfotmp['link0']))
1132
		$link0 = "down";
1133
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1134
        $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1135
        $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1136
        $ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1137
        $ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1138
        $ifinfo['collisions'] = $ifinfotmp['collisions'];
1139

    
1140
	/* Use pfctl for non wrapping 64 bit counters */
1141
	/* Pass */
1142
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1143
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1144
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1145
	$in4_pass = $pf_in4_pass[5];
1146
	$out4_pass = $pf_out4_pass[5];
1147
	$in4_pass_packets = $pf_in4_pass[3];
1148
	$out4_pass_packets = $pf_out4_pass[3];
1149
	$ifinfo['inbytespass'] = $in4_pass;
1150
	$ifinfo['outbytespass'] = $out4_pass;
1151
	$ifinfo['inpktspass'] = $in4_pass_packets;
1152
	$ifinfo['outpktspass'] = $out4_pass_packets;
1153

    
1154
	/* Block */
1155
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1156
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1157
	$in4_block = $pf_in4_block[5];
1158
	$out4_block = $pf_out4_block[5];
1159
	$in4_block_packets = $pf_in4_block[3];
1160
	$out4_block_packets = $pf_out4_block[3];
1161
	$ifinfo['inbytesblock'] = $in4_block;
1162
	$ifinfo['outbytesblock'] = $out4_block;
1163
	$ifinfo['inpktsblock'] = $in4_block_packets;
1164
	$ifinfo['outpktsblock'] = $out4_block_packets;
1165

    
1166
	$ifinfo['inbytes'] = $in4_pass + $in4_block;
1167
	$ifinfo['outbytes'] = $out4_pass + $out4_block;
1168
	$ifinfo['inpkts'] = $in4_pass_packets + $in4_block_packets;
1169
	$ifinfo['outpkts'] = $in4_pass_packets + $out4_block_packets;
1170
		
1171
	$ifconfiginfo = "";
1172
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1173
	switch ($link_type) {
1174
	 /* DHCP? -> see if dhclient is up */
1175
	case "dhcp":
1176
	case "carpdev-dhcp":
1177
		/* see if dhclient is up */
1178
		if (find_dhclient_process($ifinfo['if']) <> "")
1179
			$ifinfo['dhcplink'] = "up";
1180
		else
1181
			$ifinfo['dhcplink'] = "down";
1182

    
1183
		break;
1184
	/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1185
	case "pppoe":
1186
	case "pptp":
1187
	case "l2tp":
1188
		if ($ifinfo['status'] == "up" && !isset($link0))
1189
			/* get PPPoE link status for dial on demand */
1190
			$ifinfo["{$link_type}link"] = "up";
1191
		else
1192
			$ifinfo["{$link_type}link"] = "down";
1193

    
1194
		break;
1195
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1196
	case "ppp":
1197
		if ($ifinfo['status'] == "up")
1198
			$ifinfo['ppplink'] = "up";
1199
		else
1200
			$ifinfo['ppplink'] = "down" ;
1201

    
1202
		if (empty($ifinfo['status']))
1203
			$ifinfo['status'] = "down";
1204
			
1205
		if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1206
			foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1207
				if ($config['interfaces'][$ifdescr]['if'] == $ppp['if'])
1208
					break;
1209
			}
1210
		}
1211
		$dev = $ppp['ports'];
1212
		if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev))
1213
			break;
1214
		if (!file_exists($dev)) {
1215
			$ifinfo['nodevice'] = 1;
1216
			$ifinfo['pppinfo'] = $dev . " device not present! Is the modem attached to the system?";	
1217
		}
1218
		// Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over!
1219
		if (isset($ppp['uptime']))
1220
			$ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")";
1221
		break;
1222
	default:
1223
		break;
1224
	}
1225
	
1226
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1227
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1228
		$ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec);
1229
	}
1230
	
1231
	if ($ifinfo['status'] == "up") {
1232
		/* try to determine media with ifconfig */
1233
		unset($ifconfiginfo);
1234
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1235
		$wifconfiginfo = array();
1236
		if(is_interface_wireless($ifdescr)) {
1237
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1238
			array_shift($wifconfiginfo);
1239
		}
1240
		$matches = "";
1241
		foreach ($ifconfiginfo as $ici) {
1242

    
1243
			/* don't list media/speed for wireless cards, as it always
1244
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1245
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1246
				$ifinfo['media'] = $matches[1];
1247
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1248
				$ifinfo['media'] = $matches[1];
1249
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1250
				$ifinfo['media'] = $matches[1];
1251
			}
1252

    
1253
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1254
				if ($matches[1] != "active")
1255
					$ifinfo['status'] = $matches[1];
1256
				if($ifinfo['status'] == "running")
1257
					$ifinfo['status'] = "up";
1258
			}
1259
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1260
				$ifinfo['channel'] = $matches[1];
1261
			}
1262
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1263
				if ($matches[1][0] == '"')
1264
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1265
				else
1266
					$ifinfo['ssid'] = $matches[1];
1267
			}
1268
			if (preg_match("/laggproto (.*)$/", $ici, $matches)) {
1269
				$ifinfo['laggproto'] = $matches[1];
1270
			}
1271
			if (preg_match("/laggport: (.*)$/", $ici, $matches)) {
1272
				$ifinfo['laggport'][] = $matches[1];
1273
			}
1274
		}
1275
		foreach($wifconfiginfo as $ici) {
1276
			$elements = preg_split("/[ ]+/i", $ici);
1277
			if ($elements[0] != "") {
1278
				$ifinfo['bssid'] = $elements[0];
1279
			}
1280
			if ($elements[3] != "") {
1281
				$ifinfo['rate'] = $elements[3];
1282
			}
1283
			if ($elements[4] != "") {
1284
				$ifinfo['rssi'] = $elements[4];
1285
			}
1286

    
1287
		}
1288
		/* lookup the gateway */
1289
		if (interface_has_gateway($ifdescr)) 
1290
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1291
	}
1292

    
1293
	$bridge = "";
1294
	$bridge = link_interface_to_bridge($ifdescr);
1295
	if($bridge) {
1296
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1297
		if(stristr($bridge_text, "blocking") <> false) {
1298
			$ifinfo['bridge'] = "<b><font color='red'>blocking</font></b> - check for ethernet loops";
1299
			$ifinfo['bridgeint'] = $bridge;
1300
		} else if(stristr($bridge_text, "learning") <> false) {
1301
			$ifinfo['bridge'] = "learning";
1302
			$ifinfo['bridgeint'] = $bridge;
1303
		} else if(stristr($bridge_text, "forwarding") <> false) {
1304
			$ifinfo['bridge'] = "forwarding";
1305
			$ifinfo['bridgeint'] = $bridge;
1306
		}
1307
	}
1308

    
1309
	return $ifinfo;
1310
}
1311

    
1312
//returns cpu speed of processor. Good for determining capabilities of machine
1313
function get_cpu_speed() {
1314
	 return exec("sysctl hw.clockrate | awk '{ print $2 }'");
1315
}
1316

    
1317
function add_hostname_to_watch($hostname) {
1318
	if(!is_dir("/var/db/dnscache")) {
1319
		mkdir("/var/db/dnscache");
1320
	}
1321
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1322
		$domrecords = array();
1323
		$domips = array();
1324
		exec("host -t A $hostname", $domrecords, $rethost);
1325
		if($rethost == 0) {
1326
			foreach($domrecords as $domr) {
1327
				$doml = explode(" ", $domr);
1328
				$domip = $doml[3];
1329
				/* fill array with domain ip addresses */
1330
				if(is_ipaddr($domip)) {
1331
					$domips[] = $domip;
1332
				}
1333
			}
1334
		}
1335
		sort($domips);
1336
		$contents = "";
1337
		if(! empty($domips)) {
1338
			foreach($domips as $ip) {
1339
				$contents .= "$ip\n";
1340
			}
1341
		}
1342
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1343
	}
1344
}
1345

    
1346
function is_fqdn($fqdn) {
1347
	$hostname = false;
1348
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1349
		$hostname = true;
1350
	}
1351
	if(preg_match("/\.\./", $fqdn)) {
1352
		$hostname = false;
1353
	}
1354
	if(preg_match("/^\./i", $fqdn)) { 
1355
		$hostname = false;
1356
	}
1357
	if(preg_match("/\//i", $fqdn)) {
1358
		$hostname = false;
1359
	}
1360
	return($hostname);
1361
}
1362

    
1363
function pfsense_default_state_size() {
1364
  /* get system memory amount */
1365
  $memory = get_memory();
1366
  $avail = $memory[0];
1367
  /* Be cautious and only allocate 10% of system memory to the state table */
1368
  $max_states = (int) ($avail/10)*1000;
1369
  return $max_states;
1370
}
1371

    
1372
function pfsense_default_tables_size() {
1373
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1374
	return $current;
1375
}
1376

    
1377
function pfsense_default_table_entries_size() {
1378
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1379
	return $current;
1380
}
1381

    
1382
/* Compare the current hostname DNS to the DNS cache we made
1383
 * if it has changed we return the old records
1384
 * if no change we return true */
1385
function compare_hostname_to_dnscache($hostname) {
1386
	if(!is_dir("/var/db/dnscache")) {
1387
		mkdir("/var/db/dnscache");
1388
	}
1389
	$hostname = trim($hostname);
1390
	if(is_readable("/var/db/dnscache/{$hostname}")) {
1391
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1392
	} else {
1393
		$oldcontents = "";
1394
	}
1395
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1396
		$domrecords = array();
1397
		$domips = array();
1398
		exec("host -t A $hostname", $domrecords, $rethost);
1399
		if($rethost == 0) {
1400
			foreach($domrecords as $domr) {
1401
				$doml = explode(" ", $domr);
1402
				$domip = $doml[3];
1403
				/* fill array with domain ip addresses */
1404
				if(is_ipaddr($domip)) {
1405
					$domips[] = $domip;
1406
				}
1407
			}
1408
		}
1409
		sort($domips);
1410
		$contents = "";
1411
		if(! empty($domips)) {
1412
			foreach($domips as $ip) {
1413
				$contents .= "$ip\n";
1414
			}
1415
		}
1416
	}
1417

    
1418
	if(trim($oldcontents) != trim($contents)) {
1419
		if($g['debug']) {
1420
			log_error("DNSCACHE: Found old IP {$oldcontents} and new IP {$contents}");
1421
		}
1422
		return ($oldcontents);
1423
	} else {
1424
		return false;
1425
	}
1426
}
1427

    
1428
/*
1429
 * load_glxsb() - Load the glxsb crypto module if enabled in config.
1430
 */
1431
function load_glxsb() {
1432
	global $config, $g;
1433
	$is_loaded = `/sbin/kldstat | /usr/bin/grep -c glxsb`;
1434
	if (isset($config['system']['glxsb_enable']) && ($is_loaded == 0)) {
1435
		mwexec("/sbin/kldload glxsb");
1436
	}
1437
}
1438

    
1439
/****f* pfsense-utils/isvm
1440
 * NAME
1441
 *   isvm
1442
 * INPUTS
1443
 *	 none
1444
 * RESULT
1445
 *   returns true if machine is running under a virtual environment
1446
 ******/
1447
function isvm() {
1448
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1449
	$bios_vendor = strtolower(`/bin/kenv | /usr/bin/awk -F= '/smbios.bios.vendor/ {print $2}'`);
1450
	if(in_array($bios_vendor, $virtualenvs)) 
1451
		return true;
1452
	else
1453
		return false;
1454
}
1455

    
1456
function get_freebsd_version() {
1457
	$version = php_uname("r");
1458
	return $version[0];
1459
}
1460

    
1461
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1462
        global $ch, $fout, $file_size, $downloaded, $config;
1463
        $file_size  = 1;
1464
        $downloaded = 1;
1465
        /* open destination file */
1466
        $fout = fopen($destination_file, "wb");
1467

    
1468
        /*
1469
         *      Originally by Author: Keyvan Minoukadeh
1470
         *      Modified by Scott Ullrich to return Content-Length size
1471
         */
1472

    
1473
        $ch = curl_init();
1474
        curl_setopt($ch, CURLOPT_URL, $url_file);
1475
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1476
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1477
        /* Don't verify SSL peers since we don't have the certificates to do so. */
1478
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1479
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1480
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1481
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1482
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1483

    
1484
	if (!empty($config['system']['proxyurl'])) {
1485
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1486
		if (!empty($config['system']['proxyport']))
1487
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1488
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1489
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1490
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1491
		}
1492
	}
1493

    
1494
        @curl_exec($ch);
1495
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1496
        if($fout)
1497
                fclose($fout);
1498
        curl_close($ch);
1499
        return ($http_code == 200) ? true : $http_code;
1500
}
1501

    
1502
function read_header($ch, $string) {
1503
        global $file_size, $fout;
1504
        $length = strlen($string);
1505
        $regs = "";
1506
        ereg("(Content-Length:) (.*)", $string, $regs);
1507
        if($regs[2] <> "") {
1508
                $file_size = intval($regs[2]);
1509
        }
1510
        ob_flush();
1511
        return $length;
1512
}
1513

    
1514
function read_body($ch, $string) {
1515
        global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen;
1516
		global $pkg_interface;
1517
        $length = strlen($string);
1518
        $downloaded += intval($length);
1519
        if($file_size > 0) {
1520
                $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1521
                $downloadProgress = 100 - $downloadProgress;
1522
        } else
1523
                $downloadProgress = 0;
1524
        if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1525
                if($sendto == "status") {
1526
					if($pkg_interface == "console") {
1527
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1528
                        	$tostatus = $static_status . $downloadProgress . "%";
1529
                        	update_status($tostatus);
1530
						}
1531
					} else {
1532
                        $tostatus = $static_status . $downloadProgress . "%";
1533
                        update_status($tostatus);						
1534
					}
1535
                } else {
1536
					if($pkg_interface == "console") {
1537
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1538
                        	$tooutput = $static_output . $downloadProgress . "%";
1539
                        	update_output_window($tooutput);
1540
						}
1541
					} else {
1542
                        $tooutput = $static_output . $downloadProgress . "%";
1543
                        update_output_window($tooutput);
1544
					}
1545
                }
1546
                update_progress_bar($downloadProgress);
1547
                $lastseen = $downloadProgress;
1548
        }
1549
        if($fout)
1550
                fwrite($fout, $string);
1551
        ob_flush();
1552
        return $length;
1553
}
1554

    
1555
/*
1556
 *   update_output_window: update bottom textarea dynamically.
1557
 */
1558
function update_output_window($text) {
1559
        global $pkg_interface;
1560
        $log = ereg_replace("\n", "\\n", $text);
1561
        if($pkg_interface != "console") {
1562
                echo "\n<script language=\"JavaScript\">\nthis.document.forms[0].output.value = \"" . $log . "\";\n";
1563
				echo "this.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;\n";	
1564
				echo "</script>";
1565
        } else
1566
		echo $text;
1567
        /* ensure that contents are written out */
1568
        ob_flush();
1569
}
1570

    
1571
/*
1572
 *   update_output_window: update top textarea dynamically.
1573
 */
1574
function update_status($status) {
1575
        global $pkg_interface;
1576

    
1577
        if($pkg_interface != "console") {
1578
                echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
1579
        } else {
1580
                echo $status . "\n";
1581
        }
1582
        /* ensure that contents are written out */
1583
        ob_flush();
1584
}
1585

    
1586
/*
1587
 * update_progress_bar($percent): updates the javascript driven progress bar.
1588
 */
1589
function update_progress_bar($percent) {
1590
        global $pkg_interface;
1591
        if($percent > 100) $percent = 1;
1592
        if($pkg_interface <> "console") {
1593
                echo "\n<script type=\"text/javascript\" language=\"javascript\">";
1594
                echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1595
                echo "\n</script>";
1596
        } else {
1597
                echo " {$percent}%";
1598
        }
1599
}
1600

    
1601
/* 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. */
1602
if(!function_exists("split")) {
1603
	function split($seperator, $haystack, $limit = null) {
1604
		return preg_split($seperator, $haystack, $limit);
1605
	}
1606
}
1607

    
1608
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1609
	global $g, $config, $pconfig, $debug;
1610
	if(!$origname) 
1611
		return;
1612

    
1613
	$sectionref = &$config;
1614
	foreach($section as $sectionname) {
1615
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1616
			$sectionref = &$sectionref[$sectionname];
1617
		else
1618
			return;
1619
	}
1620

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

    
1624
	if(is_array($sectionref)) {
1625
		foreach($sectionref as $itemkey => $item) {
1626
			if($debug) fwrite($fd, "$itemkey\n");
1627

    
1628
			$fieldfound = true;
1629
			$fieldref = &$sectionref[$itemkey];
1630
			foreach($field as $fieldname) {
1631
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1632
					$fieldref = &$fieldref[$fieldname];
1633
				else {
1634
					$fieldfound = false;
1635
					break;
1636
				}
1637
			}
1638
			if($fieldfound && $fieldref == $origname) {
1639
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1640
				$fieldref = $new_alias_name;
1641
			}
1642
		}
1643
	}
1644

    
1645
	if($debug) fclose($fd);
1646

    
1647
}
1648

    
1649
function update_alias_url_data() {
1650
	global $config, $g;
1651

    
1652
	/* item is a url type */
1653
	$lockkey = lock('config');
1654
	if (is_array($config['aliases']['alias'])) {
1655
		foreach ($config['aliases']['alias'] as $x => $alias) {
1656
			if (empty($alias['aliasurl']))
1657
				continue;
1658

    
1659
			/* fetch down and add in */
1660
			$isfirst = 0;
1661
			$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1662
			unlink($temp_filename);
1663
			$fda = fopen("{$g['tmp_path']}/tmpfetch","w");
1664
			fwrite($fda, "/usr/bin/fetch -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1665
			fclose($fda);
1666
			mwexec("/bin/mkdir -p {$temp_filename}");
1667
			mwexec("/usr/bin/fetch -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1668
			/* if the item is tar gzipped then extract */
1669
			if(stristr($alias['aliasurl'], ".tgz"))
1670
				process_alias_tgz($temp_filename);
1671
			else if(stristr($alias['aliasurl'], ".zip"))
1672
				process_alias_unzip($temp_filename);
1673
			if(file_exists("{$temp_filename}/aliases")) {
1674
				$file_contents = file_get_contents("{$temp_filename}/aliases");
1675
				$file_contents = str_replace("#", "\n#", $file_contents);
1676
				$file_contents_split = split("\n", $file_contents);
1677
				foreach($file_contents_split as $fc) {
1678
					$tmp = trim($fc);
1679
					if(stristr($fc, "#")) {
1680
						$tmp_split = split("#", $tmp);
1681
						$tmp = trim($tmp_split[0]);
1682
					}
1683
					if(trim($tmp) <> "") {
1684
						if($isfirst == 1)
1685
							$address .= " ";
1686
						$address .= $tmp;
1687
						$isfirst = 1;
1688
					}
1689
				}
1690
				if($isfirst > 0) {
1691
					$config['aliases']['alias'][$x]['address'] = $address;
1692
					$updated = true;
1693
				}
1694
				mwexec("/bin/rm -rf {$temp_filename}");
1695
			}
1696
		}
1697
	}
1698
	if($updated)
1699
		write_config();
1700
	unlock($lockkey);
1701
}
1702

    
1703
function process_alias_unzip($temp_filename) {
1704
	if(!file_exists("/usr/local/bin/unzip"))
1705
		return;
1706
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.zip");
1707
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1708
	unlink("{$temp_filename}/aliases.zip");
1709
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1710
	/* foreach through all extracted files and build up aliases file */
1711
	$fd = fopen("{$temp_filename}/aliases", "w");
1712
	foreach($files_to_process as $f2p) {
1713
		$file_contents = file_get_contents($f2p);
1714
		fwrite($fd, $file_contents);
1715
		unlink($f2p);
1716
	}
1717
	fclose($fd);
1718
}
1719

    
1720
function process_alias_tgz($temp_filename) {
1721
	if(!file_exists("/usr/bin/tar"))
1722
		return;
1723
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.tgz");
1724
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1725
	unlink("{$temp_filename}/aliases.tgz");
1726
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1727
	/* foreach through all extracted files and build up aliases file */
1728
	$fd = fopen("{$temp_filename}/aliases", "w");
1729
	foreach($files_to_process as $f2p) {
1730
		$file_contents = file_get_contents($f2p);
1731
		fwrite($fd, $file_contents);
1732
		unlink($f2p);
1733
	}
1734
	fclose($fd);
1735
}
1736

    
1737
function version_compare_dates($a, $b) {
1738
	$a_time = strtotime($a);
1739
	$b_time = strtotime($b);
1740

    
1741
	if ((!$a_time) || (!$b_time)) {
1742
		return FALSE;
1743
	} else {
1744
		if ($a_time < $b_time)
1745
			return -1;
1746
		elseif ($$a_time == $b_time)
1747
			return 0;
1748
		else
1749
			return 1;
1750
	}
1751
}
1752
function version_get_string_value($a) {
1753
	$strs = array(
1754
		0 => "ALPHA-ALPHA",
1755
		2 => "ALPHA",
1756
		3 => "BETA",
1757
		4 => "B",
1758
		5 => "C",
1759
		6 => "D",
1760
		7 => "RC",
1761
		8 => "RELEASE"
1762
	);
1763
	$major = 0;
1764
	$minor = 0;
1765
	foreach ($strs as $num => $str) {
1766
		if (substr($a, 0, strlen($str)) == $str) {
1767
			$major = $num;
1768
			$n = substr($a, strlen($str));
1769
			if (is_numeric($n))
1770
				$minor = $n;
1771
			break;
1772
		}
1773
	}
1774
	return "{$major}.{$minor}";
1775
}
1776
function version_compare_string($a, $b) {
1777
	return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
1778
}
1779
function version_compare_numeric($a, $b) {
1780
	$a_arr = explode('.', rtrim($a, '.0'));
1781
	$b_arr = explode('.', rtrim($b, '.0'));
1782

    
1783
	foreach ($a_arr as $n => $val) {
1784
		if (array_key_exists($n, $b_arr)) {
1785
			// So far so good, both have values at this minor version level. Compare.
1786
			if ($val > $b_arr[$n])
1787
				return 1;
1788
			elseif ($val < $b_arr[$n])
1789
				return -1;
1790
		} else {
1791
			// a is greater, since b doesn't have any minor version here.
1792
			return 1;
1793
		}
1794
	}
1795
	if (count($b_arr) > count($a_arr)) {
1796
		// b is longer than a, so it must be greater.
1797
		return -1;
1798
	} else {
1799
		// Both a and b are of equal length and value.
1800
		return 0;
1801
	}
1802
}
1803
function pfs_version_compare($cur_time, $cur_text, $remote) {
1804
	// First try date compare
1805
	$v = version_compare_dates($cur_time, $remote);
1806
	if ($v === FALSE) {
1807
		// If that fails, try to compare by string
1808
		// Before anything else, simply test if the strings are equal
1809
		if (($cur_text == $remote) || ($cur_time == $remote))
1810
			return 0;
1811
		list($cur_num, $cur_str) = explode('-', $cur_text);
1812
		list($rem_num, $rem_str) = explode('-', $remote);
1813

    
1814
		// First try to compare the numeric parts of the version string.
1815
		$v = version_compare_numeric($cur_num, $rem_num);
1816

    
1817
		// If the numeric parts are the same, compare the string parts.
1818
		if ($v == 0)
1819
			return version_compare_string($cur_str, $rem_str);
1820
	}
1821
	return $v;
1822
}
1823
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
1824
	$urltable_prefix = "/var/db/aliastables/";
1825
	$urltable_filename = $urltable_prefix . $name . ".txt";
1826

    
1827
	// Make the aliases directory if it doesn't exist
1828
	if (!file_exists($urltable_prefix)) {
1829
		mkdir($urltable_prefix);
1830
	} elseif (!is_dir($urltable_prefix)) {
1831
		unlink($urltable_prefix);
1832
		mkdir($urltable_prefix);
1833
	}
1834

    
1835
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
1836
	if (!file_exists($urltable_filename)
1837
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400))
1838
		|| $forceupdate) {
1839

    
1840
		// Try to fetch the URL supplied
1841
		conf_mount_rw();
1842
		unlink_if_exists($urltable_filename . ".tmp");
1843
		// 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.
1844
		mwexec("/usr/bin/fetch -q -o " . escapeshellarg($urltable_filename . ".tmp") . " " . escapeshellarg($url));
1845
		// Remove comments. Might need some grep-fu to only allow lines that look like IPs/subnets
1846
		if (file_exists($urltable_filename . ".tmp")) {
1847
			mwexec("/usr/bin/grep -v '^#' " . escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
1848
			unlink_if_exists($urltable_filename . ".tmp");
1849
		} else
1850
			mwexec("/usr/bin/touch {$urltable_filename}");
1851
		conf_mount_ro();
1852
		return true;
1853
	} else {
1854
		// File exists, and it doesn't need updated.
1855
		return -1;
1856
	}
1857
}
1858
function get_real_slice_from_glabel($label) {
1859
	$label = escapeshellarg($label);
1860
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
1861
}
1862
function nanobsd_get_boot_slice() {
1863
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
1864
}
1865
function nanobsd_get_boot_drive() {
1866
	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`);
1867
}
1868
function nanobsd_get_active_slice() {
1869
	$boot_drive = nanobsd_get_boot_drive();
1870
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
1871

    
1872
	return "{$boot_drive}s{$active}";
1873
}
1874
function nanobsd_get_size() {
1875
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
1876
}
1877
function nanobsd_switch_boot_slice() {
1878
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1879
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1880
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1881
	nanobsd_detect_slice_info();
1882

    
1883
	if ($BOOTFLASH == $ACTIVE_SLICE) {
1884
		$slice = $TOFLASH;
1885
	} else {
1886
		$slice = $BOOTFLASH;
1887
	}
1888

    
1889
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
1890
	ob_implicit_flush(1);
1891
	if(strstr($slice, "s2")) {
1892
		$ASLICE="2";
1893
		$AOLDSLICE="1";
1894
		$AGLABEL_SLICE="pfsense1";
1895
		$AUFS_ID="1";
1896
		$AOLD_UFS_ID="0";
1897
	} else {
1898
		$ASLICE="1";
1899
		$AOLDSLICE="2";
1900
		$AGLABEL_SLICE="pfsense0";
1901
		$AUFS_ID="0";
1902
		$AOLD_UFS_ID="1";
1903
	}
1904
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
1905
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
1906
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
1907
	conf_mount_rw();
1908
	exec("sysctl kern.geom.debugflags=16");
1909
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
1910
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
1911
	// We can't update these if they are mounted now.
1912
	if ($BOOTFLASH != $slice) {
1913
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
1914
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
1915
	}
1916
	exec("/sbin/sysctl kern.geom.debugflags=0");
1917
	conf_mount_ro();
1918
}
1919
function nanobsd_clone_slice() {
1920
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1921
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1922
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1923
	nanobsd_detect_slice_info();
1924

    
1925
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
1926
	ob_implicit_flush(1);
1927
	exec("/sbin/sysctl kern.geom.debugflags=16");
1928
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
1929
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
1930
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
1931
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
1932
	exec("/sbin/sysctl kern.geom.debugflags=0");
1933
	if($status) {
1934
		return false;
1935
	} else {
1936
		return true;
1937
	}
1938
}
1939
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
1940
	$tmppath = "/tmp/{$gslice}";
1941
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
1942

    
1943
	exec("/bin/mkdir {$tmppath}");
1944
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
1945
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
1946
	exec("/bin/cp /etc/fstab {$fstabpath}");
1947

    
1948
	if (!file_exists($fstabpath)) {
1949
		$fstab = <<<EOF
1950
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
1951
/dev/ufs/cf /cf ufs ro,noatime 1 1
1952
EOF;
1953
		if (file_put_contents($fstabpath, $fstab))
1954
			$status = true;
1955
		else
1956
			$status = false;
1957
	} else {
1958
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
1959
	}
1960
	exec("/sbin/umount {$tmppath}");
1961
	exec("/bin/rmdir {$tmppath}");
1962

    
1963
	return $status;
1964
}
1965
function nanobsd_detect_slice_info() {
1966
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1967
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1968
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1969

    
1970
	$BOOT_DEVICE=nanobsd_get_boot_slice();
1971
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
1972
	$BOOT_DRIVE=nanobsd_get_boot_drive();
1973
	$ACTIVE_SLICE=nanobsd_get_active_slice();
1974

    
1975
	// Detect which slice is active and set information.
1976
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
1977
		$SLICE="2";
1978
		$OLDSLICE="1";
1979
		$GLABEL_SLICE="pfsense1";
1980
		$UFS_ID="1";
1981
		$OLD_UFS_ID="0";
1982

    
1983
	} else {
1984
		$SLICE="1";
1985
		$OLDSLICE="2";
1986
		$GLABEL_SLICE="pfsense0";
1987
		$UFS_ID="0";
1988
		$OLD_UFS_ID="1";
1989
	}
1990
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
1991
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
1992
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
1993
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
1994
}
1995

    
1996
function nanobsd_friendly_slice_name($slicename) {
1997
	global $g;
1998
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
1999
}
2000

    
2001
function get_include_contents($filename) {
2002
    if (is_file($filename)) {
2003
        ob_start();
2004
        include $filename;
2005
        $contents = ob_get_contents();
2006
        ob_end_clean();
2007
        return $contents;
2008
    }
2009
    return false;
2010
}
2011

    
2012
/* This xml 2 array function is courtesy of the php.net comment section on xml_parse.
2013
 * it is roughly 4 times faster then our existing pfSense parser but due to the large
2014
 * size of the RRD xml dumps this is required.
2015
 * The reason we do not use it for pfSense is that it does not know about array fields
2016
 * which causes it to fail on array fields with single items. Possible Todo?
2017
 */
2018
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
2019
{
2020
    if (!function_exists('xml_parser_create'))
2021
    {
2022
        return array ();
2023
    }
2024
    $parser = xml_parser_create('');
2025
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
2026
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2027
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
2028
    xml_parse_into_struct($parser, trim($contents), $xml_values);
2029
    xml_parser_free($parser);
2030
    if (!$xml_values)
2031
        return; //Hmm...
2032
    $xml_array = array ();
2033
    $parents = array ();
2034
    $opened_tags = array ();
2035
    $arr = array ();
2036
    $current = & $xml_array;
2037
    $repeated_tag_index = array ();
2038
    foreach ($xml_values as $data)
2039
    {
2040
        unset ($attributes, $value);
2041
        extract($data);
2042
        $result = array ();
2043
        $attributes_data = array ();
2044
        if (isset ($value))
2045
        {
2046
            if ($priority == 'tag')
2047
                $result = $value;
2048
            else
2049
                $result['value'] = $value;
2050
        }
2051
        if (isset ($attributes) and $get_attributes)
2052
        {
2053
            foreach ($attributes as $attr => $val)
2054
            {
2055
                if ($priority == 'tag')
2056
                    $attributes_data[$attr] = $val;
2057
                else
2058
                    $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
2059
            }
2060
        }
2061
        if ($type == "open")
2062
        {
2063
            $parent[$level -1] = & $current;
2064
            if (!is_array($current) or (!in_array($tag, array_keys($current))))
2065
            {
2066
                $current[$tag] = $result;
2067
                if ($attributes_data)
2068
                    $current[$tag . '_attr'] = $attributes_data;
2069
                $repeated_tag_index[$tag . '_' . $level] = 1;
2070
                $current = & $current[$tag];
2071
            }
2072
            else
2073
            {
2074
                if (isset ($current[$tag][0]))
2075
                {
2076
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2077
                    $repeated_tag_index[$tag . '_' . $level]++;
2078
                }
2079
                else
2080
                {
2081
                    $current[$tag] = array (
2082
                        $current[$tag],
2083
                        $result
2084
                    );
2085
                    $repeated_tag_index[$tag . '_' . $level] = 2;
2086
                    if (isset ($current[$tag . '_attr']))
2087
                    {
2088
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
2089
                        unset ($current[$tag . '_attr']);
2090
                    }
2091
                }
2092
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
2093
                $current = & $current[$tag][$last_item_index];
2094
            }
2095
        }
2096
        elseif ($type == "complete")
2097
        {
2098
            if (!isset ($current[$tag]))
2099
            {
2100
                $current[$tag] = $result;
2101
                $repeated_tag_index[$tag . '_' . $level] = 1;
2102
                if ($priority == 'tag' and $attributes_data)
2103
                    $current[$tag . '_attr'] = $attributes_data;
2104
            }
2105
            else
2106
            {
2107
                if (isset ($current[$tag][0]) and is_array($current[$tag]))
2108
                {
2109
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2110
                    if ($priority == 'tag' and $get_attributes and $attributes_data)
2111
                    {
2112
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2113
                    }
2114
                    $repeated_tag_index[$tag . '_' . $level]++;
2115
                }
2116
                else
2117
                {
2118
                    $current[$tag] = array (
2119
                        $current[$tag],
2120
                        $result
2121
                    );
2122
                    $repeated_tag_index[$tag . '_' . $level] = 1;
2123
                    if ($priority == 'tag' and $get_attributes)
2124
                    {
2125
                        if (isset ($current[$tag . '_attr']))
2126
                        {
2127
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
2128
                            unset ($current[$tag . '_attr']);
2129
                        }
2130
                        if ($attributes_data)
2131
                        {
2132
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2133
                        }
2134
                    }
2135
                    $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
2136
                }
2137
            }
2138
        }
2139
        elseif ($type == 'close')
2140
        {
2141
            $current = & $parent[$level -1];
2142
        }
2143
    }
2144
    return ($xml_array);
2145
}
2146

    
2147
function get_country_name($country_code) {
2148
	if ($country_code != "ALL" && strlen($country_code) != 2)
2149
		return "";
2150

    
2151
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2152
	$country_names_contents = file_get_contents($country_names_xml);
2153
	$country_names = xml2array($country_names_contents);
2154

    
2155
	if($country_code == "ALL") {
2156
		$country_list = array();
2157
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2158
			$country_list[] = array( "code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2159
						 "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2160
		}
2161
		return $country_list;
2162
	}
2163

    
2164
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2165
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2166
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2167
		}
2168
	}
2169
	return "";
2170
}
2171

    
2172
/* sort by interface only, retain the original order of rules that apply to
2173
   the same interface */
2174
function filter_rules_sort() {
2175
	global $config;
2176

    
2177
	/* mark each rule with the sequence number (to retain the order while sorting) */
2178
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2179
		$config['filter']['rule'][$i]['seq'] = $i;
2180

    
2181
	usort($config['filter']['rule'], "filter_rules_compare");
2182

    
2183
	/* strip the sequence numbers again */
2184
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2185
		unset($config['filter']['rule'][$i]['seq']);
2186
}
2187
function filter_rules_compare($a, $b) {
2188
	if (isset($a['floating']) && isset($b['floating']))
2189
		return $a['seq'] - $b['seq'];
2190
	else if (isset($a['floating']))
2191
		return -1;
2192
	else if (isset($b['floating']))
2193
		return 1;
2194
	else if ($a['interface'] == $b['interface'])
2195
		return $a['seq'] - $b['seq'];
2196
	else
2197
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2198
}
2199

    
2200
/****f* pfsense-utils/load_mac_manufacturer_table
2201
 * NAME
2202
 *   load_mac_manufacturer_table
2203
 * INPUTS
2204
 *   none
2205
 * RESULT
2206
 *   returns associative array with MAC-Manufacturer pairs
2207
 ******/
2208
function load_mac_manufacturer_table() {
2209
	/* load MAC-Manufacture data from the file */
2210
	$macs = false;
2211
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2212
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2213
	if ($macs){
2214
		foreach ($macs as $line){
2215
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2216
				/* store values like this $mac_man['000C29']='VMware' */
2217
				$mac_man["$matches[1]"]=$matches[2];
2218
			}
2219
		}
2220
 		return $mac_man;
2221
	} else
2222
		return -1;
2223

    
2224
}
2225

    
2226
/****f* pfsense-utils/is_ipaddr_configured
2227
 * NAME
2228
 *   is_ipaddr_configured
2229
 * INPUTS
2230
 *   IP Address to check.
2231
 * RESULT
2232
 *   returns true if the IP Address is
2233
 *   configured and present on this device.
2234
*/
2235
function is_ipaddr_configured($ipaddr) {
2236
	$interface_list_ips = get_configured_ip_addresses();
2237
	foreach($interface_list_ips as $ilips) {
2238
		if(strcasecmp($ipaddr, $ilips) == 0) 
2239
				return true;
2240
	}	
2241
}
2242

    
2243
/****f* pfsense-utils/pfSense_handle_custom_code
2244
 * NAME
2245
 *   pfSense_handle_custom_code
2246
 * INPUTS
2247
 *   directory name to process
2248
 * RESULT
2249
 *   globs the directory and includes the files
2250
 */
2251
function pfSense_handle_custom_code($src_dir) {
2252
	// Allow extending of the nat edit page and include custom input validation 
2253
	if(is_dir("$src_dir")) {
2254
		$cf = glob($src_dir . "/*.inc");
2255
		foreach($cf as $nf) {
2256
			if($nf == "." || $nf == "..") 
2257
				continue;
2258
			// Include the extra handler
2259
			include("$nf");
2260
		}
2261
	}
2262
}
2263

    
2264
?>
(36-36/62)